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
grueni75/GeoDiscoverer
Source/Platform/Target/Android/mobile/src/main/java/com/untouchableapps/android/geodiscoverer/ui/theme/Type.kt
1
1206
//============================================================================ // Name : Type.kt // Author : Matthias Gruenewald // Copyright : Copyright 2010-2021 Matthias Gruenewald // // This file is part of GeoDiscoverer. // // GeoDiscoverer 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. // // GeoDiscoverer 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 GeoDiscoverer. If not, see <http://www.gnu.org/licenses/>. // //============================================================================ package com.untouchableapps.android.geodiscoverer.ui.theme // Set of Material typography styles to start with val M3Typography = androidx.compose.material3.Typography( ) val M2Typography = androidx.compose.material.Typography( )
gpl-3.0
eb67e52a39e829629da036364153b4ff
39.2
78
0.6534
4.353791
false
false
false
false
elect86/jAssimp
src/test/kotlin/assimp/fbx/animFullRot.kt
2
4248
package assimp.fbx import assimp.* import glm_.mat4x4.Mat4 import glm_.vec3.Vec3 import io.kotest.matchers.shouldBe object animFullRot { operator fun invoke(fileName: String) { Importer().testFile(getResource(fileName)) { flags shouldBe 0 with(rootNode) { // name shouldBe "<MD5_Root>" // transformation shouldBe Mat4( // 1f, 0f, 0f, 0f, // 0f, 0f, -1f, 0f, // 0f, 1f, 0f, 0f, // 0f, 0f, 0f, 1f) // parent shouldBe null // numChildren shouldBe 2 // // with(children[0]) { // name shouldBe "<MD5_Mesh>" // transformation shouldBe Mat4() // (parent === rootNode) shouldBe true // numChildren shouldBe 0 // // numMeshes shouldBe 1 // meshes[0] shouldBe 0 // } // // with(children[1]) { // name shouldBe "<MD5_Hierarchy>" // transformation shouldBe Mat4() // (parent === rootNode) shouldBe true // numChildren shouldBe 1 // // with(children[0]) { // name shouldBe "Bone" // transformation shouldBe Mat4( // 1.00000000f, -0.000000000f, 0.000000000f, 0.000000000f, // 0.000000000f, -5.96046448e-07f, 1.00000000f, 0.000000000f, // -0.000000000f, -1.00000000f, -5.96046448e-07f, 0.000000000f, // 0.000000000f, 0.000000000f, 0.000000000f, 1.00000000f // ) // (parent === rootNode.children[1]) shouldBe true // numChildren shouldBe 0 // // numMeshes shouldBe 0 // } // numMeshes shouldBe 0 // } // numMeshes shouldBe 0 } // with(meshes[0]) { // // primitiveTypes shouldBe 4 // numVertices shouldBe 8436 // numFaces shouldBe 2812 // // vertices[0] shouldBe Vec3(2.81622696f, 0.415550232f, 24.7310295f) // vertices[4217] shouldBe Vec3(7.40894270f, 2.25090504f, 23.1958885f) // vertices[8435] shouldBe Vec3(1.2144182f, -3.79157066f, 25.3626385f) // // textureCoords[0][0][0] shouldBe 0.704056978f // textureCoords[0][0][1] shouldBe 0.896108985f // textureCoords[0][4217][0] shouldBe 1.852235f // textureCoords[0][4217][1] shouldBe 0.437269986f // textureCoords[0][8435][0] shouldBe 0.303604007f // textureCoords[0][8435][1] shouldBe 1.94788897f // // faces.asSequence().filterIndexed { i, f -> i in 0..7 }.forEachIndexed { i, f -> // val idx = i * 3 // f shouldBe mutableListOf(idx + 1, idx + 2, idx) // } // faces[1407] shouldBe mutableListOf(4708, 4707, 4706) // faces[2811] shouldBe mutableListOf(8435, 8434, 8433) // // numBones shouldBe 1 // // with(bones[0]) { // name shouldBe "Bone" // numWeights shouldBe 8436 // weights.forEachIndexed { i, w -> w.vertexId shouldBe i; w.weight shouldBe 1f } // offsetMatrix shouldBe Mat4( // 1.00000000f, -0.000000000f, 0.000000000f, -0.000000000f, // -0.000000000f, -5.96046448e-07f, -1.00000000f, 0.000000000f, // 0.000000000f, 1.00000000f, -5.96046448e-07f, -0.000000000f, // -0.000000000f, 0.000000000f, -0.000000000f, 1.00000000f) // } // materialIndex shouldBe 0 // // name.isEmpty() shouldBe true // } // // numMaterials shouldBe 1 // // with(materials[0]) { // textures[0].file shouldBe "" // } } } }
mit
d5caace9757a9ddffd88e7ca53bf5a45
38.342593
100
0.461158
3.958993
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/persistence/storage/structure/DBStructurePersistentItem.kt
2
1453
package org.stepic.droid.persistence.storage.structure import androidx.sqlite.db.SupportSQLiteDatabase object DBStructurePersistentItem { const val PERSISTENT_ITEMS = "persistent_items" object Columns { const val ORIGINAL_PATH = "original_path" const val LOCAL_FILE_NAME = "local_file_name" const val LOCAL_FILE_DIR = "local_file_dir" const val IS_IN_APP_INTERNAL_DIR = "is_in_app_internal_dir" const val DOWNLOAD_ID = "download_id" const val STATUS = "status" const val COURSE = "course" const val SECTION = "section" const val LESSON = "lesson" const val UNIT = "unit" const val STEP = "step" } fun createTable(db: SupportSQLiteDatabase) { val sql = """ CREATE TABLE IF NOT EXISTS $PERSISTENT_ITEMS ( ${Columns.ORIGINAL_PATH} TEXT, ${Columns.LOCAL_FILE_NAME} TEXT, ${Columns.LOCAL_FILE_DIR} TEXT, ${Columns.IS_IN_APP_INTERNAL_DIR} INTEGER, ${Columns.DOWNLOAD_ID} LONG, ${Columns.STATUS} TEXT, ${Columns.COURSE} LONG, ${Columns.SECTION} LONG, ${Columns.LESSON} LONG, ${Columns.UNIT} LONG, ${Columns.STEP} LONG, PRIMARY KEY(${Columns.STEP}, ${Columns.ORIGINAL_PATH}) )""".trimIndent() db.execSQL(sql) } }
apache-2.0
03d324027e0b714ea7a00f54bc32be51
31.311111
70
0.565038
4.273529
false
false
false
false
andrewoma/kwery
mapper/src/test/kotlin/com/github/andrewoma/kwery/mappertest/example/FilmActorDao.kt
1
2289
/* * Copyright (c) 2015 Andrew O'Malley * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.andrewoma.kwery.mappertest.example import com.github.andrewoma.kwery.core.Session import com.github.andrewoma.kwery.mapper.* import com.github.andrewoma.kwery.mappertest.example.FilmActor as FA object filmActorTable : Table<FA, FA.Id>("film_actor", tableConfig), VersionedWithTimestamp { // @formatter:off val FilmId by col(FA.Id::filmId, path = { it.id }, id = true) val ActorId by col(FA.Id::actorId, path = { it.id }, id = true) val LastUpdate by col(FA::lastUpdate, version = true) // @formatter:on override fun idColumns(id: FA.Id) = setOf(FilmId of id.filmId, ActorId of id.actorId) override fun create(value: Value<FA>) = FA(FA.Id(value of FilmId, value of ActorId), value of LastUpdate) } class FilmActorDao(session: Session) : AbstractDao<FA, FA.Id>(session, filmActorTable, { it.id }, null, IdStrategy.Explicit) { fun findByFilmIds(ids: Collection<Int>): List<FA> { val name = "findByFilmIds" val sql = sql(name) { "select $columns from ${table.name} where film_id in (:ids)" } return session.select(sql, mapOf("ids" to ids), options(name), table.rowMapper()) } }
mit
9be5ea4a9dfa2a1c33c9695ba33eb282
45.714286
126
0.725644
3.906143
false
false
false
false
Mindera/skeletoid
kt-extensions/src/main/java/com/mindera/skeletoid/kt/extensions/stlib/Any.kt
1
309
package com.mindera.skeletoid.kt.extensions.stlib fun Any?.isTrueAndNotNull(): Boolean { return this == true } fun Any?.isFalseAndNotNull(): Boolean { return this == false } fun Any?.isTrueOrNull(): Boolean { return this != false } fun Any?.isFalseOrNull(): Boolean { return this != true }
mit
2ef6fb14bc1576345acdd27bb92b2d8a
17.235294
49
0.682848
3.722892
false
false
false
false
exponentjs/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/print/PrintModule.kt
2
5529
package abi43_0_0.expo.modules.print import android.content.Context import android.os.Bundle import android.print.PrintAttributes import android.print.PrintDocumentAdapter import android.print.PrintManager import abi43_0_0.expo.modules.core.ExportedModule import abi43_0_0.expo.modules.core.ModuleRegistry import abi43_0_0.expo.modules.core.Promise import abi43_0_0.expo.modules.core.interfaces.ActivityProvider import abi43_0_0.expo.modules.core.interfaces.ExpoMethod import java.io.File import java.io.IOException class PrintModule(context: Context) : ExportedModule(context) { private val ORIENTATION_PORTRAIT = "portrait" private val ORIENTATION_LANDSCAPE = "landscape" private val jobName = "Printing" private lateinit var moduleRegistry: ModuleRegistry override fun onCreate(moduleRegistry: ModuleRegistry) { this.moduleRegistry = moduleRegistry } override fun getName(): String { return "ExponentPrint" } override fun getConstants(): MutableMap<String, Any?> { return hashMapOf( "Orientation" to hashMapOf( "portrait" to ORIENTATION_PORTRAIT, "landscape" to ORIENTATION_LANDSCAPE ) ) } @ExpoMethod fun print(options: Map<String?, Any?>, promise: Promise) { val html = if (options.containsKey("html")) { options["html"] as String? } else { null } val uri = if (options.containsKey("uri")) { options["uri"] as String? } else { null } if (html != null) { // Renders HTML to PDF and then prints try { val renderTask = PrintPDFRenderTask(context, options, moduleRegistry) renderTask.render( null, object : PrintPDFRenderTask.Callbacks() { override fun onRenderFinished(document: PrintDocumentAdapter, outputFile: File?, numberOfPages: Int) { printDocumentToPrinter(document, options) promise.resolve(null) } override fun onRenderError(errorCode: String?, errorMessage: String?, exception: Exception?) { promise.reject(errorCode, errorMessage, exception) } } ) } catch (e: Exception) { promise.reject("E_CANNOT_PRINT", "There was an error while trying to print HTML.", e) } } else { // Prints from given URI (file path or base64 data URI starting with `data:*;base64,`) try { val pda = PrintDocumentAdapter(context, promise, uri) printDocumentToPrinter(pda, options) promise.resolve(null) } catch (e: Exception) { promise.reject("E_CANNOT_PRINT", "There was an error while trying to print a file.", e) } } } @ExpoMethod fun printToFileAsync(options: Map<String?, Any?>, promise: Promise) { val filePath: String try { filePath = FileUtils.generateFilePath(context) } catch (e: IOException) { promise.reject("E_PRINT_FAILED", "An unknown I/O exception occurred.", e) return } val renderTask = PrintPDFRenderTask(context, options, moduleRegistry) renderTask.render( filePath, object : PrintPDFRenderTask.Callbacks() { override fun onRenderFinished(document: PrintDocumentAdapter, outputFile: File?, numberOfPages: Int) { val uri = FileUtils.uriFromFile(outputFile).toString() var base64: String? = null if (options.containsKey("base64") && (options["base64"] as Boolean? == true)) { try { base64 = outputFile?.let { FileUtils.encodeFromFile(it) } } catch (e: IOException) { promise.reject("E_PRINT_BASE64_FAILED", "An error occurred while encoding PDF file to base64 string.", e) return } } promise.resolve( Bundle().apply { putString("uri", uri) putInt("numberOfPages", numberOfPages) if (base64 != null) putString("base64", base64) } ) } override fun onRenderError(errorCode: String?, errorMessage: String?, exception: Exception?) { promise.reject(errorCode, errorMessage, exception) } } ) } private fun printDocumentToPrinter(document: PrintDocumentAdapter, options: Map<String?, Any?>) { val printManager = moduleRegistry .getModule(ActivityProvider::class.java) .currentActivity ?.getSystemService(Context.PRINT_SERVICE) as? PrintManager val attributes = getAttributesFromOptions(options) printManager?.print(jobName, document, attributes.build()) } private fun getAttributesFromOptions(options: Map<String?, Any?>): PrintAttributes.Builder { val orientation = if (options.containsKey("orientation")) { options["orientation"] as String? } else { null } val builder = PrintAttributes.Builder() // @tsapeta: Unfortunately these attributes might be ignored on some devices or Android versions, // in other words it might not change the default orientation in the print dialog, // however the user can change it there. if (ORIENTATION_LANDSCAPE == orientation) { builder.setMediaSize(PrintAttributes.MediaSize.UNKNOWN_LANDSCAPE) } else { builder.setMediaSize(PrintAttributes.MediaSize.UNKNOWN_PORTRAIT) } // @tsapeta: It should just copy the document without adding extra margins, // document's margins can be controlled by @page block in CSS. builder.setMinMargins(PrintAttributes.Margins.NO_MARGINS) return builder } }
bsd-3-clause
a10d712a21f480bdfbf5ce044594b7c7
34.902597
119
0.662688
4.528256
false
false
false
false
cyclestreets/android
libraries/cyclestreets-view/src/main/java/net/cyclestreets/views/overlay/POIOverlay.kt
1
12837
package net.cyclestreets.views.overlay import android.content.Context import android.content.SharedPreferences import android.graphics.Canvas import android.os.AsyncTask import android.util.Log import android.view.* import android.widget.BaseAdapter import android.widget.CheckBox import android.widget.ImageView import android.widget.TextView import com.mikepenz.iconics.typeface.library.googlematerial.GoogleMaterial import net.cyclestreets.Undoable import net.cyclestreets.api.POI import net.cyclestreets.api.POICategories import net.cyclestreets.api.POICategory import net.cyclestreets.iconics.IconicsHelper.materialIcon import net.cyclestreets.util.* import net.cyclestreets.view.R import net.cyclestreets.views.CycleMapView import net.cyclestreets.views.overlay.Bubble.hideBubble import net.cyclestreets.views.overlay.Bubble.hideOrShowBubble import net.cyclestreets.views.overlay.POIOverlay.POIOverlayItem import org.osmdroid.api.IGeoPoint import org.osmdroid.events.MapListener import org.osmdroid.events.ZoomEvent import org.osmdroid.util.BoundingBox import org.osmdroid.views.MapView import org.osmdroid.views.overlay.OverlayItem private val TAG = Logging.getTag(POIOverlay::class.java) class POIOverlay(mapView: CycleMapView) : LiveItemOverlay<POIOverlayItem?>(mapView, false), MapListener, MenuListener, PauseResumeListener, Undoable { private val context: Context = mapView.context private val activeCategories: MutableList<POICategory> = ArrayList() private val overlays: OverlayHelper = OverlayHelper(mapView) private val poiIcon = materialIcon(context, GoogleMaterial.Icon.gmd_place) private var lastFix: IGeoPoint? = null private var chooserShowing: Boolean = false init { Bubble.initialise(context, mapView) } ///////////////////////////////////////////////////// private fun allCategories(): POICategories { return POICategories.get() } private fun routeOverlay(): TapToRouteOverlay? { return overlays.get(TapToRouteOverlay::class.java) } ///////////////////////////////////////////////////// override fun onPause(prefs: SharedPreferences.Editor) { prefs.putInt("category-count", activeCategories.size) for (i in activeCategories.indices) prefs.putString("category-$i", activeCategories[i].name) } override fun onResume(prefs: SharedPreferences) { activeCategories.clear() val firstTime = !POICategories.loaded() try { reloadActiveCategories(prefs) } catch (e: Exception) { // very occasionally this throws a NullException, although it's not something // I've been able to replicate :( // Let's just carry on activeCategories.clear() } if (firstTime) { items().clear() clearLastFix() Bubble.activeItem = null refreshItems() } } private fun reloadActiveCategories(prefs: SharedPreferences) { val count = prefs.getInt("category-count", 0) for (i in 0 until count) { val name = prefs.getString("category-$i", "") for (cat in allCategories()) { if (name == cat.name) { activeCategories.add(cat) break } } } } /////////////////////////////////////////////////////// override fun onZoom(event: ZoomEvent): Boolean { clearLastFix() return super.onZoom(event) } /////////////////////////////////////////////////// override fun onSingleTap(event: MotionEvent): Boolean { // Check whether tapped in bubble if (Bubble.onSingleTap(event, mapView().projection, context, this)) return true // The following checks whether tap was on a displayed POI: return super.onSingleTap(event) } override fun onItemSingleTap(item: POIOverlayItem?): Boolean { hideOrShowBubble(item, this) redraw() return true } override fun onItemDoubleTap(item: POIOverlayItem?): Boolean { return routeMarkerAtItem(item) } private fun routeMarkerAtItem(item: POIOverlayItem?): Boolean { hideBubble(this) val o = routeOverlay() ?: return false o.setNextMarker(item!!.point) return true } ///////////////////////////////////////////////////// override fun draw(canvas: Canvas, mapView: MapView, shadow: Boolean) { if (activeCategories.isNotEmpty()) { super.draw(canvas, mapView, shadow) } if (Bubble.activeItem == null) return Bubble.drawBubble(canvas, mapView, textBrush(), urlBrush(), offset()) } private fun updateCategories(newCategories: List<POICategory>) { val removed = notIn(activeCategories, newCategories) val added = notIn(newCategories, activeCategories) if (removed.isNotEmpty()) { for (r in removed) { Log.d(TAG, "Removed POI category $r") hide(r) } redraw() } if (added.isNotEmpty()) { for (a in added) { Log.d(TAG, "Added POI category $a") activeCategories.add(a) } clearLastFix() refreshItems() } } private fun hide(cat: POICategory) { if (!activeCategories.contains(cat)) return activeCategories.remove(cat) for (i in items().indices.reversed()) { if (cat == items()[i]!!.category()) { items().removeAt(i) } } if (Bubble.activeItem != null && cat == Bubble.activeItem!!.category()) Bubble.activeItem = null } private fun notIn(c1: List<POICategory>, c2: List<POICategory>): List<POICategory> { return c1.minus(c2) } override fun fetchItemsInBackground(mapCentre: IGeoPoint, zoom: Int, boundingBox: BoundingBox): Boolean { if (activeCategories.isEmpty()) return false val moved = if (lastFix != null) GeoHelper.distanceBetween(mapCentre, lastFix) else Int.MAX_VALUE val diagonalWidth = (boundingBox.diagonalLengthInMeters / 1000).toInt() // first time through width can be zero if (diagonalWidth == 0 || moved < diagonalWidth / 2) return false lastFix = mapCentre GetPOIsTask.fetch(this, mapCentre, diagonalWidth * 3 + 1) return true } protected fun clearLastFix() { lastFix = null } ///////////////////////////////////////////////////// override fun onCreateOptionsMenu(menu: Menu) { MenuHelper.createMenuItem(menu, R.string.poi_menu_title, Menu.NONE, poiIcon) MenuHelper.enableMenuItem(menu, R.string.poi_menu_title, true) } override fun onPrepareOptionsMenu(menu: Menu) { MenuHelper.enableMenuItem(menu, R.string.poi_menu_title, true) } override fun onMenuItemSelected(featureId: Int, item: MenuItem): Boolean { if (item.itemId != R.string.poi_menu_title) return false if (chooserShowing) return true chooserShowing = true val poiAdapter = POICategoryAdapter(context, allCategories(), activeCategories) Dialog.listViewDialog(context, R.string.poi_menu_title, poiAdapter, { _, _ -> chooserShowing = false updateCategories(poiAdapter.chosenCategories()) }, { _, _ -> chooserShowing = false }) return true } override fun onBackPressed(): Boolean { hideBubble(this) redraw() return true } ///////////////////////////////////////////////////// private class GetPOIsTask(private val overlay: POIOverlay) : AsyncTask<Any, Void?, List<POI>>() { // take snapshot of categories to avoid later contention private val activeCategories: List<POICategory> = ArrayList(overlay.activeCategories) override fun doInBackground(vararg params: Any): List<POI> { val centre = params[0] as IGeoPoint val radius = params[1] as Int val pois: MutableList<POI> = ArrayList() for (cat in activeCategories) try { pois.addAll(cat.pois(centre, radius)) } catch (ex: RuntimeException) { // never mind, eh? } return pois } override fun onPostExecute(pois: List<POI>) { val items: MutableList<POIOverlayItem> = ArrayList() for (poi in pois) { // there used to be dead code here which checked for duplicate with items.contains(poi) // which could never work properly, since the lists are of different types. // if we find duplicate POIs, maybe we'll have to reintroduce that properly. items.add(POIOverlayItem(poi)) } overlay.setItems(items as List<POIOverlayItem?>?) } companion object { fun fetch(overlay: POIOverlay, centre: IGeoPoint, radius: Int) { GetPOIsTask(overlay).execute(centre, radius) } } } ////////////////////////////////// internal class POICategoryAdapter(context: Context, private val cats: POICategories, initialCategories: List<POICategory>) : BaseAdapter(), View.OnClickListener { private val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater private val selected: MutableList<POICategory> = initialCategories.toMutableList() init { Log.d(TAG, "Creating POICategoryAdapter - previously-selected categories are: $initialCategories") } fun chosenCategories(): List<POICategory> { return selected } override fun getCount(): Int { return cats.count() } override fun getItem(position: Int): Any { return cats[position] } override fun getItemId(position: Int): Long { return position.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val cat = cats[position] val v = convertView ?: inflater.inflate(R.layout.poicategories_item, parent, false) v.findViewById<TextView>(R.id.name).text = cat.name v.findViewById<ImageView>(R.id.icon).apply { setImageDrawable(cats[cat.name].icon) } val chk = v.findViewById<CheckBox>(R.id.checkbox).apply { setOnCheckedChangeListener(null) isChecked = isSelected(cat) } v.setOnClickListener(this) // This has to be done separately from the original initialisation of chk, so inflation // of the List view doesn't go mental chk.setOnCheckedChangeListener { _, isChecked -> if (isChecked) { Log.d(TAG, "Selected POI category $cat") selected.add(cat) } else { Log.d(TAG, "Deselected POI category $cat") selected.remove(cat) } } return v } override fun onClick(view: View) { view.findViewById<CheckBox>(R.id.checkbox).apply { isChecked = !isChecked } } private fun isSelected(cat: POICategory): Boolean { for (c in selected) if (cat.name == c.name) return true return false } } class POIOverlayItem(val poi: POI) : OverlayItem(poi.id().toString(), poi.name(), poi.notes(), poi.position()) { init { setMarker(this.poi.icon()) markerHotspot = HotspotPlace.CENTER } fun category(): POICategory { return poi.category() } // Equality testing override fun equals(other: Any?): Boolean { if (other !is POIOverlayItem) return false return (poi.id() == other.poi.id()) } override fun hashCode(): Int { return poi.id() } override fun toString(): String { return "POIItem [poi=${poi}]" } } }
gpl-3.0
4214f372dc0c35c65d39c8220c822118
32
122
0.571161
4.83685
false
false
false
false
hurricup/intellij-community
platform/credential-store/test/MasterPasswordMigrationTest.kt
1
4095
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.credentialStore import com.intellij.ide.passwordSafe.impl.providers.masterKey.MasterKeyPasswordSafeTest import com.intellij.ide.passwordSafe.impl.providers.masterKey.PasswordDatabase import com.intellij.openapi.util.JDOMUtil import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.runInEdtAndWait import com.intellij.util.xmlb.XmlSerializer import org.assertj.core.api.Assertions.assertThat import org.junit.ClassRule import org.junit.Test internal class MasterPasswordMigrationTest { companion object { @JvmField @ClassRule val projectRule = ApplicationRule() } @Test fun emptyPass() { val passwordSafe = convertOldDb(getDb("""<State> <option name="MASTER_PASSWORD_INFO" value="" /> <option name="PASSWORDS"> <array> <array> <option value="9a9e0048b26176cefb484b17675c09d8d4363acb16a8c2c194ddc160ea7fee1b" /> <option value="e86d036dc89ed252627ba61b6023ec0b21cbd58fbbacdbe2b530c4a553903dd8" /> <option value="05e93059f4487f4cc257133e6c54d81f53b7793965d23ca9e4b0a4960edfca33" /> <option value="41f099697425bce16e5ddd9ab89e03cc630cc4f5fa081af7c4eb934d4718d902" /> </array> <array> <option value="c124cdeb9a72bad8d1f3bc8037b45399" /> <option value="8962f7731a0b30862b4da5c9d9830a2cc5f5fc1648242d888b16d1668c2dd1ad" /> <option value="116f1b839d1326d6ecd52b78bb050cd1" /> <option value="6eee9deabcdc913623785094611a0bf0" /> </array> </array> </option> </State>""")) assertThat(passwordSafe).isNotEmpty val provider = FileCredentialStore(passwordSafe) @Suppress("DEPRECATION") assertThat(provider.getPassword(MasterKeyPasswordSafeTest::class.java, "TEST")).isEqualTo("test") } @Test fun nonEmptyPass() { var passwordSafe: Map<CredentialAttributes, Credentials>? = null runInEdtAndWait { passwordSafe = convertOldDb(getDb("""<State> <option name="MASTER_PASSWORD_INFO" value="" /> <option name="PASSWORDS"> <array> <array> <option value="a3e35d4153b3ddff12629573cd3ef001bd852f33bbf7ada6988362f6f72ccab2" /> <option value="a35725ba0caaf9ea8dc6a6a001bb03ce0307f5ace094264f3e10019076e5bd3b" /> <option value="a6f02f741d8be093f6f95db718cf4d779a93ff8917e1693eb29072b4f75aade4" /> <option value="4acfac8ee7e1f0ef8865150707a911d6d1ac6164ff31d09c1ade16c8a4191568" /> </array> <array> <option value="b81ff8a25505f9e6db9d398dcab08774" /> <option value="d8e6e0d1ea8e5b239c4c87583fc263f8" /> <option value="05396cc1090959a5cde51670c228bb8fbc6eebb9fae479d8360e11e40642f074" /> <option value="d8e6e0d1ea8e5b239c4c87583fc263f8" /> </array> </array> </option> </State>""")) } assertThat(passwordSafe).isNotEmpty val provider = FileCredentialStore(passwordSafe) @Suppress("DEPRECATION") assertThat(provider.getPassword(MasterKeyPasswordSafeTest::class.java, "TEST")).isEqualTo("test") } @Suppress("DEPRECATION") private fun getDb(data: String): PasswordDatabase { val passwordDatabase = PasswordDatabase() val state = PasswordDatabase.State() XmlSerializer.deserializeInto(state, JDOMUtil.load(data.reader())) passwordDatabase.loadState(state) return passwordDatabase } }
apache-2.0
e2e8dc3d542bb5f0f116fa814f8ec839
39.554455
101
0.713309
3.345588
false
true
false
false
Adventech/sabbath-school-android-2
common/lessons-data/src/main/java/app/ss/lessons/data/repository/lessons/LessonInfoDataSource.kt
1
3984
/* * 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.lessons.data.repository.lessons import app.ss.lessons.data.api.SSLessonsApi import app.ss.lessons.data.repository.DataSource import app.ss.lessons.data.repository.DataSourceMediator import app.ss.lessons.data.repository.LocalDataSource import app.ss.models.SSLesson import app.ss.models.SSLessonInfo import app.ss.storage.db.dao.LessonsDao import app.ss.storage.db.entity.LessonEntity import com.cryart.sabbathschool.core.extensions.connectivity.ConnectivityHelper import com.cryart.sabbathschool.core.extensions.coroutines.DispatcherProvider import com.cryart.sabbathschool.core.response.Resource import javax.inject.Inject import javax.inject.Singleton @Singleton internal class LessonInfoDataSource @Inject constructor( dispatcherProvider: DispatcherProvider, connectivityHelper: ConnectivityHelper, private val lessonsApi: SSLessonsApi, private val lessonsDao: LessonsDao ) : DataSourceMediator<SSLessonInfo, LessonInfoDataSource.Request>( dispatcherProvider = dispatcherProvider, connectivityHelper = connectivityHelper ) { data class Request(val lessonIndex: String) override val cache: LocalDataSource<SSLessonInfo, Request> = object : LocalDataSource<SSLessonInfo, Request> { override suspend fun getItem(request: Request): Resource<SSLessonInfo> { val info = lessonsDao.get(request.lessonIndex) if (info == null || info.days.isEmpty()) return Resource.loading() return Resource.success(info.toInfoModel()) } override suspend fun updateItem(data: SSLessonInfo) { lessonsDao.updateInfo( data.lesson.index, data.days, data.pdfs ) } } override val network: DataSource<SSLessonInfo, Request> = object : DataSource<SSLessonInfo, Request> { override suspend fun getItem(request: Request): Resource<SSLessonInfo> { val error = Resource.error<SSLessonInfo>(Throwable("")) val index = request.lessonIndex val language = index.substringBefore('-') val lessonId = index.substringAfterLast('-') val quarterlyId = index.substringAfter('-') .substringBeforeLast('-') val resource = lessonsApi.getLessonInfo(language, quarterlyId, lessonId) return resource.body()?.let { Resource.success(it) } ?: error } } private fun LessonEntity.toInfoModel(): SSLessonInfo = SSLessonInfo( lesson = SSLesson( title = title, start_date = start_date, end_date = end_date, cover = cover, id = id, index = index, path = path, full_path = full_path, pdfOnly = pdfOnly ), days = days, pdfs = pdfs ) }
mit
63287c26ba9e925b3baa6f965ac905f7
38.84
114
0.699548
4.627178
false
false
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/util/lexer/automata/nfa/NFAStatus.kt
1
1509
package com.bajdcc.util.lexer.automata.nfa import com.bajdcc.util.VisitBag import com.bajdcc.util.lexer.automata.BreadthFirstSearch /** * NFA状态 * [data] 数据 * @author bajdcc */ class NFAStatus(var data: NFAStatusData = NFAStatusData()) { /** * 出边集合 */ var outEdges = mutableListOf<NFAEdge>() /** * 入边集合 */ var inEdges = mutableListOf<NFAEdge>() /** * 用于遍历包括该状态在内的所有状态(连通),结果存放在PATH中 * * @param bfs 遍历算法 */ fun visit(bfs: BreadthFirstSearch<NFAEdge, NFAStatus>) { val stack = bfs.arrStatus val set = mutableSetOf<NFAStatus>() stack.clear() set.add(this) stack.add(this) var i = 0 while (i < stack.size) {// 遍历每个状态 val status = stack[i] val bag = VisitBag() bfs.visitBegin(status, bag) if (bag.visitChildren) { // 遍历状态的出边 // 边未被访问,且边类型符合要求 status.outEdges.asSequence().filter { edge -> !set.contains(edge.end) && bfs.testEdge(edge) }.forEach {// 边未被访问,且边类型符合要求 edge -> stack.add(edge.end!!) set.add(edge.end!!) } } if (bag.visitEnd) { bfs.visitEnd(status) } i++ } } }
mit
3a67fd0cef17be63a4dafbe787398e49
24.301887
136
0.50783
3.492188
false
false
false
false
DuncanCasteleyn/DiscordModBot
src/main/kotlin/be/duncanc/discordmodbot/bot/sequences/Sequence.kt
1
6313
/* * Copyright 2018 Duncan Casteleyn * * 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 be.duncanc.discordmodbot.bot.sequences import be.duncanc.discordmodbot.bot.utils.limitLessBulkDeleteByIds import net.dv8tion.jda.api.MessageBuilder import net.dv8tion.jda.api.entities.Message import net.dv8tion.jda.api.entities.MessageChannel import net.dv8tion.jda.api.entities.TextChannel import net.dv8tion.jda.api.entities.User import net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent import net.dv8tion.jda.api.events.message.MessageReceivedEvent import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent import net.dv8tion.jda.api.hooks.ListenerAdapter import org.slf4j.LoggerFactory import java.time.Instant import java.time.temporal.ChronoUnit import java.util.concurrent.TimeUnit /** * This class allows for users to be asked or do something in sequences. * * @since 1.1.0 */ @Deprecated( "To be replaced with onSlashCommand function from ListenerAdapter" ) abstract class Sequence @JvmOverloads protected constructor( val user: User, val channel: MessageChannel, cleanAfterSequence: Boolean = true, informUser: Boolean = true ) : ListenerAdapter() { companion object { private val LOG = LoggerFactory.getLogger(Sequence::class.java) } private val cleanAfterSequence: ArrayList<Long>? private val expireInstant: Instant val expired: Boolean get() { return Instant.now().isAfter(expireInstant) } init { @Suppress("LeakingThis") if (this is MessageSequence && cleanAfterSequence && channel is TextChannel) { this.cleanAfterSequence = ArrayList() } else { this.cleanAfterSequence = null } if (informUser) { try { channel.sendMessage( user.asMention + " You are now in a sequences. The bot will ignore all further commands as you first need to complete the sequences.\n" + "To complete the sequence answer the questions or tasks given by the bot in " + (if (channel is TextChannel) channel.asMention else "Private chat") + " \n" + "Any message you send in this channel will be used as input.\n" + "\nA sequences automatically expires after not receiving a message for 5 minutes within this channel.\n" + "You can also kill a sequences by sending \"STOP\" (Case sensitive)." ).queue { addMessageToCleaner(it) } } catch (e: Exception) { LOG.info("A sequence was terminated due to an exception during initialization", e) destroy() throw e } } expireInstant = Instant.now().plus(5, ChronoUnit.MINUTES) } /** * Will perform the required actions while in a sequences and then send it to the {@code onMessageReceivedDuringSequence(event)}. * * When {@code onMessageReceivedDuringSequence(event)} throws an exception it catches it, send the exception name and message and terminate the sequences. */ override fun onMessageReceived(event: MessageReceivedEvent) { if (event.author != user || event.message.channel != channel) { return } if (this is MessageSequence) { addMessageToCleaner(event.message) } if (event.message.contentRaw == "STOP") { destroy() return } if (this !is MessageSequence) { return } try { onMessageReceivedDuringSequence(event) } catch (t: Throwable) { LOG.info("A sequence was terminated due to an exception", t) destroy() val errorMessage: Message = MessageBuilder().append(user.asMention + " The sequences has been terminated due to an error; see the message below for more information.") .appendCodeBlock(t.javaClass.simpleName + ": " + t.message, "text") .build() channel.sendMessage(errorMessage).queue { it.delete().queueAfter(1, TimeUnit.MINUTES) } return } } override fun onMessageReactionAdd(event: MessageReactionAddEvent) { if (this !is ReactionSequence || event.user != user) { return } this.onReactionReceivedDuringSequence(event) } override fun onGuildMemberRemove(event: GuildMemberRemoveEvent) { if (channel is TextChannel && channel.guild == event.guild && user == event.user) { destroy() } else if (event.user.mutualGuilds.isEmpty()) { destroy() } } /** * Let the garbage collector destroy this object. */ @Suppress("unused") @Throws(Throwable::class) protected open fun finalize() { destroy() } fun destroy() { user.jda.removeEventListener(this) cleanAfterSequence?.let { synchronized(it) { if (it.isNotEmpty()) { try { (channel as TextChannel).limitLessBulkDeleteByIds(it) } catch (e: Exception) { LOG.error("Was unable to clear messages when destroying sequence", e) } } } } } protected fun addMessageToCleaner(message: Message) { if (message.channel != channel) { throw IllegalArgumentException("The message needs to be from the same channel as the sequence.") } cleanAfterSequence?.let { synchronized(it) { it.add(message.idLong) } } } }
apache-2.0
7e3ddc518aceff9f0bfd5870c9facd88
36.35503
185
0.623
4.718236
false
false
false
false
KotlinNLP/SimpleDNN
src/test/kotlin/core/functionalities/activations/SeLUSpec.kt
1
1825
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package core.functionalities.activations import com.kotlinnlp.simplednn.core.functionalities.activations.SeLU import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import kotlin.test.assertTrue /** * */ class SeLUSpec: Spek({ describe("a SeLU activation function") { val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.1, 0.01, -0.1, -0.01, 1.0, 10.0, -1.0, -10.0)) context("default configuration") { val activationFunction = SeLU() val activatedArray = activationFunction.f(array) context("f") { val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf( 0.0, 0.10507009, 0.01050700, -0.16730527, -0.01749338, 1.0507009, 10.5070099, -1.11133072, -1.758019508 )) it("should return the expected values") { assertTrue { expectedArray.equals(activatedArray, tolerance = 1.0e-07) } } } context("dfOptimized") { val dfArray = activationFunction.dfOptimized(activatedArray) val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf( 1.758099343, 1.0507009, 1.0507009, 1.59079407, 1.740605962, 1.0507009, 1.0507009, 0.646768603, 0.000079817586 )) it("should return the expected values") { assertTrue { expectedArray.equals(dfArray, tolerance = 1.0e-07) } } } } } })
mpl-2.0
c20c50444af1033a673ba508a259dcba
32.181818
121
0.659178
3.70935
false
false
false
false
MRylander/RylandersRealm
src/main/kotlin/rylandersrealm/action/ActionManager.kt
1
1837
/* * Copyright 2017 Michael S Rylander * * 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 rylandersrealm.action import org.slf4j.LoggerFactory import rylandersrealm.Invalid import rylandersrealm.Player.Player object ActionManager { private val LOG = LoggerFactory.getLogger(this::class.java) private val validActions = mutableSetOf<Action>(MoveAction()) fun registerAction(action: Action) { LOG.debug("Registering Action $action") if (!validActions.add(action)) { LOG.warn("Failed to register action $action. Currently registered actions $validActions") } } fun executePlayerAction(player: Player, rawInput: String): String { //TODO catch invalid target and invalud action exceptions. val action = parseInput(rawInput) return action.execute(player, rawInput) } /** * Exposed for unit test. */ fun parseInput(input: String): Action { val normalizedInput = normalize(input) val action = validActions.find { normalizedInput.startsWith(it.command) } ?: Invalid.ACTION LOG.debug("Parsed input: input='$input'; command='$action'") return action } } //TODO figure out where to put this. fun normalize(string: String): String = string.replace("\\s".toRegex(), "").toLowerCase()
apache-2.0
b996cf20840d4bcce6dcf41cfa10fe35
30.672414
101
0.701143
4.34279
false
false
false
false
micolous/metrodroid
src/iOSMain/kotlin/au/id/micolous/metrodroid/multi/FormattedString.kt
1
3894
/* * FormattedString.kt * * Copyright 2019 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.multi import au.id.micolous.metrodroid.util.Preferences import platform.Foundation.* import platform.UIKit.* actual class FormattedString (val attributed: NSAttributedString): Parcelable { actual val unformatted: String get() = attributed.string() actual constructor(input: String): this(NSAttributedString.create(string = input)) actual override fun toString(): String = unformatted actual operator fun plus(b: String): FormattedString = this + FormattedString(b) actual operator fun plus(b: FormattedString): FormattedString { val mut = NSMutableAttributedString() mut.appendAttributedString(attributed) mut.appendAttributedString(b.attributed) return FormattedString(mut) } actual fun substring(start: Int): FormattedString = FormattedString(attributed.attributedSubstringFromRange(NSMakeRange(start.toULong(), attributed.length - start.toULong()))) actual fun substring(start: Int, end: Int): FormattedString = FormattedString(attributed.attributedSubstringFromRange(NSMakeRange(start.toULong(), end.toULong() - start.toULong()))) actual companion object { private fun localeString(input: String, lang: String?, debugColor: UIColor): FormattedString { if (!Preferences.localisePlaces) { return FormattedString(input) } val attributes = HashMap<Any?, Any?>() attributes[UIAccessibilitySpeechAttributeLanguage] = lang ?: Preferences.language if (Preferences.debugSpans) attributes[NSForegroundColorAttributeName] = debugColor return FormattedString(NSAttributedString.create(string = input, attributes = attributes)) } actual fun monospace(input: String): FormattedString = FormattedString(NSAttributedString.create(string = input, attributes = mapOf<Any?, Any?>(NSFontAttributeName to UIFont.fontWithName("Courier", size=12.0)))) actual fun language(input: String, lang: String): FormattedString = localeString(input, lang, UIColor.blueColor) actual fun english(input: String) = localeString(input, "en", UIColor.yellowColor) actual fun defaultLanguage(input: String) = localeString(input, null, UIColor.greenColor) } } actual class FormattedStringBuilder actual constructor() { actual fun append(value: StringBuilder): FormattedStringBuilder { append(value.toString()) return this } actual fun append(value: String): FormattedStringBuilder { append(FormattedString(value)) return this } actual fun append(value: FormattedString): FormattedStringBuilder { mut.appendAttributedString(value.attributed) return this } actual fun append(value: FormattedString, start: Int, end: Int): FormattedStringBuilder { mut.appendAttributedString(value.attributed.attributedSubstringFromRange(NSMakeRange(start.toULong(), end.toULong() - start.toULong()))) return this } actual fun build(): FormattedString = FormattedString(mut) private val mut: NSMutableAttributedString = NSMutableAttributedString() }
gpl-3.0
dc35bf45f7a321277dc205973be90761
44.27907
185
0.722393
4.772059
false
false
false
false
GunoH/intellij-community
plugins/refactoring-detector/src/com/intellij/refactoring/detector/actions/FindRefactoringInCommitAction.kt
3
3196
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.refactoring.detector.actions import com.intellij.CommonBundle import com.intellij.json.JsonFileType import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.runInEdt import com.intellij.openapi.application.runReadAction import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages.showDialog import com.intellij.openapi.ui.Messages.showInfoMessage import com.intellij.openapi.vcs.VcsDataKeys import com.intellij.refactoring.detector.RefactoringDetectorBundle.Companion.message import com.intellij.testFramework.LightVirtualFile import com.intellij.vcs.log.VcsLogDataKeys import org.jetbrains.research.kotlinrminer.ide.KotlinRMiner import org.jetbrains.research.kotlinrminer.ide.Refactoring class FindRefactoringInCommitAction : DumbAwareAction() { override fun getActionUpdateThread() = ActionUpdateThread.EDT override fun update(e: AnActionEvent) { val log = e.getData(VcsLogDataKeys.VCS_LOG_COMMIT_SELECTION) e.presentation.isEnabledAndVisible = e.project != null && log != null && log.commits.isNotEmpty() } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val changes = e.getData(VcsDataKeys.CHANGES)?.toList() ?: return runBackgroundableTask(message("progress.find.refactoring.title"), project, false) { val refactorings = runReadAction { KotlinRMiner.detectRefactorings(project, changes) } runInEdt { if (refactorings.isEmpty()) { showInfoMessage(project, message("message.no.refactorings.found"), message("message.find.refactoring.dialog.title")) } else { val message = message("message.found.refactorings", refactorings.size, refactorings.joinToString(separator = "\n")) val title = message("message.find.refactoring.dialog.title") if (showDialog(project, message, title, arrayOf(message("button.show"), CommonBundle.getCancelButtonText()), 0, null) == 0) { showRefactoringsInEditor(project, refactorings) } } } } } private fun List<Refactoring>.toJsonRepresentation(): String = """[${joinToString(separator = ",\n", transform = Refactoring::toJSON)}]""" private fun showRefactoringsInEditor(project: Project, refactorings: List<Refactoring>) { val jsonFile = InMemoryJsonVirtualFile(refactorings.toJsonRepresentation()) OpenFileDescriptor(project, jsonFile, 0).navigate(true) } private class InMemoryJsonVirtualFile(private val content: String) : LightVirtualFile(message("refactorings.file.name")) { override fun getContent(): CharSequence = content override fun getPath(): String = name override fun getFileType(): FileType = JsonFileType.INSTANCE } }
apache-2.0
657d3b5d87282aaca4e3b77a1a3f4dba
46
158
0.768148
4.638607
false
false
false
false
ekoshkin/teamcity-azure-active-directory
azure-active-directory-server/src/main/kotlin/org/jetbrains/teamcity/aad/AADConstants.kt
1
1712
/* * Copyright 2000-2021 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.teamcity.aad import jetbrains.buildServer.PluginTypes import jetbrains.buildServer.users.PluginPropertyKey import jetbrains.buildServer.users.PropertyKey /** * @author Evgeniy.Koshkin */ object AADConstants { const val AAD_AUTH_SCHEME_NAME = "AAD" const val AUTH_ENDPOINT_SCHEME_PROPERTY_KEY = "authEndpoint" const val CLIENT_ID_SCHEME_PROPERTY_KEY = "clientId" const val ALLOW_MATCHING_USERS_BY_EMAIL = "allowMatchingUsersByEmail" const val ALLOW_USER_DETAILS_SYNC = "allowUserDetailsSync" const val AUTH_PROMPT = "authPrompt" const val LOGIN_PATH = "/aadLogin.html" const val OVERVIEW_PATH = "/overview.html" const val DEDICATED_AUTH_PATH = "/aadAuth.html" const val ID_TOKEN = "id_token" const val NONCE_CLAIM = "nonce" val OID_USER_PROPERTY_KEY: PropertyKey = PluginPropertyKey(PluginTypes.AUTH_PLUGIN_TYPE, "azure-active-directory", "oid") const val TTL_IN_MINUTES_PROPERTY = "teamcity.aad.token.ttl" const val ENDPOINT_TYPE_PROPERTY = "teamcity.aad.endpoint.type" const val DEDICATED_ENDPOINT_TYPE = "dedicated" }
apache-2.0
156b8084e3b6d7c818147e128b674c1f
36.217391
125
0.74007
3.689655
false
false
false
false
sczerwinski/android-calculator
app/src/main/kotlin/pl/info/czerwinski/android/calculator/processor/Value.kt
1
1295
package pl.info.czerwinski.android.calculator.processor import pl.info.czerwinski.android.calculator.processor.operations.UnaryOperation data class Value(val text: String) { companion object { val EMPTY = Value("") } constructor(int: Int) : this(int.toString()) constructor(long: Long) : this(long.toString()) constructor(float: Float) : this(if (float.isInt()) float.toInt().toString() else float.toString()) constructor(double: Double) : this(if (double.isLong()) double.toLong().toString() else double.toString()) operator fun plus(digit: Char) = Value( if (digit == '.') if ('.' in text) text else text + digit else if (text == "0") digit.toString() else text + digit ) operator fun unaryMinus() : Value = Value(if (text.startsWith('-')) text.substring(1) else "-" + text) operator fun plus(value: Value) = Value(toDouble() + value.toDouble()) operator fun minus(value: Value) = Value(toDouble() - value.toDouble()) operator fun times(value: Value) = Value(toDouble() * value.toDouble()) operator fun div(value: Value) = Value(toDouble() / value.toDouble()) fun toOperation() = UnaryOperation { this } fun toDouble() = if (text.isEmpty()) 0.0 else text.toDouble() override fun toString() = if (text.isEmpty()) "0" else text.replace('-', '\u2212') }
apache-2.0
89cb2bd7d7e802765e30fdfa6dddbddf
36
107
0.689575
3.453333
false
false
false
false
GunoH/intellij-community
plugins/kotlin/code-insight/inspections-shared/tests/testData/inspectionsLocal/removeSetterParameterType/simple2.kt
3
235
class My { var y: Int = 1 set(param: <caret>Int) { field = param - 1 } var z: Double = 3.14 private set var w: Boolean = true set(param) { field = !param } }
apache-2.0
aedfb5928719cf620d1894401826f874
15.857143
32
0.417021
3.730159
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/stepping/filter/KotlinStepOverParamDefaultImplsMethodFilter.kt
4
2644
// 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.debugger.core.stepping.filter import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.engine.MethodFilter import com.intellij.util.Range import com.sun.jdi.Location import org.jetbrains.kotlin.idea.debugger.base.util.safeMethod import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.org.objectweb.asm.Type class KotlinStepOverParamDefaultImplsMethodFilter( private val name: String, private val defaultSignature: String, private val containingTypeName: String, private val expressionLines: Range<Int> ) : MethodFilter { companion object { fun create(location: Location, expressionLines: Range<Int>): KotlinStepOverParamDefaultImplsMethodFilter? { if (location.lineNumber() < 0) { return null } val method = location.safeMethod() ?: return null val name = method.name() assert(name.endsWith(JvmAbi.DEFAULT_PARAMS_IMPL_SUFFIX)) val originalName = name.dropLast(JvmAbi.DEFAULT_PARAMS_IMPL_SUFFIX.length) val signature = method.signature() val containingTypeName = location.declaringType().name() return KotlinStepOverParamDefaultImplsMethodFilter(originalName, signature, containingTypeName, expressionLines) } } override fun locationMatches(process: DebugProcessImpl?, location: Location?): Boolean { val method = location?.safeMethod() ?: return true val containingTypeName = location.declaringType().name() return method.name() == name && containingTypeName == this.containingTypeName && signatureMatches(defaultSignature, method.signature()) } private fun signatureMatches(default: String, actual: String): Boolean { val defaultType = Type.getMethodType(default) val actualType = Type.getMethodType(actual) val defaultArgTypes = defaultType.argumentTypes val actualArgTypes = actualType.argumentTypes if (defaultArgTypes.size <= actualArgTypes.size) { // Default method should have more parameters than the implementation // because of flags return false } for ((index, type) in actualArgTypes.withIndex()) { if (defaultArgTypes[index] != type) { return false } } return true } override fun getCallingExpressionLines(): Range<Int> = expressionLines }
apache-2.0
4562f9c1ee9731bb15bdea04f1f58d74
38.462687
124
0.685325
4.969925
false
false
false
false
GunoH/intellij-community
python/src/com/jetbrains/python/sdk/flavors/PyCondaRunTargets.kt
2
3888
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.sdk.flavors import com.google.gson.annotations.SerializedName import com.intellij.execution.ExecutionException import com.intellij.execution.RunCanceledByUserException import com.intellij.execution.process.CapturingProcessHandler import com.intellij.execution.process.ProcessOutput import com.intellij.execution.target.TargetEnvironmentRequest import com.intellij.execution.target.TargetProgressIndicator import com.intellij.execution.target.TargetedCommandLineBuilder import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.util.text.StringUtil import com.jetbrains.python.PySdkBundle import com.jetbrains.python.packaging.IndicatedProcessOutputListener import com.jetbrains.python.packaging.PyCondaPackageService import com.jetbrains.python.packaging.PyExecutionException import com.jetbrains.python.run.PythonCommandLineState import com.jetbrains.python.run.target.HelpersAwareTargetEnvironmentRequest import com.jetbrains.python.sdk.PySdkUtil import com.jetbrains.python.target.PyTargetAwareAdditionalData @Deprecated("Do not run conda directly, use configureBuilderToRunPythonOnTarget") @Throws(ExecutionException::class) fun runCondaOnTarget(targetEnvironmentRequest: TargetEnvironmentRequest, condaExecutable: String, arguments: List<String>): ProcessOutput { return runOnTarget(targetEnvironmentRequest, condaExecutable, arguments, readCondaEnv(condaExecutable)) } @Deprecated("Do not run conda directly, use configureBuilderToRunPythonOnTarget") private fun runOnTarget(targetEnvironmentRequest: TargetEnvironmentRequest, executable: String, arguments: List<String>, env: Map<String, String>?): ProcessOutput { // TODO [targets] Use the wrapper for `ProgressIndicator` val targetProgressIndicator = TargetProgressIndicator.EMPTY val targetEnvironment = targetEnvironmentRequest.prepareEnvironment(targetProgressIndicator) val targetedCommandLineBuilder = TargetedCommandLineBuilder(targetEnvironmentRequest).apply { setExePath(executable) addParameters(arguments) env?.forEach { (key, value) -> addEnvironmentVariable(key, value) } } val targetedCommandLine = targetedCommandLineBuilder.build() val indicator = ProgressManager.getInstance().progressIndicator ?: EmptyProgressIndicator() val process = targetEnvironment.createProcess(targetedCommandLine, indicator) val commandPresentation = targetedCommandLine.getCommandPresentation(targetEnvironment) val handler = CapturingProcessHandler(process, Charsets.UTF_8, commandPresentation).apply { addProcessListener(IndicatedProcessOutputListener(indicator)) } return handler.runProcessWithProgressIndicator(indicator).apply { if (isCancelled) throw RunCanceledByUserException() checkExitCode(executable, arguments) } } @Deprecated("Do not run conda directly, use configureBuilderToRunPythonOnTarget") private fun readCondaEnv(condaExecutable: String): Map<String, String>? { return PyCondaPackageService.getCondaBasePython(condaExecutable)?.let { PySdkUtil.activateVirtualEnv(it) } } @Throws(PyExecutionException::class) private fun ProcessOutput.checkExitCode(executable: String, arguments: List<String>) { if (exitCode != 0) { val message = if (StringUtil.isEmptyOrSpaces(stdout) && StringUtil.isEmptyOrSpaces(stderr)) PySdkBundle.message("python.conda.permission.denied") else PySdkBundle.message("python.conda.non.zero.exit.code") throw PyExecutionException(message, executable, arguments, this) } }
apache-2.0
8260cdf072b135673d16c52359bfd190
53
158
0.818416
4.978233
false
false
false
false
ktorio/ktor
ktor-io/jvm/src/io/ktor/utils/io/charsets/CharsetJVM.kt
1
10646
package io.ktor.utils.io.charsets import io.ktor.utils.io.core.* import io.ktor.utils.io.core.Buffer import io.ktor.utils.io.core.internal.* import java.nio.* import java.nio.charset.* private const val DECODE_CHAR_BUFFER_SIZE = 8192 @Suppress("NO_ACTUAL_CLASS_MEMBER_FOR_EXPECTED_CLASS") public actual typealias Charset = java.nio.charset.Charset public actual val Charset.name: String get() = name() public actual typealias CharsetEncoder = java.nio.charset.CharsetEncoder public actual val CharsetEncoder.charset: Charset get() = charset() public actual fun CharsetEncoder.encodeToByteArray(input: CharSequence, fromIndex: Int, toIndex: Int): ByteArray { @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") if (input is String) { if (fromIndex == 0 && toIndex == input.length) { return (input as java.lang.String).getBytes(charset()) } return (input.substring(fromIndex, toIndex) as java.lang.String).getBytes(charset()) } return encodeToByteArraySlow(input, fromIndex, toIndex) } private fun CharsetEncoder.encodeToByteArraySlow(input: CharSequence, fromIndex: Int, toIndex: Int): ByteArray { val result = encode(CharBuffer.wrap(input, fromIndex, toIndex)) val existingArray = when { result.hasArray() && result.arrayOffset() == 0 -> result.array().takeIf { it.size == result.remaining() } else -> null } return existingArray ?: ByteArray(result.remaining()).also { result.get(it) } } internal actual fun CharsetEncoder.encodeImpl(input: CharSequence, fromIndex: Int, toIndex: Int, dst: Buffer): Int { val cb = CharBuffer.wrap(input, fromIndex, toIndex) val before = cb.remaining() dst.writeDirect(0) { bb -> val result = encode(cb, bb, false) if (result.isMalformed || result.isUnmappable) result.throwExceptionWrapped() } return before - cb.remaining() } public actual fun CharsetEncoder.encodeUTF8(input: ByteReadPacket, dst: Output) { if (charset === Charsets.UTF_8) { dst.writePacket(input) return } val tmp = ChunkBuffer.Pool.borrow() var readSize = 1 try { tmp.writeDirect(0) { tmpBb -> val cb = tmpBb.asCharBuffer() while (input.remaining > 0) { cb.clear() val chunk = input.prepareReadHead(readSize) if (chunk == null) { if (readSize != 1) throw MalformedInputException("...") break } val rc = chunk.decodeUTF8 { ch -> if (cb.hasRemaining()) { cb.put(ch) true } else false } input.headPosition = chunk.readPosition cb.flip() var writeSize = 1 if (cb.hasRemaining()) { dst.writeWhileSize { view -> view.writeDirect(writeSize) { to -> val cr = encode(cb, to, false) if (cr.isUnmappable || cr.isMalformed) cr.throwExceptionWrapped() if (cr.isOverflow && to.hasRemaining()) writeSize++ else writeSize = 1 } if (cb.hasRemaining()) writeSize else 0 } } if (rc > 0) { readSize = rc break } } cb.clear() cb.flip() var completeSize = 1 dst.writeWhileSize { chunk -> chunk.writeDirect(completeSize) { to -> val cr = encode(cb, to, true) if (cr.isMalformed || cr.isUnmappable) cr.throwExceptionWrapped() if (cr.isOverflow) completeSize++ else completeSize = 0 } completeSize } } } finally { tmp.release(ChunkBuffer.Pool) } } internal actual fun CharsetEncoder.encodeComplete(dst: Buffer): Boolean { var completed = false dst.writeDirect(0) { bb -> val result = encode(EmptyCharBuffer, bb, true) if (result.isMalformed || result.isUnmappable) result.throwExceptionWrapped() if (result.isUnderflow) { completed = true } } return completed } internal actual fun CharsetDecoder.decodeBuffer( input: Buffer, out: Appendable, lastBuffer: Boolean, max: Int ): Int { var charactersCopied = 0 input.readDirect { bb -> val tmpBuffer = ChunkBuffer.Pool.borrow() val cb = tmpBuffer.memory.buffer.asCharBuffer() try { while (bb.hasRemaining() && charactersCopied < max) { val partSize = minOf(cb.capacity(), max - charactersCopied) cb.clear() cb.limit(partSize) val result = decode(bb, cb, lastBuffer) if (result.isMalformed || result.isUnmappable) { result.throwExceptionWrapped() } charactersCopied += partSize } } finally { tmpBuffer.release(ChunkBuffer.Pool) } } return charactersCopied } // ----------------------- public actual typealias CharsetDecoder = java.nio.charset.CharsetDecoder public actual val CharsetDecoder.charset: Charset get() = charset()!! public actual fun CharsetDecoder.decode(input: Input, dst: Appendable, max: Int): Int { var copied = 0 val cb = CharBuffer.allocate(DECODE_CHAR_BUFFER_SIZE) var readSize = 1 input.takeWhileSize { buffer: Buffer -> val rem = max - copied if (rem == 0) return@takeWhileSize 0 buffer.readDirect { bb: ByteBuffer -> cb.clear() if (rem < DECODE_CHAR_BUFFER_SIZE) { cb.limit(rem) } val rc = decode(bb, cb, false) cb.flip() copied += cb.remaining() dst.append(cb) if (rc.isMalformed || rc.isUnmappable) rc.throwExceptionWrapped() if (rc.isUnderflow && bb.hasRemaining()) { readSize++ } else { readSize = 1 } } readSize } while (true) { cb.clear() val rem = max - copied if (rem == 0) break if (rem < DECODE_CHAR_BUFFER_SIZE) { cb.limit(rem) } val cr = decode(EmptyByteBuffer, cb, true) cb.flip() copied += cb.remaining() dst.append(cb) if (cr.isUnmappable || cr.isMalformed) cr.throwExceptionWrapped() if (cr.isOverflow) continue break } return copied } public actual fun CharsetDecoder.decodeExactBytes(input: Input, inputLength: Int): String { if (inputLength == 0) return "" if (input.headRemaining >= inputLength) { // if we have a packet or a buffered input with the first head containing enough bytes // then we can try fast-path if (input.headMemory.buffer.hasArray()) { // the most performant way is to use String ctor of ByteArray // on JVM9+ with string compression enabled it will do System.arraycopy and lazy decoding that is blazing fast // on older JVMs it is still the fastest way val bb = input.headMemory.buffer val text = String( bb.array(), bb.arrayOffset() + bb.position() + input.head.readPosition, inputLength, charset() ) input.discardExact(inputLength) return text } // the second fast-path is slower however it is still faster than general way return decodeImplByteBuffer(input, inputLength) } return decodeImplSlow(input, inputLength) } private fun CharsetDecoder.decodeImplByteBuffer(input: Input, inputLength: Int): String { val cb = CharBuffer.allocate(inputLength) val bb = input.headMemory.slice(input.head.readPosition, inputLength).buffer val rc = decode(bb, cb, true) if (rc.isMalformed || rc.isUnmappable) rc.throwExceptionWrapped() cb.flip() input.discardExact(bb.position()) return cb.toString() } private fun CharsetDecoder.decodeImplSlow(input: Input, inputLength: Int): String { val cb = CharBuffer.allocate(inputLength) var remainingInputBytes = inputLength var lastChunk = false var readSize = 1 input.takeWhileSize { buffer: Buffer -> if (!cb.hasRemaining() || remainingInputBytes == 0) return@takeWhileSize 0 buffer.readDirect { bb: ByteBuffer -> val limitBefore = bb.limit() val positionBefore = bb.position() lastChunk = limitBefore - positionBefore >= remainingInputBytes if (lastChunk) { bb.limit(positionBefore + remainingInputBytes) } val rc = decode(bb, cb, lastChunk) if (rc.isMalformed || rc.isUnmappable) rc.throwExceptionWrapped() if (rc.isUnderflow && bb.hasRemaining()) { readSize++ } else { readSize = 1 } bb.limit(limitBefore) remainingInputBytes -= bb.position() - positionBefore } readSize } if (cb.hasRemaining() && !lastChunk) { val rc = decode(EmptyByteBuffer, cb, true) if (rc.isMalformed || rc.isUnmappable) rc.throwExceptionWrapped() } if (remainingInputBytes > 0) { throw EOFException( "Not enough bytes available: had only ${inputLength - remainingInputBytes} instead of $inputLength" ) } if (remainingInputBytes < 0) { throw AssertionError("remainingInputBytes < 0") } cb.flip() return cb.toString() } private fun CoderResult.throwExceptionWrapped() { try { throwException() } catch (original: java.nio.charset.MalformedInputException) { throw MalformedInputException(original.message ?: "Failed to decode bytes") } } // ---------------------------------- public actual typealias Charsets = kotlin.text.Charsets @Suppress("ACTUAL_WITHOUT_EXPECT") public actual open class MalformedInputException actual constructor(message: String) : java.nio.charset.MalformedInputException(0) { private val _message = message override val message: String? get() = _message } private val EmptyCharBuffer = CharBuffer.allocate(0) private val EmptyByteBuffer = ByteBuffer.allocate(0)!!
apache-2.0
845ee62ea6f0e6f8c1ed50ad4c51cf94
30.037901
122
0.581063
4.553464
false
false
false
false
marius-m/wt4
app/src/main/java/lt/markmerkk/widgets/edit/LogDetailsPresenterCreate.kt
1
2323
package lt.markmerkk.widgets.edit import lt.markmerkk.* import lt.markmerkk.entities.Log import lt.markmerkk.entities.TicketCode import lt.markmerkk.entities.TimeGap import lt.markmerkk.events.EventMainOpenTickets import lt.markmerkk.mvp.LogEditService2 import lt.markmerkk.mvp.LogEditService2Impl class LogDetailsPresenterCreate( private val viewProvider: ViewProvider<LogDetailsContract.View>, private val eventBus: WTEventBus, private val timeProvider: TimeProvider, private val ticketStorage: TicketStorage, private val activeDisplayRepository: ActiveDisplayRepository, ) : LogDetailsContract.Presenter { private val logEditService: LogEditService2 = LogEditService2Impl( timeProvider = timeProvider, ticketStorage = ticketStorage, activeDisplayRepository = activeDisplayRepository, listener = object : LogEditService2.Listener { override fun showDateTimeChange(timeGap: TimeGap) { viewProvider.invoke { this.showDateTime(timeGap.start, timeGap.end) } } override fun showDuration(durationAsString: String) { viewProvider.invoke { this.showHint1(durationAsString) } } override fun showComment(comment: String) { viewProvider.invoke { this.showComment(comment) } } override fun showCode(ticketCode: TicketCode) { viewProvider.invoke { this.showTicketCode(ticketCode.code) } } override fun showSuccess(log: Log) { viewProvider.invoke { this.closeDetails() } } } ) override fun onAttach() { logEditService.initWithLog(log = Log.createAsEmpty(timeProvider)) viewProvider.invoke { this.initView("Create new log") } } override fun onDetach() { } override fun changeDateTime(timeGap: TimeGap) { logEditService.updateDateTime(timeGap) } override fun openFindTickets() { eventBus.post(EventMainOpenTickets()) } override fun changeTicketCode(ticket: String) { logEditService.updateCode(ticket) } override fun changeComment(comment: String) { logEditService.updateComment(comment) } override fun save() { logEditService.saveEntity() } }
apache-2.0
8703ab411b165f5382960f6acb731fd4
30.405405
85
0.680155
4.721545
false
false
false
false
Doctoror/ParticleConstellationsLiveWallpaper
app/src/main/java/com/doctoror/particleswallpaper/userprefs/enginetips/EngineTipsPreference.kt
1
1659
/* * Copyright (C) 2017 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.enginetips import android.app.AlertDialog import android.content.Context import android.preference.Preference import android.util.AttributeSet import com.doctoror.particleswallpaper.R import com.doctoror.particleswallpaper.framework.di.inject import org.koin.core.parameter.parametersOf class EngineTipsPreference @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : Preference(context, attrs), EngineTipsPreferenceView { private val presenter: EngineTipsPreferencePresenter by inject( context = context, parameters = { parametersOf(this as EngineTipsPreferenceView) } ) init { isPersistent = false } override fun onClick() { presenter.onClick() } override fun showDialog() { AlertDialog .Builder(context) .setTitle(title) .setMessage(R.string.engine_tips) .setPositiveButton(R.string.Close, null) .show() } }
apache-2.0
1bc0ac1c536039325638021af7c4c0d8
30.301887
75
0.713683
4.532787
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/widget/StateImageViewTarget.kt
2
1373
package eu.kanade.tachiyomi.widget import android.graphics.drawable.Drawable import android.view.View import android.widget.ImageView import androidx.core.view.isVisible import coil.drawable.CrossfadeDrawable import coil.target.ImageViewTarget /** * A Coil target to display an image with an optional view to show while loading. * * @param target the view where the image will be loaded * @param progress the view to show when the image is loading. * @param crossfadeDuration duration in millisecond to crossfade the result drawable */ class StateImageViewTarget( private val target: ImageView, private val progress: View, private val crossfadeDuration: Int = 0 ) : ImageViewTarget(target) { override fun onStart(placeholder: Drawable?) { progress.isVisible = true } override fun onSuccess(result: Drawable) { progress.isVisible = false if (crossfadeDuration > 0) { val crossfadeResult = CrossfadeDrawable(target.drawable, result, durationMillis = crossfadeDuration) target.setImageDrawable(crossfadeResult) crossfadeResult.start() } else { target.setImageDrawable(result) } } override fun onError(error: Drawable?) { progress.isVisible = false if (error != null) { target.setImageDrawable(error) } } }
apache-2.0
dc72b844b85fd67e9192691d9dd1e576
30.930233
112
0.699927
4.750865
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/AnilistInterceptor.kt
3
1732
package eu.kanade.tachiyomi.data.track.anilist import okhttp3.Interceptor import okhttp3.Response import java.io.IOException class AnilistInterceptor(val anilist: Anilist, private var token: String?) : Interceptor { /** * OAuth object used for authenticated requests. * * Anilist returns the date without milliseconds. We fix that and make the token expire 1 minute * before its original expiration date. */ private var oauth: OAuth? = null set(value) { field = value?.copy(expires = value.expires * 1000 - 60 * 1000) } override fun intercept(chain: Interceptor.Chain): Response { val originalRequest = chain.request() if (token.isNullOrEmpty()) { throw Exception("Not authenticated with Anilist") } if (oauth == null) { oauth = anilist.loadOAuth() } // Refresh access token if null or expired. if (oauth!!.isExpired()) { anilist.logout() throw IOException("Token expired") } // Throw on null auth. if (oauth == null) { throw IOException("No authentication token") } // Add the authorization header to the original request. val authRequest = originalRequest.newBuilder() .addHeader("Authorization", "Bearer ${oauth!!.access_token}") .build() return chain.proceed(authRequest) } /** * Called when the user authenticates with Anilist for the first time. Sets the refresh token * and the oauth object. */ fun setAuth(oauth: OAuth?) { token = oauth?.access_token this.oauth = oauth anilist.saveOAuth(oauth) } }
apache-2.0
a41a431c349ba64f1b696d84b684b6b7
29.385965
100
0.610277
4.758242
false
false
false
false
Novatec-Consulting-GmbH/testit-testutils
logrecorder/logrecorder-assertions/src/main/kotlin/info/novatec/testit/logrecorder/assertion/blocks/ContainsInOrder.kt
1
2879
/* * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package info.novatec.testit.logrecorder.assertion.blocks import info.novatec.testit.logrecorder.api.LogEntry import info.novatec.testit.logrecorder.assertion.LogRecordAssertion /** * Custom assertion block for the [LogRecordAssertion] DSL. * * This assertion block requires each specified expected message to be found in order, * but allows other messages between those expectations. * * **Example:** * ``` * assertThat(log) { * containsInOrder { * info("hello world") * // there might be other between these two * debug(startsWith("foo") * } * } * ``` * * @since 1.3.0 */ internal class ContainsInOrder : AbstractMessagesAssertionBlock() { override fun check(entries: List<LogEntry>, expectations: List<ExpectedLogEntry>): List<MatchingResult> { var indexOfLastMatch = -1 return expectations .map { expectation -> var result: ContainsInOrderMatchingResult? = null entries.forEachIndexed { i, entry -> if (i > indexOfLastMatch && result == null) { if (matches(expectation, entry)) { result = ContainsInOrderMatchingResult(entry, expectation) indexOfLastMatch = i } } } result ?: ContainsInOrderMatchingResult(null, expectation) } } private fun matches(expected: ExpectedLogEntry, actual: LogEntry): Boolean { val levelMatches = expected.logLevelMatcher.matches(actual.level) val messageMatches = expected.messageMatchers.all { it.matches(actual.message) } return levelMatches && messageMatches } private class ContainsInOrderMatchingResult( private val actual: LogEntry?, private val expected: ExpectedLogEntry ) : MatchingResult { override val matches: Boolean get() = actual != null override fun describe() = if (actual != null) { """[${'\u2713'}] ${actual.level} | ${actual.message}""" } else { """[${'\u2717'}] did not find entry matching: ${expected.logLevelMatcher} | ${expected.messageMatchers}""" } } }
apache-2.0
8ce2865260b70cecb18f4f15640ba433
34.54321
118
0.634248
4.735197
false
false
false
false
ClearVolume/scenery
src/test/kotlin/graphics/scenery/tests/examples/cluster/ProteinComparisonExample.kt
1
5410
package graphics.scenery.tests.examples.cluster import graphics.scenery.* import graphics.scenery.backends.Renderer import graphics.scenery.controls.GamepadButton import graphics.scenery.controls.InputHandler import graphics.scenery.controls.TrackedStereoGlasses import graphics.scenery.controls.behaviours.GamepadRotationControl import graphics.scenery.controls.behaviours.GamepadClickBehaviour import graphics.scenery.controls.behaviours.GamepadMovementControl import graphics.scenery.controls.behaviours.withCooldown import graphics.scenery.proteins.Protein import graphics.scenery.proteins.RibbonDiagram import net.java.games.input.Component import org.joml.Vector3f import kotlin.time.Duration import kotlin.time.ExperimentalTime import kotlin.time.milliseconds /** * Example for visually comparing two proteins. A gamepad can be used for navigation, * protein selection, and rotation. * * @author Ulrik Günther <[email protected]> */ class ProteinComparisonExample: SceneryBase("Protein Comparison Example") { var hmd: TrackedStereoGlasses? = null lateinit var activeProtein: Mesh var cam = DetachedHeadCamera() override fun init() { hmd = TrackedStereoGlasses("[email protected]", screenConfig = "CAVEExample.yml") hub.add(SceneryElement.HMDInput, hmd!!) renderer = Renderer.createRenderer(hub, applicationName, scene, 1280, 720) hub.add(SceneryElement.Renderer, renderer!!) cam = DetachedHeadCamera(hmd) with(cam) { position = Vector3f(0.0f, 0.0f, 2.0f) perspectiveCamera(50.0f, windowWidth, windowHeight, 0.02f, 500.0f) scene.addChild(this) } // box setup val shell = Box.hulledBox(Vector3f(10.0f)) shell.material().diffuse = Vector3f(1.0f) scene.addChild(shell) // lighting setup val lights = Light.createLightTetrahedron<PointLight>(spread = 5.0f, radius = 10.0f) lights.forEach { scene.addChild(it) } val protein1 = RibbonDiagram(Protein.fromID("2zzm")) protein1.name = protein1.protein.structure.name.toLowerCase() protein1.spatial { scale = Vector3f(0.04f) position = Vector3f(2.0f, 0.0f, 0.0f) } scene.addChild(protein1) val grid1 = BoundingGrid() grid1.node = protein1 grid1.gridColor = Vector3f(1.0f, 0.0f, 0.0f) val protein2 = RibbonDiagram(Protein.fromID("4yvj")) protein2.name = protein2.protein.structure.name.toLowerCase() protein2.spatial { scale = Vector3f(0.04f) position = Vector3f(-2.0f, 0.0f, 1.5f) } scene.addChild(protein2) val grid2 = BoundingGrid() grid2.node = protein2 scene.publishSubscribe(hub) activeProtein = protein1 } /** * Standard input setup, plus additional key bindings to * switch scenes. */ @OptIn(ExperimentalTime::class) override fun inputSetup() { val inputHandler = (hub.get(SceneryElement.Input) as? InputHandler) ?: return val toggleProteins = object : GamepadClickBehaviour { override fun click(p0: Int, p1: Int) { withCooldown(Duration.milliseconds(200)) { // finds the currently active protein, un-highlights it activeProtein.children.forEach { if (it is BoundingGrid) { it.gridColor = Vector3f(0.0f, 0.0f, 0.0f) } } // selects the new active protein activeProtein = if (activeProtein.name == "2zzm") { scene.find("4yvj") as Mesh } else { scene.find("2zzm") as Mesh } // highlights the newly active protein activeProtein.children.forEach { if (it is BoundingGrid) { it.gridColor = Vector3f(1.0f, 0.0f, 0.0f) } } } } } // toggles the active protein by pressing 1 on the keyboard, or the B key // on the gamepad. inputHandler += (toggleProteins called "toggle_proteins" boundTo GamepadButton.Button1) // removes the default second-stick camera look-around for the gamepad inputHandler -= "gamepad_camera_control" // adds a new behaviour for rotating the [activeProtein], RX and RY are the rotation // axis on the Xbox Wireless controller. For other controllers, different axis may // have to be used. Gamepad movement and rotation behaviours are always active, // hence the [GamepadButton.AlwaysActive] key binding. inputHandler += (GamepadRotationControl(listOf(Component.Identifier.Axis.RY, Component.Identifier.Axis.RX), 1.0f) { activeProtein } called "protein_rotation" boundTo GamepadButton.AlwaysActive) inputHandler += (GamepadMovementControl(listOf(Component.Identifier.Axis.Z)) { cam } called "vertical_movement" boundTo GamepadButton.AlwaysActive) } companion object { @JvmStatic fun main(args: Array<String>) { ProteinComparisonExample().main() } } }
lgpl-3.0
f3758925d6c93e956a27aa67dabd0dbf
35.795918
139
0.625439
4.358582
false
false
false
false
JonathanxD/CodeAPI
src/main/kotlin/com/github/jonathanxd/kores/util/conversion/TypeStructure.kt
1
27880
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.jonathanxd.kores.util.conversion import com.github.jonathanxd.kores.MutableInstructions import com.github.jonathanxd.kores.base.* import com.github.jonathanxd.kores.base.comment.Comments import com.github.jonathanxd.kores.base.Retention import com.github.jonathanxd.kores.factory.parameter import com.github.jonathanxd.kores.type.* import com.github.jonathanxd.kores.util.genericSignature import com.github.jonathanxd.iutils.`object`.Try import com.github.jonathanxd.iutils.array.ArrayUtils import com.github.jonathanxd.iutils.function.checked.supplier.CSupplier import com.github.jonathanxd.iutils.map.ListHashMap import java.lang.reflect.* import java.lang.reflect.Modifier import javax.lang.model.AnnotatedConstruct import javax.lang.model.element.* import javax.lang.model.type.ArrayType import javax.lang.model.type.TypeKind import javax.lang.model.type.TypeMirror import javax.lang.model.util.Elements val Class<*>.typeDeclaration: TypeDeclaration get() { val innerTypes = this.declaredClasses.filter { it.enclosingMethod == null && it.enclosingConstructor == null } val builder: TypeDeclaration.Builder<TypeDeclaration, *> = when { this.isInterface -> InterfaceDeclaration.Builder.builder() .implementations(this.genericInterfaces.toList()) this.isAnnotation -> AnnotationDeclaration.Builder.builder() .properties(this.declaredMethods.map { AnnotationProperty( Comments.Absent, it.koresAnnotations, it.returnType.koresType, it.name, it.defaultValue ) }) this.isEnum -> { val abstractMethods = this.methods.filter { Modifier.isAbstract(it.modifiers) } val enumEntries = this.declaredFields .filter { it.isEnumConstant } .map { val either = Try.Try(CSupplier { it.get(null) }) val value = if (either.isRight) either.right else null val type: Class<*>? = if (value is Enum<*>) value::class.java else null if (type != null && !type.`is`(this)) { val decl = type.typeDeclaration val spec: TypeSpec? = (decl as? ConstructorsHolder)?.constructors?.singleOrNull()?.let { if (it.parameters.size > 2) TypeSpec( it.returnType, it.parameters.subList( 2, it.parameters.size ).map { it.type }) else null } EnumEntry.Builder.builder() .annotations(it.koresAnnotations) .name(it.name) .constructorSpec(spec) .fields(decl.fields.toList()) .methods(decl.methods.toList()) .innerTypes(decl.innerTypes.toList()) .build() } else { EnumEntry.Builder.builder().annotations(it.koresAnnotations) .name(it.name).let { if (abstractMethods.isNotEmpty()) it.methods(abstractMethods.map { val names = it.parameterNames MethodDeclaration.Builder.builder() .modifiers(KoresModifier.fromJavaModifiers(it.modifiers)) .name(it.name) .returnType(it.genericReturnType.koresType) .throwsClause(it.genericExceptionTypes.map { it.koresType }) .parameters(it.parameters.let { it.mapIndexed { i, parameter -> parameter.toKoresParameter(names[i]) } }) .body(MutableInstructions.create()) .build() }) else it }.build() } } EnumDeclaration.Builder.builder() .implementations(this.genericInterfaces.map { it.koresType }) .entries(enumEntries) .constructors(this.constructorDeclarations) } else -> ClassDeclaration.Builder.builder() .superClass(this.genericSuperclass) .implementations(this.genericInterfaces.toList()) .constructors(this.constructorDeclarations) } val typeRef = this.asTypeRef // Commons return builder .outerType(typeRef.outerType) .genericSignature(this.genericSignature) .annotations(this.koresAnnotations) .modifiers(KoresModifier.fromJavaModifiers(this.modifiers)) .specifiedName(typeRef.specifiedName) .fields(this.fieldDeclarations) .methods(this.methodDeclarations) .innerTypes(innerTypes.map { it.typeDeclaration }) .build() } val Class<*>.asTypeRef: TypeRef get() = if (this.enclosingClass == null) TypeRef(null, this.concreteType.canonicalName, this.isInterface) else TypeRef(this.enclosingClass.asTypeRef, this.concreteType.simpleName, this.isInterface) val Class<*>.fieldDeclarations: List<FieldDeclaration> get() = this.declaredFields.map { FieldDeclaration.Builder.builder() .annotations(it.koresAnnotations) .modifiers(KoresModifier.fromJavaModifiers(it.modifiers)) .type(it.type.koresType) .name(it.name) .build() } val Class<*>.methodDeclarations: List<MethodDeclaration> get() { val classesDeclaredByMethods = ListHashMap<Method, Class<*>>() this.declaredClasses.forEach { cl -> cl.enclosingMethod?.let { classesDeclaredByMethods.putToList(it, cl) } } return this.declaredMethods.map { val names = it.parameterNames MethodDeclaration.Builder.builder() .annotations(it.koresAnnotations) .modifiers(KoresModifier.fromJavaModifiers(it.modifiers)) .genericSignature(it.genericSignature) .name(it.name) .returnType(it.genericReturnType.koresType) .parameters(it.parameters.mapIndexed { i, parameter -> parameter.toKoresParameter(names[i]) }) .throwsClause(it.genericExceptionTypes.map { it.koresType }) .innerTypes(classesDeclaredByMethods[it].orEmpty().map { it.typeDeclaration }) .body(MutableInstructions.create()) .build() } } val Class<*>.constructorDeclarations: List<ConstructorDeclaration> get() { val classesDeclaredByConstructors = ListHashMap<Constructor<*>, Class<*>>() this.declaredClasses.forEach { cl -> cl.enclosingConstructor?.let { classesDeclaredByConstructors.putToList(it, cl) } } return this.declaredConstructors.map { val names = it.parameterNames ConstructorDeclaration.Builder.builder() .annotations(it.koresAnnotations) .modifiers(KoresModifier.fromJavaModifiers(it.modifiers)) .genericSignature(it.genericSignature) .parameters(it.parameters.mapIndexed { i, parameter -> parameter.toKoresParameter(names[i]) }) .throwsClause(it.genericExceptionTypes.map { it.koresType }) .innerTypes(classesDeclaredByConstructors[it].orEmpty().map { it.typeDeclaration }) .body(MutableInstructions.create()) .build() } } fun Parameter.toKoresParameter(alternativeName: String? = null) = KoresParameter.Builder.builder() .annotations(this.annotations.koresAnnotation) .modifiers(KoresModifier.fromJavaModifiers(this.modifiers)) .type(this.parameterizedType) .name(alternativeName ?: this.name) .build() val <T : Annotation> Array<T>.koresAnnotation: List<KoresAnnotation> get() = this.map { it.koresAnnotation } val <T : Annotation> List<T>.koresAnnotation: List<KoresAnnotation> get() = this.map { it.koresAnnotation } val AnnotatedElement.koresAnnotations: List<KoresAnnotation> get() = this.annotations.map { it.koresAnnotation } val <T : Annotation> T.koresAnnotation: KoresAnnotation get() { val type = this.annotationClass.java val retention = type.getAnnotation(java.lang.annotation.Retention::class.java) val map = mutableMapOf<String, Any>() type.declaredMethods .filter { Modifier.isPublic(it.modifiers) && it.parameterCount == 0 } .map { map[it.name] = it.invoke(this).annotationValue(it.returnType) } return com.github.jonathanxd.kores.base.Annotation.Builder.builder() .type(type) .retention(retention?.let { Retention.fromPolicy(it.value) } ?: Retention.CLASS) .values(map) .build() } fun Any.annotationValue(rType: Class<*>): Any = when (this) { is Boolean, is Byte, is Char, is Short, is Int, is Float, is Long, is Double, is String -> this is Class<*> -> this.koresType // Not required is Enum<*> -> EnumValue(rType, this.name) is Annotation -> this.koresAnnotation else -> { if (this::class.java.isArray) { val arr = ArrayUtils.toObjectArray(this) val array = this::class.java val componentType = array.componentType arr.map { it.annotationValue(componentType) } } else throw IllegalArgumentException("Cannot convert $this to annotation value.") } } fun TypeElement.getTypeDeclaration(elements: Elements): TypeDeclaration { val innerTypes = this.enclosedElements.filterIsInstance<TypeElement>() val builder: TypeDeclaration.Builder<TypeDeclaration, *> = when { this.kind == ElementKind.INTERFACE -> InterfaceDeclaration.Builder.builder() .implementations(this.interfaces.filterNotNone().map { it.getKoresType(elements) }) this.kind == ElementKind.ANNOTATION_TYPE -> AnnotationDeclaration.Builder.builder() .properties(this.enclosedElements.filterIsInstance<ExecutableElement>().map { val rType = it.returnType.getKoresType(elements) AnnotationProperty( Comments.Absent, it.getKoresAnnotations(elements), rType, it.simpleName.toString(), it.defaultValue.annotationValue(it, it.returnType, elements) ) }) this.kind == ElementKind.ENUM -> { val abstractMethods = this.enclosedElements.filterIsInstance<ExecutableElement>().filter { it.modifiers.contains(javax.lang.model.element.Modifier.ABSTRACT) } val enumEntries = this.enclosedElements .filter { it is VariableElement && it.kind == ElementKind.ENUM_CONSTANT } .map { val enclosed = it.enclosedElements if (enclosed.isNotEmpty()) { val fields = enclosed.filterIsInstance<VariableElement>() .filter { it.kind == ElementKind.FIELD } .map { it.getFieldDeclaration(elements) } val methods = enclosed.filterIsInstance<ExecutableElement>() .filter { it.kind == ElementKind.METHOD } .map { it.getMethodDeclaration(elements) } val inner = enclosed.filterIsInstance<TypeElement>() .map { it.getTypeDeclaration(elements) } EnumEntry.Builder.builder() .annotations(it.getKoresAnnotations(elements)) .name(it.simpleName.toString()) .fields(fields) .methods(methods) .innerTypes(inner) .build() } else { EnumEntry.Builder.builder().annotations(it.getKoresAnnotations(elements)) .name(it.simpleName.toString()).let { if (abstractMethods.isNotEmpty()) it.methods(abstractMethods.map { MethodDeclaration.Builder.builder() .modifiers(KoresModifier.fromJavaxModifiers(it.modifiers)) .name(it.simpleName.toString()) .returnType(it.returnType.getKoresType(elements)) .parameters(it.parameters.map { parameter( type = it.asType().getKoresType(elements), name = it.simpleName.toString() ) }) .body(MutableInstructions.create()) .build() }) else it }.build() } } EnumDeclaration.Builder.builder() .implementations(this.interfaces.filterNotNone().map { it.getKoresType(elements) }) .entries(enumEntries) .constructors(this.getConstructorDeclarations(elements)) } else -> ClassDeclaration.Builder.builder() .also { if (this.superclass.kind != TypeKind.NONE) it.superClass(this.superclass.getKoresType(elements)) } .implementations(this.interfaces.filterNotNone().map { it.getKoresType(elements) }) .constructors(this.getConstructorDeclarations(elements)) } val asTypeRef = this.asTypeRef(elements) // Commons return builder .outerType(asTypeRef.outerType) .annotations(this.getKoresAnnotations(elements)) .modifiers(KoresModifier.fromJavaxModifiers(this.modifiers)) .genericSignature(this.getGenericSignature(false, elements)) .specifiedName(asTypeRef.specifiedName) .fields(this.getFieldDeclarations(elements)) .methods(this.getMethodDeclarations(elements)) .innerTypes(innerTypes.map { it.getTypeDeclaration(elements) }) .build() } private fun List<TypeMirror>.filterNotNone() = this.filter { it.kind != TypeKind.NONE } fun TypeElement.asTypeRef(elements: Elements): TypeRef = if (this.enclosingElement.kind == ElementKind.PACKAGE) TypeRef( null, this.getKoresType(elements).concreteType.canonicalName, this.kind == ElementKind.INTERFACE ) else { val enclosingType = this.getEnclosingType() TypeRef( enclosingType.asTypeRef(elements), this.getKoresType(elements).concreteType.simpleName, this.kind == ElementKind.INTERFACE ) } tailrec fun Element.getEnclosingType(): TypeElement = when { this.enclosingElement is TypeElement -> this.enclosingElement as TypeElement this.enclosingElement.kind == ElementKind.PACKAGE -> throw IllegalArgumentException("Package found before enclosing type") else -> this.enclosingElement.getEnclosingType() } fun VariableElement.getFieldDeclaration(elements: Elements): FieldDeclaration = FieldDeclaration.Builder.builder() .annotations(this.getKoresAnnotations(elements)) .modifiers(KoresModifier.fromJavaxModifiers(this.modifiers)) .type(this.asType().getKoresType(elements)) .name(this.simpleName.toString()) .build() fun TypeElement.getFieldDeclarations(elements: Elements): List<FieldDeclaration> = this.enclosedElements.filterIsInstance<VariableElement>() .filter { it.kind == ElementKind.FIELD } .map { it.getFieldDeclaration(elements) } fun ExecutableElement.getMethodDeclaration(elements: Elements): MethodDeclaration = MethodDeclaration.Builder.builder() .annotations(this.getKoresAnnotations(elements)) .modifiers(KoresModifier.fromJavaxModifiers(this.modifiers)) .name(this.simpleName.toString()) .returnType(this.returnType.getKoresType(elements)) .genericSignature(this.getGenericSignature(false, elements)) .parameters(this.parameters.map { parameter(type = it.asType().getKoresType(elements), name = it.simpleName.toString()) }) .throwsClause(this.thrownTypes.filterNotNone().map { it.getKoresType(elements) }) .innerTypes(this.enclosedElements.filterIsInstance<TypeElement>().map { it.getTypeDeclaration( elements ) }) .body(MutableInstructions.create()) .build() fun TypeElement.getMethodDeclarations(elements: Elements): List<MethodDeclaration> = this.enclosedElements .filterIsInstance<ExecutableElement>() .filter { it.kind == ElementKind.METHOD } .map { it.getMethodDeclaration(elements) } fun ExecutableElement.getConstructorDeclaration(elements: Elements): ConstructorDeclaration = ConstructorDeclaration.Builder.builder() .annotations(this.getKoresAnnotations(elements)) .modifiers(KoresModifier.fromJavaxModifiers(this.modifiers)) .parameters(this.parameters.map { parameter(type = it.asType().getKoresType(elements), name = it.simpleName.toString()) }) .throwsClause(this.thrownTypes.filterNotNone().map { it.getKoresType(elements) }) .innerTypes(this.enclosedElements.filterIsInstance<TypeElement>().map { it.getTypeDeclaration( elements ) }) .build() fun TypeElement.getConstructorDeclarations(elements: Elements): List<ConstructorDeclaration> = this.enclosedElements .filterIsInstance<ExecutableElement>() .filter { it.kind == ElementKind.CONSTRUCTOR } .map { it.getConstructorDeclaration(elements) } fun List<AnnotationMirror>.annotationMirrorsToKoresAnnotations(elements: Elements): List<KoresAnnotation> = this.map { it.toKoresAnnotation(elements) } fun AnnotatedConstruct.getKoresAnnotations(elements: Elements): List<KoresAnnotation> = this.annotationMirrors.map { it.toKoresAnnotation(elements) } fun AnnotationMirror.toKoresAnnotation(elements: Elements): KoresAnnotation { val type = this.annotationType.toKoresType(false, elements) val element = this.annotationType.asElement() as TypeElement val retention = element.annotationMirrors .map { it.getRetentionName(elements)?.let { enumValueOf<com.github.jonathanxd.kores.base.Retention>(it) } } .filterNotNull() .firstOrNull() ?: Retention.CLASS require(element.kind == ElementKind.ANNOTATION_TYPE) val map = mutableMapOf<String, Any>() element.enclosedElements.forEach { if (it is ExecutableElement) { val name = it.simpleName.toString() val annotationValue = this.elementValues[it] ?: it.defaultValue map[name] = annotationValue.annotationValue(it, it.returnType, elements) } } return com.github.jonathanxd.kores.base.Annotation.Builder.builder() .type(type) .retention(retention) .values(map) .build() } fun AnnotationMirror.getRetentionName(elements: Elements): String? { val type = this.annotationType.getKoresType(elements) if (type.`is`(java.lang.annotation.Retention::class.java.koresType)) { this.elementValues.entries.forEach { (e, v) -> if (e.simpleName.contentEquals("value") && v != null) { (v.value as? VariableElement)?.let { return it.simpleName.toString() } } } } return null } fun AnnotationValue.annotationValue( executableElement: ExecutableElement, rType: TypeMirror, elements: Elements ): Any { val value = this.value ?: executableElement.defaultValue if (value is AnnotationMirror) { return value.toKoresAnnotation(elements) } if (value is TypeMirror) return value.toKoresType(false, elements) if (value is VariableElement) return EnumValue( enumType = value.asType().toKoresType(false, elements), enumEntry = value.simpleName.toString() ) if (value is List<*>) { // Tries to convert to an reified array @Suppress("UNCHECKED_CAST") value as List<AnnotationValue> rType as ArrayType val component = rType.componentType return value.map { it.annotationValue(executableElement, component, elements) } } return value } fun TypeDeclaration.toRepresentation(): TypeDeclaration { val builder: TypeDeclaration.Builder<TypeDeclaration, *> = when { this.isInterface -> InterfaceDeclaration.Builder.builder() .implementations(this.interfaces.toList()) this is AnnotationDeclaration -> AnnotationDeclaration.Builder.builder() .properties(this.properties.map { AnnotationProperty( Comments.Absent, it.annotations.map { it.toRepresentation() }, it.returnType.koresType, it.name, it.defaultValue ) }) this is EnumDeclaration -> { EnumDeclaration.Builder.builder() .implementations(this.interfaces.map { it.koresType }) .entries(this.entries.map { it.toRepresentation() }) .constructors(this.constructors.map { it.toRepresentation() }) } this is ClassDeclaration -> ClassDeclaration.Builder.builder() .superClass(this.superType) .implementations(this.interfaces.toList()) .constructors(this.constructors.map { it.toRepresentation() }) else -> ClassDeclaration.Builder.builder() .superClass(this.superType) .implementations(this.interfaces.toList()) } // Commons return builder .outerType(this.outerType) .annotations(this.annotations.map { it.toRepresentation() }) .genericSignature(this.genericSignature) .modifiers(this.modifiers.toSet()) .specifiedName(this.specifiedName) .fields(this.fields.map { it.toRepresentation() }) .methods(this.methods.map { it.toRepresentation() }) .innerTypes(innerTypes.map { it.toRepresentation() }) .build() } fun KoresAnnotation.toRepresentation(): KoresAnnotation = com.github.jonathanxd.kores.base.Annotation.Builder.builder() .type(this.type.koresType) .retention(this.retention) .values(this.values.toMap()) .build() fun EnumEntry.toRepresentation(): EnumEntry = EnumEntry.Builder.builder() .annotations(this.annotations.map { it.toRepresentation() }) .methods(this.methods.map { it.toRepresentation() }) .innerTypes(this.innerTypes.map { it.toRepresentation() }) .fields(this.fields.map { it.toRepresentation() }) .build() fun FieldDeclaration.toRepresentation(): FieldDeclaration = FieldDeclaration.Builder.builder() .annotations(this.annotations.map { it.toRepresentation() }) .modifiers(this.modifiers.toSet()) .type(this.type.koresType) .name(this.name) .innerTypes(this.innerTypes.map { it.toRepresentation() }) .build() fun ConstructorDeclaration.toRepresentation(): ConstructorDeclaration = ConstructorDeclaration.Builder.builder() .annotations(this.annotations.map { it.toRepresentation() }) .modifiers(this.modifiers.toSet()) .parameters(this.parameters.map { it.toRepresentation() }) .innerTypes(this.innerTypes.map { it.toRepresentation() }) .throwsClause(this.throwsClause.map { it.koresType }) .build() fun MethodDeclaration.toRepresentation(): MethodDeclaration = MethodDeclaration.Builder.builder() .annotations(this.annotations.map { it.toRepresentation() }) .genericSignature(this.genericSignature) .modifiers(this.modifiers.toSet()) .returnType(this.returnType.koresType) .name(this.name) .parameters(this.parameters.map { it.toRepresentation() }) .innerTypes(this.innerTypes.map { it.toRepresentation() }) .throwsClause(this.throwsClause.map { it.koresType }) .build() fun KoresParameter.toRepresentation(): KoresParameter = KoresParameter.Builder.builder() .annotations(this.annotations.map { it.toRepresentation() }) .modifiers(this.modifiers.toSet()) .type(this.type.koresType) .name(this.name) .build()
mit
c71c4cfb71b72c1603d2c90e44e92933
40.7991
130
0.591607
5.169664
false
false
false
false
spotify/heroic
heroic-component/src/main/java/com/spotify/heroic/grammar/IntegerExpression.kt
1
2898
/* * Copyright (c) 2019 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.spotify.heroic.grammar import java.util.concurrent.TimeUnit /** * int's are represented internally as longs. * * @author udoprog */ data class IntegerExpression(@JvmField val context: Context, val value: Long): Expression { override fun getContext() = context fun getValueAsInteger(): Int { if (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE) { throw context.error("cannot be converted to integer") } return value.toInt() } override fun <R : Any?> visit(visitor: Expression.Visitor<R>): R { return visitor.visitInteger(this) } override fun multiply(other: Expression): IntegerExpression = IntegerExpression(context.join(other.context), value * other.cast(IntegerExpression::class.java).value) override fun divide(other: Expression): IntegerExpression = IntegerExpression(context.join(other.context), value / other.cast(IntegerExpression::class.java).value) override fun sub(other: Expression): IntegerExpression = IntegerExpression(context.join(other.context), value - other.cast(IntegerExpression::class.java).value) override fun add(other: Expression): IntegerExpression = IntegerExpression(context.join(other.context), value + other.cast(IntegerExpression::class.java).value) override fun negate(): IntegerExpression = IntegerExpression(context, -value) @Suppress("UNCHECKED_CAST") override fun <T : Expression?> cast(to: Class<T>): T { if (to.isAssignableFrom(IntegerExpression::class.java)) { return this as T } if (to.isAssignableFrom(DoubleExpression::class.java)) { return DoubleExpression(context, value.toDouble()) as T } if (to.isAssignableFrom(DurationExpression::class.java)) { return DurationExpression(context, TimeUnit.MILLISECONDS, value) as T } throw context.castError(this, to) } override fun toRepr() = value.toString() }
apache-2.0
d14e15b71033db042753d1d29fa2f82d
34.353659
91
0.691166
4.486068
false
false
false
false
sreich/ore-infinium
core/src/com/ore/infinium/LoadedViewport.kt
1
3421
/** MIT License Copyright (c) 2016 Shaun Reich <[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 com.ore.infinium import com.badlogic.gdx.math.Rectangle import com.badlogic.gdx.math.Vector2 import com.ore.infinium.util.isNegative /** * Entities and tiles within this region should be assumed loaded (within reason) */ class LoadedViewport() { //x, y, top left. in # of blocks (index units) var rect: Rectangle = Rectangle() /** * @param pos * * center point */ fun centerOn(pos: Vector2, world: OreWorld) { val halfWidth = (MAX_VIEWPORT_WIDTH / 2).toFloat() val halfHeight = (MAX_VIEWPORT_HEIGHT / 2).toFloat() rect.x = (pos.x - halfWidth).coerceIn(0f, world.worldSize.width - 1f) rect.y = (pos.y - halfHeight).coerceIn(0f, world.worldSize.height - 1f) rect.width = (pos.x + halfWidth).coerceIn(0f, world.worldSize.width - 1f) rect.height = (pos.y + halfHeight).coerceIn(0f, world.worldSize.height - 1f) assert(!rect.height.isNegative() && !rect.width.isNegative() && !rect.x.isNegative() && !rect.y.isNegative()) { "viewport is either negative (unlikely) or nan" } } operator fun contains(pos: Vector2): Boolean { return rect.contains(pos) } class PlayerViewportBlockRegion internal constructor(var x: Int, var y: Int, var width: Int, var height: Int) /** * Starting from x to (including) rect.width, blocks. Same for y. * @return a rectangle with x, y, width(x2), height(y2), inclusive, * * where these are the blocks the viewport has within its view/range */ fun blockRegionInViewport(): PlayerViewportBlockRegion { return PlayerViewportBlockRegion(rect.x.toInt(), rect.y.toInt(), rect.width.toInt(), rect.height.toInt()) } companion object { //the amount of tiles able to be seen by any client //(aka we sync only things like blocks, entities, within this region) val MAX_VIEWPORT_WIDTH = 120//65; val MAX_VIEWPORT_HEIGHT = 100//55; /** * the distance (amount of blocks, block index units) to the closest edge * that the player should probably be, when we decide to send another chunk * @param of * * * @param units * * * @return */ val reloadDistance = 30f } }
mit
70d5d2065167c8c02b3676a11be3e4d0
35.784946
113
0.67641
4.101918
false
false
false
false
PlanBase/PdfLayoutMgr2
src/main/java/com/planbase/pdf/lm2/attributes/BorderStyle.kt
1
4839
// Copyright 2013-03-03 PlanBase Inc. // // This file is part of PdfLayoutMgr2 // // PdfLayoutMgr is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // PdfLayoutMgr 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with PdfLayoutMgr. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>. // // If you wish to use this code with proprietary software, // contact PlanBase Inc. <https://planbase.com> to purchase a commercial license. package com.planbase.pdf.lm2.attributes import com.planbase.pdf.lm2.utils.LineJoinStyle import com.planbase.pdf.lm2.utils.LineJoinStyle.MITER import org.apache.pdfbox.pdmodel.graphics.color.PDColor import java.lang.StringBuilder /** * Holds the LineStyles for the top, right, bottom, and left borders of a PdfItem. * This class works just like styles in CSS in terms of specifying one style, then * overwriting it with another. This example sets all borders except to black and the default width, * then removes the top border: * * BorderStyle topBorderStyle = BorderStyle(LineStyle(PDColor.BLACK)) * .top(LineStyle(PDColor.RED, 2.0)); * * If neighboring cells in a cell-row have the same border, only one will be printed. If different, * the left-border of the right cell will override. You have to manage your own top borders * manually. */ // Like CSS it's listed Top, Right, Bottom, left data class BorderStyle(val top: LineStyle = LineStyle.NO_LINE, val right: LineStyle = LineStyle.NO_LINE, val bottom: LineStyle = LineStyle.NO_LINE, val left: LineStyle = LineStyle.NO_LINE, val lineJoinStyle: LineJoinStyle = MITER) { /** Creates a BorderStyle with [MITER]ed corners */ constructor(top: LineStyle, right: LineStyle, bottom: LineStyle, left: LineStyle) : this(top, right, bottom, left, MITER) /** * Returns equal top and bottom borders and equal right and left borders and [MITER]ed corners * @param topBottom the line style for top and bottom lines * @param rightLeft the line style for right and left lines. * @return a new immutable border object */ constructor(topBottom: LineStyle, rightLeft: LineStyle) : this(topBottom, rightLeft, topBottom, rightLeft, MITER) /** * Returns an equal border on all sides with [MITER]ed corners * @param allSides the line style * @return a new immutable border object */ constructor(allSides: LineStyle) : this(allSides, allSides, allSides, allSides, MITER) // /** // * Returns an equal border on all sides // * @param c the border color // * @param w the width of the border. // * @return a new immutable border object // */ // constructor(c: PDColor, w: Double) : this (LineStyle(c, w)) /** * Returns an equal border on all sides * @param c the border color * @return a new immutable border object with default width */ constructor(c: PDColor) : this (LineStyle(c)) fun withTop(ls: LineStyle) = BorderStyle(ls, right, bottom, left, lineJoinStyle) fun withRight(ls: LineStyle) = BorderStyle(top, ls, bottom, left, lineJoinStyle) fun withBottom(ls: LineStyle) = BorderStyle(top, right, ls, left, lineJoinStyle) fun withLeft(ls: LineStyle) = BorderStyle(top, right, bottom, ls, lineJoinStyle) fun allSame(): Boolean = top == right && right == bottom && bottom == left fun hasAllBorders(): Boolean = top.thickness > 0.0 && right.thickness > 0.0 && bottom.thickness > 0.0 && left.thickness > 0.0 fun topBottomThickness(): Double = top.thickness + bottom.thickness fun leftRightThickness(): Double = left.thickness + right.thickness override fun toString(): String { if (this == NO_BORDERS) { return "NO_BORDERS" } val sB = StringBuilder("BorderStyle(") if (allSame()) { sB.append("$top") } else { sB.append("$top, $right, $bottom, $left") } if (lineJoinStyle != MITER) { sB.append(", $lineJoinStyle") } return sB.append(")").toString() } companion object { @JvmField val NO_BORDERS = BorderStyle(LineStyle.NO_LINE) } }
agpl-3.0
cf6cfa507b61e8cadace361e993a52b7
38.341463
117
0.655714
4.114796
false
false
false
false
paplorinc/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/DgmCallTypeCalculator.kt
2
2487
// 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.plugins.groovy.lang.typing import com.intellij.psi.* import com.intellij.psi.CommonClassNames.JAVA_UTIL_COLLECTION import com.intellij.psi.util.InheritanceUtil.isInheritor import com.intellij.psi.util.PsiUtil.extractIterableTypeParameter import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.CollectionUtil.createSimilarCollection import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.DEFAULT_GROOVY_METHODS import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments class DgmCallTypeCalculator : GrCallTypeCalculator { override fun getType(receiver: PsiType?, method: PsiMethod, arguments: Arguments?, context: PsiElement): PsiType? { if (arguments == null || arguments.isEmpty()) { return null } if (method.containingClass?.qualifiedName != DEFAULT_GROOVY_METHODS) { return null } val methodName = method.name if (methodName == "find") { return (arguments.first().type as? PsiArrayType)?.componentType } if (methodName !in interestingNames || !isSimilarCollectionReturner(method)) { return null } val receiverType = arguments.first().type var itemType = getItemType(receiverType) if ("flatten" == methodName && itemType != null) { while (true) { itemType = getItemType(itemType) ?: break } } return createSimilarCollection(receiverType, context.project, itemType) } companion object { private val interestingNames = setOf( "unique", "findAll", "grep", "collectMany", "split", "plus", "intersect", "leftShift" ) private fun isSimilarCollectionReturner(method: PsiMethod): Boolean { val receiverParameter = method.parameterList.parameters.firstOrNull() ?: return false val receiverParameterType = receiverParameter.type if (receiverParameterType !is PsiArrayType && !isInheritor(receiverParameterType, JAVA_UTIL_COLLECTION)) { return false } val returnType = method.returnType as? PsiClassType ?: return false return returnType.resolve()?.qualifiedName == JAVA_UTIL_COLLECTION } private fun getItemType(type: PsiType?): PsiType? { return (type as? PsiArrayType)?.componentType ?: extractIterableTypeParameter(type, true) } } }
apache-2.0
f89d375350e225a7eef28863988a5aaa
34.028169
140
0.712907
4.6141
false
false
false
false
Werb/MoreType
app/src/main/java/com/werb/moretype/complete/OnLoadMoreListener.kt
1
2068
package com.werb.moretype.complete import android.util.Log import android.view.View import androidx.recyclerview.widget.RecyclerView /** * Created by wanbo on 2017/7/15. */ abstract class OnLoadMoreListener : androidx.recyclerview.widget.RecyclerView.OnScrollListener() { private var itemCount: Int = 0 private var lastItemCount: Int = 0 var isShowFooter: Boolean = false abstract fun isHasMore(): Boolean abstract fun onLoadMore(v: View) abstract fun showFooter(v: View) fun doOnScrolled(recyclerView: androidx.recyclerview.widget.RecyclerView, dx: Int, dy: Int) { } fun doOnScrollStateChanged() { } override fun onScrollStateChanged(recyclerView: androidx.recyclerview.widget.RecyclerView, newState: Int) { if (newState == androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_DRAGGING) { doOnScrollStateChanged() } } override fun onScrolled(recyclerView: androidx.recyclerview.widget.RecyclerView, dx: Int, dy: Int) { doOnScrolled(recyclerView, dx, dy) if (dy <= 0) { return } val layoutManager: androidx.recyclerview.widget.LinearLayoutManager if (recyclerView.layoutManager is androidx.recyclerview.widget.LinearLayoutManager) { layoutManager = recyclerView.layoutManager as androidx.recyclerview.widget.LinearLayoutManager itemCount = layoutManager.itemCount } else { Log.e("OnLoadMoreListener", "The OnLoadMoreListener only support LinearLayoutManager") return } val lastVisibleItem = layoutManager.findLastVisibleItemPosition() itemCount = layoutManager.itemCount if (lastItemCount != itemCount && lastVisibleItem + 1 == itemCount && !isShowFooter) { if (isHasMore()) { recyclerView.post { showFooter(recyclerView) onLoadMore(recyclerView) } } else { lastItemCount = itemCount } } } }
apache-2.0
b46b8cf8c74e1582afd0b20401ef698c
29.880597
111
0.658124
5.222222
false
false
false
false
JetBrains/intellij-community
python/src/com/jetbrains/python/packaging/toolwindow/PyPackagingToolWindowService.kt
1
14611
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.packaging.toolwindow import com.intellij.ProjectTopics import com.intellij.execution.process.CapturingProcessHandler import com.intellij.execution.target.TargetProgressIndicator import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.options.ex.SingleConfigurableEditor import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.withBackgroundProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.childScope import com.jetbrains.python.PyBundle.* import com.jetbrains.python.PythonHelper import com.jetbrains.python.PythonHelpersLocator import com.jetbrains.python.packaging.* import com.jetbrains.python.packaging.common.PythonPackageDetails import com.jetbrains.python.packaging.common.PythonPackageSpecification import com.jetbrains.python.packaging.common.PythonPackageManagementListener import com.jetbrains.python.packaging.management.PythonPackageManager import com.jetbrains.python.packaging.management.packagesByRepository import com.jetbrains.python.packaging.repository.* import com.jetbrains.python.run.PythonInterpreterTargetEnvironmentFactory import com.jetbrains.python.run.applyHelperPackageToPythonPath import com.jetbrains.python.run.buildTargetedCommandLine import com.jetbrains.python.run.prepareHelperScriptExecution import com.jetbrains.python.sdk.PythonSdkType import com.jetbrains.python.sdk.pythonSdk import com.jetbrains.python.sdk.sdkFlavor import com.jetbrains.python.statistics.modules import kotlinx.coroutines.* import org.intellij.plugins.markdown.ui.preview.html.MarkdownUtil import org.jetbrains.annotations.Nls import kotlin.Comparator @Service class PyPackagingToolWindowService(val project: Project) : Disposable { private lateinit var toolWindowPanel: PyPackagingToolWindowPanel lateinit var manager: PythonPackageManager private var installedPackages: List<InstalledPackage> = emptyList() internal var currentSdk: Sdk? = null private var searchJob: Job? = null private var currentQuery: String = "" private val serviceScope = ApplicationManager.getApplication().coroutineScope.childScope(Dispatchers.Default) private val invalidRepositories: List<PyInvalidRepositoryViewData> get() = service<PyPackageRepositories>().invalidRepositories.map(::PyInvalidRepositoryViewData) fun initialize(toolWindowPanel: PyPackagingToolWindowPanel) { this.toolWindowPanel = toolWindowPanel serviceScope.launch(Dispatchers.IO) { service<PyPIPackageRanking>().reload() initForSdk(project.modules.firstOrNull()?.pythonSdk) } subscribeToChanges() } suspend fun detailsForPackage(selectedPackage: DisplayablePackage): PythonPackageDetails { val spec = selectedPackage.repository.createPackageSpecification(selectedPackage.name) return manager.repositoryManager.getPackageDetails(spec) } fun handleSearch(query: String) { currentQuery = query if (query.isNotEmpty()) { searchJob?.cancel() searchJob = serviceScope.launch { val installed = installedPackages.filter { StringUtil.containsIgnoreCase(it.name, query) } val packagesFromRepos = manager.repositoryManager.packagesByRepository().map { filterPackagesForRepo(it.second, query, it.first) }.toList() if (isActive) { withContext(Dispatchers.Main) { toolWindowPanel.showSearchResult(installed, packagesFromRepos + invalidRepositories) } } } } else { val packagesByRepository = manager.repositoryManager.packagesByRepository().map { (repository, packages) -> val shownPackages = packages.asSequence().limitDisplayableResult(repository) PyPackagesViewData(repository, shownPackages, moreItems = packages.size - PACKAGES_LIMIT) }.toList() toolWindowPanel.resetSearch(installedPackages, packagesByRepository + invalidRepositories) } } suspend fun installPackage(specification: PythonPackageSpecification) { val result = manager.installPackage(specification) if (result.isSuccess) showPackagingNotification(message("python.packaging.notification.installed", specification.name)) } suspend fun deletePackage(selectedPackage: InstalledPackage) { val result = manager.uninstallPackage(selectedPackage.instance) if (result.isSuccess) showPackagingNotification(message("python.packaging.notification.deleted", selectedPackage.name)) } private suspend fun initForSdk(sdk: Sdk?) { val previousSdk = currentSdk currentSdk = sdk if (currentSdk != null) { manager = PythonPackageManager.forSdk(project, currentSdk!!) manager.repositoryManager.initCaches() manager.reloadPackages() refreshInstalledPackages() withContext(Dispatchers.Main) { handleSearch("") } } withContext(Dispatchers.Main) { toolWindowPanel.contentVisible = currentSdk != null if (currentSdk == null || currentSdk != previousSdk) { toolWindowPanel.setEmpty() } } } private fun subscribeToChanges() { val connection = project.messageBus.connect(this) connection.subscribe(PythonPackageManager.PACKAGE_MANAGEMENT_TOPIC, object : PythonPackageManagementListener { override fun packagesChanged(sdk: Sdk) { if (currentSdk == sdk) serviceScope.launch(Dispatchers.IO) { refreshInstalledPackages() withContext(Dispatchers.Main) { handleSearch(currentQuery) } } } }) connection.subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) { serviceScope.launch(Dispatchers.IO) { initForSdk(project.modules.firstOrNull()?.pythonSdk) } } }) } suspend fun refreshInstalledPackages() { val packages = manager.installedPackages.map { val repository = installedPackages.find { pkg -> pkg.name == it.name }?.repository ?: PyEmptyPackagePackageRepository InstalledPackage(it, repository) } withContext(Dispatchers.Main) { installedPackages = packages } } private suspend fun showPackagingNotification(text: @Nls String) { val notification = NotificationGroupManager.getInstance() .getNotificationGroup("PythonPackages") .createNotification(text, NotificationType.INFORMATION) withContext(Dispatchers.Main) { notification.notify(project) } } private fun filterPackagesForRepo(packageNames: List<String>, query: String, repository: PyPackageRepository, skipItems: Int = 0): PyPackagesViewData { val comparator = createNameComparator(query, repository.repositoryUrl ?: "") val searchResult = packageNames.asSequence() .filter { StringUtil.containsIgnoreCase(it, query) } .toList() val shownPackages = searchResult.asSequence() .sortedWith(comparator) .limitDisplayableResult(repository, skipItems) val exactMatch = shownPackages.indexOfFirst { StringUtil.equalsIgnoreCase(it.name, query) } return PyPackagesViewData(repository, shownPackages, exactMatch, searchResult.size - shownPackages.size) } suspend fun convertToHTML(contentType: String?, description: String): String { return withContext(Dispatchers.IO) { when (contentType) { "text/markdown" -> markdownToHtml(description, currentSdk!!.homeDirectory!!, project) "text/x-rst", "" -> rstToHtml(description, currentSdk!!) else -> description } } } private suspend fun rstToHtml(text: String, sdk: Sdk): String { val localSdk = PythonSdkType.findLocalCPythonForSdk(sdk) if (localSdk == null) return wrapHtml("<p>${message("python.toolwindow.packages.documentation.local.interpreter")}</p>") val helpersAwareTargetRequest = PythonInterpreterTargetEnvironmentFactory.findPythonTargetInterpreter(localSdk, project) val targetEnvironmentRequest = helpersAwareTargetRequest.targetEnvironmentRequest val pythonExecution = prepareHelperScriptExecution(PythonHelper.REST_RUNNER, helpersAwareTargetRequest) // todo[akniazev]: this workaround should can be removed when PY-57134 is fixed val helperLocation = if (localSdk.sdkFlavor.getLanguageLevel(localSdk).isPython2) "py2only" else "py3only" val path = PythonHelpersLocator.getHelpersRoot().toPath().resolve(helperLocation) pythonExecution.applyHelperPackageToPythonPath(listOf(path.toString()), helpersAwareTargetRequest) pythonExecution.addParameter("rst2html_no_code") val targetProgressIndicator = TargetProgressIndicator.EMPTY val targetEnvironment = targetEnvironmentRequest.prepareEnvironment(targetProgressIndicator) targetEnvironment.uploadVolumes.entries.forEach { (_, value) -> value.upload(".", targetProgressIndicator) } val targetedCommandLine = pythonExecution.buildTargetedCommandLine(targetEnvironment, localSdk, emptyList()) val indicator = ProgressManager.getInstance().progressIndicator ?: EmptyProgressIndicator() val process = targetEnvironment.createProcess(targetedCommandLine, indicator) val commandLine = targetedCommandLine.collectCommandsSynchronously() val commandLineString = commandLine.joinToString(" ") val handler = CapturingProcessHandler(process, targetedCommandLine.charset, commandLineString) val output = withBackgroundProgressIndicator(project, message("python.toolwindow.packages.converting.description.progress"), cancellable = true) { val processInput = handler.processInput processInput.use { processInput.write(text.toByteArray()) } handler.runProcess(10 * 60 * 1000) } return when { output.checkSuccess(thisLogger()) -> output.stdout else -> wrapHtml("<p>${message("python.toolwindow.packages.rst.parsing.failed")}</p>") } } private fun markdownToHtml(text: String, homeDir: VirtualFile, project: Project): String { return wrapHtml(MarkdownUtil.generateMarkdownHtml(homeDir, text, project)) } override fun dispose() { searchJob?.cancel() serviceScope.cancel() } fun wrapHtml(html: String): String = "<html><head></head><body><p>$html</p></body></html>" fun reloadPackages() { serviceScope.launch(Dispatchers.IO) { withBackgroundProgressIndicator(project, message("python.packaging.loading.packages.progress.text"), cancellable = false) { manager.reloadPackages() manager.repositoryManager.refreshCashes() refreshInstalledPackages() withContext(Dispatchers.Main) { handleSearch("") } } } } fun manageRepositories() { val updated = SingleConfigurableEditor(project, PyRepositoriesList(project)).showAndGet() if (updated) { serviceScope.launch(Dispatchers.IO) { val packageService = PyPackageService.getInstance() val repositoryService = service<PyPackageRepositories>() val allRepos = repositoryService.repositories.map { it.repositoryUrl } packageService.additionalRepositories.asSequence() .filter { it !in allRepos } .forEach { packageService.removeRepository(it) } val (valid, invalid) = repositoryService.repositories.partition { it.checkValid() } repositoryService.invalidRepositories.clear() repositoryService.invalidRepositories.addAll(invalid) invalid.forEach { packageService.removeRepository(it.repositoryUrl!!) } valid.asSequence() .map { it.repositoryUrl } .filter { it !in packageService.additionalRepositories } .forEach { packageService.addRepository(it) } reloadPackages() } } } fun getMoreResultsForRepo(repository: PyPackageRepository, skipItems: Int): PyPackagesViewData { val packagesFromRepository = manager.repositoryManager.packagesFromRepository(repository) if (currentQuery.isNotEmpty()) { return filterPackagesForRepo(packagesFromRepository, currentQuery, repository, skipItems) } else { val packagesFromRepo = packagesFromRepository.asSequence().limitDisplayableResult(repository, skipItems) return PyPackagesViewData(repository, packagesFromRepo, moreItems = packagesFromRepository.size - (PACKAGES_LIMIT + skipItems)) } } private fun Sequence<String>.limitDisplayableResult(repository: PyPackageRepository, skipItems: Int = 0): List<DisplayablePackage> { return drop(skipItems) .take(PACKAGES_LIMIT) .map { pkg -> installedPackages.find { it.name.lowercase() == pkg.lowercase() } ?: InstallablePackage(pkg, repository) } .toList() } companion object { private const val PACKAGES_LIMIT = 50 private fun createNameComparator(query: String, url: String): Comparator<String> { val nameComparator = Comparator<String> { name1, name2 -> val queryLowerCase = query.lowercase() return@Comparator when { name1.startsWith(queryLowerCase) && name2.startsWith(queryLowerCase) -> name1.length - name2.length name1.startsWith(queryLowerCase) -> -1 name2.startsWith(queryLowerCase) -> 1 else -> name1.compareTo(name2) } } if (PyPIPackageUtil.isPyPIRepository(url)) { val ranking = service<PyPIPackageRanking>().packageRank return Comparator { p1, p2 -> val rank1 = ranking[p1.lowercase()] val rank2 = ranking[p2.lowercase()] return@Comparator when { rank1 != null && rank2 == null -> -1 rank1 == null && rank2 != null -> 1 rank1 != null && rank2 != null -> rank2 - rank1 else -> nameComparator.compare(p1, p2) } } } return nameComparator } } }
apache-2.0
82d0a0147ad2410cdcd4fe8c7f7c503a
40.748571
150
0.737321
4.899732
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SuspiciousCollectionReassignmentInspection.kt
1
10837
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.diagnostics.Severity import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.quickfix.ChangeToMutableCollectionFix import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtSingleValueToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.SimpleType import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor class SuspiciousCollectionReassignmentInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = binaryExpressionVisitor(fun(binaryExpression) { if (binaryExpression.right == null) return val operationToken = binaryExpression.operationToken as? KtSingleValueToken ?: return if (operationToken !in targetOperations) return val left = binaryExpression.left ?: return val property = left.mainReference?.resolve() as? KtProperty ?: return if (!property.isVar) return val context = binaryExpression.analyze() val leftType = left.getType(context) ?: return val leftDefaultType = leftType.constructor.declarationDescriptor?.defaultType ?: return if (!leftType.isReadOnlyCollectionOrMap(binaryExpression.builtIns)) return if (context.diagnostics.forElement(binaryExpression).any { it.severity == Severity.ERROR }) return val fixes = mutableListOf<LocalQuickFix>() if (ChangeTypeToMutableFix.isApplicable(property)) { fixes.add(ChangeTypeToMutableFix(leftType)) } if (ReplaceWithFilterFix.isApplicable(binaryExpression, leftDefaultType, context)) { fixes.add(ReplaceWithFilterFix()) } when { ReplaceWithAssignmentFix.isApplicable(binaryExpression, property, context) -> fixes.add(ReplaceWithAssignmentFix()) JoinWithInitializerFix.isApplicable(binaryExpression, property) -> fixes.add(JoinWithInitializerFix(operationToken)) } if (fixes.isEmpty()) return val typeText = leftDefaultType.toString().takeWhile { it != '<' }.lowercase() val operationReference = binaryExpression.operationReference holder.registerProblem( operationReference, KotlinBundle.message("0.on.a.readonly.1.creates.a.new.1.under.the.hood", operationReference.text, typeText), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, *fixes.toTypedArray() ) }) private class ChangeTypeToMutableFix(@SafeFieldForPreview private val type: KotlinType) : LocalQuickFix { override fun getName() = KotlinBundle.message("change.type.to.mutable.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return val left = binaryExpression.left ?: return val property = left.mainReference?.resolve() as? KtProperty ?: return ChangeToMutableCollectionFix.applyFix(property, type) property.valOrVarKeyword.replace(KtPsiFactory(project).createValKeyword()) binaryExpression.findExistingEditor()?.caretModel?.moveToOffset(property.endOffset) } companion object { fun isApplicable(property: KtProperty): Boolean { return ChangeToMutableCollectionFix.isApplicable(property) } } } private class ReplaceWithFilterFix : LocalQuickFix { override fun getName() = KotlinBundle.message("replace.with.filter.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return val left = binaryExpression.left ?: return val right = binaryExpression.right ?: return val psiFactory = KtPsiFactory(project) operationReference.replace(psiFactory.createOperationName(KtTokens.EQ.value)) right.replace(psiFactory.createExpressionByPattern("$0.filter { it !in $1 }", left, right)) } companion object { fun isApplicable(binaryExpression: KtBinaryExpression, leftType: SimpleType, context: BindingContext): Boolean { if (binaryExpression.operationToken != KtTokens.MINUSEQ) return false if (leftType == binaryExpression.builtIns.map.defaultType) return false return binaryExpression.right?.getType(context)?.classDescriptor()?.isSubclassOf(binaryExpression.builtIns.iterable) == true } } } private class ReplaceWithAssignmentFix : LocalQuickFix { override fun getName() = KotlinBundle.message("replace.with.assignment.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return val psiFactory = KtPsiFactory(project) operationReference.replace(psiFactory.createOperationName(KtTokens.EQ.value)) } companion object { val emptyCollectionFactoryMethods = listOf("emptyList", "emptySet", "emptyMap", "listOf", "setOf", "mapOf").map { "kotlin.collections.$it" } fun isApplicable(binaryExpression: KtBinaryExpression, property: KtProperty, context: BindingContext): Boolean { if (binaryExpression.operationToken != KtTokens.PLUSEQ) return false if (!property.isLocal) return false val initializer = property.initializer as? KtCallExpression ?: return false if (initializer.valueArguments.isNotEmpty()) return false val initializerResultingDescriptor = initializer.getResolvedCall(context)?.resultingDescriptor val fqName = initializerResultingDescriptor?.fqNameOrNull()?.asString() if (fqName !in emptyCollectionFactoryMethods) return false val rightClassDescriptor = binaryExpression.right?.getType(context)?.classDescriptor() ?: return false val initializerClassDescriptor = initializerResultingDescriptor?.returnType?.classDescriptor() ?: return false if (!rightClassDescriptor.isSubclassOf(initializerClassDescriptor)) return false if (binaryExpression.siblings(forward = false, withItself = false) .filter { it != property } .any { sibling -> sibling.anyDescendantOfType<KtSimpleNameExpression> { it.mainReference.resolve() == property } } ) return false return true } } } private class JoinWithInitializerFix(@SafeFieldForPreview private val op: KtSingleValueToken) : LocalQuickFix { override fun getName() = KotlinBundle.message("join.with.initializer.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return val left = binaryExpression.left ?: return val right = binaryExpression.right ?: return val property = left.mainReference?.resolve() as? KtProperty ?: return val initializer = property.initializer ?: return val psiFactory = KtPsiFactory(project) val newOp = if (op == KtTokens.PLUSEQ) KtTokens.PLUS else KtTokens.MINUS val replaced = initializer.replaced(psiFactory.createExpressionByPattern("$0 $1 $2", initializer, newOp.value, right)) binaryExpression.delete() property.findExistingEditor()?.caretModel?.moveToOffset(replaced.endOffset) } companion object { fun isApplicable(binaryExpression: KtBinaryExpression, property: KtProperty): Boolean { if (!property.isLocal || property.initializer == null) return false return binaryExpression.getPrevSiblingIgnoringWhitespaceAndComments() == property } } } } private val targetOperations: List<KtSingleValueToken> = listOf(KtTokens.PLUSEQ, KtTokens.MINUSEQ) private fun KotlinType.classDescriptor() = constructor.declarationDescriptor as? ClassDescriptor internal fun KotlinType.isReadOnlyCollectionOrMap(builtIns: KotlinBuiltIns): Boolean { val leftDefaultType = constructor.declarationDescriptor?.defaultType ?: return false return leftDefaultType in listOf(builtIns.list.defaultType, builtIns.set.defaultType, builtIns.map.defaultType) }
apache-2.0
74ee7f6b275b086af47a44091bc4eaad
53.19
158
0.714589
5.79209
false
false
false
false
Hexworks/snap
src/test/kotlin/org/codetome/snap/adapter/parser/MarkdownParserTest.kt
1
7257
package org.codetome.snap.adapter.parser import com.vladsch.flexmark.ast.Node import com.vladsch.flexmark.parser.Parser import com.vladsch.flexmark.parser.ParserEmulationProfile import com.vladsch.flexmark.util.options.MutableDataSet import org.assertj.core.api.Assertions import org.codetome.snap.adapter.parser.* import org.codetome.snap.model.data.Schema import org.codetome.snap.model.rest.MethodType.GET import org.codetome.snap.model.rest.MethodType.POST import org.codetome.snap.model.rest.Path import org.codetome.snap.model.rest.RequestParamType.CONSUMES import org.codetome.snap.model.rest.ResponseParamType.* import org.codetome.snap.model.rest.RestEndpoint import org.codetome.snap.model.rest.RestMethod import org.codetome.snap.model.rest.RestService import org.json.JSONObject import org.junit.Before import org.junit.Test import org.mockito.internal.util.reflection.Whitebox import java.io.File class MarkdownParserTest { lateinit var target: MarkdownParser val document: Node init { val options = MutableDataSet() options.setFrom(ParserEmulationProfile.MARKDOWN) val parser: Parser = Parser.builder(options).build() val md = File("src/test/resources/full_config.md").readText() document = parser.parse(md) } @Before fun setUp() { val segmentTypeAnalyzer = MarkdownSegmentTypeAnalyzer() val headerSegmentParser = MarkdownHeaderSegmentParser() val descriptionSegmentParser = MarkdownDescriptionSegmentParser() val listSegmentParser = MarkdownListSegmentParser() target = MarkdownParser( markdownRootSegmentParser = MarkdownRootSegmentParser( headerSegmentParser = headerSegmentParser, descriptionSegmentParser = descriptionSegmentParser, endpointSegmentParser = MarkdownEndpointSegmentParser( segmentTypeAnalyzer = segmentTypeAnalyzer, schemaSegmentParser = MarkdownSchemaSegmentParser( segmentTypeAnalyzer), headerSegmentParser = headerSegmentParser, restMethodSegmentParser = MarkdownRestMethodSegmentParser( segmentTypeAnalyzer = segmentTypeAnalyzer, headerSegmentParser = headerSegmentParser, descriptionSegmentParser = descriptionSegmentParser, listSegmentParser = listSegmentParser), descriptionSegmentParser = descriptionSegmentParser), segmentTypeAnalyzer = segmentTypeAnalyzer)) } @Test fun shouldParse() { val actual = target.parse(document).blockingGet() val expectedId = EXPECTED_REST_SERVICE.fixtures[EXPECTED_SCHEMA_NAME]!!.first().getId() val actualFixture = actual.fixtures[EXPECTED_SCHEMA_NAME]!!.first().asMap() actualFixture.put("id", expectedId) Assertions.assertThat(actual).isEqualTo(EXPECTED_REST_SERVICE) } companion object { val EXPECTED_SCHEMA_NAME = "recommendations" val EXPECTED_SCHEMA = MarkdownSchemaSegmentParserTest.EXPECTED_SCHEMA val EXPECTED_ENTITY = MarkdownSchemaSegmentParserTest.EXPECTED_ENTITY val EXPECTED_REST_SERVICE = RestService( name = "Budapest Gourmet Guide", port = 8080, description = "BGG is a simple API allowing consumers to view recommendations.", schemas = mapOf(Pair(EXPECTED_SCHEMA_NAME, EXPECTED_SCHEMA)), fixtures = mapOf(Pair(EXPECTED_SCHEMA_NAME, listOf(EXPECTED_ENTITY))), endpoints = listOf( RestEndpoint( name = "Recommendations", path = Path( pathStr = "/recommendations"), schema = EXPECTED_SCHEMA, description = "Description.", restMethods = mapOf( Pair(GET, RestMethod( method = GET, name = "List All Recommendations", description = "Calling this method will return all recommendations without filtering.", requestParams = mapOf( Pair(CONSUMES, "application/json")), responseParams = mapOf( Pair(STATUS, "200"), Pair(PRODUCES, "application/json")) )), Pair(POST, RestMethod( method = POST, name = "Create a New Recommendation", description = "You may create your own recommendation using this action. It takes a JSON object containing a question and a collection of answers in the form of choices.", requestParams = mapOf( Pair(CONSUMES, "application/json")), responseParams = mapOf( Pair(STATUS, "201"), Pair(LOCATION, "/recommendation/{id}")) )) )), RestEndpoint( name = "Recommendation", path = Path( pathStr = "/recommendation/{id}", paramToSchemaPropertyMapping = mapOf(Pair("id", "id"))), schema = EXPECTED_SCHEMA, description = "Some description.", restMethods = mapOf( Pair(GET, RestMethod( method = GET, name = "Details of a Recommendation", description = "Using this method will return a single recommendation.", requestParams = mapOf( Pair(CONSUMES, "application/json")), responseParams = mapOf( Pair(STATUS, "200"), Pair(PRODUCES, "application/json")) )) )))) } }
agpl-3.0
acbf776b5998a3f6e127584c598a0546
51.978102
219
0.495108
6.688479
false
false
false
false
ViolentOr/RWinquisition
src/main/kotlin/me/violentor/rwinquisition/model/result/Control.kt
1
1130
package me.violentor.rwinquisition.model.result import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonProperty class Control { @get:JsonProperty("id") @set:JsonProperty("id") var id: String? = null @get:JsonProperty("title") @set:JsonProperty("title") var title: String? = null @get:JsonProperty("desc") @set:JsonProperty("desc") var desc: String? = null @get:JsonProperty("impact") @set:JsonProperty("impact") var impact: Float = 0.toFloat() @get:JsonProperty("refs") @set:JsonProperty("refs") var refs: Array<Any>? = null @get:JsonProperty("tags") @set:JsonProperty("tags") var tags: Tags? = null @get:JsonProperty("code") @set:JsonProperty("code") var code: String? = null @get:JsonProperty("source_location") @set:JsonProperty("source_location") var sourceLocation: SourceLocation? = null @get:JsonProperty("results") @set:JsonProperty("results") var results: List<ResultElement>? = null @JsonIgnore fun isSuccessfull() = this.results!![0].status == Status.PASSED }
apache-2.0
c0b67c0e899a343736f58fd7888f89e2
29.540541
67
0.673451
3.856655
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/workspaceModel/ide/impl/WorkspaceModelImpl.kt
1
6999
// 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.workspaceModel.ide.impl import com.intellij.diagnostic.StartUpMeasurer import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.workspaceModel.ide.* import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.bridgeEntities.FacetEntity import com.intellij.workspaceModel.storage.bridgeEntities.FacetId import com.intellij.workspaceModel.storage.bridgeEntities.ModuleId import com.intellij.workspaceModel.storage.impl.VersionedEntityStorageImpl import kotlin.system.measureTimeMillis class WorkspaceModelImpl(private val project: Project) : WorkspaceModel, Disposable { private val cacheEnabled = (!ApplicationManager.getApplication().isUnitTestMode && WorkspaceModelImpl.cacheEnabled) || forceEnableCaching override val cache = if (cacheEnabled) WorkspaceModelCacheImpl(project, this) else null /** specifies ID of a entity which changes should be printed to the log */ private val entityToTrace = System.getProperty("idea.workspace.model.track.facet.id")?.let { val (moduleName, facetTypeId, facetName) = it.split('/') FacetId(facetName, facetTypeId, ModuleId(moduleName)) } @Volatile var loadedFromCache = false private set override val entityStorage: VersionedEntityStorageImpl init { // TODO It's possible to load this cache from the moment we know project path // Like in ProjectLifecycleListener or something log.debug { "Loading workspace model" } val initialContent = WorkspaceModelInitialTestContent.pop() val projectEntities = when { initialContent != null -> initialContent cache != null -> { val activity = StartUpMeasurer.startActivity("(wm) Loading cache") val previousStorage: WorkspaceEntityStorage? val loadingCacheTime = measureTimeMillis { previousStorage = cache.loadCache() } val storage = if (previousStorage != null) { log.info("Load workspace model from cache in $loadingCacheTime ms") loadedFromCache = true printInfoAboutTracedEntity(previousStorage, "cache") previousStorage } else WorkspaceEntityStorageBuilder.create() activity.end() storage } else -> WorkspaceEntityStorageBuilder.create() } entityStorage = VersionedEntityStorageImpl((projectEntities as? WorkspaceEntityStorageBuilder)?.toStorage() ?: projectEntities) if (entityToTrace != null) { WorkspaceModelTopics.getInstance(project).subscribeImmediately(project.messageBus.connect(), EntityTracingListener(entityToTrace)) } } fun blockDelayedLoading() { loadedFromCache = false } internal fun printInfoAboutTracedEntity(storage: WorkspaceEntityStorage, storageDescription: String) { if (entityToTrace != null) { log.info("Traced entity from $storageDescription: ${storage.resolve(entityToTrace)?.configurationXmlTag}") } } override fun <R> updateProjectModel(updater: (WorkspaceEntityStorageBuilder) -> R): R { ApplicationManager.getApplication().assertWriteAccessAllowed() val before = entityStorage.current val builder = WorkspaceEntityStorageBuilder.from(before) val result = updater(builder) startPreUpdateHandlers(before, builder) val changes = builder.collectChanges(before) entityStorage.replace(builder.toStorage(), changes, this::onBeforeChanged, this::onChanged) return result } override fun <R> updateProjectModelSilent(updater: (WorkspaceEntityStorageBuilder) -> R): R { val builder = WorkspaceEntityStorageBuilder.from(entityStorage.current) val result = updater(builder) entityStorage.replaceSilently(builder.toStorage()) return result } override fun getBuilderSnapshot(): BuilderSnapshot { val current = entityStorage.pointer return BuilderSnapshot(current.version, current.storage) } override fun replaceProjectModel(replacement: StorageReplacement): Boolean { ApplicationManager.getApplication().assertWriteAccessAllowed() if (entityStorage.version != replacement.version) return false entityStorage.replace(replacement.snapshot, replacement.changes, this::onBeforeChanged, this::onChanged) return true } override fun dispose() = Unit private fun onBeforeChanged(change: VersionedStorageChange) { ApplicationManager.getApplication().assertWriteAccessAllowed() if (project.isDisposed) return WorkspaceModelTopics.getInstance(project).syncPublisher(project.messageBus).beforeChanged(change) } private fun onChanged(change: VersionedStorageChange) { ApplicationManager.getApplication().assertWriteAccessAllowed() if (project.isDisposed) return WorkspaceModelTopics.getInstance(project).syncPublisher(project.messageBus).changed(change) } private fun startPreUpdateHandlers(before: WorkspaceEntityStorage, builder: WorkspaceEntityStorageBuilder) { var startUpdateLoop = true var updatesStarted = 0 while (startUpdateLoop && updatesStarted < PRE_UPDATE_LOOP_BLOCK) { updatesStarted += 1 startUpdateLoop = false PRE_UPDATE_HANDLERS.extensions().forEach { startUpdateLoop = startUpdateLoop or it.update(before, builder) } } if (updatesStarted >= PRE_UPDATE_LOOP_BLOCK) { log.error("Loop workspace model updating") } } companion object { private val log = logger<WorkspaceModelImpl>() const val ENABLED_CACHE_KEY = "ide.new.project.model.cache" var forceEnableCaching = false val cacheEnabled = Registry.`is`(ENABLED_CACHE_KEY) private val PRE_UPDATE_HANDLERS = ExtensionPointName.create<WorkspaceModelPreUpdateHandler>("com.intellij.workspaceModel.preUpdateHandler") private const val PRE_UPDATE_LOOP_BLOCK = 100 } } private class EntityTracingListener(private val entityId: FacetId) : WorkspaceModelChangeListener { override fun changed(event: VersionedStorageChange) { event.getAllChanges().forEach { when (it) { is EntityChange.Added -> printInfo("added", it.entity) is EntityChange.Removed -> printInfo("removed", it.entity) is EntityChange.Replaced -> { printInfo("replaced from", it.oldEntity) printInfo("replaced to", it.newEntity) } } } } private fun printInfo(action: String, entity: WorkspaceEntity) { if ((entity as? FacetEntity)?.persistentId() == entityId) { LOG.info("$action: ${entity.configurationXmlTag}", Throwable()) } } companion object { private val LOG = logger<EntityTracingListener>() } }
apache-2.0
8ccea1f90a47669d483d0b2417b31d7b
38.542373
143
0.747678
4.949788
false
false
false
false
allotria/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/table/column/VcsLogColumnUtil.kt
2
3745
// 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.vcs.log.ui.table.column import com.intellij.vcs.log.impl.CommonUiProperties import com.intellij.vcs.log.impl.VcsLogUiProperties import com.intellij.vcs.log.impl.VcsLogUiProperties.VcsLogUiProperty internal fun VcsLogUiProperties.supportsColumnsReordering() = exists(CommonUiProperties.COLUMN_ID_ORDER) internal fun VcsLogUiProperties.supportsColumnsToggling(): Boolean { val commitColumnProperties = VcsLogColumnManager.getInstance().getProperties(Commit) return exists(commitColumnProperties.visibility) && supportsColumnsReordering() } internal fun isValidColumnOrder(columnOrder: List<VcsLogColumn<*>>): Boolean { return Root in columnOrder && Commit in columnOrder } /** * Provides a list of visible [VcsLogColumn] ordered based on the saved state. * If [VcsLogColumn] is visible and its state were not saved, it will go after ordered columns. * * Columns visibility is checked using [isVisible] method. * * @see moveColumn * @see addColumn * @see removeColumn * @see updateOrder */ internal fun VcsLogUiProperties.getColumnsOrder(): List<VcsLogColumn<*>> { val currentColumns = VcsLogColumnManager.getInstance().getCurrentColumns().filter { it.isVisible(this) } val savedOrder = get(CommonUiProperties.COLUMN_ID_ORDER).mapNotNull { id -> currentColumns.find { it.id == id } } val visibleColumns = currentColumns - savedOrder return savedOrder + visibleColumns } internal fun VcsLogUiProperties.moveColumn(column: VcsLogColumn<*>, newIndex: Int) = updateOrder { order -> order.remove(column) order.add(newIndex, column) } internal fun VcsLogUiProperties.addColumn(column: VcsLogColumn<*>) { column.changeVisibility(this, true) updateOrder { order -> order.add(column) } } internal fun VcsLogUiProperties.removeColumn(column: VcsLogColumn<*>) { column.changeVisibility(this, false) updateOrder { order -> order.remove(column) } } internal fun VcsLogUiProperties.updateOrder(newOrder: List<VcsLogColumn<*>>) { set(CommonUiProperties.COLUMN_ID_ORDER, newOrder.map { it.id }.distinct()) } internal fun VcsLogColumn<*>.isVisible(properties: VcsLogUiProperties): Boolean = withColumnProperties { columnProperties -> properties.getPropertyValue(columnProperties.visibility, true) } internal fun VcsLogColumn<*>.changeVisibility(properties: VcsLogUiProperties, value: Boolean) = withColumnProperties { columnProperties -> properties.changeProperty(columnProperties.visibility, value) } internal fun VcsLogColumn<*>.getWidth(properties: VcsLogUiProperties): Int = withColumnProperties { columnProperties -> properties.getPropertyValue(columnProperties.width, -1) } internal fun VcsLogColumn<*>.setWidth(properties: VcsLogUiProperties, value: Int) = withColumnProperties { columnProperties -> properties.changeProperty(columnProperties.width, value) } private fun VcsLogUiProperties.updateOrder(update: (MutableList<VcsLogColumn<*>>) -> Unit) { val order = getColumnsOrder().toMutableList() update(order) updateOrder(order) } private fun <T> VcsLogColumn<*>.withColumnProperties(block: (VcsLogColumnProperties) -> T): T { val properties = VcsLogColumnManager.getInstance().getProperties(this) return block(properties) } private fun <T> VcsLogUiProperties.changeProperty(property: VcsLogUiProperty<T>, value: T) { if (exists(property)) { if (get(property) != value) { set(property, value) } } } private fun <T> VcsLogUiProperties.getPropertyValue(property: VcsLogUiProperty<T>, defaultValue: T): T { return if (exists(property)) { get(property) } else { defaultValue } }
apache-2.0
98cb4953e0fc32653dff7d2edf2b5f6d
35.368932
140
0.769826
4.284897
false
false
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/refactoring/rename/impl/SymbolRenameTargetRenamerFactory.kt
3
2063
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.refactoring.rename.impl import com.intellij.model.Symbol import com.intellij.model.psi.impl.targetSymbols import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.refactoring.rename.Renamer import com.intellij.refactoring.rename.RenamerFactory import com.intellij.refactoring.rename.api.RenameTarget import com.intellij.refactoring.rename.symbol.RenameableSymbol import com.intellij.refactoring.rename.symbol.SymbolRenameTargetFactory /** * [RenamerFactory] which follows the chain: [DataContext] -> [Symbol] -> [RenameTarget] -> [Renamer]. */ class SymbolRenameTargetRenamerFactory : RenamerFactory { override fun createRenamers(dataContext: DataContext): Collection<Renamer> { val project: Project = dataContext.getData(CommonDataKeys.PROJECT) ?: return emptyList() val symbols: Collection<Symbol> = targetSymbols(dataContext) if (symbols.isEmpty()) { return emptyList() } val allRenameTargets: Collection<RenameTarget> = symbols.mapNotNull { symbol: Symbol -> renameTarget(project, symbol) } val distinctRenameTargets: Collection<RenameTarget> = allRenameTargets.toSet() val editor: Editor? = dataContext.getData(CommonDataKeys.EDITOR) return distinctRenameTargets.map { target: RenameTarget -> RenameTargetRenamer(project, editor, target) } } private fun renameTarget(project: Project, symbol: Symbol): RenameTarget? { for (factory: SymbolRenameTargetFactory in SymbolRenameTargetFactory.EP_NAME.extensions) { return factory.renameTarget(project, symbol) ?: continue } if (symbol is RenameableSymbol) { return symbol.renameTarget } if (symbol is RenameTarget) { return symbol } return null } }
apache-2.0
f5d95c1b356d8a0c74858cb2fb4f55b8
40.26
140
0.757635
4.370763
false
false
false
false
CORDEA/MackerelClient
app/src/main/java/jp/cordea/mackerelclient/adapter/MetricsAdapter.kt
1
4112
package jp.cordea.mackerelclient.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import com.github.mikephil.charting.components.XAxis import com.github.mikephil.charting.data.LineData import jp.cordea.mackerelclient.MemoryValueFormatter import jp.cordea.mackerelclient.MetricsType import jp.cordea.mackerelclient.R import jp.cordea.mackerelclient.activity.MetricsEditActivity import jp.cordea.mackerelclient.databinding.ListItemMetricsChartBinding import jp.cordea.mackerelclient.fragment.MetricsDeleteConfirmDialogFragment import jp.cordea.mackerelclient.model.MetricsLineDataSet class MetricsAdapter( private val activity: AppCompatActivity, private val type: MetricsType, private val id: String ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val items = mutableListOf<MetricsLineDataSet>() override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { (holder as? ViewHolder)?.binding?.let { binding -> val item = items[position] when (item) { is MetricsLineDataSet.Success -> { if (item.title.isNullOrBlank()) { binding.titleTextView.visibility = View.GONE } else { binding.titleTextView.text = item.title } binding.setLineData(item.toLineData()) } is MetricsLineDataSet.Failure -> { binding.titleTextView.visibility = View.GONE binding.lineChart.isVisible = false binding.error.root.isVisible = true } } binding.editButton.setOnClickListener { val intent = MetricsEditActivity .createIntent(activity, type, id, items[position].id) activity.startActivityForResult(intent, MetricsEditActivity.REQUEST_CODE) } binding.deleteButton.setOnClickListener { MetricsDeleteConfirmDialogFragment.newInstance(items[position].id) .show(activity.supportFragmentManager, MetricsDeleteConfirmDialogFragment.TAG) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val view = LayoutInflater.from(activity).inflate(R.layout.list_item_metrics_chart, parent, false) return ViewHolder(view) } override fun getItemCount(): Int = items.size fun add(item: MetricsLineDataSet) { items.add(item) notifyItemInserted(items.size - 1) } fun clear() { items.clear() notifyDataSetChanged() } private fun ListItemMetricsChartBinding.setLineData(lineData: LineData) { lineChart.apply { setDescription("") xAxis.position = XAxis.XAxisPosition.BOTTOM if (lineData.needsFormat) { val format = context.resources.getString(R.string.metrics_data_gb_format) lineData.dataSets[0].label = format.format(lineData.dataSets[0].label) if (lineData.dataSets.size > 1) { lineData.dataSets[1].label = format.format(lineData.dataSets[1].label) } axisRight.valueFormatter = MemoryValueFormatter() axisLeft.valueFormatter = MemoryValueFormatter() } axisRight.setLabelCount(3, false) axisLeft.setLabelCount(3, false) this.data = lineData invalidate() } } private val LineData.needsFormat: Boolean get() = dataSets .filter { "memory" == it.label.split(".")[0] } .size == this.dataSets.size private class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val binding: ListItemMetricsChartBinding = ListItemMetricsChartBinding.bind(view) } }
apache-2.0
5e4b6af18280d705c8fb08359ca30d67
38.161905
98
0.646644
5.064039
false
false
false
false
romannurik/muzei
main/src/main/java/com/google/android/apps/muzei/util/Zoomer.kt
2
3335
/* * Copyright 2014 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.google.android.apps.muzei.util import android.content.Context import android.os.SystemClock import android.view.animation.DecelerateInterpolator import android.view.animation.Interpolator /** * A simple class that animates double-touch zoom gestures. Functionally similar to a [ ]. */ internal class Zoomer(context: Context) { /** * The interpolator, used for making zooms animate 'naturally.' */ private val interpolator: Interpolator = DecelerateInterpolator() /** * The total animation duration for a zoom. */ private val animationDurationMillis: Int = context.resources.getInteger( android.R.integer.config_shortAnimTime) /** * Whether or not the current zoom has finished. */ private var finished = true /** * The starting zoom value. */ private var startZoom = 1f /** * The current zoom value; computed by [.computeZoom]. */ /** * Returns the current zoom level. * * @see android.widget.Scroller.getCurrX */ var currZoom: Float = 0f private set /** * The time the zoom started, computed using [android.os.SystemClock.elapsedRealtime]. */ private var startRTC: Long = 0 /** * The destination zoom factor. */ private var endZoom: Float = 0f /** * Forces the zoom finished state to the given value. Unlike [.abortAnimation], the * current zoom value isn't set to the ending value. * * @see android.widget.Scroller.forceFinished */ fun forceFinished(finished: Boolean) { this.finished = finished } /** * Starts a zoom from startZoom to endZoom. That is, to zoom from 100% to 125%, endZoom should * by 0.25f. * * @see android.widget.Scroller.startScroll */ fun startZoom(startZoom: Float, endZoom: Float) { startRTC = SystemClock.elapsedRealtime() this.endZoom = endZoom finished = false this.startZoom = startZoom currZoom = startZoom } /** * Computes the current zoom level, returning true if the zoom is still active and false if the * zoom has finished. * * @see android.widget.Scroller.computeScrollOffset */ fun computeZoom(): Boolean { if (finished) { return false } val tRTC = SystemClock.elapsedRealtime() - startRTC if (tRTC >= animationDurationMillis) { finished = true currZoom = endZoom return false } val t = tRTC * 1f / animationDurationMillis currZoom = interpolate( startZoom, endZoom, interpolator.getInterpolation(t)) return true } }
apache-2.0
a1a2100268df56aebd0b0d7c10b39ee6
27.262712
99
0.644378
4.43484
false
false
false
false
SmokSmog/smoksmog-android
app/src/main/kotlin/com/antyzero/smoksmog/logger/CrashlyticsLogger.kt
1
3047
package com.antyzero.smoksmog.logger import android.util.Log import com.crashlytics.android.core.CrashlyticsCore import smoksmog.logger.Logger /** * Crashlytics logger */ class CrashlyticsLogger @JvmOverloads constructor( private val logExceptionLevel: CrashlyticsLogger.ExceptionLevel = CrashlyticsLogger.ExceptionLevel.VERBOSE, callback: CrashlyticsLogger.ConfigurationCallback = CrashlyticsLogger.EMPTY_CALLBACK) : Logger { init { callback.onConfiguration(CrashlyticsCore.getInstance()) } override fun v(tag: String, message: String) { CrashlyticsCore.getInstance().log(Log.VERBOSE, tag, message) } override fun v(tag: String, message: String, throwable: Throwable) { CrashlyticsCore.getInstance().log(Log.VERBOSE, tag, message) if (logExceptionLevel.value <= ExceptionLevel.VERBOSE.value) { CrashlyticsCore.getInstance().logException(throwable) } } override fun d(tag: String, message: String) { CrashlyticsCore.getInstance().log(Log.DEBUG, tag, message) } override fun d(tag: String, message: String, throwable: Throwable) { CrashlyticsCore.getInstance().log(Log.DEBUG, tag, message) if (logExceptionLevel.value <= ExceptionLevel.DEBUG.value) { CrashlyticsCore.getInstance().logException(throwable) } } override fun i(tag: String, message: String) { CrashlyticsCore.getInstance().log(Log.INFO, tag, message) } override fun i(tag: String, message: String, throwable: Throwable) { CrashlyticsCore.getInstance().log(Log.INFO, tag, message) if (logExceptionLevel.value <= ExceptionLevel.INFO.value) { CrashlyticsCore.getInstance().logException(throwable) } } override fun w(tag: String, message: String) { CrashlyticsCore.getInstance().log(Log.WARN, tag, message) } override fun w(tag: String, message: String, throwable: Throwable) { CrashlyticsCore.getInstance().log(Log.WARN, tag, message) if (logExceptionLevel.value <= ExceptionLevel.WARN.value) { CrashlyticsCore.getInstance().logException(throwable) } } override fun e(tag: String, message: String) { CrashlyticsCore.getInstance().log(Log.ERROR, tag, message) } override fun e(tag: String, message: String, throwable: Throwable) { CrashlyticsCore.getInstance().log(Log.ERROR, tag, message) if (logExceptionLevel.value <= ExceptionLevel.ERROR.value) { CrashlyticsCore.getInstance().logException(throwable) } } enum class ExceptionLevel constructor(internal val value: Int) { VERBOSE(0), DEBUG(1), INFO(2), WARN(3), ERROR(4) } interface ConfigurationCallback { fun onConfiguration(instance: CrashlyticsCore) } companion object { private val EMPTY_CALLBACK = object : ConfigurationCallback { override fun onConfiguration(instance: CrashlyticsCore) { } } } }
gpl-3.0
e564138371a6843911547920ee6ba5b3
32.483516
115
0.676075
4.467742
false
true
false
false
leafclick/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/startup/GradleUnlinkedProjectProcessor.kt
1
4489
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.startup import com.intellij.CommonBundle import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil import org.jetbrains.plugins.gradle.config.GradleSettingsListenerAdapter import org.jetbrains.plugins.gradle.service.project.GradleNotification import org.jetbrains.plugins.gradle.service.project.open.linkAndRefreshGradleProject import org.jetbrains.plugins.gradle.settings.GradleProjectSettings import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.util.GradleBundle import org.jetbrains.plugins.gradle.util.GradleConstants class GradleUnlinkedProjectProcessor : StartupActivity.DumbAware { override fun runActivity(project: Project) { if (isEnabledNotifications(project)) { showNotification(project) } } companion object { private const val SHOW_UNLINKED_GRADLE_POPUP = "show.unlinked.gradle.project.popup" private val LOG = Logger.getInstance(GradleUnlinkedProjectProcessor::class.java) private fun showNotification(project: Project) { if (!GradleSettings.getInstance(project).linkedProjectsSettings.isEmpty()) return if (project.getUserData(ExternalSystemDataKeys.NEWLY_IMPORTED_PROJECT) === java.lang.Boolean.TRUE) return val externalProjectPath = project.basePath ?: return val gradleGroovyDslFile = externalProjectPath + "/" + GradleConstants.DEFAULT_SCRIPT_NAME val kotlinDslGradleFile = externalProjectPath + "/" + GradleConstants.KOTLIN_DSL_SCRIPT_NAME if (FileUtil.findFirstThatExist(gradleGroovyDslFile, kotlinDslGradleFile) == null) return val subscription = Disposer.newDisposable() val notification = GradleNotification.NOTIFICATION_GROUP.createNotification( GradleBundle.message("gradle.notifications.unlinked.project.found.title", ApplicationNamesInfo.getInstance().fullProductName), NotificationType.INFORMATION) val notificationExpire = { notification.expire() LOG.debug("Unlinked project notification expired") Disposer.dispose(subscription) } notification.addAction(NotificationAction.createSimple( GradleBundle.message("gradle.notifications.unlinked.project.found.import")) { notificationExpire() linkAndRefreshGradleProject(externalProjectPath, project) }) notification.addAction(NotificationAction.createSimple( GradleBundle.message("gradle.notifications.unlinked.project.found.skip")) { notificationExpire() disableNotifications(project) }) notification.contextHelpAction = object : DumbAwareAction( CommonBundle.getHelpButtonText(), GradleBundle.message("gradle.notifications.unlinked.project.found.help"), null) { override fun actionPerformed(e: AnActionEvent) {} } val settingsListener = object : GradleSettingsListenerAdapter() { override fun onProjectsLinked(settings: MutableCollection<GradleProjectSettings>) { notificationExpire() } } Disposer.register(project, subscription) ExternalSystemApiUtil.subscribe(project, GradleConstants.SYSTEM_ID, settingsListener, subscription) notification.notify(project) } private fun isEnabledNotifications(project: Project): Boolean { return PropertiesComponent.getInstance(project).getBoolean(SHOW_UNLINKED_GRADLE_POPUP, true) } private fun disableNotifications(project: Project) { PropertiesComponent.getInstance(project).setValue(SHOW_UNLINKED_GRADLE_POPUP, false, true) } fun enableNotifications(project: Project) { PropertiesComponent.getInstance(project).setValue(SHOW_UNLINKED_GRADLE_POPUP, true, false) } } }
apache-2.0
04ad6175793615a1161788223925a2dc
44.353535
140
0.780352
5.060879
false
false
false
false
Shahroz16/Tilde
tilde/src/main/java/com/apps/tilde/Extensions.kt
1
8232
package com.apps.tilde import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashMap import kotlin.concurrent.schedule /** * Created by rehan on 5/23/17. */ /** * Executes the block on null value to return a non null value; * if the value is already assigned, returns it without executing the block * * @param block To generate new value if null * @return Non null value */ inline fun <T> T?.assign(block: () -> T): T = this ?: block() /** * Creates an list of elements from the specified indexes, or keys, of the collection. * Indexes may be specified as individual arguments or as arrays of indexes. * * @param indexes Get elements from these indexes. * @return New list with elements from the indexes specified. */ fun <T> Iterable<T>.at(vararg indexes: Int): ArrayList<T> { return this.at(indexes.toList()) } /** * Creates an list of elements from the specified indexes, or keys, of the collection. * Indexes may be specified as individual arguments or as arrays of indexes. * * @param indexes Get elements from these indexes. * @return New list with elements from the indexes specified. */ fun <T> Iterable<T>.at(indexes: List<Int>): ArrayList<T> { return indexes.mapTo(ArrayList<T>()) { this.elementAt(it) } } /** * Creates an array of elements split into groups the length of size. * If array can’t be split evenly, the final chunk will be the remaining elements. * * @param size size of each chunk. * @return array chunked elements. */ fun <T> Iterable<T>.chunks(size: Int = 1): ArrayList<ArrayList<T>> { val result = ArrayList<ArrayList<T>>() this.mapIndexed { index, item -> if (index % size == 0) { result.add(ArrayList<T>()) } result.last().add(item) } return result } /** * Creates an array with all nil values removed. * * @return A new array that doesnt have any nil values. */ fun <T> Iterable<T?>.compact(): ArrayList<T> { val result = ArrayList<T>() this.forEach { if (it != null) { result.add(it) } } return result } /** * Returns a list with all items removed at provides indexes. * * @param indexes elements on indexes to be removed */ fun <T> Iterable<T>.removeElementsAtIndexes(vararg indexes: Int): List<T> { return this.filterIndexed { index, _ -> !indexes.contains(index) } } /** * Removes items from an list. * * @param indexes set of items that need to be removed * @return list with items removed. */ fun <T> Iterable<T>.remove(indexes: HashSet<T>): List<T> { System.out.println(indexes) return this.filter { t -> !indexes.contains(t) } } /** * Removes items from an list. * * @param indexes items to be removed * @return list with items removed. */ fun <T> Iterable<T>.remove(vararg indexes: T): List<T> { return remove(indexes.toHashSet()) } /** * Cycles through the array n times passing each element into the callback function * And indefinitely if n is -1 * * @param times Number of times to cycle through the array * @param callback function to call with the element. */ fun <T, U> Iterable<T>.cycle(times: Int = -1, callback: (T) -> U) { val function = { this.forEach { callback(it) } } if (times == -1) { { true }.loop(function) } else { (1..times).forEach { function() } } } /** * Delays the execution of a function by the specified DispatchTimeInterval. * * @param delay interval to delay the execution of the function by. * @param block block to execute. */ inline fun <T> T.delay(delay: Long, crossinline block: T.() -> Any) { Timer().schedule(delay) { block() } } // debounce => Unimplemented /** * Creates an array excluding all values of the provided arrays in order. * * @param arrays The arrays to difference between. * @return The difference between the first array and all the remaining arrays from the arrays params. */ fun <T> Iterable<T>.differenceInOrder(vararg arrays: Iterable<T>): ArrayList<T> { val result = ArrayList<T>() this.filter { item -> arrays.forEach { array -> if (array.contains(item)) { return@filter false } } return@filter true }.forEach { result.add(it) } return result } /** * Returns Factorial of number. * * @receiver Number whose factorial needs to be calculated. * @return Factorial of the receiver. */ fun Int.factorial(): Int { return toLong().factorial().toInt() } /** * Returns Factorial of number. * * @receiver Number whose factorial needs to be calculated. * @return Factorial of the receiver. */ fun Long.factorial(): Long { if (this > 0) { return this * (this - 1L).factorial() } else { return 1L } } /** * This method returns a dictionary of values in an array mapping to the * total number of occurrences in the array. If passed a function it returns * a frequency table of the results of the given function on the arrays elements. * * @receiver The array to source from. * @return Dictionary that contains the key generated from the element passed in the function. */ fun <V> Iterable<V>.frequency(): HashMap<V, Int> { val map = HashMap<V, Int>() this.forEach { map[it] = map[it].assign { 0 } + 1 } return map } /** * This method returns a dictionary of values in an array mapping to the * total number of occurrences in the array. If passed a function it returns * a frequency table of the results of the given function on the arrays elements. * * @param keyGenerator The function to get value of the key for each element to group by. * @receiver The array to source from. * @return Dictionary that contains the key generated from the element passed in the function. */ fun <K, V> Iterable<V>.frequency(keyGenerator: (V) -> K?): HashMap<K, Int> { val map = HashMap<K, Int>() this.forEach { keyGenerator(it)?.let { map[it] = map[it].assign { 0 } + 1 } } return map } /** * Splits a collection into sets, grouped by the result of running each value through a callback. * * @param keyGenerator Function whose response will be used as the key to group. * @receiver The array to group. * @return Grouped collection. */ fun <K, V> Iterable<V>.groupBy(keyGenerator: (V) -> K?): HashMap<K, ArrayList<V>> { val hashMap = HashMap<K, ArrayList<V>>() this.forEach { value -> keyGenerator(value)?.let { hashMap[it].assign { hashMap[it] = ArrayList<V>() hashMap[it]!! }.add(value) } } return hashMap } /** * Unline groupBy method, it splits a collection into set of single value, grouped by the result of running each value through a callback. * * @param keyGenerator Function whose response will be used as the key to group. * @param overrideExisting If true, the previous value present against the key will be overrided; default false. * @receiver The array to group. * @return Grouped collection. */ fun <K, V> Iterable<V>.groupByUnit(overrideExisting: Boolean = false, keyGenerator: (V) -> K?): HashMap<K, V> { val hashMap = HashMap<K, V>() this.forEach { value -> keyGenerator(value)?.let { hashMap[it] = hashMap[it]?.let { if (overrideExisting) value else it } ?: value } } return hashMap } /** * Loops to the passed function as far as the caller function returns true *. * @param function Funtion to be executed in each iteration */ fun (() -> Boolean).loop(function: () -> Unit) { while (this()) { function() } } /** * Loops to the passed function as far as the caller function returns true based on value passed * to caller function returned by the passed function * * @param function Funtion to be executed in each iteration and return a value to pass to caller function */ fun <T> ((T) -> Boolean).loop(function: () -> T) { while (this(function())) { } }
mit
05d31a113c2f410de398342b28f02a2e
27.880702
138
0.637546
3.815484
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/secondaryConstructors/dataClasses.kt
5
1499
internal data class A1(val prop1: String) { val prop2: String = "const2" var prop3: String = "" constructor(): this("default") { prop3 = "empty" } constructor(x: Int): this(x.toString()) { prop3 = "int" } fun f(): String = "$prop1#$prop2#$prop3" } internal class A2 private constructor() { var prop1: String = "" var prop2: String = "const2" var prop3: String = "" constructor(arg: String): this() { prop1 = arg } constructor(x: Double): this() { prop1 = "default" prop3 = "empty" } constructor(x: Int): this(x.toString()) { prop3 = "int" } fun f(): String = "$prop1#$prop2#$prop3" } fun box(): String { val a1x = A1("asd") if (a1x.f() != "asd#const2#") return "fail1: ${a1x.f()}" if (a1x.toString() != "A1(prop1=asd)") return "fail1s: ${a1x.toString()}" val a1y = A1() if (a1y.f() != "default#const2#empty") return "fail2: ${a1y.f()}" if (a1y.toString() != "A1(prop1=default)") return "fail2s: ${a1y.toString()}" val a1z = A1(5) if (a1z.f() != "5#const2#int") return "fail3: ${a1z.f()}" if (a1z.toString() != "A1(prop1=5)") return "fail3s: ${a1z.toString()}" val a2x = A2("asd") if (a2x.f() != "asd#const2#") return "fail4: ${a2x.f()}" val a2y = A2(123.0) if (a2y.f() != "default#const2#empty") return "fail5: ${a2y.f()}" val a2z = A2(5) if (a2z.f() != "5#const2#int") return "fail6: ${a2z.f()}" return "OK" }
apache-2.0
d0f3108107f94e0a0b5fbf422daf9071
27.283019
81
0.532355
2.657801
false
false
false
false
FirebaseExtended/mlkit-material-android
app/src/main/java/com/google/firebase/ml/md/kotlin/objectdetection/StaticObjectDotView.kt
1
3090
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.ml.md.kotlin.objectdetection import android.animation.ValueAnimator import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.view.View import androidx.interpolator.view.animation.FastOutSlowInInterpolator import com.google.firebase.ml.md.R /** Represents a detected object by drawing a circle dot at the center of object's bounding box. */ class StaticObjectDotView @JvmOverloads constructor(context: Context, selected: Boolean = false) : View(context) { private val paint: Paint = Paint().apply { style = Paint.Style.FILL } private val unselectedDotRadius: Int = context.resources.getDimensionPixelOffset(R.dimen.static_image_dot_radius_unselected) private val radiusOffsetRange: Int private var currentRadiusOffset: Float = 0.toFloat() init { val selectedDotRadius = context.resources.getDimensionPixelOffset(R.dimen.static_image_dot_radius_selected) radiusOffsetRange = selectedDotRadius - unselectedDotRadius currentRadiusOffset = (if (selected) radiusOffsetRange else 0).toFloat() } fun playAnimationWithSelectedState(selected: Boolean) { val radiusOffsetAnimator: ValueAnimator = if (selected) { ValueAnimator.ofFloat(0f, radiusOffsetRange.toFloat()) .setDuration(DOT_SELECTION_ANIMATOR_DURATION_MS).apply { startDelay = DOT_DESELECTION_ANIMATOR_DURATION_MS } } else { ValueAnimator.ofFloat(radiusOffsetRange.toFloat(), 0f) .setDuration(DOT_DESELECTION_ANIMATOR_DURATION_MS) } radiusOffsetAnimator.interpolator = FastOutSlowInInterpolator() radiusOffsetAnimator.addUpdateListener { animation -> currentRadiusOffset = animation.animatedValue as Float invalidate() } radiusOffsetAnimator.start() } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val cx = width / 2f val cy = height / 2f paint.color = Color.WHITE canvas.drawCircle(cx, cy, unselectedDotRadius + currentRadiusOffset, paint) } companion object { private const val DOT_SELECTION_ANIMATOR_DURATION_MS: Long = 116 private const val DOT_DESELECTION_ANIMATOR_DURATION_MS: Long = 67 } }
apache-2.0
72c5cbea91551bb603bf428d5462428b
38.615385
115
0.688026
4.790698
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/functions/prefixRecursiveCall.kt
5
169
operator fun String.unaryPlus() : String { if (this == "") { return "done" } return +"" } fun box() : String = if (+"11" == "done") "OK" else "FAIL"
apache-2.0
9cf995317629b7c1c7e8544ae10ea470
20.25
58
0.497041
3.25
false
false
false
false
chromeos/video-composition-sample
VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/presentation/opengl/CompositionRenderer.kt
1
10114
/* * Copyright (c) 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.chromeos.videocompositionsample.presentation.opengl import android.content.Context import android.opengl.EGL14 import android.opengl.GLES30 import android.opengl.GLSurfaceView import android.os.Handler import android.os.Looper import dev.chromeos.videocompositionsample.presentation.media.MediaTrack import dev.chromeos.videocompositionsample.presentation.media.encoder.MediaEncoder import dev.chromeos.videocompositionsample.presentation.media.encoder.surface.EncoderState import dev.chromeos.videocompositionsample.presentation.media.encoder.utils.VideoMimeType import java.io.File import javax.microedition.khronos.egl.EGLConfig import javax.microedition.khronos.opengles.GL10 class CompositionRenderer(private val context: Context, private val onSurfaceChangedListener: () -> Unit, private val onStopExport: () -> Unit, private val onEncodeError: (Exception) -> Unit ) : GLSurfaceView.Renderer { companion object { const val ENCODE_SPEED_FACTOR = 0.5f } val timePosition: Long get() = spriteList.firstOrNull()?.spriteTimePosition ?: 0 val fpsAverageList: List<Float> get() = spriteList.map { it.fpsAverage } private lateinit var shader: Shader var width = 0 var height = 0 private var spriteList: List<Sprite> = emptyList() private var absoluteFilePath: String = "" private var exportWidth = 0 private var exportHeight = 0 private var exportVideoMimeType = VideoMimeType.h264 private var isTestCaseMode = false private var mainThreadHandler: Handler = Handler(Looper.getMainLooper()) @Volatile private var opacity = 1f private var mutableOpacityTrackIndex = 0 private var mediaEncoder: MediaEncoder? = null private var outputFile: File? = null private var glMediaData: GlMediaData? = null private var isRecordingEnabled = false private var recordingStatus = EncoderState.OFF override fun onSurfaceCreated(p0: GL10?, p1: EGLConfig) { shader = Shader(context, "vertex_shader.glsl", "fragment_shader.glsl") GLES30.glEnable(GLES30.GL_CULL_FACE) GLES30.glEnable(GLES30.GL_DEPTH_TEST) } override fun onSurfaceChanged(gl: GL10, width: Int, height: Int) { this.width = width this.height = height onSurfaceChangedListener.invoke() } fun initMediaTrackList(mediaTrackList: List<MediaTrack>) { val textures = IntArray(mediaTrackList.size) { i -> i + 1 } glMediaData = GlMediaData(mediaTrackList, textures) GLES30.glGenTextures(mediaTrackList.size, textures, 0) val playedMediaTracks: MutableSet<Int> = mutableSetOf() spriteList = mediaTrackList .mapIndexed { index: Int, mediaTrack: MediaTrack -> Sprite( width = width, height = height, programId = shader.programId, textureId = textures[index], mediaTrack = mediaTrack, onActiveExportStateChangeListener = { activeIndex, isActive -> if (isActive) { mediaEncoder?.notifyStartMediaTrack(activeIndex) } else { playedMediaTracks.add(index) if (playedMediaTracks.size < mediaTrackList.size) { mediaEncoder?.notifyPauseMediaTrack(activeIndex) } else { mainThreadHandler.post { onStopExport.invoke() } } } } ).apply { pause() isPlayWhenReady = false mediaTrack.player?.playWhenReady = false } } isRecordingEnabled = false } fun playerStateChanged(index: Int, playWhenReady: Boolean) { if (playWhenReady != spriteList[index].isPlayWhenReady) { spriteList[index].isPlayWhenReady = playWhenReady } } fun play() { spriteList.forEach { it.play() } } fun pause() { isRecordingEnabled = false when (recordingStatus) { EncoderState.ON, EncoderState.RESUMED -> { mediaEncoder?.stop() recordingStatus = EncoderState.OFF } EncoderState.OFF -> { } } spriteList.forEach { it.pause() } } fun setBeginTimePosition() { spriteList.forEach { it.setBeginTimePosition() } } fun seek(position: Long) { spriteList.forEach { it.seek(position) } } fun setOpacity(trackIndex: Int, opacity: Float) { this.opacity = opacity mutableOpacityTrackIndex = trackIndex } fun export(absoluteFilePath: String, width: Int, height: Int, videoMimeType: VideoMimeType, isTestCaseMode: Boolean) { this.absoluteFilePath = absoluteFilePath this.isTestCaseMode = isTestCaseMode exportWidth = width exportHeight = height exportVideoMimeType = videoMimeType isRecordingEnabled = true spriteList.forEach { it.export(ENCODE_SPEED_FACTOR) } } private fun createNewOutputFile() { outputFile = File(absoluteFilePath) } override fun onDrawFrame(gl: GL10) { GLES30.glClearColor(0.0f, 0.0f, 0.0f, 1.0f) GLES30.glClear(GLES30.GL_DEPTH_BUFFER_BIT or GLES30.GL_COLOR_BUFFER_BIT) if (spriteList.isEmpty()) return if (isRecordingEnabled) { when (recordingStatus) { EncoderState.OFF -> { glMediaData?.let { glMediaData -> createNewOutputFile() outputFile?.let { outputFile -> mediaEncoder = MediaEncoder(onStopped = { mediaEncoder = null }) mediaEncoder?.start( context = context, eglContext = EGL14.eglGetCurrentContext(), outputFile = outputFile, width = exportWidth, height = exportHeight, videoMimeType = exportVideoMimeType, encodeSpeedFactor = ENCODE_SPEED_FACTOR, glMediaData = glMediaData, onError = { isRecordingEnabled = false outputFile.delete() mainThreadHandler.post { onEncodeError.invoke(it) } } ) recordingStatus = EncoderState.ON } ?: mainThreadHandler.post { onEncodeError.invoke(Exception("Error output file creation")) } } } EncoderState.RESUMED -> { mediaEncoder?.updateSharedContext( width = exportWidth, height = exportHeight, sharedContext = EGL14.eglGetCurrentContext() ) recordingStatus = EncoderState.ON } EncoderState.ON -> { val spriteTracksData = spriteList.map { sprite -> SpriteTrackData( isPlayWhenReady = sprite.isPlayWhenReady, videoScaleFactor = sprite.videoScaleFactor, videoTranslateFactor = sprite.videoTranslateFactor ) } val timePosition = (ENCODE_SPEED_FACTOR * (System.currentTimeMillis() - spriteList[0].systemStartPlayTime)).toLong() val encoderFrameData = EncoderFrameData( compositionTimePosition = timePosition, timeStampNs = System.nanoTime(), spriteTracksData = spriteTracksData ) mediaEncoder?.frameAvailable(encoderFrameData) spriteList.forEachIndexed { index, sprite -> val alpha = if (index == mutableOpacityTrackIndex) { opacity } else { 1f } sprite.drawClip(alpha) } } } } else { spriteList.forEachIndexed { index, sprite -> val alpha = if (index == mutableOpacityTrackIndex) { opacity } else { 1f } sprite.drawClip(alpha) } when (recordingStatus) { EncoderState.ON, EncoderState.RESUMED -> { mediaEncoder?.stop() recordingStatus = EncoderState.OFF } EncoderState.OFF -> { } } } } }
apache-2.0
3c015f038ae672f04ebdb00539ef249c
37.903846
136
0.537967
5.547998
false
false
false
false
byoutline/kickmaterial
app/src/main/java/com/byoutline/kickmaterial/views/EndlessScrollListener.kt
1
1557
package com.byoutline.kickmaterial.views import android.support.v7.widget.RecyclerView /** * @author Pawel Karczewski <pawel.karczewski at byoutline.com> on 2015-04-14 */ private const val DEFAULT_ITEMS_THRESHOLD = 2 private const val SCROLL_THRESHOLD = 1 interface EndlessScrollListener { val lastVisibleItemPosition: Int fun loadMoreData() fun hasMoreDataAndNotLoading(): Boolean } fun RecyclerView.setEndlessScrollListener( listener: EndlessScrollListener, visibleItemsThreshold: Int = DEFAULT_ITEMS_THRESHOLD) { addOnScrollListener(EndlessScrollListenerRV(listener, visibleItemsThreshold)) } private class EndlessScrollListenerRV( private val endlessScrollListener: EndlessScrollListener, private val visibleItemsThreshold: Int = DEFAULT_ITEMS_THRESHOLD ) : RecyclerView.OnScrollListener() { private var visibleItemCount: Int = 0 private var totalItemCount: Int = 0 private var lastVisibleItem: Int = 0 override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { if (dy > SCROLL_THRESHOLD) { visibleItemCount = recyclerView.childCount totalItemCount = recyclerView.layoutManager.itemCount lastVisibleItem = endlessScrollListener.lastVisibleItemPosition val shouldLoadMoreData = lastVisibleItem + visibleItemsThreshold > totalItemCount if (endlessScrollListener.hasMoreDataAndNotLoading() && shouldLoadMoreData) { endlessScrollListener.loadMoreData() } } } }
apache-2.0
50dd3ecc8edbecce68b534b610e2ca7d
33.6
93
0.73282
5.104918
false
false
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOB.kt
1
3809
package info.nightscout.androidaps.plugins.general.automation.triggers import android.widget.LinearLayout import com.google.common.base.Optional import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.plugins.general.automation.elements.InputDouble import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.JsonHelper.safeGetDouble import org.json.JSONObject import java.text.DecimalFormat class TriggerCOB(injector: HasAndroidInjector) : Trigger(injector) { private val minValue = 0 private val maxValue = sp.getInt(R.string.key_treatmentssafety_maxcarbs, 48) var cob: InputDouble = InputDouble(injector, 0.0, minValue.toDouble(), maxValue.toDouble(), 1.0, DecimalFormat("1")) var comparator: Comparator = Comparator(injector) private constructor(injector: HasAndroidInjector, triggerCOB: TriggerCOB) : this(injector) { cob = InputDouble(injector, triggerCOB.cob) comparator = Comparator(injector, triggerCOB.comparator.value) } fun setValue(value:Double) : TriggerCOB { cob.value = value return this } fun comparator(comparator: Comparator.Compare) : TriggerCOB { this.comparator.value = comparator return this } override fun shouldRun(): Boolean { val cobInfo = iobCobCalculatorPlugin.getCobInfo(false, "AutomationTriggerCOB") if (cobInfo.displayCob == null) { return if (comparator.value === Comparator.Compare.IS_NOT_AVAILABLE) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) true } else { aapsLogger.debug(LTag.AUTOMATION, "NOT ready for execution: " + friendlyDescription()) false } } if (comparator.value.check(cobInfo.displayCob, cob.value)) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) return true } aapsLogger.debug(LTag.AUTOMATION, "NOT ready for execution: " + friendlyDescription()) return false } @Synchronized override fun toJSON(): String { val data = JSONObject() .put("carbs", cob.value) .put("comparator", comparator.value.toString()) return JSONObject() .put("type", this::class.java.name) .put("data", data) .toString() } override fun fromJSON(data: String): Trigger { val d = JSONObject(data) cob.setValue(safeGetDouble(d, "carbs")) comparator.setValue(Comparator.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")!!)) return this } override fun friendlyName(): Int = R.string.triggercoblabel override fun friendlyDescription(): String = resourceHelper.gs(R.string.cobcompared, resourceHelper.gs(comparator.value.stringRes), cob.value) override fun icon(): Optional<Int?> = Optional.of(R.drawable.ic_cp_bolus_carbs) override fun duplicate(): Trigger = TriggerCOB(injector, this) override fun generateDialog(root: LinearLayout) { LayoutBuilder() .add(StaticLabel(injector, R.string.triggercoblabel, this)) .add(comparator) .add(LabelWithElement(injector, resourceHelper.gs(R.string.triggercoblabel) + ": ", "", cob)) .build(root) } }
agpl-3.0
72c75ad35d282102480cea014348bfac
40.868132
120
0.695458
4.529132
false
false
false
false
jotomo/AndroidAPS
core/src/main/java/info/nightscout/androidaps/utils/WarnColors.kt
1
1520
package info.nightscout.androidaps.utils import android.graphics.Color import android.widget.TextView import info.nightscout.androidaps.core.R import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject import javax.inject.Singleton @Singleton class WarnColors @Inject constructor(val resourceHelper: ResourceHelper) { private val normalColor = Color.WHITE private val warnColor = Color.YELLOW private val urgentColor = Color.RED fun setColor(view: TextView?, value: Double, warnLevel: Double, urgentLevel: Double) = view?.setTextColor(when { value >= urgentLevel -> urgentColor value >= warnLevel -> warnColor else -> normalColor }) fun setColorInverse(view: TextView?, value: Double, warnLevel: Double, urgentLevel: Double) = view?.setTextColor(when { value <= urgentLevel -> urgentColor value <= warnLevel -> warnColor else -> normalColor }) fun setColorByAge(view: TextView?, careportalEvent: CareportalEvent, warnThreshold: Double, urgentThreshold: Double) = view?.setTextColor(when { careportalEvent.isOlderThan(urgentThreshold) -> resourceHelper.gc(R.color.low) careportalEvent.isOlderThan(warnThreshold) -> resourceHelper.gc(R.color.high) else -> Color.WHITE }) }
agpl-3.0
3b4c304ccd6d90221ea1710423671519
39.026316
122
0.665789
4.578313
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/lang/KslScopeBuilder.kt
1
32331
package de.fabmax.kool.modules.ksl.lang import de.fabmax.kool.math.* import de.fabmax.kool.modules.ksl.model.KslOp import de.fabmax.kool.modules.ksl.model.KslScope class KslScopeBuilder(parentOp: KslOp?, val parentScope: KslScopeBuilder?, val parentStage: KslShaderStage) : KslScope(parentOp) { inline fun <reified T: Any> findParentOpByType(): T? { var parent = parentOp while (parent !is T && parent != null) { parent = parent.parentScope.parentOp } return parent as? T } val isInLoop: Boolean get() = findParentOpByType<KslLoop>() != null val parentFunction: KslFunction<*>? get() = findParentOpByType<KslFunction<*>.FunctionRoot>()?.function val isInFunction: Boolean get() = parentFunction != null fun nextName(prefix: String): String = parentStage.program.nextName(prefix) fun getBlocks(name: String?, result: MutableList<KslBlock>): MutableList<KslBlock> { ops.forEach { op -> if (op is KslBlock && (name == null || op.opName == name)) { result += op } op.childScopes.asSequence().filterIsInstance<KslScopeBuilder>().forEach { it.getBlocks(name, result) } } return result } val Double.const: KslValueFloat1 get() = KslValueFloat1(this.toFloat()) val Float.const: KslValueFloat1 get() = KslValueFloat1(this) val Float.const2: KslValueFloat2 get() = KslValueFloat2(this, this) val Float.const3: KslValueFloat3 get() = KslValueFloat3(this, this, this) val Float.const4: KslValueFloat4 get() = KslValueFloat4(this, this, this, this) val Int.const: KslValueInt1 get() = KslValueInt1(this) val Int.const2: KslValueInt2 get() = KslValueInt2(this, this) val Int.const3: KslValueInt3 get() = KslValueInt3(this, this, this) val Int.const4: KslValueInt4 get() = KslValueInt4(this, this, this, this) val UInt.const: KslValueUint1 get() = KslValueUint1(this) val UInt.const2: KslValueUint2 get() = KslValueUint2(this, this) val UInt.const3: KslValueUint3 get() = KslValueUint3(this, this, this) val UInt.const4: KslValueUint4 get() = KslValueUint4(this, this, this, this) val Int.uconst: KslValueUint1 get() = KslValueUint1(this.toUInt()) val Int.uconst2: KslValueUint2 get() = KslValueUint2(this.toUInt(), this.toUInt()) val Int.uconst3: KslValueUint3 get() = KslValueUint3(this.toUInt(), this.toUInt(), this.toUInt()) val Int.uconst4: KslValueUint4 get() = KslValueUint4(this.toUInt(), this.toUInt(), this.toUInt(), this.toUInt()) val Boolean.const: KslValueBool1 get() = KslValueBool1(this) val Boolean.const2: KslValueBool2 get() = KslValueBool2(this, this) val Boolean.const3: KslValueBool3 get() = KslValueBool3(this, this, this) val Boolean.const4: KslValueBool4 get() = KslValueBool4(this, this, this, this) val Vec2f.const: KslValueFloat2 get() = float2Value(x, y) val Vec3f.const: KslValueFloat3 get() = float3Value(x, y, z) val Vec4f.const: KslValueFloat4 get() = float4Value(x, y, z, w) val Vec2i.const: KslValueInt2 get() = int2Value(x, y) val Vec3i.const: KslValueInt3 get() = int3Value(x, y, z) val Vec4i.const: KslValueInt4 get() = int4Value(x, y, z, w) fun float2Value(x: Float, y: Float) = KslValueFloat2(x, y) fun float2Value(x: KslExpression<KslTypeFloat1>, y: KslExpression<KslTypeFloat1>) = KslValueFloat2(x, y) fun float3Value(x: Float, y: Float, z: Float) = KslValueFloat3(x, y, z) fun float3Value(x: KslExpression<KslTypeFloat1>, y: KslExpression<KslTypeFloat1>, z: KslExpression<KslTypeFloat1>) = KslValueFloat3(x, y, z) fun float4Value(x: Float, y: Float, z: Float, w: Float) = KslValueFloat4(x, y, z, w) fun float4Value(x: KslExpression<KslTypeFloat1>, y: KslExpression<KslTypeFloat1>, z: KslExpression<KslTypeFloat1>, w: KslExpression<KslTypeFloat1>) = KslValueFloat4(x, y, z, w) fun float4Value(xyz: KslVectorExpression<KslTypeFloat3, KslTypeFloat1>, w: Float) = float4Value(xyz, w.const) fun float4Value(xyz: KslVectorExpression<KslTypeFloat3, KslTypeFloat1>, w: KslExpression<KslTypeFloat1>) = KslValueFloat4(xyz.x, xyz.y, xyz.z, w) fun int2Value(x: Int, y: Int) = KslValueInt2(x, y) fun int2Value(x: KslExpression<KslTypeInt1>, y: KslExpression<KslTypeInt1>) = KslValueInt2(x, y) fun int3Value(x: Int, y: Int, z: Int) = KslValueInt3(x, y, z) fun int3Value(x: KslExpression<KslTypeInt1>, y: KslExpression<KslTypeInt1>, z: KslExpression<KslTypeInt1>) = KslValueInt3(x, y, z) fun int4Value(x: Int, y: Int, z: Int, w: Int) = KslValueInt4(x, y, z, w) fun int4Value(x: KslExpression<KslTypeInt1>, y: KslExpression<KslTypeInt1>, z: KslExpression<KslTypeInt1>, w: KslExpression<KslTypeInt1>) = KslValueInt4(x, y, z, w) fun int4Value(xyz: KslVectorExpression<KslTypeInt3, KslTypeInt1>, w: Int) = int4Value(xyz, w.const) fun int4Value(xyz: KslVectorExpression<KslTypeInt3, KslTypeInt1>, w: KslExpression<KslTypeInt1>) = KslValueInt4(xyz.x, xyz.y, xyz.z, w) fun bool2Value(x: Boolean, y: Boolean) = KslValueBool2(x, y) fun bool2Value(x: KslExpression<KslTypeBool1>, y: KslExpression<KslTypeBool1>) = KslValueBool2(x, y) fun bool3Value(x: Boolean, y: Boolean, z: Boolean) = KslValueBool3(x, y, z) fun bool3Value(x: KslExpression<KslTypeBool1>, y: KslExpression<KslTypeBool1>, z: KslExpression<KslTypeBool1>) = KslValueBool3(x, y, z) fun bool4Value(x: Boolean, y: Boolean, z: Boolean, w: Boolean) = KslValueBool4(x, y, z, w) fun bool4Value(x: KslExpression<KslTypeBool1>, y: KslExpression<KslTypeBool1>, z: KslExpression<KslTypeBool1>, w: KslExpression<KslTypeBool1>) = KslValueBool4(x, y, z, w) fun mat2Value(col0: KslVectorExpression<KslTypeFloat2, KslTypeFloat1>, col1: KslVectorExpression<KslTypeFloat2, KslTypeFloat1>) = KslValueMat2(col0, col1) fun mat3Value(col0: KslVectorExpression<KslTypeFloat3, KslTypeFloat1>, col1: KslVectorExpression<KslTypeFloat3, KslTypeFloat1>, col2: KslVectorExpression<KslTypeFloat3, KslTypeFloat1>) = KslValueMat3(col0, col1, col2) fun mat4Value(col0: KslVectorExpression<KslTypeFloat4, KslTypeFloat1>, col1: KslVectorExpression<KslTypeFloat4, KslTypeFloat1>, col2: KslVectorExpression<KslTypeFloat4, KslTypeFloat1>, col3: KslVectorExpression<KslTypeFloat4, KslTypeFloat1>) = KslValueMat4(col0, col1, col2, col3) @Deprecated("Use float1Var instead", replaceWith = ReplaceWith("float1Var(initValue, name)")) fun floatVar(initValue: KslScalarExpression<KslTypeFloat1>? = null, name: String? = null) = float1Var(initValue, name) @Deprecated("Use float1Array instead", replaceWith = ReplaceWith("float1Array(arraySize, initExpr, name)")) fun floatArray(arraySize: Int, initExpr: KslScalarExpression<KslTypeFloat1>, name: String? = null) = float1Array(arraySize, initExpr, name) @Deprecated("Use int1Var instead", replaceWith = ReplaceWith("int1Var(initValue, name)")) fun intVar(initValue: KslScalarExpression<KslTypeInt1>? = null, name: String? = null) = int1Var(initValue, name) @Deprecated("Use int1Array instead", replaceWith = ReplaceWith("int1Array(arraySize, initExpr, name)")) fun intArray(arraySize: Int, initExpr: KslScalarExpression<KslTypeInt1>, name: String? = null) = int1Array(arraySize, initExpr, name) @Deprecated("Use bool1Var instead", replaceWith = ReplaceWith("bool1Var(initValue, name)")) fun boolVar(initValue: KslScalarExpression<KslTypeBool1>? = null, name: String? = null) = bool1Var(initValue, name) fun float1Var(initValue: KslScalarExpression<KslTypeFloat1>? = null, name: String? = null) = KslVarScalar(name ?: nextName("f1"), KslTypeFloat1, true).also { ops += KslDeclareVar(it, initValue, this) } fun float2Var(initValue: KslVectorExpression<KslTypeFloat2, KslTypeFloat1>? = null, name: String? = null) = KslVarVector(name ?: nextName("f2"), KslTypeFloat2, true).also { ops += KslDeclareVar(it, initValue, this) } fun float3Var(initValue: KslVectorExpression<KslTypeFloat3, KslTypeFloat1>? = null, name: String? = null) = KslVarVector(name ?: nextName("f3"), KslTypeFloat3, true).also { ops += KslDeclareVar(it, initValue, this) } fun float4Var(initValue: KslVectorExpression<KslTypeFloat4, KslTypeFloat1>? = null, name: String? = null) = KslVarVector(name ?: nextName("f4"), KslTypeFloat4, true).also { ops += KslDeclareVar(it, initValue, this) } fun float1Array(arraySize: Int, initExpr: KslScalarExpression<KslTypeFloat1>, name: String? = null) = KslArrayScalar(name ?: nextName("f1Array"), KslTypeFloat1, arraySize, true).also { definedStates += it }.also { ops += KslDeclareArray(it, initExpr, this) } fun float2Array(arraySize: Int, initExpr: KslVectorExpression<KslTypeFloat2, KslTypeFloat1>, name: String? = null) = KslArrayVector(name ?: nextName("f2Array"), KslTypeFloat2, arraySize, true).also { definedStates += it }.also { ops += KslDeclareArray(it, initExpr, this) } fun float3Array(arraySize: Int, initExpr: KslVectorExpression<KslTypeFloat3, KslTypeFloat1>, name: String? = null) = KslArrayVector(name ?: nextName("f3Array"), KslTypeFloat3, arraySize, true).also { definedStates += it }.also { ops += KslDeclareArray(it, initExpr, this) } fun float4Array(arraySize: Int, initExpr: KslVectorExpression<KslTypeFloat4, KslTypeFloat1>, name: String? = null) = KslArrayVector(name ?: nextName("f4Array"), KslTypeFloat4, arraySize, true).also { definedStates += it }.also { ops += KslDeclareArray(it, initExpr, this) } fun int1Var(initValue: KslScalarExpression<KslTypeInt1>? = null, name: String? = null) = KslVarScalar(name ?: nextName("i1"), KslTypeInt1, true).also { ops += KslDeclareVar(it, initValue, this) } fun int2Var(initValue: KslVectorExpression<KslTypeInt2, KslTypeInt1>? = null, name: String? = null) = KslVarVector(name ?: nextName("i2"), KslTypeInt2, true).also { ops += KslDeclareVar(it, initValue, this) } fun int3Var(initValue: KslVectorExpression<KslTypeInt3, KslTypeInt1>? = null, name: String? = null) = KslVarVector(name ?: nextName("i3"), KslTypeInt3, true).also { ops += KslDeclareVar(it, initValue, this) } fun int4Var(initValue: KslVectorExpression<KslTypeInt4, KslTypeInt1>? = null, name: String? = null) = KslVarVector(name ?: nextName("i4"), KslTypeInt4, true).also { ops += KslDeclareVar(it, initValue, this) } fun uint1Var(initValue: KslScalarExpression<KslTypeUint1>? = null, name: String? = null) = KslVarScalar(name ?: nextName("u1"), KslTypeUint1, true).also { ops += KslDeclareVar(it, initValue, this) } fun uint2Var(initValue: KslVectorExpression<KslTypeUint2, KslTypeUint1>? = null, name: String? = null) = KslVarVector(name ?: nextName("u2"), KslTypeUint2, true).also { ops += KslDeclareVar(it, initValue, this) } fun uint3Var(initValue: KslVectorExpression<KslTypeUint3, KslTypeUint1>? = null, name: String? = null) = KslVarVector(name ?: nextName("u3"), KslTypeUint3, true).also { ops += KslDeclareVar(it, initValue, this) } fun uint4Var(initValue: KslVectorExpression<KslTypeUint4, KslTypeUint1>? = null, name: String? = null) = KslVarVector(name ?: nextName("u4"), KslTypeUint4, true).also { ops += KslDeclareVar(it, initValue, this) } fun int1Array(arraySize: Int, initExpr: KslScalarExpression<KslTypeInt1>, name: String? = null) = KslArrayScalar(name ?: nextName("i1Array"), KslTypeInt1, arraySize, true).also { definedStates += it }.also { ops += KslDeclareArray(it, initExpr, this) } fun int2Array(arraySize: Int, initExpr: KslVectorExpression<KslTypeInt2, KslTypeInt1>, name: String? = null) = KslArrayVector(name ?: nextName("i2Array"), KslTypeInt2, arraySize, true).also { definedStates += it }.also { ops += KslDeclareArray(it, initExpr, this) } fun int3Array(arraySize: Int, initExpr: KslVectorExpression<KslTypeInt3, KslTypeInt1>, name: String? = null) = KslArrayVector(name ?: nextName("i3Array"), KslTypeInt3, arraySize, true).also { definedStates += it }.also { ops += KslDeclareArray(it, initExpr, this) } fun int4Array(arraySize: Int, initExpr: KslVectorExpression<KslTypeInt4, KslTypeInt1>, name: String? = null) = KslArrayVector(name ?: nextName("i4Array"), KslTypeInt4, arraySize, true).also { definedStates += it }.also { ops += KslDeclareArray(it, initExpr, this) } fun bool1Var(initValue: KslScalarExpression<KslTypeBool1>? = null, name: String? = null) = KslVarScalar(name ?: nextName("b1"), KslTypeBool1, true).also { ops += KslDeclareVar(it, initValue, this) } fun bool2Var(initValue: KslVectorExpression<KslTypeBool2, KslTypeBool1>? = null, name: String? = null) = KslVarVector(name ?: nextName("b2"), KslTypeInt2, true).also { ops += KslDeclareVar(it, initValue, this) } fun bool3Var(initValue: KslVectorExpression<KslTypeBool3, KslTypeBool1>? = null, name: String? = null) = KslVarVector(name ?: nextName("b3"), KslTypeInt3, true).also { ops += KslDeclareVar(it, initValue, this) } fun bool4Var(initValue: KslVectorExpression<KslTypeBool4, KslTypeBool1>? = null, name: String? = null) = KslVarVector(name ?: nextName("b4"), KslTypeInt4, true).also { ops += KslDeclareVar(it, initValue, this) } fun mat2Var(initValue: KslMatrixExpression<KslTypeMat2, KslTypeFloat2>? = null, name: String? = null) = KslVarMatrix(name ?: nextName("m2"), KslTypeMat2, true).also { ops += KslDeclareVar(it, initValue, this) } fun mat3Var(initValue: KslMatrixExpression<KslTypeMat3, KslTypeFloat3>? = null, name: String? = null) = KslVarMatrix(name ?: nextName("m3"), KslTypeMat3, true).also { ops += KslDeclareVar(it, initValue, this) } fun mat4Var(initValue: KslMatrixExpression<KslTypeMat4, KslTypeFloat4>? = null, name: String? = null) = KslVarMatrix(name ?: nextName("m4"), KslTypeMat4, true).also { ops += KslDeclareVar(it, initValue, this) } infix fun <T: KslType> KslAssignable<T>.set(expression: KslExpression<T>) { ops += KslAssign(this, expression, this@KslScopeBuilder) } fun `if`(condition: KslExpression<KslTypeBool1>, block: KslScopeBuilder.() -> Unit): KslIf { val stmt = KslIf(condition, this).apply { body.block() } ops += stmt return stmt } fun fori(fromInclusive: KslScalarExpression<KslTypeInt1>, toExclusive: KslScalarExpression<KslTypeInt1>, block: KslScopeBuilder.(KslScalarExpression<KslTypeInt1>) -> Unit) { val i = int1Var(fromInclusive) `for`(i, i lt toExclusive, 1.const, block) } fun <T> `for`(loopVar: KslVarScalar<T>, whileExpr: KslScalarExpression<KslTypeBool1>, incExpr: KslScalarExpression<T>, block: KslScopeBuilder.(KslScalarExpression<T>) -> Unit) where T: KslNumericType, T: KslScalar { val loop = KslLoopFor(loopVar, whileExpr, incExpr, this).apply { body.block(loopVar) } ops += loop } fun `break`() { ops += KslLoopBreak(this) } fun `continue`() { ops += KslLoopContinue(this) } fun discard() { ops += KslDiscard(this) } fun <T> any(boolVec: KslVectorExpression<T, KslTypeBool1>) where T: KslBoolType, T: KslVector<KslTypeBool1> = KslBoolVectorExpr(boolVec, KslBoolVecOperator.Any) fun <T> all(boolVec: KslVectorExpression<T, KslTypeBool1>) where T: KslBoolType, T: KslVector<KslTypeBool1> = KslBoolVectorExpr(boolVec, KslBoolVecOperator.All) operator fun <T: KslType> KslAssignable<T>.plusAssign(expr: KslExpression<T>) { ops += KslAugmentedAssign(this, KslMathOperator.Plus, expr, this@KslScopeBuilder) } operator fun <T: KslType> KslAssignable<T>.minusAssign(expr: KslExpression<T>) { ops += KslAugmentedAssign(this, KslMathOperator.Minus, expr, this@KslScopeBuilder) } operator fun <T: KslType> KslAssignable<T>.timesAssign(expr: KslExpression<T>) { ops += KslAugmentedAssign(this, KslMathOperator.Times, expr, this@KslScopeBuilder) } operator fun <T: KslType> KslAssignable<T>.divAssign(expr: KslExpression<T>) { ops += KslAugmentedAssign(this, KslMathOperator.Divide, expr, this@KslScopeBuilder) } operator fun <T: KslType> KslAssignable<T>.remAssign(expr: KslExpression<T>) { ops += KslAugmentedAssign(this, KslMathOperator.Remainder, expr, this@KslScopeBuilder) } // function invocation operator fun <S> KslFunction<S>.invoke(vararg args: KslExpression<*>): KslScalarExpression<S> where S: KslType, S: KslScalar { return KslInvokeFunctionScalar(this, this@KslScopeBuilder, returnType, *args) } operator fun <V, S> KslFunction<V>.invoke(vararg args: KslExpression<*>): KslVectorExpression<V, S> where V: KslType, V: KslVector<S>, S: KslType, S: KslScalar { return KslInvokeFunctionVector(this, this@KslScopeBuilder, returnType, *args) } // builtin general functions fun <S> abs(value: KslScalarExpression<S>) where S: KslNumericType, S: KslScalar = KslBuiltinAbsScalar(value) fun <V, S> abs(vec: KslVectorExpression<V, S>) where V: KslNumericType, V: KslVector<S>, S: KslNumericType, S: KslScalar = KslBuiltinAbsVector(vec) fun atan2(y: KslScalarExpression<KslTypeFloat1>, x: KslScalarExpression<KslTypeFloat1>) = KslBuiltinAtan2Scalar(y, x) fun <V> atan2(y: KslVectorExpression<V, KslTypeFloat1>, x: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinAtan2Vector(y, x) fun ceil(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinCeilScalar(value) fun <V> ceil(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinCeilVector(vec) fun <S> clamp(value: KslScalarExpression<S>, min: KslScalarExpression<S>, max: KslScalarExpression<S>) where S: KslNumericType, S: KslScalar = KslBuiltinClampScalar(value, min, max) fun <V, S> clamp(vec: KslVectorExpression<V, S>, min: KslVectorExpression<V, S>, max: KslVectorExpression<V, S>) where V: KslNumericType, V: KslVector<S>, S: KslNumericType, S: KslScalar = KslBuiltinClampVector(vec, min, max) fun cross(a: KslVectorExpression<KslTypeFloat3, KslTypeFloat1>, b: KslVectorExpression<KslTypeFloat3, KslTypeFloat1>) = KslBuiltinCross(a, b) fun degrees(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinDegreesScalar(value) fun <V> degrees(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinDegreesVector(vec) fun <T: KslFloatType> distance(a: KslExpression<T>, b: KslExpression<T>) = KslBuiltinDistanceScalar(a, b) fun <V> dot(a: KslVectorExpression<V, KslTypeFloat1>, b: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinDot(a, b) fun exp(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinExpScalar(value) fun <V> exp(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinExpVector(vec) fun exp2(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinExpScalar(value) fun <V> exp2(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinExpVector(vec) fun <V> faceForward(a: KslVectorExpression<V, KslTypeFloat1>, b: KslVectorExpression<V, KslTypeFloat1>, c: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinFaceForward(a, b, c) fun floor(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinFloorScalar(value) fun <V> floor(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinFloorVector(vec) fun fma(a: KslScalarExpression<KslTypeFloat1>, b: KslScalarExpression<KslTypeFloat1>, c: KslScalarExpression<KslTypeFloat1>) = KslBuiltinFmaScalar(a, b, c) fun <V> fma(a: KslVectorExpression<V, KslTypeFloat1>, b: KslVectorExpression<V, KslTypeFloat1>, c: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinFmaVector(a, b, c) fun fract(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinFractScalar(value) fun <V> fract(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinFractVector(vec) fun inverseSqrt(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinInverseSqrtScalar(value) fun <V> inverseSqrt(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinInverseSqrtVector(vec) fun <V> length(arg: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinLength(arg) fun log(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinLogScalar(value) fun <V> log(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinLogVector(vec) fun log2(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinLog2Scalar(value) fun <V> log2(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinLog2Vector(vec) fun <S> max(a: KslScalarExpression<S>, b: KslScalarExpression<S>) where S: KslFloatType, S: KslScalar = KslBuiltinMaxScalar(a, b) fun <V, S> max(a: KslVectorExpression<V, S>, b: KslVectorExpression<V, S>) where V: KslFloatType, V: KslVector<S>, S: KslFloatType, S: KslScalar = KslBuiltinMaxVector(a, b) fun <S> min(a: KslScalarExpression<S>, b: KslScalarExpression<S>) where S: KslFloatType, S: KslScalar = KslBuiltinMinScalar(a, b) fun <V, S> min(a: KslVectorExpression<V, S>, b: KslVectorExpression<V, S>) where V: KslFloatType, V: KslVector<S>, S: KslFloatType, S: KslScalar = KslBuiltinMinVector(a, b) fun mix(x: KslScalarExpression<KslTypeFloat1>, y: KslScalarExpression<KslTypeFloat1>, a: KslScalarExpression<KslTypeFloat1>) = KslBuiltinMixScalar(x, y, a) fun <V> mix(x: KslVectorExpression<V, KslTypeFloat1>, y: KslVectorExpression<V, KslTypeFloat1>, a: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinMixVector(x, y, a) fun <V> mix(x: KslVectorExpression<V, KslTypeFloat1>, y: KslVectorExpression<V, KslTypeFloat1>, a: KslScalarExpression<KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinMixVector(x, y, a) fun <V> normalize(arg: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinNormalize(arg) fun pow(value: KslScalarExpression<KslTypeFloat1>, power: KslScalarExpression<KslTypeFloat1>) = KslBuiltinPowScalar(value, power) fun <V> pow(vec: KslVectorExpression<V, KslTypeFloat1>, power: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinPowVector(vec, power) fun radians(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinRadiansScalar(value) fun <V> radians(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinRadiansVector(vec) fun <V> reflect(a: KslVectorExpression<V, KslTypeFloat1>, b: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinReflect(a, b) fun <V> refract(a: KslVectorExpression<V, KslTypeFloat1>, b: KslVectorExpression<V, KslTypeFloat1>, i: KslScalarExpression<KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinRefract(a, b, i) fun round(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinRoundScalar(value) fun <V> round(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinRoundVector(vec) fun <S> sign(value: KslScalarExpression<S>) where S: KslNumericType, S: KslScalar = KslBuiltinSignScalar(value) fun <V, S> sign(vec: KslVectorExpression<V, S>) where V: KslNumericType, V: KslVector<S>, S: KslNumericType, S: KslScalar = KslBuiltinSignVector(vec) fun smoothStep(low: KslScalarExpression<KslTypeFloat1>, high: KslScalarExpression<KslTypeFloat1>, x: KslScalarExpression<KslTypeFloat1>) = KslBuiltinSmoothStepScalar(low, high, x) fun <V> smoothStep(low: KslVectorExpression<V, KslTypeFloat1>, high: KslVectorExpression<V, KslTypeFloat1>, x: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinSmoothStepVector(low, high, x) fun sqrt(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinSqrtScalar(value) fun <V> sqrt(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinSqrtVector(vec) fun step(edge: KslScalarExpression<KslTypeFloat1>, x: KslScalarExpression<KslTypeFloat1>) = KslBuiltinStepScalar(edge, x) fun <V> step(edge: KslVectorExpression<V, KslTypeFloat1>, x: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinStepVector(edge, x) fun trunc(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinTruncScalar(value) fun <V> trunc(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinTruncVector(vec) // builtin trigonometry functions fun cos(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinTrigonometryScalar(value, "cos") fun sin(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinTrigonometryScalar(value, "sin") fun tan(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinTrigonometryScalar(value, "tan") fun cosh(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinTrigonometryScalar(value, "cosh") fun sinh(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinTrigonometryScalar(value, "sinh") fun tanh(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinTrigonometryScalar(value, "tanh") fun <V> cos(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinTrigonometryVector(vec, "cos") fun <V> sin(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinTrigonometryVector(vec, "sin") fun <V> tan(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinTrigonometryVector(vec, "tan") fun <V> cosh(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinTrigonometryVector(vec, "cosh") fun <V> sinh(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinTrigonometryVector(vec, "sinh") fun <V> tanh(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinTrigonometryVector(vec, "tanh") fun acos(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinTrigonometryScalar(value, "acos") fun asin(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinTrigonometryScalar(value, "asin") fun atan(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinTrigonometryScalar(value, "atan") fun acosh(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinTrigonometryScalar(value, "acosh") fun asinh(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinTrigonometryScalar(value, "asinh") fun atanh(value: KslScalarExpression<KslTypeFloat1>) = KslBuiltinTrigonometryScalar(value, "atanh") fun <V> acos(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinTrigonometryVector(vec, "acos") fun <V> asin(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinTrigonometryVector(vec, "asin") fun <V> atan(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinTrigonometryVector(vec, "atan") fun <V> acosh(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinTrigonometryVector(vec, "acosh") fun <V> asinh(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinTrigonometryVector(vec, "asinh") fun <V> atanh(vec: KslVectorExpression<V, KslTypeFloat1>) where V: KslFloatType, V: KslVector<KslTypeFloat1> = KslBuiltinTrigonometryVector(vec, "atanh") // builtin matrix functions fun <M, V> determinant(matrix: KslMatrixExpression<M, V>) where M: KslFloatType, M: KslMatrix<V>, V: KslFloatType, V: KslVector<*> = KslBuiltinDeterminant(matrix) fun <M, V> transpose(matrix: KslMatrixExpression<M, V>) where M: KslFloatType, M: KslMatrix<V>, V: KslFloatType, V: KslVector<*> = KslBuiltinTranspose(matrix) // builtin texture functions fun <T: KslTypeColorSampler<C>, C: KslFloatType> sampleTexture(sampler: KslExpression<T>, coord: KslExpression<C>, lod: KslScalarExpression<KslTypeFloat1>? = null) = KslSampleColorTexture(sampler, coord, lod) fun <T: KslTypeDepthSampler<C>, C: KslFloatType> sampleDepthTexture(sampler: KslExpression<T>, coord: KslExpression<C>) = KslSampleDepthTexture(sampler, coord) /** * texelFetch — perform a lookup of a single texel within a texture * @param sampler Specifies the sampler to which the texture from which texels will be retrieved is bound. * @param coord Specifies the texture coordinates at which texture will be sampled. * @param lod If present, specifies the level-of-detail within the texture from which the texel will be fetched. */ fun <T: KslTypeColorSampler<R>, R : KslFloatType> texelFetch(sampler: KslExpression<T>, coord: KslExpression<*>, lod: KslScalarExpression<KslTypeInt1>? = null) = KslTexelFetch(sampler, coord, lod) fun <T> textureSize1d(sampler: KslExpression<T>, lod: KslScalarExpression<KslTypeInt1> = 0.const) where T: KslTypeSampler<*>, T: KslTypeSampler1d = KslTextureSize1d(sampler, lod) fun <T> textureSize2d(sampler: KslExpression<T>, lod: KslScalarExpression<KslTypeInt1> = 0.const) where T: KslTypeSampler<*>, T: KslTypeSampler2d = KslTextureSize2d(sampler, lod) fun <T> textureSize3d(sampler: KslExpression<T>, lod: KslScalarExpression<KslTypeInt1> = 0.const) where T: KslTypeSampler<*>, T: KslTypeSampler3d = KslTextureSize3d(sampler, lod) fun <T> textureSizeCube(sampler: KslExpression<T>, lod: KslScalarExpression<KslTypeInt1> = 0.const) where T: KslTypeSampler<*>, T: KslTypeSamplerCube = KslTextureSizeCube(sampler, lod) fun <T> textureSize2dArray(sampler: KslExpression<T>, lod: KslScalarExpression<KslTypeInt1> = 0.const) where T: KslTypeSampler<*>, T: KslTypeSampler2dArray = KslTextureSize2dArray(sampler, lod) fun <T> textureSizeCubeArray(sampler: KslExpression<T>, lod: KslScalarExpression<KslTypeInt1> = 0.const) where T: KslTypeSampler<*>, T: KslTypeSamplerCubeArray = KslTextureSizeCubeArray(sampler, lod) }
apache-2.0
abc89575be7928e1ab0622ed567ce4de
61.655039
186
0.703919
3.669164
false
false
false
false
leafclick/intellij-community
platform/workspaceModel-ide/src/com/intellij/workspace/jps/JpsLibraryEntitiesSerializer.kt
1
8025
package com.intellij.workspace.jps import com.intellij.openapi.util.JDOMUtil import com.intellij.workspace.api.* import com.intellij.workspace.ide.JpsFileEntitySource import com.intellij.workspace.legacyBridge.libraries.libraries.LegacyBridgeLibraryImpl import org.jdom.Element import org.jetbrains.jps.model.serialization.JDomSerializationUtil import org.jetbrains.jps.model.serialization.java.JpsJavaModelSerializerExtension import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer.* import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer internal class JpsLibrariesDirectorySerializerFactory(override val directoryUrl: String) : JpsDirectoryEntitiesSerializerFactory<LibraryEntity> { override val componentName: String get() = LIBRARY_TABLE_COMPONENT_NAME override fun getDefaultFileName(entity: LibraryEntity): String { return entity.name } override val entityClass: Class<LibraryEntity> get() = LibraryEntity::class.java override val entityFilter: (LibraryEntity) -> Boolean get() = { it.tableId == LibraryTableId.ProjectLibraryTableId } override fun createSerializer(fileUrl: String, entitySource: JpsFileEntitySource.FileInDirectory): JpsFileEntitiesSerializer<LibraryEntity> { return JpsLibraryEntitiesSerializer(VirtualFileUrlManager.fromUrl(fileUrl), entitySource, LibraryTableId.ProjectLibraryTableId) } } private const val LIBRARY_TABLE_COMPONENT_NAME = "libraryTable" internal class JpsLibrariesFileSerializer(fileUrl: VirtualFileUrl, entitySource: JpsFileEntitySource, libraryTableId: LibraryTableId) : JpsLibraryEntitiesSerializer(fileUrl, entitySource, libraryTableId), JpsFileEntityTypeSerializer<LibraryEntity> { override val entityFilter: (LibraryEntity) -> Boolean get() = { it.tableId == libraryTableId } } internal open class JpsLibraryEntitiesSerializer(override val fileUrl: VirtualFileUrl, override val entitySource: JpsFileEntitySource, protected val libraryTableId: LibraryTableId) : JpsFileEntitiesSerializer<LibraryEntity> { override val mainEntityClass: Class<LibraryEntity> get() = LibraryEntity::class.java override fun loadEntities(builder: TypedEntityStorageBuilder, reader: JpsFileContentReader) { val source = entitySource val libraryTableTag = reader.loadComponent(fileUrl.url, LIBRARY_TABLE_COMPONENT_NAME) ?: return for (libraryTag in libraryTableTag.getChildren(LIBRARY_TAG)) { val name = libraryTag.getAttributeValueStrict(JpsModuleRootModelSerializer.NAME_ATTRIBUTE) loadLibrary(name, libraryTag, libraryTableId, builder, source) } } override fun saveEntities(mainEntities: Collection<LibraryEntity>, entities: Map<Class<out TypedEntity>, List<TypedEntity>>, writer: JpsFileContentWriter): List<TypedEntity> { if (mainEntities.isEmpty()) { return emptyList() } val savedEntities = ArrayList<TypedEntity>() val componentTag = JDomSerializationUtil.createComponentElement(LIBRARY_TABLE_COMPONENT_NAME) mainEntities.sortedBy { it.name }.forEach { componentTag.addContent(saveLibrary(it, savedEntities)) } writer.saveComponent(fileUrl.url, LIBRARY_TABLE_COMPONENT_NAME, componentTag) return savedEntities } } private const val DEFAULT_JAR_DIRECTORY_TYPE = "CLASSES" internal fun loadLibrary(name: String, libraryElement: Element, libraryTableId: LibraryTableId, builder: TypedEntityStorageBuilder, source: EntitySource): LibraryEntity { val roots = ArrayList<LibraryRoot>() val excludedRoots = ArrayList<VirtualFileUrl>() val jarDirectories = libraryElement.getChildren(JAR_DIRECTORY_TAG).associateBy( { Pair(it.getAttributeValue(JpsModuleRootModelSerializer.TYPE_ATTRIBUTE) ?: DEFAULT_JAR_DIRECTORY_TYPE, it.getAttributeValueStrict(JpsModuleRootModelSerializer.URL_ATTRIBUTE)) }, { if (it.getAttributeValue(RECURSIVE_ATTRIBUTE)?.toBoolean() == true) LibraryRoot.InclusionOptions.ARCHIVES_UNDER_ROOT_RECURSIVELY else LibraryRoot.InclusionOptions.ARCHIVES_UNDER_ROOT } ) val type = libraryElement.getAttributeValue("type") var properties: String? = null for (childElement in libraryElement.children) { when (childElement.name) { "excluded" -> excludedRoots.addAll( childElement.getChildren(JpsJavaModelSerializerExtension.ROOT_TAG) .map { it.getAttributeValueStrict(JpsModuleRootModelSerializer.URL_ATTRIBUTE) } .map { VirtualFileUrlManager.fromUrl(it) } ) PROPERTIES_TAG -> { properties = JDOMUtil.write(childElement) } JAR_DIRECTORY_TAG -> { } else -> { val rootType = childElement.name for (rootTag in childElement.getChildren(JpsJavaModelSerializerExtension.ROOT_TAG)) { val url = rootTag.getAttributeValueStrict(JpsModuleRootModelSerializer.URL_ATTRIBUTE) val inclusionOptions = jarDirectories[Pair(rootType, url)] ?: LibraryRoot.InclusionOptions.ROOT_ITSELF roots.add(LibraryRoot(VirtualFileUrlManager.fromUrl(url), LibraryRootTypeId(rootType), inclusionOptions)) } } } } val libraryEntity = builder.addLibraryEntity(name, libraryTableId, roots, excludedRoots, source) if (type != null) { builder.addLibraryPropertiesEntity(libraryEntity, type, properties, source) } return libraryEntity } internal fun saveLibrary(library: LibraryEntity, savedEntities: MutableList<TypedEntity>): Element { savedEntities.add(library) val libraryTag = Element(LIBRARY_TAG) val legacyName = LegacyBridgeLibraryImpl.getLegacyLibraryName(library.persistentId()) if (legacyName != null) { libraryTag.setAttribute(NAME_ATTRIBUTE, legacyName) } val customProperties = library.getCustomProperties() if (customProperties != null) { savedEntities.add(customProperties) libraryTag.setAttribute(TYPE_ATTRIBUTE, customProperties.libraryType) val propertiesXmlTag = customProperties.propertiesXmlTag if (propertiesXmlTag != null) { libraryTag.addContent(JDOMUtil.load(propertiesXmlTag)) } } val rootsMap = library.roots.groupByTo(HashMap()) { it.type } ROOT_TYPES_TO_WRITE_EMPTY_TAG.forEach { rootsMap.putIfAbsent(it, ArrayList()) } val jarDirectoriesTags = ArrayList<Element>() rootsMap.entries.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) {it.key.name}).forEach { (rootType, roots) -> val rootTypeTag = Element(rootType.name) roots.forEach { rootTypeTag.addContent(Element(ROOT_TAG).setAttribute(JpsModuleRootModelSerializer.URL_ATTRIBUTE, it.url.url)) } roots.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) {it.url.url}).forEach { if (it.inclusionOptions != LibraryRoot.InclusionOptions.ROOT_ITSELF) { val jarDirectoryTag = Element(JAR_DIRECTORY_TAG) jarDirectoryTag.setAttribute(JpsModuleRootModelSerializer.URL_ATTRIBUTE, it.url.url) jarDirectoryTag.setAttribute(RECURSIVE_ATTRIBUTE, (it.inclusionOptions == LibraryRoot.InclusionOptions.ARCHIVES_UNDER_ROOT_RECURSIVELY).toString()) if (rootType.name != DEFAULT_JAR_DIRECTORY_TYPE) { jarDirectoryTag.setAttribute(TYPE_ATTRIBUTE, rootType.name) } jarDirectoriesTags.add(jarDirectoryTag) } } libraryTag.addContent(rootTypeTag) } val excludedRoots = library.excludedRoots if (excludedRoots.isNotEmpty()) { val excludedTag = Element("excluded") excludedRoots.forEach { excludedTag.addContent(Element(ROOT_TAG).setAttribute(JpsModuleRootModelSerializer.URL_ATTRIBUTE, it.url)) } libraryTag.addContent(excludedTag) } jarDirectoriesTags.forEach { libraryTag.addContent(it) } return libraryTag } private val ROOT_TYPES_TO_WRITE_EMPTY_TAG = listOf("CLASSES", "SOURCES", "JAVADOC").map { LibraryRootTypeId(it) }
apache-2.0
eed717f2dfd57e161e01a6c1ee90f816
44.602273
155
0.744299
5.066288
false
false
false
false
Zhouzhouzhou/AndroidDemo
app/src/main/java/com/zhou/android/kotlin/NtpTimeActivity.kt
1
9012
package com.zhou.android.kotlin import android.os.Handler import android.os.SystemClock import android.util.Log import com.zhou.android.R import com.zhou.android.common.BaseActivity import kotlinx.android.synthetic.main.activity_ntp_time.* import java.net.DatagramPacket import java.net.DatagramSocket import java.net.InetAddress import java.text.SimpleDateFormat import java.util.* import kotlin.experimental.and /** * android.net.SntpClient 获取网络时间的部分代码<Br/> * 经测试,系统同步时间很慢,不是网络不通问题,在时间迟迟不更新调用这部分代码是可以获取到时间 * * 部分源码地址<Br/> * * @see <a href="https://www.androidos.net.cn/android/6.0.1_r16/xref/frameworks/base/services/core/java/com/android/server/NetworkTimeUpdateService.java">NetworkTimeUpdateService</a> * @see <a href="https://www.androidos.net.cn/android/6.0.1_r16/xref/frameworks/base/core/java/android/util/NtpTrustedTime.java">NtpTrustedTime</a> * 所以应该是恰好触发 NetworkTimeUpdateService 判断逻辑bug,导致更新时间事件一直被往后延 * * Created by mxz on 2019/7/31. */ class NtpTimeActivity : BaseActivity() { private val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS", Locale.getDefault()) private val handler = Handler { text.append("${it.obj}\n") true } override fun setContentView() { setContentView(R.layout.activity_ntp_time) } override fun init() { } override fun addListener() { btnRequest.setOnClickListener { text.append("start request \n") Thread(Runnable { requestTime() }).start() } } private val REFERENCE_TIME_OFFSET = 16 private val ORIGINATE_TIME_OFFSET = 24 private val RECEIVE_TIME_OFFSET = 32 private val TRANSMIT_TIME_OFFSET = 40 private val NTP_PACKET_SIZE = 48 private val NTP_PORT = 123 private val NTP_MODE_CLIENT = 3 private val NTP_MODE_SERVER = 4 private val NTP_MODE_BROADCAST = 5 private val NTP_VERSION = 3 private val NTP_LEAP_NOSYNC = 3 private val NTP_STRATUM_DEATH = 0 private val NTP_STRATUM_MAX = 15 private val OFFSET_1900_TO_1970 = (365L * 70L + 17L) * 24L * 60L * 60L // system time computed from NTP server response private var mNtpTime: Long = 0 // value of SystemClock.elapsedRealtime() corresponding to mNtpTime private var mNtpTimeReference: Long = 0 // round trip time in milliseconds private var mRoundTripTime: Long = 0 private val DBG = true private val TAG = "zhou" private fun requestTime() { var address: InetAddress? = null try { address = InetAddress.getByName("time.gionee.com") } catch (e: Exception) { Log.d(TAG, "request time failed: $e") sendMsg("request time failed: $e") return } requestTime(address, 123, 5000) } private fun requestTime(address: InetAddress, port: Int, timeout: Int): Boolean { Log.d(TAG, "requestTime running") var socket: DatagramSocket? = null // val oldTag = TrafficStats.getAndSetThreadStatsTag(TrafficStats.TAG_SYSTEM_NTP) try { socket = DatagramSocket() socket.soTimeout = timeout val buffer = ByteArray(NTP_PACKET_SIZE) val request = DatagramPacket(buffer, buffer.size, address, port) // set mode = 3 (client) and version = 3 // mode is in low 3 bits of first byte // version is in bits 3-5 of first byte buffer[0] = (NTP_MODE_CLIENT or (NTP_VERSION shl 3)).toInt().toByte() // get current time and write it to the request packet val requestTime = System.currentTimeMillis() val requestTicks = SystemClock.elapsedRealtime() writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime) socket.send(request) // read the response val response = DatagramPacket(buffer, buffer.size) socket.receive(response) val responseTicks = SystemClock.elapsedRealtime() val responseTime = requestTime + (responseTicks - requestTicks) // extract the results val leap = (buffer[0].toInt() shr 6 and 0x3).toInt().toByte() val mode = (buffer[0] and 0x7) val stratum = (buffer[1].toInt() and 0xff) val originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET) val receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET) val transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET) /* do sanity check according to RFC */ checkValidServerReply(leap, mode, stratum, transmitTime) val roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime) val clockOffset = (receiveTime - originateTime + (transmitTime - responseTime)) / 2 Log.d( TAG, "round trip: " + roundTripTime + "ms, " + "clock offset: " + clockOffset + "ms" ) // save our results - use the times on this side of the network latency // (response rather than request time) mNtpTime = responseTime + clockOffset mNtpTimeReference = responseTicks mRoundTripTime = roundTripTime sendMsg( "success >> mNtpTime: $mNtpTime, mRoundTripTime: $mRoundTripTime \n格式化 >> ${ formatter.format( mNtpTime ) }" ) Log.d( "zhou", "success >> mNtpTime: $mNtpTime, mRoundTripTime: $mRoundTripTime, mNtpTimeReference: $mNtpTimeReference" ) } catch (e: Exception) { if (DBG) Log.d(TAG, "request time failed: $e") sendMsg("request time failed: $e") return false } finally { socket?.close() } return true } private fun writeTimeStamp(buffer: ByteArray, offset: Int, time: Long) { var offset = offset // Special case: zero means zero. if (time == 0L) { Arrays.fill(buffer, offset, offset + 8, 0x00.toByte()) return } var seconds = time / 1000L val milliseconds = time - seconds * 1000L seconds += OFFSET_1900_TO_1970 // write seconds in big endian format buffer[offset++] = (seconds shr 24).toInt().toByte() buffer[offset++] = (seconds shr 16).toInt().toByte() buffer[offset++] = (seconds shr 8).toInt().toByte() buffer[offset++] = (seconds shr 0).toInt().toByte() val fraction = milliseconds * 0x100000000L / 1000L // write fraction in big endian format buffer[offset++] = (fraction shr 24).toInt().toByte() buffer[offset++] = (fraction shr 16).toInt().toByte() buffer[offset++] = (fraction shr 8).toInt().toByte() // low order bits should be random data buffer[offset++] = (Math.random() * 255.0).toInt().toByte() } private fun readTimeStamp(buffer: ByteArray, offset: Int): Long { val seconds = read32(buffer, offset) val fraction = read32(buffer, offset + 4) // Special case: zero means zero. return if (seconds == 0L && fraction == 0L) { 0 } else (seconds - OFFSET_1900_TO_1970) * 1000 + fraction * 1000L / 0x100000000L } private fun read32(buffer: ByteArray, offset: Int): Long { val b0 = buffer[offset].toInt() val b1 = buffer[offset + 1].toInt() val b2 = buffer[offset + 2].toInt() val b3 = buffer[offset + 3].toInt() // convert signed bytes to unsigned values val i0 = if (b0 and 0x80 == 0x80) (b0 and 0x7F) + 0x80 else b0 val i1 = if (b1 and 0x80 == 0x80) (b1 and 0x7F) + 0x80 else b1 val i2 = if (b2 and 0x80 == 0x80) (b2 and 0x7F) + 0x80 else b2 val i3 = if (b3 and 0x80 == 0x80) (b3 and 0x7F) + 0x80 else b3 return (i0.toLong() shl 24) + (i1.toLong() shl 16) + (i2.toLong() shl 8) + i3.toLong() } @Throws(Exception::class) private fun checkValidServerReply( leap: Byte, mode: Byte, stratum: Int, transmitTime: Long ) { if (leap.toInt() == NTP_LEAP_NOSYNC) { throw Exception("unsynchronized server") } if (mode.toInt() != NTP_MODE_SERVER && mode.toInt() != NTP_MODE_BROADCAST) { throw Exception("untrusted mode: $mode") } if (stratum == NTP_STRATUM_DEATH || stratum > NTP_STRATUM_MAX) { throw Exception("untrusted stratum: $stratum") } if (transmitTime == 0L) { throw Exception("zero transmitTime") } } private fun sendMsg(data: String) { val msg = handler.obtainMessage() msg.obj = data msg.sendToTarget() } }
mit
4741ffe537a188926ba1df77da9d95a9
35.626556
182
0.603898
3.966742
false
false
false
false
siosio/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/AddDiffOperation.kt
1
16867
// Copyright 2000-2020 JetBrains s.r.o. Use of target source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl import com.google.common.collect.HashBiMap import com.google.common.collect.HashMultimap import com.intellij.openapi.diagnostic.logger import com.intellij.workspaceModel.storage.WorkspaceEntity import java.io.File internal class AddDiffOperation(val target: WorkspaceEntityStorageBuilderImpl, val diff: WorkspaceEntityStorageBuilderImpl) { private val replaceMap = HashBiMap.create<NotThisEntityId, ThisEntityId>() private val diffLog = diff.changeLog.changeLog // Initial storage is required in case something will fail and we need to send a report private val initialStorage = if (ConsistencyCheckingMode.current != ConsistencyCheckingMode.DISABLED) target.toStorage() else null fun addDiff() { if (target === diff) LOG.error("Trying to apply diff to itself") for ((_, change) in diffLog) { when (change) { is ChangeEntry.AddEntity<out WorkspaceEntity> -> { @Suppress("UNCHECKED_CAST") change as ChangeEntry.AddEntity<WorkspaceEntity> checkPersistentId(change.entityData, null) val sourceEntityId = change.entityData.createEntityId().notThis() // Adding new entity val targetEntityData: WorkspaceEntityData<WorkspaceEntity> val targetEntityId: ThisEntityId val idFromReplaceMap = replaceMap[sourceEntityId] if (idFromReplaceMap != null) { // Okay, we need to add the entity at the particular id targetEntityData = target.entitiesByType.cloneAndAddAt(change.entityData, idFromReplaceMap.id) targetEntityId = idFromReplaceMap } else { // Add new entity to store (without references) targetEntityData = target.entitiesByType.cloneAndAdd(change.entityData, change.clazz) targetEntityId = targetEntityData.createEntityId().asThis() replaceMap[sourceEntityId] = targetEntityId } // Restore links to soft references if (targetEntityData is SoftLinkable) target.indexes.updateSoftLinksIndex(targetEntityData) addRestoreChildren(sourceEntityId, targetEntityId) // Restore parent references addRestoreParents(sourceEntityId, targetEntityId) target.indexes.updateIndices(change.entityData.createEntityId(), targetEntityData, diff) target.changeLog.addAddEvent(targetEntityId.id, targetEntityData) } is ChangeEntry.RemoveEntity -> { val sourceEntityId = change.id.asThis() // This sourceEntityId is definitely not presented in replaceMap as a key, so we can just remove this entity from target // with this id. But there is a case when some different entity from source builder will get this id if there was a gup before. // So we should check if entity at this id was added in this transaction. If replaceMap has a value with this entity id // this means that this entity was added in this transaction and there was a gup before and we should not remove anything. if (!replaceMap.containsValue(sourceEntityId)) { target.indexes.removeFromIndices(sourceEntityId.id) if (target.entityDataById(sourceEntityId.id) != null) { target.removeEntity(sourceEntityId.id) } } } is ChangeEntry.ReplaceEntity<out WorkspaceEntity> -> { replaceOperation(change) } is ChangeEntry.ChangeEntitySource<out WorkspaceEntity> -> { replaceSourceOperation(change.newData) } is ChangeEntry.ReplaceAndChangeSource<out WorkspaceEntity> -> { replaceOperation(change.dataChange) replaceSourceOperation(change.sourceChange.newData) } } } target.indexes.applyExternalMappingChanges(diff, replaceMap, target) // Assert consistency if (!target.brokenConsistency && !diff.brokenConsistency) { target.assertConsistencyInStrictMode("Check after add Diff", null, initialStorage, diff) } else { target.brokenConsistency = true } } private fun replaceSourceOperation(data: WorkspaceEntityData<out WorkspaceEntity>) { val outdatedId = data.createEntityId().notThis() val usedPid = replaceMap.getOrDefault(outdatedId, outdatedId.id.asThis()) // We don't modify entity that isn't exist in target version of storage val existingEntityData = target.entityDataById(usedPid.id) if (existingEntityData != null) { val newEntitySource = data.entitySource existingEntityData.entitySource = newEntitySource target.indexes.entitySourceIndex.index(usedPid.id, newEntitySource) target.changeLog.addChangeSourceEvent(usedPid.id, existingEntityData) } } private fun addRestoreParents(sourceEntityId: NotThisEntityId, targetEntityId: ThisEntityId) { val allParents = diff.refs.getParentRefsOfChild(sourceEntityId.id.asChild()) for ((connectionId, sourceParentId) in allParents) { val targetParentId: ThisEntityId? = if (diffLog[sourceParentId.id] is ChangeEntry.AddEntity<*>) { replaceMap[sourceParentId.id.notThis()] ?: run { // target entity isn't added to the current builder yet. Add a placeholder val placeholderId = target.entitiesByType.book(sourceParentId.id.clazz).asThis() replaceMap[sourceParentId.id.notThis()] = placeholderId placeholderId } } else { if (target.entityDataById(sourceParentId.id) != null) sourceParentId.id.asThis() else { if (!connectionId.canRemoveParent()) { target.addDiffAndReport("Cannot restore dependency. $connectionId, $sourceParentId.id", initialStorage, diff) } null } } if (targetParentId != null) { target.refs.updateParentOfChild(connectionId, targetEntityId.id.asChild(), targetParentId.id.asParent()) } } } private fun addRestoreChildren(sourceEntityId: NotThisEntityId, targetEntityId: ThisEntityId) { // Restore children references val allSourceChildren = diff.refs.getChildrenRefsOfParentBy(sourceEntityId.id.asParent()) for ((connectionId, sourceChildrenIds) in allSourceChildren) { val targetChildrenIds = mutableListOf<ChildEntityId>() for (sourceChildId in sourceChildrenIds) { if (diffLog[sourceChildId.id] is ChangeEntry.AddEntity<*>) { // target particular entity is added in the same transaction. val possibleTargetChildId = replaceMap[sourceChildId.id.notThis()] if (possibleTargetChildId != null) { // Entity was already added to the structure targetChildrenIds += possibleTargetChildId.id.asChild() } else { // target entity isn't added yet. Add a placeholder val placeholderId = target.entitiesByType.book(sourceChildId.id.clazz).asThis() replaceMap[sourceChildId.id.notThis()] = placeholderId targetChildrenIds += placeholderId.id.asChild() } } else { if (target.entityDataById(sourceChildId.id) != null) { targetChildrenIds += sourceChildId } } } target.refs.updateChildrenOfParent(connectionId, targetEntityId.id.asParent(), targetChildrenIds) } } private fun replaceOperation(change: ChangeEntry.ReplaceEntity<out WorkspaceEntity>) { @Suppress("UNCHECKED_CAST") change as ChangeEntry.ReplaceEntity<WorkspaceEntity> val sourceEntityId = change.newData.createEntityId().notThis() val beforeChildren = target.refs.getChildrenRefsOfParentBy(sourceEntityId.id.asParent()).flatMap { (key, value) -> value.map { key to it } } val beforeParents = target.refs.getParentRefsOfChild(sourceEntityId.id.asChild()) val targetEntityId = replaceMap.getOrDefault(sourceEntityId, sourceEntityId.id.asThis()) val newTargetEntityData = change.newData.clone() newTargetEntityData.id = targetEntityId.id.arrayId checkPersistentId(change.newData, newTargetEntityData.createEntityId()) // We don't modify entity that doesn't exist in target version of storage val existingTargetEntityData = target.entityDataById(targetEntityId.id) ?: return // Replace entity doesn't modify entitySource newTargetEntityData.entitySource = existingTargetEntityData.entitySource target.indexes.updateIndices(sourceEntityId.id, newTargetEntityData, diff) val newEntityId = newTargetEntityData.createEntityId() val oldPersistentId = target.entityDataById(newEntityId)?.persistentId(target) /// Replace entity data. id should not be changed target.entitiesByType.replaceById(newTargetEntityData, sourceEntityId.id.clazz) // Restore soft references target.updatePersistentIdIndexes(newTargetEntityData.createEntity(target), oldPersistentId, newTargetEntityData) val addedChildrenMap = HashMultimap.create<ConnectionId, ChildEntityId>() change.newChildren.forEach { addedChildrenMap.put(it.first, it.second) } val removedChildrenMap = HashMultimap.create<ConnectionId, ChildEntityId>() change.removedChildren.forEach { removedChildrenMap.put(it.first, it.second) } replaceRestoreChildren(sourceEntityId.id.asParent(), newEntityId.asParent(), addedChildrenMap, removedChildrenMap) replaceRestoreParents(change, newEntityId) WorkspaceEntityStorageBuilderImpl.addReplaceEvent(target, sourceEntityId.id, beforeChildren, beforeParents, newTargetEntityData) } private fun replaceRestoreChildren( sourceEntityId: ParentEntityId, newEntityId: ParentEntityId, addedChildrenMap: HashMultimap<ConnectionId, ChildEntityId>, removedChildrenMap: HashMultimap<ConnectionId, ChildEntityId>, ) { val existingChildren = target.refs.getChildrenRefsOfParentBy(newEntityId) for ((connectionId, children) in existingChildren) { if (connectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY) { val sourceChildren = this.diff.refs.getChildrenRefsOfParentBy(sourceEntityId)[connectionId] ?: emptyList() val updatedChildren = sourceChildren.mapNotNull { childrenMapper(it) } if (updatedChildren != children) { target.refs.updateChildrenOfParent(connectionId, newEntityId, updatedChildren) } } else { // Take current children.... val mutableChildren = children.toMutableList() val addedChildrenSet = addedChildrenMap[connectionId] ?: emptySet() val updatedAddedChildren = addedChildrenSet.mapNotNull { childrenMapper(it) } mutableChildren.addAll(updatedAddedChildren) val removedChildrenSet = removedChildrenMap[connectionId] ?: emptySet() for (removedChild in removedChildrenSet) { // This method may return false if this child is already removed mutableChildren.remove(removedChild) } // .... Update if something changed if (children != mutableChildren) { target.refs.updateChildrenOfParent(connectionId, newEntityId, mutableChildren) } } addedChildrenMap.removeAll(connectionId) removedChildrenMap.removeAll(connectionId) } // N.B: removedChildrenMap may contain some entities, but this means that these entities was already removed // Do we have more children to add? Add them for ((connectionId, children) in addedChildrenMap.asMap()) { val mutableChildren = children.toMutableList() val updatedChildren = children.mapNotNull { childrenMapper(it) } mutableChildren.addAll(updatedChildren) target.refs.updateChildrenOfParent(connectionId, newEntityId, mutableChildren) } } private fun childrenMapper(child: ChildEntityId): ChildEntityId? { return if (diffLog[child.id] is ChangeEntry.AddEntity<*>) { val possibleNewChildId = replaceMap[child.id.notThis()] if (possibleNewChildId != null) { possibleNewChildId.id.asChild() } else { val bookedChildId = target.entitiesByType.book(child.id.clazz) replaceMap[child.id.notThis()] = bookedChildId.asThis() bookedChildId.asChild() } } else { if (target.entityDataById(child.id) != null) { child } else null } } private fun replaceRestoreParents( change: ChangeEntry.ReplaceEntity<out WorkspaceEntity>, newEntityId: EntityId, ) { val updatedModifiedParents = change.modifiedParents.mapValues { it.value } val modifiedParentsMap = updatedModifiedParents.toMutableMap() val newChildEntityId = newEntityId.asChild() val existingParents = target.refs.getParentRefsOfChild(newChildEntityId) for ((connectionId, existingParent) in existingParents) { if (connectionId in modifiedParentsMap) { val newParent = modifiedParentsMap.getValue(connectionId) if (newParent == null) { // target child doesn't have a parent anymore if (!connectionId.canRemoveParent()) target.addDiffAndReport("Cannot restore some dependencies; $connectionId", initialStorage, diff) else target.refs.removeParentToChildRef(connectionId, existingParent, newChildEntityId) } else { if (diffLog[newParent.id] is ChangeEntry.AddEntity<*>) { var possibleNewParent = replaceMap[newParent.id.notThis()] if (possibleNewParent == null) { possibleNewParent = target.entitiesByType.book(newParent.id.clazz).asThis() replaceMap[newParent.id.notThis()] = possibleNewParent } target.refs.updateParentOfChild(connectionId, newEntityId.asChild(), possibleNewParent.id.asParent()) } else { if (target.entityDataById(newParent.id) != null) { target.refs.updateParentOfChild(connectionId, newEntityId.asChild(), newParent) } else { if (!connectionId.canRemoveParent()) target.addDiffAndReport("Cannot restore some dependencies; $connectionId", initialStorage, diff) target.refs.removeParentToChildRef(connectionId, existingParent, newChildEntityId) } } } modifiedParentsMap.remove(connectionId) } } // Any new parents? Add them for ((connectionId, parentId) in modifiedParentsMap) { if (parentId == null) continue if (diffLog[parentId.id] is ChangeEntry.AddEntity<*>) { var possibleNewParent = replaceMap[parentId.id.notThis()] if (possibleNewParent == null) { possibleNewParent = target.entitiesByType.book(parentId.id.clazz).asThis() replaceMap[parentId.id.notThis()] = possibleNewParent } target.refs.updateParentOfChild(connectionId, newEntityId.asChild(), possibleNewParent.id.asParent()) } else { if (target.entityDataById(parentId.id) != null) { target.refs.updateParentOfChild(connectionId, newEntityId.asChild(), parentId) } } } } private fun checkPersistentId(entityData: WorkspaceEntityData<WorkspaceEntity>, newEntityId: EntityId?) { val newPersistentId = entityData.persistentId(target) if (newPersistentId != null) { val existingIds = target.indexes.persistentIdIndex.getIdsByEntry(newPersistentId) if (existingIds != null) { val existingIdCheck = if (newEntityId != null) existingIds != newEntityId else true if (existingIdCheck) { // target persistent id exists already. val existingEntityData = target.entityDataByIdOrDie(existingIds) target.removeEntity(existingEntityData.createEntity(target)) target.addDiffAndReport( """ Persistent ID already exists. Removing old entity Persistent ID: $newPersistentId Existing entity data: $existingEntityData New entity data: $entityData """.trimIndent(), initialStorage, diff) } } } } // For serializing current model during the debug process @Suppress("unused") private fun serialize(path: String) { val folder = File(path) target.serializeTo(folder.resolve("Instant_Save_Target").outputStream()) diff.serializeTo(folder.resolve("Instant_Save_Source").outputStream()) diff.serializeDiff(folder.resolve("Instant_Save_Diff").outputStream()) } companion object { private val LOG = logger<AddDiffOperation>() } }
apache-2.0
20ecb29a6a929fb818e88e933ef5888a
43.742706
144
0.692417
4.911765
false
false
false
false
LateNightProductions/CardKeeper
app/src/main/java/com/awscherb/cardkeeper/ui/scan/ScanFragment.kt
1
4358
package com.awscherb.cardkeeper.ui.scan import android.Manifest import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.text.InputType import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import androidx.appcompat.app.AlertDialog import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.awscherb.cardkeeper.R import com.awscherb.cardkeeper.data.model.ScannedCode import com.awscherb.cardkeeper.ui.base.BaseFragment import com.google.zxing.ResultPoint import com.journeyapps.barcodescanner.BarcodeCallback import com.journeyapps.barcodescanner.BarcodeResult import com.journeyapps.barcodescanner.CompoundBarcodeView import java.util.concurrent.atomic.AtomicBoolean import javax.inject.Inject class ScanFragment : BaseFragment() { private val viewModel by viewModels<ScanViewModel> { factory } @Inject lateinit var factory: ScanViewModelFactory private lateinit var scannerView: CompoundBarcodeView private val found = AtomicBoolean(false) //================================================================================ // Lifecycle methods //================================================================================ override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View = inflater.inflate(R.layout.fragment_scan, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewComponent.inject(this) scannerView = view.findViewById(R.id.fragment_scan_scanner) // Check permissions if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (activity?.checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { scannerView.resume() } else { requestPermissions( arrayOf(Manifest.permission.CAMERA), REQUEST_CAMERA ) } } // Setup scanner setCallback() viewModel.createResult.observe(viewLifecycleOwner) { onCodeAdded() } } override fun onResume() { super.onResume() scannerView.resume() } override fun onPause() { super.onPause() scannerView.pause() } private fun onCodeAdded() { findNavController().navigate( ScanFragmentDirections.actionScanFragmentToCardsFragment() ) } // ======================================================================== // Helper methods // ======================================================================== private fun setCallback() { val callback = object : BarcodeCallback { override fun barcodeResult(result: BarcodeResult) { if (found.compareAndSet(false, true)) { val input = EditText(activity).apply { setHint(R.string.dialog_card_name_hint) inputType = InputType.TYPE_TEXT_FLAG_CAP_WORDS } AlertDialog.Builder(activity!!) .setTitle(R.string.app_name) .setView(input) .setOnDismissListener { found.set(false) } .setPositiveButton(R.string.action_add) { _, _ -> viewModel.createData.postValue( CreateCodeData( format = result.barcodeFormat, text = result.text, title = input.text.toString() ) ) } .setNegativeButton(R.string.action_cancel) { dialog, _ -> dialog.dismiss() } .show() } } override fun possibleResultPoints(resultPoints: List<ResultPoint>) {} } scannerView.decodeContinuous(callback) } companion object { private const val REQUEST_CAMERA = 16 } }
apache-2.0
0de507dc2782a2b7a0589041deeddc22
32.782946
113
0.559431
5.509482
false
false
false
false
siosio/intellij-community
plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/frontend/api/fir/symbols/KtFirFunctionSymbol.kt
2
5390
/* * 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.frontend.api.fir.symbols import com.intellij.psi.PsiElement import org.jetbrains.kotlin.fir.containingClass import org.jetbrains.kotlin.fir.declarations.* import org.jetbrains.kotlin.idea.fir.findPsi import org.jetbrains.kotlin.idea.fir.low.level.api.api.FirModuleResolveState import org.jetbrains.kotlin.idea.frontend.api.ValidityToken import org.jetbrains.kotlin.idea.frontend.api.fir.KtSymbolByFirBuilder import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.annotations.containsAnnotation import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.annotations.getAnnotationClassIds import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.annotations.toAnnotationsList import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.pointers.KtFirMemberFunctionSymbolPointer import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.pointers.createSignature import org.jetbrains.kotlin.idea.frontend.api.fir.utils.cached import org.jetbrains.kotlin.idea.frontend.api.fir.utils.firRef import org.jetbrains.kotlin.idea.frontend.api.symbols.KtFunctionSymbol import org.jetbrains.kotlin.idea.frontend.api.symbols.markers.* import org.jetbrains.kotlin.idea.frontend.api.symbols.pointers.CanNotCreateSymbolPointerForLocalLibraryDeclarationException import org.jetbrains.kotlin.idea.frontend.api.symbols.pointers.KtPsiBasedSymbolPointer import org.jetbrains.kotlin.idea.frontend.api.symbols.pointers.KtSymbolPointer import org.jetbrains.kotlin.idea.frontend.api.types.KtType import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name internal class KtFirFunctionSymbol( fir: FirSimpleFunction, resolveState: FirModuleResolveState, override val token: ValidityToken, private val builder: KtSymbolByFirBuilder ) : KtFunctionSymbol(), KtFirSymbol<FirSimpleFunction> { override val firRef = firRef(fir, resolveState) override val psi: PsiElement? by firRef.withFirAndCache { fir -> fir.findPsi(fir.session) } override val name: Name get() = firRef.withFir { it.name } override val annotatedType: KtTypeAndAnnotations by cached { firRef.returnTypeAndAnnotations(FirResolvePhase.IMPLICIT_TYPES_BODY_RESOLVE, builder) } override val valueParameters: List<KtFirFunctionValueParameterSymbol> by firRef.withFirAndCache { fir -> fir.valueParameters.map { valueParameter -> builder.buildParameterSymbol(valueParameter) } } override val typeParameters by firRef.withFirAndCache { fir -> fir.typeParameters.map { typeParameter -> builder.buildTypeParameterSymbol(typeParameter.symbol.fir) } } override val annotations: List<KtAnnotationCall> by cached { firRef.toAnnotationsList() } override fun containsAnnotation(classId: ClassId): Boolean = firRef.containsAnnotation(classId) override val annotationClassIds: Collection<ClassId> by cached { firRef.getAnnotationClassIds() } override val isSuspend: Boolean get() = firRef.withFir { it.isSuspend } override val isOverride: Boolean get() = firRef.withFir { it.isOverride } override val dispatchType: KtType? by cached { firRef.dispatchReceiverTypeAndAnnotations(builder) } override val receiverType: KtTypeAndAnnotations? by cached { firRef.receiverTypeAndAnnotations(builder) } override val isOperator: Boolean get() = firRef.withFir { it.isOperator } override val isExternal: Boolean get() = firRef.withFir { it.isExternal } override val isInline: Boolean get() = firRef.withFir { it.isInline } override val isExtension: Boolean get() = firRef.withFir { it.receiverTypeRef != null } override val callableIdIfNonLocal: FqName? get() = firRef.withFir { fir -> fir.symbol.callableId.takeUnless { fir.isLocal }?.asFqNameForDebugInfo() } override val symbolKind: KtSymbolKind get() = firRef.withFir { fir -> when { fir.isLocal -> KtSymbolKind.LOCAL fir.containingClass()?.classId == null -> KtSymbolKind.TOP_LEVEL else -> KtSymbolKind.MEMBER } } override val modality: KtCommonSymbolModality get() = getModality() override val visibility: KtSymbolVisibility get() = getVisibility() override fun createPointer(): KtSymbolPointer<KtFunctionSymbol> { KtPsiBasedSymbolPointer.createForSymbolFromSource(this)?.let { return it } return when (symbolKind) { KtSymbolKind.TOP_LEVEL -> TODO("Creating symbol for top level fun is not supported yet") KtSymbolKind.MEMBER -> KtFirMemberFunctionSymbolPointer( firRef.withFir { it.containingClass()?.classId ?: error("ClassId should not be null for member function") }, firRef.withFir { it.createSignature() } ) KtSymbolKind.NON_PROPERTY_PARAMETER -> error("KtFunction could not be a parameter") KtSymbolKind.LOCAL -> throw CanNotCreateSymbolPointerForLocalLibraryDeclarationException( callableIdIfNonLocal?.asString() ?: name.asString() ) } } }
apache-2.0
4752b078ab1370451acee41582cadaf0
50.826923
124
0.746753
4.83842
false
false
false
false
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/support/ui/LithoCircleDrawable.kt
1
1833
package com.maubis.scarlet.base.support.ui import android.graphics.Canvas import android.graphics.Color import android.graphics.ColorFilter import android.graphics.Paint import android.graphics.PixelFormat import android.graphics.Rect import com.facebook.litho.drawable.ComparableDrawable import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTheme class LithoCircleDrawable(color: Int, alpha: Int = 255, val showBorder: Boolean = false) : ComparableDrawable() { private val mPaint: Paint private val mBorderPaint: Paint private var mRadius = 0 init { this.mPaint = Paint(Paint.ANTI_ALIAS_FLAG) this.mPaint.color = color this.mPaint.alpha = alpha val isNightTheme = sAppTheme.isNightTheme() this.mBorderPaint = Paint(Paint.ANTI_ALIAS_FLAG) this.mBorderPaint.color = when { !showBorder -> Color.TRANSPARENT isNightTheme -> Color.LTGRAY else -> Color.GRAY } } override fun draw(canvas: Canvas) { val bounds = bounds canvas.drawCircle(bounds.centerX().toFloat(), bounds.centerY().toFloat(), mRadius.toFloat(), mBorderPaint) canvas.drawCircle( bounds.centerX().toFloat(), bounds.centerY().toFloat(), mRadius.toFloat() - (if (showBorder) 2 else 0), mPaint) } override fun setAlpha(alpha: Int) { mPaint.alpha = alpha } override fun setColorFilter(cf: ColorFilter?) { mPaint.colorFilter = cf } override fun getOpacity(): Int { return PixelFormat.TRANSLUCENT } override fun onBoundsChange(bounds: Rect) { super.onBoundsChange(bounds) mRadius = Math.min(bounds.width(), bounds.height()) / 2 } override fun isEquivalentTo(other: ComparableDrawable?): Boolean { return other is LithoCircleDrawable && other.mRadius == mRadius && other.mPaint.color == mPaint.color } }
gpl-3.0
9a526a184cd374bff9b9646d19ac41e1
27.65625
113
0.71413
4.204128
false
false
false
false
jwren/intellij-community
plugins/kotlin/analysis-api-providers-ide-impl/src/org/jetbrains/kotlin/analysis/providers/ide/trackers/KotlinOutOfBlockPsiTreeChangePreprocessor.kt
1
1731
// 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.analysis.providers.ide.trackers import com.intellij.openapi.project.Project import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiTreeChangeEvent import com.intellij.psi.impl.PsiModificationTrackerImpl import com.intellij.psi.impl.PsiTreeChangeEventImpl import com.intellij.psi.impl.PsiTreeChangePreprocessor internal class KotlinOutOfBlockPsiTreeChangePreprocessor(private val project: Project) : PsiTreeChangePreprocessor { override fun treeChanged(event: PsiTreeChangeEventImpl) { if (!PsiModificationTrackerImpl.canAffectPsi(event)) return if (event.isOutOfBlockChange()) { incrementModificationsCount() } } private fun incrementModificationsCount() { project.getService(KotlinFirModificationTrackerService::class.java).increaseModificationCountForAllModules() } // Copy logic from PsiModificationTrackerImpl.treeChanged(). Some out-of-code-block events are written to language modification // tracker in PsiModificationTrackerImpl but don't have correspondent PomModelEvent. Increase kotlinOutOfCodeBlockTracker // manually if needed. private fun PsiTreeChangeEventImpl.isOutOfBlockChange() = when (code) { PsiTreeChangeEventImpl.PsiEventType.PROPERTY_CHANGED -> propertyName === PsiTreeChangeEvent.PROP_UNLOADED_PSI || propertyName === PsiTreeChangeEvent.PROP_ROOTS PsiTreeChangeEventImpl.PsiEventType.CHILD_MOVED -> oldParent is PsiDirectory || newParent is PsiDirectory else -> parent is PsiDirectory } }
apache-2.0
254f069c279ff53da688842a80e527fc
51.484848
158
0.782207
5.229607
false
false
false
false
androidx/androidx
navigation/navigation-fragment/src/androidTest/java/androidx/navigation/fragment/NavHostFragmentTest.kt
3
6185
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.navigation.fragment import android.os.Bundle import androidx.fragment.app.DialogFragment import androidx.navigation.findNavController import androidx.navigation.fragment.test.EmptyFragment import androidx.navigation.fragment.test.NavigationActivity import androidx.navigation.fragment.test.NavigationActivityWithFragmentTag import androidx.navigation.fragment.test.NavigationBaseActivity import androidx.navigation.fragment.test.R import androidx.test.core.app.ActivityScenario import androidx.test.filters.MediumTest import androidx.testutils.withActivity import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @MediumTest @RunWith(Parameterized::class) class NavHostFragmentTest( private val activityClass: Class<NavigationBaseActivity> ) { companion object { @JvmStatic @Parameterized.Parameters fun data(): Array<Class<out NavigationBaseActivity>> { return arrayOf( NavigationActivity::class.java, NavigationActivityWithFragmentTag::class.java ) } } @Test fun testFindNavControllerXml() { with(ActivityScenario.launch(activityClass)) { val navController = withActivity { findNavController(R.id.nav_host) } assertWithMessage("NavController on the activity's view should be non-null") .that(navController) .isNotNull() val hostRootNavController = withActivity { val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host)!! navHostFragment.requireView().findNavController() } assertWithMessage("NavController on the host's root view should be non-null") .that(hostRootNavController) .isNotNull() } } @Test fun testFindNavControllerRecreate() { with(ActivityScenario.launch(activityClass)) { val navController = withActivity { findNavController(R.id.nav_host) } assertWithMessage("NavController on the activity's view should be non-null") .that(navController) .isNotNull() assertWithMessage("NavController graph should be non-null") .that(navController.graph) .isNotNull() recreate() val restoredNavController = withActivity { findNavController(R.id.nav_host) } assertWithMessage("NavController on the activity's view should be non-null") .that(restoredNavController) .isNotNull() assertWithMessage("NavController graph should be non-null") .that(restoredNavController.graph) .isNotNull() } } @Test fun testDismissDialogAfterRecreate() { with(ActivityScenario.launch(activityClass)) { val navController = withActivity { findNavController(R.id.nav_host).also { it.navigate(R.id.dialog_fragment) } } assertThat(navController.currentDestination?.id) .isEqualTo(R.id.dialog_fragment) val dialogFragment = withActivity { val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host)!! navHostFragment.childFragmentManager.fragments.first { it is DialogFragment } } as DialogFragment assertThat(dialogFragment.dialog).isNotNull() recreate() val restoredNavController = withActivity { findNavController(R.id.nav_host) } assertThat(restoredNavController.currentDestination?.id) .isEqualTo(R.id.dialog_fragment) val restoredDialogFragment = withActivity { val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host)!! navHostFragment.childFragmentManager.fragments.first { it is DialogFragment } } as DialogFragment assertThat(restoredDialogFragment.dialog).isNotNull() restoredDialogFragment.dismiss() val foundDialogFragment = withActivity { val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host)!! navHostFragment.childFragmentManager.fragments.any { it is DialogFragment } } assertWithMessage("No DialogFragment should be found after dismissal") .that(foundDialogFragment) .isFalse() assertThat(restoredNavController.currentDestination?.id) .isEqualTo(R.id.start_fragment) } } } class NavControllerInOnCreateFragment : EmptyFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val navController = NavHostFragment.findNavController(this) assertWithMessage("The NavController's graph should be set") .that(navController.graph) .isNotNull() val backStackEntry = navController.getBackStackEntry(R.id.start_fragment) val savedStateHandle = backStackEntry.savedStateHandle assertThat(savedStateHandle) .isNotNull() } }
apache-2.0
d09c50431bb9d35dea57d80e47773b17
35.60355
94
0.650121
5.607434
false
true
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/resolutionDebugging/KotlinTypeDebugReport.kt
2
2018
// 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.actions.internal.resolutionDebugging import org.jetbrains.kotlin.idea.base.utils.fqname.fqName import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.supertypes import org.jetbrains.kotlin.utils.Printer internal data class KotlinTypeReference(val instanceString: String, val fqn: String) { override fun toString(): String = "$instanceString{$fqn}" } internal class KotlinTypeDebugReport( val typeReference: KotlinTypeReference, val fqn: String?, private val containingModule: ModuleReference, private val supertypesReferences: Collection<KotlinTypeReference> ) { fun render(printer: Printer): Unit = with(printer) { println("Instance = $typeReference") println("fqn = $fqn") println("Containing module = $containingModule") println("Supertypes") pushIndent() supertypesReferences.forEach { println(it) } popIndent() } // only [reference] in included into equality/toString override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as KotlinTypeDebugReport if (typeReference != other.typeReference) return false return true } override fun hashCode(): Int { return typeReference.hashCode() } override fun toString(): String { return "KotlinTypeDebugReport(typeReference=$typeReference)" } } internal fun ReportContext.KotlinTypeDebugReport(type: KotlinType): KotlinTypeDebugReport { return KotlinTypeDebugReport( type.referenceToInstance(), type.fqName?.toString(), type.constructor.declarationDescriptor!!.module.referenceToInstance(), type.supertypes().map { it.referenceToInstance() } ) }
apache-2.0
666c627addb7ea645c9c0f906e0b1280
33.793103
120
0.718533
4.693023
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/lang/documentation/ide/ui/ui.kt
7
4103
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("DEPRECATION") package com.intellij.lang.documentation.ide.ui import com.intellij.codeInsight.documentation.CornerAwareScrollPaneLayout import com.intellij.codeInsight.documentation.DocumentationManager import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.lang.documentation.LinkData import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.util.text.HtmlChunk import com.intellij.ui.IdeBorderFactory import com.intellij.ui.SideBorder import com.intellij.ui.components.JBLayeredPane import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.Nls import java.awt.Dimension import javax.swing.JComponent import javax.swing.JLayeredPane import javax.swing.JScrollPane internal val LOG: Logger = Logger.getInstance("#com.intellij.lang.documentation.ide.ui") /** * @see com.intellij.find.actions.ShowUsagesAction.ourPopupDelayTimeout */ internal const val DEFAULT_UI_RESPONSE_TIMEOUT: Long = 300 @JvmField internal val FORCED_WIDTH = Key.create<Int>("WidthBasedLayout.width") internal typealias UISnapshot = () -> Unit internal fun toolbarComponent(actions: ActionGroup, contextComponent: JComponent): JComponent { val toolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.JAVADOC_TOOLBAR, actions, true).also { it.setSecondaryActionsIcon(AllIcons.Actions.More, true) it.setTargetComponent(contextComponent) } return toolbar.component.also { it.border = IdeBorderFactory.createBorder(UIUtil.getTooltipSeparatorColor(), SideBorder.BOTTOM) } } internal fun actionButton(actions: ActionGroup, contextComponent: JComponent): JComponent { val presentation = Presentation().also { it.icon = AllIcons.Actions.More it.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, true) } val button = object : ActionButton(actions, presentation, ActionPlaces.UNKNOWN, Dimension(20, 20)) { override fun getDataContext(): DataContext = DataManager.getInstance().getDataContext(contextComponent) } button.setNoIconsInPopup(true) return button } internal fun scrollPaneWithCorner(parent: Disposable, scrollPane: JScrollPane, corner: JComponent): JComponent { val defaultLayout = scrollPane.layout scrollPane.layout = CornerAwareScrollPaneLayout(corner) Disposer.register(parent) { scrollPane.layout = defaultLayout } val layeredPane: JLayeredPane = object : JBLayeredPane() { override fun doLayout() { val r = bounds for (component in components) { if (component === scrollPane) { component.setBounds(0, 0, r.width, r.height) } else if (component === corner) { val d = component.preferredSize component.setBounds(r.width - d.width - 2, r.height - d.height - 2, d.width, d.height) } else { error("can't layout unexpected component: $component") } } } override fun getPreferredSize(): Dimension { return scrollPane.preferredSize } } layeredPane.setLayer(scrollPane, JLayeredPane.DEFAULT_LAYER) layeredPane.add(scrollPane) layeredPane.setLayer(corner, JLayeredPane.PALETTE_LAYER) layeredPane.add(corner) return layeredPane } internal fun linkChunk(presentableText: @Nls String, links: LinkData): HtmlChunk? { val externalUrl = links.externalUrl if (externalUrl != null) { return DocumentationManager.getLink(presentableText, externalUrl) ?: DocumentationManager.getGenericExternalDocumentationLink(presentableText) } val linkUrls = links.linkUrls if (linkUrls.isNotEmpty()) { return DocumentationManager.getExternalLinks(presentableText, linkUrls) ?: DocumentationManager.getGenericExternalDocumentationLink(presentableText) } return null }
apache-2.0
b38715140c19192dd40c5918d8406d80
36.642202
120
0.766756
4.402361
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/CustomizeTabFactory.kt
3
12762
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl.welcomeScreen import com.intellij.ide.IdeBundle import com.intellij.ide.actions.QuickChangeLookAndFeel import com.intellij.ide.actions.ShowSettingsUtilImpl import com.intellij.ide.ui.* import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.PlatformEditorBundle import com.intellij.openapi.editor.colors.EditorColorsListener import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager import com.intellij.openapi.editor.colors.impl.EditorColorsManagerImpl import com.intellij.openapi.help.HelpManager import com.intellij.openapi.keymap.KeyMapBundle import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.keymap.KeymapManagerListener import com.intellij.openapi.keymap.impl.KeymapManagerImpl import com.intellij.openapi.keymap.impl.keymapComparator import com.intellij.openapi.keymap.impl.ui.KeymapSchemeManager import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty import com.intellij.openapi.observable.properties.PropertyGraph import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.wm.WelcomeTabFactory import com.intellij.openapi.wm.impl.welcomeScreen.TabbedWelcomeScreen.DefaultWelcomeScreenTab import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.UIBundle import com.intellij.ui.components.AnActionLink import com.intellij.ui.components.JBLabel import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.builder.Cell import com.intellij.ui.dsl.builder.Row import com.intellij.ui.dsl.builder.panel import com.intellij.ui.layout.* import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBFont import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.Nls import java.awt.Font import javax.swing.DefaultComboBoxModel import javax.swing.JComponent import javax.swing.plaf.FontUIResource import javax.swing.plaf.LabelUI private val settings get() = UISettings.getInstance() private val defaultProject get() = ProjectManager.getInstance().defaultProject private val laf get() = LafManager.getInstance() private val keymapManager get() = KeymapManager.getInstance() as KeymapManagerImpl private val editorColorsManager get() = EditorColorsManager.getInstance() as EditorColorsManagerImpl class CustomizeTabFactory : WelcomeTabFactory { override fun createWelcomeTab(parentDisposable: Disposable) = CustomizeTab(parentDisposable) } private fun getIdeFont() = if (settings.overrideLafFonts) settings.fontSize2D else JBFont.label().size2D class CustomizeTab(parentDisposable: Disposable) : DefaultWelcomeScreenTab(IdeBundle.message("welcome.screen.customize.title"), WelcomeScreenEventCollector.TabType.TabNavCustomize) { private val supportedColorBlindness = getColorBlindness() private val propertyGraph = PropertyGraph() private val lafProperty = propertyGraph.graphProperty { laf.lookAndFeelReference } private val syncThemeProperty = propertyGraph.graphProperty { laf.autodetect } private val ideFontProperty = propertyGraph.graphProperty { getIdeFont() } private val keymapProperty = propertyGraph.graphProperty { keymapManager.activeKeymap } private val colorBlindnessProperty = propertyGraph.graphProperty { settings.colorBlindness ?: supportedColorBlindness.firstOrNull() } private val adjustColorsProperty = propertyGraph.graphProperty { settings.colorBlindness != null } private var keymapComboBox: ComboBox<Keymap>? = null private var colorThemeComboBox: ComboBox<LafManager.LafReference>? = null init { lafProperty.afterChange({ val newLaf = laf.findLaf(it) if (laf.currentLookAndFeel == newLaf) return@afterChange QuickChangeLookAndFeel.switchLafAndUpdateUI(laf, newLaf, true) WelcomeScreenEventCollector.logLafChanged(newLaf, laf.autodetect) }, parentDisposable) syncThemeProperty.afterChange { if (laf.autodetect == it) return@afterChange laf.autodetect = it WelcomeScreenEventCollector.logLafChanged(laf.currentLookAndFeel, laf.autodetect) } ideFontProperty.afterChange({ if (settings.fontSize2D == it) return@afterChange settings.overrideLafFonts = true WelcomeScreenEventCollector.logIdeFontChanged(settings.fontSize2D, it) settings.fontSize2D = it updateFontSettingsLater() }, parentDisposable) keymapProperty.afterChange({ if (keymapManager.activeKeymap == it) return@afterChange WelcomeScreenEventCollector.logKeymapChanged(it) keymapManager.activeKeymap = it }, parentDisposable) adjustColorsProperty.afterChange({ if (adjustColorsProperty.get() == (settings.colorBlindness != null)) return@afterChange WelcomeScreenEventCollector.logColorBlindnessChanged(adjustColorsProperty.get()) updateColorBlindness() }, parentDisposable) colorBlindnessProperty.afterChange({ updateColorBlindness() }, parentDisposable) val busConnection = ApplicationManager.getApplication().messageBus.connect(parentDisposable) busConnection.subscribe(UISettingsListener.TOPIC, UISettingsListener { updateProperty(ideFontProperty) { getIdeFont() } }) busConnection.subscribe(EditorColorsManager.TOPIC, EditorColorsListener { updateAccessibilityProperties() }) busConnection.subscribe(LafManagerListener.TOPIC, LafManagerListener { updateProperty(lafProperty) { laf.lookAndFeelReference } updateLafs() }) busConnection.subscribe(KeymapManagerListener.TOPIC, object : KeymapManagerListener { override fun activeKeymapChanged(keymap: Keymap?) { updateProperty(keymapProperty) { keymapManager.activeKeymap } updateKeymaps() } override fun keymapAdded(keymap: Keymap) { updateKeymaps() } override fun keymapRemoved(keymap: Keymap) { updateKeymaps() } }) } private fun updateColorBlindness() { settings.colorBlindness = if (adjustColorsProperty.get()) colorBlindnessProperty.get() else null ApplicationManager.getApplication().invokeLater(Runnable { DefaultColorSchemesManager.getInstance().reload() editorColorsManager.schemeChangedOrSwitched(null) }) } private fun updateFontSettingsLater() { ApplicationManager.getApplication().invokeLater { laf.updateUI() settings.fireUISettingsChanged() } } private fun <T> updateProperty(property: GraphProperty<T>, settingGetter: () -> T) { val value = settingGetter() if (property.get() != value) { property.set(value) } } private fun updateAccessibilityProperties() { val adjustColorSetting = settings.colorBlindness != null updateProperty(adjustColorsProperty) { adjustColorSetting } if (adjustColorSetting) { updateProperty(colorBlindnessProperty) { settings.colorBlindness } } } override fun buildComponent(): JComponent { return panel { header(IdeBundle.message("welcome.screen.color.theme.header"), true) row { val themeBuilder = comboBox(laf.lafComboBoxModel, laf.lookAndFeelCellRenderer) .bindItem(lafProperty) .accessibleName(IdeBundle.message("welcome.screen.color.theme.header")) colorThemeComboBox = themeBuilder.component val syncCheckBox = checkBox(IdeBundle.message("preferred.theme.autodetect.selector")) .bindSelected(syncThemeProperty) .applyToComponent { isOpaque = false isVisible = laf.autodetectSupported } themeBuilder.enabledIf(syncCheckBox.selected.not()) cell(laf.settingsToolbar).visibleIf(syncCheckBox.selected) } header(IdeBundle.message("title.accessibility")) row(IdeBundle.message("welcome.screen.ide.font.size.label")) { fontComboBox(ideFontProperty) }.bottomGap(BottomGap.SMALL) createColorBlindnessSettingBlock() header(KeyMapBundle.message("keymap.display.name")) row { keymapComboBox = comboBox(DefaultComboBoxModel(getKeymaps().toTypedArray())) .bindItem(keymapProperty) .accessibleName(KeyMapBundle.message("keymap.display.name")) .component link(KeyMapBundle.message("welcome.screen.keymap.configure.link")) { ShowSettingsUtil.getInstance().showSettingsDialog(defaultProject, KeyMapBundle.message("keymap.display.name")) } } row { cell(AnActionLink("WelcomeScreen.Configure.Import", ActionPlaces.WELCOME_SCREEN)) }.topGap(TopGap.MEDIUM) row { link(IdeBundle.message("welcome.screen.all.settings.link")) { ShowSettingsUtil.getInstance().showSettingsDialog(defaultProject, *ShowSettingsUtilImpl.getConfigurableGroups(defaultProject, true)) } } }.withBorder(JBUI.Borders.empty(23, 30, 20, 20)) .withBackground(WelcomeScreenUIManager.getMainAssociatedComponentBackground()) } private fun updateKeymaps() { (keymapComboBox?.model as DefaultComboBoxModel?)?.apply { removeAllElements() addAll(getKeymaps()) selectedItem = keymapProperty.get() } } private fun updateLafs() { colorThemeComboBox?.apply { model = laf.lafComboBoxModel selectedItem = lafProperty.get() } } private fun Panel.createColorBlindnessSettingBlock() { if (supportedColorBlindness.isNotEmpty()) { row { if (supportedColorBlindness.size == 1) { checkBox(UIBundle.message("color.blindness.checkbox.text")) .bindSelected(adjustColorsProperty) .comment(UIBundle.message("color.blindness.checkbox.comment")) .applyToComponent { isOpaque = false } } else { val checkBox = checkBox(UIBundle.message("welcome.screen.color.blindness.combobox.text")) .bindSelected(adjustColorsProperty) .applyToComponent { isOpaque = false }.component comboBox(DefaultComboBoxModel(supportedColorBlindness.toTypedArray()), SimpleListCellRenderer.create("") { PlatformEditorBundle.message(it?.key ?: "") }) .bindItem(colorBlindnessProperty) .comment(UIBundle.message("color.blindness.combobox.comment")) .enabledIf(checkBox.selected) } link(UIBundle.message("color.blindness.link.to.help")) { HelpManager.getInstance().invokeHelp("Colorblind_Settings") } } } } private fun Panel.header(@Nls title: String, firstHeader: Boolean = false) { val row = row { cell(HeaderLabel(title)) }.bottomGap(BottomGap.SMALL) if (!firstHeader) { row.topGap(TopGap.MEDIUM) } } private class HeaderLabel(@Nls title: String) : JBLabel(title) { override fun setUI(ui: LabelUI?) { super.setUI(ui) if (font != null) { font = FontUIResource(font.deriveFont(font.size2D + JBUIScale.scale(3)).deriveFont(Font.BOLD)) } } } private fun Row.fontComboBox(fontProperty: GraphProperty<Float>): Cell<ComboBox<Float>> { val fontSizes = UIUtil.getStandardFontSizes().map { it.toFloat() }.toSortedSet() fontSizes.add(fontProperty.get()) val model = DefaultComboBoxModel(fontSizes.toTypedArray()) return comboBox(model) .bindItem(fontProperty) .applyToComponent { isEditable = true } } private fun getColorBlindness(): List<ColorBlindness> { return ColorBlindness.values().asList().filter { ColorBlindnessSupport.get(it) != null } } private fun getKeymaps(): List<Keymap> { return keymapManager.getKeymaps(KeymapSchemeManager.FILTER).sortedWith(keymapComparator) } }
apache-2.0
8a49b1956d8dd17071f67b08ea0d083c
42.859107
135
0.708666
5.082437
false
false
false
false
GunoH/intellij-community
plugins/evaluation-plugin/core/src/com/intellij/cce/metric/RecallMetric.kt
8
952
package com.intellij.cce.metric import com.intellij.cce.core.Session import com.intellij.cce.metric.util.Sample import java.util.stream.Collectors class RecallMetric : Metric { private val sample = Sample() override val value: Double get() = sample.mean() override fun evaluate(sessions: List<Session>, comparator: SuggestionsComparator): Double { val listOfCompletions = sessions.stream() .flatMap { session -> session.lookups.map { lookup -> Pair(lookup.suggestions, session.expectedText) }.stream() } .collect(Collectors.toList()) val fileSample = Sample() listOfCompletions.stream() .forEach { (suggests, expectedText) -> val value = if (suggests.any { comparator.accept(it, expectedText) }) 1.0 else 0.0 fileSample.add(value) sample.add(value) } return fileSample.mean() } override val name: String = "Recall" override val valueType = MetricValueType.DOUBLE }
apache-2.0
efba5ad3aac8aa8e3b869df556666875
28.78125
119
0.70063
4.103448
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/old/tests/testData/fileOrElement/constructors/allCallsPrimary.kt
13
224
package pack internal class C @JvmOverloads constructor(arg1: Int, arg2: Int = 0, arg3: Int = 0) object User { fun main() { val c1 = C(100, 100, 100) val c2 = C(100, 100) val c3 = C(100) } }
apache-2.0
0ac476ad84bf8f8c3064ea4114680c35
19.454545
83
0.553571
2.909091
false
false
false
false
TimePath/launcher
src/main/kotlin/com/timepath/util/logging/LogIOHandler.kt
1
2563
package com.timepath.util.logging import java.io.IOException import java.io.PrintWriter import java.lang.management.ManagementFactory import java.net.Socket import java.text.DateFormat import java.text.MessageFormat import java.util.Date import java.util.LinkedList import java.util.logging.* import kotlin.concurrent.thread public class LogIOHandler : StreamHandler() { /** * Unique name */ protected val node: String = ManagementFactory.getRuntimeMXBean().getName() SuppressWarnings("MismatchedQueryAndUpdateOfCollection") // pollLast() actually does get private val recordDeque = LinkedList<String>() volatile private var pw: PrintWriter? = null init { setFormatter(LogIOFormatter()) } public fun connect(host: String, port: Int): LogIOHandler { thread { try { Socket(host, port).use { sock -> pw = PrintWriter(sock.getOutputStream(), true) send("+node|$node") } } catch (e: IOException) { LOG.log(Level.SEVERE, null, e) } } return this } synchronized public fun send(line: String) { recordDeque.addLast(line) if (pw != null) { run { val it = recordDeque.iterator() while (it.hasNext()) { pw!!.print("${it.next()}\r\n") it.remove() } } pw!!.flush() } } synchronized override fun publish(record: LogRecord) { send(getFormatter().format(record)) } synchronized override fun flush() { if (pw != null) { pw!!.flush() } } synchronized override fun close() { send("-node|$node") if (pw != null) { pw!!.close() } pw = null } private inner class LogIOFormatter : Formatter() { private val dateFormat = DateFormat.getDateTimeInstance() override fun format(record: LogRecord): String { val level = record.getLevel().getName().toLowerCase() val message = MessageFormat.format("{0}: <{2}::{3}> {4}: {5}", dateFormat.format(Date(record.getMillis())), record.getLoggerName(), record.getSourceClassName(), record.getSourceMethodName(), record.getLevel(), formatMessage(record)) return "+log||$node|$level|$message" } } companion object { private val LOG = Logger.getLogger(javaClass<LogIOHandler>().getName()) } }
artistic-2.0
65de4220fb20922e387ba3d8130f2b0c
27.477778
244
0.577448
4.685558
false
false
false
false
MartinStyk/AndroidApkAnalyzer
app/src/main/java/sk/styk/martin/apkanalyzer/ui/applist/packagename/AppListFromPackageNamesDialog.kt
1
2970
package sk.styk.martin.apkanalyzer.ui.applist.packagename import android.app.Dialog import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import dagger.hilt.android.AndroidEntryPoint import sk.styk.martin.apkanalyzer.R import sk.styk.martin.apkanalyzer.databinding.DialogAppListBinding import sk.styk.martin.apkanalyzer.ui.appdetail.AppDetailActivity import sk.styk.martin.apkanalyzer.ui.appdetail.AppDetailFragment.Companion.APP_DETAIL_REQUEST import sk.styk.martin.apkanalyzer.ui.appdetail.AppDetailRequest import sk.styk.martin.apkanalyzer.ui.applist.AppListAdapter import sk.styk.martin.apkanalyzer.util.provideViewModel import javax.inject.Inject @AndroidEntryPoint class AppListFromPackageNamesDialog : DialogFragment() { @Inject lateinit var viewModelFactory: AppListFromPackageNamesDialogViewModel.Factory private lateinit var viewModel: AppListFromPackageNamesDialogViewModel private lateinit var binding: DialogAppListBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = provideViewModel { viewModelFactory.create( packageNames = requireNotNull(requireArguments().getStringArrayList(ARG_PACKAGE_NAMES)) ) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding.viewModel = viewModel binding.lifecycleOwner = this viewModel.appClicked.observe(this, this@AppListFromPackageNamesDialog::startAppDetail) return super.onCreateView(inflater, container, savedInstanceState) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { binding = DialogAppListBinding.inflate(layoutInflater, null, false) return AlertDialog.Builder(requireContext()) .setView(binding.root) .setTitle(R.string.apps) .setNegativeButton(R.string.dismiss) { _, _ -> dismiss() } .create() } private fun startAppDetail(appListClickData: AppListAdapter.AppListClickData) { val intent = Intent(requireContext(), AppDetailActivity::class.java).apply { putExtra(APP_DETAIL_REQUEST, AppDetailRequest.InstalledPackage(appListClickData.appListData.packageName)) } startActivity(intent) } companion object { private const val ARG_PACKAGE_NAMES = "arg_package_names" fun newInstance(packageNames: List<String>) = AppListFromPackageNamesDialog().apply { val list = if (packageNames is ArrayList<String>) packageNames else ArrayList<String>(packageNames) arguments = Bundle().apply { putStringArrayList(ARG_PACKAGE_NAMES, list) } } } }
gpl-3.0
e1fa4a59f10b8bece9b0e54d25348652
39.69863
117
0.737037
5.016892
false
false
false
false
AMARJITVS/NoteDirector
app/src/main/kotlin/com/amar/notesapp/helpers/Config.kt
1
11443
package com.amar.NoteDirector.helpers import android.content.Context import android.content.res.Configuration import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.simplemobiletools.commons.helpers.BaseConfig import com.simplemobiletools.commons.helpers.SORT_BY_DATE_MODIFIED import com.simplemobiletools.commons.helpers.SORT_DESCENDING import com.amar.NoteDirector.models.AlbumCover import java.util.* class Config(context: Context) : BaseConfig(context) { companion object { fun newInstance(context: Context) = Config(context) } var fileSorting: Int get() = prefs.getInt(SORT_ORDER, SORT_BY_DATE_MODIFIED or SORT_DESCENDING) set(order) = prefs.edit().putInt(SORT_ORDER, order).apply() var directorySorting: Int get() = prefs.getInt(DIRECTORY_SORT_ORDER, SORT_BY_DATE_MODIFIED or SORT_DESCENDING) set(order) = prefs.edit().putInt(DIRECTORY_SORT_ORDER, order).apply() fun saveFileSorting(path: String, value: Int) { if (path.isEmpty()) { fileSorting = value } else { prefs.edit().putInt(SORT_FOLDER_PREFIX + path, value).apply() } } fun getFileSorting(path: String) = prefs.getInt(SORT_FOLDER_PREFIX + path, fileSorting) fun removeFileSorting(path: String) { prefs.edit().remove(SORT_FOLDER_PREFIX + path).apply() } fun hasCustomSorting(path: String) = prefs.contains(SORT_FOLDER_PREFIX + path) var wasHideFolderTooltipShown: Boolean get() = prefs.getBoolean(HIDE_FOLDER_TOOLTIP_SHOWN, false) set(wasShown) = prefs.edit().putBoolean(HIDE_FOLDER_TOOLTIP_SHOWN, wasShown).apply() var shouldShowHidden = showHiddenMedia || temporarilyShowHidden var showHiddenMedia: Boolean get() = prefs.getBoolean(SHOW_HIDDEN_MEDIA, false) set(showHiddenFolders) = prefs.edit().putBoolean(SHOW_HIDDEN_MEDIA, showHiddenFolders).apply() var temporarilyShowHidden: Boolean get() = prefs.getBoolean(TEMPORARILY_SHOW_HIDDEN, false) set(temporarilyShowHidden) = prefs.edit().putBoolean(TEMPORARILY_SHOW_HIDDEN, temporarilyShowHidden).apply() var isThirdPartyIntent: Boolean get() = prefs.getBoolean(IS_THIRD_PARTY_INTENT, false) set(isThirdPartyIntent) = prefs.edit().putBoolean(IS_THIRD_PARTY_INTENT, isThirdPartyIntent).apply() var pinnedFolders: Set<String> get() = prefs.getStringSet(PINNED_FOLDERS, HashSet<String>()) set(pinnedFolders) = prefs.edit().putStringSet(PINNED_FOLDERS, pinnedFolders).apply() var showAll: Boolean get() = prefs.getBoolean(SHOW_ALL, false) set(showAll) = prefs.edit().putBoolean(SHOW_ALL, showAll).apply() fun addPinnedFolders(paths: Set<String>) { val currPinnedFolders = HashSet<String>(pinnedFolders) currPinnedFolders.addAll(paths) pinnedFolders = currPinnedFolders } fun removePinnedFolders(paths: Set<String>) { val currPinnedFolders = HashSet<String>(pinnedFolders) currPinnedFolders.removeAll(paths) pinnedFolders = currPinnedFolders } fun addExcludedFolder(path: String) { addExcludedFolders(HashSet<String>(Arrays.asList(path))) } fun addExcludedFolders(paths: Set<String>) { val currExcludedFolders = HashSet<String>(excludedFolders) currExcludedFolders.addAll(paths) excludedFolders = currExcludedFolders } var excludedFolders: MutableSet<String> get() = prefs.getStringSet(EXCLUDED_FOLDERS, getDataFolder()) set(excludedFolders) = prefs.edit().remove(EXCLUDED_FOLDERS).putStringSet(EXCLUDED_FOLDERS, excludedFolders).apply() private fun getDataFolder(): Set<String> { val folders = HashSet<String>() val dataFolder = context.externalCacheDir?.parentFile?.parent?.trimEnd('/') ?: "" if (dataFolder.endsWith("data")) folders.add(dataFolder) return folders } var includedFolders: MutableSet<String> get() = prefs.getStringSet(INCLUDED_FOLDERS, HashSet<String>()) set(includedFolders) = prefs.edit().remove(INCLUDED_FOLDERS).putStringSet(INCLUDED_FOLDERS, includedFolders).apply() fun saveFolderMedia(path: String, json: String) { prefs.edit().putString(SAVE_FOLDER_PREFIX + path, json).apply() } fun loadFolderMedia(path: String) = prefs.getString(SAVE_FOLDER_PREFIX + path, "") var autoplayVideos: Boolean get() = prefs.getBoolean(AUTOPLAY_VIDEOS, true) set(autoplay) = prefs.edit().putBoolean(AUTOPLAY_VIDEOS, autoplay).apply() var animateGifs: Boolean get() = prefs.getBoolean(ANIMATE_GIFS, false) set(animateGifs) = prefs.edit().putBoolean(ANIMATE_GIFS, animateGifs).apply() var maxBrightness: Boolean get() = prefs.getBoolean(MAX_BRIGHTNESS, false) set(maxBrightness) = prefs.edit().putBoolean(MAX_BRIGHTNESS, maxBrightness).apply() var cropThumbnails: Boolean get() = prefs.getBoolean(CROP_THUMBNAILS, true) set(cropThumbnails) = prefs.edit().putBoolean(CROP_THUMBNAILS, cropThumbnails).apply() var screenRotation: Int get() = prefs.getInt(SCREEN_ROTATION, ROTATE_BY_DEVICE_ROTATION) set(screenRotation) = prefs.edit().putInt(SCREEN_ROTATION, screenRotation).apply() var loopVideos: Boolean get() = prefs.getBoolean(LOOP_VIDEOS, false) set(loop) = prefs.edit().putBoolean(LOOP_VIDEOS, loop).apply() var displayFileNames: Boolean get() = prefs.getBoolean(DISPLAY_FILE_NAMES, false) set(display) = prefs.edit().putBoolean(DISPLAY_FILE_NAMES, display).apply() var darkBackground: Boolean get() = prefs.getBoolean(DARK_BACKGROUND, true) set(darkBackground) = prefs.edit().putBoolean(DARK_BACKGROUND, darkBackground).apply() var filterMedia: Int get() = prefs.getInt(FILTER_MEDIA, IMAGES or VIDEOS or GIFS) set(filterMedia) = prefs.edit().putInt(FILTER_MEDIA, filterMedia).apply() var dirColumnCnt: Int get() = prefs.getInt(getDirectoryColumnsField(), getDefaultDirectoryColumnCount()) set(dirColumnCnt) = prefs.edit().putInt(getDirectoryColumnsField(), dirColumnCnt).apply() private fun getDirectoryColumnsField(): String { val isPortrait = context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT return if (isPortrait) { if (scrollHorizontally) { DIR_HORIZONTAL_COLUMN_CNT } else { DIR_COLUMN_CNT } } else { if (scrollHorizontally) { DIR_LANDSCAPE_HORIZONTAL_COLUMN_CNT } else { DIR_LANDSCAPE_COLUMN_CNT } } } private fun getDefaultDirectoryColumnCount() = context.resources.getInteger(if (scrollHorizontally) com.amar.NoteDirector.R.integer.directory_columns_horizontal_scroll else com.amar.NoteDirector.R.integer.directory_columns_vertical_scroll) var mediaColumnCnt: Int get() = prefs.getInt(getMediaColumnsField(), getDefaultMediaColumnCount()) set(mediaColumnCnt) = prefs.edit().putInt(getMediaColumnsField(), mediaColumnCnt).apply() private fun getMediaColumnsField(): String { val isPortrait = context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT return if (isPortrait) { if (scrollHorizontally) { MEDIA_HORIZONTAL_COLUMN_CNT } else { MEDIA_COLUMN_CNT } } else { if (scrollHorizontally) { MEDIA_LANDSCAPE_HORIZONTAL_COLUMN_CNT } else { MEDIA_LANDSCAPE_COLUMN_CNT } } } private fun getDefaultMediaColumnCount() = context.resources.getInteger(if (scrollHorizontally) com.amar.NoteDirector.R.integer.media_columns_horizontal_scroll else com.amar.NoteDirector.R.integer.media_columns_vertical_scroll) var directories: String get() = prefs.getString(DIRECTORIES, "") set(directories) = prefs.edit().putString(DIRECTORIES, directories).apply() var albumCovers: String get() = prefs.getString(ALBUM_COVERS, "") set(albumCovers) = prefs.edit().putString(ALBUM_COVERS, albumCovers).apply() fun parseAlbumCovers(): ArrayList<AlbumCover> { val listType = object : TypeToken<List<AlbumCover>>() {}.type return Gson().fromJson<ArrayList<AlbumCover>>(albumCovers, listType) ?: ArrayList(1) } var scrollHorizontally: Boolean get() = prefs.getBoolean(SCROLL_HORIZONTALLY, false) set(scrollHorizontally) = prefs.edit().putBoolean(SCROLL_HORIZONTALLY, scrollHorizontally).apply() var hideSystemUI: Boolean get() = prefs.getBoolean(HIDE_SYSTEM_UI, true) set(hideSystemUI) = prefs.edit().putBoolean(HIDE_SYSTEM_UI, hideSystemUI).apply() var replaceShare: Boolean get() = prefs.getBoolean(REPLACE_SHARE_WITH_ROTATE, false) set(replaceShare) = prefs.edit().putBoolean(REPLACE_SHARE_WITH_ROTATE, replaceShare).apply() var deleteEmptyFolders: Boolean get() = prefs.getBoolean(DELETE_EMPTY_FOLDERS, true) set(deleteEmptyFolders) = prefs.edit().putBoolean(DELETE_EMPTY_FOLDERS, deleteEmptyFolders).apply() var allowVideoGestures: Boolean get() = prefs.getBoolean(ALLOW_VIDEO_GESTURES, true) set(allowVideoGestures) = prefs.edit().putBoolean(ALLOW_VIDEO_GESTURES, allowVideoGestures).apply() var slideshowInterval: Int get() = prefs.getInt(SLIDESHOW_INTERVAL, SLIDESHOW_DEFAULT_INTERVAL) set(slideshowInterval) = prefs.edit().putInt(SLIDESHOW_INTERVAL, slideshowInterval).apply() var slideshowIncludePhotos: Boolean get() = prefs.getBoolean(SLIDESHOW_INCLUDE_PHOTOS, true) set(slideshowIncludePhotos) = prefs.edit().putBoolean(SLIDESHOW_INCLUDE_PHOTOS, slideshowIncludePhotos).apply() var slideshowIncludeVideos: Boolean get() = prefs.getBoolean(SLIDESHOW_INCLUDE_VIDEOS, false) set(slideshowIncludeVideos) = prefs.edit().putBoolean(SLIDESHOW_INCLUDE_VIDEOS, slideshowIncludeVideos).apply() var slideshowIncludeGIFs: Boolean get() = prefs.getBoolean(SLIDESHOW_INCLUDE_GIFS, false) set(slideshowIncludeGIFs) = prefs.edit().putBoolean(SLIDESHOW_INCLUDE_GIFS, slideshowIncludeGIFs).apply() var slideshowRandomOrder: Boolean get() = prefs.getBoolean(SLIDESHOW_RANDOM_ORDER, false) set(slideshowRandomOrder) = prefs.edit().putBoolean(SLIDESHOW_RANDOM_ORDER, slideshowRandomOrder).apply() var slideshowUseFade: Boolean get() = prefs.getBoolean(SLIDESHOW_USE_FADE, false) set(slideshowUseFade) = prefs.edit().putBoolean(SLIDESHOW_USE_FADE, slideshowUseFade).apply() var slideshowMoveBackwards: Boolean get() = prefs.getBoolean(SLIDESHOW_MOVE_BACKWARDS, false) set(slideshowMoveBackwards) = prefs.edit().putBoolean(SLIDESHOW_MOVE_BACKWARDS, slideshowMoveBackwards).apply() var loopSlideshow: Boolean get() = prefs.getBoolean(SLIDESHOW_LOOP, false) set(loopSlideshow) = prefs.edit().putBoolean(SLIDESHOW_LOOP, loopSlideshow).apply() var tempFolderPath: String get() = prefs.getString(TEMP_FOLDER_PATH, "") set(tempFolderPath) = prefs.edit().putString(TEMP_FOLDER_PATH, tempFolderPath).apply() }
apache-2.0
b652894907b1567337751a2fd0b8c0b0
41.857678
171
0.690728
4.28256
false
false
false
false
MartinStyk/AndroidApkAnalyzer
app/src/main/java/sk/styk/martin/apkanalyzer/manager/appanalysis/AndroidVersionManager.kt
1
674
package sk.styk.martin.apkanalyzer.manager.appanalysis import sk.styk.martin.apkanalyzer.R import sk.styk.martin.apkanalyzer.manager.resources.ResourcesManager import javax.inject.Inject const val MAX_SDK_VERSION = 33 class AndroidVersionManager @Inject constructor(private val resourcesManager: ResourcesManager) { fun resolveVersion(sdkVersion: Int?): String? { if (sdkVersion == null) return null //java index from 0 - first item is sdk 1 val index = sdkVersion - 1 val versions = resourcesManager.getStringArray(R.array.android_versions) return if (index >= 0 && index < versions.size) versions[index] else null } }
gpl-3.0
dd4c4e43904917ffd7d77516944b036b
32.7
97
0.732938
4.320513
false
false
false
false
quran/quran_android
common/search/src/main/java/com/quran/common/search/SearchTextUtil.kt
2
1762
package com.quran.common.search import java.text.Normalizer object SearchTextUtil { // via https://stackoverflow.com/questions/51731574/ private val nonSpacingCombiningCharactersRegex = "\\p{Mn}+".toRegex() // extra characters to remove when comparing non-Arabic strings private val charactersToReplaceRegex = "['`]".toRegex() // alifs with hamzas that we'll replace with \u0627 private val alifReplacementsRegex = "[\\u0622\\u0623\\u0625\\u0649]".toRegex() // waw with hamza to replace with \u0648 private val wawReplacementsRegex = "\\u0624".toRegex() // via https://stackoverflow.com/questions/25562974/ private val tashkeelRegex = "[\\x{064B}-\\x{065B}]|[\\x{063B}-\\x{063F}]|[\\x{064B}-\\x{065E}]|[\\x{066A}-\\x{06FF}]".toRegex() fun asSearchableString(string: String, isRtl: Boolean): String { return if (isRtl) { string .replace(tashkeelRegex, "") .replace(alifReplacementsRegex, "\u0627") .replace(wawReplacementsRegex, "\u0648") } else { val normalizedString = Normalizer.normalize(string, Normalizer.Form.NFKD) normalizedString .replace(nonSpacingCombiningCharactersRegex, "") .replace(charactersToReplaceRegex, "") .lowercase() } } fun isRtl(s: String): Boolean { val characters = s.toCharArray() for (character in characters) { val directionality = Character.getDirectionality(character).toInt() if (directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT.toInt() || directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC.toInt() ) { return true } else if (directionality == Character.DIRECTIONALITY_LEFT_TO_RIGHT.toInt()) { return false } } return false } }
gpl-3.0
0c9d215c9820d9177c629a7a7e09ff76
36.489362
129
0.675369
3.701681
false
false
false
false
rjhdby/motocitizen
Motocitizen/src/motocitizen/ui/frames/create/DescriptionFrame.kt
1
1690
package motocitizen.ui.frames.create import android.support.v4.app.FragmentActivity import android.text.Editable import android.text.TextWatcher import android.view.View import android.widget.Button import android.widget.EditText import motocitizen.content.accident.AccidentBuilder import motocitizen.main.R import motocitizen.ui.frames.FrameInterface import motocitizen.utils.hide import motocitizen.utils.show class DescriptionFrame(val context: FragmentActivity, val accidentBuilder: AccidentBuilder, val callback: () -> Unit) : FrameInterface { private val confirmButton = context.findViewById(R.id.CREATE) as Button private val view = context.findViewById<View>(R.id.create_final_frame) init { confirmButton.isEnabled = false confirmButton.setOnClickListener { callback() } (context.findViewById(R.id.create_final_text) as EditText).addTextChangedListener(finalTextWatcher()) } override fun show() { view.show() setConfirmButtonStatus() } override fun hide() { view.hide() confirmButton.isEnabled = false } private fun finalTextWatcher(): TextWatcher = object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { accidentBuilder.description = s.toString() setConfirmButtonStatus() } override fun afterTextChanged(s: Editable) {} } private fun setConfirmButtonStatus() { confirmButton.isEnabled = accidentBuilder.type.isAccident() || accidentBuilder.description.length > 6 } }
mit
50b63937f4a69f477d257f4ba1d2b84c
33.510204
136
0.723669
4.592391
false
false
false
false
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/kpspemu/hle/modules/ThreadManForUser.kt
1
10795
package com.soywiz.kpspemu.hle.modules import com.soywiz.kpspemu.* import com.soywiz.kpspemu.cpu.* import com.soywiz.kpspemu.hle.* import com.soywiz.kpspemu.util.* @Suppress("UNUSED_PARAMETER", "MemberVisibilityCanPrivate") class ThreadManForUser(emulator: Emulator) : SceModule(emulator, "ThreadManForUser", 0x40010011, "threadman.prx", "sceThreadManager") { val thread = ThreadManForUser_Thread(this) val callback = ThreadManForUser_Callback(this) val mbx = ThreadManForUser_Mbx(this) val sema = ThreadManForUser_Sema(this) val mutex = ThreadManForUser_Mutex(this) val time = ThreadManForUser_Time(this) val eflags = ThreadManForUser_EventFlags(this) val fpl = ThreadManForUser_Fpl(this) val vpl = ThreadManForUser_Vpl(this) val alarm = ThreadManForUser_Alarm(this) fun sceKernelGetVTimerTime(cpu: CpuState): Unit = UNIMPLEMENTED(0x034A921F) fun _sceKernelReturnFromTimerHandler(cpu: CpuState): Unit = UNIMPLEMENTED(0x0E927AED) fun sceKernelUSec2SysClock(cpu: CpuState): Unit = UNIMPLEMENTED(0x110DEC9A) fun sceKernelCreateVTimer(cpu: CpuState): Unit = UNIMPLEMENTED(0x20FFF560) fun sceKernelGetCallbackCount(cpu: CpuState): Unit = UNIMPLEMENTED(0x2A3D44FF) fun ThreadManForUser_31327F19(cpu: CpuState): Unit = UNIMPLEMENTED(0x31327F19) fun sceKernelDeleteVTimer(cpu: CpuState): Unit = UNIMPLEMENTED(0x328F9E52) fun sceKernelReferMsgPipeStatus(cpu: CpuState): Unit = UNIMPLEMENTED(0x33BE4024) fun sceKernelCancelMsgPipe(cpu: CpuState): Unit = UNIMPLEMENTED(0x349B864D) fun sceKernelSetVTimerHandlerWide(cpu: CpuState): Unit = UNIMPLEMENTED(0x53B00E9A) fun sceKernelSetVTimerTime(cpu: CpuState): Unit = UNIMPLEMENTED(0x542AD630) fun sceKernelReferVTimerStatus(cpu: CpuState): Unit = UNIMPLEMENTED(0x5F32BEAA) fun sceKernelReferSystemStatus(cpu: CpuState): Unit = UNIMPLEMENTED(0x627E6F3A) fun _sceKernelReturnFromCallback(cpu: CpuState): Unit = UNIMPLEMENTED(0x6E9EA350) fun ThreadManForUser_71040D5C(cpu: CpuState): Unit = UNIMPLEMENTED(0x71040D5C) fun sceKernelReleaseThreadEventHandler(cpu: CpuState): Unit = UNIMPLEMENTED(0x72F3C145) fun sceKernelReferCallbackStatus(cpu: CpuState): Unit = UNIMPLEMENTED(0x730ED8BC) fun sceKernelReceiveMsgPipe(cpu: CpuState): Unit = UNIMPLEMENTED(0x74829B76) fun sceKernelCreateMsgPipe(cpu: CpuState): Unit = UNIMPLEMENTED(0x7C0DC2A0) fun sceKernelSendMsgPipeCB(cpu: CpuState): Unit = UNIMPLEMENTED(0x7C41F2C2) fun ThreadManForUser_7CFF8CF3(cpu: CpuState): Unit = UNIMPLEMENTED(0x7CFF8CF3) fun sceKernelReferGlobalProfiler(cpu: CpuState): Unit = UNIMPLEMENTED(0x8218B4DD) fun ThreadManForUser_8672E3D0(cpu: CpuState): Unit = UNIMPLEMENTED(0x8672E3D0) fun sceKernelSendMsgPipe(cpu: CpuState): Unit = UNIMPLEMENTED(0x876DBFAD) fun sceKernelTrySendMsgPipe(cpu: CpuState): Unit = UNIMPLEMENTED(0x884C9F90) fun sceKernelGetVTimerBase(cpu: CpuState): Unit = UNIMPLEMENTED(0xB3A59970) fun sceKernelGetVTimerBaseWide(cpu: CpuState): Unit = UNIMPLEMENTED(0xB7C18B77) fun sceKernelSysClock2USec(cpu: CpuState): Unit = UNIMPLEMENTED(0xBA6B92E2) fun ThreadManForUser_BEED3A47(cpu: CpuState): Unit = UNIMPLEMENTED(0xBEED3A47) fun sceKernelGetVTimerTimeWide(cpu: CpuState): Unit = UNIMPLEMENTED(0xC0B3FFD2) fun sceKernelStartVTimer(cpu: CpuState): Unit = UNIMPLEMENTED(0xC68D9437) fun sceKernelUSec2SysClockWide(cpu: CpuState): Unit = UNIMPLEMENTED(0xC8CD158C) fun sceKernelStopVTimer(cpu: CpuState): Unit = UNIMPLEMENTED(0xD0AEEE87) fun sceKernelCancelVTimerHandler(cpu: CpuState): Unit = UNIMPLEMENTED(0xD2D615EF) fun sceKernelSetVTimerHandler(cpu: CpuState): Unit = UNIMPLEMENTED(0xD8B299AE) fun sceKernelTryReceiveMsgPipe(cpu: CpuState): Unit = UNIMPLEMENTED(0xDF52098F) fun sceKernelSysClock2USecWide(cpu: CpuState): Unit = UNIMPLEMENTED(0xE1619D7C) fun sceKernelDeleteMsgPipe(cpu: CpuState): Unit = UNIMPLEMENTED(0xF0B7DA1C) fun sceKernelSetVTimerTimeWide(cpu: CpuState): Unit = UNIMPLEMENTED(0xFB6425C3) fun sceKernelReceiveMsgPipeCB(cpu: CpuState): Unit = UNIMPLEMENTED(0xFBFA697D) override fun registerModule() { thread.registerSubmodule() mbx.registerSubmodule() callback.registerSubmodule() time.registerSubmodule() sema.registerSubmodule() mutex.registerSubmodule() eflags.registerSubmodule() fpl.registerSubmodule() vpl.registerSubmodule() alarm.registerSubmodule() registerFunctionRaw("sceKernelGetVTimerTime", 0x034A921F, since = 150) { sceKernelGetVTimerTime(it) } registerFunctionRaw( "_sceKernelReturnFromTimerHandler", 0x0E927AED, since = 150 ) { _sceKernelReturnFromTimerHandler(it) } registerFunctionRaw("sceKernelUSec2SysClock", 0x110DEC9A, since = 150) { sceKernelUSec2SysClock(it) } registerFunctionRaw("sceKernelCreateVTimer", 0x20FFF560, since = 150) { sceKernelCreateVTimer(it) } registerFunctionRaw("sceKernelGetCallbackCount", 0x2A3D44FF, since = 150) { sceKernelGetCallbackCount(it) } registerFunctionRaw("ThreadManForUser_31327F19", 0x31327F19, since = 150) { ThreadManForUser_31327F19(it) } registerFunctionRaw("sceKernelDeleteVTimer", 0x328F9E52, since = 150) { sceKernelDeleteVTimer(it) } registerFunctionRaw("sceKernelReferMsgPipeStatus", 0x33BE4024, since = 150) { sceKernelReferMsgPipeStatus(it) } registerFunctionRaw("sceKernelCancelMsgPipe", 0x349B864D, since = 150) { sceKernelCancelMsgPipe(it) } registerFunctionRaw( "sceKernelSetVTimerHandlerWide", 0x53B00E9A, since = 150 ) { sceKernelSetVTimerHandlerWide(it) } registerFunctionRaw("sceKernelSetVTimerTime", 0x542AD630, since = 150) { sceKernelSetVTimerTime(it) } registerFunctionRaw("sceKernelReferVTimerStatus", 0x5F32BEAA, since = 150) { sceKernelReferVTimerStatus(it) } registerFunctionRaw("sceKernelReferSystemStatus", 0x627E6F3A, since = 150) { sceKernelReferSystemStatus(it) } registerFunctionRaw( "_sceKernelReturnFromCallback", 0x6E9EA350, since = 150 ) { _sceKernelReturnFromCallback(it) } registerFunctionRaw("ThreadManForUser_71040D5C", 0x71040D5C, since = 150) { ThreadManForUser_71040D5C(it) } registerFunctionRaw( "sceKernelReleaseThreadEventHandler", 0x72F3C145, since = 150 ) { sceKernelReleaseThreadEventHandler(it) } registerFunctionRaw( "sceKernelReferCallbackStatus", 0x730ED8BC, since = 150 ) { sceKernelReferCallbackStatus(it) } registerFunctionRaw("sceKernelReceiveMsgPipe", 0x74829B76, since = 150) { sceKernelReceiveMsgPipe(it) } registerFunctionRaw("sceKernelCreateMsgPipe", 0x7C0DC2A0, since = 150) { sceKernelCreateMsgPipe(it) } registerFunctionRaw("sceKernelSendMsgPipeCB", 0x7C41F2C2, since = 150) { sceKernelSendMsgPipeCB(it) } registerFunctionRaw("ThreadManForUser_7CFF8CF3", 0x7CFF8CF3, since = 150) { ThreadManForUser_7CFF8CF3(it) } registerFunctionRaw( "sceKernelReferGlobalProfiler", 0x8218B4DD, since = 150 ) { sceKernelReferGlobalProfiler(it) } registerFunctionRaw("ThreadManForUser_8672E3D0", 0x8672E3D0, since = 150) { ThreadManForUser_8672E3D0(it) } registerFunctionRaw("sceKernelSendMsgPipe", 0x876DBFAD, since = 150) { sceKernelSendMsgPipe(it) } registerFunctionRaw("sceKernelTrySendMsgPipe", 0x884C9F90, since = 150) { sceKernelTrySendMsgPipe(it) } registerFunctionRaw("sceKernelGetVTimerBase", 0xB3A59970, since = 150) { sceKernelGetVTimerBase(it) } registerFunctionRaw("sceKernelGetVTimerBaseWide", 0xB7C18B77, since = 150) { sceKernelGetVTimerBaseWide(it) } registerFunctionRaw("sceKernelSysClock2USec", 0xBA6B92E2, since = 150) { sceKernelSysClock2USec(it) } registerFunctionRaw("ThreadManForUser_BEED3A47", 0xBEED3A47, since = 150) { ThreadManForUser_BEED3A47(it) } registerFunctionRaw("sceKernelGetVTimerTimeWide", 0xC0B3FFD2, since = 150) { sceKernelGetVTimerTimeWide(it) } registerFunctionRaw("sceKernelStartVTimer", 0xC68D9437, since = 150) { sceKernelStartVTimer(it) } registerFunctionRaw("sceKernelUSec2SysClockWide", 0xC8CD158C, since = 150) { sceKernelUSec2SysClockWide(it) } registerFunctionRaw("sceKernelStopVTimer", 0xD0AEEE87, since = 150) { sceKernelStopVTimer(it) } registerFunctionRaw( "sceKernelCancelVTimerHandler", 0xD2D615EF, since = 150 ) { sceKernelCancelVTimerHandler(it) } registerFunctionRaw("sceKernelSetVTimerHandler", 0xD8B299AE, since = 150) { sceKernelSetVTimerHandler(it) } registerFunctionRaw("sceKernelTryReceiveMsgPipe", 0xDF52098F, since = 150) { sceKernelTryReceiveMsgPipe(it) } registerFunctionRaw("sceKernelSysClock2USecWide", 0xE1619D7C, since = 150) { sceKernelSysClock2USecWide(it) } registerFunctionRaw("sceKernelDeleteMsgPipe", 0xF0B7DA1C, since = 150) { sceKernelDeleteMsgPipe(it) } registerFunctionRaw("sceKernelSetVTimerTimeWide", 0xFB6425C3, since = 150) { sceKernelSetVTimerTimeWide(it) } registerFunctionRaw("sceKernelReceiveMsgPipeCB", 0xFBFA697D, since = 150) { sceKernelReceiveMsgPipeCB(it) } } } class SceKernelSemaInfo( var size: Int = 0, var name: String = "", var attributes: Int = 0, // SemaphoreAttribute var initialCount: Int = 0, var currentCount: Int = 0, var maximumCount: Int = 0, var numberOfWaitingThreads: Int = 0 ) { companion object : Struct<SceKernelSemaInfo>( { SceKernelSemaInfo() }, SceKernelSemaInfo::size AS INT32, SceKernelSemaInfo::name AS STRINGZ(32), SceKernelSemaInfo::attributes AS INT32, SceKernelSemaInfo::initialCount AS INT32, SceKernelSemaInfo::currentCount AS INT32, SceKernelSemaInfo::maximumCount AS INT32, SceKernelSemaInfo::numberOfWaitingThreads AS INT32 ) } class K0Structure( var unk: IntArray = IntArray(48), // +0000 var threadId: Int = 0, // +00C0 var unk1: Int = 0, // +00C4 var stackAddr: Int = 0, // +00C8 var unk3: IntArray = IntArray(11),// +00CC var f1: Int = 0, // +00F8 var f2: Int = 0 // +00FC ) { companion object : Struct<K0Structure>( { K0Structure() }, K0Structure::unk AS INTLIKEARRAY(INT32, 48), K0Structure::threadId AS INT32, K0Structure::unk1 AS INT32, K0Structure::stackAddr AS INT32, K0Structure::unk3 AS INTLIKEARRAY(INT32, 11), K0Structure::f1 AS INT32, K0Structure::f2 AS INT32 ) }
mit
e69f496ee3ea6511f38bcfeb1690e360
56.73262
119
0.727189
3.646959
false
false
false
false
luks91/Team-Bucket
app/src/main/java/com/github/luks91/teambucket/main/reviewers/ReviewersFragment.kt
2
2721
/** * Copyright (c) 2017-present, Team Bucket Contributors. * * 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.github.luks91.teambucket.main.reviewers import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.github.luks91.teambucket.R import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import com.github.luks91.teambucket.main.base.BasePullRequestsFragment import com.github.luks91.teambucket.model.* import com.jakewharton.rxrelay2.PublishRelay import com.jakewharton.rxrelay2.Relay import javax.inject.Inject class ReviewersFragment : BasePullRequestsFragment<ReviewersView, ReviewersPresenter>(), ReviewersView { private val reviewsForUserSubject: Relay<IndexedValue<User>> = PublishRelay.create() private val imageLoadRequests: Relay<AvatarLoadRequest> = PublishRelay.create() private val layoutManager by lazy { LinearLayoutManager(context) } private val dataAdapter by lazy { ReviewersAdapter(context, imageLoadRequests, reviewsForUserSubject, layoutManager) } @Inject lateinit var reviewersPresenter: ReviewersPresenter companion object Factory { fun newInstance() = ReviewersFragment() } override fun createPresenter() = reviewersPresenter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater.inflate(R.layout.fragment_swipe_recycler_view, container, false) override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val recyclerView = view!!.findViewById(R.id.reviewersRecyclerView) as RecyclerView recyclerView.layoutManager = layoutManager recyclerView.adapter = dataAdapter } override fun onReviewersReceived(reviewers: ReviewersInformation) = dataAdapter.onReviewersReceived(reviewers) override fun intentRetrieveReviews() = reviewsForUserSubject override fun onPullRequestsProvided(reviews: List<IndexedValue<PullRequest>>) = dataAdapter.onPullRequestsProvided(reviews) override fun intentLoadAvatarImage() = imageLoadRequests }
apache-2.0
097630755968be8db45ce4f6834a5c2f
43.622951
127
0.787211
4.798942
false
false
false
false
jansorg/BashSupport
src/com/ansorgit/plugins/bash/util/BashIcons.kt
1
2567
/* * Copyright (c) Joachim Ansorg, [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 com.ansorgit.plugins.bash.util import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.IconLoader import com.intellij.util.PlatformIcons import javax.swing.Icon /** * Providese the icons which are available in the BashSupport plugin. * * @author jansorg */ object BashIcons { private val LOG = Logger.getInstance("#bash.icons") @JvmField val BASH_FILE_ICON = load("/icons/fileTypes/BashFileIcon.png") // icon used to render regular script functions @JvmField val FUNCTION_ICON = load("/icons/fileTypes/BashFileIcon.png") // icon used to render regular script variables in code completion @JvmField val VAR_ICON = load("/icons/fileTypes/BashFileIcon.png") // icon used to render BashSupport's global variables stored in settings @JvmField val GLOBAL_VAR_ICON = load("/icons/global-var-16.png") // icon used to render Bash's built-in variables @JvmField val BASH_VAR_ICON = load("/icons/bash-var-16.png") // icon used to render Bash's built-in variables of version 4 or later @JvmField val BOURNE_VAR_ICON = load("/icons/bash-var-16.png") // https://github.com/BashSupport/BashSupport/issues/611 // a concurrent modification exception is raised when we load the icon. // we assume that this is caused by a modification of the icon patchers by another plugin at the same time // as BashSupport's classes are initialized (and call the IconLoader's findIcon methods) // we use "findIcon(URL)" which isn't using the icon patcher to work around this issue private fun load(resourcePath: String): Icon { val icon = try { val url = BashIcons::class.java.getResource(resourcePath) IconLoader.findIcon(url, true) } catch (e: Exception) { LOG.warn("Error while loading icon $resourcePath", e) null } return icon ?: PlatformIcons.FILE_ICON } }
apache-2.0
a3d9017abecf3b502da2bf59557c5822
35.671429
110
0.706272
4.100639
false
false
false
false
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/storage/datacache/impl/DataCacheStorageImpl.kt
1
6408
/* * Copyright 2022 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 com.google.android.libraries.pcc.chronicle.storage.datacache.impl import android.util.LruCache import com.google.android.libraries.pcc.chronicle.api.storage.WrappedEntity import com.google.android.libraries.pcc.chronicle.api.storage.toInstant import com.google.android.libraries.pcc.chronicle.storage.datacache.DataCacheStorage import com.google.android.libraries.pcc.chronicle.util.Logcat import com.google.android.libraries.pcc.chronicle.util.TimeSource import java.time.Duration import kotlinx.atomicfu.atomic import kotlinx.atomicfu.update /** A [LruCache] based implementation of [DataCacheStorage]. */ class DataCacheStorageImpl(private val timeSource: TimeSource) : DataCacheStorage { private val entityStore = atomic(emptyMap<Class<*>, DataCacheWrapper<*>>()) override val registeredDataTypes: Set<Class<*>> get() = entityStore.value.keys override fun <T> registerDataType(cls: Class<T>, maxSize: Int, onDisk: Boolean, ttl: Duration) { entityStore.update { currentMap -> val currentCache = storeForClass(cls) currentCache?.resize(maxSize) val newEntry = DataCacheWrapper(cache = currentCache ?: LruCache(maxSize), config = CacheConfig(ttl)) currentMap + (cls to newEntry) } logger.d("[%s] registerDataType : %s", className, cls.name) } override fun <T> unregisterDataType(cls: Class<T>) { removeAll(cls) entityStore.update { it - cls } logger.d("[%s] unregisterDataType : %s", className, cls.name) } override fun <T> size(cls: Class<T>): Int = all(cls).size override fun <T> get(cls: Class<T>, id: String): WrappedEntity<T>? { val dataCacheWrapper = dataCacheWrapperForClass(cls) ?: return null val lookupEntityWrapper = dataCacheWrapper.cache.get(id) ?: return null val ttl = dataCacheWrapper.config.ttl if (lookupEntityWrapper.isExpired(ttl)) { return null } return lookupEntityWrapper } override fun <T> put(cls: Class<out T>, entity: WrappedEntity<T>): Boolean { val entityCache = storeForClass(cls) ?: return false entityCache.put(entity.metadata.id, entity) return true } override fun <T> remove(cls: Class<T>, id: String): WrappedEntity<T>? = storeForClass(cls)?.remove(id) override fun <T> all(cls: Class<T>): List<WrappedEntity<T>> { val dataCacheWrapper = dataCacheWrapperForClass(cls) ?: return emptyList() val ttl = dataCacheWrapper.config.ttl return dataCacheWrapper.cache.snapshot().values.filterNot { it.isExpired(ttl) } } override fun <T> allAsMap(cls: Class<T>): Map<String, WrappedEntity<T>> { val dataCacheWrapper = dataCacheWrapperForClass(cls) ?: return emptyMap() val ttl = dataCacheWrapper.config.ttl return dataCacheWrapper.cache.snapshot().filterNot { it.value.isExpired(ttl) } } override fun <T> removeAll(cls: Class<T>) { storeForClass(cls)?.evictAll() } override fun purgeExpiredEntities() { logger.d("[%s]: purging entities from data cache.", className) entityStore.value.values.forEach { dataCacheWrapper -> val ttl = dataCacheWrapper.config.ttl dataCacheWrapper.purgeEntitiesWhere { it.isExpired(ttl) } } } override fun purgeAllEntitiesForPackage(packageName: String): Int { logger.d("[%s]: purging all entities for package removal.", className) return entityStore.value.values .map { dataCacheWrapper -> dataCacheWrapper.purgeEntitiesWhere { packageName in it.metadata.associatedPackageNamesList } } .sum() } override fun <T> purgeEntitiesForPackage(cls: Class<T>, packageName: String): Int { logger.d("[%s]: purging %s entities for package removal.", className, cls.name) return dataCacheWrapperForClass(cls)?.purgeEntitiesWhere { packageName in it.metadata.associatedPackageNamesList } ?: 0 } override fun purgeAllEntitiesNotInPackages(packages: Set<String>): Int { logger.d("[%s]: purging entities for package reconciliation.", className) return entityStore.value.values .map { dataCacheWrapper -> dataCacheWrapper.purgeEntitiesWhere { it.metadata.associatedPackageNamesList.all { pkg -> pkg !in packages } } } .sum() } override fun <T> purgeEntitiesWhere( cls: Class<T>, predicate: (WrappedEntity<*>) -> Boolean ): Int = dataCacheWrapperForClass(cls)?.purgeEntitiesWhere(predicate) ?: 0 override fun purgeAllEntities(): Int { return entityStore.value.values .map { dataCacheWrapper -> dataCacheWrapper.purgeEntitiesWhere { true } } .sum() } private fun WrappedEntity<*>.isExpired(ttl: Duration): Boolean = metadata.created.toInstant().plusMillis(ttl.toMillis()).isBefore(timeSource.now()) private fun DataCacheWrapper<*>.purgeEntitiesWhere( predicate: (WrappedEntity<*>) -> Boolean ): Int { return cache .snapshot() .asSequence() .filter { (_, entity) -> predicate(entity) } .map { (key, _) -> cache.remove(key) } .count() } @Suppress("UNCHECKED_CAST") private fun <T> storeForClass(cls: Class<out T>): LruCache<String, WrappedEntity<T>>? = dataCacheWrapperForClass(cls)?.cache as? LruCache<String, WrappedEntity<T>> @Suppress("UNCHECKED_CAST") private fun <T> dataCacheWrapperForClass(cls: Class<T>): DataCacheWrapper<T>? { val result = entityStore.value[cls] as? DataCacheWrapper<T> if (result == null) { logger.d("[%s] no store registered for %s.", className, cls) } return result } companion object { private val logger = Logcat.default private val className = DataCacheStorageImpl::class.java.simpleName } } data class DataCacheWrapper<T>( val cache: LruCache<String, WrappedEntity<T>>, val config: CacheConfig ) data class CacheConfig(val ttl: Duration)
apache-2.0
83707f76094b824324bc66f85e18f1d1
34.6
98
0.706461
4.155642
false
false
false
false
premnirmal/StockTicker
app/src/main/kotlin/com/github/premnirmal/ticker/repo/StocksStorage.kt
1
6945
package com.github.premnirmal.ticker.repo import android.content.SharedPreferences import androidx.room.withTransaction import com.github.premnirmal.ticker.network.data.Holding import com.github.premnirmal.ticker.network.data.Position import com.github.premnirmal.ticker.network.data.Properties import com.github.premnirmal.ticker.network.data.Quote import com.github.premnirmal.ticker.repo.data.HoldingRow import com.github.premnirmal.ticker.repo.data.PropertiesRow import com.github.premnirmal.ticker.repo.data.QuoteRow import com.google.gson.Gson import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import javax.inject.Inject import javax.inject.Singleton /** * Created by premnirmal on 2/28/16. */ @Singleton class StocksStorage @Inject constructor( private val preferences: SharedPreferences, private val gson: Gson, private val db: QuotesDB, private val quoteDao: QuoteDao ) { companion object { private const val KEY_TICKERS = "TICKERS" } fun saveTickers(tickers: Set<String>) { preferences.edit() .putStringSet(KEY_TICKERS, tickers) .apply() } fun readTickers(): Set<String> { return preferences.getStringSet( KEY_TICKERS, emptySet())!! } suspend fun readQuotes(): List<Quote> { val quotesWithHoldings = db.withTransaction { quoteDao.getQuotesWithHoldings() } return withContext(Dispatchers.IO) { return@withContext quotesWithHoldings.map { quoteWithHoldings -> val quote = quoteWithHoldings.quote.toQuote() val holdings = quoteWithHoldings.holdings.map { holdingTable -> Holding( holdingTable.quoteSymbol, holdingTable.shares, holdingTable.price, holdingTable.id!! ) } quote.position = Position(quote.symbol, holdings.toMutableList()) quote.properties = quoteWithHoldings.properties?.toProperties() quote } } } suspend fun readQuote(symbol: String): Quote? { val quoteWithHolding = db.withTransaction { quoteDao.getQuoteWithHoldings(symbol) } return withContext(Dispatchers.IO) { quoteWithHolding?.let { val quote = quoteWithHolding.quote.toQuote() val holdings = quoteWithHolding.holdings.map { holdingTable -> Holding( holdingTable.quoteSymbol, holdingTable.shares, holdingTable.price, holdingTable.id!! ) } quote.position = Position(quote.symbol, holdings.toMutableList()) quote.properties = quoteWithHolding.properties?.toProperties() quote } } } suspend fun saveQuote(quote: Quote) = db.withTransaction { quoteDao.upsertQuoteAndHolding(quote.toQuoteRow(), quote.position?.toHoldingRows()) } suspend fun saveQuotes(quotes: List<Quote>) = withContext(Dispatchers.IO) { val quoteRows = quotes.map { it.toQuoteRow() } val positions = quotes.mapNotNull { it.position } val properties = quotes.mapNotNull { it.properties } db.withTransaction { quoteDao.upsertQuotes(quoteRows) positions.forEach { quoteDao.upsertHoldings(it.symbol, it.toHoldingRows()) } properties.forEach { quoteDao.upsertProperties(it.toPropertiesRow()) } } } suspend fun removeQuoteBySymbol(symbol: String) = db.withTransaction { quoteDao.deleteQuoteAndHoldings(symbol) } suspend fun removeQuotesBySymbol(tickers: List<String>) = db.withTransaction { quoteDao.deleteQuotesAndHoldings(tickers) } suspend fun addHolding(holding: Holding) = db.withTransaction { quoteDao.insertHolding(holding.toHoldingRow()) } suspend fun removeHolding( ticker: String, holding: Holding ) = db.withTransaction { quoteDao.deleteHolding(HoldingRow(holding.id, ticker, holding.shares, holding.price)) } suspend fun saveQuoteProperties( properties: Properties ) = db.withTransaction { quoteDao.upsertProperties(properties.toPropertiesRow()) } private fun Quote.toQuoteRow(): QuoteRow { return QuoteRow( this.symbol, this.name, this.lastTradePrice, this.changeInPercent, this.change, this.stockExchange, this.currencyCode, this.isPostMarket, this.annualDividendRate, this.annualDividendYield, this.dayHigh, this.dayLow, this.previousClose, this.open, this.regularMarketVolume?.toFloat(), this.trailingPE, this.fiftyTwoWeekLowChange, this.fiftyTwoWeekLowChangePercent, this.fiftyTwoWeekHighChange, this.fiftyTwoWeekHighChangePercent, this.fiftyTwoWeekLow, this.fiftyTwoWeekHigh, this.dividendDate?.toFloat(), this.earningsTimestamp?.toFloat(), this.marketCap?.toFloat(), this.tradeable, this.triggerable, this.marketState ) } private fun Position.toHoldingRows(): List<HoldingRow> { return this.holdings.map { HoldingRow(it.id, this.symbol, it.shares, it.price) } } private fun Holding.toHoldingRow(): HoldingRow { return HoldingRow(this.id, this.symbol, this.shares, this.price) } private fun QuoteRow.toQuote(): Quote { val quote = Quote( symbol = this.symbol, name = this.name, lastTradePrice = this.lastTradePrice, changeInPercent = this.changeInPercent, change = this.change ) quote.name = this.name quote.lastTradePrice = this.lastTradePrice quote.changeInPercent = this.changeInPercent quote.change = this.change quote.stockExchange = this.stockExchange quote.currencyCode = this.currency quote.isPostMarket = this.isPostMarket quote.annualDividendRate = this.annualDividendRate quote.annualDividendYield = this.annualDividendYield quote.dayHigh = this.dayHigh quote.dayLow = this.dayLow quote.previousClose = this.previousClose quote.open = this.open quote.regularMarketVolume = this.regularMarketVolume?.toLong() quote.trailingPE = this.peRatio quote.fiftyTwoWeekLowChange = this.fiftyTwoWeekLowChange quote.fiftyTwoWeekLowChangePercent = this.fiftyTwoWeekLowChangePercent quote.fiftyTwoWeekHighChange = this.fiftyTwoWeekHighChange quote.fiftyTwoWeekHighChangePercent = this.fiftyTwoWeekHighChangePercent quote.fiftyTwoWeekLow = this.fiftyTwoWeekLow quote.fiftyTwoWeekHigh = this.fiftyTwoWeekHigh quote.dividendDate = this.dividendDate?.toLong() quote.earningsTimestamp = this.earningsDate?.toLong() quote.marketCap = this.marketCap?.toLong() quote.tradeable = this.isTradeable ?: false quote.triggerable = this.isTriggerable ?: false quote.marketState = this.marketState ?: "" return quote } private fun PropertiesRow.toProperties(): Properties { return Properties( this.quoteSymbol, this.notes, this.alertAbove, this.alertBelow ) } private fun Properties.toPropertiesRow(): PropertiesRow { return PropertiesRow(this.id, this.symbol, this.notes, this.alertAbove, this.alertBelow) } }
gpl-3.0
df97ff593c4f79c212fb9e010c197199
34.075758
98
0.72167
4.206541
false
false
false
false
AlmasB/FXGL
fxgl-scene/src/main/kotlin/com/almasb/fxgl/notification/impl/NotificationServiceProvider.kt
1
3594
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.notification.impl import com.almasb.fxgl.core.Inject import com.almasb.fxgl.core.reflect.ReflectionUtils import com.almasb.fxgl.notification.Notification import com.almasb.fxgl.notification.NotificationService import com.almasb.fxgl.notification.view.NotificationView import com.almasb.fxgl.scene.SceneService import javafx.scene.Group import javafx.scene.Node import javafx.scene.paint.Color import javafx.util.Duration import java.util.* /** * @author Almas Baimagambetov ([email protected]) */ class NotificationServiceProvider : NotificationService() { private val ANIMATION_DURATION = Duration.seconds(1.0) private val NOTIFICATION_DURATION = Duration.seconds(3.0) override var backgroundColor: Color set(value) { notificationView.backgroundColor = value } get() = notificationView.backgroundColor override var textColor: Color set(value) { notificationView.textColor = value } get() = notificationView.textColor private val queue = ArrayDeque<Notification>() private var showing = false private lateinit var sceneService: SceneService private val overlayRoot get() = sceneService.overlayRoot private val timer get() = sceneService.timer @Inject("notificationViewClass") private lateinit var notificationViewClass: Class<out NotificationView> private val notificationView by lazy { ReflectionUtils.newInstance(notificationViewClass).also { it.appWidth = sceneService.prefWidth.toInt() it.appHeight = sceneService.prefHeight.toInt() } } /** * Shows a notification with given text. * Only 1 notification can be shown at a time. * If a notification is being shown already, next notifications * will be queued to be shown as soon as space available. * * @param message the text to show */ override fun pushNotification(message: String) { pushNotification(message, Group()) } override fun pushNotification(message: String, icon: Node) { val notification = Notification(message, icon) queue.add(notification) if (!showing) { showFirstNotification() } } private fun nextNotification() { if (queue.isNotEmpty()) { val n = queue.poll() notificationView.push(n) fireAndScheduleNextNotification(n) } else { notificationView.playOutAnimation() timer.runOnceAfter(this::checkLastPop, ANIMATION_DURATION) } } private fun checkLastPop() { if (queue.isEmpty()) { overlayRoot.children -= notificationView showing = false } else { // play in animation notificationView.playInAnimation() timer.runOnceAfter(this::nextNotification, ANIMATION_DURATION) } } private fun showFirstNotification() { showing = true overlayRoot.children += notificationView // play in animation notificationView.playInAnimation() timer.runOnceAfter(this::nextNotification, ANIMATION_DURATION) } private fun fireAndScheduleNextNotification(notification: Notification) { // schedule next timer.runOnceAfter(this::nextNotification, NOTIFICATION_DURATION) } override fun onUpdate(tpf: Double) { notificationView.onUpdate(tpf) } }
mit
2d549a53ebdcc4ff57b3fa34ec28b80d
27.991935
77
0.677518
4.735178
false
false
false
false
NLPIE/BioMedICUS
biomedicus-core/src/main/kotlin/edu/umn/biomedicus/measures/Numbers.kt
1
3195
/* * Copyright (c) 2018 Regents of the University of Minnesota. * * 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 edu.umn.biomedicus.measures import edu.umn.biomedicus.framework.TagEx import edu.umn.biomedicus.framework.TagExFactory import edu.umn.biomedicus.framework.get import edu.umn.biomedicus.numbers.NumberType import edu.umn.nlpengine.Document import edu.umn.nlpengine.DocumentsProcessor import edu.umn.nlpengine.Label import edu.umn.nlpengine.LabelMetadata import java.math.BigDecimal import javax.inject.Inject /** * A number in text. * @property numerator the BigDecimal representation * @property denominator the BigDecimal representation * @property numberType */ @LabelMetadata(classpath = "biomedicus.v2", distinct = true) data class Number( override val startIndex: Int, override val endIndex: Int, val numerator: String, val denominator: String, val numberType: NumberType ) : Label() { fun value(): BigDecimal { return BigDecimal(numerator).divide(BigDecimal(denominator), BigDecimal.ROUND_HALF_UP) } } /** * A number range from one number to another in text. */ @LabelMetadata(classpath = "biomedicus.v2", distinct = true) data class NumberRange( override val startIndex: Int, override val endIndex: Int, val lower: BigDecimal, val upper: BigDecimal ) : Label() /** * The document processor which is responsible for detecting number ranges in text. */ class NumberRangesLabeler(val expr: TagEx) : DocumentsProcessor { @Inject internal constructor(tagExFactory: TagExFactory) : this( tagExFactory.parse( "(?<range> [?lower:Number] ParseToken<getText=\"-\"|i\"to\"> -> upper:Number | [?ParseToken<getText=i\"between\">] -> lower:Number ParseToken<getText=\"and\"> -> upper:Number)" ) ) override fun process(document: Document) { val labeler = document.labeler(NumberRange::class.java) for (tagExResult in expr.findAll(document)) { val lower: Number = tagExResult.namedLabels["lower"] ?: error("lower should always have value") val upper: Number = tagExResult.namedLabels["upper"] ?: error("upper should always have value") val lowerValue = lower.value() val upperValue = upper.value() if (upperValue > lowerValue) { val (startIndex, endIndex) = tagExResult.namedSpans["range"] ?: error("range should always have value") labeler.add(NumberRange(startIndex, endIndex, lowerValue, upperValue)) } } } }
apache-2.0
db6dc7f97d96a0b222c42800391b418e
34.898876
196
0.67856
4.335142
false
false
false
false
funfunStudy/algorithm
kotlin/src/main/kotlin/PriyankaAndToys.kt
1
1184
import java.util.Scanner object PriyankaAndToys { @JvmStatic fun main(args: Array<String>) { val sc = Scanner(System.`in`) sc.nextLine() // val nums: ArrayList<Int> = arrayListOf() // // for (i in 0 until cases) { // nums.add(sc.nextInt()) // } // nums.sort() val inputLine = sc.nextLine() val nums = inputLine .split(" ") .map { it.toInt() } .toList() .sorted() println(getResult(nums, 0)) } fun getResult(nums: List<Int>, acc: Int): Int = when { nums.isEmpty() -> acc else -> { val max = nums .mapIndexed { index, _ -> index to convert(nums.subList(index, nums.size)) } .maxBy { it.second } val subList = nums.subList(max!!.first, max.first + max.second) getResult(nums.minus(subList), acc + 1) } } fun convert(nums: List<Int>): Int { return nums .takeWhile { it <= nums[0] + 4 } .count() } }
mit
9733b3937c36a6937335d7f666d0701d
22.7
75
0.440034
4.154386
false
false
false
false
SoulBeaver/SpriteSheetProcessor
src/main/java/com/sbg/rpg/javafx/canvas/ResizableCanvas.kt
1
1292
/* * Copyright 2016 Christian Broomfield * * 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.sbg.rpg.javafx.canvas import javafx.scene.canvas.Canvas import javafx.scene.paint.Color class ResizableCanvas: Canvas() { init { // Redraw canvas when size changes. widthProperty().addListener { _ -> draw() } heightProperty().addListener { _ -> draw() } } private fun draw() { val gc = graphicsContext2D gc.clearRect(0.0, 0.0, width, height) gc.fill = Color.ANTIQUEWHITE gc.fillRect(0.0, 0.0, width, height) gc.fill = Color.TRANSPARENT } override fun isResizable() = true override fun prefWidth(height: Double) = width override fun prefHeight(width: Double) = height }
apache-2.0
afd5a605c01142091b66fcd1fb094d6c
30.536585
76
0.680341
3.975385
false
false
false
false
shyiko/ktlint
ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/internal/importordering/ImportSorter.kt
1
1848
package com.pinterest.ktlint.ruleset.standard.internal.importordering import org.jetbrains.kotlin.psi.KtImportDirective import org.jetbrains.kotlin.resolve.ImportPath /** * Sorts the imports according to the order specified in [patterns] + alphabetically. * * Adopted from https://github.com/JetBrains/kotlin/blob/a270ee094c4d7b9520e0898a242bb6ce4dfcad7b/idea/src/org/jetbrains/kotlin/idea/util/ImportPathComparator.kt#L15 */ internal class ImportSorter( val patterns: List<PatternEntry> ) : Comparator<KtImportDirective> { override fun compare(import1: KtImportDirective, import2: KtImportDirective): Int { val importPath1 = import1.importPath!! val importPath2 = import2.importPath!! return compareValuesBy( importPath1, importPath2, { import -> findImportIndex(import) }, { import -> import.toString() } ) } fun findImportIndex(path: ImportPath): Int { var bestIndex: Int = -1 var bestEntryMatch: PatternEntry? = null var allOtherAliasIndex = -1 var allOtherIndex = -1 for ((index, entry) in patterns.withIndex()) { if (entry == PatternEntry.ALL_OTHER_ALIAS_IMPORTS_ENTRY) { allOtherAliasIndex = index } if (entry == PatternEntry.ALL_OTHER_IMPORTS_ENTRY) { allOtherIndex = index } if (entry.isBetterMatchForPackageThan(bestEntryMatch, path)) { bestEntryMatch = entry bestIndex = index } } if (bestIndex == -1 && path.hasAlias() && allOtherAliasIndex == -1 && allOtherIndex != -1) { // if no layout for alias imports specified, put them among all others bestIndex = allOtherIndex } return bestIndex } }
mit
37d51c9d0f4b554cae7e90653f67f491
34.538462
165
0.632576
4.228833
false
false
false
false
VladRassokhin/intellij-hcl
src/kotlin/org/intellij/plugins/hcl/terraform/config/inspection/HCLBlockConflictingPropertiesInspection.kt
1
3830
/* * Copyright 2000-2018 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.intellij.plugins.hcl.terraform.config.inspection import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.SuppressQuickFix import com.intellij.openapi.progress.ProgressIndicatorProvider import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.util.PsiTreeUtil import org.intellij.plugins.hcl.psi.HCLBlock import org.intellij.plugins.hcl.psi.HCLElementVisitor import org.intellij.plugins.hcl.psi.HCLObject import org.intellij.plugins.hcl.psi.HCLProperty import org.intellij.plugins.hcl.terraform.config.TerraformFileType import org.intellij.plugins.hcl.terraform.config.codeinsight.ModelHelper import org.intellij.plugins.hcl.terraform.config.model.PropertyOrBlockType class HCLBlockConflictingPropertiesInspection : LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { val ft = holder.file.fileType if (ft != TerraformFileType) { return super.buildVisitor(holder, isOnTheFly) } return MyEV(holder) } override fun getID(): String { return "ConflictingProperties" } override fun getBatchSuppressActions(element: PsiElement?): Array<SuppressQuickFix> { return super.getBatchSuppressActions(PsiTreeUtil.getParentOfType(element, HCLBlock::class.java, false)) } inner class MyEV(val holder: ProblemsHolder) : HCLElementVisitor() { override fun visitProperty(property: HCLProperty) { ProgressIndicatorProvider.checkCanceled() val obj = property.parent as? HCLObject ?: return val block = obj.parent as? HCLBlock ?: return val properties = ModelHelper.getBlockProperties(block) doCheck(holder, property, property.name, obj, properties) } override fun visitBlock(inner: HCLBlock) { ProgressIndicatorProvider.checkCanceled() val obj = inner.parent as? HCLObject ?: return val block = obj.parent as? HCLBlock ?: return val properties = ModelHelper.getBlockProperties(block) doCheck(holder, inner, inner.name, obj, properties) } } private fun doCheck(holder: ProblemsHolder, element: PsiElement, name: String, obj: HCLObject, properties: Array<out PropertyOrBlockType>) { if (properties.isEmpty()) return ProgressIndicatorProvider.checkCanceled() val pobt = properties.find { it.name == name } ?: return var conflictsWith = pobt.conflictsWith ?: return conflictsWith -= name if (conflictsWith.isEmpty()) return ProgressIndicatorProvider.checkCanceled() val conflicts = ArrayList<String>() (obj.propertyList).filter { conflictsWith.contains(it.name) }.mapTo(conflicts) { it.name } ProgressIndicatorProvider.checkCanceled() // TODO: Better block name selection? (obj.blockList).filter { conflictsWith.contains(it.name) }.mapTo(conflicts) { it.name } if (conflicts.isEmpty()) return // TODO: Add 'navigate to' and 'remove current element' quick fixes holder.registerProblem(element, "Conflicts with: ${conflicts.joinToString(", ")}", ProblemHighlightType.GENERIC_ERROR_OR_WARNING) } }
apache-2.0
23611e4614dc0180604d60a533363776
39.744681
142
0.761097
4.458673
false
false
false
false
shyiko/ktlint
ktlint-reporter-checkstyle/src/test/kotlin/com/pinterest/ktlint/reporter/checkstyle/CheckStyleReporterTest.kt
1
2247
package com.pinterest.ktlint.reporter.checkstyle import com.pinterest.ktlint.core.LintError import java.io.ByteArrayOutputStream import java.io.PrintStream import org.assertj.core.api.Assertions.assertThat import org.junit.Test class CheckStyleReporterTest { @Test fun testReportGeneration() { val out = ByteArrayOutputStream() val reporter = CheckStyleReporter(PrintStream(out, true)) reporter.onLintError( "/one-fixed-and-one-not.kt", LintError( 1, 1, "rule-1", "<\"&'>" ), false ) reporter.onLintError( "/one-fixed-and-one-not.kt", LintError( 2, 1, "rule-2", "And if you see my friend" ), true ) reporter.onLintError( "/two-not-fixed.kt", LintError( 1, 10, "rule-1", "I thought I would again" ), false ) reporter.onLintError( "/two-not-fixed.kt", LintError( 2, 20, "rule-2", "A single thin straight line" ), false ) reporter.onLintError( "/all-corrected.kt", LintError( 1, 1, "rule-1", "I thought we had more time" ), true ) reporter.afterAll() assertThat(String(out.toByteArray())).isEqualTo( """ <?xml version="1.0" encoding="utf-8"?> <checkstyle version="8.0"> <file name="/one-fixed-and-one-not.kt"> <error line="1" column="1" severity="error" message="&lt;&quot;&amp;&apos;&gt;" source="rule-1" /> </file> <file name="/two-not-fixed.kt"> <error line="1" column="10" severity="error" message="I thought I would again" source="rule-1" /> <error line="2" column="20" severity="error" message="A single thin straight line" source="rule-2" /> </file> </checkstyle> """.trimStart().replace("\n", System.lineSeparator()) ) } }
mit
1a21c88097d6391de87e1ec709986c9c
26.072289
103
0.484201
4.247637
false
false
false
false
vanniktech/Emoji
emoji-twitter/src/commonMain/kotlin/com/vanniktech/emoji/twitter/category/SmileysAndPeopleCategoryChunk1.kt
1
51742
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * 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.vanniktech.emoji.twitter.category import com.vanniktech.emoji.twitter.TwitterEmoji internal object SmileysAndPeopleCategoryChunk1 { internal val EMOJIS: List<TwitterEmoji> = listOf( TwitterEmoji(String(intArrayOf(0x1F640), 0, 1), listOf("scream_cat"), 33, 26, false), TwitterEmoji(String(intArrayOf(0x1F63F), 0, 1), listOf("crying_cat_face"), 33, 25, false), TwitterEmoji(String(intArrayOf(0x1F63E), 0, 1), listOf("pouting_cat"), 33, 24, false), TwitterEmoji(String(intArrayOf(0x1F648), 0, 1), listOf("see_no_evil"), 34, 24, false), TwitterEmoji(String(intArrayOf(0x1F649), 0, 1), listOf("hear_no_evil"), 34, 25, false), TwitterEmoji(String(intArrayOf(0x1F64A), 0, 1), listOf("speak_no_evil"), 34, 26, false), TwitterEmoji(String(intArrayOf(0x1F48B), 0, 1), listOf("kiss"), 26, 37, false), TwitterEmoji(String(intArrayOf(0x1F48C), 0, 1), listOf("love_letter"), 26, 38, false), TwitterEmoji(String(intArrayOf(0x1F498), 0, 1), listOf("cupid"), 27, 39, false), TwitterEmoji(String(intArrayOf(0x1F49D), 0, 1), listOf("gift_heart"), 27, 44, false), TwitterEmoji(String(intArrayOf(0x1F496), 0, 1), listOf("sparkling_heart"), 27, 37, false), TwitterEmoji(String(intArrayOf(0x1F497), 0, 1), listOf("heartpulse"), 27, 38, false), TwitterEmoji(String(intArrayOf(0x1F493), 0, 1), listOf("heartbeat"), 27, 34, false), TwitterEmoji(String(intArrayOf(0x1F49E), 0, 1), listOf("revolving_hearts"), 27, 45, false), TwitterEmoji(String(intArrayOf(0x1F495), 0, 1), listOf("two_hearts"), 27, 36, false), TwitterEmoji(String(intArrayOf(0x1F49F), 0, 1), listOf("heart_decoration"), 27, 46, false), TwitterEmoji(String(intArrayOf(0x2763, 0xFE0F), 0, 2), listOf("heavy_heart_exclamation_mark_ornament"), 59, 7, false), TwitterEmoji(String(intArrayOf(0x1F494), 0, 1), listOf("broken_heart"), 27, 35, false), TwitterEmoji(String(intArrayOf(0x2764, 0xFE0F, 0x200D, 0x1F525), 0, 4), listOf("heart_on_fire"), 59, 8, false), TwitterEmoji(String(intArrayOf(0x2764, 0xFE0F, 0x200D, 0x1FA79), 0, 4), listOf("mending_heart"), 59, 9, false), TwitterEmoji(String(intArrayOf(0x2764, 0xFE0F), 0, 2), listOf("heart"), 59, 10, false), TwitterEmoji(String(intArrayOf(0x1F9E1), 0, 1), listOf("orange_heart"), 53, 15, false), TwitterEmoji(String(intArrayOf(0x1F49B), 0, 1), listOf("yellow_heart"), 27, 42, false), TwitterEmoji(String(intArrayOf(0x1F49A), 0, 1), listOf("green_heart"), 27, 41, false), TwitterEmoji(String(intArrayOf(0x1F499), 0, 1), listOf("blue_heart"), 27, 40, false), TwitterEmoji(String(intArrayOf(0x1F49C), 0, 1), listOf("purple_heart"), 27, 43, false), TwitterEmoji(String(intArrayOf(0x1F90E), 0, 1), listOf("brown_heart"), 38, 51, false), TwitterEmoji(String(intArrayOf(0x1F5A4), 0, 1), listOf("black_heart"), 31, 55, false), TwitterEmoji(String(intArrayOf(0x1F90D), 0, 1), listOf("white_heart"), 38, 50, false), TwitterEmoji(String(intArrayOf(0x1F4AF), 0, 1), listOf("100"), 28, 6, false), TwitterEmoji(String(intArrayOf(0x1F4A2), 0, 1), listOf("anger"), 27, 49, false), TwitterEmoji(String(intArrayOf(0x1F4A5), 0, 1), listOf("boom", "collision"), 27, 52, false), TwitterEmoji(String(intArrayOf(0x1F4AB), 0, 1), listOf("dizzy"), 28, 2, false), TwitterEmoji(String(intArrayOf(0x1F4A6), 0, 1), listOf("sweat_drops"), 27, 53, false), TwitterEmoji(String(intArrayOf(0x1F4A8), 0, 1), listOf("dash"), 27, 55, false), TwitterEmoji(String(intArrayOf(0x1F573, 0xFE0F), 0, 2), listOf("hole"), 30, 58, false), TwitterEmoji(String(intArrayOf(0x1F4A3), 0, 1), listOf("bomb"), 27, 50, false), TwitterEmoji(String(intArrayOf(0x1F4AC), 0, 1), listOf("speech_balloon"), 28, 3, false), TwitterEmoji(String(intArrayOf(0x1F441, 0xFE0F, 0x200D, 0x1F5E8, 0xFE0F), 0, 5), listOf("eye-in-speech-bubble"), 11, 53, false), TwitterEmoji(String(intArrayOf(0x1F5E8, 0xFE0F), 0, 2), listOf("left_speech_bubble"), 32, 11, false), TwitterEmoji(String(intArrayOf(0x1F5EF, 0xFE0F), 0, 2), listOf("right_anger_bubble"), 32, 12, false), TwitterEmoji(String(intArrayOf(0x1F4AD), 0, 1), listOf("thought_balloon"), 28, 4, false), TwitterEmoji(String(intArrayOf(0x1F4A4), 0, 1), listOf("zzz"), 27, 51, false), TwitterEmoji( String(intArrayOf(0x1F44B), 0, 1), listOf("wave"), 12, 38, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F44B, 0x1F3FB), 0, 2), emptyList<String>(), 12, 39, false), TwitterEmoji(String(intArrayOf(0x1F44B, 0x1F3FC), 0, 2), emptyList<String>(), 12, 40, false), TwitterEmoji(String(intArrayOf(0x1F44B, 0x1F3FD), 0, 2), emptyList<String>(), 12, 41, false), TwitterEmoji(String(intArrayOf(0x1F44B, 0x1F3FE), 0, 2), emptyList<String>(), 12, 42, false), TwitterEmoji(String(intArrayOf(0x1F44B, 0x1F3FF), 0, 2), emptyList<String>(), 12, 43, false), ), ), TwitterEmoji( String(intArrayOf(0x1F91A), 0, 1), listOf("raised_back_of_hand"), 39, 17, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F91A, 0x1F3FB), 0, 2), emptyList<String>(), 39, 18, false), TwitterEmoji(String(intArrayOf(0x1F91A, 0x1F3FC), 0, 2), emptyList<String>(), 39, 19, false), TwitterEmoji(String(intArrayOf(0x1F91A, 0x1F3FD), 0, 2), emptyList<String>(), 39, 20, false), TwitterEmoji(String(intArrayOf(0x1F91A, 0x1F3FE), 0, 2), emptyList<String>(), 39, 21, false), TwitterEmoji(String(intArrayOf(0x1F91A, 0x1F3FF), 0, 2), emptyList<String>(), 39, 22, false), ), ), TwitterEmoji( String(intArrayOf(0x1F590, 0xFE0F), 0, 2), listOf("raised_hand_with_fingers_splayed"), 31, 37, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F590, 0x1F3FB), 0, 2), emptyList<String>(), 31, 38, false), TwitterEmoji(String(intArrayOf(0x1F590, 0x1F3FC), 0, 2), emptyList<String>(), 31, 39, false), TwitterEmoji(String(intArrayOf(0x1F590, 0x1F3FD), 0, 2), emptyList<String>(), 31, 40, false), TwitterEmoji(String(intArrayOf(0x1F590, 0x1F3FE), 0, 2), emptyList<String>(), 31, 41, false), TwitterEmoji(String(intArrayOf(0x1F590, 0x1F3FF), 0, 2), emptyList<String>(), 31, 42, false), ), ), TwitterEmoji( String(intArrayOf(0x270B), 0, 1), listOf("hand", "raised_hand"), 58, 33, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x270B, 0x1F3FB), 0, 2), emptyList<String>(), 58, 34, false), TwitterEmoji(String(intArrayOf(0x270B, 0x1F3FC), 0, 2), emptyList<String>(), 58, 35, false), TwitterEmoji(String(intArrayOf(0x270B, 0x1F3FD), 0, 2), emptyList<String>(), 58, 36, false), TwitterEmoji(String(intArrayOf(0x270B, 0x1F3FE), 0, 2), emptyList<String>(), 58, 37, false), TwitterEmoji(String(intArrayOf(0x270B, 0x1F3FF), 0, 2), emptyList<String>(), 58, 38, false), ), ), TwitterEmoji( String(intArrayOf(0x1F596), 0, 1), listOf("spock-hand"), 31, 49, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F596, 0x1F3FB), 0, 2), emptyList<String>(), 31, 50, false), TwitterEmoji(String(intArrayOf(0x1F596, 0x1F3FC), 0, 2), emptyList<String>(), 31, 51, false), TwitterEmoji(String(intArrayOf(0x1F596, 0x1F3FD), 0, 2), emptyList<String>(), 31, 52, false), TwitterEmoji(String(intArrayOf(0x1F596, 0x1F3FE), 0, 2), emptyList<String>(), 31, 53, false), TwitterEmoji(String(intArrayOf(0x1F596, 0x1F3FF), 0, 2), emptyList<String>(), 31, 54, false), ), ), TwitterEmoji( String(intArrayOf(0x1FAF1), 0, 1), listOf("rightwards_hand"), 55, 26, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FB), 0, 2), emptyList<String>(), 55, 27, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FC), 0, 2), emptyList<String>(), 55, 28, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FD), 0, 2), emptyList<String>(), 55, 29, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FE), 0, 2), emptyList<String>(), 55, 30, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FF), 0, 2), emptyList<String>(), 55, 31, false), ), ), TwitterEmoji( String(intArrayOf(0x1FAF2), 0, 1), listOf("leftwards_hand"), 55, 32, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1FAF2, 0x1F3FB), 0, 2), emptyList<String>(), 55, 33, false), TwitterEmoji(String(intArrayOf(0x1FAF2, 0x1F3FC), 0, 2), emptyList<String>(), 55, 34, false), TwitterEmoji(String(intArrayOf(0x1FAF2, 0x1F3FD), 0, 2), emptyList<String>(), 55, 35, false), TwitterEmoji(String(intArrayOf(0x1FAF2, 0x1F3FE), 0, 2), emptyList<String>(), 55, 36, false), TwitterEmoji(String(intArrayOf(0x1FAF2, 0x1F3FF), 0, 2), emptyList<String>(), 55, 37, false), ), ), TwitterEmoji( String(intArrayOf(0x1FAF3), 0, 1), listOf("palm_down_hand"), 55, 38, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1FAF3, 0x1F3FB), 0, 2), emptyList<String>(), 55, 39, false), TwitterEmoji(String(intArrayOf(0x1FAF3, 0x1F3FC), 0, 2), emptyList<String>(), 55, 40, false), TwitterEmoji(String(intArrayOf(0x1FAF3, 0x1F3FD), 0, 2), emptyList<String>(), 55, 41, false), TwitterEmoji(String(intArrayOf(0x1FAF3, 0x1F3FE), 0, 2), emptyList<String>(), 55, 42, false), TwitterEmoji(String(intArrayOf(0x1FAF3, 0x1F3FF), 0, 2), emptyList<String>(), 55, 43, false), ), ), TwitterEmoji( String(intArrayOf(0x1FAF4), 0, 1), listOf("palm_up_hand"), 55, 44, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1FAF4, 0x1F3FB), 0, 2), emptyList<String>(), 55, 45, false), TwitterEmoji(String(intArrayOf(0x1FAF4, 0x1F3FC), 0, 2), emptyList<String>(), 55, 46, false), TwitterEmoji(String(intArrayOf(0x1FAF4, 0x1F3FD), 0, 2), emptyList<String>(), 55, 47, false), TwitterEmoji(String(intArrayOf(0x1FAF4, 0x1F3FE), 0, 2), emptyList<String>(), 55, 48, false), TwitterEmoji(String(intArrayOf(0x1FAF4, 0x1F3FF), 0, 2), emptyList<String>(), 55, 49, false), ), ), TwitterEmoji( String(intArrayOf(0x1F44C), 0, 1), listOf("ok_hand"), 12, 44, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F44C, 0x1F3FB), 0, 2), emptyList<String>(), 12, 45, false), TwitterEmoji(String(intArrayOf(0x1F44C, 0x1F3FC), 0, 2), emptyList<String>(), 12, 46, false), TwitterEmoji(String(intArrayOf(0x1F44C, 0x1F3FD), 0, 2), emptyList<String>(), 12, 47, false), TwitterEmoji(String(intArrayOf(0x1F44C, 0x1F3FE), 0, 2), emptyList<String>(), 12, 48, false), TwitterEmoji(String(intArrayOf(0x1F44C, 0x1F3FF), 0, 2), emptyList<String>(), 12, 49, false), ), ), TwitterEmoji( String(intArrayOf(0x1F90C), 0, 1), listOf("pinched_fingers"), 38, 44, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F90C, 0x1F3FB), 0, 2), emptyList<String>(), 38, 45, false), TwitterEmoji(String(intArrayOf(0x1F90C, 0x1F3FC), 0, 2), emptyList<String>(), 38, 46, false), TwitterEmoji(String(intArrayOf(0x1F90C, 0x1F3FD), 0, 2), emptyList<String>(), 38, 47, false), TwitterEmoji(String(intArrayOf(0x1F90C, 0x1F3FE), 0, 2), emptyList<String>(), 38, 48, false), TwitterEmoji(String(intArrayOf(0x1F90C, 0x1F3FF), 0, 2), emptyList<String>(), 38, 49, false), ), ), TwitterEmoji( String(intArrayOf(0x1F90F), 0, 1), listOf("pinching_hand"), 38, 52, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F90F, 0x1F3FB), 0, 2), emptyList<String>(), 38, 53, false), TwitterEmoji(String(intArrayOf(0x1F90F, 0x1F3FC), 0, 2), emptyList<String>(), 38, 54, false), TwitterEmoji(String(intArrayOf(0x1F90F, 0x1F3FD), 0, 2), emptyList<String>(), 38, 55, false), TwitterEmoji(String(intArrayOf(0x1F90F, 0x1F3FE), 0, 2), emptyList<String>(), 38, 56, false), TwitterEmoji(String(intArrayOf(0x1F90F, 0x1F3FF), 0, 2), emptyList<String>(), 38, 57, false), ), ), TwitterEmoji( String(intArrayOf(0x270C, 0xFE0F), 0, 2), listOf("v"), 58, 39, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x270C, 0x1F3FB), 0, 2), emptyList<String>(), 58, 40, false), TwitterEmoji(String(intArrayOf(0x270C, 0x1F3FC), 0, 2), emptyList<String>(), 58, 41, false), TwitterEmoji(String(intArrayOf(0x270C, 0x1F3FD), 0, 2), emptyList<String>(), 58, 42, false), TwitterEmoji(String(intArrayOf(0x270C, 0x1F3FE), 0, 2), emptyList<String>(), 58, 43, false), TwitterEmoji(String(intArrayOf(0x270C, 0x1F3FF), 0, 2), emptyList<String>(), 58, 44, false), ), ), TwitterEmoji( String(intArrayOf(0x1F91E), 0, 1), listOf("crossed_fingers", "hand_with_index_and_middle_fingers_crossed"), 40, 0, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F91E, 0x1F3FB), 0, 2), emptyList<String>(), 40, 1, false), TwitterEmoji(String(intArrayOf(0x1F91E, 0x1F3FC), 0, 2), emptyList<String>(), 40, 2, false), TwitterEmoji(String(intArrayOf(0x1F91E, 0x1F3FD), 0, 2), emptyList<String>(), 40, 3, false), TwitterEmoji(String(intArrayOf(0x1F91E, 0x1F3FE), 0, 2), emptyList<String>(), 40, 4, false), TwitterEmoji(String(intArrayOf(0x1F91E, 0x1F3FF), 0, 2), emptyList<String>(), 40, 5, false), ), ), TwitterEmoji( String(intArrayOf(0x1FAF0), 0, 1), listOf("hand_with_index_finger_and_thumb_crossed"), 55, 20, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1FAF0, 0x1F3FB), 0, 2), emptyList<String>(), 55, 21, false), TwitterEmoji(String(intArrayOf(0x1FAF0, 0x1F3FC), 0, 2), emptyList<String>(), 55, 22, false), TwitterEmoji(String(intArrayOf(0x1FAF0, 0x1F3FD), 0, 2), emptyList<String>(), 55, 23, false), TwitterEmoji(String(intArrayOf(0x1FAF0, 0x1F3FE), 0, 2), emptyList<String>(), 55, 24, false), TwitterEmoji(String(intArrayOf(0x1FAF0, 0x1F3FF), 0, 2), emptyList<String>(), 55, 25, false), ), ), TwitterEmoji( String(intArrayOf(0x1F91F), 0, 1), listOf("i_love_you_hand_sign"), 40, 6, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F91F, 0x1F3FB), 0, 2), emptyList<String>(), 40, 7, false), TwitterEmoji(String(intArrayOf(0x1F91F, 0x1F3FC), 0, 2), emptyList<String>(), 40, 8, false), TwitterEmoji(String(intArrayOf(0x1F91F, 0x1F3FD), 0, 2), emptyList<String>(), 40, 9, false), TwitterEmoji(String(intArrayOf(0x1F91F, 0x1F3FE), 0, 2), emptyList<String>(), 40, 10, false), TwitterEmoji(String(intArrayOf(0x1F91F, 0x1F3FF), 0, 2), emptyList<String>(), 40, 11, false), ), ), TwitterEmoji( String(intArrayOf(0x1F918), 0, 1), listOf("the_horns", "sign_of_the_horns"), 39, 5, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F918, 0x1F3FB), 0, 2), emptyList<String>(), 39, 6, false), TwitterEmoji(String(intArrayOf(0x1F918, 0x1F3FC), 0, 2), emptyList<String>(), 39, 7, false), TwitterEmoji(String(intArrayOf(0x1F918, 0x1F3FD), 0, 2), emptyList<String>(), 39, 8, false), TwitterEmoji(String(intArrayOf(0x1F918, 0x1F3FE), 0, 2), emptyList<String>(), 39, 9, false), TwitterEmoji(String(intArrayOf(0x1F918, 0x1F3FF), 0, 2), emptyList<String>(), 39, 10, false), ), ), TwitterEmoji( String(intArrayOf(0x1F919), 0, 1), listOf("call_me_hand"), 39, 11, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F919, 0x1F3FB), 0, 2), emptyList<String>(), 39, 12, false), TwitterEmoji(String(intArrayOf(0x1F919, 0x1F3FC), 0, 2), emptyList<String>(), 39, 13, false), TwitterEmoji(String(intArrayOf(0x1F919, 0x1F3FD), 0, 2), emptyList<String>(), 39, 14, false), TwitterEmoji(String(intArrayOf(0x1F919, 0x1F3FE), 0, 2), emptyList<String>(), 39, 15, false), TwitterEmoji(String(intArrayOf(0x1F919, 0x1F3FF), 0, 2), emptyList<String>(), 39, 16, false), ), ), TwitterEmoji( String(intArrayOf(0x1F448), 0, 1), listOf("point_left"), 12, 20, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F448, 0x1F3FB), 0, 2), emptyList<String>(), 12, 21, false), TwitterEmoji(String(intArrayOf(0x1F448, 0x1F3FC), 0, 2), emptyList<String>(), 12, 22, false), TwitterEmoji(String(intArrayOf(0x1F448, 0x1F3FD), 0, 2), emptyList<String>(), 12, 23, false), TwitterEmoji(String(intArrayOf(0x1F448, 0x1F3FE), 0, 2), emptyList<String>(), 12, 24, false), TwitterEmoji(String(intArrayOf(0x1F448, 0x1F3FF), 0, 2), emptyList<String>(), 12, 25, false), ), ), TwitterEmoji( String(intArrayOf(0x1F449), 0, 1), listOf("point_right"), 12, 26, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F449, 0x1F3FB), 0, 2), emptyList<String>(), 12, 27, false), TwitterEmoji(String(intArrayOf(0x1F449, 0x1F3FC), 0, 2), emptyList<String>(), 12, 28, false), TwitterEmoji(String(intArrayOf(0x1F449, 0x1F3FD), 0, 2), emptyList<String>(), 12, 29, false), TwitterEmoji(String(intArrayOf(0x1F449, 0x1F3FE), 0, 2), emptyList<String>(), 12, 30, false), TwitterEmoji(String(intArrayOf(0x1F449, 0x1F3FF), 0, 2), emptyList<String>(), 12, 31, false), ), ), TwitterEmoji( String(intArrayOf(0x1F446), 0, 1), listOf("point_up_2"), 12, 8, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F446, 0x1F3FB), 0, 2), emptyList<String>(), 12, 9, false), TwitterEmoji(String(intArrayOf(0x1F446, 0x1F3FC), 0, 2), emptyList<String>(), 12, 10, false), TwitterEmoji(String(intArrayOf(0x1F446, 0x1F3FD), 0, 2), emptyList<String>(), 12, 11, false), TwitterEmoji(String(intArrayOf(0x1F446, 0x1F3FE), 0, 2), emptyList<String>(), 12, 12, false), TwitterEmoji(String(intArrayOf(0x1F446, 0x1F3FF), 0, 2), emptyList<String>(), 12, 13, false), ), ), TwitterEmoji( String(intArrayOf(0x1F595), 0, 1), listOf("middle_finger", "reversed_hand_with_middle_finger_extended"), 31, 43, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F595, 0x1F3FB), 0, 2), emptyList<String>(), 31, 44, false), TwitterEmoji(String(intArrayOf(0x1F595, 0x1F3FC), 0, 2), emptyList<String>(), 31, 45, false), TwitterEmoji(String(intArrayOf(0x1F595, 0x1F3FD), 0, 2), emptyList<String>(), 31, 46, false), TwitterEmoji(String(intArrayOf(0x1F595, 0x1F3FE), 0, 2), emptyList<String>(), 31, 47, false), TwitterEmoji(String(intArrayOf(0x1F595, 0x1F3FF), 0, 2), emptyList<String>(), 31, 48, false), ), ), TwitterEmoji( String(intArrayOf(0x1F447), 0, 1), listOf("point_down"), 12, 14, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F447, 0x1F3FB), 0, 2), emptyList<String>(), 12, 15, false), TwitterEmoji(String(intArrayOf(0x1F447, 0x1F3FC), 0, 2), emptyList<String>(), 12, 16, false), TwitterEmoji(String(intArrayOf(0x1F447, 0x1F3FD), 0, 2), emptyList<String>(), 12, 17, false), TwitterEmoji(String(intArrayOf(0x1F447, 0x1F3FE), 0, 2), emptyList<String>(), 12, 18, false), TwitterEmoji(String(intArrayOf(0x1F447, 0x1F3FF), 0, 2), emptyList<String>(), 12, 19, false), ), ), TwitterEmoji( String(intArrayOf(0x261D, 0xFE0F), 0, 2), listOf("point_up"), 56, 50, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x261D, 0x1F3FB), 0, 2), emptyList<String>(), 56, 51, false), TwitterEmoji(String(intArrayOf(0x261D, 0x1F3FC), 0, 2), emptyList<String>(), 56, 52, false), TwitterEmoji(String(intArrayOf(0x261D, 0x1F3FD), 0, 2), emptyList<String>(), 56, 53, false), TwitterEmoji(String(intArrayOf(0x261D, 0x1F3FE), 0, 2), emptyList<String>(), 56, 54, false), TwitterEmoji(String(intArrayOf(0x261D, 0x1F3FF), 0, 2), emptyList<String>(), 56, 55, false), ), ), TwitterEmoji( String(intArrayOf(0x1FAF5), 0, 1), listOf("index_pointing_at_the_viewer"), 55, 50, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1FAF5, 0x1F3FB), 0, 2), emptyList<String>(), 55, 51, false), TwitterEmoji(String(intArrayOf(0x1FAF5, 0x1F3FC), 0, 2), emptyList<String>(), 55, 52, false), TwitterEmoji(String(intArrayOf(0x1FAF5, 0x1F3FD), 0, 2), emptyList<String>(), 55, 53, false), TwitterEmoji(String(intArrayOf(0x1FAF5, 0x1F3FE), 0, 2), emptyList<String>(), 55, 54, false), TwitterEmoji(String(intArrayOf(0x1FAF5, 0x1F3FF), 0, 2), emptyList<String>(), 55, 55, false), ), ), TwitterEmoji( String(intArrayOf(0x1F44D), 0, 1), listOf("+1", "thumbsup"), 12, 50, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F44D, 0x1F3FB), 0, 2), emptyList<String>(), 12, 51, false), TwitterEmoji(String(intArrayOf(0x1F44D, 0x1F3FC), 0, 2), emptyList<String>(), 12, 52, false), TwitterEmoji(String(intArrayOf(0x1F44D, 0x1F3FD), 0, 2), emptyList<String>(), 12, 53, false), TwitterEmoji(String(intArrayOf(0x1F44D, 0x1F3FE), 0, 2), emptyList<String>(), 12, 54, false), TwitterEmoji(String(intArrayOf(0x1F44D, 0x1F3FF), 0, 2), emptyList<String>(), 12, 55, false), ), ), TwitterEmoji( String(intArrayOf(0x1F44E), 0, 1), listOf("-1", "thumbsdown"), 12, 56, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F44E, 0x1F3FB), 0, 2), emptyList<String>(), 12, 57, false), TwitterEmoji(String(intArrayOf(0x1F44E, 0x1F3FC), 0, 2), emptyList<String>(), 12, 58, false), TwitterEmoji(String(intArrayOf(0x1F44E, 0x1F3FD), 0, 2), emptyList<String>(), 12, 59, false), TwitterEmoji(String(intArrayOf(0x1F44E, 0x1F3FE), 0, 2), emptyList<String>(), 12, 60, false), TwitterEmoji(String(intArrayOf(0x1F44E, 0x1F3FF), 0, 2), emptyList<String>(), 13, 0, false), ), ), TwitterEmoji( String(intArrayOf(0x270A), 0, 1), listOf("fist"), 58, 27, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x270A, 0x1F3FB), 0, 2), emptyList<String>(), 58, 28, false), TwitterEmoji(String(intArrayOf(0x270A, 0x1F3FC), 0, 2), emptyList<String>(), 58, 29, false), TwitterEmoji(String(intArrayOf(0x270A, 0x1F3FD), 0, 2), emptyList<String>(), 58, 30, false), TwitterEmoji(String(intArrayOf(0x270A, 0x1F3FE), 0, 2), emptyList<String>(), 58, 31, false), TwitterEmoji(String(intArrayOf(0x270A, 0x1F3FF), 0, 2), emptyList<String>(), 58, 32, false), ), ), TwitterEmoji( String(intArrayOf(0x1F44A), 0, 1), listOf("facepunch", "punch"), 12, 32, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F44A, 0x1F3FB), 0, 2), emptyList<String>(), 12, 33, false), TwitterEmoji(String(intArrayOf(0x1F44A, 0x1F3FC), 0, 2), emptyList<String>(), 12, 34, false), TwitterEmoji(String(intArrayOf(0x1F44A, 0x1F3FD), 0, 2), emptyList<String>(), 12, 35, false), TwitterEmoji(String(intArrayOf(0x1F44A, 0x1F3FE), 0, 2), emptyList<String>(), 12, 36, false), TwitterEmoji(String(intArrayOf(0x1F44A, 0x1F3FF), 0, 2), emptyList<String>(), 12, 37, false), ), ), TwitterEmoji( String(intArrayOf(0x1F91B), 0, 1), listOf("left-facing_fist"), 39, 23, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F91B, 0x1F3FB), 0, 2), emptyList<String>(), 39, 24, false), TwitterEmoji(String(intArrayOf(0x1F91B, 0x1F3FC), 0, 2), emptyList<String>(), 39, 25, false), TwitterEmoji(String(intArrayOf(0x1F91B, 0x1F3FD), 0, 2), emptyList<String>(), 39, 26, false), TwitterEmoji(String(intArrayOf(0x1F91B, 0x1F3FE), 0, 2), emptyList<String>(), 39, 27, false), TwitterEmoji(String(intArrayOf(0x1F91B, 0x1F3FF), 0, 2), emptyList<String>(), 39, 28, false), ), ), TwitterEmoji( String(intArrayOf(0x1F91C), 0, 1), listOf("right-facing_fist"), 39, 29, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F91C, 0x1F3FB), 0, 2), emptyList<String>(), 39, 30, false), TwitterEmoji(String(intArrayOf(0x1F91C, 0x1F3FC), 0, 2), emptyList<String>(), 39, 31, false), TwitterEmoji(String(intArrayOf(0x1F91C, 0x1F3FD), 0, 2), emptyList<String>(), 39, 32, false), TwitterEmoji(String(intArrayOf(0x1F91C, 0x1F3FE), 0, 2), emptyList<String>(), 39, 33, false), TwitterEmoji(String(intArrayOf(0x1F91C, 0x1F3FF), 0, 2), emptyList<String>(), 39, 34, false), ), ), TwitterEmoji( String(intArrayOf(0x1F44F), 0, 1), listOf("clap"), 13, 1, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F44F, 0x1F3FB), 0, 2), emptyList<String>(), 13, 2, false), TwitterEmoji(String(intArrayOf(0x1F44F, 0x1F3FC), 0, 2), emptyList<String>(), 13, 3, false), TwitterEmoji(String(intArrayOf(0x1F44F, 0x1F3FD), 0, 2), emptyList<String>(), 13, 4, false), TwitterEmoji(String(intArrayOf(0x1F44F, 0x1F3FE), 0, 2), emptyList<String>(), 13, 5, false), TwitterEmoji(String(intArrayOf(0x1F44F, 0x1F3FF), 0, 2), emptyList<String>(), 13, 6, false), ), ), TwitterEmoji( String(intArrayOf(0x1F64C), 0, 1), listOf("raised_hands"), 34, 45, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F64C, 0x1F3FB), 0, 2), emptyList<String>(), 34, 46, false), TwitterEmoji(String(intArrayOf(0x1F64C, 0x1F3FC), 0, 2), emptyList<String>(), 34, 47, false), TwitterEmoji(String(intArrayOf(0x1F64C, 0x1F3FD), 0, 2), emptyList<String>(), 34, 48, false), TwitterEmoji(String(intArrayOf(0x1F64C, 0x1F3FE), 0, 2), emptyList<String>(), 34, 49, false), TwitterEmoji(String(intArrayOf(0x1F64C, 0x1F3FF), 0, 2), emptyList<String>(), 34, 50, false), ), ), TwitterEmoji( String(intArrayOf(0x1FAF6), 0, 1), listOf("heart_hands"), 55, 56, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1FAF6, 0x1F3FB), 0, 2), emptyList<String>(), 55, 57, false), TwitterEmoji(String(intArrayOf(0x1FAF6, 0x1F3FC), 0, 2), emptyList<String>(), 55, 58, false), TwitterEmoji(String(intArrayOf(0x1FAF6, 0x1F3FD), 0, 2), emptyList<String>(), 55, 59, false), TwitterEmoji(String(intArrayOf(0x1FAF6, 0x1F3FE), 0, 2), emptyList<String>(), 55, 60, false), TwitterEmoji(String(intArrayOf(0x1FAF6, 0x1F3FF), 0, 2), emptyList<String>(), 56, 0, false), ), ), TwitterEmoji( String(intArrayOf(0x1F450), 0, 1), listOf("open_hands"), 13, 7, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F450, 0x1F3FB), 0, 2), emptyList<String>(), 13, 8, false), TwitterEmoji(String(intArrayOf(0x1F450, 0x1F3FC), 0, 2), emptyList<String>(), 13, 9, false), TwitterEmoji(String(intArrayOf(0x1F450, 0x1F3FD), 0, 2), emptyList<String>(), 13, 10, false), TwitterEmoji(String(intArrayOf(0x1F450, 0x1F3FE), 0, 2), emptyList<String>(), 13, 11, false), TwitterEmoji(String(intArrayOf(0x1F450, 0x1F3FF), 0, 2), emptyList<String>(), 13, 12, false), ), ), TwitterEmoji( String(intArrayOf(0x1F932), 0, 1), listOf("palms_up_together"), 40, 57, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F932, 0x1F3FB), 0, 2), emptyList<String>(), 40, 58, false), TwitterEmoji(String(intArrayOf(0x1F932, 0x1F3FC), 0, 2), emptyList<String>(), 40, 59, false), TwitterEmoji(String(intArrayOf(0x1F932, 0x1F3FD), 0, 2), emptyList<String>(), 40, 60, false), TwitterEmoji(String(intArrayOf(0x1F932, 0x1F3FE), 0, 2), emptyList<String>(), 41, 0, false), TwitterEmoji(String(intArrayOf(0x1F932, 0x1F3FF), 0, 2), emptyList<String>(), 41, 1, false), ), ), TwitterEmoji( String(intArrayOf(0x1F91D), 0, 1), listOf("handshake"), 39, 35, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F91D, 0x1F3FB), 0, 2), emptyList<String>(), 39, 36, false), TwitterEmoji(String(intArrayOf(0x1F91D, 0x1F3FC), 0, 2), emptyList<String>(), 39, 37, false), TwitterEmoji(String(intArrayOf(0x1F91D, 0x1F3FD), 0, 2), emptyList<String>(), 39, 38, false), TwitterEmoji(String(intArrayOf(0x1F91D, 0x1F3FE), 0, 2), emptyList<String>(), 39, 39, false), TwitterEmoji(String(intArrayOf(0x1F91D, 0x1F3FF), 0, 2), emptyList<String>(), 39, 40, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FB, 0x200D, 0x1FAF2, 0x1F3FC), 0, 5), emptyList<String>(), 39, 41, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FB, 0x200D, 0x1FAF2, 0x1F3FD), 0, 5), emptyList<String>(), 39, 42, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FB, 0x200D, 0x1FAF2, 0x1F3FE), 0, 5), emptyList<String>(), 39, 43, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FB, 0x200D, 0x1FAF2, 0x1F3FF), 0, 5), emptyList<String>(), 39, 44, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FC, 0x200D, 0x1FAF2, 0x1F3FB), 0, 5), emptyList<String>(), 39, 45, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FC, 0x200D, 0x1FAF2, 0x1F3FD), 0, 5), emptyList<String>(), 39, 46, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FC, 0x200D, 0x1FAF2, 0x1F3FE), 0, 5), emptyList<String>(), 39, 47, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FC, 0x200D, 0x1FAF2, 0x1F3FF), 0, 5), emptyList<String>(), 39, 48, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FD, 0x200D, 0x1FAF2, 0x1F3FB), 0, 5), emptyList<String>(), 39, 49, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FD, 0x200D, 0x1FAF2, 0x1F3FC), 0, 5), emptyList<String>(), 39, 50, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FD, 0x200D, 0x1FAF2, 0x1F3FE), 0, 5), emptyList<String>(), 39, 51, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FD, 0x200D, 0x1FAF2, 0x1F3FF), 0, 5), emptyList<String>(), 39, 52, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FE, 0x200D, 0x1FAF2, 0x1F3FB), 0, 5), emptyList<String>(), 39, 53, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FE, 0x200D, 0x1FAF2, 0x1F3FC), 0, 5), emptyList<String>(), 39, 54, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FE, 0x200D, 0x1FAF2, 0x1F3FD), 0, 5), emptyList<String>(), 39, 55, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FE, 0x200D, 0x1FAF2, 0x1F3FF), 0, 5), emptyList<String>(), 39, 56, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FF, 0x200D, 0x1FAF2, 0x1F3FB), 0, 5), emptyList<String>(), 39, 57, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FF, 0x200D, 0x1FAF2, 0x1F3FC), 0, 5), emptyList<String>(), 39, 58, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FF, 0x200D, 0x1FAF2, 0x1F3FD), 0, 5), emptyList<String>(), 39, 59, false), TwitterEmoji(String(intArrayOf(0x1FAF1, 0x1F3FF, 0x200D, 0x1FAF2, 0x1F3FE), 0, 5), emptyList<String>(), 39, 60, false), ), ), TwitterEmoji( String(intArrayOf(0x1F64F), 0, 1), listOf("pray"), 35, 26, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F64F, 0x1F3FB), 0, 2), emptyList<String>(), 35, 27, false), TwitterEmoji(String(intArrayOf(0x1F64F, 0x1F3FC), 0, 2), emptyList<String>(), 35, 28, false), TwitterEmoji(String(intArrayOf(0x1F64F, 0x1F3FD), 0, 2), emptyList<String>(), 35, 29, false), TwitterEmoji(String(intArrayOf(0x1F64F, 0x1F3FE), 0, 2), emptyList<String>(), 35, 30, false), TwitterEmoji(String(intArrayOf(0x1F64F, 0x1F3FF), 0, 2), emptyList<String>(), 35, 31, false), ), ), TwitterEmoji( String(intArrayOf(0x270D, 0xFE0F), 0, 2), listOf("writing_hand"), 58, 45, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x270D, 0x1F3FB), 0, 2), emptyList<String>(), 58, 46, false), TwitterEmoji(String(intArrayOf(0x270D, 0x1F3FC), 0, 2), emptyList<String>(), 58, 47, false), TwitterEmoji(String(intArrayOf(0x270D, 0x1F3FD), 0, 2), emptyList<String>(), 58, 48, false), TwitterEmoji(String(intArrayOf(0x270D, 0x1F3FE), 0, 2), emptyList<String>(), 58, 49, false), TwitterEmoji(String(intArrayOf(0x270D, 0x1F3FF), 0, 2), emptyList<String>(), 58, 50, false), ), ), TwitterEmoji( String(intArrayOf(0x1F485), 0, 1), listOf("nail_care"), 25, 53, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F485, 0x1F3FB), 0, 2), emptyList<String>(), 25, 54, false), TwitterEmoji(String(intArrayOf(0x1F485, 0x1F3FC), 0, 2), emptyList<String>(), 25, 55, false), TwitterEmoji(String(intArrayOf(0x1F485, 0x1F3FD), 0, 2), emptyList<String>(), 25, 56, false), TwitterEmoji(String(intArrayOf(0x1F485, 0x1F3FE), 0, 2), emptyList<String>(), 25, 57, false), TwitterEmoji(String(intArrayOf(0x1F485, 0x1F3FF), 0, 2), emptyList<String>(), 25, 58, false), ), ), TwitterEmoji( String(intArrayOf(0x1F933), 0, 1), listOf("selfie"), 41, 2, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F933, 0x1F3FB), 0, 2), emptyList<String>(), 41, 3, false), TwitterEmoji(String(intArrayOf(0x1F933, 0x1F3FC), 0, 2), emptyList<String>(), 41, 4, false), TwitterEmoji(String(intArrayOf(0x1F933, 0x1F3FD), 0, 2), emptyList<String>(), 41, 5, false), TwitterEmoji(String(intArrayOf(0x1F933, 0x1F3FE), 0, 2), emptyList<String>(), 41, 6, false), TwitterEmoji(String(intArrayOf(0x1F933, 0x1F3FF), 0, 2), emptyList<String>(), 41, 7, false), ), ), TwitterEmoji( String(intArrayOf(0x1F4AA), 0, 1), listOf("muscle"), 27, 57, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F4AA, 0x1F3FB), 0, 2), emptyList<String>(), 27, 58, false), TwitterEmoji(String(intArrayOf(0x1F4AA, 0x1F3FC), 0, 2), emptyList<String>(), 27, 59, false), TwitterEmoji(String(intArrayOf(0x1F4AA, 0x1F3FD), 0, 2), emptyList<String>(), 27, 60, false), TwitterEmoji(String(intArrayOf(0x1F4AA, 0x1F3FE), 0, 2), emptyList<String>(), 28, 0, false), TwitterEmoji(String(intArrayOf(0x1F4AA, 0x1F3FF), 0, 2), emptyList<String>(), 28, 1, false), ), ), TwitterEmoji(String(intArrayOf(0x1F9BE), 0, 1), listOf("mechanical_arm"), 46, 3, false), TwitterEmoji(String(intArrayOf(0x1F9BF), 0, 1), listOf("mechanical_leg"), 46, 4, false), TwitterEmoji( String(intArrayOf(0x1F9B5), 0, 1), listOf("leg"), 45, 6, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F9B5, 0x1F3FB), 0, 2), emptyList<String>(), 45, 7, false), TwitterEmoji(String(intArrayOf(0x1F9B5, 0x1F3FC), 0, 2), emptyList<String>(), 45, 8, false), TwitterEmoji(String(intArrayOf(0x1F9B5, 0x1F3FD), 0, 2), emptyList<String>(), 45, 9, false), TwitterEmoji(String(intArrayOf(0x1F9B5, 0x1F3FE), 0, 2), emptyList<String>(), 45, 10, false), TwitterEmoji(String(intArrayOf(0x1F9B5, 0x1F3FF), 0, 2), emptyList<String>(), 45, 11, false), ), ), TwitterEmoji( String(intArrayOf(0x1F9B6), 0, 1), listOf("foot"), 45, 12, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F9B6, 0x1F3FB), 0, 2), emptyList<String>(), 45, 13, false), TwitterEmoji(String(intArrayOf(0x1F9B6, 0x1F3FC), 0, 2), emptyList<String>(), 45, 14, false), TwitterEmoji(String(intArrayOf(0x1F9B6, 0x1F3FD), 0, 2), emptyList<String>(), 45, 15, false), TwitterEmoji(String(intArrayOf(0x1F9B6, 0x1F3FE), 0, 2), emptyList<String>(), 45, 16, false), TwitterEmoji(String(intArrayOf(0x1F9B6, 0x1F3FF), 0, 2), emptyList<String>(), 45, 17, false), ), ), TwitterEmoji( String(intArrayOf(0x1F442), 0, 1), listOf("ear"), 11, 55, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F442, 0x1F3FB), 0, 2), emptyList<String>(), 11, 56, false), TwitterEmoji(String(intArrayOf(0x1F442, 0x1F3FC), 0, 2), emptyList<String>(), 11, 57, false), TwitterEmoji(String(intArrayOf(0x1F442, 0x1F3FD), 0, 2), emptyList<String>(), 11, 58, false), TwitterEmoji(String(intArrayOf(0x1F442, 0x1F3FE), 0, 2), emptyList<String>(), 11, 59, false), TwitterEmoji(String(intArrayOf(0x1F442, 0x1F3FF), 0, 2), emptyList<String>(), 11, 60, false), ), ), TwitterEmoji( String(intArrayOf(0x1F9BB), 0, 1), listOf("ear_with_hearing_aid"), 45, 56, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F9BB, 0x1F3FB), 0, 2), emptyList<String>(), 45, 57, false), TwitterEmoji(String(intArrayOf(0x1F9BB, 0x1F3FC), 0, 2), emptyList<String>(), 45, 58, false), TwitterEmoji(String(intArrayOf(0x1F9BB, 0x1F3FD), 0, 2), emptyList<String>(), 45, 59, false), TwitterEmoji(String(intArrayOf(0x1F9BB, 0x1F3FE), 0, 2), emptyList<String>(), 45, 60, false), TwitterEmoji(String(intArrayOf(0x1F9BB, 0x1F3FF), 0, 2), emptyList<String>(), 46, 0, false), ), ), TwitterEmoji( String(intArrayOf(0x1F443), 0, 1), listOf("nose"), 12, 0, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F443, 0x1F3FB), 0, 2), emptyList<String>(), 12, 1, false), TwitterEmoji(String(intArrayOf(0x1F443, 0x1F3FC), 0, 2), emptyList<String>(), 12, 2, false), TwitterEmoji(String(intArrayOf(0x1F443, 0x1F3FD), 0, 2), emptyList<String>(), 12, 3, false), TwitterEmoji(String(intArrayOf(0x1F443, 0x1F3FE), 0, 2), emptyList<String>(), 12, 4, false), TwitterEmoji(String(intArrayOf(0x1F443, 0x1F3FF), 0, 2), emptyList<String>(), 12, 5, false), ), ), TwitterEmoji(String(intArrayOf(0x1F9E0), 0, 1), listOf("brain"), 53, 14, false), TwitterEmoji(String(intArrayOf(0x1FAC0), 0, 1), listOf("anatomical_heart"), 54, 42, false), TwitterEmoji(String(intArrayOf(0x1FAC1), 0, 1), listOf("lungs"), 54, 43, false), TwitterEmoji(String(intArrayOf(0x1F9B7), 0, 1), listOf("tooth"), 45, 18, false), TwitterEmoji(String(intArrayOf(0x1F9B4), 0, 1), listOf("bone"), 45, 5, false), TwitterEmoji(String(intArrayOf(0x1F440), 0, 1), listOf("eyes"), 11, 52, false), TwitterEmoji(String(intArrayOf(0x1F441, 0xFE0F), 0, 2), listOf("eye"), 11, 54, false), TwitterEmoji(String(intArrayOf(0x1F445), 0, 1), listOf("tongue"), 12, 7, false), TwitterEmoji(String(intArrayOf(0x1F444), 0, 1), listOf("lips"), 12, 6, false), TwitterEmoji(String(intArrayOf(0x1FAE6), 0, 1), listOf("biting_lip"), 55, 18, false), TwitterEmoji( String(intArrayOf(0x1F476), 0, 1), listOf("baby"), 24, 28, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F476, 0x1F3FB), 0, 2), emptyList<String>(), 24, 29, false), TwitterEmoji(String(intArrayOf(0x1F476, 0x1F3FC), 0, 2), emptyList<String>(), 24, 30, false), TwitterEmoji(String(intArrayOf(0x1F476, 0x1F3FD), 0, 2), emptyList<String>(), 24, 31, false), TwitterEmoji(String(intArrayOf(0x1F476, 0x1F3FE), 0, 2), emptyList<String>(), 24, 32, false), TwitterEmoji(String(intArrayOf(0x1F476, 0x1F3FF), 0, 2), emptyList<String>(), 24, 33, false), ), ), TwitterEmoji( String(intArrayOf(0x1F9D2), 0, 1), listOf("child"), 50, 11, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F9D2, 0x1F3FB), 0, 2), emptyList<String>(), 50, 12, false), TwitterEmoji(String(intArrayOf(0x1F9D2, 0x1F3FC), 0, 2), emptyList<String>(), 50, 13, false), TwitterEmoji(String(intArrayOf(0x1F9D2, 0x1F3FD), 0, 2), emptyList<String>(), 50, 14, false), TwitterEmoji(String(intArrayOf(0x1F9D2, 0x1F3FE), 0, 2), emptyList<String>(), 50, 15, false), TwitterEmoji(String(intArrayOf(0x1F9D2, 0x1F3FF), 0, 2), emptyList<String>(), 50, 16, false), ), ), TwitterEmoji( String(intArrayOf(0x1F466), 0, 1), listOf("boy"), 13, 34, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F466, 0x1F3FB), 0, 2), emptyList<String>(), 13, 35, false), TwitterEmoji(String(intArrayOf(0x1F466, 0x1F3FC), 0, 2), emptyList<String>(), 13, 36, false), TwitterEmoji(String(intArrayOf(0x1F466, 0x1F3FD), 0, 2), emptyList<String>(), 13, 37, false), TwitterEmoji(String(intArrayOf(0x1F466, 0x1F3FE), 0, 2), emptyList<String>(), 13, 38, false), TwitterEmoji(String(intArrayOf(0x1F466, 0x1F3FF), 0, 2), emptyList<String>(), 13, 39, false), ), ), TwitterEmoji( String(intArrayOf(0x1F467), 0, 1), listOf("girl"), 13, 40, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F467, 0x1F3FB), 0, 2), emptyList<String>(), 13, 41, false), TwitterEmoji(String(intArrayOf(0x1F467, 0x1F3FC), 0, 2), emptyList<String>(), 13, 42, false), TwitterEmoji(String(intArrayOf(0x1F467, 0x1F3FD), 0, 2), emptyList<String>(), 13, 43, false), TwitterEmoji(String(intArrayOf(0x1F467, 0x1F3FE), 0, 2), emptyList<String>(), 13, 44, false), TwitterEmoji(String(intArrayOf(0x1F467, 0x1F3FF), 0, 2), emptyList<String>(), 13, 45, false), ), ), TwitterEmoji( String(intArrayOf(0x1F9D1), 0, 1), listOf("adult"), 50, 5, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB), 0, 2), emptyList<String>(), 50, 6, false), TwitterEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC), 0, 2), emptyList<String>(), 50, 7, false), TwitterEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD), 0, 2), emptyList<String>(), 50, 8, false), TwitterEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE), 0, 2), emptyList<String>(), 50, 9, false), TwitterEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF), 0, 2), emptyList<String>(), 50, 10, false), ), ), TwitterEmoji( String(intArrayOf(0x1F471), 0, 1), listOf("person_with_blond_hair"), 23, 47, true, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F471, 0x1F3FB), 0, 2), emptyList<String>(), 23, 48, false), TwitterEmoji(String(intArrayOf(0x1F471, 0x1F3FC), 0, 2), emptyList<String>(), 23, 49, false), TwitterEmoji(String(intArrayOf(0x1F471, 0x1F3FD), 0, 2), emptyList<String>(), 23, 50, false), TwitterEmoji(String(intArrayOf(0x1F471, 0x1F3FE), 0, 2), emptyList<String>(), 23, 51, false), TwitterEmoji(String(intArrayOf(0x1F471, 0x1F3FF), 0, 2), emptyList<String>(), 23, 52, false), ), ), TwitterEmoji( String(intArrayOf(0x1F468), 0, 1), listOf("man"), 17, 13, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FB), 0, 2), emptyList<String>(), 17, 14, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FC), 0, 2), emptyList<String>(), 17, 15, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FD), 0, 2), emptyList<String>(), 17, 16, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FE), 0, 2), emptyList<String>(), 17, 17, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FF), 0, 2), emptyList<String>(), 17, 18, false), ), ), TwitterEmoji( String(intArrayOf(0x1F9D4), 0, 1), listOf("bearded_person"), 50, 35, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F9D4, 0x1F3FB), 0, 2), emptyList<String>(), 50, 36, false), TwitterEmoji(String(intArrayOf(0x1F9D4, 0x1F3FC), 0, 2), emptyList<String>(), 50, 37, false), TwitterEmoji(String(intArrayOf(0x1F9D4, 0x1F3FD), 0, 2), emptyList<String>(), 50, 38, false), TwitterEmoji(String(intArrayOf(0x1F9D4, 0x1F3FE), 0, 2), emptyList<String>(), 50, 39, false), TwitterEmoji(String(intArrayOf(0x1F9D4, 0x1F3FF), 0, 2), emptyList<String>(), 50, 40, false), ), ), TwitterEmoji( String(intArrayOf(0x1F9D4, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_with_beard"), 50, 29, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F9D4, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 30, false), TwitterEmoji(String(intArrayOf(0x1F9D4, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 31, false), TwitterEmoji(String(intArrayOf(0x1F9D4, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 32, false), TwitterEmoji(String(intArrayOf(0x1F9D4, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 33, false), TwitterEmoji(String(intArrayOf(0x1F9D4, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 34, false), ), ), TwitterEmoji( String(intArrayOf(0x1F9D4, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_with_beard"), 50, 23, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F9D4, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 24, false), TwitterEmoji(String(intArrayOf(0x1F9D4, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 25, false), TwitterEmoji(String(intArrayOf(0x1F9D4, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 26, false), TwitterEmoji(String(intArrayOf(0x1F9D4, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 27, false), TwitterEmoji(String(intArrayOf(0x1F9D4, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 28, false), ), ), TwitterEmoji( String(intArrayOf(0x1F468, 0x200D, 0x1F9B0), 0, 3), listOf("red_haired_man"), 15, 29, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), 15, 30, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), 15, 31, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), 15, 32, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), 15, 33, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), 15, 34, false), ), ), TwitterEmoji( String(intArrayOf(0x1F468, 0x200D, 0x1F9B1), 0, 3), listOf("curly_haired_man"), 15, 35, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), 15, 36, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), 15, 37, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), 15, 38, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), 15, 39, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), 15, 40, false), ), ), TwitterEmoji( String(intArrayOf(0x1F468, 0x200D, 0x1F9B3), 0, 3), listOf("white_haired_man"), 15, 47, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9B3), 0, 4), emptyList<String>(), 15, 48, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9B3), 0, 4), emptyList<String>(), 15, 49, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9B3), 0, 4), emptyList<String>(), 15, 50, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9B3), 0, 4), emptyList<String>(), 15, 51, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9B3), 0, 4), emptyList<String>(), 15, 52, false), ), ), TwitterEmoji( String(intArrayOf(0x1F468, 0x200D, 0x1F9B2), 0, 3), listOf("bald_man"), 15, 41, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9B2), 0, 4), emptyList<String>(), 15, 42, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9B2), 0, 4), emptyList<String>(), 15, 43, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9B2), 0, 4), emptyList<String>(), 15, 44, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9B2), 0, 4), emptyList<String>(), 15, 45, false), TwitterEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9B2), 0, 4), emptyList<String>(), 15, 46, false), ), ), TwitterEmoji( String(intArrayOf(0x1F469), 0, 1), listOf("woman"), 21, 33, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F469, 0x1F3FB), 0, 2), emptyList<String>(), 21, 34, false), TwitterEmoji(String(intArrayOf(0x1F469, 0x1F3FC), 0, 2), emptyList<String>(), 21, 35, false), TwitterEmoji(String(intArrayOf(0x1F469, 0x1F3FD), 0, 2), emptyList<String>(), 21, 36, false), TwitterEmoji(String(intArrayOf(0x1F469, 0x1F3FE), 0, 2), emptyList<String>(), 21, 37, false), TwitterEmoji(String(intArrayOf(0x1F469, 0x1F3FF), 0, 2), emptyList<String>(), 21, 38, false), ), ), TwitterEmoji( String(intArrayOf(0x1F469, 0x200D, 0x1F9B0), 0, 3), listOf("red_haired_woman"), 18, 58, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), 18, 59, false), TwitterEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), 18, 60, false), TwitterEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), 19, 0, false), TwitterEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), 19, 1, false), TwitterEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), 19, 2, false), ), ), TwitterEmoji( String(intArrayOf(0x1F9D1, 0x200D, 0x1F9B0), 0, 3), listOf("red_haired_person"), 49, 12, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), 49, 13, false), TwitterEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), 49, 14, false), TwitterEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), 49, 15, false), TwitterEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), 49, 16, false), TwitterEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), 49, 17, false), ), ), TwitterEmoji( String(intArrayOf(0x1F469, 0x200D, 0x1F9B1), 0, 3), listOf("curly_haired_woman"), 19, 3, false, variants = listOf( TwitterEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), 19, 4, false), TwitterEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), 19, 5, false), TwitterEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), 19, 6, false), TwitterEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), 19, 7, false), TwitterEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), 19, 8, false), ), ), ) }
apache-2.0
b3e0330d2a5a971a4bd50f27ce23c3c1
68.078772
132
0.651817
2.851789
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/pumpjack/WorldIterator.kt
2
3098
package com.cout970.magneticraft.systems.tilemodules.pumpjack import com.cout970.magneticraft.misc.add import com.cout970.magneticraft.misc.getBlockPos import com.cout970.magneticraft.misc.newNbt import com.cout970.magneticraft.misc.vector.* import net.minecraft.nbt.NBTTagCompound import net.minecraft.util.math.BlockPos import kotlin.math.max import kotlin.math.min class WorldIterator(val start: BlockPos, val end: BlockPos, val inverted: Boolean = false) : Iterator<BlockPos> { companion object { fun create(a: BlockPos, b: BlockPos, inverted: Boolean = false): WorldIterator { return WorldIterator( BlockPos(min(a.x, b.x), max(0, min(a.y, b.y)), min(a.z, b.z)), BlockPos(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z)), inverted ) } fun deserializeNBT(nbt: NBTTagCompound): WorldIterator? { return if (nbt.hasKey("start")) { create(nbt.getBlockPos("start"), nbt.getBlockPos("end"), nbt.getBoolean("inverted")) .apply { current = nbt.getBlockPos("current") } } else null } } var current: BlockPos = if (inverted) end else start override fun hasNext(): Boolean = current != (if (inverted) start else end) fun reset() { current = if (inverted) end else start } override fun next(): BlockPos { if (current.xi < end.xi) { current = BlockPos(current.xi + 1, current.yi, current.zi) } else { if (current.zi < end.zi) { current = BlockPos(start.xi, current.yi, current.zi + 1) } else { if (inverted) { if (current.yi > start.yi) { current = BlockPos(start.xi, current.yi - 1, start.zi) } else { error("Iterator has no more elements") } } else { if (current.yi < end.yi) { current = BlockPos(start.xi, current.yi + 1, start.zi) } else { error("Iterator has no more elements") } } } } return current } fun totalBlocks(): Int { val totalArea = (end - start) + BlockPos(1, 1, 1) return totalArea.x * totalArea.y * totalArea.z } fun doneBlocks(): Int { val totalArea = (end - start) + BlockPos(1, 1, 1) val yLayers = if (!inverted) { (current.y - start.y) * (totalArea.x * totalArea.z) } else { (end.y - current.y) * (totalArea.x * totalArea.z) } val zLayers = (current.z - start.z) * totalArea.x val xLayers = (current.x - start.x) return xLayers + yLayers + zLayers } } fun WorldIterator?.serializeNBT() = newNbt { val iter = this@serializeNBT if (iter != null) { add("start", iter.start) add("end", iter.end) add("current", iter.current) add("inverted", iter.inverted) } }
gpl-2.0
5ac536d14fe4bbe57d07ee635e9291e7
32.322581
113
0.539703
3.961637
false
false
false
false
ReactiveCircus/FlowBinding
flowbinding-viewpager2/src/main/java/reactivecircus/flowbinding/viewpager2/ViewPager2PageScrolledFlow.kt
1
1857
@file:Suppress("MatchingDeclarationName") package reactivecircus.flowbinding.viewpager2 import androidx.annotation.CheckResult import androidx.viewpager2.widget.ViewPager2 import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.conflate import reactivecircus.flowbinding.common.checkMainThread /** * Create a [Flow] of page scroll events on the [ViewPager2] instance. * * Note: Created flow keeps a strong reference to the [ViewPager2] instance * until the coroutine that launched the flow collector is cancelled. * * Example of usage: * * ``` * viewPager2.pageScrollEvents() * .onEach { event -> * // handle page scroll event * } * .launchIn(uiScope) * ``` */ @CheckResult @OptIn(ExperimentalCoroutinesApi::class) public fun ViewPager2.pageScrollEvents(): Flow<ViewPager2PageScrollEvent> = callbackFlow { checkMainThread() val callback = object : ViewPager2.OnPageChangeCallback() { override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int ) { trySend( ViewPager2PageScrollEvent( view = this@pageScrollEvents, position = position, positionOffset = positionOffset, positionOffsetPixel = positionOffsetPixels ) ) } } registerOnPageChangeCallback(callback) awaitClose { unregisterOnPageChangeCallback(callback) } }.conflate() public data class ViewPager2PageScrollEvent( public val view: ViewPager2, public val position: Int, public val positionOffset: Float, public val positionOffsetPixel: Int )
apache-2.0
ec4beea15510c4068a8d206295d6ec54
30.474576
90
0.693053
5.059946
false
false
false
false
toastkidjp/Jitte
music/src/main/java/jp/toastkid/media/music/MediaPlayerService.kt
1
9134
/* * Copyright (c) 2019 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.media.music import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.media.AudioManager import android.media.MediaPlayer import android.media.PlaybackParams import android.net.Uri import android.os.Bundle import android.support.v4.media.MediaBrowserCompat import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat import android.view.KeyEvent import androidx.core.app.NotificationManagerCompat import androidx.media.MediaBrowserServiceCompat import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.media.music.notification.NotificationFactory import timber.log.Timber /** * @author toastkidjp */ class MediaPlayerService : MediaBrowserServiceCompat() { private lateinit var stateBuilder: PlaybackStateCompat.Builder private lateinit var notificationManager: NotificationManagerCompat private lateinit var mediaSession: MediaSessionCompat private lateinit var preferenceApplier: PreferenceApplier private lateinit var notificationFactory: NotificationFactory private val mediaPlayer = MediaPlayer() private var audioNoisyReceiver: BroadcastReceiver? = null private var playbackSpeedReceiver: BroadcastReceiver? = null private val callback = object : MediaSessionCompat.Callback() { @PlaybackStateCompat.State private var mediaState: Int = PlaybackStateCompat.STATE_NONE override fun onPlayFromUri(uri: Uri?, extras: Bundle?) { super.onPlayFromUri(uri, extras) initializeReceiversIfNeed() registerReceiver(audioNoisyReceiver, audioNoisyFilter) registerReceiver(playbackSpeedReceiver, audioSpeedFilter) mediaPlayer.reset() if (uri != null) { mediaPlayer.setDataSource(this@MediaPlayerService, uri) } mediaPlayer.isLooping = true mediaPlayer.prepare() mediaSession.setMetadata( MusicFileFinder(contentResolver).invoke().firstOrNull { it.description?.mediaUri == uri } ) mediaSession.isActive = true mediaPlayer.start() setNewState(PlaybackStateCompat.STATE_PLAYING) startService(Intent(baseContext, MediaPlayerService::class.java)) val notification = notificationFactory() ?: return notificationManager.notify(NOTIFICATION_ID, notification) startForeground(NOTIFICATION_ID, notificationFactory()) } override fun onPlay() { if (mediaSession.controller.metadata == null) { return } initializeReceiversIfNeed() registerReceiver(audioNoisyReceiver, audioNoisyFilter) registerReceiver(playbackSpeedReceiver, audioSpeedFilter) mediaSession.isActive = true mediaPlayer.start() setNewState(PlaybackStateCompat.STATE_PLAYING) val notification = notificationFactory() ?: return notificationManager.notify(NOTIFICATION_ID, notification) startForeground(NOTIFICATION_ID, notificationFactory()) } override fun onPause() { unregisterReceivers() mediaSession.isActive = false mediaPlayer.pause() setNewState(PlaybackStateCompat.STATE_PAUSED) val notification = notificationFactory() ?: return notificationManager.notify(NOTIFICATION_ID, notification) stopForeground(false) } override fun onStop() { super.onStop() try { unregisterReceivers() } catch (e: IllegalArgumentException) { Timber.w(e) } mediaSession.isActive = false mediaPlayer.stop() setNewState(PlaybackStateCompat.STATE_STOPPED) notificationManager.cancel(NOTIFICATION_ID) stopForeground(true) } override fun onSetRepeatMode(repeatMode: Int) { mediaSession.setRepeatMode(repeatMode) when (repeatMode) { PlaybackStateCompat.REPEAT_MODE_ONE -> { //mediaPlayer.isLooping = true } else -> { //mediaPlayer.isLooping = false } } } override fun onMediaButtonEvent(mediaButtonEvent: Intent): Boolean { val keyEvent = mediaButtonEvent.getParcelableExtra<KeyEvent?>(Intent.EXTRA_KEY_EVENT) if (keyEvent == null || keyEvent.action != KeyEvent.ACTION_DOWN) { return false } return when (keyEvent.keyCode) { KeyEvent.KEYCODE_MEDIA_NEXT, KeyEvent.KEYCODE_MEDIA_SKIP_FORWARD -> { onSetRepeatMode(PlaybackStateCompat.REPEAT_MODE_ONE) true } else -> super.onMediaButtonEvent(mediaButtonEvent) } } private fun setNewState(@PlaybackStateCompat.State newState: Int) { mediaState = newState stateBuilder = PlaybackStateCompat.Builder() stateBuilder .setActions(PLAYBACK_ACTION) .setState(newState, mediaPlayer.currentPosition.toLong(), 1.0f) mediaSession.setPlaybackState(stateBuilder.build()) } } private fun initializeReceiversIfNeed() { if (audioNoisyReceiver == null) { audioNoisyReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { mediaSession.controller.transportControls.pause() } } } if (playbackSpeedReceiver == null) { playbackSpeedReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val speed = intent.getFloatExtra(KEY_EXTRA_SPEED, 1f) mediaPlayer.playbackParams = PlaybackParams().setSpeed(speed) } } } } override fun onCreate() { super.onCreate() preferenceApplier = PreferenceApplier(this) notificationManager = NotificationManagerCompat.from(baseContext) notificationFactory = NotificationFactory(applicationContext) { mediaSession } mediaSession = MediaSessionCompat(this, javaClass.simpleName).also { stateBuilder = PlaybackStateCompat.Builder() stateBuilder.setActions(PLAYBACK_ACTION) it.setPlaybackState(stateBuilder.build()) it.setCallback(callback) @Suppress("UsePropertyAccessSyntax") setSessionToken(it.sessionToken) } } override fun onGetRoot( clientPackageName: String, clientUid: Int, rootHints: Bundle? ): BrowserRoot { return BrowserRoot(ROOT_ID, null) } override fun onLoadChildren( parentId: String, result: Result<MutableList<MediaBrowserCompat.MediaItem>> ) { result.sendResult( MusicFileFinder(contentResolver).invoke() .map { MediaBrowserCompat.MediaItem(it.description, MediaBrowserCompat.MediaItem.FLAG_PLAYABLE) } .toMutableList() ) } override fun onDestroy() { unregisterReceivers() audioNoisyReceiver = null playbackSpeedReceiver = null super.onDestroy() } private fun unregisterReceivers() { if (audioNoisyReceiver != null) { unregisterReceiver(audioNoisyReceiver) } if (playbackSpeedReceiver != null) { unregisterReceiver(playbackSpeedReceiver) } } companion object { private val audioNoisyFilter = IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY) private const val ACTION_CHANGE_SPEED = "jp.toastkid.media.audio.speed" private val audioSpeedFilter = IntentFilter(ACTION_CHANGE_SPEED) private const val ROOT_ID = "media-root" private const val NOTIFICATION_ID = 46 private const val KEY_EXTRA_SPEED = "speed" private const val PLAYBACK_ACTION = PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_PAUSE or PlaybackStateCompat.ACTION_PLAY_PAUSE or PlaybackStateCompat.ACTION_STOP fun makeSpeedIntent(speed: Float) = Intent(ACTION_CHANGE_SPEED) .also { it.putExtra(KEY_EXTRA_SPEED, speed) } } }
epl-1.0
076040c1c8e87317c8b893cb9e889b42
34.823529
121
0.635428
5.701623
false
false
false
false
egenvall/TravelPlanner
app/src/main/java/com/egenvall/travelplanner/common/injection/module/VtModule.kt
1
2212
package com.egenvall.travelplanner.common.injection.module import com.egenvall.travelplanner.TravelPlanner import com.egenvall.travelplanner.network.Repository import com.egenvall.travelplanner.network.RestDataSource import com.egenvall.travelplanner.network.VtService import com.egenvall.travelplanner.util.ObjectAsListJsonAdapterFactory import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import com.squareup.moshi.Moshi import dagger.Module import dagger.Provides import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory import retrofit2.converter.moshi.MoshiConverterFactory import javax.inject.Singleton @Module class VtModule(private val app : TravelPlanner) { val baseUrl = "https://api.vasttrafik.se/bin/rest.exe/v2/" @Singleton @Provides internal fun provideMoshi() : MoshiConverterFactory{ val m = Moshi.Builder().add(ObjectAsListJsonAdapterFactory()).build() return MoshiConverterFactory.create(m) } @Singleton @Provides internal fun provideRetrofit(moshiConverterFactory: MoshiConverterFactory): Retrofit { val interceptor = HttpLoggingInterceptor() interceptor.level = HttpLoggingInterceptor.Level.BODY val client = OkHttpClient.Builder().addInterceptor(interceptor).build() val retrofit = Retrofit.Builder() .baseUrl(baseUrl) .client(client) .addConverterFactory(moshiConverterFactory) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build() return retrofit } @Provides @Singleton internal fun provideApiService(retrofit: Retrofit): VtService { return retrofit.create(VtService::class.java) } /** * @param token empty AccessToken * * * @param service Västtrafik API endpoints * * * @return Instance that implements Repository, whom exposes methods that can be fetched from * * API */ @Provides @Singleton fun provideRepository(service: VtService): Repository { return RestDataSource(service) } }
apache-2.0
add4438479b61924b81e3ec07400e18b
33.030769
97
0.734057
4.704255
false
false
false
false
meh/watch_doge
src/main/java/meh/watchdoge/request/Pinger.kt
1
1218
package meh.watchdoge.request; import meh.watchdoge.backend.Command as C; import android.os.Message; class Pinger(id: Int?): Family(C.PINGER) { private val _id = id; fun create(target: String) { create(target) { } } fun create(target: String, body: Create.() -> Unit) { val next = Create(target); next.body(); _command = next; } fun start() { _command = Start(_id!!); } fun stop() { _command = Stop(_id!!); } fun subscribe() { _command = Subscribe(_id!!); } fun unsubscribe() { _command = Unsubscribe(_id!!); } fun destroy() { _command = Destroy(_id!!); } class Create(target: String): Command(C.Pinger.CREATE) { var target = target; var interval = 0.0; override fun build(msg: Message) { super.build(msg); msg.getData().putString("target", target); if (interval != 0.0) { msg.getData().putDouble("interval", interval); } } } class Destroy(id: Int): CommandWithId(id, C.Pinger.DESTROY); class Start(id: Int): CommandWithId(id, C.Pinger.START); class Stop(id: Int): CommandWithId(id, C.Pinger.STOP); class Subscribe(id: Int): CommandWithId(id, C.Pinger.SUBSCRIBE); class Unsubscribe(id: Int): CommandWithId(id, C.Pinger.UNSUBSCRIBE); }
agpl-3.0
6b3cbc6202f958c8c95c6224d3fb2146
18.645161
69
0.643678
2.852459
false
false
false
false
yshrsmz/monotweety
app/src/test/java/net/yslibrary/monotweety/TestData.kt
1
894
package net.yslibrary.monotweety import android.content.pm.ApplicationInfo import android.content.pm.PackageInfo import java.io.BufferedReader import java.io.FileInputStream import java.io.InputStreamReader fun readJsonFromAssets(filename: String): String { val ASSET_BASE_PATH = "../app/src/test/assets/" val br = BufferedReader(InputStreamReader(FileInputStream("$ASSET_BASE_PATH$filename"))) val sb = StringBuilder() var line = br.readLine() while (line != null) { sb.append(line) line = br.readLine() } br.close() return sb.toString() } fun newPackageInfo(appName: String, pacakgeName: String): PackageInfo { return PackageInfo().apply { packageName = pacakgeName applicationInfo = ApplicationInfo() applicationInfo.apply { packageName = pacakgeName name = appName } } }
apache-2.0
f69fcdf7b43378a755fde8315cfc9741
24.542857
92
0.680089
4.318841
false
false
false
false
Kotlin/dokka
core/src/main/kotlin/pages/PageNodes.kt
1
7148
package org.jetbrains.dokka.pages import org.jetbrains.dokka.links.DRI import org.jetbrains.dokka.model.Documentable import org.jetbrains.dokka.model.WithChildren import java.util.* interface PageNode : WithChildren<PageNode> { val name: String override val children: List<PageNode> fun modified( name: String = this.name, children: List<PageNode> = this.children ): PageNode } interface ContentPage : PageNode { val content: ContentNode val dri: Set<DRI> val embeddedResources: List<String> @Deprecated("Deprecated. Remove its usages from your code.", ReplaceWith("this.documentables.firstOrNull()") ) val documentable: Documentable? get() = if (this is WithDocumentables) this.documentables.firstOrNull() else null fun modified( name: String = this.name, content: ContentNode = this.content, dri: Set<DRI> = this.dri, embeddedResources: List<String> = this.embeddedResources, children: List<PageNode> = this.children ): ContentPage } interface WithDocumentables { val documentables: List<Documentable> } abstract class RootPageNode(val forceTopLevelName: Boolean = false) : PageNode { val parentMap: Map<PageNode, PageNode> by lazy { IdentityHashMap<PageNode, PageNode>().apply { fun process(parent: PageNode) { parent.children.forEach { child -> put(child, parent) process(child) } } process(this@RootPageNode) } } fun transformPageNodeTree(operation: (PageNode) -> PageNode) = this.transformNode(operation) as RootPageNode fun transformContentPagesTree(operation: (ContentPage) -> ContentPage) = transformPageNodeTree { if (it is ContentPage) operation(it) else it } private fun PageNode.transformNode(operation: (PageNode) -> PageNode): PageNode = operation(this).let { newNode -> newNode.modified(children = newNode.children.map { it.transformNode(operation) }) } abstract override fun modified( name: String, children: List<PageNode> ): RootPageNode } class ModulePageNode( override val name: String, override val content: ContentNode, override val documentables: List<Documentable> = listOf(), override val children: List<PageNode>, override val embeddedResources: List<String> = listOf() ) : RootPageNode(), ModulePage { override val dri: Set<DRI> = setOf(DRI.topLevel) override fun modified(name: String, children: List<PageNode>): ModulePageNode = modified(name = name, content = this.content, dri = dri, children = children) override fun modified( name: String, content: ContentNode, dri: Set<DRI>, embeddedResources: List<String>, children: List<PageNode> ): ModulePageNode = if (name == this.name && content === this.content && embeddedResources === this.embeddedResources && children shallowEq this.children) this else ModulePageNode(name, content, documentables, children, embeddedResources) } class PackagePageNode( override val name: String, override val content: ContentNode, override val dri: Set<DRI>, override val documentables: List<Documentable> = listOf(), override val children: List<PageNode>, override val embeddedResources: List<String> = listOf() ) : PackagePage { init { require(name.isNotBlank()) { "PackagePageNode.name cannot be blank" } } override fun modified(name: String, children: List<PageNode>): PackagePageNode = modified(name = name, content = this.content, children = children) override fun modified( name: String, content: ContentNode, dri: Set<DRI>, embeddedResources: List<String>, children: List<PageNode> ): PackagePageNode = if (name == this.name && content === this.content && embeddedResources === this.embeddedResources && children shallowEq this.children) this else PackagePageNode(name, content, dri, documentables, children, embeddedResources) } class ClasslikePageNode( override val name: String, override val content: ContentNode, override val dri: Set<DRI>, override val documentables: List<Documentable> = listOf(), override val children: List<PageNode>, override val embeddedResources: List<String> = listOf() ) : ClasslikePage { override fun modified(name: String, children: List<PageNode>): ClasslikePageNode = modified(name = name, content = this.content, children = children) override fun modified( name: String, content: ContentNode, dri: Set<DRI>, embeddedResources: List<String>, children: List<PageNode> ): ClasslikePageNode = if (name == this.name && content === this.content && embeddedResources === this.embeddedResources && children shallowEq this.children) this else ClasslikePageNode(name, content, dri, documentables, children, embeddedResources) } class MemberPageNode( override val name: String, override val content: ContentNode, override val dri: Set<DRI>, override val documentables: List<Documentable> = listOf(), override val children: List<PageNode> = emptyList(), override val embeddedResources: List<String> = listOf() ) : MemberPage { override fun modified(name: String, children: List<PageNode>): MemberPageNode = modified(name = name, content = this.content, children = children) override fun modified( name: String, content: ContentNode, dri: Set<DRI>, embeddedResources: List<String>, children: List<PageNode> ): MemberPageNode = if (name == this.name && content === this.content && embeddedResources === this.embeddedResources && children shallowEq this.children) this else MemberPageNode(name, content, dri, documentables, children, embeddedResources) } class MultimoduleRootPageNode( override val dri: Set<DRI>, override val content: ContentNode, override val embeddedResources: List<String> = emptyList() ) : RootPageNode(forceTopLevelName = true), MultimoduleRootPage { override val name = "All modules" override val children: List<PageNode> = emptyList() override fun modified(name: String, children: List<PageNode>): RootPageNode = MultimoduleRootPageNode(dri, content, embeddedResources) override fun modified( name: String, content: ContentNode, dri: Set<DRI>, embeddedResources: List<String>, children: List<PageNode> ) = if (name == this.name && content === this.content && embeddedResources === this.embeddedResources && children shallowEq this.children) this else MultimoduleRootPageNode(dri, content, embeddedResources) } inline fun <reified T : PageNode> PageNode.children() = children.filterIsInstance<T>() private infix fun <T> List<T>.shallowEq(other: List<T>) = this === other || (this.size == other.size && (this zip other).all { (a, b) -> a === b })
apache-2.0
c4bd09e73dda7412e0b4de11f95e7722
35.845361
147
0.675434
4.501259
false
false
false
false
icarumbas/bagel
core/src/ru/icarumbas/bagel/engine/world/RoomWorldCreator.kt
1
11625
package ru.icarumbas.bagel.engine.world import com.badlogic.gdx.math.MathUtils import ru.icarumbas.bagel.engine.resources.ResourceManager class RoomWorldCreator( private val worldSize: Int, private val assets: ResourceManager ) { private lateinit var newRoom: Room private var meshCheckSides = IntArray(8) private val stringSides = arrayOf("Left", "Up", "Down", "Right") private var roomsTotal = 0 private var mainRoomId = 0 private var totalNotClosedGates = 0 private var endingRoomChance = 0 private val increaseEndingRoomChanceThreshold = 25 private val rooms = ArrayList<Room>() val mesh: Array<IntArray> = Array(worldSize) { IntArray(worldSize) }.apply { map { column -> column.fill(0) } get(worldSize / 2)[worldSize / 2] = 1 } private data class SideArguments( val sideName: String, val previousPassLink: Int, val stepX: Int, val stepY: Int, val countMeshX: Int, val countMeshY: Int, val meshClosestX: Int, val meshClosestY: Int, val meshClosestX2: Int, val meshClosestY2: Int ) fun createWorld(): ArrayList<Room>{ fun isRoomBigOnHeight(mainRoomId: Int) = rooms[mainRoomId].height != REG_ROOM_HEIGHT fun isRoomBigOnWidth(mainRoomId: Int) = rooms[mainRoomId].width != REG_ROOM_WIDTH fun getRootRoom() = Room("Maps/Map9.tmx", 0, assets).apply { meshCoords = intArrayOf(worldSize / 2, worldSize / 2, worldSize / 2, worldSize / 2) } rooms.add(getRootRoom()) totalNotClosedGates = getRoomGatesCount(rooms.first()) while (totalNotClosedGates != 0) { stringSides.forEach { createRoom(getSideArguments(it)) } if (isRoomBigOnHeight(mainRoomId)) { createRoom(getSideArguments("Right", isBig = true)) createRoom(getSideArguments("Left", isBig = true)) } if (isRoomBigOnWidth(mainRoomId)) { createRoom(getSideArguments("Up", isBig = true)) createRoom(getSideArguments("Down", isBig = true)) } mainRoomId++ if (isTimeToIncreaseRoomWithoutExitChance()) endingRoomChance = 75 } return rooms.apply { trimToSize() } } private fun getSideArguments(side: String, isBig: Boolean = false): SideArguments { return when (side) { "Right" -> { if (isBig) SideArguments("Right", 6, 1, 0, 2, 3, 0, 3, 0, 1) else SideArguments("Right", 2, 1, 0, 2, 1, 0, 1, 0, 3) } "Left" -> { if (isBig) SideArguments("Left", 4, -1, 0, 0, 3, 2, 3, 2, 1) else SideArguments("Left", 0, -1, 0, 0, 1, 2, 1, 2, 3) } "Up" -> { if (isBig) SideArguments("Up", 5, 0, -1, 2, 3, 2, 1, 0, 1) else SideArguments("Up", 1, 0, -1, 0, 3, 0, 1, 2, 1) } "Down" -> { if (isBig) SideArguments("Down", 7, 0, 1, 2, 1, 2, 3, 0, 3) else SideArguments("Down", 3, 0, 1, 0, 1, 0, 3, 2, 3) } else -> throw IllegalArgumentException("cant getSideArguments for $side") } } private fun isTimeToIncreaseRoomWithoutExitChance(): Boolean { return totalNotClosedGates > increaseEndingRoomChanceThreshold } private fun createRoom(sideArgs: SideArguments) { fun isRoomHasGateForSide() = assets.getTiledMap(rooms[mainRoomId].path).properties.get(sideArgs.sideName) == "Yes" if (isRoomHasGateForSide()) { // X and y positions on mesh. For big maps part of it val meshX = rooms[mainRoomId].meshCoords[sideArgs.countMeshX] val meshY = rooms[mainRoomId].meshCoords[sideArgs.countMeshY] fun addNewRoom(){ rooms.add(chooseMap(sideArgs.sideName, meshX, meshY).apply { meshCoords = intArrayOf( meshX + meshCheckSides[0], meshY + meshCheckSides[1], meshX + meshCheckSides[6], meshY + meshCheckSides[7]) }) } fun addGateToMainRoom(){ rooms[mainRoomId].passes[sideArgs.previousPassLink] = roomsTotal } fun fillMeshOnNewRoomCoordinates(){ for (i in 0..7 step 2) { mesh[meshY + meshCheckSides[i + 1]][meshX + meshCheckSides[i]] = 1 } } fun addJointToCollidingRoom() { fun isRoomOnCoordinates(room: Room, x: Int, y: Int) = (x == room.meshCoords[sideArgs.meshClosestX] && y == room.meshCoords[sideArgs.meshClosestY]) || (x == room.meshCoords[sideArgs.meshClosestX2] && y == room.meshCoords[sideArgs.meshClosestY2]) fun addLinkToMainRoom(room: Room) { rooms[mainRoomId].passes[sideArgs.previousPassLink] = rooms.indexOf(room) } for (room in rooms) { if (isRoomOnCoordinates(room,meshX + sideArgs.stepX, meshY + sideArgs.stepY)) { addLinkToMainRoom(room) totalNotClosedGates -= 1 return } } } fun isMeshHasAtLeastOneSpace() = mesh[meshY + sideArgs.stepY][meshX + sideArgs.stepX] == 0 if (isMeshHasAtLeastOneSpace()) { roomsTotal++ addNewRoom() totalNotClosedGates += getRoomGatesCount(rooms.last()) - 1 // updateCounters() addGateToMainRoom() fillMeshOnNewRoomCoordinates() } else { addJointToCollidingRoom() } } } private fun chooseMap(side: String, meshX: Int, meshY: Int): Room { newRoom = Room("Maps/Map${getNextRoomId(side)}.tmx", roomsTotal, assets) val meshRoomWidth = (newRoom.width / REG_ROOM_WIDTH).toInt() val meshRoomHeight = (newRoom.height / REG_ROOM_HEIGHT).toInt() meshCheckSides = getFitCheckValues(side, meshRoomWidth, meshRoomHeight) if (isMeshHasSpace(meshCheckSides, meshX, meshY)) { if (!isRoomJointsUnite(newRoom, getSideCheckValues(side, meshRoomWidth, meshRoomHeight), meshX, meshY)) { chooseMap(side, meshX, meshY) } } else { chooseMap(side, meshX, meshY) } return newRoom } private fun isRoomJointsUnite(newRoom: Room, checkSides: IntArray, meshX: Int, meshY: Int): Boolean { fun isRoomOnCoordinateExists(i: Int, room: Room) = ((meshX.plus(checkSides[i]) == room.meshCoords[0] || meshX.plus(checkSides[i]) == room.meshCoords[2]) && (meshY.plus(checkSides[i + 8]) == room.meshCoords[1] || meshY.plus(checkSides[i + 8]) == room.meshCoords[3])) fun isSidesConflict(index: Int, room: Room) = (assets.getTiledMap(room.path).properties[stringSides[3 - index]] == "Yes" && assets.getTiledMap(newRoom.path).properties[stringSides[index]] != "Yes") || (assets.getTiledMap(room.path).properties[stringSides[3 - index]] != "Yes" && assets.getTiledMap(newRoom.path).properties[stringSides[index]] == "Yes") var index = 0 rooms.forEach { for (i in 0..7) { if (isRoomOnCoordinateExists(i, it)) { if (isSidesConflict(index, it)) return false } if (i % 2 > 0) index++ } index = 0 } return true } private fun getSideCheckValues(side: String, meshRoomWidth: Int, meshRoomHeight: Int): IntArray { return when (side) { "Left" -> intArrayOf(-meshRoomWidth - 1, -meshRoomWidth - 1, -meshRoomWidth, -1, -meshRoomWidth, -1, 0, 0, // Xss 0, -meshRoomHeight + 1, -meshRoomHeight, -meshRoomHeight, 1, 1, 0, -meshRoomHeight + 1) // Yss "Up" -> intArrayOf(-1, -1, 0, meshRoomWidth - 1, 0, meshRoomWidth - 1, meshRoomWidth, meshRoomWidth, -1, -meshRoomHeight, -meshRoomHeight - 1, -meshRoomHeight - 1, 0, 0, -1, -meshRoomHeight) "Right" -> intArrayOf(0, 0, 1, meshRoomWidth, meshRoomWidth, 1, meshRoomWidth + 1, meshRoomWidth + 1, 0, -meshRoomHeight + 1, -meshRoomHeight, -meshRoomHeight, 1, 1, -meshRoomHeight + 1, 0) "Down" -> intArrayOf(-1, -1, 0, meshRoomWidth - 1, 0, meshRoomWidth - 1, meshRoomWidth, meshRoomWidth, 1, meshRoomHeight, 0, 0, meshRoomHeight + 1, meshRoomHeight + 1, 1, meshRoomHeight) else -> throw IllegalArgumentException("Unknown side: $side") } } private fun getFitCheckValues(side: String, meshRoomWidth: Int, meshRoomHeight: Int): IntArray { return when (side) { "Left" -> intArrayOf(-meshRoomWidth, 0, -meshRoomWidth, -meshRoomHeight + 1, -1, 0, -1, -meshRoomHeight + 1) "Up" -> intArrayOf(0, -1, meshRoomWidth - 1, -1, 0, -meshRoomHeight, meshRoomWidth - 1, -meshRoomHeight) "Right" -> intArrayOf(1, 0, meshRoomWidth, 0, 1, -meshRoomHeight + 1, meshRoomWidth, -meshRoomHeight + 1) "Down" -> intArrayOf(0, meshRoomHeight, 0, 1, meshRoomWidth - 1, meshRoomHeight, meshRoomWidth - 1, 1) else -> throw IllegalArgumentException("Unknown side: $side") } } private fun getRoomGatesCount(room: Room): Int{ var gatesCount = 0 assets.getTiledMap(room.path).properties.keys.forEach { if (it[0].isUpperCase() && it != "Height" && it != "Width") { gatesCount += when { (room.width != REG_ROOM_WIDTH && (it == "Up" || it == "Down")) || (room.height != REG_ROOM_HEIGHT && (it == "Right" || it == "Left")) -> 2 else -> 1 } } } return gatesCount } private fun isMeshHasSpace(fitCheckValues: IntArray, meshX: Int, meshY: Int): Boolean { return (mesh[meshY + fitCheckValues[1]][meshX + fitCheckValues[0]] == 0) && (mesh[meshY + fitCheckValues[3]][meshX + fitCheckValues[2]] == 0) && (mesh[meshY + fitCheckValues[5]][meshX + fitCheckValues[4]] == 0) && (mesh[meshY + fitCheckValues[7]][meshX + fitCheckValues[6]] == 0) } private fun getNextRoomId(side: String): Int { fun isEndingRoomChanced() = MathUtils.random(100) < endingRoomChance fun isRoomPathEqualsNearest(mainRoomId: Int, randomRoomId: Int) = rooms[mainRoomId].path == "Maps/Map$randomRoomId.tmx" fun getRandomRoomIdForSide() = if (isEndingRoomChanced()) when (side) { "Left" -> 13 "Right" -> 16 "Up" -> 15 else -> 14 } else MathUtils.random(0, MAPS_TOTAL - 1) val randomRoomId = getRandomRoomIdForSide() return if (isRoomPathEqualsNearest(mainRoomId, randomRoomId)) getNextRoomId(side) else randomRoomId } }
apache-2.0
918dabea11d3793c303e7dc05edee437
35.442006
133
0.547957
3.960818
false
false
false
false
mrkirby153/KirBot
src/main/kotlin/me/mrkirby153/KirBot/command/control/MarkovCommand.kt
1
5563
package me.mrkirby153.KirBot.command.control import com.mrkirby153.bfs.query.DB import me.mrkirby153.KirBot.Bot import me.mrkirby153.KirBot.command.CommandException import me.mrkirby153.KirBot.command.annotations.AdminCommand import me.mrkirby153.KirBot.command.annotations.Command import me.mrkirby153.KirBot.command.args.CommandContext import me.mrkirby153.KirBot.logger.LogManager import me.mrkirby153.KirBot.utils.Context import me.mrkirby153.KirBot.utils.nameAndDiscrim import me.mrkirby153.KirBot.utils.resolveMentions import me.mrkirby153.kcutils.Time import net.dv8tion.jda.api.sharding.ShardManager import java.util.Hashtable import java.util.Random import java.util.Vector import javax.inject.Inject import kotlin.system.measureTimeMillis class MarkovCommand @Inject constructor(private val shardManager: ShardManager){ private val chains = mutableMapOf<String, MarkovChain>() @Command(name = "markov", arguments = ["<user:snowflake>", "[amount:int]"]) @AdminCommand fun execute(context: Context, cmdContext: CommandContext) { val userChain = chains[cmdContext.get<String>("user")!!] ?: throw CommandException( "No chain found. Did you generate one?") val user = shardManager.getUserById(cmdContext.get<String>("user")!!)?.nameAndDiscrim ?: cmdContext.get<String>("user")!! val chain = StringBuilder() for (i in 0..(cmdContext.get<Int>("amount") ?: 1)) { chain.append(userChain.makeSentence(maxDepth = 50)) } context.channel.sendMessage("```$chain\n - $user```").queue() } @Command(name = "generate", arguments = ["<user:snowflake>", "[limit:int]"], parent = "markov") @AdminCommand fun generateChain(context: Context, cmdContext: CommandContext) { val limit = cmdContext.get<Int>("limit") ?: -1 val msg = context.channel.sendMessage( "Generating chain with " + (if (limit == -1) "all" else limit) + " messages").complete() Bot.scheduler.submit { var count = 0 val time = measureTimeMillis { val params = mutableListOf<Any>(cmdContext.get<String>("user")!!) if (limit != -1) params.add(limit) val encrypted = DB.getFirstColumnValues<String>( "SELECT `message` FROM server_messages WHERE author = ?" + (if (limit != -1) " LIMIT ?" else ""), *params.toTypedArray()) val chain = MarkovChain() encrypted.forEach { val decrypted = LogManager.decrypt(it) val resolved = decrypted.resolveMentions() resolved.split(Regex("[.?!]")).forEach { sentence -> count++ chain.addWords(sentence.trim() + ".") } } this.chains[cmdContext.get<String>("user")!!] = chain } msg.editMessage("Done in ${Time.formatLong(time = time, short = true, smallest = Time.TimeUnit.MILLISECONDS)}. With $count messages").queue() } } @Command(name = "delete", arguments = ["<user:snowflake>"], parent = "markov") @AdminCommand fun deleteChain(context: Context, cmdContext: CommandContext) { chains.remove(cmdContext.get<String>("user")!!) context.success() } private class MarkovChain { val chain: Hashtable<String, Vector<String>> = Hashtable() val random = Random() val endChars = arrayOf('.', '!', '?') init { chain["_start"] = Vector() chain["_end"] = Vector() } fun addWords(phrase: String) { val words = phrase.split(" ") if (words.size < 2) return for (i in words.indices) { if (i == 0) { val startWords = this.chain["_start"]!! startWords.add(words[i]) var suffix = this.chain[words[i]] if (suffix == null) { suffix = Vector() suffix.add(words[i + 1]) this.chain[words[i]] = suffix } } else if (i == words.size - 1) { this.chain["_end"]?.add(words[i]) } else { var suffix = this.chain[words[i]] if (suffix == null) { suffix = Vector() } suffix.add(words[i + 1]) this.chain[words[i]] = suffix } } } tailrec fun makeSentence(builder: StringBuilder = StringBuilder(), nextWord: String = "$$$$", currDepth: Int = 0, maxDepth: Int = 1000): String { val next = if (nextWord == "$$$$") { this.chain["_start"]!!.elementAt(random.nextInt(this.chain["_start"]!!.size)) } else { nextWord } builder.append("$next ") return if (currDepth >= maxDepth || endChars.contains(next[next.length - 1])) { builder.toString() } else { val selection = this.chain[next] ?: return builder.toString() val n = selection.elementAt(random.nextInt(selection.size)) makeSentence(builder, n, currDepth + 1, maxDepth) } } } }
mit
078ab9f02369b63ef35457580635767c
40.214815
121
0.543052
4.548651
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/actions/ide/CopyUpsourceSelectionReference.kt
1
4271
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.actions.ide import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.psi.PsiFileSystemItem import com.vladsch.md.nav.MdBundle import com.vladsch.md.nav.actions.ide.CopyReferenceUtils.getElementsToCopy import com.vladsch.md.nav.actions.ide.CopyReferenceUtils.highlight import com.vladsch.md.nav.actions.ide.CopyReferenceUtils.setStatusBarText import com.vladsch.md.nav.settings.MdApplicationSettings import java.awt.datatransfer.StringSelection // CopyPathProvider only available 2019.08.26, so 193+ open class CopyUpsourceSelectionReference : DumbAwareAction() { override fun update(e: AnActionEvent) { if (isAvailable(e)) { val dataContext = e.dataContext val editor = CommonDataKeys.EDITOR.getData(dataContext) val project = e.project if (project != null) { val elements = getElementsToCopy(editor, dataContext) val copy = project.let { editor?.let { it1 -> getQualifiedName(it, elements, it1) } } if (copy != null) { val text = getText(copy) val description = getDescription(copy) if (text != null) e.presentation.text = text if (description != null) e.presentation.description = description e.presentation.isEnabledAndVisible = true super.update(e) return } } } e.presentation.isEnabledAndVisible = false } fun isAvailable(e: AnActionEvent): Boolean { var available = MdApplicationSettings.instance.documentSettings.copyUpsourcePathWithLineNumbers if (available) { val project = e.project if (project != null) { available = CopyReferenceUtils.isUpsourceCopyReferenceAvailable(project) } } return available } fun getDescription(copy: String): String? { return MdBundle.message("message.upsource.path.to.description", copy) } fun getText(copy: String): String? { return MdBundle.message("message.upsource.path.to.label", copy) } override fun actionPerformed(e: AnActionEvent) { val project = getEventProject(e) val dataContext = e.dataContext val editor = CommonDataKeys.EDITOR.getData(dataContext) val elements = getElementsToCopy(editor, dataContext) val copy = project?.let { editor?.let { it1 -> getQualifiedName(it, elements, it1) } } CopyPasteManager.getInstance().setContents(StringSelection(copy)) setStatusBarText(project, MdBundle.message("message.0.path.has.been.copied", copy)) highlight(editor, project, elements) } fun getQualifiedName(project: Project, elements: List<PsiElement>, editor: Editor?): String? { if (elements.isEmpty()) { return getPathToElement(project, editor?.document?.let { FileDocumentManager.getInstance().getFile(it) }, editor) } val refs = elements.map { element -> val virtualFile = if (element is PsiFileSystemItem) element.virtualFile else element.containingFile.virtualFile getPathToElement(project, virtualFile ?: return@map null, editor) ?: return@map null }.filterNotNull() return if (refs.isNotEmpty()) refs.joinToString("\n") else null } fun getPathToElement(project: Project, virtualFile: VirtualFile?, editor: Editor?): String? { return if (virtualFile == null || editor == null) null else editor.let { CopyReferenceUtils.getUpsourceReference(project, virtualFile, editor) } } }
apache-2.0
7fe8c60e8e4a2183d456a00c16f1ff46
40.872549
177
0.6797
4.766741
false
false
false
false
NordicSemiconductor/Android-nRF-Toolbox
profile_uart/src/main/java/no/nordicsemi/android/uart/view/OutputSection.kt
1
7065
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package no.nordicsemi.android.uart.view import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Delete import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch import no.nordicsemi.android.ui.view.SectionTitle import no.nordicsemi.android.uart.R import no.nordicsemi.android.uart.data.UARTRecord import no.nordicsemi.android.uart.data.UARTRecordType import java.text.SimpleDateFormat import java.util.* @Composable internal fun OutputSection(records: List<UARTRecord>, onEvent: (UARTViewEvent) -> Unit) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxSize() ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { SectionTitle( resId = R.drawable.ic_output, title = stringResource(R.string.uart_output), modifier = Modifier, menu = { Menu(onEvent) } ) } Spacer(modifier = Modifier.size(16.dp)) val scrollState = rememberLazyListState() val scrollDown = remember { derivedStateOf { scrollState.isScrolledToTheEnd() } } LazyColumn( modifier = Modifier.fillMaxWidth(), state = scrollState ) { if (records.isEmpty()) { item { Text(text = stringResource(id = R.string.uart_output_placeholder)) } } else { records.forEach { item { when (it.type) { UARTRecordType.INPUT -> MessageItemInput(record = it) UARTRecordType.OUTPUT -> MessageItemOutput(record = it) } Spacer(modifier = Modifier.height(16.dp)) } } } } LaunchedEffect(records, scrollDown.value) { if (!scrollDown.value || records.isEmpty()) { return@LaunchedEffect } launch { scrollState.scrollToItem(records.lastIndex) } } } } fun LazyListState.isScrolledToTheEnd() = layoutInfo.visibleItemsInfo.lastOrNull()?.index == layoutInfo.totalItemsCount - 1 @Composable private fun MessageItemInput(record: UARTRecord) { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.End ) { Text( text = record.timeToString(), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurface ) Spacer(modifier = Modifier.height(4.dp)) Column( modifier = Modifier .clip(RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp, bottomStart = 10.dp)) .background(MaterialTheme.colorScheme.secondary) .padding(8.dp), horizontalAlignment = Alignment.End ) { Text( text = record.text, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSecondary ) } } } @Composable private fun MessageItemOutput(record: UARTRecord) { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.Start ) { Text( text = record.timeToString(), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurface, ) Spacer(modifier = Modifier.height(4.dp)) Column( modifier = Modifier .clip(RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp, bottomEnd = 10.dp)) .background(MaterialTheme.colorScheme.primary) .padding(8.dp) ) { Text( text = record.text, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onPrimary ) } } } @Composable private fun Menu(onEvent: (UARTViewEvent) -> Unit) { Row { IconButton(onClick = { onEvent(ClearOutputItems) }) { Icon( Icons.Default.Delete, contentDescription = stringResource(id = R.string.uart_clear_items), ) } } } private val datFormatter = SimpleDateFormat("dd MMMM yyyy, HH:mm:ss", Locale.ENGLISH) private fun UARTRecord.timeToString(): String { return datFormatter.format(timestamp) }
bsd-3-clause
7bc2b98e639d703f7915b90ea885bdcc
35.606218
122
0.656476
4.875776
false
false
false
false
dataloom/conductor-client
src/test/kotlin/com/openlattice/linking/PostgresLinkingLogServiceTest.kt
1
5225
package com.openlattice.linking import com.dataloom.mappers.ObjectMappers import com.fasterxml.jackson.databind.ObjectMapper import com.kryptnostic.rhizome.configuration.RhizomeConfiguration import com.kryptnostic.rhizome.configuration.service.ConfigurationService import com.openlattice.postgres.PostgresTable import com.zaxxer.hikari.HikariConfig import com.zaxxer.hikari.HikariDataSource import org.junit.AfterClass import org.junit.BeforeClass import org.junit.Test import org.slf4j.Logger import org.slf4j.LoggerFactory import java.util.* class PostgresLinkingLogServiceTest { companion object { private val logger: Logger = LoggerFactory.getLogger(PostgresLinkingLogServiceTest::class.java) @JvmStatic private val objectMapper: ObjectMapper = ObjectMappers.getJsonMapper() private val hds: HikariDataSource = HikariDataSource(HikariConfig(ConfigurationService.StaticLoader.loadConfiguration(RhizomeConfiguration::class.java)?.postgresConfiguration?.get()?.hikariConfiguration)) private var service: PostgresLinkingLogService = PostgresLinkingLogService(hds, objectMapper) @BeforeClass @JvmStatic fun setUp() { val sql = PostgresTable.LINKING_LOG.createTableQuery() logger.info("creating table $sql") hds.connection.use { conn -> conn.prepareStatement(sql).use {ps -> ps.execute() } } } @AfterClass @JvmStatic fun tearDown() { logger.info("dropping table") hds.connection.use { conn -> conn.prepareStatement("DROP TABLE linking_log").use {ps -> ps.execute() } } } @JvmStatic fun generateNRandomLinks( n: Number ) : Map<UUID, Set<UUID>> { val randEsId: UUID = UUID.randomUUID() val randEkIds = generateSequence { UUID.randomUUID() }.take(n as Int).toSet() return mapOf( randEsId to randEkIds ) } } @Test fun logLinkCreated() { val linkingId = UUID.randomUUID() val links = generateNRandomLinks(10) service.createOrUpdateCluster( linkingId, links , true ) val latest = service.readLatestLinkLog( linkingId ) assert(links == latest) } @Test fun logEntitiesAddedToLink() { val linkingId = UUID.randomUUID() val links = generateNRandomLinks(10) val newLinks = generateNRandomLinks(10) service.createOrUpdateCluster( linkingId, links, true ) var latest = service.readLatestLinkLog( linkingId ) assert( latest == links ) service.createOrUpdateCluster( linkingId, newLinks, false ) latest = service.readLatestLinkLog( linkingId ) assert( latest.containsKey(links.keys.first()) ) assert( latest.containsKey(newLinks.keys.first()) ) assert( latest == links.plus(newLinks) ) } @Test fun logEntitiesRemovedFromLink() { val linkingId = UUID.randomUUID() val links = generateNRandomLinks(10) val otherLinks = generateNRandomLinks(10) service.createOrUpdateCluster( linkingId, links, true ) var latest = service.readLatestLinkLog(linkingId) assert( latest == links ) service.createOrUpdateCluster( linkingId, otherLinks, false) latest = service.readLatestLinkLog(linkingId) assert( latest == links.plus(otherLinks) ) service.clearEntitiesFromCluster( linkingId, links ) latest = service.readLatestLinkLog(linkingId) assert( latest == otherLinks ) } @Test fun readLatestLinkLog() { val linkingId = UUID.randomUUID() val firstAdd = generateNRandomLinks(10) service.createOrUpdateCluster( linkingId, firstAdd, true ) var latest = service.readLatestLinkLog( linkingId ) var expected = firstAdd assert(expected.equals(latest)) val secondAdd = generateNRandomLinks(10) service.createOrUpdateCluster( linkingId, secondAdd, false ) latest = service.readLatestLinkLog( linkingId ) expected = expected.plus(secondAdd) assert(expected.equals(latest)) val thirdAdd = generateNRandomLinks(10) service.createOrUpdateCluster( linkingId, thirdAdd, false ) latest = service.readLatestLinkLog( linkingId ) expected = expected.plus(thirdAdd) assert(expected.equals(latest)) val fourthAdd = generateNRandomLinks(10) service.createOrUpdateCluster( linkingId , fourthAdd, false ) latest = service.readLatestLinkLog( linkingId ) expected = expected.plus(fourthAdd) assert(expected.equals(latest)) service.createOrUpdateCluster( UUID.randomUUID(), generateNRandomLinks(10), true ) latest = service.readLatestLinkLog( linkingId ) assert(expected.equals(latest)) service.clearEntitiesFromCluster( linkingId, fourthAdd ) latest = service.readLatestLinkLog( linkingId ) expected = expected.minus( fourthAdd.keys.first() ) assert(expected.equals(latest)) } }
gpl-3.0
7056f971a96ac79c025b8abe5f1151ed
36.056738
212
0.666603
4.575306
false
true
false
false
nithia/xkotlin
exercises/allergies/src/test/kotlin/AllergiesTest.kt
1
4723
import org.junit.Test import org.junit.Ignore import kotlin.test.assertEquals class AllergiesTest { @Test fun noAllergiesMeansNotAllergicToAnything() { val allergies = Allergies(0) assertEquals(false, allergies.isAllergicTo(Allergen.EGGS)) assertEquals(false, allergies.isAllergicTo(Allergen.PEANUTS)) assertEquals(false, allergies.isAllergicTo(Allergen.STRAWBERRIES)) assertEquals(false, allergies.isAllergicTo(Allergen.CATS)) } @Ignore @Test fun allergicToEggs() { val allergies = Allergies(1) assertEquals(true, allergies.isAllergicTo(Allergen.EGGS)) } @Ignore @Test fun allergicToPeanuts() { val allergies = Allergies(2) assertEquals(true, allergies.isAllergicTo(Allergen.PEANUTS)) } @Ignore @Test fun allergicToShellfish() { val allergies = Allergies(4) assertEquals(true, allergies.isAllergicTo(Allergen.SHELLFISH)) } @Ignore @Test fun allergicToStrawberries() { val allergies = Allergies(8) assertEquals(true, allergies.isAllergicTo(Allergen.STRAWBERRIES)) } @Ignore @Test fun allergicToTomatoes() { val allergies = Allergies(16) assertEquals(true, allergies.isAllergicTo(Allergen.TOMATOES)) } @Ignore @Test fun allergicToChocolate() { val allergies = Allergies(32) assertEquals(true, allergies.isAllergicTo(Allergen.CHOCOLATE)) } @Ignore @Test fun allergicToPollen() { val allergies = Allergies(64) assertEquals(true, allergies.isAllergicTo(Allergen.POLLEN)) } @Ignore @Test fun allergicToCats() { val allergies = Allergies(128) assertEquals(true, allergies.isAllergicTo(Allergen.CATS)) } @Ignore @Test fun isAllergicToEggsInAdditionToOtherStuff() { val allergies = Allergies(5) assertEquals(true, allergies.isAllergicTo(Allergen.EGGS)) } @Ignore @Test fun noAllergies() { val allergies = Allergies(0) assertEquals(0, allergies.getList().size) } @Ignore @Test fun isAllergicToJustEggs() { val allergies = Allergies(1) val expectedAllergens = listOf(Allergen.EGGS) assertEquals(expectedAllergens, allergies.getList()) } @Ignore @Test fun isAllergicToJustPeanuts() { val allergies = Allergies(2) val expectedAllergens = listOf(Allergen.PEANUTS) assertEquals(expectedAllergens, allergies.getList()) } @Ignore @Test fun isAllergicToJustStrawberries() { val allergies = Allergies(8) val expectedAllergens = listOf(Allergen.STRAWBERRIES) assertEquals(expectedAllergens, allergies.getList()) } @Ignore @Test fun isAllergicToEggsAndPeanuts() { val allergies = Allergies(3) val expectedAllergens = listOf( Allergen.EGGS, Allergen.PEANUTS ) assertEquals(expectedAllergens, allergies.getList()) } @Ignore @Test fun isAllergicToEggsAndShellfish() { val allergies = Allergies(5) val expectedAllergens = listOf( Allergen.EGGS, Allergen.SHELLFISH ) assertEquals(expectedAllergens, allergies.getList()) } @Ignore @Test fun isAllergicToLotsOfStuff() { val allergies = Allergies(248) val expectedAllergens = listOf( Allergen.STRAWBERRIES, Allergen.TOMATOES, Allergen.CHOCOLATE, Allergen.POLLEN, Allergen.CATS ) assertEquals(expectedAllergens, allergies.getList()) } @Ignore @Test fun isAllergicToEverything() { val allergies = Allergies(255) val expectedAllergens = listOf( Allergen.EGGS, Allergen.PEANUTS, Allergen.SHELLFISH, Allergen.STRAWBERRIES, Allergen.TOMATOES, Allergen.CHOCOLATE, Allergen.POLLEN, Allergen.CATS ) assertEquals(expectedAllergens, allergies.getList()) } @Ignore @Test fun ignoreNonAllergenScoreParts() { val allergies = Allergies(509) val expectedAllergens = listOf( Allergen.EGGS, Allergen.SHELLFISH, Allergen.STRAWBERRIES, Allergen.TOMATOES, Allergen.CHOCOLATE, Allergen.POLLEN, Allergen.CATS ) assertEquals(expectedAllergens, allergies.getList()) } }
mit
c9fc6ca34110405409e78a6cce1eab8a
22.853535
74
0.607453
3.349645
false
true
false
false
keidrun/qstackoverflow
src/test/kotlin/com/keidrun/qstackoverflow/lib/SOSerectorTest.kt
1
5265
/** * Copyright 2017 Keid */ package com.keidrun.qstackoverflow.lib import org.junit.Test import kotlin.test.assertEquals class SOSerectorTest { @Test fun testFormatDate() { val sut: SOSerector = SOSerector.Format.DATE val expected: String = "yyyy-MM-dd" val actual: String = sut.toString() assertEquals(expected = expected, actual = actual) } @Test fun testOrderDesc() { val sut: SOSerector = SOSerector.Order.DESC val expected: String = "desc" val actual: String = sut.toString() assertEquals(expected = expected, actual = actual) } @Test fun testOrderAsc() { val sut: SOSerector = SOSerector.Order.ASC val expected: String = "asc" val actual: String = sut.toString() assertEquals(expected = expected, actual = actual) } @Test fun searchOrderDesc() { val expected: SOSerector = SOSerector.Order.DESC val arg: String = "desc" val actual: SOSerector = SOSerector.Order.DESC.serectorOf(arg) assertEquals(expected = expected, actual = actual) } @Test fun searchOrderAsc() { val expected: SOSerector = SOSerector.Order.ASC val arg: String = "asc" val actual: SOSerector = SOSerector.Order.DESC.serectorOf(arg) assertEquals(expected = expected, actual = actual) } @Test fun searchOrderDefault() { val expected: SOSerector = SOSerector.Order.DESC val arg: String = "hoge" val actual: SOSerector = SOSerector.Order.DESC.serectorOf(arg) assertEquals(expected = expected, actual = actual) } @Test fun testSortActivity() { val sut: SOSerector = SOSerector.Sort.ACTIVITY val expected: String = "activity" val actual: String = sut.toString() assertEquals(expected = expected, actual = actual) } @Test fun testSortVotes() { val sut: SOSerector = SOSerector.Sort.VOTES val expected: String = "votes" val actual: String = sut.toString() assertEquals(expected = expected, actual = actual) } @Test fun testSortCreation() { val sut: SOSerector = SOSerector.Sort.CREATION val expected: String = "creation" val actual: String = sut.toString() assertEquals(expected = expected, actual = actual) } @Test fun testSortRelevance() { val sut: SOSerector = SOSerector.Sort.RELEVANCE val expected: String = "relevance" val actual: String = sut.toString() assertEquals(expected = expected, actual = actual) } @Test fun searchSortActivity() { val expected: SOSerector = SOSerector.Sort.ACTIVITY val arg: String = "activity" val actual: SOSerector = SOSerector.Sort.ACTIVITY.serectorOf(arg) assertEquals(expected = expected, actual = actual) } @Test fun searchSortVotes() { val expected: SOSerector = SOSerector.Sort.VOTES val arg: String = "votes" val actual: SOSerector = SOSerector.Sort.ACTIVITY.serectorOf(arg) assertEquals(expected = expected, actual = actual) } @Test fun searchSortCreation() { val expected: SOSerector = SOSerector.Sort.CREATION val arg: String = "creation" val actual: SOSerector = SOSerector.Sort.ACTIVITY.serectorOf(arg) assertEquals(expected = expected, actual = actual) } @Test fun searchSortRelevance() { val expected: SOSerector = SOSerector.Sort.RELEVANCE val arg: String = "relevance" val actual: SOSerector = SOSerector.Sort.ACTIVITY.serectorOf(arg) assertEquals(expected = expected, actual = actual) } @Test fun searchSortDefault() { val expected: SOSerector = SOSerector.Sort.ACTIVITY val arg: String = "hoge" val actual: SOSerector = SOSerector.Sort.ACTIVITY.serectorOf(arg) assertEquals(expected = expected, actual = actual) } @Test fun testSiteEnglish() { val sut: SOSerector = SOSerector.Site.ENGLISH val expected: String = "en" val actual: String = sut.toString() assertEquals(expected = expected, actual = actual) } @Test fun testSiteJapanese() { val sut: SOSerector = SOSerector.Site.JAPANESE val expected: String = "ja" val actual: String = sut.toString() assertEquals(expected = expected, actual = actual) } @Test fun searchSiteEnglish() { val expected: SOSerector = SOSerector.Site.ENGLISH val arg: String = "en" val actual: SOSerector = SOSerector.Site.ENGLISH.serectorOf(arg) assertEquals(expected = expected, actual = actual) } @Test fun searchSiteJapanese() { val expected: SOSerector = SOSerector.Site.JAPANESE val arg: String = "ja" val actual: SOSerector = SOSerector.Site.ENGLISH.serectorOf(arg) assertEquals(expected = expected, actual = actual) } @Test fun searchSiteDefault() { val expected: SOSerector = SOSerector.Site.ENGLISH val arg: String = "hoge" val actual: SOSerector = SOSerector.Site.ENGLISH.serectorOf(arg) assertEquals(expected = expected, actual = actual) } }
mit
ed10034fdf71b1e8f41a082991e5b7a1
26.570681
73
0.639316
4.053118
false
true
false
false
wordpress-mobile/WordPress-Stores-Android
fluxc/src/main/java/org/wordpress/android/fluxc/model/revisions/LocalRevisionModel.kt
2
2210
package org.wordpress.android.fluxc.model.revisions import com.yarolegovich.wellsql.core.Identifiable import com.yarolegovich.wellsql.core.annotation.Column import com.yarolegovich.wellsql.core.annotation.PrimaryKey import com.yarolegovich.wellsql.core.annotation.Table import org.wordpress.android.fluxc.model.PostModel import org.wordpress.android.fluxc.model.SiteModel @Table class LocalRevisionModel(@PrimaryKey @Column private var id: Int = 0) : Identifiable { @Column var revisionId: Long = 0 @Column var postId: Long = 0 @Column var siteId: Long = 0 @Column var diffFromVersion: Long = 0 @Column var totalAdditions: Int = 0 @Column var totalDeletions: Int = 0 @Column var postContent: String? = null @Column var postExcerpt: String? = null @Column var postTitle: String? = null @Column var postDateGmt: String? = null @Column var postModifiedGmt: String? = null @Column var postAuthorId: String? = null override fun getId(): Int { return this.id } override fun setId(id: Int) { this.id = id } companion object { @JvmStatic fun fromRevisionModel(revisionModel: RevisionModel, site: SiteModel, post: PostModel): LocalRevisionModel { val localRevisionModel = LocalRevisionModel() localRevisionModel.revisionId = revisionModel.revisionId localRevisionModel.postId = post.remotePostId localRevisionModel.siteId = site.siteId localRevisionModel.diffFromVersion = revisionModel.diffFromVersion localRevisionModel.totalAdditions = revisionModel.totalAdditions localRevisionModel.totalDeletions = revisionModel.totalDeletions localRevisionModel.postContent = revisionModel.postContent localRevisionModel.postExcerpt = revisionModel.postExcerpt localRevisionModel.postTitle = revisionModel.postTitle localRevisionModel.postDateGmt = revisionModel.postDateGmt localRevisionModel.postModifiedGmt = revisionModel.postModifiedGmt localRevisionModel.postAuthorId = revisionModel.postAuthorId return localRevisionModel } } }
gpl-2.0
4b944c5ee55abbee32641ffcdc99267e
35.229508
115
0.71991
4.623431
false
false
false
false