repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
farmerbb/Notepad
app/src/main/java/com/farmerbb/notepad/model/Prefs.kt
1
3393
/* Copyright 2022 Braden Farmer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farmerbb.notepad.model import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import de.schnettler.datastore.manager.PreferenceRequest object PrefKeys { val Theme = stringPreferencesKey("theme") val FontSize = stringPreferencesKey("font_size") val SortBy = stringPreferencesKey("sort_by") val ExportFilename = stringPreferencesKey("export_filename") val ShowDialogs = booleanPreferencesKey("show_dialogs") val ShowDate = booleanPreferencesKey("show_date") val DirectEdit = booleanPreferencesKey("direct_edit") val Markdown = booleanPreferencesKey("markdown") val RtlSupport = booleanPreferencesKey("rtl_layout") val ShowDoubleTapMessage = booleanPreferencesKey("show_double_tap_message") val FirstRun = intPreferencesKey("first-run") val FirstLoad = intPreferencesKey("first-load") } object Prefs { object Theme: PreferenceRequest<String>( key = PrefKeys.Theme, defaultValue = "light-sans" ) object FontSize: PreferenceRequest<String>( key = PrefKeys.FontSize, defaultValue = "normal" ) object SortBy: PreferenceRequest<String>( key = PrefKeys.SortBy, defaultValue = "date" ) object ExportFilename: PreferenceRequest<String>( key = PrefKeys.ExportFilename, defaultValue = "text-only" ) object ShowDialogs: PreferenceRequest<Boolean>( key = PrefKeys.ShowDialogs, defaultValue = false ) object ShowDate: PreferenceRequest<Boolean>( key = PrefKeys.ShowDate, defaultValue = false ) object DirectEdit: PreferenceRequest<Boolean>( key = PrefKeys.DirectEdit, defaultValue = false ) object Markdown: PreferenceRequest<Boolean>( key = PrefKeys.Markdown, defaultValue = false ) object RtlSupport: PreferenceRequest<Boolean>( key = PrefKeys.RtlSupport, defaultValue = false ) object ShowDoubleTapMessage: PreferenceRequest<Boolean>( key = PrefKeys.ShowDoubleTapMessage, defaultValue = true ) object FirstRun: PreferenceRequest<Int>( key = PrefKeys.FirstRun, defaultValue = 0 ) object FirstLoad: PreferenceRequest<Int>( key = PrefKeys.FirstLoad, defaultValue = 0 ) } enum class SortOrder(val stringValue: String) { DateDescending("date"), DateAscending("date-reversed"), TitleDescending("name-reversed"), TitleAscending("name"), } enum class FilenameFormat(val stringValue: String) { TitleOnly("text-only"), TitleAndTimestamp("text-timestamp"), TimestampAndTitle("timestamp-text"), }
apache-2.0
c3667bd5d2dccea5175856bb14d9dfc2
29.576577
79
0.704391
4.826458
false
false
false
false
Heiner1/AndroidAPS
danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketReviewGetPumpDecRatioTest.kt
1
899
package info.nightscout.androidaps.danars.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danars.DanaRSTestBase import org.junit.Assert import org.junit.Test class DanaRsPacketReviewGetPumpDecRatioTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { if (it is DanaRSPacketReviewGetPumpDecRatio) { it.aapsLogger = aapsLogger it.danaPump = danaPump } } } @Test fun runTest() { val packet = DanaRSPacketReviewGetPumpDecRatio(packetInjector) val array = ByteArray(100) putByteToArray(array, 0, 4.toByte()) packet.handleMessage(array) Assert.assertEquals(20, danaPump.decRatio) Assert.assertEquals("REVIEW__GET_PUMP_DEC_RATIO", packet.friendlyName) } }
agpl-3.0
47b9ff41e2c0e293a487aed208fae8a3
30.034483
78
0.696329
4.781915
false
true
false
false
cyclestreets/android
libraries/cyclestreets-view/src/main/java/net/cyclestreets/views/overlay/RotateMapOverlay.kt
1
5996
package net.cyclestreets.views.overlay import android.content.Context import android.content.SharedPreferences import android.graphics.Canvas import android.graphics.drawable.Drawable import android.hardware.GeomagneticField import android.location.Location import android.location.LocationManager import android.util.Log import android.view.LayoutInflater import android.view.Surface import android.view.WindowManager import androidx.core.content.res.ResourcesCompat import com.google.android.material.floatingactionbutton.FloatingActionButton import net.cyclestreets.util.Logging import net.cyclestreets.view.R import net.cyclestreets.views.CycleMapView import org.osmdroid.views.MapView import org.osmdroid.views.overlay.Overlay import org.osmdroid.views.overlay.compass.IOrientationConsumer import org.osmdroid.views.overlay.compass.IOrientationProvider import org.osmdroid.views.overlay.compass.InternalCompassOrientationProvider import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider import org.osmdroid.views.overlay.mylocation.IMyLocationConsumer import org.osmdroid.views.overlay.mylocation.IMyLocationProvider class RotateMapOverlay(private val mapView: CycleMapView) : Overlay(), PauseResumeListener, IMyLocationConsumer, IOrientationConsumer { private val rotateButton: FloatingActionButton private val onIcon: Drawable private val offIcon: Drawable private val locationProvider: IMyLocationProvider private val compassProvider: IOrientationProvider private var rotate = false private var gpsspeed = 0f private var lat = 0f private var lon = 0f private var alt = 0f private var timeOfFix: Long = 0 private var deviceOrientation = 0 init { val context = mapView.context onIcon = ResourcesCompat.getDrawable(context.resources, R.drawable.compass, null)!! offIcon = ResourcesCompat.getDrawable(context.resources, R.drawable.compass_off, null)!! val rotateButtonView = LayoutInflater.from(context).inflate(R.layout.compassbutton, null) rotateButton = rotateButtonView.findViewById(R.id.compass_button) rotateButton.setOnClickListener { setRotation(!rotate) } mapView.addView(rotateButtonView) locationProvider = UseEverythingLocationProvider(context) compassProvider = InternalCompassOrientationProvider(context) } private fun setRotation(state: Boolean) { Log.d(TAG, "Setting map rotation to $state") rotateButton.setImageDrawable(if (state) onIcon else offIcon) if (state) startRotate() else endRotate() rotate = state } private fun startRotate() { locationProvider.startLocationProvider(this) compassProvider.startOrientationProvider(this) } private fun endRotate() { locationProvider.stopLocationProvider() compassProvider.stopOrientationProvider() resetMapOrientation() rotateButton.rotation = 0f } override fun onLocationChanged(location: Location?, source: IMyLocationProvider?) { if (location == null) return gpsspeed = location.speed lat = location.latitude.toFloat() lon = location.longitude.toFloat() alt = location.altitude.toFloat() timeOfFix = location.time if (gpsspeed > onTheMoveThreshold) setMapOrientation(location.bearing) } override fun onOrientationChanged(orientationToMagneticNorth: Float, source: IOrientationProvider?) { if (gpsspeed > onTheMoveThreshold) return val gf = GeomagneticField(lat, lon, alt, timeOfFix) var trueNorth = orientationToMagneticNorth + gf.declination synchronized(trueNorth) { if (trueNorth > 360) trueNorth -= 360 setMapOrientation(trueNorth) } } private fun setMapOrientation(orientation: Float) { var mapOrientation = 360 - orientation - deviceOrientation if (mapOrientation < 0) mapOrientation += 360 if (mapOrientation > 360) mapOrientation -= 360 //help smooth everything out mapOrientation = ((mapOrientation / 5).toInt()) * 5f mapView.mapView().apply { setMapCenterOffset(0, height / 4) setMapOrientation(mapOrientation) } rotateButton.rotation = mapOrientation } private fun resetMapOrientation() { mapView.mapView().apply { setMapCenterOffset(0, 0) setMapOrientation(0f) } } private fun captureDeviceOrientation() { val rotation = (mapView.context.getSystemService( Context.WINDOW_SERVICE) as WindowManager).defaultDisplay.rotation deviceOrientation = when (rotation) { Surface.ROTATION_0 -> 0 Surface.ROTATION_90 -> 90 Surface.ROTATION_180 -> 180 else -> 270 } } override fun draw(c: Canvas, osmv: MapView, shadow: Boolean) {} ///////////////////////////////////////// override fun onResume(prefs: SharedPreferences) { setRotation(prefs.getBoolean(ROTATE_PREF, false)) captureDeviceOrientation() } override fun onPause(prefs: SharedPreferences.Editor) { endRotate() prefs.putBoolean(ROTATE_PREF, rotate) } companion object { private val TAG = Logging.getTag(RotateMapOverlay::class.java) private const val ROTATE_PREF = "rotateMap" private const val onTheMoveThreshold = 1 // if speed is below this, prefer the compass for orientation // once we're move, prefer gps } private class UseEverythingLocationProvider(context: Context) : GpsMyLocationProvider(context) { init { val locMan = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager for (source in locMan.getProviders(true)) addLocationSource(source) } } }
gpl-3.0
15605daf6efbd3bd7bb640139a6c652f
34.276471
105
0.695297
4.95128
false
false
false
false
PolymerLabs/arcs
javatests/arcs/core/host/ParticleIdentifierTest.kt
1
2528
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.host import arcs.core.host.api.HandleHolder import arcs.sdk.Particle import com.google.common.truth.Truth.assertThat import kotlin.test.assertFailsWith import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class ParticleIdentifierTest { @Test fun from_emptyString_throws() { val e = assertFailsWith<IllegalArgumentException> { ParticleIdentifier.from("") } assertThat(e).hasMessageThat().contains("Canonical variant of \"\" is blank") } @Test fun from_blankString_throws() { val e = assertFailsWith<IllegalArgumentException> { ParticleIdentifier.from(" \t") } assertThat(e).hasMessageThat().contains("Canonical variant of \" \t\" is blank") } @Test fun from_allSlashes_throws() { val e = assertFailsWith<IllegalArgumentException> { ParticleIdentifier.from("////////") } assertThat(e).hasMessageThat().contains("Canonical variant of \"////////\" is blank") } @Test fun from_almostAllSlashes() { val pid = ParticleIdentifier.from("///a/////") assertThat(pid.id).isEqualTo("a") } @Test fun from_simple() { val pid = ParticleIdentifier.from("ThisIsMe") assertThat(pid.id).isEqualTo("ThisIsMe") } @Test fun from_bazelPath() { val pid = ParticleIdentifier.from("//java/arcs/core/host/ParticleIdentifier") assertThat(pid.id).isEqualTo("java.arcs.core.host.ParticleIdentifier") } @Test fun kclassToParticleIdentifier() { val pid = MyParticleImplementation::class.toParticleIdentifier() assertThat(pid.id) .isEqualTo("arcs.core.host.ParticleIdentifierTest.MyParticleImplementation") } @Test fun anonymousKClassToParticleIdentifier() { val pid = ( object : Particle { override val handles: HandleHolder get() = throw UnsupportedOperationException() } )::class.toParticleIdentifier() assertThat(pid.id) .isEqualTo("arcs.core.host.ParticleIdentifierTest.anonymousKClassToParticleIdentifier.pid.1") } private class MyParticleImplementation : Particle { override val handles: HandleHolder get() = throw UnsupportedOperationException() } }
bsd-3-clause
37653e44fbad7ac63f18d305d829ad4a
27.727273
99
0.701741
4.234506
false
true
false
false
SourceUtils/hl2-toolkit
src/main/kotlin/com/timepath/hl2/io/image/VTF.kt
1
7941
package com.timepath.hl2.io.image import com.timepath.EnumFlags import com.timepath.Logger import com.timepath.StringUtils import com.timepath.io.utils.ViewableData import java.awt.Graphics2D import java.awt.Image import java.awt.image.BufferedImage import java.io.FileInputStream import java.io.IOException import java.io.InputStream import java.nio.BufferUnderflowException import java.nio.ByteBuffer import java.nio.ByteOrder import java.util.logging.Level import javax.swing.ImageIcon /** * TODO: .360.vtf files seem to be a slightly different format... and LZMA compressed. */ public class VTF : ViewableData { private var buf: ByteBuffer? = null public var bumpScale: Float = 0f private set public var depth: Int = 0 private set public var flags: Int = 0 private set public var format: ImageFormat? = null private set public var frameCount: Int = 0 private set /** * Zero indexed */ public var frameFirst: Int = 0 private set public var headerSize: Int = 0 private set public var height: Int = 0 private set public var mipCount: Int = 0 private set public var reflectivity: FloatArray? = null private set public var thumbFormat: ImageFormat? = null private set public var thumbHeight: Int = 0 private set private var thumbImage: Image? = null public var thumbWidth: Int = 0 private set public var version: IntArray? = null private set public var width: Int = 0 private set throws(IOException::class) fun loadFromStream(`is`: InputStream): Boolean { val magic = `is`.read() or (`is`.read() shl 8) or (`is`.read() shl 16) val type = `is`.read() if (magic != HEADER) { LOG.log(Level.FINE, { "Invalid VTF file: ${magic}" }) return false } val array = ByteArray(4 + `is`.available()) `is`.read(array, 4, array.size() - 4) buf = ByteBuffer.wrap(array) buf!!.order(ByteOrder.LITTLE_ENDIAN) buf!!.position(4) version = intArrayOf(buf!!.getInt(), buf!!.getInt()) headerSize = buf!!.getInt() if (type == 'X'.toInt()) { flags = buf!!.getInt() } width = buf!!.getShort().toInt() height = buf!!.getShort().toInt() if (type == 'X'.toInt()) { depth = buf!!.getShort().toInt() } if (type == 0) { flags = buf!!.getInt() } val enumSet = EnumFlags.decode(flags, javaClass<VTFFlags>()) frameCount = buf!!.getShort().toInt() if (type == 0) { frameFirst = buf!!.getShort().toInt() buf!!.get(ByteArray(4)) } else if (type == 'X'.toInt()) { val preloadDataSize = buf!!.getShort() val mipSkipCount = buf!!.get() val numResources = buf!!.get() } reflectivity = floatArrayOf(buf!!.getFloat().toFloat(), buf!!.getFloat().toFloat(), buf!!.getFloat().toFloat()) if (type == 0) { buf!!.get(ByteArray(4)) } bumpScale = buf!!.getFloat() format = ImageFormat.getEnumForIndex(buf!!.getInt()) if (type == 0) { mipCount = buf!!.get().toInt() thumbFormat = ImageFormat.getEnumForIndex(buf!!.getInt()) thumbWidth = buf!!.get().toInt() thumbHeight = buf!!.get().toInt() depth = buf!!.getShort().toInt() } else if (type == 'X'.toInt()) { val lowResImageSample = ByteArray(4) buf!!.get(lowResImageSample) val compressedSize = buf!!.getInt() } val debug = arrayOf(arrayOf("Width = ", width), arrayOf("Height = ", height), arrayOf("Frames = ", frameCount), arrayOf<Any?>("Flags = ", enumSet), arrayOf("Format = ", format), arrayOf("MipCount = ", mipCount)) LOG.fine({ StringUtils.fromDoubleArray(debug, "VTF:") }) return true } public fun getControls() { buf!!.position(headerSize - 8) // 8 bytes for CRC or other things. I have no idea what the data after the first 64 bytes up // until here are for val crcHead = buf!!.getInt() val crc = buf!!.getInt() if (crcHead == VTF_RSRC_TEXTURE_CRC) { LOG.info({ "CRC=0x${Integer.toHexString(crc).toUpperCase()}" }) } else { LOG.log(Level.WARNING, { "CRC header ${crcHead} is invalid" }) } } override fun getIcon() = ImageIcon(getThumbImage()) public fun getThumbImage(): Image { if (thumbImage == null) { buf!!.position(headerSize) val thumbData = ByteArray((Math.max(thumbWidth, 4) * Math.max(thumbHeight, 4)) / 2) // DXT1. Each 'block' is 4*4 pixels. 16 pixels become 8 // bytes buf!!.get(thumbData) thumbImage = DXTLoader.loadDXT1(thumbData, thumbWidth, thumbHeight) } return thumbImage!! } /** * Return the image for the given level of detail * * @param level From 0 to {@link #mipCount}-1 * @return * * @throws IOException */ throws(IOException::class) public fun getImage(level: Int): Image? = getImage(level, frameFirst) /** * Return the image for the given level of detail and frame * * @param level From 0 to {@link #mipCount}-1 * @param frame From 0 to {@link #frameCount}-1 */ public fun getImage(level: Int, frame: Int): Image? { if ((level < 0) || (level >= mipCount)) { return null } if ((frame < 0) || (frame >= frameCount)) { return null } var thumbLen = (Math.max(thumbWidth, 4) * Math.max(thumbHeight, 4)) / 2 // Thumbnail is a minimum of 4*4 if ((thumbWidth == 0) || (thumbHeight == 0)) { thumbLen = 0 } buf!!.position(headerSize + thumbLen) val sizesX = IntArray(mipCount) // smallest -> largest {1, 2, 4, 8, 16, 32, 64, 128} val sizesY = IntArray(mipCount) for (n in 0..mipCount - 1) { sizesX[mipCount - 1 - n] = Math.max(width.ushr(n), 1) sizesY[mipCount - 1 - n] = Math.max(height.ushr(n), 1) } var image: BufferedImage? = null for (i in 0..mipCount - 1) { val w = sizesX[i] val h = sizesY[i] LOG.log(Level.FINE, { "${w}, ${h}" }) val nBytes = format!!.getBytes(w, h) if (i == (mipCount - level - 1)) { val imageData = ByteArray(nBytes * frameCount) try { buf!![imageData] } catch (ignored: BufferUnderflowException) { LOG.log(Level.SEVERE, { "Underflow; ${nBytes}" }) } System.arraycopy(imageData, frame * nBytes, imageData, 0, nBytes) LOG.info({ "VTF format ${format}" }) image = BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB) val g = image.getGraphics() as Graphics2D g.drawImage(format!!.load(imageData, w, h), 0, 0, w, h, null) } else { buf!![ByteArray(nBytes * frameCount)] } } return image } companion object { /** * 'VTF\0' as little endian */ private val HEADER = 4609110 private val LOG = Logger() /** * 'CRC\2' as little endian */ private val VTF_RSRC_TEXTURE_CRC = 37966403 throws(IOException::class) public fun load(s: String): VTF? { return load(FileInputStream(s)) } throws(IOException::class) public fun load(`is`: InputStream): VTF? { val vtf = VTF() if (vtf.loadFromStream(`is`)) { return vtf } return null } } }
artistic-2.0
69d69796c52f4870db389418a133e0df
33.828947
219
0.548671
4.164132
false
false
false
false
blindpirate/gradle
.teamcity/src/main/kotlin/promotion/StartReleaseCycle.kt
1
2459
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package promotion import common.gradleWrapper import jetbrains.buildServer.configs.kotlin.v2019_2.ParameterDisplay import jetbrains.buildServer.configs.kotlin.v2019_2.RelativeId import vcsroots.gradlePromotionMaster object StartReleaseCycle : BasePromotionBuildType(vcsRootId = gradlePromotionMaster) { init { id("Promotion_StartReleaseCycle") name = "Start Release Cycle" description = "Promotes a successful build on master as the start of a new release cycle on the release branch" params { text("gitUserEmail", "", label = "Git user.email Configuration", description = "Enter the git 'user.email' configuration to commit change under", display = ParameterDisplay.PROMPT, allowEmpty = true) text("confirmationCode", "", label = "Confirmation Code", description = "Enter the value 'startCycle' (no quotes) to confirm the promotion", display = ParameterDisplay.PROMPT, allowEmpty = false) text("gitUserName", "", label = "Git user.name Configuration", description = "Enter the git 'user.name' configuration to commit change under", display = ParameterDisplay.PROMPT, allowEmpty = true) } steps { gradleWrapper { name = "Promote" tasks = "clean promoteStartReleaseCycle" useGradleWrapper = true gradleParams = """-PcommitId=%dep.${RelativeId("Check_Stage_ReadyforNightly_Trigger")}.build.vcs.number% -PconfirmationCode=%confirmationCode% "-PgitUserName=%gitUserName%" "-PgitUserEmail=%gitUserEmail%" """ param("org.jfrog.artifactory.selectedDeployableServer.defaultModuleVersionConfiguration", "GLOBAL") } } dependencies { snapshot(RelativeId("Check_Stage_ReadyforNightly_Trigger")) { } } } }
apache-2.0
5521b14e656f9bed5696e0315170a43a
47.215686
224
0.696218
4.756286
false
true
false
false
DuncanCasteleyn/DiscordModBot
src/main/kotlin/be/duncanc/discordmodbot/data/services/IAmRolesService.kt
1
4048
/* * 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.data.services import be.duncanc.discordmodbot.data.entities.IAmRolesCategory import be.duncanc.discordmodbot.data.repositories.jpa.IAmRolesRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.util.* @Transactional(readOnly = true) @Service class IAmRolesService @Autowired constructor( private val iAmRolesRepository: IAmRolesRepository ) { companion object { private val illegalArgumentException = IllegalArgumentException("The entity does not exist within the database.") } fun getAllCategoriesForGuild(guildId: Long): List<IAmRolesCategory> { return iAmRolesRepository.findByGuildId(guildId).toList() } fun getExistingCategoryNames(guildId: Long): Set<String> { val list: MutableSet<String> = HashSet() iAmRolesRepository.findByGuildId(guildId) .forEach { it.categoryName.let { categoryName -> list.add(categoryName) } } return list } @Transactional fun removeRole(guildId: Long, roleId: Long) { val byGuildId = iAmRolesRepository.findByGuildId(guildId) val effectedCategories = byGuildId.filter { it.roles.contains(roleId) }.toList() effectedCategories.forEach { it.roles.remove(roleId) } iAmRolesRepository.saveAll(effectedCategories) } @Transactional fun addNewCategory(guildId: Long, categoryName: String, allowedRoles: Int) { iAmRolesRepository.save(IAmRolesCategory(guildId, null, categoryName, allowedRoles)) } @Transactional fun removeCategory(guildId: Long, categoryId: Long) { iAmRolesRepository.deleteById(IAmRolesCategory.IAmRoleId(guildId, categoryId)) } @Transactional fun changeCategoryName(guildId: Long, categoryId: Long, newName: String) { val iAmRolesCategory = iAmRolesRepository.findById(IAmRolesCategory.IAmRoleId(guildId, categoryId)) .orElseThrow { illegalArgumentException } iAmRolesCategory.categoryName = newName iAmRolesRepository.save(iAmRolesCategory) } /** * @return returns true when added and false when the role was removed */ @Transactional fun addOrRemoveRole(guildId: Long, categoryId: Long, roleId: Long): Boolean { val iAmRolesCategory = iAmRolesRepository.findById(IAmRolesCategory.IAmRoleId(guildId, categoryId)) .orElseThrow { illegalArgumentException } return if (iAmRolesCategory.roles.contains(roleId)) { iAmRolesCategory.roles.remove(roleId) false } else { iAmRolesCategory.roles.add(roleId) true } } @Transactional fun changeAllowedRoles(guildId: Long, categoryId: Long, newAmount: Int) { val iAmRolesCategory = iAmRolesRepository.findById(IAmRolesCategory.IAmRoleId(guildId, categoryId)) .orElseThrow { illegalArgumentException } iAmRolesCategory.allowedRoles = newAmount iAmRolesRepository.save(iAmRolesCategory) } fun getRoleIds(guildId: Long, categoryId: Long): Set<Long> { val iAmRolesCategory = iAmRolesRepository.findById(IAmRolesCategory.IAmRoleId(guildId, categoryId)) .orElseThrow { illegalArgumentException } return HashSet(iAmRolesCategory.roles) } }
apache-2.0
7778d4e329aa1262ba700103c04cfa97
36.831776
107
0.720109
5.066333
false
false
false
false
yeoupooh/WoLa
src/main/kotlin/com/subakstudio/wifi/WiFiAccessPoint.kt
1
450
package com.subakstudio.wifi /** * Created by yeoupooh on 4/11/16. */ class WiFiAccessPoint(val ssid: String, val bssid: String, val rssi: Int, val channel: String, val ht: String, val cc: String, val securities: String) { override fun toString(): String { return String.format("${this.javaClass.simpleName}{ssid=[${ssid}] bssid=[${bssid}] rssi=[${rssi}] channel=[${channel}] ht=[${ht}] cc=[${cc}] securities=[${securities}]}") } }
gpl-3.0
1fb6b524656fecd0ab7c5e6fd70917f5
44.1
178
0.66
3.515625
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/base/util/src/org/jetbrains/kotlin/idea/base/util/caching/WorkspaceEntityChangeListener.kt
1
2530
// 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.base.util.caching import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleByEntity import com.intellij.workspaceModel.storage.EntityChange import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.VersionedStorageChange import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleEntity abstract class WorkspaceEntityChangeListener<Entity : WorkspaceEntity, Value : Any>( protected val project: Project, private val afterChangeApplied: Boolean = true ) : WorkspaceModelChangeListener { protected abstract val entityClass: Class<Entity> protected abstract fun map(storage: EntityStorage, entity: Entity): Value? protected abstract fun entitiesChanged(outdated: List<Value>) final override fun beforeChanged(event: VersionedStorageChange) { if (!afterChangeApplied) { handleEvent(event) } } final override fun changed(event: VersionedStorageChange) { if (afterChangeApplied) { handleEvent(event) } } private fun handleEvent(event: VersionedStorageChange) { val storageBefore = event.storageBefore val changes = event.getChanges(entityClass).ifEmpty { return } val outdatedEntities: List<Value> = changes.asSequence() .mapNotNull(EntityChange<Entity>::oldEntity) .mapNotNull { map(storageBefore, it) } .toList() if (outdatedEntities.isNotEmpty()) { entitiesChanged(outdatedEntities) } } } abstract class ModuleEntityChangeListener(project: Project) : WorkspaceEntityChangeListener<ModuleEntity, Module>(project) { override val entityClass: Class<ModuleEntity> get() = ModuleEntity::class.java override fun map(storage: EntityStorage, entity: ModuleEntity): Module? = storage.findModuleByEntity(entity) ?: // TODO: workaround to bypass bug with new modules not present in storageAfter WorkspaceModel.getInstance(project).entityStorage.current.findModuleByEntity(entity) }
apache-2.0
71f57ce430e27641b5e7d614c207abf2
41.183333
124
0.75415
5.238095
false
false
false
false
mdaniel/intellij-community
python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyDataclassTypeProvider.kt
4
12175
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.jetbrains.python.codeInsight.stdlib import com.intellij.openapi.util.Ref import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import com.jetbrains.python.PyNames import com.jetbrains.python.codeInsight.* import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyCallExpressionNavigator import com.jetbrains.python.psi.impl.stubs.PyDataclassFieldStubImpl import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.stubs.PyDataclassFieldStub import com.jetbrains.python.psi.types.* import one.util.streamex.StreamEx class PyDataclassTypeProvider : PyTypeProviderBase() { override fun getReferenceExpressionType(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyType? { return getDataclassesReplaceType(referenceExpression, context) } override fun getReferenceType(referenceTarget: PsiElement, context: TypeEvalContext, anchor: PsiElement?): Ref<PyType>? { val result = when { referenceTarget is PyClass && anchor is PyCallExpression -> getDataclassTypeForClass(referenceTarget, context) referenceTarget is PyParameter && referenceTarget.isSelf && anchor is PyCallExpression -> { PsiTreeUtil.getParentOfType(referenceTarget, PyFunction::class.java) ?.takeIf { it.modifier == PyFunction.Modifier.CLASSMETHOD } ?.let { it.containingClass?.let { getDataclassTypeForClass(it, context) } } } else -> null } return PyTypeUtil.notNullToRef(result) } override fun getParameterType(param: PyNamedParameter, func: PyFunction, context: TypeEvalContext): Ref<PyType>? { if (!param.isPositionalContainer && !param.isKeywordContainer && param.annotationValue == null && func.name == DUNDER_POST_INIT) { val cls = func.containingClass val name = param.name if (cls != null && name != null && parseStdDataclassParameters(cls, context)?.init == true) { cls .findClassAttribute(name, false, context) // `true` is not used here because ancestor should be a dataclass ?.let { return Ref.create(getTypeForParameter(cls, it, PyDataclassParameters.PredefinedType.STD, context)) } for (ancestor in cls.getAncestorClasses(context)) { if (parseStdDataclassParameters(ancestor, context) != null) { ancestor .findClassAttribute(name, false, context) ?.let { return Ref.create(getTypeForParameter(ancestor, it, PyDataclassParameters.PredefinedType.STD, context)) } } } } } return null } companion object { private fun getDataclassesReplaceType(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyCallableType? { val call = PyCallExpressionNavigator.getPyCallExpressionByCallee(referenceExpression) ?: return null val callee = call.callee as? PyReferenceExpression ?: return null val resolveContext = PyResolveContext.defaultContext(context) val resolvedCallee = PyUtil.multiResolveTopPriority(callee.getReference(resolveContext)).singleOrNull() return if (resolvedCallee is PyCallable) getDataclassesReplaceType(resolvedCallee, call, context) else null } private fun getDataclassesReplaceType(resolvedCallee: PyCallable, call: PyCallExpression, context: TypeEvalContext): PyCallableType? { val instanceName = when (resolvedCallee.qualifiedName) { "dataclasses.replace" -> "obj" "attr.assoc", "attr.evolve" -> "inst" else -> return null } val obj = call.getArgument(0, instanceName, PyTypedElement::class.java) ?: return null val objType = context.getType(obj) as? PyClassType ?: return null if (objType.isDefinition) return null val dataclassType = getDataclassTypeForClass(objType.pyClass, context) ?: return null val dataclassParameters = dataclassType.getParameters(context) ?: return null val parameters = mutableListOf<PyCallableParameter>() val elementGenerator = PyElementGenerator.getInstance(resolvedCallee.project) parameters.add(PyCallableParameterImpl.nonPsi(instanceName, objType)) parameters.add(PyCallableParameterImpl.psi(elementGenerator.createSingleStarParameter())) val ellipsis = elementGenerator.createEllipsis() dataclassParameters.mapTo(parameters) { PyCallableParameterImpl.nonPsi(it.name, it.getType(context), ellipsis) } return PyCallableTypeImpl(parameters, dataclassType.getReturnType(context)) } private fun getDataclassTypeForClass(cls: PyClass, context: TypeEvalContext): PyCallableType? { val clsType = (context.getType(cls) as? PyClassLikeType) ?: return null val resolveContext = PyResolveContext.defaultContext(context) val elementGenerator = PyElementGenerator.getInstance(cls.project) val ellipsis = elementGenerator.createEllipsis() val collected = linkedMapOf<String, PyCallableParameter>() var seenInit = false val keywordOnly = linkedSetOf<String>() var seenKeywordOnlyClass = false val seenNames = mutableSetOf<String>() for (currentType in StreamEx.of(clsType).append(cls.getAncestorTypes(context))) { if (currentType == null || !currentType.resolveMember(PyNames.INIT, null, AccessDirection.READ, resolveContext, false).isNullOrEmpty() || !currentType.resolveMember(PyNames.NEW, null, AccessDirection.READ, resolveContext, false).isNullOrEmpty() || currentType !is PyClassType) { if (seenInit) continue else break } val current = currentType.pyClass val parameters = parseDataclassParameters(current, context) if (parameters == null) { if (PyKnownDecoratorUtil.hasUnknownDecorator(current, context)) break else continue } else if (parameters.type.asPredefinedType == null) { break } seenInit = seenInit || parameters.init seenKeywordOnlyClass = seenKeywordOnlyClass || parameters.kwOnly if (seenInit) { current .classAttributes .asReversed() .asSequence() .filterNot { PyTypingTypeProvider.isClassVar(it, context) } .mapNotNull { fieldToParameter(current, it, parameters.type, ellipsis, context) } .filterNot { it.first in seenNames } .forEach { (name, kwOnly, parameter) -> // note: attributes are visited from inheritors to ancestors, in reversed order for every of them if ((seenKeywordOnlyClass || kwOnly) && name !in collected) { keywordOnly += name } if (parameter == null) { seenNames.add(name) } else if (parameters.type.asPredefinedType == PyDataclassParameters.PredefinedType.STD) { // std: attribute that overrides ancestor's attribute does not change the order but updates type collected[name] = collected.remove(name) ?: parameter } else if (!collected.containsKey(name)) { // attrs: attribute that overrides ancestor's attribute changes the order collected[name] = parameter } } } } return if (seenInit) PyCallableTypeImpl(buildParameters(elementGenerator, collected, keywordOnly), clsType.toInstance()) else null } private fun buildParameters(elementGenerator: PyElementGenerator, fields: Map<String, PyCallableParameter>, keywordOnly: Set<String>): List<PyCallableParameter> { if (keywordOnly.isEmpty()) return fields.values.reversed() val positionalOrKeyword = mutableListOf<PyCallableParameter>() val keyword = mutableListOf<PyCallableParameter>() for ((name, value) in fields.entries.reversed()) { if (name !in keywordOnly) { positionalOrKeyword += value } else { keyword += value } } val singleStarParameter = elementGenerator.createSingleStarParameter() return positionalOrKeyword + listOf(PyCallableParameterImpl.psi(singleStarParameter)) + keyword } private fun fieldToParameter(cls: PyClass, field: PyTargetExpression, dataclassType: PyDataclassParameters.Type, ellipsis: PyNoneLiteralExpression, context: TypeEvalContext): Triple<String, Boolean, PyCallableParameter?>? { val fieldName = field.name ?: return null val stub = field.stub val fieldStub = if (stub == null) PyDataclassFieldStubImpl.create(field) else stub.getCustomStub(PyDataclassFieldStub::class.java) if (fieldStub != null && !fieldStub.initValue()) return Triple(fieldName, false, null) if (fieldStub == null && field.annotationValue == null) return null // skip fields that are not annotated val parameterName = fieldName.let { if (dataclassType.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS && PyUtil.getInitialUnderscores(it) == 1) { it.substring(1) } else it } val parameter = PyCallableParameterImpl.nonPsi( parameterName, getTypeForParameter(cls, field, dataclassType, context), getDefaultValueForParameter(cls, field, fieldStub, dataclassType, ellipsis, context) ) return Triple(parameterName, fieldStub?.kwOnly() == true, parameter) } private fun getTypeForParameter(cls: PyClass, field: PyTargetExpression, dataclassType: PyDataclassParameters.Type, context: TypeEvalContext): PyType? { if (dataclassType.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS && context.maySwitchToAST(field)) { (field.findAssignedValue() as? PyCallExpression) ?.getKeywordArgument("type") ?.let { PyTypingTypeProvider.getType(it, context) } ?.apply { return get() } } val type = context.getType(field) if (type is PyCollectionType && type.classQName == DATACLASSES_INITVAR_TYPE) { return type.elementTypes.firstOrNull() } if (type == null && dataclassType.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS) { methodDecoratedAsAttributeDefault(cls, field.name) ?.let { context.getReturnType(it) } ?.let { return PyUnionType.createWeakType(it) } } return type } private fun getDefaultValueForParameter(cls: PyClass, field: PyTargetExpression, fieldStub: PyDataclassFieldStub?, dataclassType: PyDataclassParameters.Type, ellipsis: PyNoneLiteralExpression, context: TypeEvalContext): PyExpression? { return if (fieldStub == null) { when { context.maySwitchToAST(field) -> field.findAssignedValue() field.hasAssignedValue() -> ellipsis else -> null } } else if (fieldStub.hasDefault() || fieldStub.hasDefaultFactory() || dataclassType.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS && methodDecoratedAsAttributeDefault(cls, field.name) != null) { ellipsis } else null } private fun methodDecoratedAsAttributeDefault(cls: PyClass, attributeName: String?): PyFunction? { if (attributeName == null) return null return cls.methods.firstOrNull { it.decoratorList?.findDecorator("$attributeName.default") != null } } } }
apache-2.0
56646f29b4c966ebcfff8256bde1676a
43.761029
140
0.664805
5.444991
false
false
false
false
brianwernick/AndroidMarkup
library/src/main/kotlin/com/devbrackets/android/androidmarkup/parser/markdown/MarkdownDocumentConverter.kt
1
4125
package com.devbrackets.android.androidmarkup.parser.markdown import com.devbrackets.android.androidmarkup.parser.core.MarkupElement import com.devbrackets.android.androidmarkup.parser.core.SpanType import org.commonmark.node.* /** * A Converter that will take the commonmark-java * node structure and convert it to a * [com.devbrackets.android.androidMarkup.parser.core.MarkupDocument] */ open class MarkdownDocumentConverter { open fun convert(node: Node) : MarkupElement { val converterVisitor = ConverterVisitor() node.accept(converterVisitor) return converterVisitor.rootElement } open class Builder { open fun build() : MarkdownDocumentConverter { return MarkdownDocumentConverter() } } open class ConverterVisitor : AbstractVisitor() { val rootElement = MarkupElement(null) var currentElement = rootElement override fun visit(thematicBreak: ThematicBreak) { super.visit(thematicBreak) } override fun visit(blockQuote: BlockQuote) { super.visit(blockQuote) } override fun visit(code: Code) { super.visit(code) } override fun visit(fencedCodeBlock: FencedCodeBlock) { super.visit(fencedCodeBlock) } override fun visit(indentedCodeBlock: IndentedCodeBlock) { super.visit(indentedCodeBlock) } override fun visit(heading: Heading) { super.visit(heading) } override fun visit(htmlInline: HtmlInline) { super.visit(htmlInline) } override fun visit(htmlBlock: HtmlBlock) { super.visit(htmlBlock) } override fun visit(image: Image) { super.visit(image) } override fun visit(paragraph: Paragraph) { super.visit(paragraph) val element = MarkupElement(currentElement) element.spanType = SpanType.TEXT currentElement.addChild(element) element.text = "\n" } override fun visit(orderedList: OrderedList) { val parent = currentElement currentElement = MarkupElement(currentElement) currentElement.spanType = SpanType.ORDERED_LIST currentElement.parent?.addChild(currentElement) visitChildren(orderedList) currentElement = parent } override fun visit(bulletList: BulletList) { val parent = currentElement currentElement = MarkupElement(currentElement) currentElement.spanType = SpanType.UNORDERED_LIST currentElement.parent?.addChild(currentElement) visitChildren(bulletList) currentElement = parent } override fun visit(listItem: ListItem) { super.visit(listItem) } override fun visit(emphasis: Emphasis) { val parent = currentElement currentElement = MarkupElement(currentElement) currentElement.spanType = SpanType.ITALIC currentElement.parent?.addChild(currentElement) visitChildren(emphasis) currentElement = parent } override fun visit(strongEmphasis: StrongEmphasis) { val parent = currentElement currentElement = MarkupElement(currentElement) currentElement.spanType = SpanType.BOLD currentElement.parent?.addChild(currentElement) visitChildren(strongEmphasis) currentElement = parent } override fun visit(text: Text) { val element = MarkupElement(currentElement) element.spanType = SpanType.TEXT currentElement.addChild(element) element.text = text.literal.orEmpty() } override fun visit(hardLineBreak: HardLineBreak) { val element = MarkupElement(currentElement) element.spanType = SpanType.TEXT currentElement.addChild(element) element.text = "\n" } } }
apache-2.0
f59c19e39518431f861be0d3c605f940
27.455172
70
0.62497
5.434783
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/oyster/OysterPurse.kt
1
2334
/* * OysterPurse.kt * * Copyright 2019 Michael Farrell <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.oyster import au.id.micolous.metrodroid.card.classic.ClassicCard import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.transit.TransitBalance import au.id.micolous.metrodroid.transit.TransitCurrency import au.id.micolous.metrodroid.util.ImmutableByteArray @Parcelize class OysterPurse( val value: Int, private val sequence: Int, private val subsequence: Int ) : Comparable<OysterPurse>, TransitBalance { override val balance: TransitCurrency get() = TransitCurrency.GBP(value) internal constructor(record: ImmutableByteArray) : this( subsequence = record.getBitsFromBuffer(4, 4), sequence = record.byteArrayToInt(1, 1), value = record.getBitsFromBufferSignedLeBits(25, 15) ) override fun compareTo(other: OysterPurse): Int { val c = sequence.compareTo(other.sequence) return when { c != 0 -> c else -> subsequence.compareTo(other.subsequence) } } companion object { internal fun parse(a: ImmutableByteArray?, b: ImmutableByteArray?) : OysterPurse? { val purseA = a?.let { OysterPurse(it) } val purseB = b?.let { OysterPurse(it) } return when { purseA == null -> purseB purseB == null -> purseA else -> maxOf(purseA, purseB) } } internal fun parse(card: ClassicCard) : OysterPurse? { return parse(card[1, 1].data, card[1, 2].data) } } }
gpl-3.0
9127eded12051725f24af16ef76a6974
33.338235
91
0.66581
4.330241
false
false
false
false
Mystery00/JanYoShare
app/src/main/java/com/janyo/janyoshare/util/bitmap/RectangleBitmapCrop.kt
1
726
package com.janyo.janyoshare.util.bitmap import android.graphics.* /** * Created by mystery0. */ class RectangleBitmapCrop : BitmapCrop() { override fun crop(bitmap: Bitmap): Bitmap { val width = bitmap.width val height = bitmap.height val output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) val canvas = Canvas(output) val paint = Paint() val rectF = RectF(width * 20 / 192f, height * 20 / 192f, width * 172 / 192f, height * 172 / 192f) paint.isAntiAlias = true canvas.drawARGB(0, 0, 0, 0) canvas.drawRect(rectF, paint) paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)//设置图像重叠时的处理方式 canvas.drawBitmap(bitmap, 0f, 0f, paint) return output } }
gpl-3.0
747c9ec7429fc3fdd5348f6dfe632b46
26.038462
99
0.712251
3.147982
false
false
false
false
GunoH/intellij-community
platform/util/src/com/intellij/concurrency/threadContext.kt
5
3897
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("ThreadContext") @file:Experimental package com.intellij.concurrency import com.intellij.openapi.application.AccessToken import org.jetbrains.annotations.ApiStatus.Experimental import org.jetbrains.annotations.ApiStatus.Internal import org.jetbrains.annotations.VisibleForTesting import java.util.concurrent.Callable import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext private val tlCoroutineContext: ThreadLocal<CoroutineContext?> = ThreadLocal() @Internal @VisibleForTesting fun checkUninitializedThreadContext() { check(tlCoroutineContext.get() == null) { "Thread context was already set" } } /** * @return current thread context */ fun currentThreadContext(): CoroutineContext { return tlCoroutineContext.get() ?: EmptyCoroutineContext } /** * Resets the current thread context to initial value. * * @return handle to restore the previous thread context */ fun resetThreadContext(): AccessToken { return updateThreadContext { null } } /** * Replaces the current thread context with [coroutineContext]. * * @return handle to restore the previous thread context */ fun replaceThreadContext(coroutineContext: CoroutineContext): AccessToken { return updateThreadContext { coroutineContext } } /** * Updates the current thread context with [coroutineContext] as per [CoroutineContext.plus], * and runs the [action]. * * @return result of [action] invocation */ fun <X> withThreadContext(coroutineContext: CoroutineContext, action: () -> X): X { return withThreadContext(coroutineContext).use { action() } } /** * Updates the current thread context with [coroutineContext] as per [CoroutineContext.plus]. * * @return handle to restore the previous thread context */ fun withThreadContext(coroutineContext: CoroutineContext): AccessToken { return updateThreadContext { current -> if (current == null) { coroutineContext } else { current + coroutineContext } } } private fun updateThreadContext( update: (CoroutineContext?) -> CoroutineContext? ): AccessToken { val previousContext = tlCoroutineContext.get() val newContext = update(previousContext) tlCoroutineContext.set(newContext) return object : AccessToken() { override fun finish() { val currentContext = tlCoroutineContext.get() tlCoroutineContext.set(previousContext) check(currentContext === newContext) { "Context was not reset correctly" } } } } /** * Returns a `Runnable` instance, which saves [currentThreadContext] and, * when run, installs the saved context and runs original [runnable] within the installed context. * ``` * val executor = Executors.newSingleThreadExecutor() * val context = currentThreadContext() * executor.submit { * replaceThreadContext(context).use { * runnable.run() * } * } * // is roughly equivalent to * executor.submit(captureThreadContext(runnable)) * ``` * * Before installing the saved context, the returned `Runnable` asserts that there is no context already installed in the thread. * This check effectively forbids double capturing, e.g. `captureThreadContext(captureThreadContext(runnable))` will fail. * This method should be used with executors from [java.util.concurrent.Executors] or with [java.util.concurrent.CompletionStage] methods. * Do not use this method with executors returned from [com.intellij.util.concurrency.AppExecutorUtil], they already capture the context. */ fun captureThreadContext(runnable: Runnable): Runnable { return ContextRunnable(true, runnable) } /** * Same as [captureThreadContext] but for [Callable]. */ fun <V> captureThreadContext(callable: Callable<V>): Callable<V> { return ContextCallable(true, callable) }
apache-2.0
2236c07853996b3aaca94c9c87d007f8
29.445313
138
0.749038
4.633769
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/KotlinClearPackageCachesListener.kt
8
1123
// 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 import com.intellij.ide.plugins.DynamicPluginListener import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import org.jetbrains.kotlin.resolve.jvm.KotlinJavaPsiFacade class KotlinClearPackageCachesListener(private val project: Project) : DynamicPluginListener, ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent): Unit = clearPackageCaches() override fun beforePluginUnload(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean): Unit = clearPackageCaches() override fun pluginUnloaded(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean): Unit = clearPackageCaches() override fun pluginLoaded(pluginDescriptor: IdeaPluginDescriptor): Unit = clearPackageCaches() private fun clearPackageCaches(): Unit = KotlinJavaPsiFacade.getInstance(project).clearPackageCaches() }
apache-2.0
a210d36bd61611e9fd2782a5adc70080
58.105263
123
0.82992
5.322275
false
false
false
false
jk1/intellij-community
platform/script-debugger/debugger-ui/src/CallFrameView.kt
2
4162
/* * 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 org.jetbrains.debugger.frame import com.intellij.icons.AllIcons import com.intellij.ui.ColoredTextContainer import com.intellij.ui.SimpleTextAttributes import com.intellij.xdebugger.evaluation.XDebuggerEvaluator import com.intellij.xdebugger.frame.XCompositeNode import com.intellij.xdebugger.frame.XStackFrame import org.jetbrains.concurrency.Promise import org.jetbrains.debugger.* // isInLibraryContent call could be costly, so we compute it only once (our customizePresentation called on each repaint) class CallFrameView @JvmOverloads constructor(val callFrame: CallFrame, override val viewSupport: DebuggerViewSupport, val script: Script? = null, sourceInfo: SourceInfo? = null, isInLibraryContent: Boolean? = null, override val vm: Vm? = null) : XStackFrame(), VariableContext { private val sourceInfo = sourceInfo ?: viewSupport.getSourceInfo(script, callFrame) private val isInLibraryContent: Boolean = isInLibraryContent ?: (this.sourceInfo != null && viewSupport.isInLibraryContent(this.sourceInfo, script)) private var evaluator: XDebuggerEvaluator? = null override fun getEqualityObject(): Any = callFrame.equalityObject override fun computeChildren(node: XCompositeNode) { node.setAlreadySorted(true) createAndAddScopeList(node, callFrame.variableScopes, this, callFrame) } override val evaluateContext: EvaluateContext get() = callFrame.evaluateContext override fun watchableAsEvaluationExpression(): Boolean = true override val memberFilter: Promise<MemberFilter> get() = viewSupport.getMemberFilter(this) fun getMemberFilter(scope: Scope): Promise<MemberFilter> = createVariableContext(scope, this, callFrame).memberFilter override fun getEvaluator(): XDebuggerEvaluator? { if (evaluator == null) { evaluator = viewSupport.createFrameEvaluator(this) } return evaluator } override fun getSourcePosition(): SourceInfo? = sourceInfo override fun customizePresentation(component: ColoredTextContainer) { if (sourceInfo == null) { val scriptName = if (script == null) "unknown" else script.url.trimParameters().toDecodedForm() val line = callFrame.line component.append(if (line == -1) scriptName else "$scriptName:$line", SimpleTextAttributes.ERROR_ATTRIBUTES) return } val fileName = sourceInfo.file.name val line = sourceInfo.line + 1 val textAttributes = if (isInLibraryContent || callFrame.isFromAsyncStack) SimpleTextAttributes.GRAYED_ATTRIBUTES else SimpleTextAttributes.REGULAR_ATTRIBUTES val functionName = sourceInfo.functionName if (functionName == null || (functionName.isEmpty() && callFrame.hasOnlyGlobalScope)) { if (fileName.startsWith("index.")) { sourceInfo.file.parent?.let { component.append("${it.name}/", textAttributes) } } component.append("$fileName:$line", textAttributes) } else { if (functionName.isEmpty()) { component.append("anonymous", if (isInLibraryContent) SimpleTextAttributes.GRAYED_ITALIC_ATTRIBUTES else SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES) } else { component.append(functionName, textAttributes) } component.append("(), $fileName:$line", textAttributes) } component.setIcon(AllIcons.Debugger.StackFrame) } }
apache-2.0
b2bc6b7a881ee1bf905495d7a65072df
40.63
160
0.705911
5.183064
false
false
false
false
google/accompanist
sample/src/main/java/com/google/accompanist/sample/navigation/material/BottomSheetNavSample.kt
1
4101
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.accompanist.sample.navigation.material import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.google.accompanist.navigation.material.ExperimentalMaterialNavigationApi import com.google.accompanist.navigation.material.ModalBottomSheetLayout import com.google.accompanist.navigation.material.bottomSheet import com.google.accompanist.navigation.material.rememberBottomSheetNavigator import com.google.accompanist.sample.AccompanistSampleTheme import java.util.UUID class BottomSheetNavSample : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AccompanistSampleTheme { BottomSheetNavDemo() } } } } private object Destinations { const val Home = "HOME" const val Feed = "FEED" const val Sheet = "SHEET" } @OptIn(ExperimentalMaterialNavigationApi::class) @Composable fun BottomSheetNavDemo() { val bottomSheetNavigator = rememberBottomSheetNavigator() val navController = rememberNavController(bottomSheetNavigator) ModalBottomSheetLayout(bottomSheetNavigator) { NavHost(navController, Destinations.Home) { composable(Destinations.Home) { HomeScreen( showSheet = { navController.navigate(Destinations.Sheet + "?arg=From Home Screen") }, showFeed = { navController.navigate(Destinations.Feed) } ) } composable(Destinations.Feed) { Text("Feed!") } bottomSheet(Destinations.Sheet + "?arg={arg}") { backstackEntry -> val arg = backstackEntry.arguments?.getString("arg") ?: "Missing argument :(" BottomSheet( showFeed = { navController.navigate(Destinations.Feed) }, showAnotherSheet = { navController.navigate(Destinations.Sheet + "?arg=${UUID.randomUUID()}") }, arg = arg ) } } } } @Composable private fun HomeScreen(showSheet: () -> Unit, showFeed: () -> Unit) { Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally) { Text("Body") Button(onClick = showSheet) { Text("Show sheet!") } Button(onClick = showFeed) { Text("Navigate to Feed") } } } @Composable private fun BottomSheet(showFeed: () -> Unit, showAnotherSheet: () -> Unit, arg: String) { Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { Text("Sheet with arg: $arg") Button(onClick = showFeed) { Text("Click me to navigate!") } Button(onClick = showAnotherSheet) { Text("Click me to show another sheet!") } } }
apache-2.0
e206c6a1f50743e78bfb13276cfaebb8
35.292035
96
0.677152
4.976942
false
false
false
false
google/accompanist
swiperefresh/src/main/java/com/google/accompanist/swiperefresh/SwipeRefresh.kt
1
12011
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("DEPRECATION") package com.google.accompanist.swiperefresh import androidx.compose.animation.core.Animatable import androidx.compose.foundation.MutatePriority import androidx.compose.foundation.MutatorMutex import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.nestedscroll.NestedScrollConnection import androidx.compose.ui.input.nestedscroll.NestedScrollSource import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Velocity import androidx.compose.ui.unit.dp import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import kotlin.math.absoluteValue import kotlin.math.roundToInt private const val DragMultiplier = 0.5f /** * Creates a [SwipeRefreshState] that is remembered across compositions. * * Changes to [isRefreshing] will result in the [SwipeRefreshState] being updated. * * @param isRefreshing the value for [SwipeRefreshState.isRefreshing] */ @Deprecated( """ accompanist/swiperefresh is deprecated. The androidx.compose equivalent of rememberSwipeRefreshState() is rememberPullRefreshState(). For more migration information, please visit https://google.github.io/accompanist/swiperefresh/#migration """, replaceWith = ReplaceWith( "rememberPullRefreshState(isRefreshing, onRefresh = )", "androidx.compose.material.pullrefresh.rememberPullRefreshState" ) ) @Composable fun rememberSwipeRefreshState( isRefreshing: Boolean ): SwipeRefreshState { return remember { SwipeRefreshState( isRefreshing = isRefreshing ) }.apply { this.isRefreshing = isRefreshing } } /** * A state object that can be hoisted to control and observe changes for [SwipeRefresh]. * * In most cases, this will be created via [rememberSwipeRefreshState]. * * @param isRefreshing the initial value for [SwipeRefreshState.isRefreshing] */ @Deprecated( """ accompanist/swiperefresh is deprecated. The androidx.compose equivalent of SwipeRefreshState is PullRefreshState. For more migration information, please visit https://google.github.io/accompanist/swiperefresh/#migration """ ) @Stable class SwipeRefreshState( isRefreshing: Boolean, ) { private val _indicatorOffset = Animatable(0f) private val mutatorMutex = MutatorMutex() /** * Whether this [SwipeRefreshState] is currently refreshing or not. */ var isRefreshing: Boolean by mutableStateOf(isRefreshing) /** * Whether a swipe/drag is currently in progress. */ var isSwipeInProgress: Boolean by mutableStateOf(false) internal set /** * The current offset for the indicator, in pixels. */ val indicatorOffset: Float get() = _indicatorOffset.value internal suspend fun animateOffsetTo(offset: Float) { mutatorMutex.mutate { _indicatorOffset.animateTo(offset) } } /** * Dispatch scroll delta in pixels from touch events. */ internal suspend fun dispatchScrollDelta(delta: Float) { mutatorMutex.mutate(MutatePriority.UserInput) { _indicatorOffset.snapTo(_indicatorOffset.value + delta) } } } private class SwipeRefreshNestedScrollConnection( private val state: SwipeRefreshState, private val coroutineScope: CoroutineScope, private val onRefresh: () -> Unit, ) : NestedScrollConnection { var enabled: Boolean = false var refreshTrigger: Float = 0f override fun onPreScroll( available: Offset, source: NestedScrollSource ): Offset = when { // If swiping isn't enabled, return zero !enabled -> Offset.Zero // If we're refreshing, return zero state.isRefreshing -> Offset.Zero // If the user is swiping up, handle it source == NestedScrollSource.Drag && available.y < 0 -> onScroll(available) else -> Offset.Zero } override fun onPostScroll( consumed: Offset, available: Offset, source: NestedScrollSource ): Offset = when { // If swiping isn't enabled, return zero !enabled -> Offset.Zero // If we're refreshing, return zero state.isRefreshing -> Offset.Zero // If the user is swiping down and there's y remaining, handle it source == NestedScrollSource.Drag && available.y > 0 -> onScroll(available) else -> Offset.Zero } private fun onScroll(available: Offset): Offset { if (available.y > 0) { state.isSwipeInProgress = true } else if (state.indicatorOffset.roundToInt() == 0) { state.isSwipeInProgress = false } val newOffset = (available.y * DragMultiplier + state.indicatorOffset).coerceAtLeast(0f) val dragConsumed = newOffset - state.indicatorOffset return if (dragConsumed.absoluteValue >= 0.5f) { coroutineScope.launch { state.dispatchScrollDelta(dragConsumed) } // Return the consumed Y Offset(x = 0f, y = dragConsumed / DragMultiplier) } else { Offset.Zero } } override suspend fun onPreFling(available: Velocity): Velocity { // If we're dragging, not currently refreshing and scrolled // past the trigger point, refresh! if (!state.isRefreshing && state.indicatorOffset >= refreshTrigger) { onRefresh() } // Reset the drag in progress state state.isSwipeInProgress = false // Don't consume any velocity, to allow the scrolling layout to fling return Velocity.Zero } } /** * A layout which implements the swipe-to-refresh pattern, allowing the user to refresh content via * a vertical swipe gesture. * * This layout requires its content to be scrollable so that it receives vertical swipe events. * The scrollable content does not need to be a direct descendant though. Layouts such as * [androidx.compose.foundation.lazy.LazyColumn] are automatically scrollable, but others such as * [androidx.compose.foundation.layout.Column] require you to provide the * [androidx.compose.foundation.verticalScroll] modifier to that content. * * Apps should provide a [onRefresh] block to be notified each time a swipe to refresh gesture * is completed. That block is responsible for updating the [state] as appropriately, * typically by setting [SwipeRefreshState.isRefreshing] to `true` once a 'refresh' has been * started. Once a refresh has completed, the app should then set * [SwipeRefreshState.isRefreshing] to `false`. * * If an app wishes to show the progress animation outside of a swipe gesture, it can * set [SwipeRefreshState.isRefreshing] as required. * * This layout does not clip any of it's contents, including the indicator. If clipping * is required, apps can provide the [androidx.compose.ui.draw.clipToBounds] modifier. * * @sample com.google.accompanist.sample.swiperefresh.SwipeRefreshSample * * @param state the state object to be used to control or observe the [SwipeRefresh] state. * @param onRefresh Lambda which is invoked when a swipe to refresh gesture is completed. * @param modifier the modifier to apply to this layout. * @param swipeEnabled Whether the the layout should react to swipe gestures or not. * @param refreshTriggerDistance The minimum swipe distance which would trigger a refresh. * @param indicatorAlignment The alignment of the indicator. Defaults to [Alignment.TopCenter]. * @param indicatorPadding Content padding for the indicator, to inset the indicator in if required. * @param indicator the indicator that represents the current state. By default this * will use a [SwipeRefreshIndicator]. * @param clipIndicatorToPadding Whether to clip the indicator to [indicatorPadding]. If false is * provided the indicator will be clipped to the [content] bounds. Defaults to true. * @param content The content containing a scroll composable. */ @Deprecated( """ accompanist/swiperefresh is deprecated. The androidx.compose equivalent of SwipeRefresh is Modifier.pullRefresh(). This is often migrated as: Box(modifier = Modifier.pullRefresh(refreshState)) { ... PullRefreshIndicator(...) } For more migration information, please visit https://google.github.io/accompanist/swiperefresh/#migration """ ) @Composable fun SwipeRefresh( state: SwipeRefreshState, onRefresh: () -> Unit, modifier: Modifier = Modifier, swipeEnabled: Boolean = true, refreshTriggerDistance: Dp = 80.dp, indicatorAlignment: Alignment = Alignment.TopCenter, indicatorPadding: PaddingValues = PaddingValues(0.dp), indicator: @Composable (state: SwipeRefreshState, refreshTrigger: Dp) -> Unit = { s, trigger -> SwipeRefreshIndicator(s, trigger) }, clipIndicatorToPadding: Boolean = true, content: @Composable () -> Unit, ) { val coroutineScope = rememberCoroutineScope() val updatedOnRefresh = rememberUpdatedState(onRefresh) // Our LaunchedEffect, which animates the indicator to its resting position LaunchedEffect(state.isSwipeInProgress) { if (!state.isSwipeInProgress) { // If there's not a swipe in progress, rest the indicator at 0f state.animateOffsetTo(0f) } } val refreshTriggerPx = with(LocalDensity.current) { refreshTriggerDistance.toPx() } // Our nested scroll connection, which updates our state. val nestedScrollConnection = remember(state, coroutineScope) { SwipeRefreshNestedScrollConnection(state, coroutineScope) { // On refresh, re-dispatch to the update onRefresh block updatedOnRefresh.value.invoke() } }.apply { this.enabled = swipeEnabled this.refreshTrigger = refreshTriggerPx } Box(modifier.nestedScroll(connection = nestedScrollConnection)) { content() Box( Modifier // If we're not clipping to the padding, we use clipToBounds() before the padding() // modifier. .let { if (!clipIndicatorToPadding) it.clipToBounds() else it } .padding(indicatorPadding) .matchParentSize() // Else, if we're are clipping to the padding, we use clipToBounds() after // the padding() modifier. .let { if (clipIndicatorToPadding) it.clipToBounds() else it } ) { Box(Modifier.align(indicatorAlignment)) { indicator(state, refreshTriggerDistance) } } } }
apache-2.0
2cb70524e3522459f53ebf61fc1e654a
36.88959
110
0.710432
4.874594
false
false
false
false
evanchooly/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/Args.kt
1
3395
package com.beust.kobalt import com.beust.jcommander.Parameter class Args { @Parameter var targets: List<String> = arrayListOf() @Parameter(names = arrayOf("-bf", "--buildFile"), description = "The build file") var buildFile: String? = null @Parameter(names = arrayOf("--checkVersions"), description = "Check if there are any newer versions of the " + "dependencies") var checkVersions = false @Parameter(names = arrayOf("--client")) var client: Boolean = false @Parameter(names = arrayOf("--dev"), description = "Turn on dev mode, resulting in a more verbose log output") var dev: Boolean = false @Parameter(names = arrayOf("--download"), description = "Force a download from the downloadUrl in the wrapper") var download: Boolean = false @Parameter(names = arrayOf("--dryRun"), description = "Display all the tasks that will get run without " + "actually running them") var dryRun: Boolean = false @Parameter(names = arrayOf("--force"), description = "Force a new server to be launched even if another one" + " is already running") var force: Boolean = false @Parameter(names = arrayOf("--gc"), description = "Delete old files") var gc: Boolean = false @Parameter(names = arrayOf("--help", "--usage"), description = "Display the help") var usage: Boolean = false @Parameter(names = arrayOf("-i", "--init"), description = "Invoke the templates named, separated by a comma") var templates: String? = null @Parameter(names = arrayOf("--listTemplates"), description = "List the available templates") var listTemplates: Boolean = false @Parameter(names = arrayOf("--log"), description = "Define the log level (1-3)") var log: Int = 1 @Parameter(names = arrayOf("--forceIncremental"), description = "Force the build to be incremental even if the build file was modified") var forceIncremental: Boolean = false @Parameter(names = arrayOf("--noIncremental"), description = "Turn off incremental builds") var noIncremental: Boolean = false @Parameter(names = arrayOf("--plugins"), description = "Comma-separated list of plug-in Maven id's") var pluginIds: String? = null @Parameter(names = arrayOf("--pluginJarFiles"), description = "Comma-separated list of plug-in jar files") var pluginJarFiles: String? = null @Parameter(names = arrayOf("--port"), description = "Port, if --server was specified") var port: Int? = null @Parameter(names = arrayOf("--profiles"), description = "Comma-separated list of profiles to run") var profiles: String? = null @Parameter(names = arrayOf("--resolve"), description = "Resolve the given comma-separated dependencies and display their dependency tree") var dependencies: String? = null @Parameter(names = arrayOf("--projectInfo"), description = "Display information about the current projects") var projectInfo: Boolean = false @Parameter(names = arrayOf("--server"), description = "Run in server mode") var serverMode: Boolean = false @Parameter(names = arrayOf("--tasks"), description = "Display the tasks available for this build") var tasks: Boolean = false @Parameter(names = arrayOf("--update"), description = "Update to the latest version of Kobalt") var update: Boolean = false }
apache-2.0
3230a441a3c04e9edbb95bbf25deff97
39.903614
115
0.674521
4.637978
false
false
false
false
AoDevBlue/AnimeUltimeTv
app/src/main/java/blue/aodev/animeultimetv/data/converters/EpisodeReleaseHistoryAdapter.kt
1
1626
package blue.aodev.animeultimetv.data.converters import blue.aodev.animeultimetv.data.model.EpisodeReleaseId import okhttp3.ResponseBody import org.jsoup.Jsoup import org.jsoup.nodes.Element import retrofit2.Converter import retrofit2.Retrofit import java.lang.reflect.ParameterizedType import java.lang.reflect.Type internal class EpisodeReleaseHistoryAdapter : Converter<ResponseBody, List<EpisodeReleaseId>> { companion object { val FACTORY: Converter.Factory = object : Converter.Factory() { override fun responseBodyConverter(type: Type, annotations: Array<Annotation>, retrofit: Retrofit): Converter<ResponseBody, *>? { if (type is ParameterizedType && getRawType(type) === List::class.java && getParameterUpperBound(0, type) === EpisodeReleaseId::class.java) { return EpisodeReleaseHistoryAdapter() } return null } } } override fun convert(responseBody: ResponseBody): List<EpisodeReleaseId> { return Jsoup.parse(responseBody.string()) .select(".history tr") .map { convertEpisodeElement(it) } .filterNotNull() } private fun convertEpisodeElement(episodeElement: Element): EpisodeReleaseId? { val tds = episodeElement.select("td") if (tds.size < 2) return null val id = tds[0].child(0).attr("href").split("/")[1].toInt() val numbers = tds[1].text() return EpisodeReleaseId(id, numbers) } }
mit
eb8e5bb847dddf8cd14ca2611bedf9fd
35.977273
97
0.627921
4.972477
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/nbt/lang/colors/NbttSyntaxHighlighter.kt
1
3104
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.lang.colors import com.demonwav.mcdev.nbt.lang.NbttLexerAdapter import com.demonwav.mcdev.nbt.lang.gen.psi.NbttTypes import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.fileTypes.SyntaxHighlighterBase import com.intellij.psi.tree.IElementType class NbttSyntaxHighlighter : SyntaxHighlighterBase() { override fun getHighlightingLexer() = NbttLexerAdapter() override fun getTokenHighlights(tokenType: IElementType): Array<TextAttributesKey> { return when (tokenType) { NbttTypes.BYTES, NbttTypes.INTS, NbttTypes.LONGS -> KEYWORD_KEYS NbttTypes.STRING_LITERAL -> STRING_KEYS NbttTypes.UNQUOTED_STRING_LITERAL -> UNQUOTED_STRING_KEYS NbttTypes.BYTE_LITERAL -> BYTE_KEYS NbttTypes.SHORT_LITERAL -> SHORT_KEYS NbttTypes.INT_LITERAL -> INT_KEYS NbttTypes.LONG_LITERAL -> LONG_KEYS NbttTypes.FLOAT_LITERAL -> FLOAT_KEYS NbttTypes.DOUBLE_LITERAL -> DOUBLE_KEYS else -> EMPTY_KEYS } } companion object { val KEYWORD = TextAttributesKey.createTextAttributesKey("NBTT_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD) val STRING = TextAttributesKey.createTextAttributesKey("NBTT_STRING", DefaultLanguageHighlighterColors.STRING) val UNQUOTED_STRING = TextAttributesKey.createTextAttributesKey("NBTT_UNQUOTED_STRING", STRING) val STRING_NAME = TextAttributesKey.createTextAttributesKey("NBTT_STRING_NAME", STRING) val UNQUOTED_STRING_NAME = TextAttributesKey.createTextAttributesKey("NBTT_UNQUOTED_STRING_NAME", STRING_NAME) val BYTE = TextAttributesKey.createTextAttributesKey("NBTT_BYTE", DefaultLanguageHighlighterColors.NUMBER) val SHORT = TextAttributesKey.createTextAttributesKey("NBTT_SHORT", DefaultLanguageHighlighterColors.NUMBER) val INT = TextAttributesKey.createTextAttributesKey("NBTT_INT", DefaultLanguageHighlighterColors.NUMBER) val LONG = TextAttributesKey.createTextAttributesKey("NBTT_LONG", DefaultLanguageHighlighterColors.NUMBER) val FLOAT = TextAttributesKey.createTextAttributesKey("NBTT_FLOAT", DefaultLanguageHighlighterColors.NUMBER) val DOUBLE = TextAttributesKey.createTextAttributesKey("NBTT_DOUBLE", DefaultLanguageHighlighterColors.NUMBER) val MATERIAL = TextAttributesKey.createTextAttributesKey("NBTT_MATERIAL", STRING) val KEYWORD_KEYS = arrayOf(KEYWORD) val STRING_KEYS = arrayOf(STRING) val UNQUOTED_STRING_KEYS = arrayOf(UNQUOTED_STRING) val BYTE_KEYS = arrayOf(BYTE) val SHORT_KEYS = arrayOf(SHORT) val INT_KEYS = arrayOf(INT) val LONG_KEYS = arrayOf(LONG) val FLOAT_KEYS = arrayOf(FLOAT) val DOUBLE_KEYS = arrayOf(DOUBLE) val EMPTY_KEYS = emptyArray<TextAttributesKey>() } }
mit
4fbd5c7677aaeadef51a96b9eadb9c05
47.5
121
0.733892
5.243243
false
false
false
false
dhis2/dhis2-android-sdk
core/src/test/java/org/hisp/dhis/android/core/organisationunit/internal/OrganisationUnitCallUnitShould.kt
1
8322
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 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. * Neither the name of the HISP project 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 OWNER 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 org.hisp.dhis.android.core.organisationunit.internal import com.google.common.truth.Truth.assertThat import com.nhaarman.mockitokotlin2.* import io.reactivex.Completable import io.reactivex.Single import java.io.IOException import java.util.* import org.hisp.dhis.android.core.arch.api.fields.internal.Fields import org.hisp.dhis.android.core.arch.api.filters.internal.Filter import org.hisp.dhis.android.core.arch.api.payload.internal.Payload import org.hisp.dhis.android.core.arch.cleaners.internal.CollectionCleaner import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore import org.hisp.dhis.android.core.organisationunit.OrganisationUnit import org.hisp.dhis.android.core.user.User import org.hisp.dhis.android.core.user.UserInternalAccessor import org.hisp.dhis.android.core.user.internal.UserOrganisationUnitLinkStore import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class OrganisationUnitCallUnitShould { private val organisationUnitPayload: Payload<OrganisationUnit> = mock() private val organisationUnitService: OrganisationUnitService = mock() // Captors for the organisationUnitService arguments: private val fieldsCaptor = argumentCaptor<Fields<OrganisationUnit>>() private val filtersCaptor = argumentCaptor<Filter<OrganisationUnit, String>>() private val pagingCaptor = argumentCaptor<Boolean>() private val pageCaptor = argumentCaptor<Int>() private val pageSizeCaptor = argumentCaptor<Int>() private val orderCaptor = argumentCaptor<String>() private val organisationUnit: OrganisationUnit = mock() private val user: User = mock() private val created: Date = mock() private val collectionCleaner: CollectionCleaner<OrganisationUnit> = mock() private val organisationUnitHandler: OrganisationUnitHandler = mock() private val userOrganisationUnitLinkStore: UserOrganisationUnitLinkStore = mock() private val organisationUnitIdentifiableObjectStore: IdentifiableObjectStore<OrganisationUnit> = mock() private val organisationUnitDisplayPathTransformer: OrganisationUnitDisplayPathTransformer = mock() // the call we are testing: private lateinit var lastUpdated: Date private lateinit var organisationUnitCall: Completable @Before @Throws(IOException::class) fun setUp() { lastUpdated = Date() val orgUnitUid = "orgUnitUid1" whenever(organisationUnit.uid()).doReturn(orgUnitUid) whenever(organisationUnit.code()).doReturn("organisation_unit_code") whenever(organisationUnit.name()).doReturn("organisation_unit_name") whenever(organisationUnit.displayName()).doReturn("organisation_unit_display_name") whenever(organisationUnit.deleted()).doReturn(false) whenever(organisationUnit.created()).doReturn(created) whenever(organisationUnit.lastUpdated()).doReturn(lastUpdated) whenever(organisationUnit.shortName()).doReturn("organisation_unit_short_name") whenever(organisationUnit.displayShortName()).doReturn("organisation_unit_display_short_name") whenever(organisationUnit.description()).doReturn("organisation_unit_description") whenever(organisationUnit.displayDescription()).doReturn("organisation_unit_display_description") whenever(organisationUnit.path()).doReturn("/root/orgUnitUid1") whenever(organisationUnit.openingDate()).doReturn(created) whenever(organisationUnit.closedDate()).doReturn(lastUpdated) whenever(organisationUnit.level()).doReturn(4) whenever(organisationUnit.parent()).doReturn(null) whenever(user.uid()).doReturn("user_uid") whenever(user.code()).doReturn("user_code") whenever(user.name()).doReturn("user_name") whenever(user.displayName()).doReturn("user_display_name") whenever(user.created()).doReturn(created) whenever(user.lastUpdated()).doReturn(lastUpdated) whenever(user.birthday()).doReturn("user_birthday") whenever(user.education()).doReturn("user_education") whenever(user.gender()).doReturn("user_gender") whenever(user.jobTitle()).doReturn("user_job_title") whenever(user.surname()).doReturn("user_surname") whenever(user.firstName()).doReturn("user_first_name") whenever(user.introduction()).doReturn("user_introduction") whenever(user.employer()).doReturn("user_employer") whenever(user.interests()).doReturn("user_interests") whenever(user.languages()).doReturn("user_languages") whenever(user.email()).doReturn("user_email") whenever(user.phoneNumber()).doReturn("user_phone_number") whenever(user.nationality()).doReturn("user_nationality") organisationUnitCall = OrganisationUnitCall( organisationUnitService, organisationUnitHandler, organisationUnitDisplayPathTransformer, userOrganisationUnitLinkStore, organisationUnitIdentifiableObjectStore, collectionCleaner ) .download(user) // Return only one organisationUnit. val organisationUnits = listOf(organisationUnit) whenever(UserInternalAccessor.accessOrganisationUnits(user)).doReturn(organisationUnits) whenever( organisationUnitService.getOrganisationUnits( fieldsCaptor.capture(), filtersCaptor.capture(), orderCaptor.capture(), pagingCaptor.capture(), pageSizeCaptor.capture(), pageCaptor.capture() ) ).doReturn(Single.just(organisationUnitPayload)) whenever(organisationUnitPayload.items()).doReturn(organisationUnits) } @Test fun invoke_server_with_correct_parameters() { organisationUnitCall.blockingGet() assertThat(fieldsCaptor.firstValue).isEqualTo(OrganisationUnitFields.allFields) assertThat(filtersCaptor.firstValue.operator()).isEqualTo("like") assertThat(filtersCaptor.firstValue.field()).isEqualTo(OrganisationUnitFields.path) assertThat(orderCaptor.firstValue).isEqualTo(OrganisationUnitFields.ASC_ORDER) assertThat(pagingCaptor.firstValue).isTrue() assertThat(pageCaptor.firstValue).isEqualTo(1) } @Test fun invoke_handler_if_request_succeeds() { organisationUnitCall.blockingGet() verify(organisationUnitHandler, times(1)).handleMany(any(), any()) } @Test fun perform_call_twice_on_consecutive_calls() { organisationUnitCall.blockingGet() organisationUnitCall.blockingGet() verify(organisationUnitHandler, times(2)).handleMany(any(), any()) } }
bsd-3-clause
952b53cec1d542feb3056004577056d6
49.13253
111
0.742129
4.968358
false
false
false
false
dkandalov/katas
kotlin/src/katas/kotlin/coroutines/hello.kt
1
2349
package katas.kotlin.coroutines import kotlin.coroutines.* import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn object Hello { fun launchCoroutine(context: CoroutineContext, coroutineScope: suspend () -> Unit) { coroutineScope.startCoroutine(MyContinuation(context)) } fun main() { var savedContinuation: Continuation<Unit>? = null val coroutineScope: suspend () -> Unit = { println("Start of scope") suspendCoroutineUninterceptedOrReturn { continuation: Continuation<Unit> -> savedContinuation = continuation println("Suspended") COROUTINE_SUSPENDED } println("End of scope") } println("Start") // coroutineScope.startCoroutineUninterceptedOrReturn(MyContinuation(EmptyCoroutineContext)) coroutineScope.startCoroutine(MyContinuation(MyEmptyCoroutineContext)) println("About to resume") savedContinuation!!.resume(Unit) // savedContinuation!!.context.printed() println("About to resume again") savedContinuation!!.resume(Unit) println("About to resume again 2") savedContinuation!!.resume(Unit) println("End") } } class MyContinuation<Unit>(override val context: CoroutineContext): Continuation<Unit> { override fun resumeWith(result: Result<Unit>) {} } object MyEmptyCoroutineContext : CoroutineContext { @Suppress("UNCHECKED_CAST") override fun <E : CoroutineContext.Element> get(key: CoroutineContext.Key<E>): E? = if (key === ContinuationInterceptor.Key) (MyInterceptor as E?) else null override fun <R> fold(initial: R, operation: (R, CoroutineContext.Element) -> R): R = initial override fun plus(context: CoroutineContext): CoroutineContext = context override fun minusKey(key: CoroutineContext.Key<*>): CoroutineContext = this override fun hashCode(): Int = 0 override fun toString(): String = "EmptyCoroutineContext" } object MyInterceptor : ContinuationInterceptor, AbstractCoroutineContextElement(Key) { object Key : CoroutineContext.Key<MyInterceptor> override fun <T> interceptContinuation(continuation: Continuation<T>) = continuation } fun main() { Hello.main() }
unlicense
a635ca2ef784d328a46f02710be8b502
36.285714
99
0.698595
5.278652
false
false
false
false
dahlstrom-g/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/imports/impl/GroovyFileImportsImpl.kt
12
4577
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.imports.impl import com.intellij.psi.PsiElement import com.intellij.psi.ResolveState import com.intellij.psi.scope.PsiScopeProcessor import org.jetbrains.annotations.NonNls import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement import org.jetbrains.plugins.groovy.lang.resolve.imports.* import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint import org.jetbrains.plugins.groovy.util.flatten internal class GroovyFileImportsImpl( override val file: GroovyFileBase, private val imports: Map<ImportKind<*>, Collection<GroovyImport>>, private val statementToImport: Map<GrImportStatement, GroovyImport>, private val importToStatement: Map<GroovyImport, GrImportStatement> ) : GroovyFileImports { @Suppress("UNCHECKED_CAST") private fun <T : GroovyImport> getImports(kind: ImportKind<T>): Collection<T> { val collection = imports[kind] ?: return emptyList() return collection as Collection<T> } private val regularImports get() = getImports(ImportKind.Regular) private val staticImports get() = getImports(ImportKind.Static) override val starImports: Collection<StarImport> get() = getImports(ImportKind.Star) override val staticStarImports: Collection<StaticStarImport> get() = getImports(ImportKind.StaticStar) override val allNamedImports: Collection<GroovyNamedImport> = flatten(regularImports, staticImports) private val allStarImports = flatten(starImports, staticStarImports) private val allNamedImportsMap by lazy { allNamedImports.groupBy { it.name } } override fun getImportsByName(name: String): Collection<GroovyNamedImport> = allNamedImportsMap[name] ?: emptyList() private fun ResolveState.putImport(import: GroovyImport): ResolveState { val state = put(importKey, import) val statement = importToStatement[import] ?: return state return state.put(ClassHint.RESOLVE_CONTEXT, statement) } @Suppress("LoopToCallChain") private fun Collection<GroovyImport>.doProcess(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { for (import in this) { if (!import.processDeclarations(processor, state.putImport(import), place, file)) return false } return true } override fun processStaticImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { return staticImports.doProcess(processor, state, place) } override fun processAllNamedImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { return allNamedImports.doProcess(processor, state, place) } override fun processStaticStarImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { return staticStarImports.doProcess(processor, state, place) } override fun processAllStarImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { return allStarImports.doProcess(processor, state, place) } override fun processDefaultImports(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { return defaultImports.doProcess(processor, state, place) } override fun isImplicit(import: GroovyImport): Boolean = !importToStatement.containsKey(import) override fun findUnnecessaryStatements(): Collection<GrImportStatement> { return statementToImport.filterValues { it.isUnnecessary(this) }.keys } override fun findUnresolvedStatements(names: Collection<String>): Collection<GrImportStatement> { if (names.isEmpty()) return emptyList() val result = HashSet<GrImportStatement>() for (import in starImports) { val statement = importToStatement[import] ?: continue if (import.resolveImport(file) == null) { result += statement } } for (import in allNamedImports) { if (import.name !in names) continue val statement = importToStatement[import] ?: continue if (import.resolveImport(file) == null) { result += statement } } return result } @NonNls override fun toString(): String = "Regular: ${regularImports.size}; " + "static: ${staticImports.size}; " + "*: ${starImports.size}; " + "static *: ${staticStarImports.size}" }
apache-2.0
84b6c3b8b771ec781bf112a571805c3a
42.590476
140
0.744811
4.767708
false
false
false
false
subhalaxmin/Programming-Kotlin
Chapter07/src/main/kotlin/com/packt/chapter4/4.3.kt
4
399
fun hello(): String = "hello world" fun hello(name: String): String = "hello to you $name" fun invocation() { val string = "hello" val length = string.take(5) } object Square { fun printArea(width: Int, height: Int): Unit { val area = calculateArea(width, height) println("The area is $area") } fun calculateArea(width: Int, height: Int): Int { return width * height } }
mit
87c1ea141ff2ce45ef0622ae4a55ebdd
19
54
0.646617
3.381356
false
false
false
false
seratch/jslack
slack-api-model-kotlin-extension/src/main/kotlin/com/slack/api/model/kotlin_extension/block/dsl/ContextBlockElementDsl.kt
1
827
package com.slack.api.model.kotlin_extension.block.dsl import com.slack.api.model.kotlin_extension.block.BlockLayoutBuilder import com.slack.api.model.kotlin_extension.block.composition.dsl.TextObjectDsl @BlockLayoutBuilder interface ContextBlockElementDsl : TextObjectDsl { /** * An element to insert an image as part of a larger block of content. If you want a block with only an image in * it, you're looking for the image block. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#image">Image element documentation</a> */ fun image( imageUrl: String? = null, altText: String? = null, fallback: String? = null, imageWidth: Int? = null, imageHeight: Int? = null, imageBytes: Int? = null ) }
mit
7579e0832b052ead6a34c42530314ce7
36.636364
116
0.665054
4.014563
false
false
false
false
JuliaSoboleva/SmartReceiptsLibrary
app/src/main/java/co/smartreceipts/android/distance/editor/DistanceCreateEditFragment.kt
1
19742
package co.smartreceipts.android.distance.editor import android.app.AlertDialog import android.content.Context import android.os.Bundle import android.view.* import android.widget.Toast import androidx.appcompat.widget.Toolbar import androidx.constraintlayout.widget.ConstraintLayout import co.smartreceipts.analytics.Analytics import co.smartreceipts.analytics.events.Events import co.smartreceipts.android.R import co.smartreceipts.android.activities.NavigationHandler import co.smartreceipts.android.activities.SmartReceiptsActivity import co.smartreceipts.android.adapters.FooterButtonArrayAdapter import co.smartreceipts.android.autocomplete.AutoCompleteArrayAdapter import co.smartreceipts.android.autocomplete.AutoCompleteField import co.smartreceipts.android.autocomplete.AutoCompleteResult import co.smartreceipts.android.autocomplete.distance.DistanceAutoCompleteField import co.smartreceipts.android.currency.widget.CurrencyListEditorPresenter import co.smartreceipts.android.currency.widget.DefaultCurrencyListEditorView import co.smartreceipts.android.databinding.UpdateDistanceBinding import co.smartreceipts.android.date.DateFormatter import co.smartreceipts.android.distance.editor.currency.DistanceCurrencyCodeSupplier import co.smartreceipts.android.fragments.WBFragment import co.smartreceipts.android.model.AutoCompleteUpdateEvent import co.smartreceipts.android.model.Distance import co.smartreceipts.android.model.PaymentMethod import co.smartreceipts.android.model.Trip import co.smartreceipts.android.model.factory.DistanceBuilderFactory import co.smartreceipts.android.model.utils.ModelUtils import co.smartreceipts.android.persistence.DatabaseHelper import co.smartreceipts.android.receipts.editor.paymentmethods.PaymentMethodsPresenter import co.smartreceipts.android.receipts.editor.paymentmethods.PaymentMethodsView import co.smartreceipts.android.utils.SoftKeyboardManager import co.smartreceipts.android.widget.model.UiIndicator import co.smartreceipts.android.widget.ui.PriceInputEditText import com.google.android.material.snackbar.Snackbar import com.jakewharton.rxbinding3.widget.textChanges import dagger.android.support.AndroidSupportInjection import io.reactivex.Observable import io.reactivex.functions.Consumer import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.Subject import kotlinx.android.synthetic.main.update_distance.* import java.sql.Date import java.util.* import javax.inject.Inject class DistanceCreateEditFragment : WBFragment(), DistanceCreateEditView, View.OnFocusChangeListener, PaymentMethodsView { @Inject lateinit var presenter: DistanceCreateEditPresenter @Inject lateinit var analytics: Analytics @Inject lateinit var database: DatabaseHelper @Inject lateinit var dateFormatter: DateFormatter @Inject lateinit var navigationHandler: NavigationHandler<SmartReceiptsActivity> @Inject lateinit var paymentMethodsPresenter: PaymentMethodsPresenter private lateinit var paymentMethodsViewsList: List<@JvmSuppressWildcards View> override val editableItem: Distance? get() = arguments?.getParcelable(Distance.PARCEL_KEY) private val parentTrip: Trip get() = arguments?.getParcelable(Trip.PARCEL_KEY) ?: throw IllegalStateException("Distance can't exist without parent trip") private var suggestedDate: Date = Date(Calendar.getInstance().timeInMillis) private lateinit var currencyListEditorPresenter: CurrencyListEditorPresenter private lateinit var resultsAdapter: AutoCompleteArrayAdapter<Distance> private var shouldHideResults: Boolean = false private var focusedView: View? = null private lateinit var snackbar: Snackbar private lateinit var paymentMethodsAdapter: FooterButtonArrayAdapter<PaymentMethod> private var itemToRemoveOrReAdd: AutoCompleteResult<Distance>? = null private var _binding: UpdateDistanceBinding? = null private val binding get() = _binding!! override val createDistanceClicks: Observable<Distance> get() = _createDistanceClicks override val updateDistanceClicks: Observable<Distance> get() = _updateDistanceClicks override val deleteDistanceClicks: Observable<Distance> get() = _deleteDistanceClicks override val hideAutoCompleteVisibilityClick: Observable<AutoCompleteUpdateEvent<Distance>> get() =_hideAutoCompleteVisibilityClicks override val unHideAutoCompleteVisibilityClick: Observable<AutoCompleteUpdateEvent<Distance>> get() =_unHideAutoCompleteVisibilityClicks private val _createDistanceClicks: Subject<Distance> = PublishSubject.create<Distance>().toSerialized() private val _updateDistanceClicks: Subject<Distance> = PublishSubject.create<Distance>().toSerialized() private val _deleteDistanceClicks: Subject<Distance> = PublishSubject.create<Distance>().toSerialized() private val _hideAutoCompleteVisibilityClicks: Subject<AutoCompleteUpdateEvent<Distance>> = PublishSubject.create<AutoCompleteUpdateEvent<Distance>>().toSerialized() private val _unHideAutoCompleteVisibilityClicks: Subject<AutoCompleteUpdateEvent<Distance>> = PublishSubject.create<AutoCompleteUpdateEvent<Distance>>().toSerialized() override fun onAttach(context: Context) { AndroidSupportInjection.inject(this) super.onAttach(context) } override fun onFocusChange(view: View, hasFocus: Boolean) { if (focusedView is PriceInputEditText && !hasFocus) { // format rate on focus lose (focusedView as PriceInputEditText).formatPriceText() } focusedView = if (hasFocus) view else null if (editableItem == null && hasFocus) { // Only launch if we have focus and it's a new distance SoftKeyboardManager.showKeyboard(view) } } override fun onResume() { super.onResume() focusedView?.requestFocus() // Make sure we're focused on the right view } override fun onPause() { SoftKeyboardManager.hideKeyboard(focusedView) super.onPause() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) if (savedInstanceState != null) { suggestedDate = Date(arguments?.getLong(ARG_SUGGESTED_DATE, suggestedDate.time) ?: suggestedDate.time) } paymentMethodsAdapter = FooterButtonArrayAdapter(requireActivity(), ArrayList(), R.string.manage_payment_methods) { analytics.record(Events.Informational.ClickedManagePaymentMethods) navigationHandler.navigateToPaymentMethodsEditor() } currencyListEditorPresenter = CurrencyListEditorPresenter( DefaultCurrencyListEditorView(requireContext()) { spinner_currency }, database, DistanceCurrencyCodeSupplier(parentTrip, editableItem), savedInstanceState ) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = UpdateDistanceBinding.inflate(inflater, container, false) paymentMethodsViewsList = listOf(binding.distanceInputGuideImagePaymentMethod, binding.distanceInputPaymentMethod) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setUpFocusBehavior() // Toolbar stuff when { navigationHandler.isDualPane -> toolbar.visibility = View.GONE else -> setSupportActionBar(toolbar as Toolbar) } supportActionBar?.apply { setHomeButtonEnabled(true) setDisplayHomeAsUpEnabled(true) setHomeAsUpIndicator(R.drawable.ic_clear_24dp) setTitle(if (editableItem == null) R.string.dialog_mileage_title_create else R.string.dialog_mileage_title_update) subtitle = "" } text_distance_rate.setDecimalPlaces(Distance.RATE_PRECISION) if (editableItem == null) { // New Distance text_distance_date.date = suggestedDate text_distance_rate.setText(presenter.getDefaultDistanceRate()) } else { // Update distance text_distance_value.setText(editableItem!!.decimalFormattedDistance) text_distance_rate.setText(editableItem!!.decimalFormattedRate) text_distance_location.setText(editableItem!!.location) text_distance_comment.setText(editableItem!!.comment) text_distance_date.date = editableItem!!.date text_distance_date.timeZone = editableItem!!.timeZone } } override fun onStart() { super.onStart() presenter.subscribe() currencyListEditorPresenter.subscribe() paymentMethodsPresenter.subscribe() } override fun onStop() { presenter.unsubscribe() currencyListEditorPresenter.unsubscribe() paymentMethodsPresenter.unsubscribe() if (::snackbar.isInitialized && snackbar.isShown) { snackbar.dismiss() } super.onStop() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) currencyListEditorPresenter.onSaveInstanceState(outState) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(if (editableItem == null) R.menu.menu_save else R.menu.menu_save_delete, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { navigationHandler.navigateBack() return true } R.id.action_save -> { when { editableItem != null -> _updateDistanceClicks.onNext(constructDistance()) else -> _createDistanceClicks.onNext(constructDistance()) } return true } R.id.action_delete -> { showDeleteDialog() return true } else -> return super.onOptionsItemSelected(item) } } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun present(uiIndicator: UiIndicator<Int>) { when (uiIndicator.state) { UiIndicator.State.Success -> navigationHandler.navigateBack() else -> if (uiIndicator.state == UiIndicator.State.Error && uiIndicator.data.isPresent) { Toast.makeText(requireContext(), uiIndicator.data.get(), Toast.LENGTH_LONG).show() } } } private fun setUpFocusBehavior() { text_distance_value.onFocusChangeListener = this text_distance_rate.onFocusChangeListener = this text_distance_location.onFocusChangeListener = this text_distance_date.onFocusChangeListener = this spinner_currency.onFocusChangeListener = this text_distance_comment.onFocusChangeListener = this distance_input_payment_method.onFocusChangeListener = this // And ensure that we do not show the keyboard when clicking these views val hideSoftKeyboardOnTouchListener = SoftKeyboardManager.HideSoftKeyboardOnTouchListener() spinner_currency.setOnTouchListener(hideSoftKeyboardOnTouchListener) distance_input_payment_method.setOnTouchListener(hideSoftKeyboardOnTouchListener) text_distance_date.apply { isFocusable = false isFocusableInTouchMode = false setDateFormatter(dateFormatter) setOnTouchListener(hideSoftKeyboardOnTouchListener) } // Focused View if (focusedView == null) { focusedView = text_distance_value } } private fun constructDistance(): Distance { val distanceBuilder: DistanceBuilderFactory = when (editableItem) { null -> DistanceBuilderFactory() .setDistance(ModelUtils.tryParse(text_distance_value.text.toString())) .setRate(ModelUtils.tryParse(text_distance_rate.text.toString())) else -> DistanceBuilderFactory(editableItem!!) .setDistance(ModelUtils.tryParse(text_distance_value.text.toString(), editableItem!!.distance)) .setRate(ModelUtils.tryParse(text_distance_rate.text.toString(), editableItem!!.rate)) } val paymentMethod: PaymentMethod? = if (presenter.isUsePaymentMethods()) { distance_input_payment_method.selectedItem as PaymentMethod } else { null } return distanceBuilder .setTrip(parentTrip) .setLocation(text_distance_location.text.toString()) .setDate(text_distance_date.date) .setTimezone(text_distance_date.timeZone) .setCurrency(spinner_currency.selectedItem.toString()) .setComment(text_distance_comment.text.toString()) .setPaymentMethod(paymentMethod) .build() } private fun showDeleteDialog() { AlertDialog.Builder(activity) .setTitle(getString(R.string.delete_item, editableItem!!.location)) .setMessage(R.string.delete_sync_information) .setCancelable(true) .setPositiveButton(R.string.delete) { _, _ -> _deleteDistanceClicks.onNext(editableItem!!) } .setNegativeButton(android.R.string.cancel) { _, _ -> } .show() } override fun togglePaymentMethodFieldVisibility(): Consumer<in Boolean> { return Consumer { isVisible -> run { for (v in paymentMethodsViewsList) { v.visibility = if (isVisible) View.VISIBLE else View.GONE } } } } override fun displayPaymentMethods(list: List<PaymentMethod>) { if (isAdded) { paymentMethodsAdapter.update(list) distance_input_payment_method.adapter = paymentMethodsAdapter if (editableItem != null) { // Here we manually loop through all payment methods and check for id == id in case the user changed this via "Manage" val distancePaymentMethod = editableItem!!.paymentMethod for (i in 0 until paymentMethodsAdapter.count) { val paymentMethod = paymentMethodsAdapter.getItem(i) if (paymentMethod != null && paymentMethod.id == distancePaymentMethod.id) { distance_input_payment_method.setSelection(i) break } } } } } override fun getTextChangeStream(field: AutoCompleteField): Observable<CharSequence> { return when (field) { DistanceAutoCompleteField.Location -> text_distance_location.textChanges() DistanceAutoCompleteField.Comment -> text_distance_comment.textChanges() else -> throw IllegalArgumentException("Unsupported field type: $field") } } override fun displayAutoCompleteResults(field: AutoCompleteField, results: MutableList<AutoCompleteResult<Distance>>) { if (isAdded) { if (!shouldHideResults) { if (::snackbar.isInitialized && snackbar.isShown) { snackbar.dismiss() } resultsAdapter = AutoCompleteArrayAdapter(requireContext(), results, this) when (field) { DistanceAutoCompleteField.Location -> { text_distance_location.setAdapter(resultsAdapter) if (text_distance_location.hasFocus()) { text_distance_location.showDropDown() } } DistanceAutoCompleteField.Comment -> { text_distance_comment.setAdapter(resultsAdapter) if (text_distance_comment.hasFocus()) { text_distance_comment.showDropDown() } } else -> throw IllegalArgumentException("Unsupported field type: $field") } } else { shouldHideResults = false } } } override fun fillValueField(autoCompleteResult: AutoCompleteResult<Distance>) { shouldHideResults = true if (text_distance_location.isPopupShowing) { text_distance_location.setText(autoCompleteResult.displayName) text_distance_location.setSelection(text_distance_location.text.length) text_distance_location.dismissDropDown() } else { text_distance_comment.setText(autoCompleteResult.displayName) text_distance_comment.setSelection(text_distance_comment.text.length) text_distance_comment.dismissDropDown() } SoftKeyboardManager.hideKeyboard(focusedView) } override fun sendAutoCompleteHideEvent(autoCompleteResult: AutoCompleteResult<Distance>) { SoftKeyboardManager.hideKeyboard(focusedView) itemToRemoveOrReAdd = autoCompleteResult when(text_distance_location.isPopupShowing) { true -> _hideAutoCompleteVisibilityClicks.onNext( AutoCompleteUpdateEvent(autoCompleteResult, DistanceAutoCompleteField.Location, resultsAdapter.getPosition(autoCompleteResult))) false -> _hideAutoCompleteVisibilityClicks.onNext( AutoCompleteUpdateEvent(autoCompleteResult, DistanceAutoCompleteField.Comment, resultsAdapter.getPosition(autoCompleteResult))) } } override fun removeValueFromAutoComplete(position: Int) { activity!!.runOnUiThread { itemToRemoveOrReAdd = resultsAdapter.getItem(position) resultsAdapter.remove(itemToRemoveOrReAdd) resultsAdapter.notifyDataSetChanged() val view = activity!!.findViewById<ConstraintLayout>(R.id.update_distance_layout) snackbar = Snackbar.make(view, getString( R.string.item_removed_from_auto_complete, itemToRemoveOrReAdd!!.displayName), Snackbar.LENGTH_LONG) snackbar.setAction(R.string.undo) { if (text_distance_location.hasFocus()) { _unHideAutoCompleteVisibilityClicks.onNext( AutoCompleteUpdateEvent(itemToRemoveOrReAdd, DistanceAutoCompleteField.Location, position)) } else { _unHideAutoCompleteVisibilityClicks.onNext( AutoCompleteUpdateEvent(itemToRemoveOrReAdd, DistanceAutoCompleteField.Comment, position)) } } snackbar.show() } } override fun sendAutoCompleteUnHideEvent(position: Int) { activity!!.runOnUiThread { resultsAdapter.insert(itemToRemoveOrReAdd, position) resultsAdapter.notifyDataSetChanged() Toast.makeText(context, R.string.result_restored, Toast.LENGTH_LONG).show() } } override fun displayAutoCompleteError() { activity!!.runOnUiThread { Toast.makeText(activity, R.string.result_restore_failed, Toast.LENGTH_LONG).show() } } companion object { @JvmStatic fun newInstance() = DistanceCreateEditFragment() const val ARG_SUGGESTED_DATE = "arg_suggested_date" } }
agpl-3.0
ce33b78e05cc5072bb999d9a1ca27d7a
40.389937
152
0.677692
5.60693
false
false
false
false
MGaetan89/ShowsRage
app/src/main/kotlin/com/mgaetan89/showsrage/fragment/AddShowFragment.kt
1
3819
package com.mgaetan89.showsrage.fragment import android.app.SearchManager import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.SearchView import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.View import android.view.ViewGroup import com.mgaetan89.showsrage.R import com.mgaetan89.showsrage.activity.MainActivity import com.mgaetan89.showsrage.adapter.SearchResultsAdapter import com.mgaetan89.showsrage.model.SearchResultItem import com.mgaetan89.showsrage.model.SearchResults import com.mgaetan89.showsrage.network.SickRageApi import kotlinx.android.synthetic.main.fragment_add_show.empty import kotlinx.android.synthetic.main.fragment_add_show.list import retrofit.Callback import retrofit.RetrofitError import retrofit.client.Response class AddShowFragment : Fragment(), Callback<SearchResults>, SearchView.OnQueryTextListener { private val searchResults = mutableListOf<SearchResultItem>() init { this.setHasOptionsMenu(true) } override fun failure(error: RetrofitError?) { error?.printStackTrace() } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val activity = this.activity if (activity is MainActivity) { activity.displayHomeAsUp(true) } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.add_show, menu) val activity = this.activity ?: return val searchManager = activity.getSystemService(Context.SEARCH_SERVICE) as SearchManager val searchMenu = menu.findItem(R.id.menu_search) (searchMenu.actionView as SearchView).also { it.setIconifiedByDefault(false) it.setOnQueryTextListener(this) it.setSearchableInfo(searchManager.getSearchableInfo(activity.componentName)) it.setQuery(getQueryFromIntent(activity.intent), true) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_add_show, container, false) override fun onDestroy() { this.searchResults.clear() super.onDestroy() } override fun onQueryTextChange(newText: String?) = false override fun onQueryTextSubmit(query: String?): Boolean { if (isQueryValid(query)) { if (this.list?.adapter?.itemCount == 0) { this.empty?.let { it.setText(R.string.loading) it.visibility = View.VISIBLE } } SickRageApi.instance.services?.search(query!!, this) return true } return false } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val columnCount = this.resources.getInteger(R.integer.shows_column_count) this.list?.adapter = SearchResultsAdapter(this.searchResults) this.list?.layoutManager = GridLayoutManager(this.activity, columnCount) } override fun success(searchResults: SearchResults?, response: Response?) { this.searchResults.clear() this.searchResults.addAll(getSearchResults(searchResults)) if (this.searchResults.isEmpty()) { this.empty?.let { it.setText(R.string.no_results) it.visibility = View.VISIBLE } this.list?.visibility = View.GONE } else { this.empty?.visibility = View.GONE this.list?.visibility = View.VISIBLE } this.list?.adapter?.notifyDataSetChanged() } companion object { fun getQueryFromIntent(intent: Intent?): String? = if (Intent.ACTION_SEARCH != intent?.action) "" else intent.getStringExtra(SearchManager.QUERY) fun getSearchResults(searchResults: SearchResults?) = searchResults?.data?.results ?: emptyList() fun isQueryValid(query: String?) = !query.isNullOrBlank() fun newInstance() = AddShowFragment() } }
apache-2.0
946ca82d3976cab6a48ff3ea5b334df7
29.070866
111
0.77481
3.98643
false
false
false
false
ssseasonnn/RxDownload
rxdownload4-manager/src/main/java/zlc/season/rxdownload4/manager/TaskManager.kt
1
4755
package zlc.season.rxdownload4.manager import io.reactivex.android.schedulers.AndroidSchedulers.mainThread import io.reactivex.disposables.Disposable import io.reactivex.flowables.ConnectableFlowable import io.reactivex.rxkotlin.subscribeBy import zlc.season.rxdownload4.Progress import zlc.season.rxdownload4.delete import zlc.season.rxdownload4.file import zlc.season.rxdownload4.storage.Storage import zlc.season.rxdownload4.task.Task import zlc.season.rxdownload4.utils.safeDispose import java.util.concurrent.TimeUnit.MILLISECONDS import java.util.concurrent.TimeUnit.SECONDS class TaskManager( private val task: Task, private val storage: Storage, private val connectFlowable: ConnectableFlowable<Progress>, private val notificationCreator: NotificationCreator, taskRecorder: TaskRecorder, val taskLimitation: TaskLimitation ) { init { notificationCreator.init(task) } //For download use private val downloadHandler by lazy { StatusHandler(task) } //For record use private val recordHandler by lazy { StatusHandler(task, taskRecorder) } //For notification use private val notificationHandler by lazy { StatusHandler(task, logTag = "Notification") { val notification = notificationCreator.create(task, it) showNotification(task, notification) } } //Download disposable private var disposable: Disposable? = null private var downloadDisposable: Disposable? = null private var recordDisposable: Disposable? = null private var notificationDisposable: Disposable? = null /** * @param tag As the unique identifier for this subscription * @param receiveLastStatus If true, the last status will be received after subscribing */ internal fun addCallback(tag: Any, receiveLastStatus: Boolean, callback: (Status) -> Unit) { downloadHandler.addCallback(tag, receiveLastStatus, callback) } internal fun removeCallback(tag: Any) { downloadHandler.removeCallback(tag) } internal fun currentStatus() = downloadHandler.currentStatus internal fun getFile() = task.file(storage) internal fun innerStart() { if (isStarted()) { return } subscribeNotification() subscribeRecord() subscribeDownload() disposable = connectFlowable.connect() } private fun subscribeDownload() { downloadDisposable = connectFlowable .doOnSubscribe { downloadHandler.onStarted() } .subscribeOn(mainThread()) .observeOn(mainThread()) .doOnNext { downloadHandler.onDownloading(it) } .doOnComplete { downloadHandler.onCompleted() } .doOnError { downloadHandler.onFailed(it) } .doOnCancel { downloadHandler.onPaused() } .subscribeBy() } private fun subscribeRecord() { recordDisposable = connectFlowable.sample(10, SECONDS) .doOnSubscribe { recordHandler.onStarted() } .doOnNext { recordHandler.onDownloading(it) } .doOnComplete { recordHandler.onCompleted() } .doOnError { recordHandler.onFailed(it) } .doOnCancel { recordHandler.onPaused() } .subscribeBy() } private fun subscribeNotification() { notificationDisposable = connectFlowable.sample(500, MILLISECONDS) .doOnSubscribe { notificationHandler.onStarted() } .doOnNext { notificationHandler.onDownloading(it) } .doOnComplete { notificationHandler.onCompleted() } .doOnError { notificationHandler.onFailed(it) } .doOnCancel { notificationHandler.onPaused() } .subscribeBy() } internal fun innerStop() { //send pause status notificationHandler.onPaused() downloadHandler.onPaused() recordHandler.onPaused() notificationDisposable.safeDispose() recordDisposable.safeDispose() downloadDisposable.safeDispose() disposable.safeDispose() } internal fun innerDelete() { innerStop() task.delete(storage) //send delete status downloadHandler.onDeleted() notificationHandler.onDeleted() recordHandler.onDeleted() cancelNotification(task) } /** * Send Pending status */ internal fun innerPending() { downloadHandler.onPending() recordHandler.onPending() notificationHandler.onPending() } private fun isStarted(): Boolean { return disposable != null && !disposable!!.isDisposed } }
apache-2.0
44e48728ed0a1925ce3af91c5b1732eb
31.353741
96
0.661199
5.465517
false
false
false
false
bradylangdale/IntrepidClient
Client Files/IntrepidClient/src/main/kotlin/org/abendigo/csgo/offsets/Offsets.kt
1
4886
@file:JvmName("Offsets") package org.abendigo.csgo.offsets import org.abendigo.csgo.Client.clientDLL import org.abendigo.csgo.csgoModule import org.abendigo.csgo.engineDLL val worldDecal by scanOffset(clientDLL, 0, 0, 0, "DT_TEWorldDecal") val firstClass by scanOffset(clientDLL, 0x2B, 0, READ, worldDecal) val gameDirectoryPointer by scanOffset(csgoModule, 1, 0, READ or SUBTRACT, 0xB9, 0, 0, 0, 0, 0x8D, 0x51) // client.dll offsets const val m_bDormant = 0xE9 const val m_dwIndex = 0x64 const val m_dwModel = 0x6C val m_dwRadarBase by scanOffset(clientDLL, 1, 0, READ or SUBTRACT, 161, 0, 0, 0, 0, 139, 12, 176, 139, 1, 255, 80, 0, 70, 59, 53, 0, 0, 0, 0, 124, 234, 139, 13, 0, 0, 0, 0) val m_dwWeaponTable by scanOffset(clientDLL, 1, 0, READ or SUBTRACT, 161, 0, 0, 0, 0, 15, 183, 201, 3, 201, 139, 68, 0, 12, 195) val m_dwWeaponTableIndex by scanOffset(clientDLL, 3, 0, READ, 102, 139, 142, 0, 0, 0, 0, 232, 0, 0, 0, 0, 5, 0, 0, 0, 0, 80) val m_dwInput by scanOffset(clientDLL, 1, 0, READ or SUBTRACT, 0xB9, 0, 0, 0, 0, 0xFF, 0x75, 0x08, 0xE8, 0, 0, 0, 0, 0x8B, 0x06) val m_dwGlowObject by scanOffset(clientDLL, 1, 4, READ or SUBTRACT, 0xA1, 0, 0, 0, 0, 0xA8, 0x01, 0x75, 0x4E, 0x0F, 0x57, 0xC0) val m_dwForceJump by scanOffset(clientDLL, 2, 0, READ or SUBTRACT, 137, 21, 0, 0, 0, 0, 139, 21, 0, 0, 0, 0, 246, 194, 3, 116, 3, 131, 206, 8) val m_dwForceAttack by scanOffset(clientDLL, 2, 0, READ or SUBTRACT, 137, 21, 0, 0, 0, 0, 139, 21, 0, 0, 0, 0, 246, 194, 3, 116, 3, 131, 206, 4) val m_dwViewMatrix by scanOffset(clientDLL, 828, 176, READ or SUBTRACT, 129, 198, 0, 0, 0, 0, 136, 69, 154, 15, 182, 192) val m_dwEntityList by scanOffset(clientDLL, 1, 0, READ or SUBTRACT, 187, 0, 0, 0, 0, 131, 255, 1, 15, 140, 0, 0, 0, 0, 59, 248) val m_dwLocalPlayer by scanOffset(clientDLL, 1, 16, READ or SUBTRACT, 163, 0, 0, 0, 0, 199, 5, 0, 0, 0, 0, 0, 0, 0, 0, 232, 0, 0, 0, 0, 89, 195, 106, 0) // engine.dll offsets val m_dwGlobalVars by scanOffset(engineDLL, 18, 0, READ or SUBTRACT, 0x8B, 0x0D, 0x0, 0x0, 0x0, 0x0, 0x83, 0xC4, 0x04, 0x8B, 0x01, 0x68, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x35) val m_dwClientState by scanOffset(engineDLL, 1, 0, READ or SUBTRACT, 161, 0, 0, 0, 0, 243, 15, 17, 128, 0, 0, 0, 0, 217, 70, 4, 217, 5, 0, 0, 0, 0) val m_dwInGame by scanOffset(engineDLL, 2, 0, READ, 131, 185, 0, 0, 0, 0, 6, 15, 148, 192, 195) val m_dwMaxPlayer by scanOffset(engineDLL, 7, 0, READ, 161, 0, 0, 0, 0, 139, 128, 0, 0, 0, 0, 195, 204, 204, 204, 204, 85, 139, 236, 139, 69, 8) val m_dwMapDirectory by scanOffset(engineDLL, 1, 0, READ, 5, 0, 0, 0, 0, 195, 204, 204, 204, 204, 204, 204, 204, 128, 61) val m_dwMapname by scanOffset(engineDLL, 1, 0, READ, 5, 0, 0, 0, 0, 195, 204, 204, 204, 204, 204, 204, 204, 161, 0, 0, 0, 0) val m_dwPlayerInfo by scanOffset(engineDLL, 2, 0, READ, 139, 136, 0, 0, 0, 0, 139, 1, 139, 64, 0, 255, 208, 139, 248) val m_dwViewAngles by scanOffset(engineDLL, 4, 0, READ, 0xF3, 0x0F, 0x11, 0x80, 0, 0, 0, 0, 0xD9, 0x46, 0x04, 0xD9, 0x05, 0, 0, 0, 0) val m_dwEnginePosition by scanOffset(engineDLL, 4, 0, READ or SUBTRACT, 243, 15, 17, 21, 0, 0, 0, 0, 243, 15, 17, 13, 0, 0, 0, 0, 243, 15, 17, 5, 0, 0, 0, 0, 243, 15, 17, 61, 0, 0, 0, 0) val m_bSendPacket by scanOffset(engineDLL, 0, 0, SUBTRACT, 0x01, 0x8B, 0x01, 0x8B, 0x40, 0x10) // thanks WasserEsser! val m_dwForceFullUpdate by scanOffset(engineDLL, 0x3, 0, READ or SUBTRACT, 0xB0, 0xFF, 0xB7, 0x00, 0x00, 0x00, 0x00, 0xE8) // DT_BaseEntity val m_bSpotted by beNetVar() val m_vecOrigin by beNetVar() val m_iTeamNum by beNetVar() // DT_BasePlayer val m_fFlags by bpNetVar() val m_iHealth by bpNetVar() val m_vecViewOffset by bpNetVar(index = 0) val m_vecVelocity by bpNetVar(index = 0) val m_vecPunch by bpNetVar("m_aimPunchAngle") val nActiveWeapon by bpNetVar() val nTickBase by bpNetVar() val m_lifeState by bpNetVar() val m_hActiveWeapon by bpNetVar() val m_nTickBase by bpNetVar() val m_nButtons by bpNetVar() val m_hMyWeapons by bpNetVar() // DT_CSPlayer val m_iCrossHairID by cspNetVar("m_bHasDefuser", 0x5C) val m_bIsScoped by cspNetVar() val m_iShotsFired by cspNetVar() val m_flFlashMaxAlpha by cspNetVar() // DT_BaseAnimating val m_dwBoneMatrix by netVar("DT_BaseAnimating", "m_nForceBone", 0x1C) // DT_BaseCombatWeapon val m_flNextPrimaryAttack by bcwNetVar() val m_iClip1 by bcwNetVar() val m_iClip2 by bcwNetVar() // DT_WeaponCSBase val m_iWeaponID by netVar("DT_WeaponCSBase", "m_fAccuracyPenalty", 0x30) // thanks n1BogOLlyQ val m_iItemDefinitionIndex by wepNetVar() val m_iAccountID by wepNetVar() val m_OriginalOwnerXuidLow by wepNetVar() val m_OriginalOwnerXuidHigh by wepNetVar() val m_iItemIDLow by wepNetVar() val m_iItemIDHigh by wepNetVar() val m_nFallbackPaintKit by wepNetVar() val m_nFallbackSeed by wepNetVar() val m_flFallbackWear by wepNetVar() val m_nFallbackStatTrak by wepNetVar() val m_iEntityQuality by wepNetVar() val m_szCustomName by wepNetVar()
gpl-3.0
8996eb1d2c4fafe75eafe9f97c4e2150
49.381443
133
0.692796
2.513374
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KotlinConstantConditionsInspection.kt
1
31851
// 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.dfa import com.intellij.codeInsight.PsiEquivalenceUtil import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.dataFlow.interpreter.RunnerResult import com.intellij.codeInspection.dataFlow.interpreter.StandardDataFlowInterpreter import com.intellij.codeInspection.dataFlow.jvm.JvmDfaMemoryStateImpl import com.intellij.codeInspection.dataFlow.lang.DfaAnchor import com.intellij.codeInspection.dataFlow.lang.DfaListener import com.intellij.codeInspection.dataFlow.lang.UnsatisfiedConditionProblem import com.intellij.codeInspection.dataFlow.lang.ir.DataFlowIRProvider import com.intellij.codeInspection.dataFlow.lang.ir.DfaInstructionState import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState import com.intellij.codeInspection.dataFlow.types.DfType import com.intellij.codeInspection.dataFlow.types.DfTypes import com.intellij.codeInspection.dataFlow.value.DfaValue import com.intellij.codeInspection.dataFlow.value.DfaValueFactory import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.siblings import com.intellij.util.ThreeState import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.diagnostics.Severity import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.inspections.dfa.KotlinAnchor.* import org.jetbrains.kotlin.idea.inspections.dfa.KotlinProblem.* import org.jetbrains.kotlin.idea.intentions.loopToCallChain.isConstant import org.jetbrains.kotlin.idea.intentions.negate import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.readWriteAccess import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.lexer.KtSingleValueToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.isNull import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.typeUtil.isNothing import org.jetbrains.kotlin.types.typeUtil.isNullableNothing class KotlinConstantConditionsInspection : AbstractKotlinInspection() { private enum class ConstantValue { TRUE, FALSE, NULL, ZERO, UNKNOWN } private class KotlinDfaListener : DfaListener { val constantConditions = hashMapOf<KotlinAnchor, ConstantValue>() val problems = hashMapOf<KotlinProblem, ThreeState>() override fun beforePush(args: Array<out DfaValue>, value: DfaValue, anchor: DfaAnchor, state: DfaMemoryState) { if (anchor is KotlinAnchor) { recordExpressionValue(anchor, state, value) } } override fun onCondition(problem: UnsatisfiedConditionProblem, value: DfaValue, failed: ThreeState, state: DfaMemoryState) { if (problem is KotlinProblem) { problems.merge(problem, failed, ThreeState::merge) } } private fun recordExpressionValue(anchor: KotlinAnchor, state: DfaMemoryState, value: DfaValue) { val oldVal = constantConditions[anchor] if (oldVal == ConstantValue.UNKNOWN) return var newVal = when (val dfType = state.getDfType(value)) { DfTypes.TRUE -> ConstantValue.TRUE DfTypes.FALSE -> ConstantValue.FALSE DfTypes.NULL -> ConstantValue.NULL else -> { val constVal: Number? = dfType.getConstantOfType(Number::class.java) if (constVal != null && (constVal == 0 || constVal == 0L)) ConstantValue.ZERO else ConstantValue.UNKNOWN } } if (oldVal != null && oldVal != newVal) { newVal = ConstantValue.UNKNOWN } constantConditions[anchor] = newVal } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { // Non-JVM is not supported now if (holder.file.module?.platform?.isJvm() != true) return PsiElementVisitor.EMPTY_VISITOR return object : KtVisitorVoid() { override fun visitProperty(property: KtProperty) { if (shouldAnalyzeProperty(property)) { val initializer = property.delegateExpressionOrInitializer ?: return analyze(initializer) } } override fun visitPropertyAccessor(accessor: KtPropertyAccessor) { if (shouldAnalyzeProperty(accessor.property)) { val bodyExpression = accessor.bodyExpression ?: accessor.bodyBlockExpression ?: return analyze(bodyExpression) } } override fun visitParameter(parameter: KtParameter) { analyze(parameter.defaultValue ?: return) } private fun shouldAnalyzeProperty(property: KtProperty) = property.isTopLevel || property.parent is KtClassBody override fun visitClassInitializer(initializer: KtClassInitializer) { analyze(initializer.body ?: return) } override fun visitNamedFunction(function: KtNamedFunction) { val body = function.bodyExpression ?: function.bodyBlockExpression ?: return analyze(body) } private fun analyze(body: KtExpression) { val factory = DfaValueFactory(holder.project) processDataflowAnalysis(factory, body, holder, listOf(JvmDfaMemoryStateImpl(factory))) } } } private fun processDataflowAnalysis( factory: DfaValueFactory, body: KtExpression, holder: ProblemsHolder, states: Collection<DfaMemoryState> ) { val flow = DataFlowIRProvider.forElement(body, factory) ?: return val listener = KotlinDfaListener() val interpreter = StandardDataFlowInterpreter(flow, listener) if (interpreter.interpret(states.map { s -> DfaInstructionState(flow.getInstruction(0), s) }) != RunnerResult.OK) return reportProblems(listener, holder) for ((closure, closureStates) in interpreter.closures.entrySet()) { if (closure is KtExpression) { processDataflowAnalysis(factory, closure, holder, closureStates) } } } private fun reportProblems( listener: KotlinDfaListener, holder: ProblemsHolder ) { listener.constantConditions.forEach { (anchor, cv) -> if (cv != ConstantValue.UNKNOWN) { when (anchor) { is KotlinExpressionAnchor -> { val expr = anchor.expression if (!shouldSuppress(cv, expr)) { val key = when (cv) { ConstantValue.TRUE -> if (shouldReportAsValue(expr)) "inspection.message.value.always.true" else if (logicalChain(expr)) "inspection.message.condition.always.true.when.reached" else "inspection.message.condition.always.true" ConstantValue.FALSE -> if (shouldReportAsValue(expr)) "inspection.message.value.always.false" else if (logicalChain(expr)) "inspection.message.condition.always.false.when.reached" else "inspection.message.condition.always.false" ConstantValue.NULL -> "inspection.message.value.always.null" ConstantValue.ZERO -> "inspection.message.value.always.zero" else -> throw IllegalStateException("Unexpected constant: $cv") } val highlightType = if (shouldReportAsValue(expr)) ProblemHighlightType.WEAK_WARNING else ProblemHighlightType.GENERIC_ERROR_OR_WARNING holder.registerProblem(expr, KotlinBundle.message(key, expr.text), highlightType) } } is KotlinWhenConditionAnchor -> { val condition = anchor.condition if (!shouldSuppressWhenCondition(cv, condition)) { val message = KotlinBundle.message("inspection.message.when.condition.always.false") if (cv == ConstantValue.FALSE) { holder.registerProblem(condition, message) } else if (cv == ConstantValue.TRUE) { condition.siblings(forward = true, withSelf = false) .filterIsInstance<KtWhenCondition>() .forEach { cond -> holder.registerProblem(cond, message) } val nextEntry = condition.parent as? KtWhenEntry ?: return@forEach nextEntry.siblings(forward = true, withSelf = false) .filterIsInstance<KtWhenEntry>() .filterNot { entry -> entry.isElse } .flatMap { entry -> entry.conditions.asSequence() } .forEach { cond -> holder.registerProblem(cond, message) } } } } is KotlinForVisitedAnchor -> { val loopRange = anchor.forExpression.loopRange!! if (cv == ConstantValue.FALSE && !shouldSuppressForCondition(loopRange)) { val message = KotlinBundle.message("inspection.message.for.never.visited") holder.registerProblem(loopRange, message) } } } } } listener.problems.forEach { (problem, state) -> if (state == ThreeState.YES) { when (problem) { is KotlinArrayIndexProblem -> holder.registerProblem(problem.index, KotlinBundle.message("inspection.message.index.out.of.bounds")) is KotlinNullCheckProblem -> { val expr = problem.expr if (expr.baseExpression?.isNull() != true) { holder.registerProblem(expr.operationReference, KotlinBundle.message("inspection.message.nonnull.cast.will.always.fail")) } } is KotlinCastProblem -> { val anchor = (problem.cast as? KtBinaryExpressionWithTypeRHS)?.operationReference ?: problem.cast if (!isCompilationWarning(anchor)) { holder.registerProblem(anchor, KotlinBundle.message("inspection.message.cast.will.always.fail")) } } } } } } private fun shouldSuppressForCondition(loopRange: KtExpression): Boolean { if (loopRange is KtBinaryExpression) { val left = loopRange.left val right = loopRange.right // Reported separately by EmptyRangeInspection return left != null && right != null && left.isConstant() && right.isConstant() } return false } private fun shouldReportAsValue(expr: KtExpression) = expr is KtSimpleNameExpression || expr is KtQualifiedExpression && expr.selectorExpression is KtSimpleNameExpression private fun logicalChain(expr: KtExpression): Boolean { var context = expr var parent = context.parent while (parent is KtParenthesizedExpression) { context = parent parent = context.parent } if (parent is KtBinaryExpression && parent.right == context) { val token = parent.operationToken return token == KtTokens.ANDAND || token == KtTokens.OROR } return false } private fun shouldSuppressWhenCondition( cv: ConstantValue, condition: KtWhenCondition ): Boolean { if (cv != ConstantValue.FALSE && cv != ConstantValue.TRUE) return true if (cv == ConstantValue.TRUE && isLastCondition(condition)) return true if (condition.textLength == 0) return true return isCompilationWarning(condition) } private fun isLastCondition(condition: KtWhenCondition): Boolean { val entry = condition.parent as? KtWhenEntry ?: return false val whenExpr = entry.parent as? KtWhenExpression ?: return false if (entry.conditions.last() == condition) { val entries = whenExpr.entries val lastEntry = entries.last() if (lastEntry == entry) return true val size = entries.size // Also, do not report the always reachable entry right before 'else', // usually it's necessary for the smart-cast, or for definite assignment, and the report is just noise if (lastEntry.isElse && size > 1 && entries[size - 2] == entry) return true } return false } companion object { private fun areEquivalent(e1: KtElement, e2: KtElement): Boolean { return PsiEquivalenceUtil.areEquivalent(e1, e2, {ref1, ref2 -> ref1.element.text.equals(ref2.element.text)}, null, null, false) } private tailrec fun isOppositeCondition(candidate: KtExpression?, template: KtBinaryExpression, expression: KtExpression): Boolean { if (candidate !is KtBinaryExpression || candidate.operationToken !== KtTokens.ANDAND) return false val left = candidate.left val right = candidate.right if (left == null || right == null) return false val templateLeft = template.left val templateRight = template.right if (templateLeft == null || templateRight == null) return false if (templateRight === expression) { return areEquivalent(left, templateLeft) && areEquivalent(right.negate(false), templateRight) } if (!areEquivalent(right, templateRight)) return false if (templateLeft === expression) { return areEquivalent(left.negate(false), templateLeft) } if (templateLeft !is KtBinaryExpression || templateLeft.operationToken !== KtTokens.ANDAND) return false return isOppositeCondition(left, templateLeft, expression) } private fun hasOppositeCondition(whenExpression: KtWhenExpression, topCondition: KtExpression, expression: KtExpression): Boolean { for (entry in whenExpression.entries) { for (condition in entry.conditions) { if (condition is KtWhenConditionWithExpression) { val candidate = condition.expression if (candidate === topCondition) return false if (topCondition is KtBinaryExpression && isOppositeCondition(candidate, topCondition, expression)) return true if (candidate != null && areEquivalent(expression.negate(false), candidate)) return true } } } return false } /** * Returns true if expression is part of when condition expression that looks like * ``` * when { * a && b -> ... * a && !b -> ... * } * ``` * In this case, !b could be reported as 'always true' but such warnings are annoying */ private fun isPairingConditionInWhen(expression: KtExpression): Boolean { val parent = expression.parent if (parent is KtBinaryExpression && parent.operationToken == KtTokens.ANDAND) { var topAnd: KtBinaryExpression = parent while (true) { val nextParent = topAnd.parent if (nextParent is KtBinaryExpression && nextParent.operationToken == KtTokens.ANDAND) { topAnd = nextParent } else break } val topAndParent = topAnd.parent if (topAndParent is KtWhenConditionWithExpression) { val whenExpression = (topAndParent.parent as? KtWhenEntry)?.parent as? KtWhenExpression if (whenExpression != null && hasOppositeCondition(whenExpression, topAnd, expression)) { return true } } } if (parent is KtWhenConditionWithExpression) { val whenExpression = (parent.parent as? KtWhenEntry)?.parent as? KtWhenExpression if (whenExpression != null && hasOppositeCondition(whenExpression, expression, expression)) { return true } } return false } private fun isCompilationWarning(anchor: KtElement): Boolean { val context = anchor.analyze(BodyResolveMode.FULL) if (context.diagnostics.forElement(anchor).any { it.factory == Errors.CAST_NEVER_SUCCEEDS || it.factory == Errors.SENSELESS_COMPARISON || it.factory == Errors.SENSELESS_NULL_IN_WHEN || it.factory == Errors.USELESS_IS_CHECK || it.factory == Errors.DUPLICATE_LABEL_IN_WHEN } ) { return true } val rootElement = anchor.containingFile val suppressionCache = KotlinCacheService.getInstance(anchor.project).getSuppressionCache() return suppressionCache.isSuppressed(anchor, rootElement, "CAST_NEVER_SUCCEEDS", Severity.WARNING) || suppressionCache.isSuppressed(anchor, rootElement, "SENSELESS_COMPARISON", Severity.WARNING) || suppressionCache.isSuppressed(anchor, rootElement, "SENSELESS_NULL_IN_WHEN", Severity.WARNING) || suppressionCache.isSuppressed(anchor, rootElement, "USELESS_IS_CHECK", Severity.WARNING) || suppressionCache.isSuppressed(anchor, rootElement, "DUPLICATE_LABEL_IN_WHEN", Severity.WARNING) } private fun isCallToMethod(call: KtCallExpression, packageName: String, methodName: String): Boolean { val descriptor = call.resolveToCall()?.resultingDescriptor ?: return false if (descriptor.name.asString() != methodName) return false val packageFragment = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false return packageFragment.fqName.asString() == packageName } // Do not report x.let { true } or x.let { false } as it's pretty evident private fun isLetConstant(expr: KtExpression): Boolean { val call = (expr as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression ?: return false if (!isCallToMethod(call, "kotlin", "let")) return false val lambda = call.lambdaArguments.singleOrNull()?.getLambdaExpression() ?: return false return lambda.bodyExpression?.statements?.singleOrNull() is KtConstantExpression } // Do not report on also, as it always returns the qualifier. If necessary, qualifier itself will be reported private fun isAlsoChain(expr: KtExpression): Boolean { val call = (expr as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression ?: return false return isCallToMethod(call, "kotlin", "also") } private fun isAssertion(parent: PsiElement?, value: Boolean): Boolean { return when (parent) { is KtBinaryExpression -> (parent.operationToken == KtTokens.ANDAND || parent.operationToken == KtTokens.OROR) && isAssertion(parent.parent, value) is KtParenthesizedExpression -> isAssertion(parent.parent, value) is KtPrefixExpression -> parent.operationToken == KtTokens.EXCL && isAssertion(parent.parent, !value) is KtValueArgument -> { if (!value) return false val valueArgList = parent.parent as? KtValueArgumentList ?: return false val call = valueArgList.parent as? KtCallExpression ?: return false val descriptor = call.resolveToCall()?.resultingDescriptor ?: return false val name = descriptor.name.asString() if (name != "assert" && name != "require" && name != "check") return false val pkg = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false return pkg.fqName.asString() == "kotlin" } else -> false } } private fun hasWritesTo(block: PsiElement?, variable: KtProperty): Boolean { return !PsiTreeUtil.processElements(block, KtSimpleNameExpression::class.java) { ref -> val write = ref.mainReference.isReferenceTo(variable) && ref.readWriteAccess(false).isWrite !write } } private fun isUpdateChain(expression: KtExpression): Boolean { // x = x or ..., etc. if (expression !is KtSimpleNameExpression) return false val binOp = expression.parent as? KtBinaryExpression ?: return false val op = binOp.operationReference.text if (op != "or" && op != "and" && op != "xor" && op != "||" && op != "&&") return false val assignment = binOp.parent as? KtBinaryExpression ?: return false if (assignment.operationToken != KtTokens.EQ) return false val left = assignment.left if (left !is KtSimpleNameExpression || !left.textMatches(expression.text)) return false val variable = expression.mainReference.resolve() as? KtProperty ?: return false val varParent = variable.parent as? KtBlockExpression ?: return false var context: PsiElement = assignment var block = context.parent while (block is KtContainerNode || block is KtBlockExpression && block.statements.first() == context || block is KtIfExpression && block.then?.parent == context && block.`else` == null && !hasWritesTo(block.condition, variable) ) { context = block block = context.parent } if (block !== varParent) return false var curExpression = variable.nextSibling while (curExpression != context) { if (hasWritesTo(curExpression, variable)) return false curExpression = curExpression.nextSibling } return true } fun shouldSuppress(value: DfType, expression: KtExpression): Boolean { val constant = when(value) { DfTypes.NULL -> ConstantValue.NULL DfTypes.TRUE -> ConstantValue.TRUE DfTypes.FALSE -> ConstantValue.FALSE DfTypes.intValue(0), DfTypes.longValue(0) -> ConstantValue.ZERO else -> ConstantValue.UNKNOWN } return shouldSuppress(constant, expression) } private fun shouldSuppress(value: ConstantValue, expression: KtExpression): Boolean { // TODO: return x && y.let {return...} var parent = expression.parent if (parent is KtDotQualifiedExpression && parent.selectorExpression == expression) { // Will be reported for parent qualified expression return true } while (parent is KtParenthesizedExpression) { parent = parent.parent } if (expression is KtConstantExpression || // If result of initialization is constant, then the initializer will be reported expression is KtProperty || // If result of assignment is constant, then the right-hand part will be reported expression is KtBinaryExpression && expression.operationToken == KtTokens.EQ || // Negation operand: negation itself will be reported (parent as? KtPrefixExpression)?.operationToken == KtTokens.EXCL ) { return true } if (expression is KtBinaryExpression && expression.operationToken == KtTokens.ELVIS) { // Left part of Elvis is Nothing?, so the right part is always executed // Could be caused by code like return x?.let { return ... } ?: true // While inner "return" is redundant, the "always true" warning is confusing // probably separate inspection could report extra "return" if (expression.left?.getKotlinType()?.isNullableNothing() == true) { return true } } if (isAlsoChain(expression) || isLetConstant(expression) || isUpdateChain(expression)) return true when (value) { ConstantValue.TRUE -> { if (isAndOrConditionWithNothingOperand(expression, KtTokens.OROR)) return true if (isSmartCastNecessary(expression, true)) return true if (isPairingConditionInWhen(expression)) return true if (isAssertion(parent, true)) return true } ConstantValue.FALSE -> { if (isAndOrConditionWithNothingOperand(expression, KtTokens.ANDAND)) return true if (isSmartCastNecessary(expression, false)) return true if (isAssertion(parent, false)) return true } ConstantValue.ZERO -> { if (expression.readWriteAccess(false).isWrite) { // like if (x == 0) x++, warning would be somewhat annoying return true } if (expression is KtDotQualifiedExpression && expression.selectorExpression?.textMatches("ordinal") == true) { var receiver: KtExpression? = expression.receiverExpression if (receiver is KtQualifiedExpression) { receiver = receiver.selectorExpression } if (receiver is KtSimpleNameExpression && receiver.resolveMainReferenceToDescriptors() .any { desc -> desc is ClassDescriptor && desc.kind == ClassKind.ENUM_ENTRY } ) { // ordinal() call on explicit enum constant return true } } val bindingContext = expression.analyze() if (ConstantExpressionEvaluator.getConstant(expression, bindingContext) != null) return true if (expression is KtSimpleNameExpression && (parent is KtValueArgument || parent is KtContainerNode && parent.parent is KtArrayAccessExpression) ) { // zero value is passed as argument to another method or used for array access. Often, such a warning is annoying return true } } ConstantValue.NULL -> { if (parent is KtProperty && parent.typeReference == null && expression is KtSimpleNameExpression) { // initialize other variable with null to copy type, like // var x1 : X = null // var x2 = x1 -- let's suppress this return true } if (expression is KtBinaryExpressionWithTypeRHS && expression.left.isNull()) { // like (null as? X) return true } if (parent is KtBinaryExpression) { val token = parent.operationToken if ((token === KtTokens.EQEQ || token === KtTokens.EXCLEQ || token === KtTokens.EQEQEQ || token === KtTokens.EXCLEQEQEQ) && (parent.left?.isNull() == true || parent.right?.isNull() == true) ) { // like if (x == null) when 'x' is known to be null: report 'always true' instead return true } } val kotlinType = expression.getKotlinType() if (kotlinType.toDfType() == DfTypes.NULL) { // According to type system, nothing but null could be stored in such an expression (likely "Void?" type) return true } } else -> {} } if (expression is KtSimpleNameExpression) { val target = expression.mainReference.resolve() if (target is KtProperty && !target.isVar && target.initializer is KtConstantExpression) { // suppress warnings uses of boolean constant like 'val b = true' return true } } if (isCompilationWarning(expression)) { return true } return expression.isUsedAsStatement(expression.analyze(BodyResolveMode.FULL)) } // x || return y private fun isAndOrConditionWithNothingOperand(expression: KtExpression, token: KtSingleValueToken): Boolean { if (expression !is KtBinaryExpression || expression.operationToken != token) return false val type = expression.right?.getKotlinType() return type != null && type.isNothing() } } }
apache-2.0
07035d772fc6a0b0695b7cb4da630970
52.086667
158
0.585759
5.933495
false
false
false
false
allotria/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/left/ModuleContextComboBox.kt
1
2250
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.left import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.util.NlsActions import com.intellij.openapi.util.NlsActions.ActionText import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageSearchToolWindowModel import org.jetbrains.annotations.Nls import javax.swing.JLabel class ModuleContextComboBox(viewModel: PackageSearchToolWindowModel) : ContextComboBoxBase(viewModel) { override fun createNameLabel() = JLabel("") override fun createValueLabel() = object : JLabel() { override fun getIcon() = viewModel.selectedProjectModule.value?.moduleType?.icon ?: AllIcons.General.ProjectStructure override fun getText() = viewModel.selectedProjectModule.value?.name ?: PackageSearchBundle.message("packagesearch.ui.toolwindow.allModules") } override fun createActionGroup(): ActionGroup { return DefaultActionGroup( createSelectProjectAction(), DefaultActionGroup(createSelectModuleActions()) ) } private fun createSelectProjectAction() = createSelectAction(null, PackageSearchBundle.message("packagesearch.ui.toolwindow.allModules")) private fun createSelectModuleActions(): List<AnAction> = viewModel.projectModules.value .sortedBy { it.getFullName() } .map { createSelectAction(it, it.getFullName()) } private fun createSelectAction(projectModule: ProjectModule?, @ActionText title: String) = object : AnAction(title, title, projectModule?.moduleType?.icon ?: AllIcons.General.ProjectStructure) { override fun actionPerformed(e: AnActionEvent) { viewModel.selectedProjectModule.set(projectModule) updateLabel() } } }
apache-2.0
a9426ada1b8f2481400cdb4ee8fea845
44
141
0.747111
5.369928
false
false
false
false
Skatteetaten/boober
src/test/kotlin/no/skatteetaten/aurora/boober/utils/UrlParserTest.kt
1
14104
package no.skatteetaten.aurora.boober.utils import no.skatteetaten.aurora.boober.service.UrlValidationException import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows class UrlParserTest { // Test data private val httpUrl = "http://hostname" private val httpUrlWithPort = "http://hostname:6543" private val httpUrlWithPath = "http://hostname/path/secondPath" private val httpUrlWithSlash = "http://hostname/" private val httpUrlWithQuery = "http://hostname?param1=some_arg&param2=another_arg" private val httpUrlWithPortPathSlashAndQuery = "http://hostname:6543/path/?param=some_arg" private val httpsUrl = "https://hostname" private val jdbcPostgresUrl = "jdbc:postgresql://hostname/dbname" private val jdbcPostgresUrlWithoutHostname = "jdbc:postgresql:dbname" private val jdbcPostgresUrlWithPort = "jdbc:postgresql://hostname:6543/dbname" private val jdbcPostgresUrlWithQuery = "jdbc:postgresql://hostname/dbname?param1=some_arg&param2=another_arg" private val jdbcPostgresUrlWithPortAndQuery = "jdbc:postgresql://hostname:6543/dbname?param=some_arg" private val jdbcOracleUrl = "jdbc:oracle:thin:@hostname" private val jdbcOracleUrlWithPort = "jdbc:oracle:thin:@hostname:6543" private val jdbcOracleUrlWithService = "jdbc:oracle:thin:@hostname/service" private val jdbcOracleUrlWithMode = "jdbc:oracle:thin:@hostname:mode" private val jdbcOracleUrlWithQuery = "jdbc:oracle:thin:@hostname?param1=some_arg&param2=another_arg" private val jdbcOracleUrlWithPortAndService = "jdbc:oracle:thin:@hostname:6543/service" private val jdbcOracleUrlWithPortAndMode = "jdbc:oracle:thin:@hostname:6543:mode" private val jdbcOracleUrlWithPortServiceAndMode = "jdbc:oracle:thin:@hostname:6543/service:mode" private val jdbcOracleUrlWithPortServiceModeAndQuery = "jdbc:oracle:thin:@hostname:6543/service:mode?param=arg" private val jdbcOracleUrlWithDoubleSlash = "jdbc:oracle:thin:@//hostname" private val jdbcOracleUrlWithProtocol = "jdbc:oracle:thin:@protocol://hostname" private val jdbcOracleUrlWithProtocolPortServiceModeAndQuery = "jdbc:oracle:thin:@protocol://hostname:6543/service:mode?param=arg" private val httpUrls = listOf( httpUrl, httpUrlWithPort, httpUrlWithPath, httpUrlWithSlash, httpUrlWithQuery, httpUrlWithPortPathSlashAndQuery ) private val httpsUrls = listOf(httpsUrl) private val jdbcPosgresUrls = listOf( jdbcPostgresUrl, jdbcPostgresUrlWithoutHostname, jdbcPostgresUrlWithPort, jdbcPostgresUrlWithQuery, jdbcPostgresUrlWithPortAndQuery ) private val jdbcOracleUrls = listOf( jdbcOracleUrl, jdbcOracleUrlWithPort, jdbcOracleUrlWithService, jdbcOracleUrlWithMode, jdbcOracleUrlWithQuery, jdbcOracleUrlWithPortAndService, jdbcOracleUrlWithPortAndMode, jdbcOracleUrlWithPortServiceAndMode, jdbcOracleUrlWithPortServiceModeAndQuery, jdbcOracleUrlWithDoubleSlash, jdbcOracleUrlWithProtocol, jdbcOracleUrlWithProtocolPortServiceModeAndQuery ) private val validUrls = listOf( httpUrls, httpsUrls, jdbcPosgresUrls, jdbcOracleUrls ).flatten() private val misspelledHttpUrl = "http:/hostname" private val misspelledJdbcPostgresUrl = "jdbc:postgres/hostname/dbname" private val misspelledJdbcOracleUrl = "jdbc:oracle:thing:@hostname" @Test fun `Validation works as expected`() { validUrls.forEach { with(UrlParser(it)) { assertTrue { this.isValid() } this.assertIsValid() } } listOf( misspelledHttpUrl, misspelledJdbcPostgresUrl, misspelledJdbcOracleUrl ).forEach { with(UrlParser(it)) { assertFalse(this.isValid()) assertThrows<UrlValidationException> { this.assertIsValid() } } } } @Test fun `Hostname can be extracted from url`() { validUrls.forEach { assertEquals( if (it.contains("hostname")) "hostname" else "localhost", UrlParser(it).hostName ) } } @Test fun `Port can be extracted from url`() { httpUrls.forEach { assertEquals( if (it.contains("6543")) 6543 else 80, UrlParser(it).port ) } httpsUrls.forEach { assertEquals( if (it.contains("6543")) 6543 else 443, UrlParser(it).port ) } jdbcPosgresUrls.forEach { assertEquals( if (it.contains("6543")) 6543 else 5432, UrlParser(it).port ) } jdbcOracleUrls.forEach { assertEquals( if (it.contains("6543")) 6543 else 1521, UrlParser(it).port ) } } @Test fun `Suffix can be extracted from url`() { mapOf( httpUrl to "", httpUrlWithPort to "", httpUrlWithPath to "/path/secondPath", httpUrlWithSlash to "/", httpUrlWithQuery to "?param1=some_arg&param2=another_arg", httpUrlWithPortPathSlashAndQuery to "/path/?param=some_arg", httpsUrl to "", jdbcPostgresUrl to "/dbname", jdbcPostgresUrlWithoutHostname to "/dbname", jdbcPostgresUrlWithPort to "/dbname", jdbcPostgresUrlWithQuery to "/dbname?param1=some_arg&param2=another_arg", jdbcPostgresUrlWithPortAndQuery to "/dbname?param=some_arg", jdbcOracleUrl to "", jdbcOracleUrlWithPort to "", jdbcOracleUrlWithService to "/service", jdbcOracleUrlWithMode to ":mode", jdbcOracleUrlWithQuery to "?param1=some_arg&param2=another_arg", jdbcOracleUrlWithPortAndService to "/service", jdbcOracleUrlWithPortAndMode to ":mode", jdbcOracleUrlWithPortServiceAndMode to "/service:mode", jdbcOracleUrlWithPortServiceModeAndQuery to "/service:mode?param=arg", jdbcOracleUrlWithDoubleSlash to "", jdbcOracleUrlWithProtocol to "", jdbcOracleUrlWithProtocolPortServiceModeAndQuery to "/service:mode?param=arg" ).forEach { (input, expectedOutput) -> assertEquals(expectedOutput, UrlParser(input).suffix) } } @Test fun `Generates string with default values`() { mapOf( httpUrl to "http://hostname:80", httpUrlWithPort to "http://hostname:6543", httpUrlWithPath to "http://hostname:80/path/secondPath", httpUrlWithSlash to "http://hostname:80/", httpUrlWithQuery to "http://hostname:80?param1=some_arg&param2=another_arg", httpUrlWithPortPathSlashAndQuery to "http://hostname:6543/path/?param=some_arg", httpsUrl to "https://hostname:443", jdbcPostgresUrl to "jdbc:postgresql://hostname:5432/dbname", jdbcPostgresUrlWithoutHostname to "jdbc:postgresql://localhost:5432/dbname", jdbcPostgresUrlWithPort to "jdbc:postgresql://hostname:6543/dbname", jdbcPostgresUrlWithQuery to "jdbc:postgresql://hostname:5432/dbname?param1=some_arg&param2=another_arg", jdbcPostgresUrlWithPortAndQuery to "jdbc:postgresql://hostname:6543/dbname?param=some_arg", jdbcOracleUrl to "jdbc:oracle:thin:@hostname:1521", jdbcOracleUrlWithPort to "jdbc:oracle:thin:@hostname:6543", jdbcOracleUrlWithService to "jdbc:oracle:thin:@hostname:1521/service", jdbcOracleUrlWithMode to "jdbc:oracle:thin:@hostname:1521:mode", jdbcOracleUrlWithQuery to "jdbc:oracle:thin:@hostname:1521?param1=some_arg&param2=another_arg", jdbcOracleUrlWithPortAndService to "jdbc:oracle:thin:@hostname:6543/service", jdbcOracleUrlWithPortAndMode to "jdbc:oracle:thin:@hostname:6543:mode", jdbcOracleUrlWithPortServiceAndMode to "jdbc:oracle:thin:@hostname:6543/service:mode", jdbcOracleUrlWithPortServiceModeAndQuery to "jdbc:oracle:thin:@hostname:6543/service:mode?param=arg", jdbcOracleUrlWithDoubleSlash to "jdbc:oracle:thin:@//hostname:1521", jdbcOracleUrlWithProtocol to "jdbc:oracle:thin:@protocol://hostname:1521", jdbcOracleUrlWithProtocolPortServiceModeAndQuery to "jdbc:oracle:thin:@protocol://hostname:6543/service:mode?param=arg" ).forEach { (input, expectedOutput) -> assertEquals(expectedOutput, UrlParser(input).makeString()) } } @Test fun `Generates url with modified host name`() { validUrls.forEach { assertEquals( "newName.domain", UrlParser(it).withModifiedHostName("newName.domain").hostName ) } mapOf( httpUrl to "http://newName.domain:80", httpUrlWithPort to "http://newName.domain:6543", httpUrlWithPath to "http://newName.domain:80/path/secondPath", httpUrlWithSlash to "http://newName.domain:80/", httpUrlWithQuery to "http://newName.domain:80?param1=some_arg&param2=another_arg", httpUrlWithPortPathSlashAndQuery to "http://newName.domain:6543/path/?param=some_arg", httpsUrl to "https://newName.domain:443", jdbcPostgresUrl to "jdbc:postgresql://newName.domain:5432/dbname", jdbcPostgresUrlWithoutHostname to "jdbc:postgresql://newName.domain:5432/dbname", jdbcPostgresUrlWithPort to "jdbc:postgresql://newName.domain:6543/dbname", jdbcPostgresUrlWithQuery to "jdbc:postgresql://newName.domain:5432/dbname?param1=some_arg&param2=another_arg", jdbcPostgresUrlWithPortAndQuery to "jdbc:postgresql://newName.domain:6543/dbname?param=some_arg", jdbcOracleUrl to "jdbc:oracle:thin:@newName.domain:1521", jdbcOracleUrlWithPort to "jdbc:oracle:thin:@newName.domain:6543", jdbcOracleUrlWithService to "jdbc:oracle:thin:@newName.domain:1521/service", jdbcOracleUrlWithMode to "jdbc:oracle:thin:@newName.domain:1521:mode", jdbcOracleUrlWithQuery to "jdbc:oracle:thin:@newName.domain:1521?param1=some_arg&param2=another_arg", jdbcOracleUrlWithPortAndService to "jdbc:oracle:thin:@newName.domain:6543/service", jdbcOracleUrlWithPortAndMode to "jdbc:oracle:thin:@newName.domain:6543:mode", jdbcOracleUrlWithPortServiceAndMode to "jdbc:oracle:thin:@newName.domain:6543/service:mode", jdbcOracleUrlWithPortServiceModeAndQuery to "jdbc:oracle:thin:@newName.domain:6543/service:mode?param=arg", jdbcOracleUrlWithDoubleSlash to "jdbc:oracle:thin:@//newName.domain:1521", jdbcOracleUrlWithProtocol to "jdbc:oracle:thin:@protocol://newName.domain:1521", jdbcOracleUrlWithProtocolPortServiceModeAndQuery to "jdbc:oracle:thin:@protocol://newName.domain:6543/service:mode?param=arg" ).forEach { (input, expectedOutput) -> assertEquals( expectedOutput, UrlParser(input).withModifiedHostName("newName.domain").makeString() ) } } @Test fun `Generates url with modified port`() { validUrls.forEach { assertEquals( 18000, UrlParser(it).withModifiedPort(18000).port ) } mapOf( httpUrl to "http://hostname:18000", httpUrlWithPort to "http://hostname:18000", httpUrlWithPath to "http://hostname:18000/path/secondPath", httpUrlWithSlash to "http://hostname:18000/", httpUrlWithQuery to "http://hostname:18000?param1=some_arg&param2=another_arg", httpUrlWithPortPathSlashAndQuery to "http://hostname:18000/path/?param=some_arg", httpsUrl to "https://hostname:18000", jdbcPostgresUrl to "jdbc:postgresql://hostname:18000/dbname", jdbcPostgresUrlWithoutHostname to "jdbc:postgresql://localhost:18000/dbname", jdbcPostgresUrlWithPort to "jdbc:postgresql://hostname:18000/dbname", jdbcPostgresUrlWithQuery to "jdbc:postgresql://hostname:18000/dbname?param1=some_arg&param2=another_arg", jdbcPostgresUrlWithPortAndQuery to "jdbc:postgresql://hostname:18000/dbname?param=some_arg", jdbcOracleUrl to "jdbc:oracle:thin:@hostname:18000", jdbcOracleUrlWithPort to "jdbc:oracle:thin:@hostname:18000", jdbcOracleUrlWithService to "jdbc:oracle:thin:@hostname:18000/service", jdbcOracleUrlWithMode to "jdbc:oracle:thin:@hostname:18000:mode", jdbcOracleUrlWithQuery to "jdbc:oracle:thin:@hostname:18000?param1=some_arg&param2=another_arg", jdbcOracleUrlWithPortAndService to "jdbc:oracle:thin:@hostname:18000/service", jdbcOracleUrlWithPortAndMode to "jdbc:oracle:thin:@hostname:18000:mode", jdbcOracleUrlWithPortServiceAndMode to "jdbc:oracle:thin:@hostname:18000/service:mode", jdbcOracleUrlWithPortServiceModeAndQuery to "jdbc:oracle:thin:@hostname:18000/service:mode?param=arg", jdbcOracleUrlWithDoubleSlash to "jdbc:oracle:thin:@//hostname:18000", jdbcOracleUrlWithProtocol to "jdbc:oracle:thin:@protocol://hostname:18000", jdbcOracleUrlWithProtocolPortServiceModeAndQuery to "jdbc:oracle:thin:@protocol://hostname:18000/service:mode?param=arg" ).forEach { (input, expectedOutput) -> assertEquals( expectedOutput, UrlParser(input).withModifiedPort(18000).makeString() ) } } }
apache-2.0
148a201dde9df8c2bb3fbb3a81bca0a2
46.972789
137
0.66669
5.250931
false
false
false
false
Kotlin/kotlinx.coroutines
benchmarks/src/jmh/kotlin/benchmarks/akka/StatefulActorAkkaBenchmark.kt
1
6462
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package benchmarks.akka import akka.actor.* import com.typesafe.config.* import org.openjdk.jmh.annotations.* import scala.concurrent.* import scala.concurrent.duration.* import java.util.concurrent.* const val ROUNDS = 10_000 const val STATE_SIZE = 1024 val CORES_COUNT = Runtime.getRuntime().availableProcessors() /* * Benchmarks following computation pattern: * N actors, each has independent state (coefficients), receives numbers and answers with product and * N requestors, which randomly send requests. N roundtrips over every requestor are measured * * Benchmark (dispatcher) Mode Cnt Score Error Units * StatefulActorAkkaBenchmark.multipleComputationsMultipleRequestors default-dispatcher avgt 14 72.568 ± 10.620 ms/op * StatefulActorAkkaBenchmark.multipleComputationsMultipleRequestors single-thread-dispatcher avgt 14 70.198 ± 3.594 ms/op * * StatefulActorAkkaBenchmark.multipleComputationsSingleRequestor default-dispatcher avgt 14 36.737 ± 3.589 ms/op * StatefulActorAkkaBenchmark.multipleComputationsSingleRequestor single-thread-dispatcher avgt 14 9.050 ± 0.385 ms/op * * StatefulActorAkkaBenchmark.singleComputationMultipleRequestors default-dispatcher avgt 14 446.563 ± 85.577 ms/op * StatefulActorAkkaBenchmark.singleComputationMultipleRequestors single-thread-dispatcher avgt 14 70.250 ± 3.104 ms/op * * StatefulActorAkkaBenchmark.singleComputationSingleRequestor default-dispatcher avgt 14 39.964 ± 2.343 ms/op * StatefulActorAkkaBenchmark.singleComputationSingleRequestor single-thread-dispatcher avgt 14 10.214 ± 2.152 ms/op */ //@Warmup(iterations = 7, time = 1, timeUnit = TimeUnit.SECONDS) //@Measurement(iterations = 7, time = 1, timeUnit = TimeUnit.SECONDS) //@Fork(value = 2) //@BenchmarkMode(Mode.AverageTime) //@OutputTimeUnit(TimeUnit.MILLISECONDS) //@State(Scope.Benchmark) open class StatefulActorAkkaBenchmark { lateinit var system: ActorSystem @Param("default-dispatcher", "single-thread-dispatcher") var dispatcher: String = "akka.actor.default-dispatcher" @Setup fun setup() { // TODO extract it to common AkkaBase if new benchmark will appear system = ActorSystem.create("StatefulActors", ConfigFactory.parseString(""" akka.actor.single-thread-dispatcher { type = Dispatcher executor = "thread-pool-executor" thread-pool-executor { fixed-pool-size = 1 } throughput = 1 } """.trimIndent() )) } @TearDown fun tearDown() { Await.ready(system.terminate(), Duration.Inf()) } // @Benchmark fun singleComputationSingleRequestor() { run(1, 1) } // @Benchmark fun singleComputationMultipleRequestors() { run(1, CORES_COUNT) } // @Benchmark fun multipleComputationsSingleRequestor() { run(CORES_COUNT, 1) } // @Benchmark fun multipleComputationsMultipleRequestors() { run(CORES_COUNT, CORES_COUNT) } private fun run(computationActors: Int, requestorActors: Int) { val stopLatch = CountDownLatch(requestorActors) /* * For complex setups Akka creates actors slowly, * so first start message may become dead letter (and freeze benchmark) */ val initLatch = CountDownLatch(computationActors + requestorActors) val computations = createComputationActors(initLatch, computationActors) val requestors = createRequestorActors(requestorActors, computations, initLatch, stopLatch) initLatch.await() for (requestor in requestors) { requestor.tell(1L, ActorRef.noSender()) } stopLatch.await() computations.forEach { it.tell(Stop(), ActorRef.noSender()) } } private fun createRequestorActors(requestorActors: Int, computations: List<ActorRef>, initLatch: CountDownLatch, stopLatch: CountDownLatch): List<ActorRef> { return (0 until requestorActors).map { system.actorOf(Props.create(RequestorActor::class.java, computations, initLatch, stopLatch) .withDispatcher("akka.actor.$dispatcher")) } } private fun createComputationActors(initLatch: CountDownLatch, count: Int): List<ActorRef> { return (0 until count).map { system.actorOf(Props.create( ComputationActor::class.java, LongArray(STATE_SIZE) { ThreadLocalRandom.current().nextLong(0, 100) }, initLatch) .withDispatcher("akka.actor.$dispatcher")) } } class RequestorActor(val computations: List<ActorRef>, val initLatch: CountDownLatch, val stopLatch: CountDownLatch) : UntypedAbstractActor() { private var received = 0 override fun onReceive(message: Any?) { when (message) { is Long -> { if (++received >= ROUNDS) { context.stop(self) stopLatch.countDown() } else { computations[ThreadLocalRandom.current().nextInt(0, computations.size)] .tell(ThreadLocalRandom.current().nextLong(), self) } } else -> unhandled(message) } } override fun preStart() { initLatch.countDown() } } class ComputationActor(val coefficients: LongArray, val initLatch: CountDownLatch) : UntypedAbstractActor() { override fun onReceive(message: Any?) { when (message) { is Long -> { var result = 0L for (coefficient in coefficients) { result += coefficient * message } sender.tell(result, self) } is Stop -> { context.stop(self) } else -> unhandled(message) } } override fun preStart() { initLatch.countDown() } } }
apache-2.0
17e82761742385484abf76285ae70d67
36.964706
161
0.615432
4.885693
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/src/flow/operators/Transform.kt
1
4724
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:JvmMultifileClass @file:JvmName("FlowKt") @file:Suppress("UNCHECKED_CAST") package kotlinx.coroutines.flow import kotlinx.coroutines.* import kotlinx.coroutines.flow.internal.* import kotlin.jvm.* import kotlinx.coroutines.flow.internal.unsafeFlow as flow import kotlinx.coroutines.flow.unsafeTransform as transform /** * Returns a flow containing only values of the original flow that match the given [predicate]. */ public inline fun <T> Flow<T>.filter(crossinline predicate: suspend (T) -> Boolean): Flow<T> = transform { value -> if (predicate(value)) return@transform emit(value) } /** * Returns a flow containing only values of the original flow that do not match the given [predicate]. */ public inline fun <T> Flow<T>.filterNot(crossinline predicate: suspend (T) -> Boolean): Flow<T> = transform { value -> if (!predicate(value)) return@transform emit(value) } /** * Returns a flow containing only values that are instances of specified type [R]. */ @Suppress("UNCHECKED_CAST") public inline fun <reified R> Flow<*>.filterIsInstance(): Flow<R> = filter { it is R } as Flow<R> /** * Returns a flow containing only values of the original flow that are not null. */ public fun <T: Any> Flow<T?>.filterNotNull(): Flow<T> = transform<T?, T> { value -> if (value != null) return@transform emit(value) } /** * Returns a flow containing the results of applying the given [transform] function to each value of the original flow. */ public inline fun <T, R> Flow<T>.map(crossinline transform: suspend (value: T) -> R): Flow<R> = transform { value -> return@transform emit(transform(value)) } /** * Returns a flow that contains only non-null results of applying the given [transform] function to each value of the original flow. */ public inline fun <T, R: Any> Flow<T>.mapNotNull(crossinline transform: suspend (value: T) -> R?): Flow<R> = transform { value -> val transformed = transform(value) ?: return@transform return@transform emit(transformed) } /** * Returns a flow that wraps each element into [IndexedValue], containing value and its index (starting from zero). */ public fun <T> Flow<T>.withIndex(): Flow<IndexedValue<T>> = flow { var index = 0 collect { value -> emit(IndexedValue(checkIndexOverflow(index++), value)) } } /** * Returns a flow that invokes the given [action] **before** each value of the upstream flow is emitted downstream. */ public fun <T> Flow<T>.onEach(action: suspend (T) -> Unit): Flow<T> = transform { value -> action(value) return@transform emit(value) } /** * Folds the given flow with [operation], emitting every intermediate result, including [initial] value. * Note that initial value should be immutable (or should not be mutated) as it is shared between different collectors. * For example: * ``` * flowOf(1, 2, 3).scan(emptyList<Int>()) { acc, value -> acc + value }.toList() * ``` * will produce `[], [1], [1, 2], [1, 2, 3]`. * * This function is an alias to [runningFold] operator. */ public fun <T, R> Flow<T>.scan(initial: R, @BuilderInference operation: suspend (accumulator: R, value: T) -> R): Flow<R> = runningFold(initial, operation) /** * Folds the given flow with [operation], emitting every intermediate result, including [initial] value. * Note that initial value should be immutable (or should not be mutated) as it is shared between different collectors. * For example: * ``` * flowOf(1, 2, 3).runningFold(emptyList<Int>()) { acc, value -> acc + value }.toList() * ``` * will produce `[], [1], [1, 2], [1, 2, 3]`. */ public fun <T, R> Flow<T>.runningFold(initial: R, @BuilderInference operation: suspend (accumulator: R, value: T) -> R): Flow<R> = flow { var accumulator: R = initial emit(accumulator) collect { value -> accumulator = operation(accumulator, value) emit(accumulator) } } /** * Reduces the given flow with [operation], emitting every intermediate result, including initial value. * The first element is taken as initial value for operation accumulator. * This operator has a sibling with initial value -- [scan]. * * For example: * ``` * flowOf(1, 2, 3, 4).runningReduce { acc, value -> acc + value }.toList() * ``` * will produce `[1, 3, 6, 10]` */ public fun <T> Flow<T>.runningReduce(operation: suspend (accumulator: T, value: T) -> T): Flow<T> = flow { var accumulator: Any? = NULL collect { value -> accumulator = if (accumulator === NULL) { value } else { operation(accumulator as T, value) } emit(accumulator as T) } }
apache-2.0
8bd3ab46406a70f7380a8284805fd738
35.620155
155
0.677815
3.770152
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-integration/src/main/kotlin/slatekit/integration/apis/InfoApi.kt
1
1342
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.integration.apis import slatekit.apis.Api import slatekit.apis.Action import slatekit.apis.AuthModes import slatekit.apis.Verbs import slatekit.context.Context import slatekit.common.Sources import slatekit.requests.Request import slatekit.common.info.* @Api(area = "app", name = "info", desc = "api info about the application and host", auth = AuthModes.KEYED, roles = ["admin"], verb = Verbs.AUTO, sources = [Sources.ALL]) class InfoApi(val context: Context) { @Action(desc = "gets info about this build") fun build(): Build = context.info.build @Action(desc = "get info about the application") fun about(): About = context.info.about @Action(desc = "get info about the application") fun cmd(cmd: Request): About = context.info.about @Action(desc = "gets info about the language") fun lang(): Lang = context.info.lang @Action(desc = "gets info about the folders") fun dirs(): Folders = context.dirs ?: Folders.none }
apache-2.0
7d318ccde3b7ce1b010bb91cd6bcb651
26.958333
94
0.704918
3.727778
false
false
false
false
leafclick/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/search/GithubPullRequestSearchQuery.kt
1
5192
// 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.github.pullrequest.search import org.jetbrains.plugins.github.api.data.GithubIssueState import org.jetbrains.plugins.github.api.data.request.search.GithubIssueSearchSort import org.jetbrains.plugins.github.api.util.GithubApiSearchQueryBuilder import java.text.ParseException import java.text.SimpleDateFormat internal class GithubPullRequestSearchQuery(private val terms: List<Term<*>>) { fun buildApiSearchQuery(searchQueryBuilder: GithubApiSearchQueryBuilder) { for (term in terms) { when (term) { is Term.QueryPart -> { searchQueryBuilder.query(term.apiValue) } is Term.Qualifier -> { searchQueryBuilder.qualifier(term.apiName, term.apiValue) } } } } fun isEmpty() = terms.isEmpty() override fun toString(): String { val builder = StringBuilder() for (term in terms) { builder.append(term.toString()) if (builder.isNotEmpty()) builder.append(" ") } return builder.toString() } companion object { private val DATE_FORMAT = SimpleDateFormat("yyyy-MM-dd") fun parseFromString(string: String): GithubPullRequestSearchQuery { val result = mutableListOf<Term<*>>() val terms = string.split(' ') for (term in terms) { if (term.isEmpty()) continue val colonIdx = term.indexOf(':') if (colonIdx < 0) { result.add(Term.QueryPart(term)) } else { try { result.add(QualifierName.valueOf(term.substring(0, colonIdx)).createTerm(term.substring(colonIdx + 1))) } catch (e: IllegalArgumentException) { result.add(Term.QueryPart(term)) } } } return GithubPullRequestSearchQuery(result) } } @Suppress("EnumEntryName") enum class QualifierName(val apiName: String) { state("state") { override fun createTerm(value: String) = Term.Qualifier.Enum.from<GithubIssueState>(this, value) }, assignee("assignee") { override fun createTerm(value: String) = Term.Qualifier.Simple(this, value) }, author("author") { override fun createTerm(value: String) = Term.Qualifier.Simple(this, value) }, after("created") { override fun createTerm(value: String) = Term.Qualifier.Date.After.from(this, value) }, before("created") { override fun createTerm(value: String) = Term.Qualifier.Date.Before.from(this, value) }, sortBy("sort") { override fun createTerm(value: String) = Term.Qualifier.Enum.from<GithubIssueSearchSort>(this, value) }; abstract fun createTerm(value: String): Term<*> } /** * Part of search query (search term) */ sealed class Term<T : Any>(protected val value: T) { abstract val apiValue: String? class QueryPart(value: String) : Term<String>(value) { override val apiValue = this.value override fun toString(): String = value } sealed class Qualifier<T : Any>(protected val name: QualifierName, value: T) : Term<T>(value) { val apiName: String = name.apiName override fun toString(): String = "$name:$value" class Simple(name: QualifierName, value: String) : Qualifier<String>(name, value) { override val apiValue = this.value } class Enum<T : kotlin.Enum<T>>(name: QualifierName, value: T) : Qualifier<kotlin.Enum<T>>(name, value) { override val apiValue = this.value.name companion object { inline fun <reified T : kotlin.Enum<T>> from(name: QualifierName, value: String): Term<*> { return try { Enum(name, enumValueOf<T>(value)) } catch (e: IllegalArgumentException) { Simple(name, value) } } } } sealed class Date(name: QualifierName, value: java.util.Date) : Qualifier<java.util.Date>(name, value) { protected fun formatDate(): String = DATE_FORMAT.format(this.value) override fun toString(): String = "$name:${formatDate()}" class Before(name: QualifierName, value: java.util.Date) : Date(name, value) { override val apiValue = "<${formatDate()}" companion object { fun from(name: QualifierName, value: String): Term<*> { val date = try { DATE_FORMAT.parse(value) } catch (e: ParseException) { return Simple(name, value) } return Before(name, date) } } } class After(name: QualifierName, value: java.util.Date) : Date(name, value) { override val apiValue = ">${formatDate()}" companion object { fun from(name: QualifierName, value: String): Term<*> { return try { After(name, DATE_FORMAT.parse(value)) } catch (e: ParseException) { Simple(name, value) } } } } } } } }
apache-2.0
0a1a53eded9caf6c36186cd3f13ded0d
31.660377
140
0.60651
4.392555
false
false
false
false
leafclick/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/GithubApiRequests.kt
1
26463
// 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.github.api import com.intellij.openapi.util.io.StreamUtil import com.intellij.util.ThrowableConvertor import org.jetbrains.plugins.github.api.GithubApiRequest.* import org.jetbrains.plugins.github.api.data.* import org.jetbrains.plugins.github.api.data.request.* import org.jetbrains.plugins.github.api.util.GithubApiPagesLoader import org.jetbrains.plugins.github.api.util.GithubApiSearchQueryBuilder import org.jetbrains.plugins.github.api.util.GithubApiUrlQueryBuilder import java.awt.Image /** * Collection of factory methods for API requests used in plugin * TODO: improve url building (DSL?) */ object GithubApiRequests { object CurrentUser : Entity("/user") { @JvmStatic fun get(server: GithubServerPath) = get(getUrl(server, urlSuffix)) @JvmStatic fun get(url: String) = Get.json<GithubAuthenticatedUser>(url).withOperationName("get profile information") @JvmStatic fun getAvatar(url: String) = object : Get<Image>(url) { override fun extractResult(response: GithubApiResponse): Image { return response.handleBody(ThrowableConvertor { GithubApiContentHelper.loadImage(it) }) } }.withOperationName("get profile avatar") object Repos : Entity("/repos") { @JvmOverloads @JvmStatic fun pages(server: GithubServerPath, type: Type = Type.DEFAULT, visibility: Visibility = Visibility.DEFAULT, affiliation: Affiliation = Affiliation.DEFAULT, pagination: GithubRequestPagination? = null) = GithubApiPagesLoader.Request(get(server, type, visibility, affiliation, pagination), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, type: Type = Type.DEFAULT, visibility: Visibility = Visibility.DEFAULT, affiliation: Affiliation = Affiliation.DEFAULT, pagination: GithubRequestPagination? = null): GithubApiRequest<GithubResponsePage<GithubRepo>> { if (type != Type.DEFAULT && (visibility != Visibility.DEFAULT || affiliation != Affiliation.DEFAULT)) { throw IllegalArgumentException("Param 'type' should not be used together with 'visibility' or 'affiliation'") } return get(getUrl(server, CurrentUser.urlSuffix, urlSuffix, getQuery(type.toString(), visibility.toString(), affiliation.toString(), pagination?.toString().orEmpty()))) } @JvmStatic fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get user repositories") @JvmStatic fun create(server: GithubServerPath, name: String, description: String, private: Boolean, autoInit: Boolean? = null) = Post.json<GithubRepo>(getUrl(server, CurrentUser.urlSuffix, urlSuffix), GithubRepoRequest(name, description, private, autoInit)) .withOperationName("create user repository") } object Orgs : Entity("/orgs") { @JvmOverloads @JvmStatic fun pages(server: GithubServerPath, pagination: GithubRequestPagination? = null) = GithubApiPagesLoader.Request(get(server, pagination), ::get) fun get(server: GithubServerPath, pagination: GithubRequestPagination? = null) = get(getUrl(server, CurrentUser.urlSuffix, urlSuffix, getQuery(pagination?.toString().orEmpty()))) fun get(url: String) = Get.jsonPage<GithubOrg>(url).withOperationName("get user organizations") } object RepoSubs : Entity("/subscriptions") { @JvmStatic fun pages(server: GithubServerPath) = GithubApiPagesLoader.Request(get(server), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, pagination: GithubRequestPagination? = null) = get(getUrl(server, CurrentUser.urlSuffix, urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get repository subscriptions") } } object Organisations : Entity("/orgs") { object Repos : Entity("/repos") { @JvmStatic fun pages(server: GithubServerPath, organisation: String, pagination: GithubRequestPagination? = null) = GithubApiPagesLoader.Request(get(server, organisation, pagination), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, organisation: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Organisations.urlSuffix, "/", organisation, urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get organisation repositories") @JvmStatic fun create(server: GithubServerPath, organisation: String, name: String, description: String, private: Boolean) = Post.json<GithubRepo>(getUrl(server, Organisations.urlSuffix, "/", organisation, urlSuffix), GithubRepoRequest(name, description, private, null)) .withOperationName("create organisation repository") } } object Repos : Entity("/repos") { @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String) = Get.Optional.json<GithubRepoDetailed>(getUrl(server, urlSuffix, "/$username/$repoName")) .withOperationName("get information for repository $username/$repoName") @JvmStatic fun delete(server: GithubServerPath, username: String, repoName: String) = delete(getUrl(server, urlSuffix, "/$username/$repoName")).withOperationName("delete repository $username/$repoName") @JvmStatic fun delete(url: String) = Delete.json<Unit>(url).withOperationName("delete repository at $url") object Branches : Entity("/branches") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubBranch>(url).withOperationName("get branches") } object Commits : Entity("/commits") { @JvmStatic fun getDiff(repository: GHRepositoryCoordinates, ref: String) = object : Get<String>(getUrl(repository, urlSuffix, "/$ref"), GithubApiContentHelper.V3_DIFF_JSON_MIME_TYPE) { override fun extractResult(response: GithubApiResponse): String { return response.handleBody(ThrowableConvertor { StreamUtil.readText(it, Charsets.UTF_8) }) } }.withOperationName("get diff for ref") @JvmStatic fun getDiff(repository: GHRepositoryCoordinates, refA: String, refB: String) = object : Get<String>(getUrl(repository, "/compare/$refA...$refB"), GithubApiContentHelper.V3_DIFF_JSON_MIME_TYPE) { override fun extractResult(response: GithubApiResponse): String { return response.handleBody(ThrowableConvertor { StreamUtil.readText(it, Charsets.UTF_8) }) } }.withOperationName("get diff between refs") } object Forks : Entity("/forks") { @JvmStatic fun create(server: GithubServerPath, username: String, repoName: String) = Post.json<GithubRepo>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix), Any()) .withOperationName("fork repository $username/$repoName for cuurent user") @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get forks") } object Assignees : Entity("/assignees") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubUser>(url).withOperationName("get assignees") } object Labels : Entity("/labels") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubIssueLabel>(url).withOperationName("get assignees") } object Collaborators : Entity("/collaborators") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String) = GithubApiPagesLoader.Request(get(server, username, repoName), ::get) @JvmOverloads @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty()))) @JvmStatic fun get(url: String) = Get.jsonPage<GithubUserWithPermissions>(url).withOperationName("get collaborators") @JvmStatic fun add(server: GithubServerPath, username: String, repoName: String, collaborator: String) = Put.json<Unit>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", collaborator)) } object Issues : Entity("/issues") { @JvmStatic fun create(server: GithubServerPath, username: String, repoName: String, title: String, body: String? = null, milestone: Long? = null, labels: List<String>? = null, assignees: List<String>? = null) = Post.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix), GithubCreateIssueRequest(title, body, milestone, labels, assignees)) @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String, state: String? = null, assignee: String? = null) = GithubApiPagesLoader.Request(get(server, username, repoName, state, assignee), ::get) @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, state: String? = null, assignee: String? = null, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param("state", state); param("assignee", assignee); param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonPage<GithubIssue>(url).withOperationName("get issues in repository") @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, id: String) = Get.Optional.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", id)) @JvmStatic fun updateState(server: GithubServerPath, username: String, repoName: String, id: String, open: Boolean) = Patch.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", id), GithubChangeIssueStateRequest(if (open) "open" else "closed")) @JvmStatic fun updateAssignees(server: GithubServerPath, username: String, repoName: String, id: String, assignees: Collection<String>) = Patch.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", id), GithubAssigneesCollectionRequest(assignees)) object Comments : Entity("/comments") { @JvmStatic fun create(repository: GHRepositoryCoordinates, issueId: Long, body: String) = create(repository.serverPath, repository.repositoryPath.owner, repository.repositoryPath.repository, issueId.toString(), body) @JvmStatic fun create(server: GithubServerPath, username: String, repoName: String, issueId: String, body: String) = Post.json<GithubIssueCommentWithHtml>( getUrl(server, Repos.urlSuffix, "/$username/$repoName", Issues.urlSuffix, "/", issueId, urlSuffix), GithubCreateIssueCommentRequest(body), GithubApiContentHelper.V3_HTML_JSON_MIME_TYPE) @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String, issueId: String) = GithubApiPagesLoader.Request(get(server, username, repoName, issueId), ::get) @JvmStatic fun pages(url: String) = GithubApiPagesLoader.Request(get(url), ::get) @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, issueId: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", Issues.urlSuffix, "/", issueId, urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonPage<GithubIssueCommentWithHtml>(url, GithubApiContentHelper.V3_HTML_JSON_MIME_TYPE) .withOperationName("get comments for issue") } object Labels : Entity("/labels") { @JvmStatic fun replace(server: GithubServerPath, username: String, repoName: String, issueId: String, labels: Collection<String>) = Put.jsonList<GithubIssueLabel>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", Issues.urlSuffix, "/", issueId, urlSuffix), GithubLabelsCollectionRequest(labels)) } } object PullRequests : Entity("/pulls") { @JvmStatic fun getDiff(repository: GHRepositoryCoordinates, number: Long) = object : Get<String>(getUrl(repository, urlSuffix, "/$number"), GithubApiContentHelper.V3_DIFF_JSON_MIME_TYPE) { override fun extractResult(response: GithubApiResponse): String { return response.handleBody(ThrowableConvertor { StreamUtil.readText(it, Charsets.UTF_8) }) } }.withOperationName("get pull request diff file") @JvmStatic fun create(server: GithubServerPath, username: String, repoName: String, title: String, description: String, head: String, base: String) = Post.json<GithubPullRequestDetailed>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix), GithubPullRequestRequest(title, description, head, base)) .withOperationName("create pull request in $username/$repoName") @JvmStatic fun update(serverPath: GithubServerPath, username: String, repoName: String, number: Long, title: String? = null, body: String? = null, state: GithubIssueState? = null, base: String? = null, maintainerCanModify: Boolean? = null) = Patch.json<GithubPullRequestDetailed>(getUrl(serverPath, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/$number"), GithubPullUpdateRequest(title, body, state, base, maintainerCanModify)) .withOperationName("update pull request $number") @JvmStatic fun update(url: String, title: String? = null, body: String? = null, state: GithubIssueState? = null, base: String? = null, maintainerCanModify: Boolean? = null) = Patch.json<GithubPullRequestDetailed>(url, GithubPullUpdateRequest(title, body, state, base, maintainerCanModify)) .withOperationName("update pull request") @JvmStatic fun merge(server: GithubServerPath, repoPath: GHRepositoryPath, number: Long, commitSubject: String, commitBody: String, headSha: String) = Put.json<Unit>(getUrl(server, Repos.urlSuffix, "/$repoPath", urlSuffix, "/$number", "/merge"), GithubPullRequestMergeRequest(commitSubject, commitBody, headSha, GithubPullRequestMergeMethod.merge)) .withOperationName("merge pull request ${number}") @JvmStatic fun squashMerge(server: GithubServerPath, repoPath: GHRepositoryPath, number: Long, commitSubject: String, commitBody: String, headSha: String) = Put.json<Unit>(getUrl(server, Repos.urlSuffix, "/$repoPath", urlSuffix, "/$number", "/merge"), GithubPullRequestMergeRequest(commitSubject, commitBody, headSha, GithubPullRequestMergeMethod.squash)) .withOperationName("squash and merge pull request ${number}") @JvmStatic fun rebaseMerge(server: GithubServerPath, repoPath: GHRepositoryPath, number: Long, headSha: String) = Put.json<Unit>(getUrl(server, Repos.urlSuffix, "/$repoPath", urlSuffix, "/$number", "/merge"), GithubPullRequestMergeRebaseRequest(headSha)) .withOperationName("rebase and merge pull request ${number}") @JvmStatic fun getListETag(server: GithubServerPath, repoPath: GHRepositoryPath) = object : Get<String?>(getUrl(server, Repos.urlSuffix, "/$repoPath", urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param(GithubRequestPagination(pageSize = 1)) })) { override fun extractResult(response: GithubApiResponse) = response.findHeader("ETag") }.withOperationName("get pull request list ETag") object Reviewers : Entity("/requested_reviewers") { @JvmStatic fun add(server: GithubServerPath, username: String, repoName: String, number: Long, reviewers: Collection<String>, teamReviewers: List<String>) = Post.json<Unit>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", PullRequests.urlSuffix, "/$number", urlSuffix), GithubReviewersCollectionRequest(reviewers, teamReviewers)) @JvmStatic fun remove(server: GithubServerPath, username: String, repoName: String, number: Long, reviewers: Collection<String>, teamReviewers: List<String>) = Delete.json<Unit>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", PullRequests.urlSuffix, "/$number", urlSuffix), GithubReviewersCollectionRequest(reviewers, teamReviewers)) } object Commits : Entity("/commits") { @JvmStatic fun pages(repository: GHRepositoryCoordinates, number: Long) = GithubApiPagesLoader.Request(get(repository, number), ::get) @JvmStatic fun pages(url: String) = GithubApiPagesLoader.Request(get(url), ::get) @JvmStatic fun get(repository: GHRepositoryCoordinates, number: Long, pagination: GithubRequestPagination? = null) = get(getUrl(repository, PullRequests.urlSuffix, "/$number", urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonPage<GithubCommit>(url) .withOperationName("get commits for pull request") } object Comments : Entity("/comments") { @JvmStatic fun pages(server: GithubServerPath, username: String, repoName: String, number: Long) = GithubApiPagesLoader.Request(get(server, username, repoName, number), ::get) @JvmStatic fun pages(url: String) = GithubApiPagesLoader.Request(get(url), ::get) @JvmStatic fun get(server: GithubServerPath, username: String, repoName: String, number: Long, pagination: GithubRequestPagination? = null) = get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", PullRequests.urlSuffix, "/$number", urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonPage<GithubPullRequestCommentWithHtml>(url, GithubApiContentHelper.V3_HTML_JSON_MIME_TYPE) .withOperationName("get comments for pull request") @JvmStatic fun createReply(repository: GHRepositoryCoordinates, pullRequest: Long, commentId: Long, body: String) = Post.json<GithubPullRequestCommentWithHtml>( getUrl(repository, PullRequests.urlSuffix, "/$pullRequest", "/comments/$commentId/replies"), mapOf("body" to body), GithubApiContentHelper.V3_HTML_JSON_MIME_TYPE).withOperationName("reply to pull request review comment") @JvmStatic fun create(repository: GHRepositoryCoordinates, pullRequest: Long, commitSha: String, filePath: String, diffLine: Int, body: String) = Post.json<GithubPullRequestCommentWithHtml>( getUrl(repository, PullRequests.urlSuffix, "/$pullRequest", "/comments"), mapOf("body" to body, "commit_id" to commitSha, "path" to filePath, "position" to diffLine), GithubApiContentHelper.V3_HTML_JSON_MIME_TYPE).withOperationName("create pull request review comment") } } } object Gists : Entity("/gists") { @JvmStatic fun create(server: GithubServerPath, contents: List<GithubGistRequest.FileContent>, description: String, public: Boolean) = Post.json<GithubGist>(getUrl(server, urlSuffix), GithubGistRequest(contents, description, public)) .withOperationName("create gist") @JvmStatic fun get(server: GithubServerPath, id: String) = Get.Optional.json<GithubGist>(getUrl(server, urlSuffix, "/$id")) .withOperationName("get gist $id") @JvmStatic fun delete(server: GithubServerPath, id: String) = Delete.json<Unit>(getUrl(server, urlSuffix, "/$id")) .withOperationName("delete gist $id") } object Search : Entity("/search") { object Issues : Entity("/issues") { @JvmStatic fun pages(server: GithubServerPath, repoPath: GHRepositoryPath?, state: String?, assignee: String?, query: String?) = GithubApiPagesLoader.Request(get(server, repoPath, state, assignee, query), ::get) @JvmStatic fun get(server: GithubServerPath, repoPath: GHRepositoryPath?, state: String?, assignee: String?, query: String?, pagination: GithubRequestPagination? = null) = get(getUrl(server, Search.urlSuffix, urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param("q", GithubApiSearchQueryBuilder.searchQuery { qualifier("repo", repoPath?.toString().orEmpty()) qualifier("state", state) qualifier("assignee", assignee) query(query) }) param(pagination) })) @JvmStatic fun get(server: GithubServerPath, query: String, pagination: GithubRequestPagination? = null) = get(getUrl(server, Search.urlSuffix, urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param("q", query) param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonSearchPage<GithubSearchedIssue>(url).withOperationName("search issues in repository") } } object Auth : Entity("/authorizations") { @JvmStatic fun create(server: GithubServerPath, scopes: List<String>, note: String) = Post.json<GithubAuthorization>(getUrl(server, urlSuffix), GithubAuthorizationCreateRequest(scopes, note, null)) .withOperationName("create authorization $note") @JvmStatic fun get(server: GithubServerPath, pagination: GithubRequestPagination? = null) = get(getUrl(server, urlSuffix, GithubApiUrlQueryBuilder.urlQuery { param(pagination) })) @JvmStatic fun get(url: String) = Get.jsonPage<GithubAuthorization>(url) .withOperationName("get authorizations") @JvmStatic fun pages(server: GithubServerPath, pagination: GithubRequestPagination? = null) = GithubApiPagesLoader.Request(get(server, pagination), ::get) } abstract class Entity(val urlSuffix: String) private fun getUrl(server: GithubServerPath, suffix: String) = server.toApiUrl() + suffix private fun getUrl(repository: GHRepositoryCoordinates, vararg suffixes: String) = getUrl(repository.serverPath, Repos.urlSuffix, "/", repository.repositoryPath.toString(), *suffixes) fun getUrl(server: GithubServerPath, vararg suffixes: String) = StringBuilder(server.toApiUrl()).append(*suffixes).toString() private fun getQuery(vararg queryParts: String): String { val builder = StringBuilder() for (part in queryParts) { if (part.isEmpty()) continue if (builder.isEmpty()) builder.append("?") else builder.append("&") builder.append(part) } return builder.toString() } }
apache-2.0
03ced58c8120ae1d9434b9e350dacc5a
46.855335
140
0.655557
5.189841
false
false
false
false
googlecodelabs/android-gestural-navigation
app/src/main/java/com/example/android/uamp/MediaItemData.kt
1
3521
/* * Copyright 2020 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.uamp import android.net.Uri import android.support.v4.media.MediaBrowserCompat import androidx.recyclerview.widget.DiffUtil import android.support.v4.media.MediaBrowserCompat.MediaItem import com.example.android.uamp.viewmodels.MediaItemFragmentViewModel /** * Data class to encapsulate properties of a [MediaItem]. * * If an item is [browsable] it means that it has a list of child media items that * can be retrieved by passing the mediaId to [MediaBrowserCompat.subscribe]. * * Objects of this class are built from [MediaItem]s in * [MediaItemFragmentViewModel.subscriptionCallback]. */ data class MediaItemData( val mediaId: String, val title: String, val subtitle: String, val albumArtUri: Uri, val browsable: Boolean, var playbackRes: Int) { companion object { /** * Indicates [playbackRes] has changed. */ const val PLAYBACK_RES_CHANGED = 1 /** * [DiffUtil.ItemCallback] for a [MediaItemData]. * * Since all [MediaItemData]s have a unique ID, it's easiest to check if two * items are the same by simply comparing that ID. * * To check if the contents are the same, we use the same ID, but it may be the * case that it's only the play state itself which has changed (from playing to * paused, or perhaps a different item is the active item now). In this case * we check both the ID and the playback resource. * * To calculate the payload, we use the simplest method possible: * - Since the title, subtitle, and albumArtUri are constant (with respect to mediaId), * there's no reason to check if they've changed. If the mediaId is the same, none of * those properties have changed. * - If the playback resource (playbackRes) has changed to reflect the change in playback * state, that's all that needs to be updated. We return [PLAYBACK_RES_CHANGED] as * the payload in this case. * - If something else changed, then refresh the full item for simplicity. */ val diffCallback = object : DiffUtil.ItemCallback<MediaItemData>() { override fun areItemsTheSame(oldItem: MediaItemData, newItem: MediaItemData): Boolean = oldItem.mediaId == newItem.mediaId override fun areContentsTheSame(oldItem: MediaItemData, newItem: MediaItemData) = oldItem.mediaId == newItem.mediaId && oldItem.playbackRes == newItem.playbackRes override fun getChangePayload(oldItem: MediaItemData, newItem: MediaItemData) = if (oldItem.playbackRes != newItem.playbackRes) { PLAYBACK_RES_CHANGED } else null } } }
apache-2.0
2e15ac9e5cfc2643878b4bdb548aa8e7
41.421687
100
0.662028
4.836538
false
false
false
false
mrbublos/vkm
app/src/main/java/vkm/vkm/MainActivity.kt
1
3738
package vkm.vkm import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.graphics.Point import android.os.Bundle import android.os.Environment import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import vkm.vkm.utils.HttpUtils import vkm.vkm.utils.Proxy import vkm.vkm.utils.Swiper import vkm.vkm.utils.db.Db import vkm.vkm.utils.log import java.io.File import kotlin.coroutines.Continuation import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class MainActivity : AppCompatActivity() { companion object { private const val EXTERNAL_STORAGE_WRITE_PERMISSION = 1 } private var initialized = false private var permissionContinuation: Continuation<IntArray>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // asking for writing permissions val permissionCheck = ContextCompat.checkSelfPermission(applicationContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) GlobalScope.launch(Dispatchers.Main) { "starting permissions".log() if (permissionCheck != PackageManager.PERMISSION_GRANTED) { suspendCoroutine<IntArray> { permissionContinuation = it requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), EXTERNAL_STORAGE_WRITE_PERMISSION) }.takeIf { it.isEmpty() || it[0] != PackageManager.PERMISSION_GRANTED }?.let { finish() return@launch } } permissionContinuation = null "permissions received".log() initialize() startActivity(Intent(applicationContext, PagerActivity::class.java)) finish() } } private fun initialize() { val point = Point() windowManager.defaultDisplay.getSize(point) Swiper.SWIPE_DISTANCE_MIN = Math.max(point.x / 3, 200) loadProxy() DownloadManager.initialize(Db.instance(applicationContext).tracksDao()) initialized = true } private fun loadProxy() { val destinationDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).resolve("vkm") destinationDir.mkdirs() val file = File(destinationDir, "proxy.txt") if (file.exists()) { val proxyData = file.readLines()[0].split(":") HttpUtils.currentProxy = Proxy(host = proxyData[0], port = proxyData[1].toInt(), speed = 0, type = "") } } private fun saveProxy() { val currentProxy = HttpUtils.currentProxy ?: return val destinationDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).resolve("vkm") destinationDir.mkdirs() File(destinationDir, "proxy.txt").writeText("${currentProxy.host}:${currentProxy.port}") } override fun onPause() { super.onPause() if (initialized) { DownloadManager.stopDownload() } saveProxy() } override fun onStop() { super.onStop() if (initialized) { DownloadManager.stopDownload() } saveProxy() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { if (EXTERNAL_STORAGE_WRITE_PERMISSION == requestCode) { permissionContinuation?.resume(grantResults) } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } }
gpl-3.0
9e0a25b8d27912bab3722e86806f339c
35.291262
127
0.676297
5.065041
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertTryFinallyToUseCallIntention.kt
2
5061
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.contentRange import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.types.typeUtil.supertypes @Suppress("DEPRECATION") class ConvertTryFinallyToUseCallInspection : IntentionBasedInspection<KtTryExpression>( ConvertTryFinallyToUseCallIntention::class, problemText = KotlinBundle.message("convert.try.finally.to.use.before.text") ) { override fun inspectionTarget(element: KtTryExpression) = element.tryKeyword ?: element.tryBlock } class ConvertTryFinallyToUseCallIntention : SelfTargetingRangeIntention<KtTryExpression>( KtTryExpression::class.java, KotlinBundle.lazyMessage("convert.try.finally.to.use") ) { override fun applyTo(element: KtTryExpression, editor: Editor?) { val finallySection = element.finallyBlock ?: return val finallyExpression = finallySection.finalExpression.statements.single() val finallyExpressionReceiver = (finallyExpression as? KtQualifiedExpression)?.receiverExpression val resourceReference = finallyExpressionReceiver as? KtNameReferenceExpression val resourceName = resourceReference?.getReferencedNameAsName() val factory = KtPsiFactory(element) val useCallExpression = factory.buildExpression { if (resourceName != null) { appendName(resourceName) appendFixedText(".") } else if (finallyExpressionReceiver is KtThisExpression) { appendFixedText(finallyExpressionReceiver.text) appendFixedText(".") } appendFixedText("use {") if (resourceName != null) { appendName(resourceName) appendFixedText("->") } appendFixedText("\n") appendChildRange(element.tryBlock.contentRange()) appendFixedText("\n}") } val call = when (val result = element.replace(useCallExpression) as KtExpression) { is KtQualifiedExpression -> result.selectorExpression as? KtCallExpression ?: return is KtCallExpression -> result else -> return } val lambda = call.lambdaArguments.firstOrNull() ?: return val lambdaParameter = lambda.getLambdaExpression()?.valueParameters?.firstOrNull() ?: return editor?.selectionModel?.setSelection(lambdaParameter.startOffset, lambdaParameter.endOffset) } override fun applicabilityRange(element: KtTryExpression): TextRange? { // Single statement in finally, no catch blocks val finallySection = element.finallyBlock ?: return null val finallyExpression = finallySection.finalExpression.statements.singleOrNull() ?: return null if (element.catchClauses.isNotEmpty()) return null val context = element.analyze() val resolvedCall = finallyExpression.getResolvedCall(context) ?: return null if (resolvedCall.candidateDescriptor.name.asString() != "close") return null if (resolvedCall.extensionReceiver != null) return null val receiver = resolvedCall.dispatchReceiver ?: return null if (receiver.type.supertypes().all { it.constructor.declarationDescriptor?.fqNameSafe?.asString().let { s -> s != "java.io.Closeable" && s != "java.lang.AutoCloseable" } }) return null when (receiver) { is ExpressionReceiver -> { val expression = receiver.expression if (expression !is KtThisExpression) { val resourceReference = expression as? KtReferenceExpression ?: return null val resourceDescriptor = context[BindingContext.REFERENCE_TARGET, resourceReference] as? VariableDescriptor ?: return null if (resourceDescriptor.isVar) return null } } is ImplicitReceiver -> { } else -> return null } return TextRange(element.startOffset, element.tryBlock.lBrace?.endOffset ?: element.endOffset) } }
apache-2.0
549372164eb91c50b6614eb51a870f42
46.308411
158
0.698479
5.661074
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/propertyModification.kt
9
263
// "Replace with 'new'" "true" // WITH_STDLIB class A { @Deprecated("msg", ReplaceWith("new")) var old get() = new set(value) { new = value } var new = "" } fun foo() { val a = A() a.<caret>old += "foo" }
apache-2.0
dbf337d14f389d99fe69e83faf122c33
13.666667
42
0.448669
3.246914
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ide/projectWizard/NewProjectWizardCollector.kt
1
6165
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.projectWizard import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.ide.wizard.NewProjectWizardLanguageStep import com.intellij.internal.statistic.StructuredIdeActivity import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.* import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.openapi.project.Project import java.lang.Integer.min class NewProjectWizardCollector : CounterUsagesCollector() { override fun getGroup() = GROUP companion object { private val GROUP = EventLogGroup("new.project.wizard.interactions", 2) private val sessionIdField = EventFields.Int("wizard_session_id") private val screenNumField = IntEventField("screen") private val typedCharsField = IntEventField("typed_chars") private val hitsField = IntEventField("hits") private val generatorTypeField = ClassEventField("generator") private val languageField = EventFields.String("language", NewProjectWizardLanguageStep.allLanguages.keys.toList()) private val gitField = EventFields.Boolean("git") private val isSucceededField = EventFields.Boolean("project_created") private val inputMaskField = EventFields.Long("input_mask") //events private val activity = GROUP.registerIdeActivity("new_project_wizard", finishEventAdditionalFields = arrayOf(isSucceededField)) private val open = GROUP.registerEvent("wizard.dialog.open", sessionIdField) private val screen = GROUP.registerEvent("screen", sessionIdField, screenNumField) private val next = GROUP.registerEvent("navigate.next", sessionIdField, inputMaskField) private val prev = GROUP.registerEvent("navigate.prev", sessionIdField, inputMaskField) private val projectCreated = GROUP.registerEvent("project.created", sessionIdField) private val search = GROUP.registerEvent("search", sessionIdField, typedCharsField, hitsField) private val generator = GROUP.registerEvent("search", sessionIdField, generatorTypeField) private val location = GROUP.registerEvent("project.location.changed", sessionIdField, generatorTypeField) private val name = GROUP.registerEvent("project.name.changed", sessionIdField, generatorTypeField) private val languageSelected = GROUP.registerEvent("select.language", sessionIdField, languageField) private val gitChanged = GROUP.registerEvent("git.changed", sessionIdField) private val templateSelected = GROUP.registerEvent("select.custom.template", sessionIdField) private val helpNavigation = GROUP.registerEvent("navigate.help", sessionIdField) //finish events private val gitFinish = GROUP.registerEvent("create.git.repo", sessionIdField, gitField) private val generatorFinished = GROUP.registerEvent("generator.finished", sessionIdField, generatorTypeField) private val languageFinished = GROUP.registerEvent("language.finished", sessionIdField, languageField) //logs @JvmStatic fun logStarted(project: Project?) = activity.started(project) @JvmStatic fun logScreen(context: WizardContext, screenNumber: Int) = screen.log(context.project, context.sessionId.id, screenNumber) @JvmStatic fun logOpen(context: WizardContext) = open.log(context.project, context.sessionId.id) @JvmStatic fun logSearchChanged(context: WizardContext, chars: Int, results: Int) = search.log(context.project, context.sessionId.id, min(chars, 10), results) @JvmStatic fun logLocationChanged(context: WizardContext, generator: Class<*>) = location.log(context.project, context.sessionId.id, generator) @JvmStatic fun logNameChanged(context: WizardContext, generator: Class<*>) = name.log(context.project, context.sessionId.id, generator) @JvmStatic fun logLanguageChanged(context: WizardContext, language: String) = languageSelected.log(context.project, context.sessionId.id, language) @JvmStatic fun logGitChanged(context: WizardContext) = gitChanged.log(context.project, context.sessionId.id) @JvmStatic fun logGeneratorSelected(context: WizardContext, title: Class<*>) = generator.log(context.project, context.sessionId.id, title) @JvmStatic fun logCustomTemplateSelected(context: WizardContext) = templateSelected.log(context.project, context.sessionId.id) @JvmStatic fun logNext(context: WizardContext, inputMask: Long = -1) = next.log(context.project, context.sessionId.id, inputMask) @JvmStatic fun logPrev(context: WizardContext, inputMask: Long = -1) = prev.log(context.project, context.sessionId.id, inputMask) @JvmStatic fun logHelpNavigation(context: WizardContext) = helpNavigation.log(context.project, context.sessionId.id) //finish @JvmStatic fun logFinished(activity: StructuredIdeActivity, success: Boolean) = activity.finished { listOf(isSucceededField with success)} @JvmStatic fun logProjectCreated(project: Project?, context: WizardContext) = projectCreated.log(project, context.sessionId.id) @JvmStatic fun logLanguageFinished(context: WizardContext, language: String) = languageFinished.log(context.project, context.sessionId.id, language) @JvmStatic fun logGitFinished(context: WizardContext, git: Boolean) = gitFinish.log(context.project, context.sessionId.id, git) @JvmStatic fun logGeneratorFinished(context: WizardContext, generator: Class<*>) = generatorFinished.log(context.project, context.sessionId.id, generator) } open class BuildSystemCollector(buildSystemList: List<String>) { private val buildSystemField = BuildSystemField(buildSystemList) private val buildSystem = GROUP.registerEvent("select.build.system", sessionIdField, buildSystemField) private class BuildSystemField(buildSystemList: List<String>) : StringEventField("build_system") { override val validationRule: List<String> = buildSystemList } fun logBuildSystemChanged(context: WizardContext, name: String) = buildSystem.log(context.project, context.sessionId.id, name) } }
apache-2.0
81a2a809beb47358892a2f31c75ccb88
72.404762
162
0.788483
4.706107
false
false
false
false
alibaba/p3c
eclipse-plugin/com.alibaba.smartfox.eclipse.plugin/src/main/kotlin/com/alibaba/smartfox/eclipse/ui/InspectionResults.kt
2
3153
/* * Copyright 1999-2017 Alibaba Group. * * 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.alibaba.smartfox.eclipse.ui import com.alibaba.smartfox.eclipse.pmd.RulePriority import com.alibaba.smartfox.eclipse.util.MarkerUtil import org.eclipse.core.resources.IFile import org.eclipse.core.resources.IMarker /** * * * @author caikang * @date 2017/06/13 */ object InspectionResults { private val fileViolations = linkedMapOf<IFile, List<MarkerViolation>>() var contentDescription = "" val errors: List<LevelViolations> get() { val result = toLevelViolationList(fileViolations.values.flatten()) contentDescription = getContentDescription(result) return result } lateinit var view: InspectionResultView fun clear() { fileViolations.forEach { MarkerUtil.removeAllMarkers(it.key) } fileViolations.clear() // update contentDescription errors } private fun toLevelViolationList(markers: Collection<MarkerViolation>): List<LevelViolations> { return markers.groupBy { it.violation.rule.priority.priority }.mapValues { it.value.groupBy { it.violation.rule.name }.mapValues { it.value.groupBy { it.marker.resource as IFile }.map { FileMarkers(it.key, it.value) } }.map { RuleViolations(it.key, it.value) } }.toSortedMap().map { val level = RulePriority.valueOf(it.key).title LevelViolations(level, it.value) } } fun updateFileViolations(file: IFile, markers: List<MarkerViolation>) { if (markers.isEmpty()) { fileViolations.remove(file) } else { fileViolations[file] = markers } view.refreshView(this) } fun removeMarker(marker: IMarker) { val file = marker.resource as IFile val list = fileViolations[file] ?: return val result = list.filter { it.marker != marker } fileViolations[file] = result marker.delete() view.refreshView(this) } fun getContentDescription(errors: List<LevelViolations>): String { val map = errors.associateBy { it.level } return "${map[RulePriority.Blocker.title]?.count ?: 0} Blockers," + "${map[RulePriority.Critical.title]?.count ?: 0} Criticals," + "${map[RulePriority.Major.title]?.count ?: 0} Majors" } }
apache-2.0
a36c7f746354ad395a64f4abb47d9428
29.61165
99
0.615921
4.523673
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/viewmodels/EditorialViewModel.kt
1
5293
package com.kickstarter.viewmodels import com.kickstarter.libs.ActivityViewModel import com.kickstarter.libs.Environment import com.kickstarter.libs.rx.transformers.Transformers.errors import com.kickstarter.libs.rx.transformers.Transformers.values import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.models.Category import com.kickstarter.services.DiscoveryParams import com.kickstarter.ui.IntentKey import com.kickstarter.ui.activities.EditorialActivity import com.kickstarter.ui.data.Editorial import rx.Notification import rx.Observable import rx.subjects.BehaviorSubject import rx.subjects.PublishSubject interface EditorialViewModel { interface Inputs { /** Call when the user clicks the retry container. */ fun retryContainerClicked() } interface Outputs { /** Emits the @StringRes ID of the description of the [Editorial]. */ fun description(): Observable<Int> /** Emits the [DiscoveryParams] for the tag of the [Editorial]. */ fun discoveryParams(): Observable<DiscoveryParams> /** Emits the @DrawableRes of the graphic of the [Editorial]. */ fun graphic(): Observable<Int> /** Emits when we should refresh the [com.kickstarter.ui.fragments.DiscoveryFragment]. */ fun refreshDiscoveryFragment(): Observable<Void> /** Emits a [Boolean] determining if the retry container should be visible. */ fun retryContainerIsGone(): Observable<Boolean> /** Emits a list of root [Category]s. */ fun rootCategories(): Observable<List<Category>> /** Emits the @StringRes ID of the title of the [Editorial]. */ fun title(): Observable<Int> } class ViewModel(val environment: Environment) : ActivityViewModel<EditorialActivity>(environment), Inputs, Outputs { private val retryContainerClicked: PublishSubject<Void> = PublishSubject.create() private val description: BehaviorSubject<Int> = BehaviorSubject.create() private val discoveryParams: BehaviorSubject<DiscoveryParams> = BehaviorSubject.create() private val graphic: BehaviorSubject<Int> = BehaviorSubject.create() private val refreshDiscoveryFragment: PublishSubject<Void> = PublishSubject.create() private val retryContainerIsGone: BehaviorSubject<Boolean> = BehaviorSubject.create() private val rootCategories: BehaviorSubject<List<Category>> = BehaviorSubject.create() private val title: BehaviorSubject<Int> = BehaviorSubject.create() private val apolloClient = requireNotNull(environment.apolloClient()) val inputs: Inputs = this val outputs: Outputs = this init { val editorial = intent() .map { it.getSerializableExtra(IntentKey.EDITORIAL) } .filter { ObjectUtils.isNotNull(it) } .ofType(Editorial::class.java) val categoriesNotification = Observable.merge(fetchCategories(), this.retryContainerClicked.switchMap { fetchCategories() }) categoriesNotification .compose(values()) .map { it.filter { category -> category.isRoot } } .map { it.sorted() } .compose(bindToLifecycle()) .subscribe { this.rootCategories.onNext(it) } categoriesNotification .compose(errors()) .compose(bindToLifecycle()) .subscribe { this.retryContainerIsGone.onNext(false) } editorial .map { it.tagId } .map { DiscoveryParams.builder().sort(DiscoveryParams.Sort.MAGIC).tagId(it).build() } .compose(bindToLifecycle()) .subscribe(this.discoveryParams) editorial .map { it.graphic } .compose(bindToLifecycle()) .subscribe(this.graphic) editorial .map { it.title } .compose(bindToLifecycle()) .subscribe(this.title) editorial .map { it.description } .compose(bindToLifecycle()) .subscribe(this.description) this.retryContainerClicked .compose(bindToLifecycle()) .subscribe(this.refreshDiscoveryFragment) } private fun fetchCategories(): Observable<Notification<List<Category>>>? { return this.apolloClient.fetchCategories() .doOnSubscribe { this.retryContainerIsGone.onNext(true) } .materialize() .share() } override fun retryContainerClicked() = this.retryContainerClicked.onNext(null) override fun description(): Observable<Int> = this.description override fun discoveryParams(): Observable<DiscoveryParams> = this.discoveryParams override fun graphic(): Observable<Int> = this.graphic override fun refreshDiscoveryFragment(): Observable<Void> = this.refreshDiscoveryFragment override fun retryContainerIsGone(): Observable<Boolean> = this.retryContainerIsGone override fun rootCategories(): Observable<List<Category>> = this.rootCategories override fun title(): Observable<Int> = this.title } }
apache-2.0
b70a2d3674b467ee7b69114d6e9b35e3
39.098485
136
0.656716
5.439877
false
false
false
false
Setekh/corvus-android-essentials
app/src/main/java/eu/corvus/essentials/core/BaseApplication.kt
1
3737
package eu.corvus.essentials.core import android.app.Activity import android.app.Application import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.Looper import org.jetbrains.anko.AnkoLogger import timber.log.Timber import java.util.concurrent.Executors /** * Created by Vlad Cazacu on 10/4/2016. */ abstract class BaseApplication : Application(), Application.ActivityLifecycleCallbacks, AnkoLogger { val activityStack = mutableMapOf<Class<out Activity>, ActivityInfo>() var topActivity: Activity? = null override fun onCreate() { super.onCreate() appContext = this threads = provideThreads() registerActivityLifecycleCallbacks(this) Dispatcher.initialize(this) Preferences.initialize(this) configureTimber() initialize() } private fun provideThreads(): Threads { val execService = Executors.newFixedThreadPool(getNumberOfCores()) val scheduleService = Executors.newScheduledThreadPool(getNumberOfCores()) return Threads(execService, scheduleService, Handler(Looper.getMainLooper())) } /** * Override this in production! */ fun configureTimber() { Timber.plant(Timber.DebugTree()) } abstract fun initialize() // initialize override fun onActivityStarted(activity: Activity) { } override fun onActivityPaused(activity: Activity) { changeState(activity, ActivityState.Paused) } override fun onActivityResumed(activity: Activity) { changeState(activity, ActivityState.Active) } override fun onActivityStopped(activity: Activity) { changeState(activity, ActivityState.Stopped) } override fun onActivityCreated(activity: Activity, bundle: Bundle?) { changeState(activity, ActivityState.Created) } override fun onActivityDestroyed(activity: Activity) { changeState(activity, ActivityState.Destroyed) if(activityStack.isEmpty()) { MemoryStorage.onNoActivity() } } override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle?) = Unit private fun changeState(activity: Activity, activityState: ActivityState) { val activityInfo = when(activityState) { ActivityState.Created -> { val activityInfo = ActivityInfo(activity.javaClass, activity, activityState) activityStack.put(activity.javaClass, activityInfo) topActivity = activity activityInfo } ActivityState.Destroyed -> activityStack.remove(activity.javaClass) else -> activityStack[activity.javaClass] } activityInfo ?: return activityInfo.activityState = activityState if(activityState == ActivityState.Active) topActivity = activity if(currentActivity() == null) Dispatcher.sendBroadcast(Intent(AppBackground)) else Dispatcher.sendBroadcast(Intent(AppForeground)) } fun currentActivity(): Activity? { var currentActivity: Activity? = null activityStack.forEach { val value = it.value if (value.activityState == ActivityState.Active) currentActivity = value.activity } return currentActivity } fun clearTop() { activityStack.clear() } enum class ActivityState { Active, Paused, Stopped, Created, Destroyed } data class ActivityInfo(val type: Class<out Activity>, var activity: Activity, var activityState: ActivityState) override fun onTerminate() { super.onTerminate() threads.terminate() } }
apache-2.0
b6e681d92362729f25e8860b6ce9fba1
27.753846
116
0.672732
5.46345
false
false
false
false
siosio/intellij-community
platform/platform-impl/src/com/intellij/openapi/util/registry/RegistryToAdvancedSettingsMigration.kt
1
3004
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.util.registry import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.editor.impl.TabCharacterPaintMode import com.intellij.openapi.options.advanced.AdvancedSettingBean import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity class RegistryToAdvancedSettingsMigration : StartupActivity.DumbAware { override fun runActivity(project: Project) { val propertyName = "registry.to.advanced.settings.migration.build" val lastMigratedVersion = PropertiesComponent.getInstance().getValue(propertyName) val currentVersion = ApplicationInfo.getInstance().build.asString() if (currentVersion != lastMigratedVersion) { val userProperties = Registry.getInstance().userProperties for (setting in AdvancedSettingBean.EP_NAME.extensions) { if (setting.id == "editor.tab.painting") { migrateEditorTabPainting(userProperties, setting) continue } if (setting.id == "vcs.process.ignored") { migrateVcsIgnoreProcessing(userProperties, setting) continue } val userProperty = userProperties[setting.id] ?: continue try { AdvancedSettings.getInstance().setSetting(setting.id, setting.valueFromString(userProperty), setting.type()) userProperties.remove(setting.id) } catch (e: IllegalArgumentException) { continue } } PropertiesComponent.getInstance().setValue(propertyName, currentVersion) } } private fun migrateEditorTabPainting(userProperties: MutableMap<String, String>, setting: AdvancedSettingBean) { val mode = if (userProperties["editor.old.tab.painting"] == "true") { userProperties.remove("editor.old.tab.painting") TabCharacterPaintMode.LONG_ARROW } else if (userProperties["editor.arrow.tab.painting"] == "true") { userProperties.remove("editor.arrow.tab.painting") TabCharacterPaintMode.ARROW } else { return } AdvancedSettings.getInstance().setSetting(setting.id, mode, setting.type()) } private fun migrateVcsIgnoreProcessing(userProperties: MutableMap<String, String>, setting: AdvancedSettingBean) { if (userProperties["git.process.ignored"] == "false") { userProperties.remove("git.process.ignored") } else if (userProperties["hg4idea.process.ignored"] == "false") { userProperties.remove("hg4idea.process.ignored") } else if (userProperties["p4.process.ignored"] == "false") { userProperties.remove("p4.process.ignored") } else { return } AdvancedSettings.getInstance().setSetting(setting.id, false, setting.type()) } }
apache-2.0
78c2182f588fc430624737911bb938b9
39.594595
158
0.719707
4.614439
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/content/SingleContentLayout.kt
4
28430
// 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.content import com.intellij.CommonBundle import com.intellij.icons.AllIcons import com.intellij.ide.IdeBundle import com.intellij.ide.actions.PinActiveTabAction import com.intellij.ide.impl.DataManagerImpl import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.JBPopupMenu import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.openapi.util.* import com.intellij.openapi.wm.ex.ToolWindowEx import com.intellij.toolWindow.InternalDecoratorImpl import com.intellij.ui.ExperimentalUI.isNewUI import com.intellij.ui.MouseDragHelper import com.intellij.ui.PopupHandler import com.intellij.ui.awt.RelativePoint import com.intellij.ui.components.panels.HorizontalLayout import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.content.AlertIcon import com.intellij.ui.content.Content import com.intellij.ui.content.ContentManager import com.intellij.ui.content.impl.ContentManagerImpl import com.intellij.ui.tabs.* import com.intellij.ui.tabs.impl.JBTabsImpl import com.intellij.ui.tabs.impl.MorePopupAware import com.intellij.ui.tabs.impl.TabLabel import com.intellij.util.castSafelyTo import com.intellij.util.containers.ContainerUtil import com.intellij.util.ui.AbstractLayoutManager import com.intellij.util.ui.UIUtil import java.awt.* import java.awt.event.* import java.beans.PropertyChangeEvent import java.beans.PropertyChangeListener import java.beans.PropertyChangeSupport import javax.swing.Icon import javax.swing.JComponent import javax.swing.SwingUtilities /** * Tool window header that shows tabs and actions from its content. * * If toolwindow [Content] returns [SingleContentSupplier] as a data provider * via [SingleContentSupplier.KEY] that in case of single content view * all [JBTabs] and actions are moved into this header. * * When two or more contents exist then header looks like [TabContentLayout]. */ internal class SingleContentLayout( ui: ToolWindowContentUi ) : TabContentLayout(ui) { private var isSingleContentView: Boolean = false private var tabAdapter: TabAdapter? = null private val toolbars = mutableMapOf<ToolbarType, ActionToolbar>() private var wrapper: JComponent? = null override fun update() { super.update() tryUpdateContentView() } override fun rebuild() { super.rebuild() tryUpdateContentView() } private fun Content.getSupplier(): SingleContentSupplier? { return (component as? DataProvider)?.let(SingleContentSupplier.KEY::getData) } private fun getSingleContentOrNull(): Content? { return findTopLevelContentManager()?.contentsRecursively?.singleOrNull() } private fun findTopLevelContentManager(): ContentManagerImpl? { return InternalDecoratorImpl.findTopLevelDecorator(ui.component)?.contentManager as? ContentManagerImpl } private fun tryUpdateContentView() { val currentContent = getSingleContentOrNull() val contentSupplier = currentContent?.getSupplier() if (contentSupplier != null) { if (isSingleContentView) { updateSingleContentView(currentContent, contentSupplier) } else { initSingleContentView(currentContent, contentSupplier) } } else if (isSingleContentView) { resetSingleContentView() } val toolwindow = ui.getWindow().castSafelyTo<ToolWindowEx>() if (toolwindow != null) { val group = toolwindow.decoration?.actionGroup if (isSingleContentView) { // install extra actions if (group !is ExtendedTitleActionsGroup) { toolwindow.setAdditionalGearActions(ExtendedTitleActionsGroup( group, PinActiveTabAction(), Separator.create() )) } } else { // restore user's group if (group is ExtendedTitleActionsGroup) { toolwindow.setAdditionalGearActions(group.originActions) } } } } private fun initSingleContentView(content: Content, supplier: SingleContentSupplier) { tabAdapter = TabAdapter(content, supplier.getTabs(), tabPainter, ui).also { Disposer.register(content, it) ui.tabComponent.add(it) } assert(toolbars.isEmpty()) supplier.getToolbarActions()?.let { mainActionGroup -> toolbars[ToolbarType.MAIN] = createToolbar( supplier.getMainToolbarPlace(), mainActionGroup, content.component ) } let { val contentActions = DefaultActionGroup() contentActions.add(CloseCurrentContentAction()) contentActions.add(Separator.create()) contentActions.addAll(supplier.getContentActions()) contentActions.add(MyInvisibleAction()) toolbars[ToolbarType.CLOSE_GROUP] = createToolbar( supplier.getContentToolbarPlace(), contentActions, content.component ).apply { setReservePlaceAutoPopupIcon(false) layoutPolicy = ActionToolbar.NOWRAP_LAYOUT_POLICY } } toolbars.forEach { (_, toolbar) -> ui.tabComponent.add(toolbar.component) } wrapper = NonOpaquePanel(HorizontalLayout(0)).also { MyRedispatchMouseEventListener { e -> // extra actions are registered in ToolWindowContentUi#initMouseListeners if (SwingUtilities.isLeftMouseButton(e)) { ui.tabComponent.parent?.let { westPanel -> westPanel.dispatchEvent(SwingUtilities.convertMouseEvent(e.component, e, westPanel)) } } }.installOn(it) MouseDragHelper.setComponentDraggable(it, true) ToolWindowContentUi.initMouseListeners(it, ui, true) ui.tabComponent.add(it) } isSingleContentView = true supplier.init(toolbars[ToolbarType.MAIN], toolbars[ToolbarType.CLOSE_GROUP]) supplier.customize(wrapper) } private fun updateSingleContentView(content: Content, supplier: SingleContentSupplier) { if (tabAdapter?.jbTabs != supplier.getTabs()) { // in case of 'reusing content' just revoke old view and create new one resetSingleContentView() initSingleContentView(content, supplier) } else { toolbars.forEach { (_, toolbar) -> toolbar.updateActionsImmediately() } supplier.customize(wrapper) ui.tabComponent.repaint() } } private fun resetSingleContentView() { val adapter = tabAdapter ?: error("Adapter must not be null") tabAdapter = null ui.tabComponent.remove(adapter) Disposer.dispose(adapter) toolbars.values.forEach { ui.tabComponent.remove(it.component) } toolbars.clear() ui.tabComponent.remove(wrapper ?: error("Wrapper must not be null")) wrapper = null isSingleContentView = false adapter.content.getSupplier()?.reset() } private fun createToolbar(place: String, group: ActionGroup, target: JComponent? = null): ActionToolbar { val toolbar = ActionManager.getInstance().createActionToolbar(place, group, true) toolbar.setTargetComponent(target) toolbar.component.isOpaque = false return toolbar } override fun isToDrawTabs(): TabsDrawMode { return if (isSingleContentView) TabsDrawMode.HIDE else super.isToDrawTabs() } override fun layout() { super.layout() if (isSingleContentView) { val component = ui.tabComponent component.bounds = component.bounds.apply { width = component.parent.width } val labelWidth = idLabel.x + idLabel.preferredSize.width var tabsWidth = tabAdapter?.preferredSize?.width ?: 0 var mainToolbarWidth = toolbars[ToolbarType.MAIN]?.component?.preferredSize?.width ?: 0 val contentToolbarWidth = toolbars[ToolbarType.CLOSE_GROUP]?.component?.preferredSize?.width ?: 0 val minTabWidth = tabAdapter?.minimumSize?.width ?: 0 val fixedWidth = labelWidth + mainToolbarWidth + contentToolbarWidth val freeWidth = component.bounds.width - fixedWidth if (freeWidth < minTabWidth) { mainToolbarWidth += freeWidth - minTabWidth } tabsWidth = maxOf(minTabWidth, minOf(freeWidth, tabsWidth)) val wrapperWidth = maxOf(0, freeWidth - tabsWidth) var x = labelWidth tabAdapter?.apply { bounds = Rectangle(x, 0, tabsWidth, component.height) x += tabsWidth } toolbars[ToolbarType.MAIN]?.component?.apply { val height = preferredSize.height bounds = Rectangle(x, (component.height - height) / 2, mainToolbarWidth, height) x += mainToolbarWidth } wrapper?.apply { bounds = Rectangle(x, 0, wrapperWidth, component.height) x += wrapperWidth } toolbars[ToolbarType.CLOSE_GROUP]?.component?.apply { val height = preferredSize.height bounds = Rectangle(x, (component.height - height) / 2, contentToolbarWidth, height) x += contentToolbarWidth } } } override fun updateIdLabel(label: BaseLabel) { super.updateIdLabel(label) if (!isSingleContentView) { label.icon = null label.toolTipText = null } else if (tabs.size == 1) { label.icon = tabs[0].content.icon val displayName = tabs[0].content.displayName label.text = createProcessName( prefix = ui.window.stripeTitle, title = displayName ) label.toolTipText = displayName } } @NlsSafe private fun createProcessName(title: String, prefix: String? = null) = prefix?.let { if (isNewUI()) it else "$it:" } ?: title private inner class TabAdapter( val content: Content, val jbTabs: JBTabs, val tabPainter: JBTabPainter, val twcui: ToolWindowContentUi ) : NonOpaquePanel(), TabsListener, PropertyChangeListener, DataProvider, MorePopupAware, Disposable { private val labels = mutableListOf<MyContentTabLabel>() private val popupToolbar: JComponent private val popupHandler = object : PopupHandler() { override fun invokePopup(comp: Component, x: Int, y: Int) = showPopup(comp, x, y) } private val closeHandler = object : MouseAdapter() { override fun mouseReleased(e: MouseEvent) { if (UIUtil.isCloseClick(e, MouseEvent.MOUSE_RELEASED)) { val tabLabel = e.component as? MyContentTabLabel if (tabLabel != null && tabLabel.content.isCloseable) { tabLabel?.closeContent() } } } } private val containerListener = object : ContainerListener { override fun componentAdded(e: ContainerEvent) = update(e) override fun componentRemoved(e: ContainerEvent) = update(e) private fun update(e: ContainerEvent) { if (e.child is TabLabel) { checkAndUpdate() } } } init { updateTabs() jbTabs.addListener(object : TabsListener { override fun selectionChanged(oldSelection: TabInfo?, newSelection: TabInfo?) = checkAndUpdate() override fun tabRemoved(tabToRemove: TabInfo) = checkAndUpdate() override fun tabsMoved() = checkAndUpdate() }, this) jbTabs.component.addContainerListener(containerListener) val tabList = ActionManager.getInstance().getAction("TabList") val tabListGroup = DefaultActionGroup(tabList, Separator.create(), MyInvisibleAction()) popupToolbar = createToolbar(ActionPlaces.TOOLWINDOW_POPUP, tabListGroup, this).apply { setReservePlaceAutoPopupIcon(false) layoutPolicy = ActionToolbar.NOWRAP_LAYOUT_POLICY }.component layout = HorizontalTabLayoutWithHiddenControl { labels.find { it.content.info == jbTabs.selectedInfo } } add(popupToolbar, HorizontalTabLayoutWithHiddenControl.CONTROL) } private fun retrieveInfo(label: MyContentTabLabel): TabInfo { return label.content.info } private fun checkAndUpdate() { val currentContent = getSingleContentOrNull() val currentSupplier = currentContent?.getSupplier() val src = currentSupplier?.getTabs()?.tabs ?: return val dst = labels.map(::retrieveInfo) if (!ContainerUtil.equalsIdentity(src, dst)) { updateTabs() } updateSingleContentView(currentContent, currentSupplier) updateLabels(labels) revalidate() } fun updateTabs() { labels.removeAll { retrieveInfo(it).changeSupport.removePropertyChangeListener(this) remove(it) true } val supplier = getSingleContentOrNull()?.getSupplier() ?: return if (jbTabs.tabs.size > 1) { labels.addAll(jbTabs.tabs.map { info -> info.changeSupport.addPropertyChangeListener(this) MyContentTabLabel(FakeContent(supplier, info), this@SingleContentLayout).apply { addMouseListener(closeHandler) } }) labels.forEach(::add) } updateLabels(labels) } fun updateLabels(labels: List<MyContentTabLabel>) { labels.associateBy { it.content.info }.forEach(::copyValues) } override fun dispose() { labels.forEach { retrieveInfo(it).changeSupport.removePropertyChangeListener(this) } jbTabs.component.removeContainerListener(containerListener) } override fun getMinimumSize(): Dimension { if (isMinimumSizeSet) { return super.getMinimumSize() } val minWidth = if (labels.isEmpty()) 0 else popupToolbar.preferredSize.width return Dimension(minWidth, 0) } fun copyValues(from: TabInfo, to: ContentLabel) { to.icon = from.icon to.text = from.text } fun showPopup(component: Component, x: Int, y: Int) { // ViewContext.CONTENT_KEY val info = ((component as? ContentTabLabel)?.content as? FakeContent)?.info if (info == null) { logger<SingleContentLayout>().warn("Cannot resolve label popup component. Event will be ignored") return } val supplier = getSingleContentOrNull()?.getSupplier() val toShow = getPopupMenu(supplier?.getTabs()) ?: return toShow.setTargetComponent(component) JBPopupMenu.showAt(RelativePoint(component, Point(x, y)), toShow.component) } private fun getPopupMenu(tabs: JBTabs?): ActionPopupMenu? { val jbTabsImpl = tabs as? JBTabsImpl ?: return null val popup = jbTabsImpl.popupGroup ?: return null val popupPlace = jbTabsImpl.popupPlace ?: ActionPlaces.UNKNOWN val group = DefaultActionGroup() group.addAll(popup) group.addSeparator() group.addAll(jbTabsImpl.navigationActions) return ActionManager.getInstance().createActionPopupMenu(popupPlace, group) } override fun paintComponent(g: Graphics) { if (g is Graphics2D) { labels.forEach { comp -> val labelBounds = comp.bounds if (jbTabs.selectedInfo == retrieveInfo(comp)) { tabPainter.paintSelectedTab(JBTabsPosition.top, g, labelBounds, 1, null, twcui.window.isActive, comp.isHovered) } else { tabPainter.paintTab(JBTabsPosition.top, g, labelBounds, 1, null, twcui.window.isActive, comp.isHovered) } } } super.paintComponent(g) } override fun propertyChange(evt: PropertyChangeEvent) { val source = evt.source as? TabInfo ?: error("Bad event source") val label = labels.find { it.content.info == source } ?: error("Cannot find label for $source") copyValues(source, label) } private inner class MyContentTabLabel(content: FakeContent, layout: TabContentLayout) : ContentTabLabel(content, layout), DataProvider { init { addMouseListener(popupHandler) } override fun selectContent() { retrieveInfo(this).let { jbTabs.select(it, true) } } public override fun closeContent() { retrieveInfo(this).let { info -> getSingleContentOrNull()?.getSupplier()?.close(info) } } override fun getData(dataId: String): Any? { if (JBTabsEx.NAVIGATION_ACTIONS_KEY.`is`(dataId)) { return jbTabs } return DataManagerImpl.getDataProviderEx(retrieveInfo(this).component)?.getData(dataId) } override fun getContent(): FakeContent { return super.getContent() as FakeContent } } override fun getData(dataId: String): Any? { if (MorePopupAware.KEY.`is`(dataId)) { return this } return null } override fun canShowMorePopup(): Boolean { return true } override fun showMorePopup() { val contentToShow = labels .filter { it.bounds.width <= 0 } .map(MyContentTabLabel::getContent) val step = object : BaseListPopupStep<FakeContent>(null, contentToShow) { override fun onChosen(selectedValue: FakeContent, finalChoice: Boolean): PopupStep<*>? { jbTabs.select(selectedValue.info, true) return FINAL_CHOICE } override fun getIconFor(value: FakeContent) = value.icon override fun getTextFor(value: FakeContent) = value.displayName } JBPopupFactory.getInstance() .createListPopup(step) .show(RelativePoint.getSouthWestOf(popupToolbar)) } } private class ExtendedTitleActionsGroup( val originActions: ActionGroup?, vararg extendedActions: AnAction ) : DefaultActionGroup() { init { extendedActions.forEach(::add) originActions?.let(::addAll) } } private inner class CloseCurrentContentAction : DumbAwareAction(CommonBundle.messagePointer("action.close"), AllIcons.Actions.Cancel) { override fun actionPerformed(e: AnActionEvent) { val content = getSingleContentOrNull() if (content != null && content.isPinned) { content.isPinned = false } else { content?.let { it.manager?.removeContent(it, true) } } } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = getSingleContentOrNull()?.isCloseable == true if (isPinned()) { e.presentation.icon = AllIcons.General.Pin_tab e.presentation.text = IdeBundle.message("action.unpin.tab") } else { e.presentation.icon = AllIcons.Actions.Cancel e.presentation.text = CommonBundle.message("action.close") } } private fun isPinned(): Boolean { return getSingleContentOrNull()?.isPinned == true } } /** * The minimal [Content] implementation. * * Is used only to pass as an argument to support [SingleContentLayout.TabAdapter.MyContentTabLabel]. * * All unused methods throw [IllegalStateException]. */ private class FakeContent(val supplier: SingleContentSupplier, val info: TabInfo) : Content { private val pcs = PropertyChangeSupport(this) override fun addPropertyChangeListener(l: PropertyChangeListener?) { pcs.addPropertyChangeListener(l) } override fun removePropertyChangeListener(l: PropertyChangeListener?) { pcs.removePropertyChangeListener(l) } override fun isSelected(): Boolean { return supplier.getTabs().selectedInfo == info } override fun isCloseable(): Boolean { return supplier.isClosable(info) } override fun isPinned(): Boolean { return false } override fun getManager(): ContentManager? { return null } override fun getIcon(): Icon? { return info.icon } @NlsSafe override fun getDisplayName(): String { return info.text } override fun <T : Any?> getUserData(key: Key<T>): T? { error("An operation is not supported") } override fun <T : Any?> putUserData(key: Key<T>, value: T?) { error("An operation is not supported") } override fun dispose() { error("An operation is not supported") } override fun getComponent(): JComponent { error("An operation is not supported") } override fun getPreferredFocusableComponent(): JComponent? { error("An operation is not supported") } override fun setComponent(component: JComponent?) { error("An operation is not supported") } override fun setPreferredFocusableComponent(component: JComponent?) { error("An operation is not supported") } override fun setPreferredFocusedComponent(computable: Computable<out JComponent>?) { error("An operation is not supported") } override fun setIcon(icon: Icon?) { error("An operation is not supported") } override fun setDisplayName(displayName: String?) { error("An operation is not supported") } override fun setTabName(tabName: String?) { error("An operation is not supported") } override fun getTabName(): String { error("An operation is not supported") } override fun getToolwindowTitle(): String { error("An operation is not supported") } override fun setToolwindowTitle(toolwindowTitle: String?) { error("An operation is not supported") } override fun getDisposer(): Disposable? { error("An operation is not supported") } override fun setDisposer(disposer: Disposable) { error("An operation is not supported") } override fun setShouldDisposeContent(value: Boolean) { error("An operation is not supported") } override fun getDescription(): String? { error("An operation is not supported") } override fun setDescription(description: String?) { error("An operation is not supported") } override fun release() { error("An operation is not supported") } override fun isValid(): Boolean { error("An operation is not supported") } override fun setPinned(locked: Boolean) { error("An operation is not supported") } override fun setPinnable(pinnable: Boolean) { error("An operation is not supported") } override fun isPinnable(): Boolean { error("An operation is not supported") } override fun setCloseable(closeable: Boolean) { error("An operation is not supported") } override fun setActions(actions: ActionGroup?, place: String?, contextComponent: JComponent?) { error("An operation is not supported") } override fun getActions(): ActionGroup? { error("An operation is not supported") } override fun setSearchComponent(comp: JComponent?) { error("An operation is not supported") } override fun getSearchComponent(): JComponent? { error("An operation is not supported") } override fun getPlace(): String { error("An operation is not supported") } override fun getActionsContextComponent(): JComponent? { error("An operation is not supported") } override fun setAlertIcon(icon: AlertIcon?) { error("An operation is not supported") } override fun getAlertIcon(): AlertIcon? { error("An operation is not supported") } override fun fireAlert() { error("An operation is not supported") } override fun getBusyObject(): BusyObject? { error("An operation is not supported") } override fun setBusyObject(`object`: BusyObject?) { error("An operation is not supported") } override fun getSeparator(): String { error("An operation is not supported") } override fun setSeparator(separator: String?) { error("An operation is not supported") } override fun setPopupIcon(icon: Icon?) { error("An operation is not supported") } override fun getPopupIcon(): Icon? { error("An operation is not supported") } override fun setExecutionId(executionId: Long) { error("An operation is not supported") } override fun getExecutionId(): Long { error("An operation is not supported") } } private class HorizontalTabLayoutWithHiddenControl( val selected: () -> JComponent? ) : AbstractLayoutManager() { private var control: Component? = null override fun addLayoutComponent(comp: Component?, constraints: Any?) { if (constraints == CONTROL) { assert(control == null) { "Cannot add a second control component" } control = comp } super.addLayoutComponent(comp, constraints) } override fun removeLayoutComponent(comp: Component?) { if (control === comp) { control = null } super.removeLayoutComponent(comp) } override fun preferredLayoutSize(parent: Container): Dimension { return parent.components.asSequence() .filterNot { it === control } .map { it.preferredSize } .fold(Dimension()) { acc, size -> acc.apply { width += size.width height = maxOf(acc.height, size.height, parent.height) } } } override fun layoutContainer(parent: Container) { var eachX = 0 val canFitAllComponents = parent.preferredSize.width <= parent.bounds.width val children = parent.components.asSequence().filterNot { it === control } if (canFitAllComponents) { children.forEach { val dim = it.preferredSize it.bounds = Rectangle(eachX, 0, dim.width, parent.height) eachX += dim.width } control?.bounds = Rectangle(0, 0, 0, 0) } else { // copy of [TabContentLayout#layout] val toLayout = children.toMutableList() val toRemove = mutableListOf<Component>() var requiredWidth = toLayout.sumOf { it.preferredSize.width } val selected = selected() val toFitWidth = parent.bounds.width - (control?.preferredSize?.width ?: 0) while (true) { if (requiredWidth <= toFitWidth) break if (toLayout.size <= 1) break if (toLayout.first() != selected) { requiredWidth -= toLayout.first().preferredSize.width + 1 toRemove += toLayout.first() toLayout.removeFirst() } else if (toLayout.last() != selected) { requiredWidth -= toLayout.last().preferredSize.width + 1 toRemove += toLayout.last() toLayout.removeLast() } else { break } } toLayout.forEach { val prefSize = it.preferredSize it.bounds = Rectangle(eachX, 0, minOf(prefSize.width, toFitWidth), parent.height) eachX += prefSize.width } toRemove.forEach { it.bounds = Rectangle(0, 0, 0, 0) } control?.let { val controlPrefSize = it.preferredSize it.bounds = Rectangle(Point(toFitWidth, (parent.height - controlPrefSize.height) / 2), controlPrefSize) } } } companion object { const val CONTROL = "ControlComponent" } } /** * Workaround action to prevent [Separator] disappearing when [SingleContentSupplier.getContentActions] is empty. */ private class MyInvisibleAction : DumbAwareAction(), CustomComponentAction { override fun actionPerformed(e: AnActionEvent) { error("An operation is not supported") } override fun createCustomComponent(presentation: Presentation, place: String): JComponent { return NonOpaquePanel() } } private class MyRedispatchMouseEventListener( val redispatch: (MouseEvent) -> Unit ) : MouseListener, MouseMotionListener { fun installOn(component: Component) { component.addMouseListener(this) component.addMouseMotionListener(this) } override fun mouseClicked(e: MouseEvent) = redispatch(e) override fun mousePressed(e: MouseEvent) = redispatch(e) override fun mouseReleased(e: MouseEvent) = redispatch(e) override fun mouseEntered(e: MouseEvent) = redispatch(e) override fun mouseExited(e: MouseEvent) = redispatch(e) override fun mouseDragged(e: MouseEvent) = redispatch(e) override fun mouseMoved(e: MouseEvent) = redispatch(e) } private enum class ToolbarType { MAIN, CLOSE_GROUP } }
apache-2.0
c5a152f1929c854292dd2be35cb628ce
30.242857
140
0.670665
4.901724
false
false
false
false
K0zka/kerub
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/storage/migrate/dead/block/MigrateBlockAllocationFactoryTest.kt
2
9673
package com.github.kerubistan.kerub.planner.steps.storage.migrate.dead.block import com.github.kerubistan.kerub.hostUp import com.github.kerubistan.kerub.model.LvmStorageCapability import com.github.kerubistan.kerub.model.VirtualMachineStatus import com.github.kerubistan.kerub.model.VirtualStorageLink import com.github.kerubistan.kerub.model.config.HostConfiguration import com.github.kerubistan.kerub.model.dynamic.CompositeStorageDeviceDynamic import com.github.kerubistan.kerub.model.dynamic.VirtualMachineDynamic import com.github.kerubistan.kerub.model.dynamic.VirtualStorageDeviceDynamic import com.github.kerubistan.kerub.model.dynamic.VirtualStorageLvmAllocation import com.github.kerubistan.kerub.model.hardware.BlockDevice import com.github.kerubistan.kerub.model.io.BusType import com.github.kerubistan.kerub.model.io.DeviceType import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.steps.AbstractFactoryVerifications import com.github.kerubistan.kerub.testDisk import com.github.kerubistan.kerub.testHost import com.github.kerubistan.kerub.testHostCapabilities import com.github.kerubistan.kerub.testVm import io.github.kerubistan.kroki.size.GB import io.github.kerubistan.kroki.size.TB import org.junit.Test import java.util.UUID import kotlin.test.assertTrue class MigrateBlockAllocationFactoryTest : AbstractFactoryVerifications(MigrateBlockAllocationFactory) { @Test fun produce() { assertTrue("only a single host - nowhere to migrate to") { val host1cap = LvmStorageCapability( physicalVolumes = mapOf("/dev/sda" to 1.TB), size = 1.TB, volumeGroupName = "vg-1" ) val host1 = testHost.copy( address = "host-1.example.com", id = UUID.randomUUID(), capabilities = testHostCapabilities.copy( blockDevices = listOf(BlockDevice(deviceName = "/dev/sda", storageCapacity = 1.TB)), storageCapabilities = listOf(host1cap) ) ) val host1dyn = hostUp(host1).copy( storageStatus = listOf( CompositeStorageDeviceDynamic( id = host1cap.id, reportedFreeCapacity = 1.TB ) ) ) val sourceAllocation = VirtualStorageLvmAllocation( hostId = host1.id, vgName = host1cap.volumeGroupName, capabilityId = host1cap.id, path = "/dev/vg-1/source", actualSize = 1.GB ) MigrateBlockAllocationFactory.produce( OperationalState.fromLists( hosts = listOf(host1), hostDyns = listOf(host1dyn), vStorage = listOf(testDisk), vStorageDyns = listOf( VirtualStorageDeviceDynamic( id = testDisk.id, allocations = listOf( sourceAllocation ) ) ) )).isEmpty() } assertTrue("two servers, plenty of space, rw disk - but ut is used by a vm - let's do nothing") { val host1cap = LvmStorageCapability( physicalVolumes = mapOf("/dev/sda" to 1.TB), size = 1.TB, volumeGroupName = "vg-1" ) val host1 = testHost.copy( address = "host-1.example.com", id = UUID.randomUUID(), capabilities = testHostCapabilities.copy( blockDevices = listOf(BlockDevice(deviceName = "/dev/sda", storageCapacity = 1.TB)), storageCapabilities = listOf(host1cap) ) ) val host2cap = LvmStorageCapability( physicalVolumes = mapOf("/dev/sda" to 1.TB), size = 1.TB, volumeGroupName = "vg-1" ) val host2 = testHost.copy( address = "host-2.example.com", id = UUID.randomUUID(), capabilities = testHostCapabilities.copy( blockDevices = listOf(BlockDevice(deviceName = "/dev/sda", storageCapacity = 1.TB)), storageCapabilities = listOf(host2cap) ) ) val host1dyn = hostUp(host1).copy( storageStatus = listOf( CompositeStorageDeviceDynamic( id = host1cap.id, reportedFreeCapacity = 1.TB ) ) ) val host2dyn = hostUp(host2).copy( storageStatus = listOf( CompositeStorageDeviceDynamic( id = host2cap.id, reportedFreeCapacity = 1.TB ) ) ) val sourceAllocation = VirtualStorageLvmAllocation( hostId = host1.id, vgName = host1cap.volumeGroupName, capabilityId = host1cap.id, path = "/dev/vg-1/source", actualSize = 1.GB ) val vm = testVm.copy( virtualStorageLinks = listOf( VirtualStorageLink( virtualStorageId = testDisk.id, device = DeviceType.disk, readOnly = false, bus = BusType.sata ) ) ) MigrateBlockAllocationFactory.produce( OperationalState.fromLists( hosts = listOf(host1, host2), hostDyns = listOf(host1dyn, host2dyn), vms = listOf(vm), vmDyns = listOf( VirtualMachineDynamic( id = vm.id, status = VirtualMachineStatus.Up, memoryUsed = 1.GB, hostId = host1.id ) ), vStorage = listOf(testDisk), vStorageDyns = listOf( VirtualStorageDeviceDynamic( id = testDisk.id, allocations = listOf( sourceAllocation ) ) ) )).isEmpty() } assertTrue("two servers, rw disk - but not enough free space on the other server - let's do nothing") { val host1cap = LvmStorageCapability( physicalVolumes = mapOf("/dev/sda" to 1.TB), size = 1.TB, volumeGroupName = "vg-1" ) val host1 = testHost.copy( address = "host-1.example.com", id = UUID.randomUUID(), capabilities = testHostCapabilities.copy( blockDevices = listOf(BlockDevice(deviceName = "/dev/sda", storageCapacity = 1.TB)), storageCapabilities = listOf(host1cap) ) ) val host2cap = LvmStorageCapability( physicalVolumes = mapOf("/dev/sda" to 1.TB), size = 1.TB, volumeGroupName = "vg-1" ) val host2 = testHost.copy( address = "host-2.example.com", id = UUID.randomUUID(), capabilities = testHostCapabilities.copy( blockDevices = listOf(BlockDevice(deviceName = "/dev/sda", storageCapacity = 1.TB)), storageCapabilities = listOf(host2cap) ) ) val host1dyn = hostUp(host1).copy( storageStatus = listOf( CompositeStorageDeviceDynamic( id = host1cap.id, reportedFreeCapacity = 1.TB ) ) ) val host2dyn = hostUp(host2).copy( storageStatus = listOf( CompositeStorageDeviceDynamic( id = host2cap.id, reportedFreeCapacity = 0.TB ) ) ) val sourceAllocation = VirtualStorageLvmAllocation( hostId = host1.id, vgName = host1cap.volumeGroupName, capabilityId = host1cap.id, path = "/dev/vg-1/source", actualSize = 1.GB ) MigrateBlockAllocationFactory.produce( OperationalState.fromLists( hosts = listOf(host1, host2), hostDyns = listOf(host1dyn, host2dyn), vStorage = listOf(testDisk), vStorageDyns = listOf( VirtualStorageDeviceDynamic( id = testDisk.id, allocations = listOf( sourceAllocation ) ) ) )).isEmpty() } assertTrue("two servers, plenty of space, rw disk - let's do it") { val host1cap = LvmStorageCapability( physicalVolumes = mapOf("/dev/sda" to 1.TB), size = 1.TB, volumeGroupName = "vg-1" ) val host1 = testHost.copy( address = "host-1.example.com", id = UUID.randomUUID(), capabilities = testHostCapabilities.copy( blockDevices = listOf(BlockDevice(deviceName = "/dev/sda", storageCapacity = 1.TB)), storageCapabilities = listOf(host1cap) ) ) val host2cap = LvmStorageCapability( physicalVolumes = mapOf("/dev/sda" to 1.TB), size = 1.TB, volumeGroupName = "vg-1" ) val host2 = testHost.copy( address = "host-2.example.com", id = UUID.randomUUID(), capabilities = testHostCapabilities.copy( blockDevices = listOf(BlockDevice(deviceName = "/dev/sda", storageCapacity = 1.TB)), storageCapabilities = listOf(host2cap) ) ) val host1dyn = hostUp(host1).copy( storageStatus = listOf( CompositeStorageDeviceDynamic( id = host1cap.id, reportedFreeCapacity = 1.TB ) ) ) val host2dyn = hostUp(host2).copy( storageStatus = listOf( CompositeStorageDeviceDynamic( id = host2cap.id, reportedFreeCapacity = 1.TB ) ) ) val sourceAllocation = VirtualStorageLvmAllocation( hostId = host1.id, vgName = host1cap.volumeGroupName, capabilityId = host1cap.id, path = "/dev/vg-1/source", actualSize = 1.GB ) MigrateBlockAllocationFactory.produce( OperationalState.fromLists( hosts = listOf(host1, host2), hostDyns = listOf(host1dyn, host2dyn), hostCfgs = listOf( HostConfiguration(id = host1.id, publicKey = "host1-public-key"), HostConfiguration(id = host2.id, acceptedPublicKeys = listOf("host1-public-key")) ), vStorage = listOf(testDisk), vStorageDyns = listOf( VirtualStorageDeviceDynamic( id = testDisk.id, allocations = listOf( sourceAllocation ) ) ) )).single().let { it.sourceAllocation == sourceAllocation && it.sourceHost == host1 && it.targetHost == host2 && it.allocationStep.host == host2 && it.allocationStep.capability == host2cap && it.deAllocationStep.host == host1 && it.deAllocationStep.allocation == sourceAllocation && it.virtualStorage == testDisk } } } }
apache-2.0
5c9e1d003bc21d72ec3aae66006ebedd
30.206452
105
0.646645
3.908283
false
true
false
false
dahlstrom-g/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/inspections/declarations/HLRedundantUnitReturnTypeInspection.kt
3
2080
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.fir.inspections.declarations import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.codeInspection.ProblemHighlightType import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.api.applicator.with import org.jetbrains.kotlin.idea.fir.api.AbstractHLInspection import org.jetbrains.kotlin.idea.fir.api.applicator.inputProvider import org.jetbrains.kotlin.idea.fir.api.applicator.presentation import org.jetbrains.kotlin.idea.fir.applicators.ApplicabilityRanges import org.jetbrains.kotlin.idea.fir.applicators.CallableReturnTypeUpdaterApplicator import org.jetbrains.kotlin.psi.KtNamedFunction internal class HLRedundantUnitReturnTypeInspection : AbstractHLInspection<KtNamedFunction, CallableReturnTypeUpdaterApplicator.TypeInfo>( KtNamedFunction::class ), CleanupLocalInspectionTool { override val applicabilityRange = ApplicabilityRanges.CALLABLE_RETURN_TYPE override val applicator = CallableReturnTypeUpdaterApplicator.applicator.with { isApplicableByPsi { callable -> val function = callable as? KtNamedFunction ?: return@isApplicableByPsi false function.hasBlockBody() && function.typeReference != null } familyName(KotlinBundle.lazyMessage("remove.explicit.type.specification")) actionName(KotlinBundle.lazyMessage("redundant.unit.return.type")) } override val inputProvider = inputProvider<KtNamedFunction, CallableReturnTypeUpdaterApplicator.TypeInfo> { function -> when { function.getFunctionLikeSymbol().returnType.isUnit -> CallableReturnTypeUpdaterApplicator.TypeInfo(CallableReturnTypeUpdaterApplicator.TypeInfo.UNIT) else -> null } } override val presentation = presentation<KtNamedFunction> { highlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL) } }
apache-2.0
64e7742a3d08b3b6a08b0fd1b28114e4
47.372093
158
0.783173
5.430809
false
false
false
false
dahlstrom-g/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/RemoveChangeListAction.kt
10
6999
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.actions import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsDataKeys import com.intellij.openapi.vcs.changes.ChangeList import com.intellij.openapi.vcs.changes.ChangeListManagerEx import com.intellij.openapi.vcs.changes.LocalChangeList import com.intellij.util.ArrayUtil import com.intellij.util.ThreeState import java.util.* class RemoveChangeListAction : AbstractChangeListAction() { private val LOG = logger<RemoveChangeListAction>() override fun update(e: AnActionEvent) { val changeListsArray = e.getData(VcsDataKeys.CHANGE_LISTS) val changeLists = changeListsArray?.asList() ?: emptyList() val enabled = canRemoveChangeLists(e.project, changeLists) updateEnabledAndVisible(e, enabled) val presentation = e.presentation presentation.text = ActionsBundle.message("action.ChangesView.RemoveChangeList.text.template", changeLists.size) val hasChanges = !ArrayUtil.isEmpty(e.getData(VcsDataKeys.CHANGES)) if (hasChanges) { val containsActiveChangelist = changeLists.any { it is LocalChangeList && it.isDefault } val changeListName = if (containsActiveChangelist) VcsBundle.message("changes.another.change.list") else VcsBundle.message("changes.default.change.list") presentation.description = ActionsBundle.message("action.ChangesView.RemoveChangeList.description.template", changeLists.size, changeListName) } else { presentation.description = null } } private fun canRemoveChangeLists(project: Project?, lists: List<ChangeList>): Boolean { if (project == null || lists.isEmpty()) return false for (changeList in lists) { if (changeList !is LocalChangeList) return false if (changeList.isReadOnly) return false } return true } override fun actionPerformed(e: AnActionEvent) { val project = e.getRequiredData(CommonDataKeys.PROJECT) val selectedLists = e.getRequiredData(VcsDataKeys.CHANGE_LISTS) @Suppress("UNCHECKED_CAST") deleteLists(project, Arrays.asList(*selectedLists) as Collection<LocalChangeList>) } private fun deleteLists(project: Project, lists: Collection<LocalChangeList>) { val manager = ChangeListManagerEx.getInstanceEx(project) val toRemove = mutableListOf<LocalChangeList>() val toAsk = mutableListOf<LocalChangeList>() for (list in lists.mapNotNull { manager.getChangeList(it.id) }) { when (ChangeListRemoveConfirmation.checkCanDeleteChangelist(project, list, explicitly = true)) { ThreeState.UNSURE -> toAsk.add(list) ThreeState.YES -> toRemove.add(list) ThreeState.NO -> { } } } val pendingLists = toAsk + toRemove val activeChangelistSelected = pendingLists.any { it.isDefault } if (activeChangelistSelected) { val remainingLists = manager.changeLists.subtract(pendingLists).toList() if (remainingLists.isEmpty()) { if (!confirmAllChangeListsRemoval(project, pendingLists, toAsk)) return var defaultList = manager.findChangeList(LocalChangeList.getDefaultName()) if (defaultList == null) { defaultList = manager.addChangeList(LocalChangeList.getDefaultName(), null) } else { manager.editComment(defaultList.name, null) manager.editChangeListData(defaultList.name, null) } manager.setDefaultChangeList(defaultList!!) toRemove.addAll(toAsk) toRemove.remove(defaultList) } else { val newDefault = askNewDefaultChangeList(project, toAsk, remainingLists) ?: return manager.setDefaultChangeList(newDefault) toRemove.addAll(toAsk) if (toRemove.remove(newDefault)) LOG.error("New default changelist should be selected among remaining") } } else { if (confirmChangeListRemoval(project, toAsk)) { toRemove.addAll(toAsk) } } toRemove.forEach { manager.removeChangeList(it.name) } } private fun confirmChangeListRemoval(project: Project, lists: List<LocalChangeList>): Boolean { val haveNoChanges = lists.all { it.changes.isEmpty() } if (haveNoChanges) return true val message = if (lists.size == 1) VcsBundle.message("changes.removechangelist.warning.text", lists.single().name) else VcsBundle.message("changes.removechangelist.multiple.warning.text", lists.size) return Messages.YES == Messages.showYesNoDialog(project, message, VcsBundle.message("changes.removechangelist.warning.title"), Messages.getQuestionIcon()) } private fun confirmAllChangeListsRemoval(project: Project, pendingLists: List<LocalChangeList>, toAsk: List<LocalChangeList>): Boolean { if (pendingLists.size == 1) return true if (toAsk.isEmpty()) return true val haveNoChanges = pendingLists.all { it.changes.isEmpty() } if (haveNoChanges) return true val message = VcsBundle.message("changes.removechangelist.all.lists.warning.text", pendingLists.size) return Messages.YES == Messages.showYesNoDialog(project, message, VcsBundle.message("changes.removechangelist.warning.title"), Messages.getQuestionIcon()) } private fun askNewDefaultChangeList(project: Project, lists: List<LocalChangeList>, remainingLists: List<LocalChangeList>): LocalChangeList? { assert(remainingLists.isNotEmpty()) val haveNoChanges = lists.all { it.changes.isEmpty() } // don't ask "Which changelist to make active" if there is only one option anyway // unless there are some changes to be moved - give user a chance to cancel deletion if (remainingLists.size == 1 && haveNoChanges) { return remainingLists.single() } else { val remainingListsNames = remainingLists.map { it.name }.toTypedArray() val message = if (haveNoChanges) VcsBundle.message("changes.remove.active.empty.prompt") else VcsBundle.message("changes.remove.active.prompt") val nameIndex = Messages.showChooseDialog(project, message, VcsBundle.message("changes.remove.active.title"), Messages.getQuestionIcon(), remainingListsNames, remainingListsNames.first()) if (nameIndex < 0) return null return remainingLists[nameIndex] } } }
apache-2.0
99bd66dfa8a3ba18cc9dc5c67bf7272a
39.697674
140
0.6971
4.901261
false
false
false
false
androidx/androidx
compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/RenderNodeApi29.android.kt
3
8647
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.platform import android.graphics.Outline import android.graphics.RenderNode import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.CanvasHolder import androidx.compose.ui.graphics.CompositingStrategy import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.RenderEffect /** * RenderNode on Q+ devices, where it is officially supported. */ @RequiresApi(Build.VERSION_CODES.Q) internal class RenderNodeApi29(val ownerView: AndroidComposeView) : DeviceRenderNode { private val renderNode = RenderNode("Compose") private var internalRenderEffect: RenderEffect? = null private var internalCompositingStrategy: CompositingStrategy = CompositingStrategy.Auto internal fun isUsingCompositingLayer(): Boolean = renderNode.useCompositingLayer internal fun hasOverlappingRendering(): Boolean = renderNode.hasOverlappingRendering() override val uniqueId: Long get() = renderNode.uniqueId override val left: Int get() = renderNode.left override val top: Int get() = renderNode.top override val right: Int get() = renderNode.right override val bottom: Int get() = renderNode.bottom override val width: Int get() = renderNode.width override val height: Int get() = renderNode.height override var scaleX: Float get() = renderNode.scaleX set(value) { renderNode.scaleX = value } override var scaleY: Float get() = renderNode.scaleY set(value) { renderNode.scaleY = value } override var translationX: Float get() = renderNode.translationX set(value) { renderNode.translationX = value } override var translationY: Float get() = renderNode.translationY set(value) { renderNode.translationY = value } override var elevation: Float get() = renderNode.elevation set(value) { renderNode.elevation = value } override var ambientShadowColor: Int get() = renderNode.ambientShadowColor set(value) { renderNode.ambientShadowColor = value } override var spotShadowColor: Int get() = renderNode.spotShadowColor set(value) { renderNode.spotShadowColor = value } override var rotationZ: Float get() = renderNode.rotationZ set(value) { renderNode.rotationZ = value } override var rotationX: Float get() = renderNode.rotationX set(value) { renderNode.rotationX = value } override var rotationY: Float get() = renderNode.rotationY set(value) { renderNode.rotationY = value } override var cameraDistance: Float get() = renderNode.cameraDistance set(value) { renderNode.cameraDistance = value } override var pivotX: Float get() = renderNode.pivotX set(value) { renderNode.pivotX = value } override var pivotY: Float get() = renderNode.pivotY set(value) { renderNode.pivotY = value } override var clipToOutline: Boolean get() = renderNode.clipToOutline set(value) { renderNode.clipToOutline = value } override var clipToBounds: Boolean get() = renderNode.clipToBounds set(value) { renderNode.clipToBounds = value } override var alpha: Float get() = renderNode.alpha set(value) { renderNode.alpha = value } override var renderEffect: RenderEffect? get() = internalRenderEffect set(value) { internalRenderEffect = value if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { RenderNodeApi29VerificationHelper.setRenderEffect(renderNode, value) } } override var compositingStrategy: CompositingStrategy get() = internalCompositingStrategy set(value) { with(renderNode) { when (value) { CompositingStrategy.Offscreen -> { setUseCompositingLayer(true, null) setHasOverlappingRendering(true) } CompositingStrategy.ModulateAlpha -> { setUseCompositingLayer(false, null) setHasOverlappingRendering(false) } else -> { // CompositingStrategy.Auto setUseCompositingLayer(false, null) setHasOverlappingRendering(true) } } } internalCompositingStrategy = value } override val hasDisplayList: Boolean get() = renderNode.hasDisplayList() override fun setOutline(outline: Outline?) { renderNode.setOutline(outline) } override fun setPosition(left: Int, top: Int, right: Int, bottom: Int): Boolean { return renderNode.setPosition(left, top, right, bottom) } override fun offsetLeftAndRight(offset: Int) { renderNode.offsetLeftAndRight(offset) } override fun offsetTopAndBottom(offset: Int) { renderNode.offsetTopAndBottom(offset) } override fun record( canvasHolder: CanvasHolder, clipPath: Path?, drawBlock: (Canvas) -> Unit ) { canvasHolder.drawInto(renderNode.beginRecording()) { if (clipPath != null) { save() clipPath(clipPath) } drawBlock(this) if (clipPath != null) { restore() } } renderNode.endRecording() } override fun getMatrix(matrix: android.graphics.Matrix) { return renderNode.getMatrix(matrix) } override fun getInverseMatrix(matrix: android.graphics.Matrix) { return renderNode.getInverseMatrix(matrix) } override fun drawInto(canvas: android.graphics.Canvas) { canvas.drawRenderNode(renderNode) } override fun setHasOverlappingRendering(hasOverlappingRendering: Boolean): Boolean = renderNode.setHasOverlappingRendering(hasOverlappingRendering) override fun dumpRenderNodeData(): DeviceRenderNodeData = DeviceRenderNodeData( uniqueId = renderNode.uniqueId, left = renderNode.left, top = renderNode.top, right = renderNode.right, bottom = renderNode.bottom, width = renderNode.width, height = renderNode.height, scaleX = renderNode.scaleX, scaleY = renderNode.scaleY, translationX = renderNode.translationX, translationY = renderNode.translationY, elevation = renderNode.elevation, ambientShadowColor = renderNode.ambientShadowColor, spotShadowColor = renderNode.spotShadowColor, rotationZ = renderNode.rotationZ, rotationX = renderNode.rotationX, rotationY = renderNode.rotationY, cameraDistance = renderNode.cameraDistance, pivotX = renderNode.pivotX, pivotY = renderNode.pivotY, clipToOutline = renderNode.clipToOutline, clipToBounds = renderNode.clipToBounds, alpha = renderNode.alpha, renderEffect = internalRenderEffect, compositingStrategy = internalCompositingStrategy ) override fun discardDisplayList() { renderNode.discardDisplayList() } } @RequiresApi(Build.VERSION_CODES.S) private object RenderNodeApi29VerificationHelper { @androidx.annotation.DoNotInline fun setRenderEffect(renderNode: RenderNode, target: RenderEffect?) { renderNode.setRenderEffect(target?.asAndroidRenderEffect()) } }
apache-2.0
69481f0ad053df949d61fd85cbcb74e1
30.673993
91
0.629814
5.291922
false
false
false
false
androidx/androidx
datastore/datastore-core/src/androidMain/kotlin/androidx/datastore/core/MultiProcessDataStoreFactory.kt
3
6622
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.datastore.core import androidx.datastore.core.handlers.NoOpCorruptionHandler import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler import java.io.File import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob public object MultiProcessDataStoreFactory { /** * Create an instance of MultiProcessDataStore, which provides cross-process eventual * consistency. Never create more than one instance of DataStore for a given file in the same * process; doing so can break all DataStore functionality. You should consider managing your * DataStore instance for each file as a singleton. If there are multiple DataStores active for * a given file in the same process, DataStore will throw IllegalStateException when reading or * updating data. A DataStore is considered active as long as its scope is active. Having * multiple instances, each for a different file, in the same process is OK. * * T is the type DataStore acts on. The type T must be immutable. Mutating a type used in * DataStore invalidates any guarantees that DataStore provides and will result in * potentially serious, hard-to-catch bugs. We strongly recommend using protocol buffers: * https://developers.google.com/protocol-buffers/docs/javatutorial - which provides * immutability guarantees, a simple API and efficient serialization. * * @param storage Storage to handle file reads and writes used with DataStore. The type T must * be immutable. The storage must operate on the same file as the one passed in * {@link produceFile}. * @param corruptionHandler The [ReplaceFileCorruptionHandler] is invoked if DataStore * encounters a [CorruptionException] when attempting to read data. CorruptionExceptions are * thrown by serializers when data can not be de-serialized. * @param migrations Migrations are run before any access to data can occur. Migrations must * be idempotent. * @param scope The scope in which IO operations and transform functions will execute. * @param produceFile Function which returns the file that the new DataStore will act on. The * function must return the same path every time. No two instances of DataStore should act on * the same file at the same time in the same process. * * @return a new DataStore instance with the provided configuration */ @ExperimentalMultiProcessDataStore @JvmOverloads // Generate constructors for default params for java users. public fun <T> create( storage: Storage<T>, corruptionHandler: ReplaceFileCorruptionHandler<T>? = null, migrations: List<DataMigration<T>> = listOf(), scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()), produceFile: () -> File ): DataStore<T> = MultiProcessDataStore<T>( storage = storage, produceFile = produceFile, initTasksList = listOf(DataMigrationInitializer.getInitializer(migrations)), corruptionHandler = corruptionHandler ?: NoOpCorruptionHandler(), scope = scope ) /** * Create an instance of MultiProcessDataStore, which provides cross-process eventual * consistency. Never create more than one instance of DataStore for a given file in the same * process; doing so can break all DataStore functionality. You should consider managing your * DataStore instance for each file as a singleton. If there are multiple DataStores active for * a given file in the same process, DataStore will throw IllegalStateException when reading or * updating data. A DataStore is considered active as long as its scope is active. Having * multiple instances, each for a different file, in the same process is OK. * * T is the type DataStore acts on. The type T must be immutable. Mutating a type used in * DataStore invalidates any guarantees that DataStore provides and will result in * potentially serious, hard-to-catch bugs. We strongly recommend using protocol buffers: * https://developers.google.com/protocol-buffers/docs/javatutorial - which provides * immutability guarantees, a simple API and efficient serialization. * * @param serializer Serializer for the type T used with DataStore. The type T must be immutable. * @param corruptionHandler The {@link androidx.datastore.core.handlers.ReplaceFileCorruptionHandler} * is invoked if DataStore encounters a [CorruptionException] when attempting to read data. * CorruptionExceptions are thrown by serializers when data can not be de-serialized. * @param migrations Migrations are run before any access to data can occur. Migrations must * be idempotent. * @param scope The scope in which IO operations and transform functions will execute. * @param produceFile Function which returns the file that the new DataStore will act on. The * function must return the same path every time. No two instances of DataStore should act on * the same file at the same time in the same process. * * @return a new DataStore instance with the provided configuration */ @ExperimentalMultiProcessDataStore @JvmOverloads // Generate constructors for default params for java users. public fun <T> create( serializer: Serializer<T>, corruptionHandler: ReplaceFileCorruptionHandler<T>? = null, migrations: List<DataMigration<T>> = listOf(), scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()), produceFile: () -> File ): DataStore<T> = MultiProcessDataStore<T>( storage = FileStorage(serializer, produceFile), initTasksList = listOf(DataMigrationInitializer.getInitializer(migrations)), corruptionHandler = corruptionHandler ?: NoOpCorruptionHandler(), scope = scope, produceFile = produceFile ) }
apache-2.0
7195ad0c9031e4e92943c5657f9a6fc8
56.086207
105
0.737844
5.157321
false
false
false
false
androidx/androidx
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/window/WindowState.desktop.kt
3
8882
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.window import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp /** * Creates a [WindowState] that is remembered across compositions. * * Changes to the provided initial values will **not** result in the state being recreated or * changed in any way if it has already been created. * * @param placement the initial value for [WindowState.placement] * @param isMinimized the initial value for [WindowState.isMinimized] * @param position the initial value for [WindowState.position] * @param size the initial value for [WindowState.size] */ @Composable fun rememberWindowState( placement: WindowPlacement = WindowPlacement.Floating, isMinimized: Boolean = false, position: WindowPosition = WindowPosition.PlatformDefault, size: DpSize = DpSize(800.dp, 600.dp), ): WindowState = rememberSaveable(saver = WindowStateImpl.Saver(position)) { WindowStateImpl( placement, isMinimized, position, size ) } /** * Creates a [WindowState] that is remembered across compositions. * * Changes to the provided initial values will **not** result in the state being recreated or * changed in any way if it has already been created. * * @param placement the initial value for [WindowState.placement] * @param isMinimized the initial value for [WindowState.isMinimized] * @param position the initial value for [WindowState.position] * @param size the initial value for [WindowState.size] */ @Suppress("DEPRECATION") @Composable @Deprecated("Use rememberWindowState which accepts DpSize") fun rememberWindowState( placement: WindowPlacement = WindowPlacement.Floating, isMinimized: Boolean = false, position: WindowPosition = WindowPosition.PlatformDefault, size: WindowSize ): WindowState = rememberSaveable(saver = WindowStateImpl.Saver(position)) { WindowStateImpl( placement, isMinimized, position, DpSize(size.width, size.height) ) } /** * Creates a [WindowState] that is remembered across compositions. * * Changes to the provided initial values will **not** result in the state being recreated or * changed in any way if it has already been created. * * @param placement the initial value for [WindowState.placement] * @param isMinimized the initial value for [WindowState.isMinimized] * @param position the initial value for [WindowState.position] * @param width the initial value for width of [WindowState.size] * @param height the initial value for height of [WindowState.size] */ @Composable fun rememberWindowState( placement: WindowPlacement = WindowPlacement.Floating, isMinimized: Boolean = false, position: WindowPosition = WindowPosition.PlatformDefault, width: Dp = 800.dp, height: Dp = 600.dp ): WindowState = rememberSaveable(saver = WindowStateImpl.Saver(position)) { WindowStateImpl( placement, isMinimized, position, DpSize(width, height) ) } /** * A state object that can be hoisted to control and observe window attributes * (size/position/state). * * @param placement the initial value for [WindowState.placement] * @param isMinimized the initial value for [WindowState.isMinimized] * @param position the initial value for [WindowState.position] * @param size the initial value for [WindowState.size] */ fun WindowState( placement: WindowPlacement = WindowPlacement.Floating, isMinimized: Boolean = false, position: WindowPosition = WindowPosition.PlatformDefault, size: DpSize = DpSize(800.dp, 600.dp) ): WindowState = WindowStateImpl( placement, isMinimized, position, size ) /** * A state object that can be hoisted to control and observe window attributes * (size/position/state). * * @param placement the initial value for [WindowState.placement] * @param isMinimized the initial value for [WindowState.isMinimized] * @param position the initial value for [WindowState.position] * @param size the initial value for [WindowState.size] */ @Deprecated("Use WindowState which accepts DpSize") @Suppress("DEPRECATION") fun WindowState( placement: WindowPlacement = WindowPlacement.Floating, isMinimized: Boolean = false, position: WindowPosition = WindowPosition.PlatformDefault, size: WindowSize ): WindowState = WindowStateImpl( placement, isMinimized, position, DpSize(size.width, size.height) ) /** * A state object that can be hoisted to control and observe window attributes * (size/position/state). * * @param placement the initial value for [WindowState.placement] * @param isMinimized the initial value for [WindowState.isMinimized] * @param position the initial value for [WindowState.position] * @param width the initial value for width of [WindowState.size] * @param height the initial value for height of [WindowState.size] */ fun WindowState( placement: WindowPlacement = WindowPlacement.Floating, isMinimized: Boolean = false, position: WindowPosition = WindowPosition.PlatformDefault, width: Dp = 800.dp, height: Dp = 600.dp ): WindowState = WindowStateImpl( placement, isMinimized, position, DpSize(width, height) ) /** * A state object that can be hoisted to control and observe window attributes * (size/position/state). */ interface WindowState { /** * Describes how the window is placed on the screen. */ var placement: WindowPlacement /** * `true` if the window is minimized. */ var isMinimized: Boolean /** * The current position of the window. If the position is not specified * ([WindowPosition.isSpecified] is false), the position will be set to absolute values * [WindowPosition.Absolute] when the window appears on the screen. */ var position: WindowPosition /** * The current size of the window. * * If the size is not specified * ([DpSize.width.isSpecified] or [DpSize.height.isSpecified] is false), the size will be set * to absolute values * ([Dp.isSpecified] is true) when the window appears on the screen. * * Unspecified can be only width, only height, or both. If, for example, window contains some * text and we use size=DpSize(300.dp, Dp.Unspecified) then the width will be exactly * 300.dp, but the height will be such that all the text will fit. */ var size: DpSize } private class WindowStateImpl( placement: WindowPlacement, isMinimized: Boolean, position: WindowPosition, size: DpSize ) : WindowState { override var placement by mutableStateOf(placement) override var isMinimized by mutableStateOf(isMinimized) override var position by mutableStateOf(position) override var size by mutableStateOf(size) companion object { /** * The default [Saver] implementation for [WindowStateImpl]. */ fun Saver(unspecifiedPosition: WindowPosition) = listSaver<WindowState, Any>( save = { listOf( it.placement.ordinal, it.isMinimized, it.position.isSpecified, it.position.x.value, it.position.y.value, it.size.width.value, it.size.height.value, ) }, restore = { state -> WindowStateImpl( placement = WindowPlacement.values()[state[0] as Int], isMinimized = state[1] as Boolean, position = if (state[2] as Boolean) { WindowPosition((state[3] as Float).dp, (state[4] as Float).dp) } else { unspecifiedPosition }, size = DpSize((state[5] as Float).dp, (state[6] as Float).dp), ) } ) } }
apache-2.0
01b2a958fd632981ff258e900ffa8382
34.818548
97
0.694551
4.652698
false
false
false
false
GunoH/intellij-community
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/attach/dialog/items/AttachToProcessTableSelectionModel.kt
2
3357
package com.intellij.xdebugger.impl.ui.attach.dialog.items import com.intellij.ui.table.JBTable import java.awt.Rectangle import javax.swing.DefaultListSelectionModel import javax.swing.ListSelectionModel import javax.swing.table.TableModel internal interface AttachSelectionIgnoredNode internal interface AttachNodeContainer<TNodeType> { fun getAttachNode(): TNodeType } class AttachToProcessTableSelectionModel(private val table: JBTable) : DefaultListSelectionModel() { init { selectionMode = ListSelectionModel.SINGLE_SELECTION } override fun setSelectionInterval(index0: Int, index1: Int) { if (index0 >= 0 && index0 < table.rowCount && table.model.getValueAt<Any>(index0) is AttachSelectionIgnoredNode) { val currentIndex = minSelectionIndex if (currentIndex < 0 || currentIndex >= table.rowCount) { val next = getNextIndex(index0) setSelectionInterval(next, next) return } if (currentIndex == index0 - 1) { val newIndex = getNextIndex(index0) setSelectionInterval(newIndex, newIndex) return } if (currentIndex == index0 + 1) { val newIndex = getPreviousIndex(index0) setSelectionInterval(newIndex, newIndex) return } setSelectionInterval(-1, -1) return } super.setSelectionInterval(index0, index1) scrollIfNeeded(index0) } override fun addSelectionInterval(index0: Int, index1: Int) { if (index0 >= 0 && index0 < table.rowCount && table.model.getValueAt<Any>(index0) is AttachSelectionIgnoredNode) { return } super.addSelectionInterval(index0, index1) scrollIfNeeded(index0) } private fun scrollIfNeeded(index0: Int) { if (index0 >= 0 && index0 < table.rowCount) { val cellRect = table.getCellRect(index0, 0, true) val visibleRect = table.visibleRect if (visibleRect.isEmpty) return if (visibleRect.contains(cellRect)) return if (visibleRect.y + visibleRect.height < cellRect.y + cellRect.height) { table.scrollRectToVisible(Rectangle( cellRect.x,cellRect.y + cellRect.height, cellRect.width, 0)) } else { table.scrollRectToVisible(Rectangle( cellRect.x, cellRect.y, cellRect.width, 0)) } } } private fun getPreviousIndex(index0: Int): Int { var newIndex = index0 - 1 while (newIndex >= 0 && table.model.getValueAt<Any>(newIndex) is AttachSelectionIgnoredNode) { newIndex-- } return if (newIndex >= 0) newIndex else -1 } private fun getNextIndex(index0: Int): Int { var newIndex = index0 + 1 while (newIndex < table.rowCount && table.model.getValueAt<Any>(newIndex) is AttachSelectionIgnoredNode) { newIndex++ } return if (newIndex < table.rowCount) newIndex else -1 } } internal inline fun <reified TNodeType> TableModel.getValueAt(row: Int): TNodeType? { if (row < 0 || row >= rowCount) { return null } return when (val value = getValueAt(row, 0)) { is TNodeType -> value is AttachNodeContainer<*> -> value.getAttachNode() as? TNodeType else -> null } } internal fun JBTable.focusFirst() { val currentIndex = selectedRow if (currentIndex >= 0 && currentIndex < model.rowCount) { return } if (model.rowCount > 0) { selectionModel.setSelectionInterval(0, 0) } }
apache-2.0
bb859de68c307751fa0ac25215b5cf1d
28.982143
118
0.682752
4.270992
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/DslHighlightingMarker.kt
4
2787
// 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.highlighter.markers import com.intellij.application.options.colors.ColorAndFontOptions import com.intellij.codeInsight.daemon.GutterIconNavigationHandler import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.ide.DataManager import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.psi.PsiElement import com.intellij.util.Function import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.core.toDescriptor import org.jetbrains.kotlin.idea.highlighter.dsl.DslKotlinHighlightingVisitorExtension import org.jetbrains.kotlin.idea.highlighter.dsl.isDslHighlightingMarker import org.jetbrains.kotlin.psi.KtClass import javax.swing.JComponent private val navHandler = GutterIconNavigationHandler<PsiElement> { event, element -> val dataContext = (event.component as? JComponent)?.let { DataManager.getInstance().getDataContext(it) } ?: return@GutterIconNavigationHandler val ktClass = element?.parent as? KtClass ?: return@GutterIconNavigationHandler val styleId = ktClass.styleIdForMarkerAnnotation() ?: return@GutterIconNavigationHandler ColorAndFontOptions.selectOrEditColor(dataContext, DslKotlinHighlightingVisitorExtension.styleOptionDisplayName(styleId), KotlinLanguage.NAME) } private val toolTipHandler = Function<PsiElement, String> { KotlinBundle.message("highlighter.tool.tip.marker.annotation.for.dsl") } fun collectHighlightingColorsMarkers( ktClass: KtClass, result: LineMarkerInfos ) { if (!KotlinLineMarkerOptions.dslOption.isEnabled) return val styleId = ktClass.styleIdForMarkerAnnotation() ?: return val anchor = ktClass.nameIdentifier ?: return @Suppress("MoveLambdaOutsideParentheses") result.add( LineMarkerInfo( anchor, anchor.textRange, createDslStyleIcon(styleId), toolTipHandler, navHandler, GutterIconRenderer.Alignment.RIGHT, { KotlinBundle.message("highlighter.tool.tip.marker.annotation.for.dsl") } ) ) } private fun KtClass.styleIdForMarkerAnnotation(): Int? { val classDescriptor = toDescriptor() as? ClassDescriptor ?: return null if (classDescriptor.kind != ClassKind.ANNOTATION_CLASS) return null if (!classDescriptor.isDslHighlightingMarker()) return null return DslKotlinHighlightingVisitorExtension.styleIdByMarkerAnnotation(classDescriptor) }
apache-2.0
a162c6f3d1dce92038d451e5d0468dee
43.951613
158
0.788303
4.880911
false
false
false
false
GunoH/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/components/ToolbarPane.kt
2
2629
/* * 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.notebooks.visualization.r.inlays.components import org.jetbrains.plugins.notebooks.visualization.r.ui.UiCustomizer import java.awt.BorderLayout import javax.swing.JComponent import javax.swing.JPanel /** * ToolbarPane - a special component consisting of two parts which are * setDataComponent() - used for displaying some output and should fill the major part of ToolbarPane, is aligned to the left * setToolbarComponent() - typically occupies the small area to the right and contains the button that shows the output actions menu */ class ToolbarPane(val inlayOutput: InlayOutput) : JPanel(BorderLayout()) { private var mainPanel: JPanel? = null var dataComponent: JComponent? = null set(value) { field = value updateMainComponent() updateChildrenBounds() } var progressComponent: JComponent? = null set(value) { field = value updateMainComponent() updateChildrenBounds() UiCustomizer.instance.toolbarPaneProgressComponentChanged(this, value) } var toolbarComponent: JComponent? = null set(value) { field = value updateMainComponent() updateChildrenBounds() UiCustomizer.instance.toolbarPaneToolbarComponentChanged(this, value) } private fun updateMainComponent() { if (mainPanel == null) { mainPanel = JPanel(BorderLayout()).also { mainPanel -> UiCustomizer.instance.toolbarPaneMainPanelCreated(this, mainPanel) add(NotebookInlayMouseListener.wrapPanel(mainPanel, inlayOutput.editor), BorderLayout.CENTER) } } mainPanel?.let { main -> main.removeAll() progressComponent?.let { progress -> main.add(progress, BorderLayout.PAGE_START) } dataComponent?.let { central -> main.add(central, BorderLayout.CENTER) } toolbarComponent?.let { toolbar -> main.add(toolbar, BorderLayout.LINE_END) } } } private fun updateChildrenBounds() { mainPanel?.setBounds(0, 0, width, height) val progressBarWidth = if (progressComponent != null) PROGRESS_BAR_DEFAULT_WIDTH else 0 toolbarComponent?.setBounds(width - toolbarComponent!!.preferredSize.width, progressBarWidth, toolbarComponent!!.preferredSize.width, toolbarComponent!!.preferredSize.height) } override fun setBounds(x: Int, y: Int, width: Int, height: Int) { super.setBounds(x, y, width, height) updateChildrenBounds() } }
apache-2.0
12d552f0a1ccf7e3246735cea87565b9
33.605263
140
0.706733
4.580139
false
false
false
false
GunoH/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotatorPre40.kt
7
5432
// 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.plugins.groovy.annotator import com.intellij.codeInspection.ProblemHighlightType import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.HighlightSeverity import com.intellij.psi.PsiElement import org.jetbrains.annotations.Nls import org.jetbrains.plugins.groovy.GroovyBundle import org.jetbrains.plugins.groovy.codeInspection.bugs.GrRemoveModifierFix import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor import org.jetbrains.plugins.groovy.lang.psi.api.GrRangeExpression import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrYieldStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrCaseSection import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrSwitchExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrPermitsClause import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrRecordDefinition import org.jetbrains.plugins.groovy.lang.psi.util.forbidRecord class GroovyAnnotatorPre40(private val holder: AnnotationHolder) : GroovyElementVisitor() { companion object { fun AnnotationHolder.registerModifierProblem(modifier : PsiElement, inspectionMessage : @Nls String, fixMessage : @Nls String) { val builder = newAnnotation(HighlightSeverity.ERROR, inspectionMessage).range(modifier) registerLocalFix(builder, GrRemoveModifierFix(modifier.text, fixMessage), modifier, inspectionMessage, ProblemHighlightType.ERROR, modifier.textRange) builder.create() } } override fun visitModifierList(modifierList: GrModifierList) { val sealed = modifierList.getModifier(GrModifier.SEALED) if (sealed != null) { holder.registerModifierProblem(sealed, GroovyBundle.message("inspection.message.modifier.sealed.available.with.groovy.or.later"), GroovyBundle.message("illegal.sealed.modifier.fix")) } val nonSealed = modifierList.getModifier(GrModifier.NON_SEALED) if (nonSealed != null) { holder.registerModifierProblem(nonSealed, GroovyBundle.message("inspection.message.modifier.nonsealed.available.with.groovy.or.later"), GroovyBundle.message("illegal.nonsealed.modifier.fix")) } } override fun visitPermitsClause(permitsClause: GrPermitsClause) { permitsClause.keyword?.let {holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("inspection.message.permits.available.with.groovy.4.or.later")).range(it).create() } } override fun visitSwitchExpression(switchExpression: GrSwitchExpression) { switchExpression.firstChild?.let { holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("inspection.message.switch.expressions.are.available.with.groovy.4.or.later")).range(it).create() } super.visitSwitchExpression(switchExpression) } override fun visitCaseSection(caseSection: GrCaseSection) : Unit = with(caseSection) { arrow?.let { holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("inspection.message.arrows.in.case.expressions.are.available.with.groovy.4.or.later")).range(it).create() } expressions?.takeIf { it.size > 1 }?.let { holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("inspection.message.multiple.expressions.in.case.section.are.available.with.groovy.4.or.later")).range( it.first()?.parent ?: this).create() } super.visitCaseSection(caseSection) } override fun visitYieldStatement(yieldStatement: GrYieldStatement) { yieldStatement.yieldKeyword.let { holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("inspection.message.keyword.yield.available.with.groovy.4.or.later")).range(it).create() } super.visitYieldStatement(yieldStatement) } override fun visitRangeExpression(range: GrRangeExpression) { when (range.boundaryType) { GrRangeExpression.BoundaryType.LEFT_OPEN -> holder .newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("inspection.message.left.open.ranges.are.available.in.groovy.4.or.later")) .range(range) .create() GrRangeExpression.BoundaryType.BOTH_OPEN -> holder .newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("inspection.message.both.open.ranges.are.available.in.groovy.4.or.later")) .range(range) .create() else -> {} } } override fun visitLiteralExpression(literal: GrLiteral) { super.visitLiteralExpression(literal) if (literal.text.startsWith(".")) { holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("inspection.message.fraction.literals.without.leading.zero.are.available.in.groovy.or.later")) .range(literal) .create() } } override fun visitRecordDefinition(recordDefinition: GrRecordDefinition) { forbidRecord(holder, recordDefinition) super.visitRecordDefinition(recordDefinition) } }
apache-2.0
80d100c5bfc26e44f93d67a3852cde23
50.245283
197
0.76215
4.409091
false
false
false
false
siosio/intellij-community
platform/util-ex/src/com/intellij/openapi/progress/coroutines.kt
1
4425
// 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. @file:ApiStatus.Experimental package com.intellij.openapi.progress import com.intellij.openapi.util.Computable import com.intellij.util.ConcurrencyUtil import kotlinx.coroutines.* import org.jetbrains.annotations.ApiStatus import kotlin.coroutines.coroutineContext /** * Checks whether the coroutine is active, and throws [CancellationException] if the coroutine is canceled. * This function might suspend if the coroutine is paused, * or yield if the coroutine has a lower priority while higher priority task is running. * * @throws CancellationException if the coroutine is canceled; the exception is also thrown if coroutine is canceled while suspended * @see ensureActive * @see coroutineSuspender */ suspend fun checkCanceled() { val ctx = coroutineContext ctx.ensureActive() // standard check first ctx[CoroutineSuspenderElementKey]?.checkPaused() // will suspend if paused } /** * The method has same semantics as [runBlocking], * and additionally [action] is canceled when current progress indicator is canceled. * * This is a bridge for invoking suspending code from blocking code. * * Example: * ``` * ProgressManager.getInstance().runProcess({ * runSuspendingAction { * someSuspendingFunctionWhichDoesntKnowAboutIndicator() * } * }, progress); * ``` * @see runUnderIndicator * @see runBlocking */ fun <T> runSuspendingAction(action: suspend CoroutineScope.() -> T): T { val indicator = ProgressManager.getGlobalProgressIndicator() return runSuspendingAction(indicator, action) } fun <T> runSuspendingAction(indicator: ProgressIndicator?, action: suspend CoroutineScope.() -> T): T { if (indicator == null) { // we are not under indicator => just run the action, since nobody will cancel it anyway return runBlocking(block = action) } // we are under indicator => the Job must be canceled when indicator is canceled return runBlocking(progressSinkElement(ProgressIndicatorSink(indicator)) + CoroutineName("indicator run blocking")) { val indicatorWatchJob = launch(Dispatchers.Default + CoroutineName("indicator watcher")) { while (true) { if (indicator.isCanceled) { // will throw PCE which will cancel the runBlocking Job and thrown further in the caller of runSuspendingAction indicator.checkCanceled() } delay(ConcurrencyUtil.DEFAULT_TIMEOUT_MS) } } val result = action() indicatorWatchJob.cancel() result } } /** * Runs blocking (e.g. Java) code under indicator, which is canceled if current Job is canceled. * * This is a bridge for invoking blocking code from suspending code. * * Example: * ``` * launch { * runUnderIndicator { * someJavaFunctionWhichDoesntKnowAboutCoroutines() * } * } * ``` * @see runSuspendingAction * @see ProgressManager.runProcess */ fun <T> CoroutineScope.runUnderIndicator(action: () -> T): T { return runUnderIndicator(coroutineContext.job, coroutineContext.progressSink, action) } @Suppress("EXPERIMENTAL_API_USAGE_ERROR") internal fun <T> runUnderIndicator(job: Job, progressSink: ProgressSink?, action: () -> T): T { job.ensureActive() val indicator = if (progressSink == null) EmptyProgressIndicator() else ProgressSinkIndicator(progressSink) try { return ProgressManager.getInstance().runProcess(Computable { // Register handler inside runProcess to avoid cancelling the indicator before even starting the progress. // If the Job was canceled while runProcess was preparing, // then CompletionHandler is invoked right away and cancels the indicator. val completionHandle = job.invokeOnCompletion(onCancelling = true) { if (it is CancellationException) { indicator.cancel() } } try { indicator.checkCanceled() action() } finally { completionHandle.dispose() } }, indicator) } catch (e: ProcessCanceledException) { if (!indicator.isCanceled) { // means the exception was thrown manually // => treat it as any other exception throw e } // indicator is canceled // => CompletionHandler was actually invoked // => current Job is canceled check(job.isCancelled) throw job.getCancellationException() } }
apache-2.0
d8bda4572236a6a118dbd07f29f494b9
34.119048
140
0.71661
4.747854
false
false
false
false
Firenox89/Shinobooru
app/src/main/java/com/github/firenox89/shinobooru/cloud/NextCloudSyncer.kt
1
9771
package com.github.firenox89.shinobooru.cloud import android.content.Context import com.github.firenox89.shinobooru.repo.DataSource import com.github.firenox89.shinobooru.repo.model.CloudPost import com.github.firenox89.shinobooru.repo.model.DownloadedPost import com.github.firenox89.shinobooru.settings.SettingsManager import com.github.kittinunf.result.Result import com.github.kittinunf.result.flatMap import com.github.kittinunf.result.map import com.github.kittinunf.result.mapError import com.owncloud.android.lib.common.OwnCloudClient import com.owncloud.android.lib.common.OwnCloudClientFactory import com.owncloud.android.lib.common.OwnCloudCredentialsFactory import com.owncloud.android.lib.common.operations.RemoteOperationResult import com.owncloud.android.lib.resources.files.* import com.owncloud.android.lib.resources.files.model.RemoteFile import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.produce import org.koin.core.KoinComponent import org.koin.core.inject import timber.log.Timber import java.io.File import java.lang.Exception import java.lang.IllegalArgumentException import java.util.concurrent.Executors import kotlin.coroutines.coroutineContext const val SHINOBOORU_REMOTE_PATH = "/Shinobooru/" class NextCloudSyncer(private val appContext: Context, private val dataSource: DataSource) : CloudSync, KoinComponent { private val settingsManager: SettingsManager by inject() private val networkDispatcher = Executors.newFixedThreadPool(8).asCoroutineDispatcher() private val syncDir = dataSource.getSyncDir() private fun getClient(): Result<OwnCloudClient, Exception> = settingsManager.nextcloudBaseUri?.let { baseUri -> Result.of<OwnCloudClient, Exception> { OwnCloudClientFactory.createOwnCloudClient(baseUri, appContext, true).apply { credentials = OwnCloudCredentialsFactory.newBasicCredentials( settingsManager.nextcloudUser, settingsManager.nextcloudPassword ) } } } ?: Result.error(IllegalArgumentException("Nextcloud Uri not set.")) override suspend fun upload(posts: List<DownloadedPost>): Result<Channel<UploadProgress>, Exception> = getClient().map { client -> val progressChannel = Channel<UploadProgress>() CoroutineScope(coroutineContext).async { var currentProgress = UploadProgress(posts.size, 0, null) posts.map { post -> async(networkDispatcher) { Timber.d("Upload $post") UploadFileRemoteOperation( post.file.absolutePath, SHINOBOORU_REMOTE_PATH + post.file.name, post.getMIMEType(), (post.file.lastModified() / 1000).toString() ).execute(client).let { result -> if (!result.isSuccess) { Timber.e("Uploaded failed $result") Result.error(result.exception) } else { Timber.d("Uploaded $result") Result.success(Unit) } } } }.forEach { it.await().fold({ currentProgress = currentProgress.copy(postsUploaded = currentProgress.postsUploaded + 1) progressChannel.offer(currentProgress) }, { exception -> currentProgress = currentProgress.copy(postsUploaded = currentProgress.postsUploaded + 1, error = exception) progressChannel.offer(currentProgress) }) } progressChannel.close() } progressChannel } override suspend fun download(posts: List<CloudPost>): Result<ReceiveChannel<DownloadProgress>, Exception> = getClient().map { client -> CoroutineScope(coroutineContext).produce(networkDispatcher) { var currentProgress = DownloadProgress(posts.size, 0, null) posts.map { post -> async { DownloadFileRemoteOperation( post.remotePath, syncDir.absolutePath ).execute(client).let { result -> if (!result.isSuccess) { Timber.e("Download failed $result") Result.error(result.exception) } else { Timber.d("Download $result") val syncFile = File(syncDir.absolutePath + post.remotePath) val fileDst = dataSource.getFileDestinationFor(post.fileName) syncFile.renameTo(fileDst) Timber.d("Download $fileDst") DownloadedPost.postFromName(fileDst).mapError { Timber.e("Failed to parse file $fileDst, deleting it.") fileDst.delete() it } } } } }.forEach { Timber.e("Await $it") it.await().fold({ Timber.e("Downloaded $it") currentProgress = currentProgress.copy(postsDownloaded = currentProgress.postsDownloaded + 1) offer(currentProgress) }, { exception -> Timber.e("Downloaded $exception") currentProgress = currentProgress.copy(postsDownloaded = currentProgress.postsDownloaded + 1, error = exception) offer(currentProgress) }) } dataSource.refreshLocalPosts() close() } } override suspend fun remove(posts: List<DownloadedPost>): Result<Unit, Exception> = withContext(Dispatchers.IO) { Result.of<Unit, Exception> { getClient().flatMap { client -> posts.forEach { post -> Timber.d("Remove $post") RemoveFileRemoteOperation( SHINOBOORU_REMOTE_PATH + "/" + post.file.name ).execute(client).let { result -> if (!result.isSuccess) { Timber.e("Remove failed $result") return@flatMap Result.error(result.exception) } else { Timber.d("Removed $result") } } } Result.success(Unit) } } } override suspend fun fetchData(): Result<List<CloudPost>, Exception> = withContext(Dispatchers.IO) { getClient().flatMap { client -> val res = ReadFolderRemoteOperation(SHINOBOORU_REMOTE_PATH).execute(client) when { res.isSuccess -> { val remoteFiles = res.data as ArrayList<RemoteFile> val list = remoteFiles.filter { !it.remotePath.endsWith("/") }.mapNotNull { val createPostResult = CloudPost.fromRemotePath( it.remotePath, it.remotePath.removePrefix(SHINOBOORU_REMOTE_PATH) ) if (createPostResult is Result.Success) { createPostResult.get() } else { createPostResult as Result.Failure Timber.e(createPostResult.error, "Failed to load ${it.remotePath}") null } } Result.success(list) } res.code == RemoteOperationResult.ResultCode.FILE_NOT_FOUND -> { val createRes = CreateFolderRemoteOperation(SHINOBOORU_REMOTE_PATH, true) .execute(client) when { createRes.isSuccess -> { Result.success(emptyList()) } createRes.exception != null -> { Result.error(createRes.exception) } else -> { Result.error(IllegalArgumentException("Create root dir failed with unknown code $createRes")) } } } res.exception != null -> { Result.error(res.exception) } else -> { Result.error(IllegalArgumentException("Unhandled result code ${res.code}")) } } } } }
mit
2f1146ffcaf0aeaf4a1774929618a049
47.86
140
0.499539
6.227533
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/compiler-plugins/kotlinx-serialization/common/src/org/jetbrains/kotlin/idea/compilerPlugin/kotlinxSerialization/KotlinSerializationImportHandler.kt
1
1817
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.compilerPlugin.kotlinxSerialization import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments import org.jetbrains.kotlin.idea.artifacts.KotlinArtifactNames import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts import org.jetbrains.kotlin.idea.facet.KotlinFacet import java.io.File object KotlinSerializationImportHandler { val PLUGIN_JPS_JAR: String by lazy { KotlinArtifacts.instance.kotlinxSerializationCompilerPlugin.absolutePath } fun isPluginJarPath(path: String): Boolean { return path.endsWith(KotlinArtifactNames.KOTLINX_SERIALIZATION_COMPILER_PLUGIN) } fun modifyCompilerArguments(facet: KotlinFacet, buildSystemPluginJar: String) { val facetSettings = facet.configuration.settings val commonArguments = facetSettings.compilerArguments ?: CommonCompilerArguments.DummyImpl() var pluginWasEnabled = false val oldPluginClasspaths = (commonArguments.pluginClasspaths ?: emptyArray()).filterTo(mutableListOf()) { val lastIndexOfFile = it.lastIndexOfAny(charArrayOf('/', File.separatorChar)) if (lastIndexOfFile < 0) { return@filterTo true } val match = it.drop(lastIndexOfFile + 1).matches("$buildSystemPluginJar-.*\\.jar".toRegex()) if (match) pluginWasEnabled = true !match } val newPluginClasspaths = if (pluginWasEnabled) oldPluginClasspaths + PLUGIN_JPS_JAR else oldPluginClasspaths commonArguments.pluginClasspaths = newPluginClasspaths.toTypedArray() facetSettings.compilerArguments = commonArguments } }
apache-2.0
8a23da940015fee2ea49264db8ee0925
48.135135
158
0.745735
5.147309
false
false
false
false
smmribeiro/intellij-community
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ModifiableRootModelBridgeImpl.kt
1
28212
// 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.legacyBridge.module.roots import com.intellij.configurationStore.serializeStateInto import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.ModuleOrderEnumerator import com.intellij.openapi.roots.impl.RootConfigurationAccessor import com.intellij.openapi.roots.impl.RootModelBase.CollectDependentModules import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryTable import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ArrayUtilRt import com.intellij.util.SmartList import com.intellij.util.isEmpty import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.getInstance import com.intellij.workspaceModel.ide.impl.legacyBridge.LegacyBridgeModifiableBase import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridgeImpl import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryNameGenerator import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleEntity import com.intellij.workspaceModel.ide.legacyBridge.ModifiableRootModelBridge import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge import com.intellij.workspaceModel.ide.legacyBridge.ModuleExtensionBridge import com.intellij.workspaceModel.storage.CachedValue import com.intellij.workspaceModel.storage.WorkspaceEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jdom.Element import org.jetbrains.jps.model.module.JpsModuleSourceRoot import org.jetbrains.jps.model.module.JpsModuleSourceRootType import java.util.concurrent.ConcurrentHashMap internal class ModifiableRootModelBridgeImpl( diff: WorkspaceEntityStorageBuilder, override val moduleBridge: ModuleBridge, override val accessor: RootConfigurationAccessor, cacheStorageResult: Boolean = true ) : LegacyBridgeModifiableBase(diff, cacheStorageResult), ModifiableRootModelBridge, ModuleRootModelBridge { /* We save the module entity for the following case: - Modifiable model created - module disposed - modifiable model used This case can appear, for example, during maven import moduleEntity would be removed from this diff after module disposing */ private var savedModuleEntity: ModuleEntity init { savedModuleEntity = getModuleEntity(entityStorageOnDiff.current, module) ?: error("Cannot find module entity for ${module.moduleEntityId}. Bridge: '$moduleBridge'. Store: $diff") } private fun getModuleEntity(current: WorkspaceEntityStorage, myModuleBridge: ModuleBridge): ModuleEntity? { // Try to get entity by module id // In some cases this won't work. These cases can happen during maven or gradle import where we provide a general builder. // The case: we rename the module. Since the changes not yet committed, the module will remain with the old persistentId. After that // we try to get modifiableRootModel. In general case it would work fine because the builder will be based on main store, but // in case of gradle/maven import we take the builder that was used for renaming. So, the old name cannot be found in the new store. return current.resolve(myModuleBridge.moduleEntityId) ?: current.findModuleEntity(myModuleBridge) } override fun getModificationCount(): Long = diff.modificationCount private val extensionsDisposable = Disposer.newDisposable() private val virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManager.getInstance(project) private val extensionsDelegate = lazy { RootModelBridgeImpl.loadExtensions(storage = entityStorageOnDiff, module = module, diff = diff, writable = true, parentDisposable = extensionsDisposable) } private val extensions by extensionsDelegate private val sourceRootPropertiesMap = ConcurrentHashMap<VirtualFileUrl, JpsModuleSourceRoot>() internal val moduleEntity: ModuleEntity get() { val actualModuleEntity = getModuleEntity(entityStorageOnDiff.current, module) ?: return savedModuleEntity savedModuleEntity = actualModuleEntity return actualModuleEntity } private val moduleLibraryTable = ModifiableModuleLibraryTableBridge(this) /** * Contains instances of OrderEntries edited via [ModifiableRootModel] interfaces; we need to keep references to them to update their indices; * it should be used for modifications only, in order to read actual state one need to use [orderEntriesArray]. */ private val mutableOrderEntries: ArrayList<OrderEntryBridge> by lazy { ArrayList<OrderEntryBridge>().also { addOrderEntries(moduleEntity.dependencies, it) } } /** * Provides cached value for [mutableOrderEntries] converted to an array to avoid creating array each time [getOrderEntries] is called; * also it updates instances in [mutableOrderEntries] when underlying entities are changed via [WorkspaceModel] interface (e.g. when a * library referenced from [LibraryOrderEntry] is renamed). */ private val orderEntriesArrayValue: CachedValue<Array<OrderEntry>> = CachedValue { storage -> val dependencies = storage.findModuleEntity(module)?.dependencies ?: return@CachedValue emptyArray() if (mutableOrderEntries.size == dependencies.size) { //keep old instances of OrderEntries if possible (i.e. if only some properties of order entries were changes via WorkspaceModel) for (i in mutableOrderEntries.indices) { if (dependencies[i] != mutableOrderEntries[i].item && dependencies[i].javaClass == mutableOrderEntries[i].item.javaClass) { mutableOrderEntries[i].item = dependencies[i] } } } else { mutableOrderEntries.clear() addOrderEntries(dependencies, mutableOrderEntries) } mutableOrderEntries.toTypedArray() } private val orderEntriesArray get() = entityStorageOnDiff.cachedValue(orderEntriesArrayValue) private fun addOrderEntries(dependencies: List<ModuleDependencyItem>, target: MutableList<OrderEntryBridge>) = dependencies.mapIndexedTo(target) { index, item -> RootModelBridgeImpl.toOrderEntry(item, index, this, this::updateDependencyItem) } private val contentEntriesImplValue: CachedValue<List<ModifiableContentEntryBridge>> = CachedValue { storage -> val moduleEntity = storage.findModuleEntity(module) ?: return@CachedValue emptyList<ModifiableContentEntryBridge>() val contentEntries = moduleEntity.contentRoots.sortedBy { it.url.url }.toList() contentEntries.map { ModifiableContentEntryBridge( diff = diff, contentEntryUrl = it.url, modifiableRootModel = this ) } } private fun updateDependencyItem(index: Int, transformer: (ModuleDependencyItem) -> ModuleDependencyItem) { val oldItem = moduleEntity.dependencies[index] val newItem = transformer(oldItem) if (oldItem == newItem) return diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { val copy = dependencies.toMutableList() copy[index] = newItem dependencies = copy } } override val storage: WorkspaceEntityStorage get() = entityStorageOnDiff.current override fun getOrCreateJpsRootProperties(sourceRootUrl: VirtualFileUrl, creator: () -> JpsModuleSourceRoot): JpsModuleSourceRoot { return sourceRootPropertiesMap.computeIfAbsent(sourceRootUrl) { creator() } } override fun removeCachedJpsRootProperties(sourceRootUrl: VirtualFileUrl) { sourceRootPropertiesMap.remove(sourceRootUrl) } private val contentEntries get() = entityStorageOnDiff.cachedValue(contentEntriesImplValue) override fun getProject(): Project = moduleBridge.project override fun addContentEntry(root: VirtualFile): ContentEntry = addContentEntry(root.url) override fun addContentEntry(url: String): ContentEntry { assertModelIsLive() val virtualFileUrl = virtualFileManager.fromUrl(url) val existingEntry = contentEntries.firstOrNull { it.contentEntryUrl == virtualFileUrl } if (existingEntry != null) { return existingEntry } diff.addContentRootEntity( module = moduleEntity, excludedUrls = emptyList(), excludedPatterns = emptyList(), url = virtualFileUrl ) // TODO It's N^2 operations since we need to recreate contentEntries every time return contentEntries.firstOrNull { it.contentEntryUrl == virtualFileUrl } ?: error("addContentEntry: unable to find content entry after adding: $url to module ${moduleEntity.name}") } override fun removeContentEntry(entry: ContentEntry) { assertModelIsLive() val entryImpl = entry as ModifiableContentEntryBridge val contentEntryUrl = entryImpl.contentEntryUrl val entity = currentModel.contentEntities.firstOrNull { it.url == contentEntryUrl } ?: error("ContentEntry $entry does not belong to modifiableRootModel of module ${moduleBridge.name}") entry.clearSourceFolders() diff.removeEntity(entity) if (assertChangesApplied && contentEntries.any { it.url == contentEntryUrl.url }) { error("removeContentEntry: removed content entry url '$contentEntryUrl' still exists after removing") } } override fun addOrderEntry(orderEntry: OrderEntry) { assertModelIsLive() when (orderEntry) { is LibraryOrderEntryBridge -> { if (orderEntry.isModuleLevel) { moduleLibraryTable.addLibraryCopy(orderEntry.library as LibraryBridgeImpl, orderEntry.isExported, orderEntry.libraryDependencyItem.scope) } else { appendDependency(orderEntry.libraryDependencyItem) } } is ModuleOrderEntry -> orderEntry.module?.let { addModuleOrderEntry(it) } ?: error("Module is empty: $orderEntry") is ModuleSourceOrderEntry -> appendDependency(ModuleDependencyItem.ModuleSourceDependency) is InheritedJdkOrderEntry -> appendDependency(ModuleDependencyItem.InheritedSdkDependency) is ModuleJdkOrderEntry -> appendDependency((orderEntry as SdkOrderEntryBridge).sdkDependencyItem) else -> error("OrderEntry should not be extended by external systems") } } override fun addLibraryEntry(library: Library): LibraryOrderEntry { appendDependency(ModuleDependencyItem.Exportable.LibraryDependency( library = library.libraryId, exported = false, scope = ModuleDependencyItem.DependencyScope.COMPILE )) return (mutableOrderEntries.lastOrNull() as? LibraryOrderEntry ?: error("Unable to find library orderEntry after adding")) } private val Library.libraryId: LibraryId get() { val libraryId = if (this is LibraryBridge) libraryId else { val libraryName = name if (libraryName.isNullOrEmpty()) { error("Library name is null or empty: ${this}") } LibraryId(libraryName, LibraryNameGenerator.getLibraryTableId(table.tableLevel)) } return libraryId } override fun addLibraryEntries(libraries: List<Library>, scope: DependencyScope, exported: Boolean) { val dependencyScope = scope.toEntityDependencyScope() appendDependencies(libraries.map { ModuleDependencyItem.Exportable.LibraryDependency(it.libraryId, exported, dependencyScope) }) } override fun addInvalidLibrary(name: String, level: String): LibraryOrderEntry { val libraryDependency = ModuleDependencyItem.Exportable.LibraryDependency( library = LibraryId(name, LibraryNameGenerator.getLibraryTableId(level)), exported = false, scope = ModuleDependencyItem.DependencyScope.COMPILE ) appendDependency(libraryDependency) return (mutableOrderEntries.lastOrNull() as? LibraryOrderEntry ?: error("Unable to find library orderEntry after adding")) } override fun addModuleOrderEntry(module: Module): ModuleOrderEntry { val moduleDependency = ModuleDependencyItem.Exportable.ModuleDependency( module = (module as ModuleBridge).moduleEntityId, productionOnTest = false, exported = false, scope = ModuleDependencyItem.DependencyScope.COMPILE ) appendDependency(moduleDependency) return mutableOrderEntries.lastOrNull() as? ModuleOrderEntry ?: error("Unable to find module orderEntry after adding") } override fun addModuleEntries(modules: MutableList<Module>, scope: DependencyScope, exported: Boolean) { val dependencyScope = scope.toEntityDependencyScope() appendDependencies(modules.map { ModuleDependencyItem.Exportable.ModuleDependency((it as ModuleBridge).moduleEntityId, exported, dependencyScope, productionOnTest = false) }) } override fun addInvalidModuleEntry(name: String): ModuleOrderEntry { val moduleDependency = ModuleDependencyItem.Exportable.ModuleDependency( module = ModuleId(name), productionOnTest = false, exported = false, scope = ModuleDependencyItem.DependencyScope.COMPILE ) appendDependency(moduleDependency) return mutableOrderEntries.lastOrNull() as? ModuleOrderEntry ?: error("Unable to find module orderEntry after adding") } internal fun appendDependency(dependency: ModuleDependencyItem) { mutableOrderEntries.add(RootModelBridgeImpl.toOrderEntry(dependency, mutableOrderEntries.size, this, this::updateDependencyItem)) entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { dependencies = dependencies + dependency } } internal fun appendDependencies(dependencies: List<ModuleDependencyItem>) { for (dependency in dependencies) { mutableOrderEntries.add(RootModelBridgeImpl.toOrderEntry(dependency, mutableOrderEntries.size, this, this::updateDependencyItem)) } entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { this.dependencies = this.dependencies + dependencies } } internal fun insertDependency(dependency: ModuleDependencyItem, position: Int): OrderEntryBridge { val last = position == mutableOrderEntries.size val newEntry = RootModelBridgeImpl.toOrderEntry(dependency, position, this, this::updateDependencyItem) if (last) { mutableOrderEntries.add(newEntry) } else { mutableOrderEntries.add(position, newEntry) for (i in position + 1 until mutableOrderEntries.size) { mutableOrderEntries[i].updateIndex(i) } } entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { dependencies = if (last) dependencies + dependency else dependencies.subList(0, position) + dependency + dependencies.subList(position, dependencies.size) } return newEntry } internal fun removeDependencies(filter: (Int, ModuleDependencyItem) -> Boolean) { val newDependencies = ArrayList<ModuleDependencyItem>() val newOrderEntries = ArrayList<OrderEntryBridge>() val oldDependencies = moduleEntity.dependencies for (i in oldDependencies.indices) { if (!filter(i, oldDependencies[i])) { newDependencies.add(oldDependencies[i]) val entryBridge = mutableOrderEntries[i] entryBridge.updateIndex(newOrderEntries.size) newOrderEntries.add(entryBridge) } } mutableOrderEntries.clear() mutableOrderEntries.addAll(newOrderEntries) entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { dependencies = newDependencies } } override fun findModuleOrderEntry(module: Module): ModuleOrderEntry? { return orderEntries.filterIsInstance<ModuleOrderEntry>().firstOrNull { module == it.module } } override fun findLibraryOrderEntry(library: Library): LibraryOrderEntry? { if (library is LibraryBridge) { val libraryIdToFind = library.libraryId return orderEntries .filterIsInstance<LibraryOrderEntry>() .firstOrNull { libraryIdToFind == (it.library as? LibraryBridge)?.libraryId } } else { return orderEntries.filterIsInstance<LibraryOrderEntry>().firstOrNull { it.library == library } } } override fun removeOrderEntry(orderEntry: OrderEntry) { assertModelIsLive() val entryImpl = orderEntry as OrderEntryBridge val item = entryImpl.item if (mutableOrderEntries.none { it.item == item }) { LOG.error("OrderEntry $item does not belong to modifiableRootModel of module ${moduleBridge.name}") return } if (orderEntry is LibraryOrderEntryBridge && orderEntry.isModuleLevel) { moduleLibraryTable.removeLibrary(orderEntry.library as LibraryBridge) } else { val itemIndex = entryImpl.currentIndex removeDependencies { index, _ -> index == itemIndex } } } override fun rearrangeOrderEntries(newOrder: Array<out OrderEntry>) { val newOrderEntries = newOrder.mapTo(ArrayList()) { it as OrderEntryBridge } val newEntities = newOrderEntries.map { it.item } if (newEntities.toSet() != moduleEntity.dependencies.toSet()) { error("Expected the same entities as existing order entries, but in a different order") } mutableOrderEntries.clear() mutableOrderEntries.addAll(newOrderEntries) for (i in mutableOrderEntries.indices) { mutableOrderEntries[i].updateIndex(i) } entityStorageOnDiff.clearCachedValue(orderEntriesArrayValue) diff.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { dependencies = newEntities } } override fun clear() { for (library in moduleLibraryTable.libraries) { moduleLibraryTable.removeLibrary(library) } val currentSdk = sdk val jdkItem = currentSdk?.let { ModuleDependencyItem.SdkDependency(it.name, it.sdkType.name) } if (moduleEntity.dependencies != listOfNotNull(jdkItem, ModuleDependencyItem.ModuleSourceDependency)) { removeDependencies { _, _ -> true } if (jdkItem != null) { appendDependency(jdkItem) } appendDependency(ModuleDependencyItem.ModuleSourceDependency) } for (contentRoot in moduleEntity.contentRoots) { diff.removeEntity(contentRoot) } } fun collectChangesAndDispose(): WorkspaceEntityStorageBuilder? { assertModelIsLive() Disposer.dispose(moduleLibraryTable) if (!isChanged) { moduleLibraryTable.restoreLibraryMappingsAndDisposeCopies() disposeWithoutLibraries() return null } if (extensionsDelegate.isInitialized() && extensions.any { it.isChanged }) { val element = Element("component") for (extension in extensions) { if (extension is ModuleExtensionBridge) continue extension.commit() if (extension is PersistentStateComponent<*>) { serializeStateInto(extension, element) } else { @Suppress("DEPRECATION") extension.writeExternal(element) } } val elementAsString = JDOMUtil.writeElement(element) val customImlDataEntity = moduleEntity.customImlData if (customImlDataEntity?.rootManagerTagCustomData != elementAsString) { when { customImlDataEntity == null && !element.isEmpty() -> diff.addModuleCustomImlDataEntity( module = moduleEntity, rootManagerTagCustomData = elementAsString, customModuleOptions = emptyMap(), source = moduleEntity.entitySource ) customImlDataEntity == null && element.isEmpty() -> Unit customImlDataEntity != null && customImlDataEntity.customModuleOptions.isEmpty() && element.isEmpty() -> diff.removeEntity(customImlDataEntity) customImlDataEntity != null && customImlDataEntity.customModuleOptions.isNotEmpty() && element.isEmpty() -> diff.modifyEntity(ModifiableModuleCustomImlDataEntity::class.java, customImlDataEntity) { rootManagerTagCustomData = null } customImlDataEntity != null && !element.isEmpty() -> diff.modifyEntity(ModifiableModuleCustomImlDataEntity::class.java, customImlDataEntity) { rootManagerTagCustomData = elementAsString } else -> error("Should not be reached") } } } if (!sourceRootPropertiesMap.isEmpty()) { for (sourceRoot in moduleEntity.sourceRoots) { val actualSourceRootData = sourceRootPropertiesMap[sourceRoot.url] ?: continue SourceRootPropertiesHelper.applyChanges(diff, sourceRoot, actualSourceRootData) } } disposeWithoutLibraries() return diff } private fun areSourceRootPropertiesChanged(): Boolean { if (sourceRootPropertiesMap.isEmpty()) return false return moduleEntity.sourceRoots.any { sourceRoot -> val actualSourceRootData = sourceRootPropertiesMap[sourceRoot.url] actualSourceRootData != null && !SourceRootPropertiesHelper.hasEqualProperties(sourceRoot, actualSourceRootData) } } override fun commit() { val diff = collectChangesAndDispose() ?: return val moduleDiff = module.diff if (moduleDiff != null) { moduleDiff.addDiff(diff) } else { WorkspaceModel.getInstance(project).updateProjectModel { it.addDiff(diff) } } postCommit() } override fun prepareForCommit() { collectChangesAndDispose() } override fun postCommit() { moduleLibraryTable.disposeOriginalLibrariesAndUpdateCopies() } override fun dispose() { disposeWithoutLibraries() moduleLibraryTable.restoreLibraryMappingsAndDisposeCopies() Disposer.dispose(moduleLibraryTable) } private fun disposeWithoutLibraries() { if (!modelIsCommittedOrDisposed) { Disposer.dispose(extensionsDisposable) } // No assertions here since it is ok to call dispose twice or more modelIsCommittedOrDisposed = true } override fun getModuleLibraryTable(): LibraryTable = moduleLibraryTable override fun setSdk(jdk: Sdk?) { if (jdk == null) { setSdkItem(null) if (assertChangesApplied && sdkName != null) { error("setSdk: expected sdkName is null, but got: $sdkName") } } else { if (ModifiableRootModelBridge.findSdk(jdk.name, jdk.sdkType.name) == null) { error("setSdk: sdk '${jdk.name}' type '${jdk.sdkType.name}' is not registered in ProjectJdkTable") } setInvalidSdk(jdk.name, jdk.sdkType.name) } } override fun setInvalidSdk(sdkName: String, sdkType: String) { setSdkItem(ModuleDependencyItem.SdkDependency(sdkName, sdkType)) if (assertChangesApplied && getSdkName() != sdkName) { error("setInvalidSdk: expected sdkName '$sdkName' but got '${getSdkName()}' after doing a change") } } override fun inheritSdk() { if (isSdkInherited) return setSdkItem(ModuleDependencyItem.InheritedSdkDependency) if (assertChangesApplied && !isSdkInherited) { error("inheritSdk: Sdk is still not inherited after inheritSdk()") } } // TODO compare by actual values override fun isChanged(): Boolean { if (!diff.isEmpty()) return true if (extensionsDelegate.isInitialized() && extensions.any { it.isChanged }) return true if (areSourceRootPropertiesChanged()) return true return false } override fun isWritable(): Boolean = true override fun <T : OrderEntry?> replaceEntryOfType(entryClass: Class<T>, entry: T) = throw NotImplementedError("Not implemented since it was used only by project model implementation") override fun getSdkName(): String? = orderEntries.filterIsInstance<JdkOrderEntry>().firstOrNull()?.jdkName // TODO override fun isDisposed(): Boolean = modelIsCommittedOrDisposed private fun setSdkItem(item: ModuleDependencyItem?) { removeDependencies { _, it -> it is ModuleDependencyItem.InheritedSdkDependency || it is ModuleDependencyItem.SdkDependency } if (item != null) { insertDependency(item, 0) } } private val modelValue = CachedValue { storage -> RootModelBridgeImpl( moduleEntity = getModuleEntity(storage, moduleBridge), storage = entityStorageOnDiff, itemUpdater = null, rootModel = this, updater = { transformer -> transformer(diff) } ) } internal val currentModel get() = entityStorageOnDiff.cachedValue(modelValue) override fun getExcludeRoots(): Array<VirtualFile> = currentModel.excludeRoots override fun orderEntries(): OrderEnumerator = ModuleOrderEnumerator(this, null) override fun <T : Any?> getModuleExtension(klass: Class<T>): T? { return extensions.filterIsInstance(klass).firstOrNull() } override fun getDependencyModuleNames(): Array<String> { val result = orderEntries().withoutSdk().withoutLibraries().withoutModuleSourceEntries().process(CollectDependentModules(), ArrayList()) return ArrayUtilRt.toStringArray(result) } override fun getModule(): ModuleBridge = moduleBridge override fun isSdkInherited(): Boolean = orderEntriesArray.any { it is InheritedJdkOrderEntry } override fun getOrderEntries(): Array<OrderEntry> = orderEntriesArray override fun getSourceRootUrls(): Array<String> = currentModel.sourceRootUrls override fun getSourceRootUrls(includingTests: Boolean): Array<String> = currentModel.getSourceRootUrls(includingTests) override fun getContentEntries(): Array<ContentEntry> = contentEntries.toTypedArray() override fun getExcludeRootUrls(): Array<String> = currentModel.excludeRootUrls override fun <R : Any?> processOrder(policy: RootPolicy<R>, initialValue: R): R { var result = initialValue for (orderEntry in orderEntries) { result = orderEntry.accept(policy, result) } return result } override fun getSdk(): Sdk? = (orderEntriesArray.find { it is JdkOrderEntry } as JdkOrderEntry?)?.jdk override fun getSourceRoots(): Array<VirtualFile> = currentModel.sourceRoots override fun getSourceRoots(includingTests: Boolean): Array<VirtualFile> = currentModel.getSourceRoots(includingTests) override fun getSourceRoots(rootType: JpsModuleSourceRootType<*>): MutableList<VirtualFile> = currentModel.getSourceRoots(rootType) override fun getSourceRoots(rootTypes: MutableSet<out JpsModuleSourceRootType<*>>): MutableList<VirtualFile> = currentModel.getSourceRoots(rootTypes) override fun getContentRoots(): Array<VirtualFile> = currentModel.contentRoots override fun getContentRootUrls(): Array<String> = currentModel.contentRootUrls override fun getModuleDependencies(): Array<Module> = getModuleDependencies(true) override fun getModuleDependencies(includeTests: Boolean): Array<Module> { var result: MutableList<Module>? = null for (entry in orderEntriesArray) { if (entry is ModuleOrderEntry) { val scope = entry.scope if (includeTests || scope.isForProductionCompile || scope.isForProductionRuntime) { val module = entry.module if (module != null) { if (result == null) { result = SmartList() } result.add(module) } } } } return if (result.isNullOrEmpty()) Module.EMPTY_ARRAY else result.toTypedArray() } companion object { private val LOG = logger<ModifiableRootModelBridgeImpl>() } }
apache-2.0
612a4af2e616962209a55b98bb77bf7d
39.302857
151
0.739721
5.568891
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToBlockBodyIntention.kt
2
5292
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.setType import org.jetbrains.kotlin.idea.formatter.adjustLineIndent import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.isNullabilityFlexible import org.jetbrains.kotlin.types.typeUtil.isNothing import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.types.typeUtil.makeNotNullable class ConvertToBlockBodyIntention : SelfTargetingIntention<KtDeclarationWithBody>( KtDeclarationWithBody::class.java, KotlinBundle.lazyMessage("convert.to.block.body") ) { override fun isApplicableTo(element: KtDeclarationWithBody, caretOffset: Int): Boolean { if (element is KtFunctionLiteral || element.hasBlockBody() || !element.hasBody()) return false when (element) { is KtNamedFunction -> { val returnType = element.returnType() ?: return false if (!element.hasDeclaredReturnType() && returnType.isError) return false// do not convert when type is implicit and unknown return true } is KtPropertyAccessor -> return true else -> error("Unknown declaration type: $element") } } override fun allowCaretInsideElement(element: PsiElement) = element !is KtDeclaration && super.allowCaretInsideElement(element) override fun applyTo(element: KtDeclarationWithBody, editor: Editor?) { convert(element, true) } companion object { fun convert(declaration: KtDeclarationWithBody, withReformat: Boolean = false): KtDeclarationWithBody { val body = declaration.bodyExpression!! fun generateBody(returnsValue: Boolean): KtExpression { val bodyType = body.analyze().getType(body) val factory = KtPsiFactory(declaration) if (bodyType != null && bodyType.isUnit() && body is KtNameReferenceExpression) return factory.createEmptyBody() val unitWhenAsResult = (bodyType == null || bodyType.isUnit()) && body.resultingWhens().isNotEmpty() val needReturn = returnsValue && (bodyType == null || (!bodyType.isUnit() && !bodyType.isNothing())) return if (needReturn || unitWhenAsResult) { val annotatedExpr = body as? KtAnnotatedExpression val returnedExpr = annotatedExpr?.baseExpression ?: body val block = factory.createSingleStatementBlock(factory.createExpressionByPattern("return $0", returnedExpr)) val statement = block.firstStatement annotatedExpr?.annotationEntries?.forEach { block.addBefore(it, statement) block.addBefore(factory.createNewLine(), statement) } block } else { factory.createSingleStatementBlock(body) } } val newBody = when (declaration) { is KtNamedFunction -> { val returnType = declaration.returnType()!! if (!declaration.hasDeclaredReturnType() && !returnType.isUnit()) { declaration.setType(returnType) } generateBody(!returnType.isUnit() && !returnType.isNothing()) } is KtPropertyAccessor -> { val parent = declaration.parent if (parent is KtProperty && parent.typeReference == null) { val descriptor = parent.resolveToDescriptorIfAny() (descriptor as? CallableDescriptor)?.returnType?.let { parent.setType(it) } } generateBody(declaration.isGetter) } else -> throw RuntimeException("Unknown declaration type: $declaration") } declaration.equalsToken!!.delete() val replaced = body.replace(newBody) if (withReformat) declaration.containingKtFile.adjustLineIndent(replaced.startOffset, replaced.endOffset) return declaration } private fun KtNamedFunction.returnType(): KotlinType? { val descriptor = resolveToDescriptorIfAny() val returnType = descriptor?.returnType ?: return null if (returnType.isNullabilityFlexible() && descriptor.overriddenDescriptors.firstOrNull()?.returnType?.isMarkedNullable == false ) return returnType.makeNotNullable() return returnType } } }
apache-2.0
a541541cd0e9bf4fb352f0e971b8fcc8
46.675676
158
0.647014
5.727273
false
false
false
false
smmribeiro/intellij-community
plugins/filePrediction/test/com/intellij/filePrediction/features/history/ngram/FilePredictionRunnerAssertion.kt
12
2438
// 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.filePrediction.features.history.ngram import com.intellij.internal.ml.ngram.NGramIncrementalModelRunner import com.intellij.internal.ml.ngram.VocabularyWithLimit import junit.framework.TestCase internal class FilePredictionRunnerAssertion { private var withVocabulary: Boolean = false private var vocabularySize: Int = 3 private var withFileSequence: Boolean = false private var fileSequence: List<Int> = emptyList() private var withRecentFiles: Boolean = false private var nextFileSequenceIdx: Int = -1 private var recentFiles: List<String> = emptyList() private var recentFilesIdx: List<Int> = emptyList() fun withVocabulary(size: Int): FilePredictionRunnerAssertion { withVocabulary = true vocabularySize = size return this } fun withFileSequence(files: List<Int>): FilePredictionRunnerAssertion { withFileSequence = true fileSequence = files return this } fun withRecentFiles(nextIdx: Int, recent: List<String>, idx: List<Int>): FilePredictionRunnerAssertion { withRecentFiles = true nextFileSequenceIdx = nextIdx recentFiles = recent recentFilesIdx = idx return this } fun assert(runner: NGramIncrementalModelRunner) { TestCase.assertTrue(runner.vocabulary is VocabularyWithLimit) val vocabulary = runner.vocabulary as VocabularyWithLimit if (withVocabulary) { // unknown token is always added to wordIndices, therefore, actual size will be always size + 1 TestCase.assertEquals(vocabularySize, vocabulary.wordIndices.size - 1) } if (withFileSequence) { val actualFileSequence = vocabulary.recentSequence.subListFromStart(vocabulary.recentSequence.size()) TestCase.assertEquals("File sequence is different from expected", fileSequence, actualFileSequence) } if (withRecentFiles) { val recent = vocabulary.recent TestCase.assertEquals("Next file sequence index is different from expected", nextFileSequenceIdx, recent.lastIndex() + 1) val tokens = recent.getRecentTokens() TestCase.assertEquals("Recent files are different from expected", recentFiles, tokens.map { it.first }) TestCase.assertEquals("Recent files indices are different from expected", recentFilesIdx, tokens.map { it.second }) } } }
apache-2.0
d0e740139d869dc2b9b6f342a911966b
37.714286
140
0.755947
4.688462
false
true
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/intentions/ConvertLambdaToClosureAction.kt
9
2202
// 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.groovy.annotator.intentions import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.SmartPsiElementPointer import com.intellij.psi.util.createSmartPointer import org.jetbrains.plugins.groovy.GroovyBundle.message import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory import org.jetbrains.plugins.groovy.lang.psi.api.GrBlockLambdaBody import org.jetbrains.plugins.groovy.lang.psi.api.GrLambdaExpression class ConvertLambdaToClosureAction(lambda: GrLambdaExpression) : IntentionAction { private val myLambda: SmartPsiElementPointer<GrLambdaExpression> = lambda.createSmartPointer() override fun getText(): String = familyName override fun getFamilyName(): String = message("action.convert.lambda.to.closure") override fun startInWriteAction(): Boolean = true override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean = myLambda.element != null override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { val lambda = myLambda.element ?: return val closureText = closureText(lambda) ?: return val closure = GroovyPsiElementFactory.getInstance(project).createClosureFromText(closureText) lambda.replaceWithExpression(closure, false) } private fun closureText(lambda: GrLambdaExpression): String? { val parameterList = lambda.parameterList val body = lambda.body ?: return null val closureText = StringBuilder() closureText.append("{") if (parameterList.parametersCount != 0) { appendTextBetween(closureText, parameterList.text, parameterList.lParen, parameterList.rParen) } appendElements(closureText, parameterList, body) if (body is GrBlockLambdaBody) { appendTextBetween(closureText, body.text, body.lBrace, body.rBrace) } else { closureText.append(body.text) } closureText.append("}") return closureText.toString() } }
apache-2.0
67417be58533938ab7b81efef9a25f53
40.54717
140
0.776567
4.695096
false
false
false
false
NlRVANA/Unity
app/src/main/java/com/zwq65/unity/data/db/AppDbHelper.kt
1
2024
/* * Copyright [2017] [NIRVANA PRIVATE LIMITED] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zwq65.unity.data.db import com.zwq65.unity.data.db.model.DaoMaster import com.zwq65.unity.data.db.model.DaoSession import com.zwq65.unity.data.db.model.Picture import io.reactivex.Observable import javax.inject.Inject import javax.inject.Singleton /** * ================================================ * Database操作帮助类 * <p> * Created by NIRVANA on 2017/01/27. * Contact with <[email protected]> * ================================================ */ @Singleton class AppDbHelper @Inject internal constructor(dbOpenHelper: DbOpenHelper) : DbHelper { private val mDaoSession: DaoSession = DaoMaster(dbOpenHelper.writableDb).newSession() override val collectionPictures: Observable<List<Picture>> get() = Observable.fromCallable { mDaoSession.pictureDao.loadAll() } override fun savePicture(picture: Picture): Observable<Long> { return Observable.fromCallable { mDaoSession.pictureDao.insertOrReplace(picture) } } override fun deletePicture(id: String): Observable<Long> { return Observable.fromCallable { mDaoSession.pictureDao.deleteByKey(id) 1L } } override fun isPictureExist(id: String): Observable<Boolean> { return Observable.fromCallable { val picture = mDaoSession.pictureDao.load(id) picture != null } } }
apache-2.0
55445621fb23e6b500e37ef2de59d091
32.566667
90
0.671797
4.285106
false
false
false
false
sksamuel/ktest
kotest-assertions/kotest-assertions-core/src/jvmTest/kotlin/com/sksamuel/kotest/matchers/string/EndWithTest.kt
1
2357
package com.sksamuel.kotest.matchers.string import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.FreeSpec import io.kotest.matchers.should import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNot import io.kotest.matchers.string.endWith import io.kotest.matchers.string.shouldEndWith import io.kotest.matchers.string.shouldNotEndWith @Suppress("RedundantNullableReturnType") class EndWithTest : FreeSpec() { init { "should endWith" - { "should test strings" { "hello" should endWith("o") "hello" should endWith("o" as CharSequence) "hello" should endWith("") "hello" should endWith("" as CharSequence) "hello" shouldEndWith "" "hello" shouldEndWith "lo" "hello" shouldEndWith "o" "hello" shouldNotEndWith "w" "" should endWith("") shouldThrow<AssertionError> { "" should endWith("h") } shouldThrow<AssertionError> { "hello" should endWith("goodbye") } } "work with char seqs" { val cs: CharSequence = "hello" cs should endWith("o") cs.shouldEndWith("o") val csnullable: CharSequence? = "hello" csnullable should endWith("o") csnullable.shouldEndWith("o") } "return the correct type" { val cs1: CharSequence = "hello" val a1 = cs1.shouldEndWith("o") a1 shouldBe "hello" val cs2: CharSequence? = "hello" val a2 = cs2.shouldEndWith("o") a2 shouldBe "hello" } "should fail if value is null" { shouldThrow<AssertionError> { null shouldNot endWith("") }.message shouldBe "Expecting actual not to be null" shouldThrow<AssertionError> { null shouldNotEndWith "" }.message shouldBe "Expecting actual not to be null" shouldThrow<AssertionError> { null should endWith("o") }.message shouldBe "Expecting actual not to be null" shouldThrow<AssertionError> { null shouldEndWith "o" }.message shouldBe "Expecting actual not to be null" } } } }
mit
cf4f4532cb6ee2a23c2ad1385602fecc
32.671429
64
0.574459
4.869835
false
true
false
false
MyCollab/mycollab
mycollab-services/src/main/java/com/mycollab/module/project/service/impl/MilestoneServiceImpl.kt
3
4219
/** * Copyright © MyCollab * * This program 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. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.project.service.impl import com.google.common.eventbus.AsyncEventBus import com.mycollab.aspect.ClassInfo import com.mycollab.aspect.ClassInfoMap import com.mycollab.aspect.Traceable import com.mycollab.cache.CleanCacheEvent import com.mycollab.common.ModuleNameConstants import com.mycollab.core.cache.CacheKey import com.mycollab.core.cache.CleanCache import com.mycollab.db.persistence.ICrudGenericDAO import com.mycollab.db.persistence.ISearchableDAO import com.mycollab.db.persistence.service.DefaultService import com.mycollab.module.project.ProjectTypeConstants import com.mycollab.module.project.dao.MilestoneMapper import com.mycollab.module.project.dao.MilestoneMapperExt import com.mycollab.module.project.domain.Milestone import com.mycollab.module.project.domain.SimpleMilestone import com.mycollab.module.project.domain.criteria.MilestoneSearchCriteria import com.mycollab.module.project.i18n.OptionI18nEnum.MilestoneStatus import com.mycollab.module.project.service.* import org.springframework.jdbc.core.BatchPreparedStatementSetter import org.springframework.jdbc.core.JdbcTemplate import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.sql.PreparedStatement import java.sql.SQLException import javax.sql.DataSource /** * @author MyCollab Ltd. * @since 1.0 */ @Service @Transactional @Traceable(nameField = "name", extraFieldName = "projectid") class MilestoneServiceImpl(private val milestoneMapper: MilestoneMapper, private val milestoneMapperExt: MilestoneMapperExt, private val dataSource: DataSource, private val asyncEventBus: AsyncEventBus) : DefaultService<Int, Milestone, MilestoneSearchCriteria>(), MilestoneService { override val crudMapper: ICrudGenericDAO<Int, Milestone> get() = milestoneMapper as ICrudGenericDAO<Int, Milestone> override val searchMapper: ISearchableDAO<MilestoneSearchCriteria> get() = milestoneMapperExt override fun findById(milestoneId: Int, sAccountId: Int): SimpleMilestone? = milestoneMapperExt.findById(milestoneId) override fun saveWithSession(record: Milestone, username: String?): Int { if (record.status == null) { record.status = MilestoneStatus.InProgress.name } return super.saveWithSession(record, username) } @CleanCache fun postDirtyUpdate(sAccountId: Int?) { asyncEventBus.post(CleanCacheEvent(sAccountId, arrayOf(ProjectService::class.java, ProjectTicketService::class.java, ProjectActivityStreamService::class.java))) } override fun massUpdateOptionIndexes(mapIndexes: List<Map<String, Int>>, @CacheKey sAccountId: Int) { val jdbcTemplate = JdbcTemplate(dataSource) jdbcTemplate.batchUpdate("UPDATE `m_prj_milestone` SET `orderIndex`=? WHERE `id`=?", object : BatchPreparedStatementSetter { @Throws(SQLException::class) override fun setValues(preparedStatement: PreparedStatement, i: Int) { preparedStatement.setInt(1, mapIndexes[i]["index"]!!) preparedStatement.setInt(2, mapIndexes[i]["id"]!!) } override fun getBatchSize(): Int = mapIndexes.size }) } companion object { init { ClassInfoMap.put(MilestoneServiceImpl::class.java, ClassInfo(ModuleNameConstants.PRJ, ProjectTypeConstants.MILESTONE)) } } }
agpl-3.0
8ebe2f5aa3df8e059d73c348d61de41f
42.484536
168
0.749881
4.589771
false
false
false
false
intrigus/jtransc
jtransc-main/src/com/jtransc/report.kt
1
4849
package com.jtransc import com.jtransc.annotation.haxe.HaxeMethodBody import com.jtransc.ast.* import com.jtransc.backend.toAst import com.jtransc.ds.diff import com.jtransc.ds.hasAnyFlags import com.jtransc.ds.hasFlag import com.jtransc.maven.MavenLocalRepository import com.jtransc.org.objectweb.asm.ClassReader import com.jtransc.org.objectweb.asm.Opcodes import com.jtransc.org.objectweb.asm.tree.AnnotationNode import com.jtransc.org.objectweb.asm.tree.ClassNode import com.jtransc.org.objectweb.asm.tree.FieldNode import com.jtransc.org.objectweb.asm.tree.MethodNode import com.jtransc.vfs.* import java.util.function.BiConsumer class JTranscRtReport { val types = AstTypes() companion object { @JvmStatic fun main(args: Array<String>) { JTranscRtReport().report() } } val jtranscVersion = JTranscVersion.getVersion() val javaRt = MergeVfs(listOf( ZipVfs(GetClassJar(String::class.java)), ZipVfs(GetClassJar(BiConsumer::class.java)) )) val jtranscRt = MergedLocalAndJars(MavenLocalRepository.locateJars("com.jtransc:jtransc-rt:$jtranscVersion")) fun report() { reportPackage("java", listOf("java.rmi", "java.sql", "java.beans", "java.awt", "java.applet", "java/applet", "sun", "javax", "com/sun", "com.sun", "jdk")) reportNotImplementedNatives("java") } fun reportPackage(packageName: String, ignoreSet: List<String>) { val ignoreSetNormalized = ignoreSet.map { it.replace('.', '/') } val packagePath = packageName.replace('.', '/') fileList@ for (e in javaRt[packagePath].listdirRecursive().filter { it.name.endsWith(".class") }) { //for (e.file) for (base in ignoreSetNormalized) { if (e.file.path.startsWith(base)) { continue@fileList } } compareFiles(e.file, jtranscRt[e.path]) } } fun reportNotImplementedNatives(packageName: String) { val packagePath = packageName.replace('.', '/') fileList@ for (e in jtranscRt[packagePath].listdirRecursive().filter { it.name.endsWith(".class") }) { val clazz = readClass(e.file.readBytes()) val nativeMethodsWithoutBody = clazz.methods.filterIsInstance<MethodNode>() .filter { it.access hasFlag Opcodes.ACC_NATIVE } if (nativeMethodsWithoutBody.isNotEmpty()) { println("CLASS ${clazz.name} (native without body):") try { for (method in nativeMethodsWithoutBody.filter { method -> if (method.invisibleAnnotations != null) { !AstAnnotationList( AstMethodRef(FqName.fromInternal(clazz.name), method.name, types.demangleMethod(method.desc)), method.invisibleAnnotations.filterIsInstance<AnnotationNode>().map { it.toAst(types) }).contains<HaxeMethodBody>() } else { true } }) { println(" - ${method.name} : ${method.desc}") } } catch (e: Throwable) { e.printStackTrace() } } } } private fun readClass(data: ByteArray): ClassNode { return ClassNode(Opcodes.ASM5).apply { ClassReader(data).accept(this, ClassReader.SKIP_CODE + ClassReader.SKIP_DEBUG + ClassReader.SKIP_FRAMES) } } fun compareFiles(f1: SyncVfsFile, f2: SyncVfsFile) { //interface MemberRef {} data class MethodRef(val name: String, val desc: String) fun ClassNode.getPublicOrProtectedMethodDescs() = this.methods .filterIsInstance<MethodNode>() .filter { it.access hasAnyFlags (Opcodes.ACC_PUBLIC or Opcodes.ACC_PROTECTED) } .map { MethodRef(it.name, it.desc) } fun ClassNode.getPublicOrProtectedFieldDescs() = this.methods .filterIsInstance<FieldNode>() .filter { it.access hasAnyFlags (Opcodes.ACC_PUBLIC or Opcodes.ACC_PROTECTED) } .map { AstFieldWithoutClassRef(it.name, types.demangle(it.desc)) } if (f1.exists) { val javaClass = readClass(f1.readBytes()) if (javaClass.access hasAnyFlags Opcodes.ACC_PUBLIC) { if (f2.exists) { val jtranscClass = readClass(f2.readBytes()) val javaMethods = javaClass.getPublicOrProtectedMethodDescs() val jtranscMethods = jtranscClass.getPublicOrProtectedMethodDescs() val javaFields = javaClass.getPublicOrProtectedFieldDescs() val jtranscFields = jtranscClass.getPublicOrProtectedFieldDescs() val methodResults = javaMethods.diff(jtranscMethods) val fieldResults = javaFields.diff(jtranscFields) if (methodResults.justFirst.isNotEmpty()) { println("${javaClass.name} (missing methods)") for (i in methodResults.justFirst) { println(" - ${i.name} : ${i.desc}") } } if (fieldResults.justFirst.isNotEmpty()) { println("${javaClass.name} (missing fields)") for (i in fieldResults.justFirst) { println(" - ${i.name} : ${i.type.mangle()}") } } } else { println("${javaClass.name} (missing class)") } } //for (node in origClass.methods.filterIsInstance<MethodNode>()) node.name + node.desc //println("" + f1.path + " : " + f2.path) } } }
apache-2.0
70398215eb22ddbdc0b2bc8d46cd5bb7
34.144928
156
0.704475
3.562821
false
false
false
false
bmaslakov/kotlin-algorithm-club
src/test/io/uuddlrlrba/ktalgs/datastructures/QueueTest.kt
1
2477
/* * Copyright (c) 2017 Kotlin Algorithm Club * * 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 io.uuddlrlrba.ktalgs.datastructures import org.junit.Assert import org.junit.Test import java.util.* class QueueTest { @Test fun emptyTest() { val queue = Queue<Int>() Assert.assertEquals(0, queue.size) Assert.assertTrue(queue.isEmpty()) } @Test(expected= NoSuchElementException::class) fun exceptionTest() { val queue = Queue<Int>() queue.peek() } @Test fun naiveTest() { val queue = Queue<Int>() for (i in 0..10) { queue.add(i) } for (i in 0..10) { Assert.assertEquals(i, queue.peek()) Assert.assertEquals(i, queue.poll()) } Assert.assertEquals(0, queue.size) } @Test fun naiveIteratorTest() { val queue = Queue<Int>() for (i in 0..10) { queue.add(i) } var k = 0 for (i in queue) { Assert.assertEquals(i, k++) } } @Test fun naiveContainsTest() { val queue = Queue<Int>() for (i in 0..10) { queue.add(i) } for (i in 0..10) { Assert.assertTrue(queue.contains(i)) } Assert.assertFalse(queue.contains(100)) Assert.assertFalse(queue.contains(101)) Assert.assertFalse(queue.contains(103)) } }
mit
ee85d8f81929ef2d7d74d48ef6c67c36
28.488095
81
0.631813
4.184122
false
true
false
false
hazuki0x0/YuzuBrowser
module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/filter/unified/EndWithFilter.kt
1
1296
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.adblock.filter.unified import android.net.Uri class EndWithFilter( filter: String, contentType: Int, domains: DomainMap?, thirdParty: Int ) : UnifiedFilter(filter, contentType, false, domains, thirdParty) { override val filterType: Int get() = FILTER_TYPE_END override fun check(url: Uri): Boolean { val urlStr = url.toString() val index = urlStr.indexOf(pattern) if (index >= 0) { return if (index + pattern.length == urlStr.length) { true } else { urlStr[index + pattern.length].checkSeparator() } } return false } }
apache-2.0
bbb662ebfa5f6692868a0a52f43dd34c
29.857143
75
0.655864
4.180645
false
false
false
false
dcz-switcher/niortbus
app/src/main/java/com/niortreactnative/activities/MainActivity.kt
1
1841
package com.niortreactnative.activities import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.util.Log import com.niortreactnative.R import com.niortreactnative.adapters.Line import com.niortreactnative.fragments.LineDetailFragment import com.niortreactnative.fragments.LineListFragment class MainActivity : AppCompatActivity(), LineListFragment.OnLineSelectedListener { private val TAG:String = "MainActivity" private val TAG_LINELIST_FRAGMENT = "tag_linelist_fragment" private val TAG_LINEDETAIL_FRAGMENT = "tag_linedetail_fragment" private var lineListFragment:LineListFragment? = null override fun onLineSelected(line: Line){ Log.d(TAG, "hey ! it works dude") Log.d(TAG, "line departure is " + line.departure) supportFragmentManager.beginTransaction() .add(R.id.fragment_stack, LineDetailFragment(), TAG_LINEDETAIL_FRAGMENT) .addToBackStack(TAG_LINEDETAIL_FRAGMENT) .commit() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d(TAG, "on create") setContentView(R.layout.activity_main) lineListFragment = supportFragmentManager.findFragmentByTag(TAG_LINELIST_FRAGMENT) as? LineListFragment if (lineListFragment == null) { lineListFragment = LineListFragment() supportFragmentManager.beginTransaction() .replace(R.id.fragment_stack, lineListFragment, TAG_LINELIST_FRAGMENT) .commit() } //todo manager navigation between views /* supportFragmentManager.beginTransaction() .replace(R.id.fragment_stack, LineDetailFragment(), TAG_LINEDETAIL_FRAGMENT) .commit() */ } }
mit
18a7e94caf3f4fe5d8f2975bd91a758f
31.875
111
0.688756
4.794271
false
false
false
false
badoualy/kotlogram
mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/secure/pq/PQSolver.kt
1
2440
package com.github.badoualy.telegram.mtproto.secure.pq import com.github.badoualy.telegram.mtproto.util.SolvedPQ import java.math.BigInteger import java.util.* internal class PQSolver { companion object { /** * Decomposes pq into prime factors such that p < q * Same implementation than https://github.com/enricostara/telegram-mt-node/blob/master/lib/security/pq-finder.js * TODO: check origin */ @JvmStatic @SuppressWarnings("SuspiciousNameCombination") fun solve(input: BigInteger): SolvedPQ { val r = Random() val pq = input.toLong() var q: Long = 0 for (i in 0..2) { val w = (r.nextInt(128) and 15) + 17 var x = (r.nextInt(1000000000) + 1).toLong() var y = x val lim = 1 shl (i + 18) for (j in 1..lim - 1) { var a = x var b = x var c = w.toLong() while (b != 0L) { if ((b and 1) != 0L) { c += a if (c >= pq) { c -= pq } } a += a if (a >= pq) { a -= pq } b = b shr 1 } x = c val z = if (x < y) y - x else x - y // var z = y.gt(x) TODO why different here ? q = GCD(z, pq) if (q != 1L) break if ((j and (j - 1)) == 0) y = x } if (q > 1) break } val p = pq / q return SolvedPQ(p, q) } private fun GCD(x: Long, y: Long): Long { var a = x var b = y while (a != 0L && b != 0L) { while ((b and 1) == 0L) { b = b shr 1 } while ((a and 1) == 0L) { a = a shr 1 } if (a > b) { a -= b } else { b -= a } } return if (b == 0L) a else b } } }
mit
88e88218bbb90246da1824d67019146d
29.898734
121
0.329098
4.510166
false
false
false
false
savoirfairelinux/ring-client-android
ring-android/app/src/main/java/cx/ring/tv/about/AboutDetailsPresenter.kt
1
1694
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package cx.ring.tv.about import android.content.Context import androidx.leanback.widget.Presenter import android.view.ViewGroup import android.view.LayoutInflater import cx.ring.databinding.DetailViewContentBinding import cx.ring.tv.cards.iconcards.IconCard class AboutDetailsPresenter(private val context: Context) : Presenter() { private var binding: DetailViewContentBinding? = null override fun onCreateViewHolder(parent: ViewGroup): ViewHolder { return ViewHolder(DetailViewContentBinding.inflate(LayoutInflater.from(context)) .apply { binding = this } .root) } override fun onBindViewHolder(viewHolder: ViewHolder, itemData: Any) { val card = itemData as IconCard binding?.apply { primaryText.text = card.title extraText.text = card.description } } override fun onUnbindViewHolder(viewHolder: ViewHolder) {} }
gpl-3.0
bc171e7fcd6f3437d89dd90ce6f17ab4
36.666667
88
0.727863
4.434555
false
false
false
false
hhariri/mark-code
src/main/kotlin/com/hadihariri/markcode/Main.kt
1
757
package com.hadihariri.markcode import java.io.File fun main(args: Array<String>) { if (args.size < 2) { println("Usage: <doc_directory> <examples output directory> [-o]") return } val writeExpectedOutput = args.size > 2 && args[2] == "-o" val chapters = mutableListOf<Chapter>() File(args[0]).listFiles { _, name -> name.endsWith(".adoc") }.forEach { val chapterCodeDir = File(args[1], it.nameWithoutExtension ) val chapter = Chapter(it, chapterCodeDir) chapters.add(chapter) chapter.process(writeExpectedOutput) } if (writeExpectedOutput) { writeVerifyAllSamples(chapters, File(args[1])) } if (chapters.any { it.hasErrors }) { System.exit(1) } }
mit
828f2168040725cc785c2ff32515b406
27.037037
75
0.620872
3.766169
false
false
false
false
cloudbearings/contentful-management.java
src/test/kotlin/com/contentful/java/cma/ModuleTests.kt
1
3255
/* * Copyright (C) 2014 Contentful GmbH * * 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.contentful.java.cma import com.contentful.java.cma.model.CMAResource import retrofit.RestAdapter import java.util.concurrent.CountDownLatch import kotlin.test.assertEquals import kotlin.test.assertNotEquals import org.junit.Before as before import org.junit.Test as test class ModuleTests : BaseTest() { var module: AbsModule<Any>? = null before fun setup() { super<BaseTest>.setUp() module = object : AbsModule<Any>(null, SynchronousExecutor()) { override fun createService(restAdapter: RestAdapter?): Any? { return null } } } test(expected = IllegalArgumentException::class) fun testNotNull() { try { module!!.assertNotNull(null, "parameter") } catch (e: IllegalArgumentException) { assertEquals("parameter may not be null.", e.getMessage()) throw e } } test(expected = IllegalArgumentException::class) fun testResourceId() { try { module!!.getResourceIdOrThrow(CMAResource(), "parameter") } catch (e: IllegalArgumentException) { assertEquals("parameter.setId() was not called.", e.getMessage()) throw e } } test(expected = IllegalArgumentException::class) fun testSpaceId() { try { module!!.getSpaceIdOrThrow(CMAResource(), "parameter") } catch (e: IllegalArgumentException) { assertEquals("parameter must have a space associated.", e.getMessage()) throw e } } test fun testDefersToBackgroundThread() { val currentThreadId = Thread.currentThread().getId() var workerThreadId: Long? = null val module = object : AbsModule<Any>(null, SynchronousExecutor()) { override fun createService(restAdapter: RestAdapter?): Any? = null fun work() { val cdl = CountDownLatch(1) defer( object : RxExtensions.DefFunc<Long>() { override fun method(): Long? { workerThreadId = Thread.currentThread().getId() return workerThreadId } }, object : CMACallback<Long>() { override fun onSuccess(result: Long?) { cdl.countDown() } }) cdl.await() } } module.work() assertNotEquals(currentThreadId, workerThreadId) } }
apache-2.0
89d6de0310e5dd6e7834c9f882654385
31.888889
83
0.583717
5.199681
false
true
false
false
jrenner/kotlin-voxel
core/src/main/kotlin/org/jrenner/learngl/Assets.kt
1
3305
package org.jrenner.learngl import com.badlogic.gdx.assets.AssetManager import com.badlogic.gdx.scenes.scene2d.ui.Skin import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle import com.badlogic.gdx.graphics.Pixmap import com.badlogic.gdx.math.MathUtils import com.badlogic.gdx.graphics.Texture import kotlin.properties.Delegates import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.Texture.TextureFilter import com.badlogic.gdx.graphics.Texture.TextureWrap import com.badlogic.gdx.assets.loaders.TextureLoader.TextureParameter class Assets { val manager = AssetManager() private val texturePath = "texture/" fun load(){ val texParam = TextureParameter() texParam.genMipMaps = true texParam.magFilter = TextureFilter.Linear texParam.minFilter = TextureFilter.MipMapLinearLinear fun loadTex(path: String) = manager.load(texturePath + path, Texture::class.java, texParam) arrayOf( "dirt.png" //"grass.png" ).forEach { loadTex(it) } manager.load("ui/ui.json", Skin::class.java) manager.finishLoading() skin = manager.get("ui/ui.json") setupSkinFonts() } private fun getTexture(name: String): Texture = manager.get(texturePath + name, Texture::class.java) val grassTexture by lazy { getTexture("grass.png") } val dirtTexture by lazy { getTexture("dirt.png") } fun setupSkinFonts() { skin.get(LabelStyle::class.java).font = fonts.normal } val uvTestTexture: Texture by lazy { val sz = 64 val pixmap = Pixmap(sz, sz, Pixmap.Format.RGBA8888) pixmap.setColor(Color.GRAY) pixmap.fill() pixmap.setColor(Color.BLACK) pixmap.drawCircle(sz / 2, sz / 2, sz / 2 - 2) pixmap.setColor(Color.BLUE) val c = sz / 2 pixmap.drawLine(c, c, c + 8, c) pixmap.setColor(Color.MAGENTA) pixmap.drawLine(c, c, c, c + 8) pixmap.setColor(Color.YELLOW) pixmap.drawRectangle(c, c + 8, 3, 3) pixmap.setColor(Color.RED) pixmap.drawRectangle(c + 8, c, 3, 3) val tex = Texture(pixmap, true) tex.setFilter(TextureFilter.MipMapLinearNearest, TextureFilter.Linear) tex.setWrap(TextureWrap.Repeat, TextureWrap.Repeat) pixmap.dispose() tex } fun createTexture(baseColor: Color): Texture { val sz = 64 val pixmap = Pixmap(sz, sz, Pixmap.Format.RGBA8888) for (y in 0..sz-1) { for (x in 0..sz-1) { val c = MathUtils.random(0.3f, 0.6f) val r = Math.max(0f, baseColor.r - c) val g = Math.max(0f, baseColor.g - c) val b = Math.max(0f, baseColor.b - c) pixmap.setColor(r, g, b, 1.0f) pixmap.drawPixel(x, y) } } val tex = Texture(pixmap, true) //tex.setFilter(TextureFilter.MipMapLinearNearest, TextureFilter.Linear) tex.setFilter(TextureFilter.Nearest, TextureFilter.Nearest) tex.setWrap(TextureWrap.Repeat, TextureWrap.Repeat) pixmap.dispose() return tex } }
apache-2.0
8be2df6a8b50b2bdd83ca1b75aa6f2e9
32.072165
104
0.609985
3.939213
false
false
false
false
tmarsteel/kotlin-prolog
stdlib/src/main/kotlin/com/github/prologdb/runtime/stdlib/essential/math/MathOperatorRegistry.kt
1
3316
package com.github.prologdb.runtime.stdlib.essential.math import com.github.prologdb.runtime.ClauseIndicator import com.github.prologdb.runtime.term.CompoundTerm import com.github.prologdb.runtime.term.PrologNumber import com.github.prologdb.runtime.util.ArityMap /** * Takes an arithmetic compound term (e.g. +(1,2) or mod(23,4)) and returns the calculated value */ typealias Calculator = (CompoundTerm) -> PrologNumber /** * Keeps track of ways to evaluate mathematical compounds. This is global; registring a new calculator * will affect all prolog runtimes. * * **This is not an [com.github.prologdb.runtime.util.OperatorRegistry]!** */ object MathOperatorRegistry { /** * Maps operator names to calculators */ private val calculators: MutableMap<String, ArityMap<Calculator>> = mutableMapOf() fun registerOperator(operatorName: String, arities: IntRange, calculator: Calculator) { if (arities.first <= 0) { throw IllegalArgumentException("Cannot register an arithmetic operator with arity less than 1") } val arityMap: ArityMap<Calculator> if (operatorName in calculators) { arityMap = calculators[operatorName]!! } else { arityMap = ArityMap() calculators[operatorName] = arityMap } for (arity in arities) { arityMap[arity] = calculator } } fun getCalculator(operatorName: String, arity: Int): Calculator? = calculators[operatorName]?.get(arity) /** * Evaluates the given compound term as an arithmetic expression. */ fun evaluate(compoundTerm: CompoundTerm): PrologNumber { val calculator = getCalculator(compoundTerm.functor, compoundTerm.arity) ?: throw UndefinedMathOperatorException(ClauseIndicator.of(compoundTerm)) return calculator(compoundTerm) } fun registerOperator(operatorName: String, calculator: (PrologNumber) -> PrologNumber) { registerOperator(operatorName, 1..1) { termAST -> if (termAST.arity != 1 || termAST.functor != operatorName) { throw InvalidMathOperatorInvocationException(ClauseIndicator.of(operatorName, 1), ClauseIndicator.of(termAST)) } calculator(termAST.arguments[0].asPrologNumber) } } fun registerOperator(operatorName: String, calculator: (PrologNumber, PrologNumber) -> PrologNumber) { registerOperator(operatorName, 2..2) { compoundTerm -> if (compoundTerm.arity != 2 || compoundTerm.functor != operatorName) { throw InvalidMathOperatorInvocationException(ClauseIndicator.of(operatorName, 2), ClauseIndicator.of(compoundTerm)) } calculator(compoundTerm.arguments[0].asPrologNumber, compoundTerm.arguments[1].asPrologNumber) } } init { // common binary operators registerOperator("+", PrologNumber::plus) registerOperator("-", PrologNumber::minus) registerOperator("*", PrologNumber::times) registerOperator("/", PrologNumber::div) registerOperator("mod", PrologNumber::rem) registerOperator("^", PrologNumber::toThe) registerOperator("+", PrologNumber::unaryPlus) registerOperator("-", PrologNumber::unaryMinus) } }
mit
1cc7920ed1d6505025e6188bc7ff9117
38.47619
131
0.680036
4.971514
false
false
false
false
Camano/CoolKotlin
utilities/passwordgen.kt
1
608
import java.util.* fun main(args: Array<String>) { val length = 10 // password length println(generatePswd(length)) } internal fun generatePswd(len: Int): CharArray { println("Your Password:") val charsCaps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" val chars = "abcdefghijklmnopqrstuvwxyz" val nums = "0123456789" val symbols = "!@#$%^&*_=+-/€.?<>)" val passSymbols = charsCaps + chars + nums + symbols val rnd = Random() val password = CharArray(len) for (i in 0..len - 1) { password[i] = passSymbols[rnd.nextInt(passSymbols.length)] } return password }
apache-2.0
7095e82c516282833f180551d63cf763
27.857143
66
0.640264
3.717791
false
false
false
false
googlecodelabs/android-datastore
app/src/main/java/com/codelab/android/datastore/data/TasksRepository.kt
1
2349
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.codelab.android.datastore.data import kotlinx.coroutines.flow.flowOf import java.text.SimpleDateFormat import java.util.Date import java.util.Locale object TasksRepository { private val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US) // In a real app, this would be coming from a data source like a database val tasks = flowOf( listOf( Task( name = "Open codelab", deadline = simpleDateFormat.parse("2020-07-03")!!, priority = TaskPriority.LOW, completed = true ), Task( name = "Import project", deadline = simpleDateFormat.parse("2020-04-03")!!, priority = TaskPriority.MEDIUM, completed = true ), Task( name = "Check out the code", deadline = simpleDateFormat.parse("2020-05-03")!!, priority = TaskPriority.LOW ), Task( name = "Read about DataStore", deadline = simpleDateFormat.parse("2020-06-03")!!, priority = TaskPriority.HIGH ), Task( name = "Implement each step", deadline = Date(), priority = TaskPriority.MEDIUM ), Task( name = "Understand how to use DataStore", deadline = simpleDateFormat.parse("2020-04-03")!!, priority = TaskPriority.HIGH ), Task( name = "Understand how to migrate to DataStore", deadline = Date(), priority = TaskPriority.HIGH ) ) ) }
apache-2.0
d8ff092f48d1643c112c249843009ad9
33.544118
97
0.571733
5.051613
false
false
false
false
nickthecoder/tickle
tickle-groovy/src/main/kotlin/uk/co/nickthecoder/tickle/groovy/GroovyLanguage.kt
1
5277
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.groovy import groovy.lang.GroovyRuntimeException import groovy.util.GroovyScriptEngine import uk.co.nickthecoder.tickle.Director import uk.co.nickthecoder.tickle.Producer import uk.co.nickthecoder.tickle.Role import uk.co.nickthecoder.tickle.scripts.Language import uk.co.nickthecoder.tickle.scripts.ScriptException import java.io.File import java.util.regex.Pattern class GroovyLanguage : Language() { private lateinit var engine: GroovyScriptEngine override val fileExtension = "groovy" override val name = "Groovy" private lateinit var path: File override fun setClasspath(directory: File) { path = directory createEngine() } private fun createEngine() { engine = GroovyScriptEngine(path.path) engine.config.minimumRecompilationInterval = 0 } override fun loadScript(file: File): Class<*> { try { return engine.loadScriptByName(file.name) } catch (e: GroovyRuntimeException) { throw convertException(e) } catch (e: Exception) { e.printStackTrace() throw ScriptException(e) } } override fun clear() { super.clear() // By creating a new engine, I hope that the classes used by the previous engine's // classloader can be garbage collected. createEngine() } override fun generateScript(name: String, type: Class<*>?): String { return when (type) { Role::class.java -> generateRole(name) Director::class.java -> generateDirector(name) Producer::class.java -> generateProducer(name) else -> generatePlainScript(name, type) } } fun generatePlainScript(name: String, type: Class<*>?) = """import uk.co.nickthecoder.tickle.* ${if (type == null || type.`package`.name == "uk.co.nickthecoder.tickle") "" else "import ${type.name}"} import uk.co.nickthecoder.tickle.resources.* class $name ${if (type == null) "" else (if (type.isInterface) "implements" else "extends") + " ${type.simpleName}"}{ } """ fun generateRole(name: String) = """import uk.co.nickthecoder.tickle.* import uk.co.nickthecoder.tickle.resources.* class $name extends AbstractRole { // NOTE. Some common methods were automatically generated. // These may be removed if you don't need them. void begin() { } void activated() { } // tick is called 60 times per second (a Role MUST have a tick method). void tick() { } } """ fun generateDirector(name: String) = """import uk.co.nickthecoder.tickle.* import uk.co.nickthecoder.tickle.resources.* import uk.co.nickthecoder.tickle.events.* class $name extends AbstractDirector { // NOTE. Some common methods were automatically generated. // These may be removed if you don't need them. void sceneLoaded() { } void begin() { } void activated() { } void onKey(KeyEvent event) { } void onMouseButton(MouseEvent event) { } } """ fun generateProducer(name: String) = """import uk.co.nickthecoder.tickle.* import uk.co.nickthecoder.tickle.resources.* import uk.co.nickthecoder.tickle.events.* class $name extends AbstractProducer { // NOTE. Some common methods were automatically generated. // These may be removed if you don't need them. void begin() { } void sceneLoaded() { } void sceneBegin() { } void sceneEnd() { } void sceneActivated() { } void tick() { } void onKey(KeyEvent event) { } void onMouseButton(MouseEvent event) { } } """ companion object { private val messagePattern = Pattern.compile("file\\:(?<FILE>.*?\\.groovy)|line (?<LINE>\\d*), column (?<COLUMN>\\d*)") fun convertException(e: GroovyRuntimeException): ScriptException { var message = e.message ?: return ScriptException(e) val matcher = messagePattern.matcher(message) var file: File? = null var line: Int? = null var column: Int? = null while (matcher.find()) { matcher.group("FILE")?.let { file = File(it) } matcher.group("LINE")?.let { line = it.toInt() } matcher.group("COLUMN")?.let { column = it.toInt() message = message.substring(0, matcher.end()) } } message = message.removePrefix("startup failed:\n") return ScriptException(message, e, file, line, column) } } }
gpl-3.0
6621b27c0f8960fb0a1ef65deb0c3195
25.253731
127
0.643737
4.272874
false
false
false
false
androidx/constraintlayout
projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/Bug01Composable.kt
2
5420
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.constraintlayout import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.constraintlayout.compose.ConstraintLayout import androidx.constraintlayout.compose.Dimension import androidx.fragment.app.DialogFragment import java.util.* private const val LOREM_IPSUM_LONG = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." /** * A SIMPLIFIED/minimalist version of the problem I am encountering. * Contains a [ConstraintLayout] with two sections: * 1. textSection: Section for the text. THIS SECTION KEEPS GETTING UNDESIRABLY CROPPED * - When increasing font-size of the device, such that the content gets bigger than the screen, * I would have this section scrollable (currently leaving scroll out for simplicity) * 2. buttonSection: Section for sticky buttons anchored to the bottom of the dialog * - When increasing font-size of the device, such that the content gets bigger than the screen, * I want this section to stick to the bottom (as opposed to be scrollable) * (In my real example, there are more items in each section. Hence, the use of [Box]) */ @Preview(widthDp = 270, heightDp = 320, backgroundColor = 0xFFFFFF, showBackground = true) @Composable fun TestDialogContent() { ConstraintLayout( modifier = Modifier .fillMaxWidth() .wrapContentHeight() ) { val (textSection, buttonSection) = createRefs() Column( modifier = Modifier.constrainAs(textSection) { top.linkTo(parent.top, margin = 48.dp) bottom.linkTo(buttonSection.top, margin = 16.dp) start.linkTo(parent.start, margin = 24.dp) end.linkTo(parent.end, margin = 24.dp) width = Dimension.matchParent /** * I want this to wrap the height of the entire [Text] * Instead, I'm only seeing a cropped section of the [Text] * I've also tried: * - Dimension.preferredWrapContent.atLeastWrapContent * - Dimension.fillToConstraints.atLeastWrapContent * - Dimension.preferredWrapContent */ height = Dimension.preferredWrapContent } ) { Text( modifier = Modifier .fillMaxWidth() .wrapContentHeight(), text = "Lorem ipsum dolor sit amet", style = MaterialTheme.typography.h5, color = Color.Gray, fontWeight = FontWeight.Medium, ) Spacer(Modifier.height(8.dp)) Text( text = LOREM_IPSUM_LONG, style = MaterialTheme.typography.body2, color = Color.Gray ) } Box( modifier = Modifier.constrainAs(buttonSection) { bottom.linkTo(parent.bottom, margin = 48.dp) start.linkTo(parent.start, margin = 24.dp) end.linkTo(parent.end, margin = 24.dp) width = Dimension.matchParent height = Dimension.wrapContent } ) { Button( modifier = Modifier .fillMaxWidth() .wrapContentHeight(), onClick = { }, shape = RoundedCornerShape(30.dp), contentPadding = PaddingValues(horizontal = 24.dp, vertical = 14.dp), ) { Text(text = "BUTTON", textAlign = TextAlign.Center) } } } }
apache-2.0
53a4e5a0b293f29f8f3ff32baf2268b6
43.065041
486
0.663284
4.59322
false
false
false
false
quarck/CalendarNotification
app/src/main/java/com/github/quarck/calnotify/monitorstorage/MonitorStorage.kt
1
5105
// // Calendar Notifications Plus // Copyright (C) 2017 Sergey Parshin ([email protected]) // // 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, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // package com.github.quarck.calnotify.monitorstorage import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import com.github.quarck.calnotify.calendar.MonitorEventAlertEntry import com.github.quarck.calnotify.logs.DevLog //import com.github.quarck.calnotify.logs.Logger import java.io.Closeable class MonitorStorage(val context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_CURRENT_VERSION), Closeable, MonitorStorageInterface { private var impl: MonitorStorageImplInterface init { impl = MonitorStorageImplV1(context); } override fun onCreate(db: SQLiteDatabase) = impl.createDb(db) override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { DevLog.info(LOG_TAG, "onUpgrade $oldVersion -> $newVersion") if (oldVersion != newVersion) { throw Exception("DB storage error: upgrade from $oldVersion to $newVersion is not supported") } } override fun addAlert(entry: MonitorEventAlertEntry) = synchronized(MonitorStorage::class.java) { writableDatabase.use { impl.addAlert(it, entry) } } override fun addAlerts(entries: Collection<MonitorEventAlertEntry>) = synchronized(MonitorStorage::class.java) { writableDatabase.use { impl.addAlerts(it, entries) } } override fun deleteAlert(entry: MonitorEventAlertEntry) = deleteAlert(entry.eventId, entry.alertTime, entry.instanceStartTime) override fun deleteAlerts(entries: Collection<MonitorEventAlertEntry>) = synchronized(MonitorStorage::class.java) { writableDatabase.use { impl.deleteAlerts(it, entries) } } override fun deleteAlert(eventId: Long, alertTime: Long, instanceStart: Long) = synchronized(MonitorStorage::class.java) { writableDatabase.use { impl.deleteAlert(it, eventId, alertTime, instanceStart) } } override fun deleteAlertsMatching(filter: (MonitorEventAlertEntry) -> Boolean) = synchronized(MonitorStorage::class.java) { writableDatabase.use { impl.deleteAlertsMatching(it, filter) } } override fun updateAlert(entry: MonitorEventAlertEntry) = synchronized(MonitorStorage::class.java) { writableDatabase.use { impl.updateAlert(it, entry) } } override fun updateAlerts(entries: Collection<MonitorEventAlertEntry>) = synchronized(MonitorStorage::class.java) { writableDatabase.use { impl.updateAlerts(it, entries) } } override fun getAlert(eventId: Long, alertTime: Long, instanceStart: Long): MonitorEventAlertEntry? = synchronized(MonitorStorage::class.java) { readableDatabase.use { impl.getAlert(it, eventId, alertTime, instanceStart) } } override fun getInstanceAlerts(eventId: Long, instanceStart: Long): List<MonitorEventAlertEntry> = synchronized(MonitorStorage::class.java) { readableDatabase.use { impl.getInstanceAlerts(it, eventId, instanceStart) } } override fun getNextAlert(since: Long): Long? = synchronized(MonitorStorage::class.java) { readableDatabase.use { impl.getNextAlert(it, since) } } override fun getAlertsAt(time: Long): List<MonitorEventAlertEntry> = synchronized(MonitorStorage::class.java) { readableDatabase.use { impl.getAlertsAt(it, time) } } override val alerts: List<MonitorEventAlertEntry> get() = synchronized(MonitorStorage::class.java) { readableDatabase.use { impl.getAlerts(it) } } override fun getAlertsForInstanceStartRange(scanFrom: Long, scanTo: Long): List<MonitorEventAlertEntry> = synchronized(MonitorStorage::class.java) { readableDatabase.use { impl.getAlertsForInstanceStartRange(it, scanFrom, scanTo) } } override fun getAlertsForAlertRange(scanFrom: Long, scanTo: Long): List<MonitorEventAlertEntry> = synchronized(MonitorStorage::class.java) { readableDatabase.use { impl.getAlertsForAlertRange(it, scanFrom, scanTo) } } companion object { private const val LOG_TAG = "MonitorStorage" private const val DATABASE_VERSION_V1 = 1 private const val DATABASE_CURRENT_VERSION = DATABASE_VERSION_V1 private const val DATABASE_NAME = "CalendarMonitor" } }
gpl-3.0
9c666b776d1f9b77e73c2ccca10bae80
47.628571
141
0.732223
4.545859
false
false
false
false
LorittaBot/Loritta
web/showtime/showtime-frontend/src/jsMain/kotlin/net/perfectdreams/loritta/cinnamon/showtime/frontend/utils/LinkPreloaderManager.kt
1
6908
package net.perfectdreams.loritta.cinnamon.showtime.frontend.utils import io.ktor.client.request.* import io.ktor.client.statement.* import kotlinx.browser.document import kotlinx.browser.window import kotlinx.coroutines.sync.withLock import kotlinx.dom.removeClass import net.perfectdreams.loritta.cinnamon.showtime.frontend.ShowtimeFrontend import net.perfectdreams.loritta.cinnamon.showtime.frontend.utils.extensions.onClick import net.perfectdreams.loritta.cinnamon.showtime.frontend.utils.extensions.select import net.perfectdreams.loritta.cinnamon.showtime.frontend.utils.extensions.selectAll import org.w3c.dom.Element import org.w3c.dom.HTMLBodyElement import org.w3c.dom.HTMLElement import org.w3c.dom.HTMLTitleElement import org.w3c.dom.asList import org.w3c.dom.url.URL class LinkPreloaderManager(val showtime: ShowtimeFrontend) { companion object { private const val PRELOAD_LINK_ATTRIBUTE = "data-preload-link" private const val PRELOAD_LINK_ACTIVE_ATTRIBUTE = "data-preload-link-activated" private const val PRELOAD_PERSIST_ATTRIBUTE = "data-preload-persist" private const val PRELOAD_KEEP_SCROLL = "data-preload-keep-scroll" } fun setupLinkPreloader() { println("Setting up link preloader") document.querySelectorAll("a[$PRELOAD_LINK_ATTRIBUTE=\"true\"]:not([$PRELOAD_LINK_ACTIVE_ATTRIBUTE=\"true\"])") .asList().forEach { if (it is Element) { setupLinkPreloader(it) } } } fun setupLinkPreloader(element: Element) { val location = document.location ?: return // I wonder when location can be null... var pageUrl = element.getAttribute("href")!! if (pageUrl.startsWith("http")) { if (!pageUrl.startsWith(window.location.origin)) // Mesmo que seja no mesmo domínio, existe as políticas de CORS return val urlLocation = URL(pageUrl) pageUrl = urlLocation.pathname } element.setAttribute(PRELOAD_LINK_ACTIVE_ATTRIBUTE, "true") element.onClick { it -> println("Clicked!!! $pageUrl") val body = document.body ?: return@onClick // If we don't have a body, what we will switch to? if (it.asDynamic().ctrlKey as Boolean || it.asDynamic().metaKey as Boolean || it.asDynamic().shiftKey as Boolean) return@onClick it.preventDefault() // Same page, no need to redirect /* if (pageUrl == window.location.pathname) return@onClick */ println("Going to load $pageUrl") showtime.launchGlobal { // Close navbar if it is open, this avoids the user clicking on something and wondering "but where is the new content?" val navbar = document.select<Element?>("#navigation-bar") navbar?.removeClass("expanded") document.body!!.style.overflowY = "" // Start progress indicator showtime.startFakeProgressIndicator() // First prepare the page preload, this is useful so the page can preload data (do queries, as an example) before we totally switch val preparePreLoadJob = showtime.async { showtime.viewManager.preparePreLoad(pageUrl) } // Switch page // We need to rebuild the URL from scratch, if we just do a "pageUrl" request, it won't add the port for some reason val content = ShowtimeFrontend.http.get(location.protocol + "//" + location.host + pageUrl) { header("Link-Preload", true) } println("Content:") println(content) // Find all persistent elements in the old page val persistentElements = document.selectAll<HTMLElement>("[$PRELOAD_PERSIST_ATTRIBUTE=\"true\"]") // Find all keep scroll elements in the old page // The values needs to be stored before switching, if not the value will be "0" val keepScrollElements = document.selectAll<HTMLElement>("[$PRELOAD_KEEP_SCROLL=\"true\"]") .map { it.id to it.scrollTop } // We need to create a dummy element to append our inner HTML val dummyElement = document.createElement("html") dummyElement.innerHTML = content.bodyAsText() // Await until preLoad is done to continue preparePreLoadJob.await() // We are now going to reuse the mutex in the pageManager // The reason we reuse it is to avoid calling "onLoad()" before "onPreLoad()" is finished! :3 showtime.viewManager.preparingMutex.withLock { // Replace the page's title dummyElement.select<HTMLTitleElement?>("title")?.let { println("Page title is ${it.outerHTML}") document.select<HTMLTitleElement?>("title")?.outerHTML = it.outerHTML } // Switch the page's content (not all, just the body xoxo) body.innerHTML = dummyElement.select<HTMLBodyElement?>("body")?.innerHTML ?: "Broken!" // Push the current page to history showtime.pushState(pageUrl) // Now copy the persistent elements persistentElements.forEach { val newElementThatShouldBeReplaced = document.getElementById(it.id) as HTMLElement? println("Persisted element $it is going to persist thru $newElementThatShouldBeReplaced") newElementThatShouldBeReplaced?.replaceWith(it) } // Also copy the keep scroll of the affected elements keepScrollElements.forEach { val newElementThatShouldChangeTheScroll = document.getElementById(it.first) as HTMLElement? println("Keeping element $it scroll, value: ${it.second}") newElementThatShouldChangeTheScroll?.scrollTop = it.second } // Now that all of the elements are loaded, we can switch from the preparing to the active view showtime.viewManager.switchPreparingToActiveView() // Reset scroll to the top of the page window.scrollTo(0.0, 0.0) // remove visible class and set progress bar to 100% showtime.stopFakeProgressIndicator() // Setup link preloader again setupLinkPreloader() // Also setup ads NitroPayUtils.renderAds() } } } } }
agpl-3.0
8a78d4d01f4d35d2ef0507ba19fdda0d
44.741722
147
0.605126
5.123145
false
false
false
false
MaibornWolff/codecharta
analysis/model/src/main/kotlin/de/maibornwolff/codecharta/serialization/ProjectWrapperJsonDeserializer.kt
1
1075
package de.maibornwolff.codecharta.serialization import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import de.maibornwolff.codecharta.model.ProjectWrapper import java.lang.reflect.Type class ProjectWrapperJsonDeserializer : JsonDeserializer<ProjectWrapper> { override fun deserialize(json: JsonElement, typeOfT: Type?, context: JsonDeserializationContext): ProjectWrapper { val projectJsonDeserializer = ProjectJsonDeserializer() val jsonObject = json.asJsonObject val data = jsonObject.get("data") val checksum = jsonObject.get("checksum") return if (data != null && checksum != null) { val project = projectJsonDeserializer.deserialize(data, typeOfT, context) ProjectWrapper(project, data.toString()) } else { val project = projectJsonDeserializer.deserialize(json, typeOfT, context) ProjectWrapper(project, json.toString()) } } }
bsd-3-clause
f15cf3b96f1a10e57fcbe04d16c0301f
42
122
0.692093
5.40201
false
false
false
false
DVT/showcase-android
app/src/main/kotlin/za/co/dvt/android/showcase/ui/contact/ContactUsViewModel.kt
1
1657
package za.co.dvt.android.showcase.ui.contact import android.arch.lifecycle.ViewModel import io.reactivex.Flowable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import za.co.dvt.android.showcase.injection.ShowcaseComponent import za.co.dvt.android.showcase.model.Office import za.co.dvt.android.showcase.repository.OfficesRepository import za.co.dvt.android.showcase.repository.TrackingRepository import za.co.dvt.android.showcase.utils.SingleLiveEvent import javax.inject.Inject /** * @author rebeccafranks * @since 2017/06/25. */ class ContactUsViewModel : ViewModel(), ShowcaseComponent.Injectable { override fun inject(component: ShowcaseComponent) { component.inject(this) } @Inject lateinit var officesRepository: OfficesRepository fun getOffices(): Flowable<List<Office>> = officesRepository.getOffices() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) @Inject lateinit var trackingRepository: TrackingRepository val openEmail: SingleLiveEvent<Office> = SingleLiveEvent() val openCall: SingleLiveEvent<Office> = SingleLiveEvent() val openNavigate: SingleLiveEvent<Office> = SingleLiveEvent() fun openEmail(office: Office) { trackingRepository.trackEmailOffice(office) openEmail.value = office } fun openCall(office: Office) { trackingRepository.trackCallOffice(office) openCall.value = office } fun openNavigation(office: Office) { trackingRepository.trackNavigationOffice(office) openNavigate.value = office } }
apache-2.0
939c1e6dd8548f9ff01efd825f85a227
29.145455
77
0.750151
4.418667
false
false
false
false
ericberman/MyFlightbookAndroid
app/src/main/java/com/myflightbook/android/webservices/ImagesSvc.kt
1
2022
/* MyFlightbook for Android - provides native access to MyFlightbook pilot's logbook Copyright (C) 2017-2022 MyFlightbook, LLC This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.myflightbook.android.webservices import android.content.Context import org.ksoap2.serialization.SoapSerializationEnvelope import model.MFBImageInfo import model.LatLong import com.myflightbook.android.marshal.MarshalDouble class ImagesSvc : MFBSoap(), Runnable { private var mContext: Context? = null override fun addMappings(e: SoapSerializationEnvelope) { e.addMapping(NAMESPACE, "MFBImageInfo", MFBImageInfo::class.java) e.addMapping(NAMESPACE, "LatLong", LatLong::class.java) val md = MarshalDouble() md.register(e) } override fun run() { invoke(mContext) } fun deleteImage(szAuthToken: String?, mfbii: MFBImageInfo?, c: Context?) { val request = setMethod("DeleteImage") request.addProperty("szAuthUserToken", szAuthToken) request.addProperty("mfbii", mfbii) mContext = c Thread(this).start() } fun updateImageAnnotation(szAuthToken: String?, mfbii: MFBImageInfo?, c: Context?) { val request = setMethod("UpdateImageAnnotation") request.addProperty("szAuthUserToken", szAuthToken) request.addProperty("mfbii", mfbii) mContext = c Thread(this).start() } }
gpl-3.0
31f434e5af31fd9553f260685f9c3ee6
35.781818
88
0.712166
4.48337
false
false
false
false
rpandey1234/kotlin-koans
src/i_introduction/_7_Nullable_Types/NullableTypes.kt
1
1101
package i_introduction._7_Nullable_Types import util.TODO import util.doc7 fun test() { val s: String = "this variable cannot store null references" val q: String? = null if (q != null) q.length // you have to check to dereference val i: Int? = q?.length // null val j: Int = q?.length ?: 0 // 0 } fun todoTask7(client: Client?, message: String?, mailer: Mailer): Nothing = TODO( """ Task 7. Rewrite JavaCode7.sendMessageToClient in Kotlin, using only one 'if' expression. Declarations of Client, PersonalInfo and Mailer are given below. """, documentation = doc7(), references = { JavaCode7().sendMessageToClient(client, message, mailer) } ) fun sendMessageToClient(client: Client?, message: String?, mailer: Mailer) { val email = client?.personalInfo?.email ?: return if (message == null) { return } mailer.sendMessage(email, message) } class Client (val personalInfo: PersonalInfo?) class PersonalInfo (val email: String?) interface Mailer { fun sendMessage(email: String, message: String) }
mit
963afd1c57f99e463b6db33fe45617ae
27.973684
88
0.663942
4.003636
false
false
false
false
GiuseppeGiacoppo/Android-Clean-Architecture-with-Kotlin
core/src/main/java/me/giacoppo/examples/kotlin/mvp/repository/interactor/executor/JobExecutor.kt
1
1045
package me.giacoppo.examples.kotlin.mvp.repository.interactor.executor import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit class JobExecutor private constructor() : ThreadExecutor { private val INITIAL_POOL_SIZE = 3 private val MAX_POOL_SIZE = 5 private val KEEP_ALIVE_TIME = 10 private val KEEP_ALIVE_TIME_UNIT: TimeUnit = TimeUnit.SECONDS private val threadPoolExecutor: ThreadPoolExecutor private object Holder { val instance: JobExecutor = JobExecutor() } companion object { val instance: JobExecutor by lazy { Holder.instance } } init { val workQueue : BlockingQueue<Runnable> = LinkedBlockingQueue() threadPoolExecutor = ThreadPoolExecutor(INITIAL_POOL_SIZE,MAX_POOL_SIZE,KEEP_ALIVE_TIME.toLong(),KEEP_ALIVE_TIME_UNIT,workQueue) } override fun execute(runnable: Runnable) { this.threadPoolExecutor.execute(runnable) } }
apache-2.0
754f818f0b23a13818f1a5d32f5c480a
32.741935
136
0.742584
4.707207
false
false
false
false
Bombe/Sone
src/main/kotlin/net/pterodactylus/sone/web/pages/ViewSonePage.kt
1
2159
package net.pterodactylus.sone.web.pages import net.pterodactylus.sone.data.* import net.pterodactylus.sone.main.* import net.pterodactylus.sone.template.* import net.pterodactylus.sone.utils.* import net.pterodactylus.sone.web.* import net.pterodactylus.sone.web.page.* import net.pterodactylus.util.template.* import java.net.* import javax.inject.* /** * Lets the user browser another Sone. */ @TemplatePath("/templates/viewSone.html") @ToadletPath("viewSone.html") class ViewSonePage @Inject constructor(webInterface: WebInterface, loaders: Loaders, templateRenderer: TemplateRenderer) : SoneTemplatePage(webInterface, loaders, templateRenderer) { override fun handleRequest(soneRequest: SoneRequest, templateContext: TemplateContext) { templateContext["soneId"] = soneRequest.parameters["sone"] soneRequest.parameters["sone"]!!.let(soneRequest.core::getSone)?.let { sone -> templateContext["sone"] = sone val sonePosts = sone.posts val directedPosts = soneRequest.core.getDirectedPosts(sone.id) (sonePosts + directedPosts) .sortedByDescending(Post::getTime) .paginate(soneRequest.core.preferences.postsPerPage) .apply { page = soneRequest.parameters["postPage"]?.toIntOrNull() ?: 0 } .also { templateContext["postPagination"] = it templateContext["posts"] = it.items } sone.replies .mapPresent(PostReply::getPost) .distinct() .minus(sonePosts) .minus(directedPosts) .sortedByDescending { soneRequest.core.getReplies(it.id).first().time } .paginate(soneRequest.core.preferences.postsPerPage) .apply { page = soneRequest.parameters["repliedPostPage"]?.toIntOrNull() ?: 0 } .also { templateContext["repliedPostPagination"] = it templateContext["repliedPosts"] = it.items } } } override fun isLinkExcepted(link: URI) = true override fun getPageTitle(soneRequest: SoneRequest): String = soneRequest.parameters["sone"]!!.let(soneRequest.core::getSone)?.let { sone -> "${SoneAccessor.getNiceName(sone)} - ${translation.translate("Page.ViewSone.Title")}" } ?: translation.translate("Page.ViewSone.Page.TitleWithoutSone") }
gpl-3.0
4a5052fb1d5d9d1cf7a77e1668ce00c9
36.877193
122
0.73321
3.925455
false
false
false
false
kysersozelee/KotlinStudy
JsonParser/src/main.kt
1
1107
import Json.* fun main(args: Array<String>) { //kotlin¿¡¼­ °´Ã¼ ¼±¾ðÇϰí ÇÔ¼ö È£ÃâÇÏ´Â Çü½ÄÀÌ ÀÌ¿Í °°³ª var jobj = JsonObject() jobj.add("õÁ¤ÇÊ", 29) jobj.add("½ÉÇö¿ì", 30) println("json array serialize ==> ${jobj.toJsonString()}") var jobj3 = JsonObject() jobj3.add("À̵¿¿ì", 99) var jobj2 = JsonObject() jobj2.add("idiots", jobj) jobj2.add("genius", jobj3) jobj2.add("null test", null) println("nested json object serialize ==> ${jobj2.toJsonString()}") var jarr = JsonArray() jarr.add(123) jarr.add("asd") jarr.add(0.323) jarr.add(true) println("json array serialize ==> ${jarr.toJsonString()}") var parser: JsonParser = JsonParser() var parsedJobj: JsonObject = parser.parse(jobj2.toJsonString()) as JsonObject var geniusJobj: JsonObject? = parsedJobj.get("genius")?.asObject() var parsedJarr: JsonArray = parser.parse(jarr.toJsonString()) as JsonArray println("json object deserialize input jsonstr : ${jobj2.toJsonString()} parsedJobj : ${parsedJobj.toJsonString()} genius : ==> ${geniusJobj?.toJsonString()}") }
bsd-2-clause
c57ab46454cdd7c9a769cd77fbeef1ce
24.404762
161
0.657633
2.853093
false
false
false
false
Ph1b/MaterialAudiobookPlayer
app/src/main/kotlin/de/ph1b/audiobook/features/bookOverview/BookOverviewViewModel.kt
1
4213
package de.ph1b.audiobook.features.bookOverview import androidx.datastore.core.DataStore import de.paulwoitaschek.flowpref.Pref import de.ph1b.audiobook.common.pref.CurrentBook import de.ph1b.audiobook.common.pref.PrefKeys import de.ph1b.audiobook.data.Book2 import de.ph1b.audiobook.data.repo.BookRepo2 import de.ph1b.audiobook.features.bookOverview.list.BookOverviewViewState import de.ph1b.audiobook.features.bookOverview.list.header.BookOverviewCategory import de.ph1b.audiobook.features.gridCount.GridCount import de.ph1b.audiobook.playback.PlayerController import de.ph1b.audiobook.playback.playstate.PlayStateManager import de.ph1b.audiobook.playback.playstate.PlayStateManager.PlayState import de.ph1b.audiobook.scanner.MediaScanTrigger import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import javax.inject.Inject import javax.inject.Named class BookOverviewViewModel @Inject constructor( private val repo: BookRepo2, private val mediaScanner: MediaScanTrigger, private val playStateManager: PlayStateManager, private val playerController: PlayerController, @CurrentBook private val currentBookDataStore: DataStore<Book2.Id?>, @Named(PrefKeys.GRID_MODE) private val gridModePref: Pref<GridMode>, private val gridCount: GridCount, ) { fun attach() { mediaScanner.scan() } fun useGrid(useGrid: Boolean) { gridModePref.value = if (useGrid) GridMode.GRID else GridMode.LIST } fun state(): Flow<BookOverviewState> { val playingStream = playStateManager.playStateFlow() .map { it == PlayState.Playing } .distinctUntilChanged() return combine( repo.flow(), currentBookDataStore.data, playingStream, mediaScanner.scannerActive, gridModePref.flow ) { books, currentBookId, playing, scannerActive, gridMode -> state( books = books, scannerActive = scannerActive, currentBookId = currentBookId, playing = playing, gridMode = gridMode ) } } private fun state( books: List<Book2>, scannerActive: Boolean, currentBookId: Book2.Id?, playing: Boolean, gridMode: GridMode ): BookOverviewState { if (books.isEmpty()) { return if (scannerActive) { BookOverviewState.Loading } else { BookOverviewState.NoFolderSet } } return content( books = books, currentBookId = currentBookId, playing = playing, gridMode = gridMode ) } private fun content( books: List<Book2>, currentBookId: Book2.Id?, playing: Boolean, gridMode: GridMode ): BookOverviewState.Content { val currentBookPresent = books.any { it.id == currentBookId } val amountOfColumns = gridCount.gridColumnCount(gridMode) val categoriesWithContents = LinkedHashMap<BookOverviewCategory, BookOverviewCategoryContent>() BookOverviewCategory.values().forEach { category -> val content = content(books, category, currentBookId, amountOfColumns) if (content != null) { categoriesWithContents[category] = content } } return BookOverviewState.Content( playing = playing, currentBookPresent = currentBookPresent, categoriesWithContents = categoriesWithContents, columnCount = amountOfColumns ) } private fun content( books: List<Book2>, category: BookOverviewCategory, currentBookId: Book2.Id?, amountOfColumns: Int ): BookOverviewCategoryContent? { val booksOfCategory = books.filter(category.filter).sortedWith(category.comparator) if (booksOfCategory.isEmpty()) { return null } val rows = when (category) { BookOverviewCategory.CURRENT -> 4 BookOverviewCategory.NOT_STARTED -> 4 BookOverviewCategory.FINISHED -> 2 } val models = booksOfCategory.take(rows * amountOfColumns).map { book -> BookOverviewViewState(book, amountOfColumns, currentBookId) } val hasMore = models.size != booksOfCategory.size return BookOverviewCategoryContent(models, hasMore) } fun playPause() { playerController.playPause() } }
lgpl-3.0
2fe3691f1cd76c9a8cc1bf27eadea79a
29.092857
99
0.726798
4.584331
false
false
false
false
Ph1b/MaterialAudiobookPlayer
playbackScreen/src/main/kotlin/voice/playbackScreen/BookPlayViewModel.kt
1
3647
package voice.playbackScreen import androidx.datastore.core.DataStore import de.ph1b.audiobook.common.pref.CurrentBook import de.ph1b.audiobook.data.Book2 import de.ph1b.audiobook.data.durationMs import de.ph1b.audiobook.data.markForPosition import de.ph1b.audiobook.data.repo.BookRepo2 import de.ph1b.audiobook.data.repo.BookmarkRepo import de.ph1b.audiobook.playback.PlayerController import de.ph1b.audiobook.playback.playstate.PlayStateManager import kotlinx.coroutines.MainScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import voice.sleepTimer.SleepTimer import javax.inject.Inject import kotlin.time.Duration.Companion.milliseconds class BookPlayViewModel @Inject constructor( private val repo: BookRepo2, private val player: PlayerController, private val sleepTimer: SleepTimer, private val playStateManager: PlayStateManager, private val bookmarkRepo: BookmarkRepo, @CurrentBook private val currentBookId: DataStore<Book2.Id?>, private val navigator: BookPlayNavigator ) { private val scope = MainScope() private val _viewEffects = MutableSharedFlow<BookPlayViewEffect>(extraBufferCapacity = 1) val viewEffects: Flow<BookPlayViewEffect> get() = _viewEffects lateinit var bookId: Book2.Id fun viewState(): Flow<BookPlayViewState> { scope.launch { currentBookId.updateData { bookId } } return combine( repo.flow(bookId).filterNotNull(), playStateManager.playStateFlow(), sleepTimer.leftSleepTimeFlow ) { book, playState, sleepTime -> val currentMark = book.currentChapter.markForPosition(book.content.positionInChapter) val hasMoreThanOneChapter = book.chapters.sumOf { it.chapterMarks.count() } > 1 BookPlayViewState( sleepTime = sleepTime, playing = playState == PlayStateManager.PlayState.Playing, title = book.content.name, showPreviousNextButtons = hasMoreThanOneChapter, chapterName = currentMark.name.takeIf { hasMoreThanOneChapter }, duration = currentMark.durationMs.milliseconds, playedTime = (book.content.positionInChapter - currentMark.startMs).milliseconds, cover = book.content.cover, skipSilence = book.content.skipSilence ) } } fun next() { player.next() } fun previous() { player.previous() } fun playPause() { player.playPause() } fun rewind() { player.rewind() } fun fastForward() { player.fastForward() } fun onSettingsClicked() { navigator.toSettings() } fun onCurrentChapterClicked() { navigator.toSelectChapters(bookId) } fun onPlaybackSpeedIconClicked() { navigator.toChangePlaybackSpeed() } fun onBookmarkClicked() { navigator.toBookmarkDialog(bookId) } fun seekTo(ms: Long) { scope.launch { val book = repo.flow(bookId).first() ?: return@launch val currentChapter = book.currentChapter val currentMark = currentChapter.markForPosition(book.content.positionInChapter) player.setPosition(currentMark.startMs + ms, currentChapter.id) } } fun toggleSleepTimer() { if (sleepTimer.sleepTimerActive()) { sleepTimer.setActive(false) } else { _viewEffects.tryEmit(BookPlayViewEffect.ShowSleepTimeDialog) } } fun toggleSkipSilence() { scope.launch { val book = repo.flow(bookId).first() ?: return@launch val skipSilence = book.content.skipSilence player.skipSilence(!skipSilence) } } }
lgpl-3.0
07f335cac00f08107c61d6605ea3e1ab
27.944444
103
0.737867
4.336504
false
false
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/lang/core/macros/MacroExpander.kt
1
2880
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.macros import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.RsElement import org.rust.lang.core.psi.ext.childrenOfType class MacroExpander(project: Project) { val psiFactory = RsPsiFactory(project) fun expandMacro(def: RsMacroDefinition, call: RsMacroCall): List<ExpansionResult>? { val case = def.macroDefinitionBodyStubbed ?.macroDefinitionCaseList ?.singleOrNull() ?: return null val patGroup = case.macroPattern.macroBindingGroupList.singleOrNull() ?: return null val patBinding = patGroup.macroBindingList.singleOrNull() ?: return null val name = patBinding.colon.prevSibling?.text val type = patBinding.colon.nextSibling?.text if (!(name != null && type != null && type == "item")) return null val expGroup = case.macroExpansion.macroExpansionReferenceGroupList.singleOrNull() ?: return null val expansionText = expGroup.textBetweenParens(expGroup.lparen, expGroup.rparen)?.toString() ?: return null val items = parseBodyAsItemList(call) ?: return null val newText = items.joinToString("\n\n") { item -> expansionText.replace("$" + name, item.text) } val expandedFile = psiFactory.createFile(newText) return expandedFile.childrenOfType() } private val RsMacroDefinition.macroDefinitionBodyStubbed: RsMacroDefinitionBody? get() { val stub = stub ?: return macroDefinitionBody val text = stub.macroBody ?: return null return CachedValuesManager.getCachedValue(this) { CachedValueProvider.Result.create( psiFactory.createMacroDefinitionBody(text), PsiModificationTracker.MODIFICATION_COUNT ) } } private fun parseBodyAsItemList(call: RsMacroCall): List<RsElement>? { val text = call.macroArgument?.braceListBodyText() ?: return null val file = psiFactory.createFile(text) as? RsFile ?: return null return file.childrenOfType() } } private fun PsiElement.braceListBodyText(): CharSequence? = textBetweenParens(firstChild, lastChild) private fun PsiElement.textBetweenParens(bra: PsiElement?, ket: PsiElement?): CharSequence? { if (bra == null || ket == null || bra == ket) return null return containingFile.text.subSequence( bra.textRange.endOffset + 1, ket.textRange.startOffset ) }
mit
e1d09252975a7df22698169fc6a98fb6
36.402597
115
0.678125
4.690554
false
false
false
false
kory33/SignVote
src/main/kotlin/com/github/kory33/signvote/constants/VotePointDataFileKeys.kt
1
473
package com.github.kory33.signvote.constants /** * Keys in json file which stores information about vote points * @author Kory */ object VotePointDataFileKeys { val NAME = "name" private val VOTE_SIGN = "votesign" val VOTE_SIGN_WORLD = VOTE_SIGN + ".world" private val VOTE_SIGN_LOC = VOTE_SIGN + ".location" val VOTE_SIGN_LOC_X = VOTE_SIGN_LOC + ".X" val VOTE_SIGN_LOC_Y = VOTE_SIGN_LOC + ".Y" val VOTE_SIGN_LOC_Z = VOTE_SIGN_LOC + ".Z" }
gpl-3.0
ce9f3fe1f7c78c8af785a3238204f38d
28.5625
63
0.657505
3.174497
false
false
false
false
googlemaps/android-samples
ApiDemos/kotlin/app/src/gms/java/com/example/kotlindemos/LiteDemoActivity.kt
1
5974
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.example.kotlindemos import android.graphics.Color import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import com.example.kotlindemos.OnMapAndViewReadyListener.OnGlobalLayoutAndMapReadyListener import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.* /** * This demo shows some features supported in lite mode. * In particular it demonstrates the use of [com.google.android.gms.maps.model.Marker]s to * launch the Google Maps Mobile application, [com.google.android.gms.maps.CameraUpdate]s * and [com.google.android.gms.maps.model.Polygon]s. */ class LiteDemoActivity : AppCompatActivity(), OnGlobalLayoutAndMapReadyListener { private lateinit var map: GoogleMap override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Set the layout setContentView(R.layout.lite_demo) // Get the map and register for the ready callback val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment OnMapAndViewReadyListener(mapFragment, this) } /** * Move the camera to center on Darwin. */ fun showDarwin(v: View?) { if (!::map.isInitialized) return // Center camera on Adelaide marker map.moveCamera(CameraUpdateFactory.newLatLngZoom(DARWIN, 10f)) } /** * Move the camera to center on Adelaide. */ fun showAdelaide(v: View?) { if (!::map.isInitialized) return // Center camera on Adelaide marker map.moveCamera(CameraUpdateFactory.newLatLngZoom(ADELAIDE, 10f)) } /** * Move the camera to show all of Australia. * Construct a [com.google.android.gms.maps.model.LatLngBounds] from markers positions, * then move the camera. */ fun showAustralia(v: View?) { if (!::map.isInitialized) return // Create bounds that include all locations of the map val boundsBuilder = LatLngBounds.builder() .include(PERTH) .include(ADELAIDE) .include(MELBOURNE) .include(SYDNEY) .include(DARWIN) .include(BRISBANE) // Move camera to show all markers and locations map.moveCamera(CameraUpdateFactory.newLatLngBounds(boundsBuilder.build(), 20)) } /** * Called when the map is ready to add all markers and objects to the map. */ override fun onMapReady(googleMap: GoogleMap?) { // return early if the map was not initialised properly map = googleMap ?: return addMarkers() addPolyObjects() showAustralia(null) } /** * Add a Polyline and a Polygon to the map. * The Polyline connects Melbourne, Adelaide and Perth. The Polygon is located in the Northern * Territory (Australia). */ private fun addPolyObjects() { map.addPolyline( PolylineOptions() .add( MELBOURNE, ADELAIDE, PERTH ) .color(Color.GREEN) .width(5f) ) map.addPolygon( PolygonOptions() .add(*POLYGON) .fillColor(Color.CYAN) .strokeColor(Color.BLUE) .strokeWidth(5f) ) } /** * Add Markers with default info windows to the map. */ private fun addMarkers() { map.addMarker( MarkerOptions() .position(BRISBANE) .title("Brisbane") ) map.addMarker( MarkerOptions() .position(MELBOURNE) .title("Melbourne") .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)) ) map.addMarker( MarkerOptions() .position(SYDNEY) .title("Sydney") .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)) ) map.addMarker( MarkerOptions() .position(ADELAIDE) .title("Adelaide") .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)) ) map.addMarker( MarkerOptions() .position(PERTH) .title("Perth") .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)) ) } companion object { private val BRISBANE = LatLng(-27.47093, 153.0235) private val MELBOURNE = LatLng(-37.81319, 144.96298) private val SYDNEY = LatLng(-33.87365, 151.20689) private val ADELAIDE = LatLng(-34.92873, 138.59995) private val PERTH = LatLng(-31.952854, 115.857342) private val DARWIN = LatLng(-12.459501, 130.839915) /** * A Polygon with five points in the Norther Territory, Australia. */ private val POLYGON = arrayOf( LatLng(-18.000328, 130.473633), LatLng(-16.173880, 135.087891), LatLng(-19.663970, 137.724609), LatLng(-23.202307, 135.395508), LatLng(-19.705347, 129.550781) ) } }
apache-2.0
1e9a0255372b32eaf1c222da39dbe221
33.33908
98
0.62387
4.584804
false
false
false
false
sephiroth74/Material-BottomNavigation
bottom-navigation/src/main/java/it/sephiroth/android/library/bottomnavigation/BadgeProvider.kt
1
1996
package it.sephiroth.android.library.bottomnavigation import android.graphics.drawable.Drawable import android.os.Bundle import androidx.annotation.IdRes import it.sephiroth.android.library.bottonnavigation.R import java.util.* /** * Created by alessandro crugnola on 4/12/16. * BadgeProvider * * The MIT License */ @Suppress("unused") open class BadgeProvider(private val navigation: BottomNavigation) { private val map = HashSet<Int>() private val badgeSize: Int = navigation.context.resources.getDimensionPixelSize(R.dimen.bbn_badge_size) fun save(): Bundle { val bundle = Bundle() bundle.putSerializable("map", map) return bundle } @Suppress("UNCHECKED_CAST") fun restore(bundle: Bundle) { val set = bundle.getSerializable("map") if (null != set && set is HashSet<*>) { map.addAll(set as HashSet<Int>) } } /** * Returns if the menu item will require a badge * * @param itemId the menu item id * @return true if the menu item has to draw a badge */ fun hasBadge(@IdRes itemId: Int): Boolean { return map.contains(itemId) } internal fun getBadge(@IdRes itemId: Int): Drawable? { return if (map.contains(itemId)) { newDrawable(itemId, navigation.menu!!.badgeColor) } else null } protected open fun newDrawable(@IdRes itemId: Int, preferredColor: Int): Drawable { return BadgeDrawable(preferredColor, badgeSize) } /** * Request to display a new badge over the passed menu item id * * @param itemId the menu item id */ fun show(@IdRes itemId: Int) { map.add(itemId) navigation.invalidateBadge(itemId) } /** * Remove the currently displayed badge * * @param itemId the menu item id */ open fun remove(@IdRes itemId: Int) { if (map.remove(itemId)) { navigation.invalidateBadge(itemId) } } }
mit
999b902c43d028dc505f57e043e6693a
25.613333
107
0.635271
4.219873
false
false
false
false
chrisbanes/tivi
data/src/main/java/app/tivi/data/mappers/TraktSeasonToSeason.kt
1
1334
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.data.mappers import app.tivi.data.entities.Season import javax.inject.Inject import javax.inject.Singleton import com.uwetrottmann.trakt5.entities.Season as TraktSeason @Singleton class TraktSeasonToSeason @Inject constructor() : Mapper<TraktSeason, Season> { override suspend fun map(from: TraktSeason) = Season( showId = 0, traktId = from.ids?.trakt, tmdbId = from.ids?.tmdb, number = from.number, title = from.title, summary = from.overview, traktRating = from.rating?.toFloat() ?: 0f, traktRatingVotes = from.votes ?: 0, episodeCount = from.episode_count, episodesAired = from.aired_episodes, network = from.network ) }
apache-2.0
8b4a7e0602e8051f9f50f0b29034152e
33.205128
79
0.701649
4.079511
false
false
false
false
quarkusio/quarkus
devtools/project-core-extension-codestarts/src/main/resources/codestarts/quarkus/extension-codestarts/picocli-codestart/kotlin/src/main/kotlin/org/acme/GreetingCommand.kt
1
436
package org.acme import picocli.CommandLine import picocli.CommandLine.Command import picocli.CommandLine.Parameters @Command(name = "greeting", mixinStandardHelpOptions = true) class GreetingCommand : Runnable { @Parameters(paramLabel = "<name>", defaultValue = "picocli", description = ["Your name."]) var name: String? = null override fun run() { System.out.printf("Hello %s, go go commando!\n", name) } }
apache-2.0
d7757c96b2c25e50f4c0874ac7965844
26.3125
94
0.708716
4.074766
false
false
false
false
drimachine/grakmat
src/main/kotlin/org/drimachine/grakmat/SpacedCombinators.kt
1
5967
/* * Copyright (c) 2016 Drimachine.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("SpacedCombinators") package org.drimachine.grakmat import java.util.* var SPACE: Parser<Char> = anyOf(' ', '\t', '\r', '\n') withName "SPACE" val SPACES: Parser<String> = oneOrMore(SPACE) .map { spaces: List<Char> -> spaces.joinToString("") } .withName("SPACES") val OPTIONAL_SPACES: Parser<String> = zeroOrMore(SPACE) .map { spaces: List<Char> -> spaces.joinToString("") } .withName("OPTIONAL SPACES") /** * Works like [and], but inserts spaces between parsers. */ infix fun <A, B> Parser<A>._and_(other: Parser<B>): Parser<Pair<A, B>> = SpacedAndParser(this, other) /** * Works like [_and_], but returns only second result. */ infix fun <A, B> Parser<A>._then_(other: Parser<B>): Parser<B> = this _and_ other map { it.second } /** * Works like [_and_], but returns only first result. */ infix fun <A, B> Parser<A>._before_(other: Parser<B>): Parser<A> = this _and_ other map { it.first } /** * @see _and_ */ class SpacedAndParser<out A, out B>(val leftParser: Parser<A>, val rightParser: Parser<B>) : Parser<Pair<A, B>> { override val expectedDescription: String get() = "${leftParser.expectedDescription} and ${rightParser.expectedDescription}" override fun eat(source: Source, input: String): Result<Pair<A, B>> { val leftResult: Result<A> = leftParser.eat(source, input) val middleResult: Result<String> = OPTIONAL_SPACES.eat(source, leftResult.remainder) val rightResult: Result<B> = rightParser.eat(source, middleResult.remainder) return Result(leftResult.value to rightResult.value, rightResult.remainder) } override fun toString(): String = expectedDescription } /** * Works like [repeat], but inserts spaces between results. */ infix fun <A> Parser<A>._repeat_(times: Int): Parser<List<A>> = SpacedRepeatParser(this, times) /** * @see _repeat_ */ class SpacedRepeatParser<out A>(val target: Parser<A>, val times: Int) : Parser<List<A>> { override val expectedDescription: String get() = "${target.expectedDescription} exactly $times times" override fun eat(source: Source, input: String): Result<List<A>> { val list = ArrayList<A>() var remainder = input // (1..times) - repeat folding 'times' times for (time in 1..times) { val next: Result<A> = target.eat(source, remainder) list.add(next.value) val spacesResult: Result<String> = OPTIONAL_SPACES.eat(source, next.remainder) remainder = spacesResult.value } return Result(Collections.unmodifiableList(list), remainder) } override fun toString(): String = expectedDescription } /** * Works like [atLeast], but inserts spaces between results. */ infix fun <A> Parser<A>._atLeast_(times: Int): Parser<List<A>> = SpacedAtLeastParser(this, times) /** * Alias to `atLeast(0, xxx)`. * * @see atLeast */ fun <A> _zeroOrMore_(target: Parser<A>): Parser<List<A>> = target _atLeast_ 0 /** * Alias to `atLeast(1, xxx)`. * * @see atLeast */ fun <A> _oneOrMore_(target: Parser<A>): Parser<List<A>> = target _atLeast_ 1 /** * @see _atLeast_ */ class SpacedAtLeastParser<out A>(val target: Parser<A>, val times: Int) : Parser<List<A>> { override val expectedDescription: String get() = "${target.expectedDescription} at least $times times" override fun eat(source: Source, input: String): Result<List<A>> { var (list: List<A>, remainder: String) = target.repeat(times).eat(source, input) list = ArrayList<A>(list) do { val (next: A?, nextRemainder: String) = optional(target).eat(source, remainder) if (next != null) { list.add(next) val spacesResult: Result<String> = OPTIONAL_SPACES.eat(source, nextRemainder) remainder = spacesResult.remainder } else { remainder = nextRemainder } } while (next != null) return Result(Collections.unmodifiableList(list), remainder) } override fun toString(): String = expectedDescription } /** * Works like [inRange], but inserts spaces between results. */ infix fun <A> Parser<A>._inRange_(bounds: IntRange) : Parser<List<A>> = SpacedRangedParser(this, bounds) /** * @see _inRange_ */ class SpacedRangedParser<out A>(val target: Parser<A>, val bounds: IntRange) : Parser<List<A>> { override val expectedDescription: String get() = "${target.expectedDescription}{${bounds.start},${bounds.endInclusive}}" override fun eat(source: Source, input: String): Result<List<A>> { var (list, remainder) = target.repeat(bounds.start).eat(source, input) list = ArrayList<A>(list) do { val (next: A?, nextRemainder: String) = optional(target).eat(source, remainder) if (next != null) { list.add(next) remainder = nextRemainder } else { val spacesResult: Result<String> = OPTIONAL_SPACES.eat(source, nextRemainder) remainder = spacesResult.remainder } } while (next != null && list.size < bounds.endInclusive) return Result(Collections.unmodifiableList(list), remainder) } override fun toString(): String = expectedDescription }
apache-2.0
ee7ef3a7b7b77dce883f5ef9fdc151d3
33.097143
113
0.64002
3.905105
false
false
false
false