repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
jitsi/jitsi-videobridge
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/rtcp/KeyframeRequester.kt
1
9121
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.nlj.rtcp import org.jitsi.nlj.Event import org.jitsi.nlj.PacketInfo import org.jitsi.nlj.SetLocalSsrcEvent import org.jitsi.nlj.stats.NodeStatsBlock import org.jitsi.nlj.transform.node.TransformerNode import org.jitsi.nlj.util.NEVER import org.jitsi.nlj.util.ReadOnlyStreamInformationStore import org.jitsi.rtp.rtcp.rtcpfb.RtcpFbPacket import org.jitsi.rtp.rtcp.rtcpfb.payload_specific_fb.RtcpFbFirPacket import org.jitsi.rtp.rtcp.rtcpfb.payload_specific_fb.RtcpFbFirPacketBuilder import org.jitsi.rtp.rtcp.rtcpfb.payload_specific_fb.RtcpFbPliPacket import org.jitsi.rtp.rtcp.rtcpfb.payload_specific_fb.RtcpFbPliPacketBuilder import org.jitsi.utils.MediaType import org.jitsi.utils.logging2.Logger import org.jitsi.utils.logging2.cdebug import org.jitsi.utils.logging2.createChildLogger import java.time.Clock import java.time.Duration import java.time.Instant import java.util.concurrent.atomic.AtomicInteger import kotlin.math.min /** * [KeyframeRequester] handles a few things around keyframes: * 1) The bridge requesting a keyframe (e.g. in order to switch) via the [KeyframeRequester#requestKeyframe] * method which will create a new keyframe request and forward it * 2) PLI/FIR translation. If a PLI or FIR packet is forwarded through here, this class may translate it depending * on what the client supports * 3) Aggregation. This class will pace outgoing requests such that we don't spam the sender */ class KeyframeRequester @JvmOverloads constructor( private val streamInformationStore: ReadOnlyStreamInformationStore, parentLogger: Logger, private val clock: Clock = Clock.systemDefaultZone() ) : TransformerNode("Keyframe Requester") { private val logger = createChildLogger(parentLogger) // Map a SSRC to the timestamp (represented as an [Instant]) of when we last requested a keyframe for it private val keyframeRequests = mutableMapOf<Long, Instant>() private val firCommandSequenceNumber: AtomicInteger = AtomicInteger(0) private val keyframeRequestsSyncRoot = Any() private var localSsrc: Long? = null private var waitInterval = DEFAULT_WAIT_INTERVAL // Stats // Number of PLI/FIRs received and forwarded to the endpoint. private var numPlisForwarded: Int = 0 private var numFirsForwarded: Int = 0 // Number of PLI/FIRs received but dropped due to throttling. private var numPlisDropped: Int = 0 private var numFirsDropped: Int = 0 // Number of PLI/FIRs generated as a result of an API request or due to translation between PLI/FIR. private var numPlisGenerated: Int = 0 private var numFirsGenerated: Int = 0 // Number of calls to requestKeyframe private var numApiRequests: Int = 0 // Number of calls to requestKeyframe ignored due to throttling private var numApiRequestsDropped: Int = 0 override fun transform(packetInfo: PacketInfo): PacketInfo? { val pliOrFirPacket = packetInfo.getPliOrFirPacket() ?: return packetInfo val now = clock.instant() val sourceSsrc: Long val canSend: Boolean val forward: Boolean when (pliOrFirPacket) { is RtcpFbPliPacket -> { sourceSsrc = pliOrFirPacket.mediaSourceSsrc canSend = canSendKeyframeRequest(sourceSsrc, now) forward = canSend && streamInformationStore.supportsPli if (forward) numPlisForwarded++ if (!canSend) numPlisDropped++ } is RtcpFbFirPacket -> { sourceSsrc = pliOrFirPacket.mediaSenderSsrc canSend = canSendKeyframeRequest(sourceSsrc, now) // When both are supported, we favor generating a PLI rather than forwarding a FIR forward = canSend && streamInformationStore.supportsFir && !streamInformationStore.supportsPli if (forward) { // When we forward a FIR we need to update the seq num. pliOrFirPacket.seqNum = firCommandSequenceNumber.incrementAndGet() // We manage the seq num space, so we should use the same SSRC localSsrc?.let { pliOrFirPacket.mediaSenderSsrc = it } numFirsForwarded++ } if (!canSend) numFirsDropped++ } // This is not possible, but the compiler doesn't know it. else -> throw IllegalStateException("Packet is neither PLI nor FIR") } if (!forward && canSend) { doRequestKeyframe(sourceSsrc) } return if (forward) packetInfo else null } /** * Returns 'true' when at least one method is supported, AND we haven't sent a request very recently. */ private fun canSendKeyframeRequest(mediaSsrc: Long, now: Instant): Boolean { if (!streamInformationStore.supportsPli && !streamInformationStore.supportsFir) { return false } synchronized(keyframeRequestsSyncRoot) { return if (Duration.between(keyframeRequests.getOrDefault(mediaSsrc, NEVER), now) < waitInterval) { logger.cdebug { "Sent a keyframe request less than $waitInterval ago for $mediaSsrc, ignoring request" } false } else { keyframeRequests[mediaSsrc] = now logger.cdebug { "Keyframe requester requesting keyframe for $mediaSsrc" } true } } } fun requestKeyframe(mediaSsrc: Long? = null) { val ssrc = mediaSsrc ?: streamInformationStore.primaryMediaSsrcs.firstOrNull() ?: run { numApiRequestsDropped++ logger.cdebug { "No video SSRC found to request keyframe" } return } numApiRequests++ if (!canSendKeyframeRequest(ssrc, clock.instant())) { numApiRequestsDropped++ return } doRequestKeyframe(ssrc) } private fun doRequestKeyframe(mediaSsrc: Long) { val pkt = when { streamInformationStore.supportsPli -> { numPlisGenerated++ RtcpFbPliPacketBuilder(mediaSourceSsrc = mediaSsrc).build() } streamInformationStore.supportsFir -> { numFirsGenerated++ RtcpFbFirPacketBuilder( mediaSenderSsrc = mediaSsrc, firCommandSeqNum = firCommandSequenceNumber.incrementAndGet() ).build() } else -> { logger.warn("Can not send neither PLI nor FIR") return } } next(PacketInfo(pkt)) } override fun handleEvent(event: Event) { when (event) { is SetLocalSsrcEvent -> { if (event.mediaType == MediaType.VIDEO) { localSsrc = event.ssrc } } } } override fun trace(f: () -> Unit) = f.invoke() override fun getNodeStats(): NodeStatsBlock { return super.getNodeStats().apply { addNumber("wait_interval_ms", waitInterval.toMillis()) addNumber("num_api_requests", numApiRequests) addNumber("num_api_requests_dropped", numApiRequestsDropped) addNumber("num_firs_dropped", numFirsDropped) addNumber("num_firs_generated", numFirsGenerated) addNumber("num_firs_forwarded", numFirsForwarded) addNumber("num_plis_dropped", numPlisDropped) addNumber("num_plis_generated", numPlisGenerated) addNumber("num_plis_forwarded", numPlisForwarded) } } fun onRttUpdate(newRtt: Double) { // avg(rtt) + stddev(rtt) would be more accurate than rtt + 10. waitInterval = Duration.ofMillis(min(DEFAULT_WAIT_INTERVAL.toMillis(), newRtt.toLong() + 10)) } companion object { private val DEFAULT_WAIT_INTERVAL = Duration.ofMillis(100) } } private fun PacketInfo.getPliOrFirPacket(): RtcpFbPacket? { return when (val pkt = packet) { // We intentionally ignore compound RTCP packets in order to avoid unnecessary parsing. We can do this because: // 1. Compound packets coming from remote endpoint are terminated in RtcpTermination // 2. Whenever a PLI or FIR is generated in our code, it is not part of a compound packet. is RtcpFbFirPacket -> pkt is RtcpFbPliPacket -> pkt else -> null } }
apache-2.0
568c9ce6503890df4f67394630c556f5
40.085586
119
0.656288
4.444932
false
false
false
false
PizzaGames/emulio
core/src/main/com/github/emulio/model/theme/TextList.kt
1
605
package com.github.emulio.model.theme class TextList : Text { constructor() constructor(copy: Text) : super(copy) constructor(copy: TextList) { selectorColor = copy.selectorColor selectedColor = copy.selectedColor primaryColor = copy.primaryColor secondaryColor = copy.secondaryColor text = copy.text forceUpperCase = copy.forceUpperCase color = copy.color fontPath = copy.fontPath fontSize = copy.fontSize alignment = copy.alignment } var selectorColor: String? = null var selectedColor: String? = null var primaryColor: String? = null var secondaryColor: String? = null }
gpl-3.0
b797fdb3123936f18b5ef9f48e36da99
23.24
38
0.752066
3.757764
false
false
false
false
edsilfer/presence-control
app/src/main/java/br/com/edsilfer/android/presence_control/commons/layout/searchbar/domain/entity/SearchResult.kt
1
484
package br.com.edsilfer.android.presence_control.commons.layout.searchbar.domain.entity import com.google.android.gms.maps.model.LatLng /** * Created by ferna on 5/21/2017. */ data class SearchResult( val header: String = "", val subheader: String = "", val distance: String = "", val latitude: Double = 0.toDouble(), val longitude: Double = 0.toDouble() ) { fun getLatLng () : LatLng{ return LatLng(latitude, longitude) } }
apache-2.0
e6795847ffd0ab2d92e87d5a5a03b048
25.944444
87
0.640496
3.811024
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/features/heat_machines/TileEntities.kt
2
9343
package com.cout970.magneticraft.features.heat_machines import com.cout970.magneticraft.Debug import com.cout970.magneticraft.api.internal.energy.ElectricNode import com.cout970.magneticraft.api.internal.heat.HeatNode import com.cout970.magneticraft.features.electric_machines.Blocks import com.cout970.magneticraft.misc.RegisterTileEntity import com.cout970.magneticraft.misc.STANDARD_AMBIENT_TEMPERATURE import com.cout970.magneticraft.misc.block.getFacing import com.cout970.magneticraft.misc.block.getOrientation import com.cout970.magneticraft.misc.block.getOrientationActive import com.cout970.magneticraft.misc.crafting.FurnaceCraftingProcess import com.cout970.magneticraft.misc.crafting.GasificationCraftingProcess import com.cout970.magneticraft.misc.energy.RfNodeWrapper import com.cout970.magneticraft.misc.energy.RfStorage import com.cout970.magneticraft.misc.fluid.Tank import com.cout970.magneticraft.misc.fromCelsiusToKelvin import com.cout970.magneticraft.misc.inventory.Inventory import com.cout970.magneticraft.misc.inventory.InventoryCapabilityFilter import com.cout970.magneticraft.misc.tileentity.DoNotRemove import com.cout970.magneticraft.misc.world.isServer import com.cout970.magneticraft.systems.blocks.CommonMethods import com.cout970.magneticraft.systems.config.Config import com.cout970.magneticraft.systems.tileentities.TileBase import com.cout970.magneticraft.systems.tilemodules.* import net.minecraft.block.state.IBlockState import net.minecraft.util.EnumFacing import net.minecraft.util.ITickable import net.minecraft.util.math.BlockPos import net.minecraft.world.World /** * Created by cout970 on 2017/08/10. */ @RegisterTileEntity("combustion_chamber") class TileCombustionChamber : TileBase(), ITickable { val facing: EnumFacing get() = getBlockState().getOrientation() val inventory = Inventory(1) val node = HeatNode(ref) val heatModule = ModuleHeat(node, capabilityFilter = { it == EnumFacing.UP }) val invModule = ModuleInventory(inventory) val combustionChamberModule = ModuleCombustionChamber(node, inventory) init { initModules(invModule, combustionChamberModule, heatModule) } @DoNotRemove override fun update() { super.update() } } @RegisterTileEntity("steam_boiler") class TileSteamBoiler : TileBase(), ITickable { val node = HeatNode(ref) val heatModule = ModuleHeat(node) val waterTank = Tank( capacity = 1000, allowInput = true, allowOutput = false, fluidFilter = { it.fluid.name == "water" } ).apply { clientFluidName = "water" } val steamTank = Tank( capacity = 16000, allowInput = false, allowOutput = true, fluidFilter = { it.fluid.name == "steam" } ).apply { clientFluidName = "steam" } val fluidModule = ModuleFluidHandler(waterTank, steamTank) val boilerModule = ModuleSteamBoiler(node, waterTank, steamTank, Config.boilerMaxProduction) val fluidExportModule = ModuleFluidExporter(steamTank, { listOf(BlockPos(0, 1, 0) to EnumFacing.DOWN) }) val openGui = ModuleOpenGui() init { initModules(fluidModule, boilerModule, fluidExportModule, openGui, heatModule) } @DoNotRemove override fun update() { super.update() } } @RegisterTileEntity("heat_pipe") class TileHeatPipe : TileBase(), ITickable { val heatNode = HeatNode(ref) val heatModule = ModuleHeat(heatNode) val heatPipeConnections = ModuleHeatPipeConnections(heatModule) init { initModules(heatModule, heatPipeConnections) } @DoNotRemove override fun update() { super.update() if (Debug.DEBUG) { sendUpdateToNearPlayers() } } } @RegisterTileEntity("insulated_heat_pipe") class TileInsulatedHeatPipe : TileBase(), ITickable { val heatNode = HeatNode(ref) val heatModule = ModuleHeat(heatNode) val heatPipeConnections = ModuleHeatPipeConnections(heatModule) init { initModules(heatModule, heatPipeConnections) } @DoNotRemove override fun update() { super.update() if (Debug.DEBUG) { sendUpdateToNearPlayers() } } } @RegisterTileEntity("heat_sink") class TileHeatSink : TileBase(), ITickable { val facing: EnumFacing get() = getBlockState().getFacing() val heatNode = HeatNode(ref) val heatModule = ModuleHeat(heatNode, capabilityFilter = { it != facing.opposite }) init { initModules(heatModule) } @DoNotRemove override fun update() { super.update() // Dissipate heat if (world.isServer && heatNode.temperature > STANDARD_AMBIENT_TEMPERATURE) { val diff = heatNode.temperature - STANDARD_AMBIENT_TEMPERATURE heatNode.applyHeat(-diff) } } } @RegisterTileEntity("electric_heater") class TileElectricHeater : TileBase(), ITickable { val electricNode = ElectricNode(ref) val heatNode = HeatNode(ref) val electricModule = ModuleElectricity(listOf(electricNode)) val moduleHeat = ModuleHeat(heatNode, capabilityFilter = { it?.axis == EnumFacing.Axis.Y }) val storageModule = ModuleInternalStorage( initialCapacity = 10_000, mainNode = electricNode ) val electricHeaterModule = ModuleElectricHeater(heatNode, storageModule) val updateBlockstate = ModuleUpdateBlockstate { currentState -> if (heatNode.temperature > 90.fromCelsiusToKelvin()) currentState.withProperty(Blocks.PROPERTY_WORKING_MODE, Blocks.WorkingMode.ON) else currentState.withProperty(Blocks.PROPERTY_WORKING_MODE, Blocks.WorkingMode.OFF) } init { initModules(electricModule, storageModule, electricHeaterModule, updateBlockstate, moduleHeat) } override fun shouldRefresh(world: World?, pos: BlockPos?, oldState: IBlockState, newSate: IBlockState): Boolean { return oldState.block !== newSate.block } @DoNotRemove override fun update() { super.update() } } @RegisterTileEntity("rf_heater") class TileRfHeater : TileBase(), ITickable { val storage = RfStorage(80_000) val node = HeatNode(ref) val rfModule = ModuleRf(storage) val heatModule = ModuleHeat(node, capabilityFilter = { it?.axis == EnumFacing.Axis.Y }) val electricHeaterModule = ModuleElectricHeater(node, RfNodeWrapper(storage)) val updateBlockstate = ModuleUpdateBlockstate { currentState -> if (node.temperature > 90.fromCelsiusToKelvin()) currentState.withProperty(Blocks.PROPERTY_WORKING_MODE, Blocks.WorkingMode.ON) else currentState.withProperty(Blocks.PROPERTY_WORKING_MODE, Blocks.WorkingMode.OFF) } init { initModules(electricHeaterModule, rfModule, updateBlockstate, heatModule) } override fun shouldRefresh(world: World?, pos: BlockPos?, oldState: IBlockState, newSate: IBlockState): Boolean { return oldState.block !== newSate.block } @DoNotRemove override fun update() { super.update() } } @RegisterTileEntity("gasification_unit") class TileGasificationUnit : TileBase(), ITickable { val tank = Tank(4_000) val heatNode = HeatNode(ref) val inv = Inventory(2) val fluidModule = ModuleFluidHandler(tank) val heatModule = ModuleHeat(heatNode) val inventoryModule = ModuleInventory(inv, capabilityFilter = { InventoryCapabilityFilter(it, listOf(0), listOf(1)) }) val exporter = ModuleFluidExporter(tank, { listOf(BlockPos(0, 1, 0) to EnumFacing.UP) }) val bucketModule = ModuleBucketIO(tank, input = false, output = true) val openGui = ModuleOpenGui() val process = ModuleHeatProcessing( craftingProcess = GasificationCraftingProcess(tank, inv, 0, 1), node = heatNode, costPerTick = Config.gasificationUnitConsumption.toFloat(), workingRate = 1f ) init { initModules(heatModule, fluidModule, exporter, bucketModule, process, inventoryModule, openGui) } @DoNotRemove override fun update() { super.update() } } @RegisterTileEntity("brick_furnace") class TileBrickFurnace : TileBase(), ITickable { val facing: EnumFacing get() = getBlockState().getOrientationActive() val node = HeatNode(ref) val heatModule = ModuleHeat(node) val invModule = ModuleInventory(Inventory(2), capabilityFilter = { InventoryCapabilityFilter(it, inputSlots = listOf(0), outputSlots = listOf(1)) }) val updateBlockModule = ModuleUpdateBlockstate { oldState -> val state = CommonMethods.OrientationActive.of(facing, processModule.working) oldState.withProperty(CommonMethods.PROPERTY_ORIENTATION_ACTIVE, state) } val processModule = ModuleHeatProcessing( craftingProcess = FurnaceCraftingProcess(invModule, 0, 1), node = node, workingRate = 1f, costPerTick = Config.electricFurnaceMaxConsumption.toFloat() ) init { initModules(heatModule, invModule, processModule, updateBlockModule) } @DoNotRemove override fun update() { super.update() } override fun shouldRefresh(world: World, pos: BlockPos, oldState: IBlockState, newSate: IBlockState): Boolean { return oldState.block != newSate.block } }
gpl-2.0
f8a69f752e937c30e50f034acc61b207
30.355705
122
0.713154
4.165403
false
false
false
false
andrei-heidelbacher/algostorm
algostorm-core/src/test/kotlin/com/andreihh/algostorm/core/ecs/IdTest.kt
1
1308
/* * Copyright 2017 Andrei Heidelbacher <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andreihh.algostorm.core.ecs import org.junit.Test import kotlin.test.assertEquals class IdTest { @Test(expected = IllegalArgumentException::class) fun testZeroIdShouldThrow() { EntityRef.Id(0) } @Test(expected = IllegalArgumentException::class) fun testNegativeIdShouldThrow() { EntityRef.Id(-138) } @Test fun testPositiveIdShouldEqualGivenValue() { val value = 198 val id = EntityRef.Id(value) assertEquals(value, id.value) } @Test fun testToStringReturnsValueString() { val value = 198 val id = EntityRef.Id(value) assertEquals("$value", "$id") } }
apache-2.0
a32b41da8f4298485c019fb9e70c1af7
28.727273
75
0.695719
4.165605
false
true
false
false
yschimke/oksocial
src/main/kotlin/com/baulsupp/okurl/services/google/firebase/FirebaseCompleter.kt
1
3327
package com.baulsupp.okurl.services.google.firebase import com.baulsupp.okurl.completion.ApiCompleter import com.baulsupp.okurl.completion.DirCompletionVariableCache import com.baulsupp.okurl.completion.HostUrlCompleter import com.baulsupp.okurl.completion.UrlList import com.baulsupp.okurl.credentials.Token import com.baulsupp.okurl.kotlin.queryOptionalMap import com.baulsupp.okurl.kotlin.request import com.baulsupp.okurl.util.FileUtil import okhttp3.HttpUrl import okhttp3.OkHttpClient import java.util.logging.Logger class FirebaseCompleter(private val client: OkHttpClient) : ApiCompleter { override suspend fun prefixUrls(): UrlList = UrlList(UrlList.Match.HOSTS, HostUrlCompleter.hostUrls(hosts(), false)) override suspend fun siteUrls(url: HttpUrl, tokenSet: Token): UrlList { val results = siblings(url, tokenSet) + children(url, tokenSet) val candidates = results.map { url.newBuilder().encodedPath(it).build().toString() } logger.fine("candidates $candidates") return UrlList(UrlList.Match.EXACT, dedup(candidates + thisNode(url))) } private fun dedup(candidates: List<String>) = candidates.toSortedSet().toList() fun thisNode(url: HttpUrl): List<String> { val path = url.encodedPath return if (path.endsWith("/")) { listOf("$url.json") } else if (path.endsWith(".json") || url.querySize > 0) { listOf(url.toString()) } else if (path.contains('.')) { listOf(url.toString().replaceAfterLast(".", "json")) } else { listOf() } } suspend fun siblings(url: HttpUrl, tokenSet: Token): List<String> { return if (url.encodedPath == "/" || url.querySize > 1 || url.encodedPath.contains(".")) { listOf() } else { val parentPath = url.encodedPath.replaceAfterLast("/", "") val encodedPath = url.newBuilder().encodedPath("$parentPath.json") val siblings = keyList(encodedPath, tokenSet) siblings.toList().flatMap { listOf("$parentPath$it", "$parentPath$it.json") } } } suspend fun keyList(encodedPath: HttpUrl.Builder, tokenSet: Token): List<String> { val request = request(tokenSet = tokenSet) { encodedPath.addQueryParameter("shallow", "true").build() } return client.queryOptionalMap<Any>(request)?.keys?.toList().orEmpty() } suspend fun children(url: HttpUrl, tokenSet: Token): List<String> { return if (url.querySize > 1 || url.encodedPath.contains(".")) { listOf() } else { val path = url.encodedPath val encodedPath = url.newBuilder().encodedPath("$path.json") val children = keyList(encodedPath, tokenSet) val prefixPath = if (path.endsWith("/")) path else "$path/" children.toList().flatMap { listOf("$prefixPath$it/", "$prefixPath$it.json") } } } fun hosts(): List<String> = knownHosts() companion object { private val logger = Logger.getLogger(FirebaseCompleter::class.java.name) val firebaseCache = DirCompletionVariableCache(FileUtil.okurlSettingsDir) fun knownHosts(): List<String> = firebaseCache["firebase", "hosts"].orEmpty() fun registerKnownHost(host: String) { val previous = firebaseCache["firebase", "hosts"] if (previous == null || !previous.contains(host)) { firebaseCache["firebase", "hosts"] = listOf(host) + (previous ?: listOf()) } } } }
apache-2.0
ab56dd1beb4cb6f7661c34573fd3a8f6
34.774194
118
0.694019
4.13806
false
false
false
false
mozilla-mobile/focus-android
app/src/main/java/org/mozilla/focus/session/IntentProcessor.kt
1
7481
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.session import android.content.Context import android.content.Intent import android.os.Bundle import android.text.TextUtils import mozilla.components.browser.state.state.SessionState import mozilla.components.feature.customtabs.createCustomTabConfigFromIntent import mozilla.components.feature.customtabs.isCustomTabIntent import mozilla.components.feature.tabs.CustomTabsUseCases import mozilla.components.feature.tabs.TabsUseCases import mozilla.components.support.utils.SafeIntent import mozilla.components.support.utils.WebURLFinder import org.mozilla.focus.activity.TextActionActivity import org.mozilla.focus.ext.components import org.mozilla.focus.shortcut.HomeScreen import org.mozilla.focus.utils.SearchUtils import org.mozilla.focus.utils.UrlUtils /** * Implementation moved from Focus SessionManager. To be replaced with SessionIntentProcessor from feature-session * component soon. */ class IntentProcessor( private val context: Context, private val tabsUseCases: TabsUseCases, private val customTabsUseCases: CustomTabsUseCases, ) { sealed class Result { object None : Result() data class Tab(val id: String) : Result() data class CustomTab(val id: String) : Result() } /** * Handle this incoming intent (via onCreate()) and create a new session if required. */ fun handleIntent(context: Context, intent: SafeIntent, savedInstanceState: Bundle?): Result { if ((intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) { // This Intent was launched from history (recent apps). Android will redeliver the // original Intent (which might be a VIEW intent). However if there's no active browsing // session then we do not want to re-process the Intent and potentially re-open a website // from a session that the user already "erased". return Result.None } if (savedInstanceState != null) { // We are restoring a previous session - No need to handle this Intent. return Result.None } return createSessionFromIntent(context, intent) } /** * Handle this incoming intent (via onNewIntent()) and create a new session if required. */ fun handleNewIntent(context: Context, intent: SafeIntent) { createSessionFromIntent(context, intent) } @Suppress("ComplexMethod", "ReturnCount") private fun createSessionFromIntent(context: Context, intent: SafeIntent): Result { when (intent.action) { Intent.ACTION_VIEW -> { val dataString = intent.dataString if (TextUtils.isEmpty(dataString)) { // If there's no URL in the Intent then we can't create a session. return Result.None } return when { intent.hasExtra(HomeScreen.ADD_TO_HOMESCREEN_TAG) -> { val requestDesktop = intent.getBooleanExtra(HomeScreen.REQUEST_DESKTOP, false) // Ignoring, because exception! // HomeScreen.BLOCKING_ENABLED createSession( SessionState.Source.Internal.HomeScreen, intent, intent.dataString ?: "", requestDesktop, ) } intent.hasExtra(TextActionActivity.EXTRA_TEXT_SELECTION) -> createSession( SessionState.Source.Internal.TextSelection, intent, intent.dataString ?: "", ) else -> createSession( SessionState.Source.External.ActionView(null), intent, intent.dataString ?: "", ) } } Intent.ACTION_SEND -> { val dataString = intent.getStringExtra(Intent.EXTRA_TEXT) if (TextUtils.isEmpty(dataString)) { return Result.None } return if (!UrlUtils.isUrl(dataString)) { val bestURL = WebURLFinder(dataString).bestWebURL() if (!TextUtils.isEmpty(bestURL)) { createSession(SessionState.Source.External.ActionSend(null), bestURL ?: "") } else { createSearchSession( SessionState.Source.External.ActionSend(null), SearchUtils.createSearchUrl(context, dataString ?: ""), dataString ?: "", ) } } else { createSession(SessionState.Source.External.ActionSend(null), dataString ?: "") } } else -> return Result.None } } private fun createSession(source: SessionState.Source, url: String): Result { return Result.Tab( tabsUseCases.addTab( url, source = source, selectTab = true, private = true, ), ) } private fun createSearchSession(source: SessionState.Source, url: String, searchTerms: String): Result { return Result.Tab( tabsUseCases.addTab( url, source = source, searchTerms = searchTerms, private = true, ), ) } private fun createSession(source: SessionState.Source, intent: SafeIntent, url: String): Result { return if (isCustomTabIntent(intent.unsafe)) { Result.CustomTab( customTabsUseCases.add( url, createCustomTabConfigFromIntent(intent.unsafe, context.resources), private = true, source = source, ), ) } else { Result.Tab( tabsUseCases.addTab( url, source = source, selectTab = true, private = true, ), ) } } private fun createSession( source: SessionState.Source, intent: SafeIntent, url: String, requestDesktop: Boolean, ): Result { val (result, tabId) = if (isCustomTabIntent(intent)) { val tabId = customTabsUseCases.add( url, createCustomTabConfigFromIntent(intent.unsafe, context.resources), private = true, source = source, ) Pair(Result.CustomTab(tabId), tabId) } else { val tabId = tabsUseCases.addTab( url, source = source, private = true, ) Pair(Result.Tab(tabId), tabId) } if (requestDesktop) { context.components.sessionUseCases.requestDesktopSite(requestDesktop, tabId) } return result } }
mpl-2.0
e9ba0099add6c5bbcf0cfdf9ababaff3
35.852217
114
0.554204
5.339757
false
false
false
false
wireapp/wire-android
app/src/test/kotlin/com/waz/zclient/feature/backup/keyvalues/KeyValuesBackUpMapperTest.kt
1
1348
package com.waz.zclient.feature.backup.keyvalues import com.waz.zclient.UnitTest import com.waz.zclient.framework.data.property.KeyValueTestDataProvider import com.waz.zclient.storage.db.property.KeyValuesEntity import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test class KeyValuesBackUpMapperTest : UnitTest() { private lateinit var keyValuesBackUpMapper: KeyValuesBackUpMapper @Before fun setUp() { keyValuesBackUpMapper = KeyValuesBackUpMapper() } @Test fun `given a KeyValuesEntity, when fromEntity() is called, then maps it into a KeyValueBackUpModel`() { val data = KeyValueTestDataProvider.provideDummyTestData() val entity = KeyValuesEntity(key = data.key, value = data.value) val model = keyValuesBackUpMapper.fromEntity(entity) assertEquals(data.key, model.key) assertEquals(data.value, model.value) } @Test fun `given a KeyValueBackUpModel, when toEntity() is called, then maps it into a KeyValuesEntity`() { val data = KeyValueTestDataProvider.provideDummyTestData() val model = KeyValuesBackUpModel(key = data.key, value = data.value) val entity = keyValuesBackUpMapper.toEntity(model) assertEquals(data.key, entity.key) assertEquals(data.value, entity.value) } }
gpl-3.0
d75207e76d4452bc5db98ac43df84f91
31.095238
107
0.728487
4.252366
false
true
false
false
fare1990/telegram-bot-bumblebee
telegram-bot-bumblebee-core/src/main/java/com/github/bumblebee/command/statistics/service/StatisticsService.kt
1
2930
package com.github.bumblebee.command.statistics.service import com.github.bumblebee.command.statistics.dao.StatisticsRepository import com.github.bumblebee.command.statistics.entity.Statistic import com.github.bumblebee.util.logger import com.github.telegram.domain.Message import com.github.telegram.domain.User import org.springframework.stereotype.Service import java.time.Instant import java.time.LocalDate import java.time.ZoneId import java.util.* import java.util.concurrent.ConcurrentHashMap @Service class StatisticsService(private val repository: StatisticsRepository) { private val stats: MutableMap<Long, MutableList<Statistic>> = loadPersistentStat() private fun loadPersistentStat(): MutableMap<Long, MutableList<Statistic>> { return repository.findStatisticByPostedDate(LocalDate.now()) .groupByTo(ConcurrentHashMap()) { it.chatId } } fun getStatistics(): Map<Long, List<Statistic>> = stats fun handleMessage(message: Message, from: User) { stats.compute(message.chat.id, { _, existingChatStats -> val chatStats = existingChatStats ?: mutableListOf() // get or create Statistics object val userStat = Optional.ofNullable(chatStats.find { it.authorId == from.id }).orElseGet { val stat = createInitialStat(message) chatStats.add(stat) stat } userStat.messageCount++ userStat.authorName = formatUserName(from) repository.save(userStat) log.debug("Saved stat: {}", userStat) chatStats }) } fun cleanupStats(date: LocalDate) { log.debug("Stat before cleanup: {}", stats) stats.values.forEach { chatStats -> chatStats.removeIf { date != it.postedDate } } log.debug("Stat after cleanup: {}", stats) } fun getAllStatInChatByUsers(chatId: Long): Map<String?, Int> = repository.findStatisticByChatId(chatId) .groupBy { it.authorId } .mapKeys { it.value.sortedByDescending { it.postedDate }.first().authorName } .mapValues { it.value.sumBy { it.messageCount } } private fun createInitialStat(message: Message): Statistic = with(Statistic()) { postedDate = message.postedDate() chatId = message.chat.id authorId = message.from!!.id this } private fun Message.postedDate(): LocalDate { return Instant.ofEpochSecond(date.toLong()).atZone(ZoneId.systemDefault()).toLocalDate() } private fun formatUserName(from: User): String = when { !from.lastName.isNullOrBlank() -> "${from.firstName} ${from.lastName}" !from.firstName.isBlank() -> from.firstName !from.userName.isNullOrBlank() -> from.userName!! else -> from.id.toString() } companion object { val log = logger<StatisticsService>() } }
mit
36d479fdfd5143ad206189b5a98b731b
35.17284
107
0.664164
4.528594
false
false
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/lang/utils/RsBooleanExpUtils.kt
3
1305
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.utils import com.intellij.psi.PsiElement import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.ComparisonOp.* import org.rust.lang.core.psi.ext.EqualityOp.* import org.rust.lang.core.psi.ext.operatorType fun RsBinaryExpr.negateToString(): String { val lhs = left.text val rhs = right?.text ?: "" val op = when (operatorType) { EQ -> "!=" EXCLEQ -> "==" GT -> "<=" LT -> ">=" GTEQ -> "<" LTEQ -> ">" else -> null } return if (op != null) "$lhs $op $rhs" else "!($text)" } fun PsiElement.isNegation(): Boolean = this is RsUnaryExpr && excl != null fun PsiElement.negate(): PsiElement { val psiFactory = RsPsiFactory(project) return when { isNegation() -> { val inner = (this as RsUnaryExpr).expr!! (inner as? RsParenExpr)?.expr ?: inner } this is RsBinaryExpr -> psiFactory.createExpression(negateToString()) this is RsParenExpr || this is RsPathExpr || this is RsCallExpr -> psiFactory.createExpression("!$text") else -> psiFactory.createExpression("!($text)") } }
mit
99b68f8ad8a4e52cf9b0e395f76953ab
25.632653
74
0.591571
4.169329
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/ui/preferences/components/ScrollContainers.kt
1
3066
package app.lawnchair.ui.preferences.components import androidx.compose.foundation.MutatePriority import androidx.compose.foundation.ScrollState import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import app.lawnchair.ui.util.addIf import app.lawnchair.ui.util.rememberExtendPadding import com.google.accompanist.insets.ui.LocalScaffoldPadding import kotlinx.coroutines.awaitCancellation @Composable fun PreferenceColumn( verticalArrangement: Arrangement.Vertical = Arrangement.Top, horizontalAlignment: Alignment.Horizontal = Alignment.Start, scrollState: ScrollState? = rememberScrollState(), content: @Composable ColumnScope.() -> Unit ) { ConsumeScaffoldPadding { contentPadding -> NestedScrollStretch { Column( verticalArrangement = verticalArrangement, horizontalAlignment = horizontalAlignment, modifier = Modifier .fillMaxHeight() .addIf(scrollState != null) { this .verticalScroll(scrollState!!) } .padding(rememberExtendPadding(contentPadding, bottom = 16.dp)), content = content ) } } } @Composable fun PreferenceLazyColumn( modifier: Modifier = Modifier, enabled: Boolean = true, state: LazyListState = rememberLazyListState(), isChild: Boolean = false, content: LazyListScope.() -> Unit ) { if (!enabled) { LaunchedEffect(key1 = null) { state.scroll(scrollPriority = MutatePriority.PreventUserInput) { awaitCancellation() } } } ConsumeScaffoldPadding { contentPadding -> NestedScrollStretch { LazyColumn( modifier = modifier .addIf(!isChild) { fillMaxHeight() }, contentPadding = rememberExtendPadding( contentPadding, bottom = if (isChild) 0.dp else 16.dp ), state = state, content = content ) } } } @Composable fun ConsumeScaffoldPadding( content: @Composable (contentPadding: PaddingValues) -> Unit ) { val contentPadding = LocalScaffoldPadding.current CompositionLocalProvider( LocalScaffoldPadding provides PaddingValues(0.dp) ) { content(contentPadding) } }
gpl-3.0
c8e4fae4094b8767b77fd618b3870119
32.692308
84
0.658187
5.574545
false
false
false
false
Zhuinden/simple-stack
samples/multistack-samples/simple-stack-example-multistack-nested-fragment/src/main/java/com/zhuinden/simplestackbottomnavfragmentexample/core/navigation/FragmentStackHostFragment.kt
1
1998
package com.zhuinden.simplestackbottomnavfragmentexample.core.navigation import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import com.zhuinden.simplestack.SimpleStateChanger import com.zhuinden.simplestack.StateChange import com.zhuinden.simplestackbottomnavfragmentexample.R import com.zhuinden.simplestackextensions.fragments.DefaultFragmentStateChanger import com.zhuinden.simplestackextensions.fragmentsktx.lookup class FragmentStackHostFragment : Fragment(R.layout.stack_host_fragment), SimpleStateChanger.NavigationHandler { companion object { fun newInstance(stackHostId: String): FragmentStackHostFragment = FragmentStackHostFragment().apply { arguments = Bundle().also { bundle -> bundle.putString("stackHostId", stackHostId) } } } private lateinit var stateChanger: DefaultFragmentStateChanger private val stackHost by lazy { lookup<FragmentStackHost>(requireArguments().getString("stackHostId")!!) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) stateChanger = DefaultFragmentStateChanger(childFragmentManager, R.id.containerStackHost) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) stackHost.backstack.setStateChanger(SimpleStateChanger(this)) } override fun onResume() { super.onResume() stackHost.backstack.reattachStateChanger() stackHost.isActiveForBack = true } override fun onPause() { stackHost.isActiveForBack = false stackHost.backstack.detachStateChanger() super.onPause() } override fun onDestroyView() { super.onDestroyView() stackHost.backstack.executePendingStateChange() } override fun onNavigationEvent(stateChange: StateChange) { stateChanger.handleStateChange(stateChange) } }
apache-2.0
607f8fd405c4e2f9aac1381893da1cdf
31.241935
112
0.742743
5.18961
false
false
false
false
googlecodelabs/tv-watchnext
step_final/src/main/java/com/example/android/watchnextcodelab/channels/ChannelTvProviderFacade.kt
4
13642
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.example.android.watchnextcodelab.channels import android.content.ComponentName import android.content.ContentResolver import android.content.ContentUris import android.content.Context import android.graphics.BitmapFactory import android.net.Uri import android.support.annotation.DrawableRes import android.support.annotation.VisibleForTesting import android.support.annotation.WorkerThread import android.support.media.tv.Channel import android.support.media.tv.ChannelLogoUtils import android.support.media.tv.PreviewProgram import android.support.media.tv.TvContractCompat import android.util.Log import com.example.android.watchnextcodelab.MainActivity import com.example.android.watchnextcodelab.R import com.example.android.watchnextcodelab.model.Category import com.example.android.watchnextcodelab.model.Movie import com.example.android.watchnextcodelab.model.MovieProgramId import com.google.common.collect.BiMap import com.google.common.collect.HashBiMap import java.util.* private const val TAG = "ChannelTvProviderFacade" private const val SCHEME = "watchnextcodelab" private const val APPS_LAUNCH_HOST = "com.example.android.watchnextcodelab" val BASE_URI = Uri.parse(SCHEME + "://" + APPS_LAUNCH_HOST) const private val START_APP_ACTION_PATH = "startapp" const val PLAY_VIDEO_ACTION_PATH = "playvideo" private const val CHANNELS_COLUMN_ID_INDEX = 0 private const val CHANNELS_COLUMN_INTERNAL_PROVIDER_ID_INDEX = 1 private val CHANNELS_MAP_PROJECTION = arrayOf( TvContractCompat.Channels._ID, TvContractCompat.Channels.COLUMN_INTERNAL_PROVIDER_ID, TvContractCompat.Channels.COLUMN_BROWSABLE) private const val PROGRAMS_COLUMN_ID_INDEX = 0 private const val PROGRAMS_COLUMN_INTERNAL_PROVIDER_ID_INDEX = 1 private const val PROGRAMS_COLUMN_TITLE_INDEX = 2 private val PROGRAMS_MAP_PROJECTION = arrayOf( TvContractCompat.PreviewPrograms._ID, TvContractCompat.PreviewPrograms.COLUMN_INTERNAL_PROVIDER_ID, TvContractCompat.PreviewPrograms.COLUMN_TITLE) /** * Wraps the TV Provider's content provider API for channels and programs. */ object ChannelTvProviderFacade { @WorkerThread fun deleteChannel(context: Context, channelId: Long) { val rowsDeleted = context.contentResolver .delete(TvContractCompat.buildChannelUri(channelId), null, null) if (rowsDeleted < 1) { Log.e(TAG, "Failed to delete channel " + channelId) } } @WorkerThread @VisibleForTesting internal fun deleteChannels(context: Context) { val rowsDeleted = context.contentResolver .delete(TvContractCompat.Channels.CONTENT_URI, null, null) Log.e(TAG, "Deleted $rowsDeleted channels") } @WorkerThread internal fun addChannel(context: Context, category: Category): Long { val channelInputId = createInputId(context) val channel = Channel.Builder() .setDisplayName(category.name) .setDescription(category.description) .setType(TvContractCompat.Channels.TYPE_PREVIEW) .setInputId(channelInputId) .setAppLinkIntentUri(Uri.withAppendedPath(BASE_URI, START_APP_ACTION_PATH)) .setInternalProviderId(category.id) .build() val channelUri = context.contentResolver .insert(TvContractCompat.Channels.CONTENT_URI, channel.toContentValues()) if (channelUri == null || channelUri == Uri.EMPTY) { Log.e(TAG, "Failed to insert channel.") return -1 } val channelId = ContentUris.parseId(channelUri) writeChannelLogo(context, channelId, R.drawable.watchnext_channel_banner) Log.d(TAG, "Added channel $channelId") return channelId } private fun createInputId(context: Context): String { val componentName = ComponentName(context, MainActivity::class.java.name) return TvContractCompat.buildInputId(componentName) } /** * Writes a drawable as the channel logo. * * @param channelId identifies the channel to write the logo. * @param drawableId resource to write as the channel logo. This must be a bitmap and not, say * a vector drawable. */ @WorkerThread private fun writeChannelLogo(context: Context, channelId: Long, @DrawableRes drawableId: Int) { val bitmap = BitmapFactory.decodeResource(context.resources, drawableId) ChannelLogoUtils.storeChannelLogo(context, channelId, bitmap) } @WorkerThread fun addPrograms(context: Context, channelId: Long, category: Category): List<MovieProgramId> { val movies = category.movies // Maps movie ids to lists of program ids. val movieToProgramIds = movies.associateBy({ it.movieId }, { mutableListOf<Long>() }) movies.forEachIndexed { index, movie -> val weight = movies.size - index val programId = addProgram(context, channelId, movie, weight) movieToProgramIds[movie.movieId]?.apply { add(programId) } } return movieToProgramIds.map { entry -> MovieProgramId(entry.key, entry.value) } } @WorkerThread fun addProgram(context: Context, channelId: Long, movie: Movie, weight: Int): Long { val builder = PreviewProgram.Builder() .setChannelId(channelId) .setWeight(weight) addMovieToBuilder(builder, movie) val program = builder.build() val previewProgramUri = TvContractCompat.buildPreviewProgramsUriForChannel(channelId) val programUri = context.contentResolver.insert(previewProgramUri, program.toContentValues()) if (programUri == null || programUri == Uri.EMPTY) { Log.e(TAG, "Failed to insert program ${movie.title}") } else { val programId = ContentUris.parseId(programUri) Log.d(TAG, "Added program $programId") return programId } return -1L } private fun addMovieToBuilder(builder: PreviewProgram.Builder, movie: Movie) { val movieId = java.lang.Long.toString(movie.movieId) builder.setTitle(movie.title) .setDescription(movie.description) .setDurationMillis(java.lang.Long.valueOf(movie.duration)!!.toInt()) .setType(TvContractCompat.PreviewPrograms.TYPE_MOVIE) .setIntentUri(Uri .withAppendedPath(BASE_URI, PLAY_VIDEO_ACTION_PATH) .buildUpon() .appendPath(movieId) .build()) .setInternalProviderId(movieId) .setContentId(movieId) .setPreviewVideoUri(Uri.parse(movie.previewVideoUrl)) .setPosterArtUri(Uri.parse(movie.thumbnailUrl)) .setPosterArtAspectRatio(movie.posterArtAspectRatio) .setContentRatings(arrayOf(movie.contentRating)) .setGenre(movie.genre) .setLive(movie.isLive) .setReleaseDate(movie.releaseDate) .setReviewRating(movie.rating) .setReviewRatingStyle(movie.ratingStyle) .setStartingPrice(movie.startingPrice) .setOfferPrice(movie.offerPrice) .setVideoWidth(movie.width) .setVideoHeight(movie.height) } @WorkerThread internal fun loadProgramsForChannel(context: Context, channelId: Long): List<ProgramMetadata> { val programs = ArrayList<ProgramMetadata>() // Iterate "cursor" through all the programs assigned to "channelId". val programUri = TvContractCompat.buildPreviewProgramsUriForChannel(channelId) context.contentResolver.query(programUri, PROGRAMS_MAP_PROJECTION, null, null, null) .use { cursor -> while (cursor.moveToNext()) { if (!cursor.isNull(PROGRAMS_COLUMN_INTERNAL_PROVIDER_ID_INDEX)) { // Found a row that contains a non-null COLUMN_INTERNAL_PROVIDER_ID. val id = cursor.getString(PROGRAMS_COLUMN_INTERNAL_PROVIDER_ID_INDEX) val programId = cursor.getLong(PROGRAMS_COLUMN_ID_INDEX) val title = cursor.getString(PROGRAMS_COLUMN_TITLE_INDEX) programs.add(ProgramMetadata(id, programId, title)) } } } return programs } @WorkerThread internal fun updateProgram(context: Context, programId: Long, movie: Movie) { val programUri = TvContractCompat.buildPreviewProgramUri(programId) val contentResolver = context.contentResolver contentResolver.query(programUri, null, null, null, null) .use { cursor -> if (!cursor.moveToFirst()) { Log.w(TAG, "Could not update program $programId for movie ${movie.title}") } var program = PreviewProgram.fromCursor(cursor) val builder = PreviewProgram.Builder(program) addMovieToBuilder(builder, movie) program = builder.build() val rowsUpdated = contentResolver .update(programUri, program.toContentValues(), null, null) if (rowsUpdated < 1) { Log.w(TAG, "No programs were updated with id $programId for movie ${movie.title}") } } } @WorkerThread internal fun deleteProgram(context: Context, programId: Long) { val rowsDeleted = context.contentResolver .delete(TvContractCompat.buildPreviewProgramUri(programId), null, null) if (rowsDeleted < 1) { Log.e(TAG, "Failed to delete program $programId") } } /** * Returns the id of the video to play. This will parse a program's intent Uri to retrieve the * id. If the Uri path is does not indicate that a video should be played, then -1 will be * returned. * * @param uri of the program's intent Uri. * @return the id of the video to play. */ fun parseVideoId(uri: Uri): Long { val segments = uri.pathSegments return if (segments.size == 2 && PLAY_VIDEO_ACTION_PATH == segments[0]) segments[1].toLong() else -1L } /** * Represents a program from the TV Provider. It contains the program's id assigned by the TV * Provider, the internal provided id provided by this app (in this case Movie::getMovieId), and * the title of the program. */ class ProgramMetadata internal constructor(val id: String, val programId: Long, val title: String) /** * Queries the TV provider for all of the app's channels returning a bi-directional map of * channel ids to the internal provided id associated with the channel. In this app, the * internal provided id is the category id. * * A BiMap is returned so that a client may easily switch the direction of the map depending on * how they require the data. This prevents extra look ups queries to retrieve a map of category * ids to channel ids. * * @param context used to get a reference to a [ContentResolver]. * @return a bi-directional map of channel ids to category ids. */ @WorkerThread internal fun findChannelCategoryIds(context: Context): BiMap<Long, String> { val channelCategoryIds = HashBiMap.create<Long, String>() context.contentResolver.query( TvContractCompat.Channels.CONTENT_URI, CHANNELS_MAP_PROJECTION, null, null, null).use { cursor -> while (cursor.moveToNext()) { val categoryId = cursor.getString(CHANNELS_COLUMN_INTERNAL_PROVIDER_ID_INDEX) val channelId = cursor.getLong(CHANNELS_COLUMN_ID_INDEX) channelCategoryIds.put(channelId, categoryId) } } return channelCategoryIds } /** * Gets a list of channels from the TV Provider. * * @param context used to get a reference to a [android.content.ContentResolver] * @return a list of channel ids */ @WorkerThread @VisibleForTesting internal fun getChannels(context: Context): List<Long> { val channelIds = mutableListOf<Long>() context.contentResolver.query( TvContractCompat.Channels.CONTENT_URI, CHANNELS_MAP_PROJECTION, null, null, null).use { cursor -> while (cursor.moveToNext()) { val channelId = cursor.getLong(CHANNELS_COLUMN_ID_INDEX) channelIds.add(channelId) } } return channelIds } }
apache-2.0
2df9927ced0d651a21eed572b8c0bfb7
41.108025
103
0.647412
4.746695
false
false
false
false
Shynixn/BlockBall
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/commandmenu/BallSettingsPage.kt
1
10089
package com.github.shynixn.blockball.core.logic.business.commandmenu import com.github.shynixn.blockball.api.business.enumeration.* import com.github.shynixn.blockball.api.persistence.entity.Arena import com.github.shynixn.blockball.api.persistence.entity.ChatBuilder import com.github.shynixn.blockball.api.persistence.entity.Particle import com.github.shynixn.blockball.api.persistence.entity.Sound import com.github.shynixn.blockball.core.logic.persistence.entity.ChatBuilderEntity /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ class BallSettingsPage : Page(BallSettingsPage.ID, MainSettingsPage.ID) { companion object { /** Id of the page. */ const val ID = 30 } /** * Returns the key of the command when this page should be executed. * * @return key */ override fun getCommandKey(): MenuPageKey { return MenuPageKey.BALL } /** * Executes actions for this page. * * @param cache cache */ override fun <P> execute( player: P, command: MenuCommand, cache: Array<Any?>, args: Array<String> ): MenuCommandResult { val ballMeta = (cache[0] as Arena).meta.ballMeta if (command == MenuCommand.BALL_OPEN) { cache[5] = null } else if (command == MenuCommand.BALL_SKIN && args.size == 3) { ballMeta.skin = args[2] } else if (command == MenuCommand.BALL_SIZE_CALLBACK && args.size == 3) { ballMeta.size = BallSize.values()[args[2].toInt()] } else if (command == MenuCommand.BALL_SLIME) { ballMeta.isSlimeVisible = !ballMeta.isSlimeVisible } else if (command == MenuCommand.BALL_INTERACTION_HITBOX && args.size == 3 && args[2].toDoubleOrNull() != null) { ballMeta.interactionHitBoxSize = args[2].toDouble() } else if (command == MenuCommand.BALL_KICKPASS_HITBOX && args.size == 3 && args[2].toDoubleOrNull() != null) { ballMeta.kickPassHitBoxSize = args[2].toDouble() } else if (command == MenuCommand.BALL_INTERACT_COOLDOWN && args.size == 3 && args[2].toIntOrNull() != null) { ballMeta.interactionCoolDown = args[2].toInt() } else if (command == MenuCommand.BALL_KICKPASS_DELAY && args.size == 3 && args[2].toIntOrNull() != null) { ballMeta.kickPassDelay = args[2].toInt() } else if (command == MenuCommand.BALL_TOGGLE_ALWAYSBOUNCE) { ballMeta.alwaysBounce = !ballMeta.alwaysBounce } else if (command == MenuCommand.BALL_TOGGLE_ROTATING) { ballMeta.rotating = !ballMeta.rotating } else if (command == MenuCommand.BALL_PARTICLEACTION_CALLBACK && args.size == 3) { cache[5] = ballMeta.particleEffects[BallActionType.values()[args[2].toInt()]] } else if (command == MenuCommand.BALL_SOUNDACTION_CALLBACK && args.size == 3) { cache[5] = ballMeta.soundEffects[BallActionType.values()[args[2].toInt()]] } return super.execute(player, command, cache, args) } /** * Builds the page content. * * @param cache cache * @return content */ override fun buildPage(cache: Array<Any?>): ChatBuilder { val ballMeta = (cache[0] as Arena).meta.ballMeta val builder = ChatBuilderEntity() .component("- Skin: ").builder() .component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color) .setHoverText(ballMeta.skin).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.BALL_SKIN.command) .setHoverText("Changes the skin of the ball. Can be the name of a skin or a skin URL.") .builder().nextLine() .component("- Skin Size: " + ballMeta.size.name).builder() .component(MenuClickableItem.SELECT.text).setColor(MenuClickableItem.SELECT.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.LIST_BALLSIZES.command) .setHoverText("Opens the selectionbox for ball sizes.") .builder().nextLine() .component("- Slime Visible: " + ballMeta.isSlimeVisible).builder() .component(MenuClickableItem.SELECT.text).setColor(MenuClickableItem.TOGGLE.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.BALL_SLIME.command) .setHoverText("Toggles if the slime hitbox is rendered instead of the ball helmet.") .builder().nextLine() .component("- Interaction Hitbox Size: " + ballMeta.interactionHitBoxSize).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.BALL_INTERACTION_HITBOX.command) .setHoverText("Changes the hitbox size when running into the ball.") .builder().nextLine() .component("- KickPass Hitbox Size: " + ballMeta.kickPassHitBoxSize).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.BALL_KICKPASS_HITBOX.command) .setHoverText("Changes the hitbox size when left or rightclicking the ball.") .builder().nextLine() .component("- Always Bounce: " + ballMeta.alwaysBounce).builder() .component(MenuClickableItem.TOGGLE.text).setColor(MenuClickableItem.TOGGLE.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.BALL_TOGGLE_ALWAYSBOUNCE.command) .setHoverText("Should the ball always bounce of surfaces?") .builder().nextLine() .component("- Rotation Animation: " + ballMeta.rotating).builder() .component(MenuClickableItem.TOGGLE.text).setColor(MenuClickableItem.TOGGLE.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.BALL_TOGGLE_ROTATING.command) .setHoverText("Should the ball play a rotation animation?") .builder().nextLine() .component("- KickPass Delay: " + ballMeta.kickPassDelay).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.BALL_KICKPASS_DELAY.command) .setHoverText("Delay in ticks until a kick or pass is executed.") .builder().nextLine() .component("- Interaction Cooldown: " + ballMeta.interactionCoolDown).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.BALL_INTERACT_COOLDOWN.command) .setHoverText("Cooldown in ticks until the next player can interact with the ball again.") .builder().nextLine() .component("- Ball Modifiers: ").builder() .component(MenuClickableItem.PAGE.text).setColor(MenuClickableItem.PAGE.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.BALLMOD_OPEN.command) .setHoverText("Opens the page for ball modifiers.") .builder().nextLine() .component("- Sound Effect: ").builder() .component(MenuClickableItem.SELECT.text).setColor(MenuClickableItem.SELECT.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.LIST_BALL_SOUNDEFFECTS.command) .setHoverText("Opens the selection page for action binders.") .builder().nextLine() .component("- Particle Effect: ").builder() .component(MenuClickableItem.SELECT.text).setColor(MenuClickableItem.SELECT.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.LIST_BALL_PARTICLEFFECTS.command) .setHoverText("Opens the selection page for action binders.") .builder().nextLine() if (cache[5] != null && cache[5] is Sound) { builder.component("- Selected Sound-effect: ").builder().component(MenuClickableItem.PAGE.text) .setColor(MenuClickableItem.PAGE.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.SOUND_BALL.command) .setHoverText("Opens the page for editing sound effects.") .builder().nextLine() } else if (cache[5] != null && cache[5] is Particle) { builder.component("- Selected Particle-effect: ").builder().component(MenuClickableItem.PAGE.text) .setColor(MenuClickableItem.PAGE.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.PARTICLE_BALL.command) .setHoverText("Opens the page for editing particle effects.") .builder().nextLine() } return builder } }
apache-2.0
ad85753a2c096b5ea1c49d7d9e6d8cdf
55.363128
122
0.668054
4.542548
false
false
false
false
chrisbanes/tivi
data/src/main/java/app/tivi/data/ThreeTenExtensions.kt
1
1479
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.data import org.threeten.bp.Instant import org.threeten.bp.OffsetDateTime import org.threeten.bp.Period import org.threeten.bp.temporal.ChronoUnit import org.threeten.bp.temporal.TemporalAmount fun TemporalAmount.inPast(): Instant = Instant.now().minus(this) fun periodOf(years: Int = 0, months: Int = 0, days: Int = 0): Period = Period.of(years, months, days) fun instantInPast(days: Int = 0, hours: Int = 0, minutes: Int = 0): Instant { var instant = Instant.now() if (days != 0) { instant = instant.minus(days.toLong(), ChronoUnit.DAYS) } if (hours != 0) { instant = instant.minus(hours.toLong(), ChronoUnit.HOURS) } if (minutes != 0) { instant = instant.minus(minutes.toLong(), ChronoUnit.HOURS) } return instant } fun OffsetDateTime.isBefore(instant: Instant): Boolean = toInstant().isBefore(instant)
apache-2.0
0e1f04f35f95296d06a2769eaf009a6f
33.395349
101
0.708587
3.821705
false
false
false
false
outadoc/Twistoast-android
twistoast/src/main/kotlin/fr/outadev/twistoast/StopScheduleViewHolder.kt
1
8198
/* * Twistoast - StopScheduleViewHolder.kt * Copyright (C) 2013-2016 Baptiste Candellier * * Twistoast 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. * * Twistoast 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 fr.outadev.twistoast import android.graphics.Color import android.graphics.drawable.GradientDrawable import android.support.annotation.StringRes import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.animation.AlphaAnimation import android.widget.FrameLayout import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import fr.outadev.android.transport.timeo.TimeoStop import fr.outadev.android.transport.timeo.TimeoStopSchedule import fr.outadev.android.transport.timeo.TimeoStopTrafficMessage import fr.outadev.twistoast.uiutils.Colors import fr.outadev.twistoast.uiutils.collapse import fr.outadev.twistoast.uiutils.expand import org.jetbrains.anko.onClick /** * Container for an item in the list. Here, this corresponds to a bus stop, and all the info * displayed for it (schedules, and metadata). */ class StopScheduleViewHolder(v: View) : RecyclerView.ViewHolder(v) { val container: LinearLayout val rowLineIdContainer: FrameLayout val rowLineId: TextView val rowStopName: TextView val rowDirectionName: TextView val viewScheduleContainer: LinearLayout val imgStopWatched: ImageView val lineDrawable: GradientDrawable val lblStopTrafficTitle: TextView val lblStopTrafficMessage: TextView val lblScheduleTime = arrayOfNulls<TextView>(RecyclerAdapterRealtime.NB_SCHEDULES_DISPLAYED) val lblScheduleDirection = arrayOfNulls<TextView>(RecyclerAdapterRealtime.NB_SCHEDULES_DISPLAYED) val lblScheduleSeparator = arrayOfNulls<TextView>(RecyclerAdapterRealtime.NB_SCHEDULES_DISPLAYED) val scheduleContainers = arrayOfNulls<View>(RecyclerAdapterRealtime.NB_SCHEDULES_DISPLAYED) val viewStopTrafficInfoContainer: View val imgStopTrafficExpandIcon: View var isExpanded: Boolean init { val inflater = LayoutInflater.from(v.context) container = v as LinearLayout isExpanded = false // Get references to the views rowLineIdContainer = v.findViewById(R.id.rowLineIdContainer) as FrameLayout rowLineId = v.findViewById(R.id.rowLineId) as TextView rowStopName = v.findViewById(R.id.rowStopName) as TextView rowDirectionName = v.findViewById(R.id.rowDirectionName) as TextView viewScheduleContainer = v.findViewById(R.id.viewScheduleContainer) as LinearLayout imgStopWatched = v.findViewById(R.id.imgStopWatched) as ImageView lineDrawable = rowLineIdContainer.background as GradientDrawable lblStopTrafficTitle = v.findViewById(R.id.lblStopTrafficTitle) as TextView lblStopTrafficMessage = v.findViewById(R.id.lblStopTrafficMessage) as TextView viewStopTrafficInfoContainer = v.findViewById(R.id.viewStopTrafficInfoContainer) imgStopTrafficExpandIcon = v.findViewById(R.id.imgStopTrafficExpandIcon) // Stop traffic info is collapsed by default. // When it's clicked, we display the message. viewStopTrafficInfoContainer.onClick { if (!isExpanded) { lblStopTrafficMessage.expand() imgStopTrafficExpandIcon .animate() .rotation(180.0f) .start() } else { lblStopTrafficMessage.collapse() imgStopTrafficExpandIcon .animate() .rotation(0f) .start() } isExpanded = !isExpanded viewStopTrafficInfoContainer.requestLayout() } // Store references to schedule views for (i in 0..RecyclerAdapterRealtime.NB_SCHEDULES_DISPLAYED - 1) { // Create schedule detail views and make them accessible val singleScheduleView = inflater.inflate(R.layout.view_single_schedule_label, null) lblScheduleTime[i] = singleScheduleView.findViewById(R.id.lbl_schedule) as TextView lblScheduleDirection[i] = singleScheduleView.findViewById(R.id.lbl_schedule_direction) as TextView lblScheduleSeparator[i] = singleScheduleView.findViewById(R.id.lbl_schedule_separator) as TextView scheduleContainers[i] = singleScheduleView viewScheduleContainer.addView(singleScheduleView) } } fun displayStopInfo(stop: TimeoStop) { lineDrawable.setColor(Colors.getBrighterColor(Color.parseColor(stop.line.color))) rowLineId.text = stop.line.id rowStopName.text = rowStopName.context.getString(R.string.stop_name, stop.name) val dir = if (stop.line.direction.name != null) stop.line.direction.name else stop.line.direction.id rowDirectionName.text = rowDirectionName.context.getString(R.string.direction_name, dir) } fun displaySchedule(stopSchedule: TimeoStopSchedule) { // Get the schedules for this stop stopSchedule.schedules.forEachIndexed { i, schedule -> lblScheduleTime[i]?.text = TimeFormatter.formatTime(lblScheduleTime[i]!!.context, schedule.scheduleTime) lblScheduleDirection[i]?.text = schedule.direction scheduleContainers[i]?.visibility = View.VISIBLE if (!schedule.direction.isNullOrBlank()) lblScheduleSeparator[i]?.visibility = View.VISIBLE } if (stopSchedule.schedules.isEmpty()) { // If no schedules are available, add a fake one to inform the user displayErrorSchedule(R.string.no_upcoming_stops) } if (stopSchedule.trafficMessages.isNotEmpty()) { displayTrafficMessage(stopSchedule.trafficMessages.first()) } startFadeIn() } fun displayTrafficMessage(message: TimeoStopTrafficMessage) { lblStopTrafficTitle.text = message.title lblStopTrafficMessage.text = message.body viewStopTrafficInfoContainer.visibility = View.VISIBLE } /** * Displays an error message in place of the stop's schedules. * * @param messageRes the string resource message to display * @param invalidStop whether or not to fade out the stop */ fun displayErrorSchedule(@StringRes messageRes: Int, invalidStop: Boolean = false) { // Make the row look a bit translucent to make it stand out lblScheduleTime[0]?.setText(messageRes) scheduleContainers[0]?.visibility = View.VISIBLE if (invalidStop) container.alpha = 0.4f } fun startFadeIn() { // Fade in the row! if (container.alpha != 1.0f) { container.alpha = 1.0f val alphaAnim = AlphaAnimation(0.4f, 1.0f) alphaAnim.duration = 500 container.startAnimation(alphaAnim) } } /** * Reset the row's properties and empty everything. */ fun resetView() { // Clear any previous data for (i in 0..RecyclerAdapterRealtime.NB_SCHEDULES_DISPLAYED - 1) { lblScheduleTime[i]?.text = "" lblScheduleDirection[i]?.text = "" lblScheduleSeparator[i]?.visibility = View.GONE scheduleContainers[i]?.visibility = View.GONE } viewStopTrafficInfoContainer.visibility = View.GONE lblStopTrafficMessage.layoutParams.height = 0 imgStopTrafficExpandIcon.rotation = 0f isExpanded = false } }
gpl-3.0
e01cb243544449565c3533fbcbf8fff3
37.308411
116
0.694194
4.494518
false
false
false
false
JimSeker/ui
Communication/FragComNavVModelDemo_kt/app/src/main/java/edu/cs4730/fragcomnavvmodeldemo_kt/FirstFragment.kt
1
1699
package edu.cs4730.fragcomnavvmodeldemo_kt import androidx.navigation.Navigation.findNavController import android.widget.TextView import android.view.LayoutInflater import android.view.ViewGroup import android.os.Bundle import android.view.View import android.widget.Button import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider /** * simple example use a viewmodel as plain old java object. Except it shared between all the fragments and MainActivity. * Note it would even better with LiveData, but that is another example. */ class FirstFragment : Fragment() { lateinit var tv1: TextView lateinit var tv2: TextView lateinit var btn1: Button lateinit var mViewModel: DataViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val myView = inflater.inflate(R.layout.fragment_first, container, false) mViewModel = ViewModelProvider(requireActivity())[DataViewModel::class.java] tv1 = myView.findViewById(R.id.ff_tv1) tv2 = myView.findViewById(R.id.ff_tv2) btn1 = myView.findViewById(R.id.ff_btn1) btn1.setOnClickListener(View.OnClickListener { v -> //this is call the navigation to change the second fragment mViewModel.num_two++ mViewModel.setItem("Called by FirstFragment") findNavController(v).navigate(R.id.action_first_to_second) }) mViewModel.data.observe(viewLifecycleOwner) { data -> tv2.text = "Parameter2: $data" } tv1.text = "Parameter1: " + mViewModel.num_one return myView } }
apache-2.0
b80a23f1d7651cb2d785cc0e1836c760
40.463415
121
0.721012
4.35641
false
false
false
false
nithia/xkotlin
exercises/grade-school/src/example/kotlin/School.kt
1
377
import java.util.HashMap class School { private val database = mutableMapOf<Int, List<String>>() internal fun db() = HashMap(database) fun add(student: String, grade: Int) { database[grade] = grade(grade) + student } fun grade(grade: Int) = database[grade] ?: listOf() fun sort() = database.toSortedMap().mapValues { it.value.sorted() } }
mit
814aac98abdc538e2f726684a21cb0ce
22.5625
71
0.644562
3.808081
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/service/permission/LanternSubject.kt
1
3184
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.service.permission import org.spongepowered.api.service.context.Context import org.spongepowered.api.service.permission.MemorySubjectData import org.spongepowered.api.service.permission.PermissionService import org.spongepowered.api.service.permission.Subject import org.spongepowered.api.service.permission.SubjectData import org.spongepowered.api.service.permission.SubjectReference import org.spongepowered.api.util.Tristate import java.util.Optional abstract class LanternSubject : Subject { abstract val service: PermissionService override fun getTransientSubjectData(): MemorySubjectData = this.subjectData abstract override fun getSubjectData(): MemorySubjectData override fun isSubjectDataPersisted(): Boolean = false override fun asSubjectReference(): SubjectReference = this.service.newSubjectReference(this.containingCollection.identifier, this.identifier) override fun hasPermission(contexts: Set<Context>, permission: String): Boolean = this.getPermissionValue(contexts, permission) == Tristate.TRUE override fun getPermissionValue(contexts: Set<Context>, permission: String): Tristate = this.getDataPermissionValue(this.transientSubjectData, permission) protected fun getDataPermissionValue(subject: MemorySubjectData, permission: String?): Tristate { var res = subject.getNodeTree(SubjectData.GLOBAL_CONTEXT)[permission] if (res === Tristate.UNDEFINED) { for (parent in subject.getParents(SubjectData.GLOBAL_CONTEXT)) { res = parent.resolve().join().getPermissionValue(SubjectData.GLOBAL_CONTEXT, permission) if (res !== Tristate.UNDEFINED) { return res } } } return res } override fun isChildOf(contexts: Set<Context>, parent: SubjectReference): Boolean = this.subjectData.getParents(contexts).contains(parent) override fun getParents(contexts: Set<Context>): List<SubjectReference> = this.subjectData.getParents(contexts) protected fun getDataOptionValue(subject: MemorySubjectData, option: String): Optional<String> { var result = Optional.ofNullable(subject.getOptions(SubjectData.GLOBAL_CONTEXT)[option]) if (!result.isPresent) { for (parent in subject.getParents(SubjectData.GLOBAL_CONTEXT)) { result = parent.resolve().join().getOption(SubjectData.GLOBAL_CONTEXT, option) if (result.isPresent) return result } } return result } override fun getOption(contexts: Set<Context>, key: String): Optional<String> = this.getDataOptionValue(transientSubjectData, key) override fun getActiveContexts(): Set<Context> = SubjectData.GLOBAL_CONTEXT }
mit
d31bca16a597ef51e41ca6f3220f8628
41.453333
134
0.717023
4.668622
false
false
false
false
ChrisZhong/organization-model
chazm-model/src/main/kotlin/runtimemodels/chazm/model/relation/ModeratesEvent.kt
2
1611
package runtimemodels.chazm.model.relation import runtimemodels.chazm.api.entity.Attribute import runtimemodels.chazm.api.entity.AttributeId import runtimemodels.chazm.api.entity.Pmf import runtimemodels.chazm.api.entity.PmfId import runtimemodels.chazm.api.id.UniqueId import runtimemodels.chazm.api.relation.Moderates import runtimemodels.chazm.model.event.AbstractEvent import runtimemodels.chazm.model.event.EventType import runtimemodels.chazm.model.message.M import java.util.* import javax.inject.Inject /** * The [ModeratesEvent] class indicates that there is an update about a [Moderates] relation. * * @author Christopher Zhong * @since 7.0.0 */ open class ModeratesEvent @Inject internal constructor( category: EventType, moderates: Moderates ) : AbstractEvent(category) { /** * Returns a [UniqueId] that represents a [Pmf]. * * @return a [UniqueId]. */ val pmfId: PmfId = moderates.pmf.id /** * Returns a [UniqueId] that represents an [Attribute]. * * @return a [UniqueId]. */ val attributeId: AttributeId = moderates.attribute.id override fun equals(other: Any?): Boolean { if (other is ModeratesEvent) { return super.equals(other) && pmfId == other.pmfId && attributeId == other.attributeId } return false } override fun hashCode(): Int = Objects.hash(category, pmfId, attributeId) override fun toString(): String = M.EVENT_WITH_2_IDS[super.toString(), pmfId, attributeId] companion object { private const val serialVersionUID = 273935856408749575L } }
apache-2.0
d9120e01da2b864abe86fae4360f5220
29.396226
98
0.71198
4.057935
false
false
false
false
android/topeka
base/src/test/java/com/google/samples/apps/topeka/model/CategoryTest.kt
3
1730
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.topeka.model import com.google.samples.apps.topeka.model.quiz.Quiz import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import java.util.* class CategoryTest { @Test fun construct_withScores_sameSizeQuizAndScores() { assertThat(Category(NAME, ID, THEME, QUIZZES, SCORES, false), notNullValue()) } @Test(expected = IllegalArgumentException::class) fun construct_withScores_failsDifferentSizeQuizAndScores() { Category(NAME, ID, THEME, QUIZZES, IntArray(2), false) } @Test fun hashCode_failsForDifferent() { createCategory().apply { val other = Category(ID, NAME, THEME, QUIZZES, SCORES, true) assertThat(hashCode() == other.hashCode(), `is`(false)) } } private fun createCategory() = Category(NAME, ID, THEME, QUIZZES, SCORES, false) private val NAME = "Foo" private val ID = "id" private val THEME = Theme.blue private val QUIZZES = ArrayList<Quiz<*>>() private val SCORES = IntArray(0) }
apache-2.0
89909e1a52d85600ff93798f13beb68e
32.288462
85
0.708671
3.914027
false
true
false
false
scorsero/scorsero-client-android
app/src/main/java/io/github/dmi3coder/scorsero/navigation/DrawerController.kt
1
2432
package io.github.dmi3coder.scorsero.navigation import android.os.Bundle import android.support.v4.widget.DrawerLayout import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bluelinelabs.conductor.Controller import com.bluelinelabs.conductor.Router import io.github.dmi3coder.scorsero.BaseNavigator import io.github.dmi3coder.scorsero.BuildConfig import io.github.dmi3coder.scorsero.MainActivity import io.github.dmi3coder.scorsero.R import io.github.dmi3coder.scorsero.navigation.NavigationContract.Presenter import kotlinx.android.synthetic.main.activity_main.drawer_layout import kotlinx.android.synthetic.main.controller_drawer.view.drawer_list /** * Created by dim3coder on 8:53 AM 8/2/17. */ class DrawerController() : Controller(), NavigationContract.View { constructor(mainRouter: Router) : this() { this.mainRouter = mainRouter } lateinit var mainRouter: Router lateinit internal var presenter: Presenter internal var view: View? = null lateinit var drawer: DrawerLayout private var adapter: DrawerAdapter? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View { view = inflater.inflate(R.layout.controller_drawer, container, false) drawer = (activity as MainActivity).drawer_layout //The hell I need this complexity? val presenter = NavigationPresenter(this, baseNavigator = activity as BaseNavigator) presenter.start() return view!! } override fun onRestoreViewState(view: View, savedViewState: Bundle) { super.onRestoreViewState(view, savedViewState) adapter?.selectSubscription?.onNext(savedViewState.getInt(DRAWER_SELECTED_POSITION)) } override fun setPresenter(presenter: Presenter) { this.presenter = presenter } override fun onSaveViewState(view: View, outState: Bundle) { super.onSaveViewState(view, outState) outState.putInt(DRAWER_SELECTED_POSITION, (view.drawer_list.adapter as DrawerAdapter).selectSubscription.value) } override fun showNavigationItems(items: Array<NavigationItem>) { view!!.drawer_list.layoutManager = LinearLayoutManager(activity) adapter = DrawerAdapter(items, presenter, drawer) view!!.drawer_list.adapter = adapter } companion object { val DRAWER_SELECTED_POSITION = "${BuildConfig.APPLICATION_ID}.navigation.DRAWER_SELECTED_POSITION" } }
gpl-3.0
23e27873a120fd50555b80abe51f759f
35.863636
102
0.783306
4.289242
false
false
false
false
QuincySx/vport-android
app/src/main/java/com/a21vianet/wallet/vport/action/info/changename/PersonalChangeNameActivity.kt
1
2289
package com.a21vianet.wallet.vport.action.info.changename import android.widget.Toast import com.a21vianet.wallet.vport.R import com.a21vianet.wallet.vport.biz.CryptoBiz import com.a21vianet.wallet.vport.http.Api import com.a21vianet.wallet.vport.library.commom.crypto.bean.Contract import com.a21vianet.wallet.vport.library.commom.http.ipfs.IPFSRequest import com.a21vianet.wallet.vport.library.commom.http.ipfs.bean.UserInfoIPFS import com.google.gson.Gson import com.littlesparkle.growler.core.ui.activity.BaseTitleBarActivity import com.littlesparkle.growler.core.ui.mvp.BasePresenter import com.littlesparkle.growler.core.ui.mvp.BaseView import kotlinx.android.synthetic.main.activity_personal_change_name.* import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers class PersonalChangeNameActivity : BaseTitleBarActivity<BasePresenter<BaseView>>() { override fun getLayoutResId(): Int { return R.layout.activity_personal_change_name } override fun selfTitleResId(): Int { return R.string.title_personal_change_name } override fun initData() { super.initData() } override fun initView() { super.initView() tv_change.setOnClickListener { val nickname = edit_nickname.text.trim().toString() update(nickname) } } fun update(nickname: String) { showProgress() val contract = Contract() contract.get() IPFSRequest(Api.IPFSWebApi) .ipfsGetJson(contract.ipfsHex) .map({ val userinfo = Gson().fromJson(it, UserInfoIPFS::class.java) userinfo.name = nickname userinfo }) .flatMap { CryptoBiz.signIPFSTx(contract, it) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ contract.nickname = nickname contract.save() dismissProgress() finish() }, { dismissProgress() Toast.makeText(this@PersonalChangeNameActivity, "保存失败", Toast.LENGTH_LONG).show() }) } }
mit
b539b60c49437567e77d5c15fd24283c
34.092308
101
0.64007
4.27955
false
false
false
false
SimonVT/cathode
cathode-sync/src/main/java/net/simonvt/cathode/actions/user/SyncHiddenCollected.kt
1
5465
/* * Copyright (C) 2017 Simon Vig Therkildsen * * 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 net.simonvt.cathode.actions.user import android.content.ContentProviderOperation import android.content.Context import androidx.work.WorkManager import net.simonvt.cathode.actions.PagedAction import net.simonvt.cathode.actions.PagedResponse import net.simonvt.cathode.api.entity.HiddenItem import net.simonvt.cathode.api.enumeration.HiddenSection import net.simonvt.cathode.api.enumeration.ItemType import net.simonvt.cathode.api.service.UsersService import net.simonvt.cathode.common.database.forEach import net.simonvt.cathode.common.database.getLong import net.simonvt.cathode.provider.DatabaseContract.SeasonColumns import net.simonvt.cathode.provider.DatabaseContract.ShowColumns import net.simonvt.cathode.provider.ProviderSchematic.Seasons import net.simonvt.cathode.provider.ProviderSchematic.Shows import net.simonvt.cathode.provider.batch import net.simonvt.cathode.provider.helper.SeasonDatabaseHelper import net.simonvt.cathode.provider.helper.ShowDatabaseHelper import net.simonvt.cathode.provider.query import net.simonvt.cathode.work.enqueueUniqueNow import net.simonvt.cathode.work.movies.SyncPendingMoviesWorker import net.simonvt.cathode.work.shows.SyncPendingShowsWorker import retrofit2.Call import javax.inject.Inject class SyncHiddenCollected @Inject constructor( private val context: Context, private val showHelper: ShowDatabaseHelper, private val seasonHelper: SeasonDatabaseHelper, private val usersService: UsersService, private val workManager: WorkManager ) : PagedAction<Unit, HiddenItem>() { override fun key(params: Unit): String = "SyncHiddenCollected" override fun getCall(params: Unit, page: Int): Call<List<HiddenItem>> = usersService.getHiddenItems(HiddenSection.PROGRESS_COLLECTED, null, page, 25) override suspend fun handleResponse( params: Unit, pagedResponse: PagedResponse<Unit, HiddenItem> ) { val ops = arrayListOf<ContentProviderOperation>() val unhandledShows = mutableListOf<Long>() val unhandledSeasons = mutableListOf<Long>() val hiddenShows = context.contentResolver.query( Shows.SHOWS, arrayOf(ShowColumns.ID), ShowColumns.HIDDEN_COLLECTED + "=1" ) hiddenShows.forEach { cursor -> unhandledShows.add(cursor.getLong(ShowColumns.ID)) } hiddenShows.close() val hiddenSeasons = context.contentResolver.query( Seasons.SEASONS, arrayOf(SeasonColumns.ID), SeasonColumns.HIDDEN_COLLECTED + "=1" ) hiddenSeasons.forEach { cursor -> unhandledSeasons.add(cursor.getLong(SeasonColumns.ID)) } hiddenSeasons.close() var page: PagedResponse<Unit, HiddenItem>? = pagedResponse do { for (hiddenItem in page!!.response) { when (hiddenItem.type) { ItemType.SHOW -> { val show = hiddenItem.show!! val traktId = show.ids.trakt!! val showResult = showHelper.getIdOrCreate(traktId) val showId = showResult.showId if (!unhandledShows.remove(showId)) { val op = ContentProviderOperation.newUpdate(Shows.withId(showId)) .withValue(ShowColumns.HIDDEN_COLLECTED, 1) .build() ops.add(op) } } ItemType.SEASON -> { val show = hiddenItem.show!! val season = hiddenItem.season!! val traktId = show.ids.trakt!! val showResult = showHelper.getIdOrCreate(traktId) val showId = showResult.showId val seasonNumber = season.number val result = seasonHelper.getIdOrCreate(showId, seasonNumber) val seasonId = result.id if (result.didCreate && !showResult.didCreate) { showHelper.markPending(showId) } if (!unhandledSeasons.remove(seasonId)) { val op = ContentProviderOperation.newUpdate(Seasons.withId(seasonId)) .withValue(SeasonColumns.HIDDEN_COLLECTED, 1) .build() ops.add(op) } } else -> throw RuntimeException("Unknown item type: ${hiddenItem.type}") } } page = page.nextPage() } while (page != null) workManager.enqueueUniqueNow(SyncPendingShowsWorker.TAG, SyncPendingShowsWorker::class.java) workManager.enqueueUniqueNow(SyncPendingMoviesWorker.TAG, SyncPendingMoviesWorker::class.java) for (showId in unhandledShows) { val op = ContentProviderOperation.newUpdate(Shows.withId(showId)) .withValue(ShowColumns.HIDDEN_COLLECTED, 0) .build() ops.add(op) } for (seasonId in unhandledSeasons) { val op = ContentProviderOperation.newUpdate(Seasons.withId(seasonId)) .withValue(SeasonColumns.HIDDEN_COLLECTED, 0) .build() ops.add(op) } context.contentResolver.batch(ops) } }
apache-2.0
04dd44a45710a85afd540abd6c9fc5d6
35.925676
98
0.708326
4.483183
false
false
false
false
pokk/mvp-magazine
app/src/main/kotlin/taiwan/no1/app/internal/di/modules/AppModule.kt
1
1459
package taiwan.no1.app.internal.di.modules import android.app.Application import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import dagger.Module import dagger.Provides import taiwan.no1.app.data.executor.JobExecutor import taiwan.no1.app.data.repositiry.DataRepository import taiwan.no1.app.domain.executor.PostExecutionThread import taiwan.no1.app.domain.executor.ThreadExecutor import taiwan.no1.app.domain.repository.IRepository import taiwan.no1.app.utilies.UIThread import javax.inject.Singleton /** * Dagger module that provides objects which will live during the application lifecycle. * * @author Jieyi * @since 12/6/16 */ @Module class AppModule(private val app: Application) { @Provides @Singleton fun provideApplication(): Application = app @Provides @Singleton fun provideAppContext(): Context = app @Provides @Singleton fun provideSharePreferences(application: Application): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(application) @Provides @Singleton fun provideRepository(dataRepository: DataRepository): IRepository = dataRepository @Provides @Singleton fun providePostExecutionThread(uiThread: UIThread): PostExecutionThread = uiThread @Provides @Singleton fun provideThreadExecutor(jobExecutor: JobExecutor): ThreadExecutor = jobExecutor }
apache-2.0
e7a0fa6f75064dfd822a62de226443d1
27.607843
88
0.777245
4.661342
false
false
false
false
Mauin/detekt
detekt-cli/src/main/kotlin/io/gitlab/arturbosch/detekt/cli/out/XmlOutputReport.kt
1
2032
package io.gitlab.arturbosch.detekt.cli.out import io.gitlab.arturbosch.detekt.api.Detektion import io.gitlab.arturbosch.detekt.api.Finding import io.gitlab.arturbosch.detekt.api.OutputReport import io.gitlab.arturbosch.detekt.api.Severity /** * Generates an XML report following the structure of a Checkstyle report. * * @author Marvin Ramin */ class XmlOutputReport : OutputReport() { override val ending: String = "xml" private sealed class MessageType(val label: String) { class Warning : MessageType("warning") class Info : MessageType("info") class Fatal : MessageType("fatal") class Error : MessageType("error") } override fun render(detektion: Detektion): String { val smells = detektion.findings.flatMap { it.value } val lines = ArrayList<String>() lines += "<?xml version=\"1.0\" encoding=\"utf-8\"?>" lines += "<checkstyle version=\"4.3\">" smells.groupBy { it.location.file }.forEach { fileName, findings -> lines += "<file name=\"${fileName.toXmlString()}\">" findings.forEach { lines += arrayOf( "\t<error line=\"${it.location.source.line.toXmlString()}\"", "column=\"${it.location.source.column.toXmlString()}\"", "severity=\"${it.messageType.label.toXmlString()}\"", "message=\"${it.messageOrDescription().toXmlString()}\"", "source=\"${"detekt.${it.id.toXmlString()}"}\" />" ).joinToString(separator = " ") } lines += "</file>" } lines += "</checkstyle>" return lines.joinToString(separator = "\n") } private val Finding.messageType: MessageType get() = when (issue.severity) { Severity.CodeSmell -> MessageType.Warning() Severity.Style -> MessageType.Warning() Severity.Warning -> MessageType.Warning() Severity.Maintainability -> MessageType.Warning() Severity.Defect -> MessageType.Error() Severity.Minor -> MessageType.Info() Severity.Security -> MessageType.Fatal() Severity.Performance -> MessageType.Warning() } private fun Any.toXmlString() = XmlEscape.escapeXml(toString().trim()) }
apache-2.0
ff170ec6c2846864486978fd326cec73
31.774194
74
0.6875
3.798131
false
false
false
false
MichaelNedzelsky/intellij-community
platform/configuration-store-impl/src/ApplicationStoreImpl.kt
4
5217
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.application.options.PathMacrosImpl import com.intellij.openapi.application.Application import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.invokeAndWaitIfNeed import com.intellij.openapi.components.PathMacroManager import com.intellij.openapi.components.StateStorageOperation import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.components.impl.BasePathMacroManager import com.intellij.openapi.components.impl.ServiceManagerImpl import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.NamedJDOMExternalizable import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import org.jdom.Element private class ApplicationPathMacroManager : BasePathMacroManager(null) class ApplicationStoreImpl(private val application: Application, pathMacroManager: PathMacroManager? = null) : ComponentStoreImpl() { override val storageManager = ApplicationStorageManager(application, pathMacroManager) // number of app components require some state, so, we load default state in test mode override val loadPolicy: StateLoadPolicy get() = if (application.isUnitTestMode) StateLoadPolicy.LOAD_ONLY_DEFAULT else StateLoadPolicy.LOAD override fun setPath(path: String) { // app config must be first, because collapseMacros collapse from fist to last, so, at first we must replace APP_CONFIG because it overlaps ROOT_CONFIG value storageManager.addMacro(StoragePathMacros.APP_CONFIG, "$path/${ApplicationStorageManager.FILE_STORAGE_DIR}") storageManager.addMacro(ROOT_CONFIG, path) val configDir = LocalFileSystem.getInstance().refreshAndFindFileByPath(path) if (configDir != null) { invokeAndWaitIfNeed { // not recursive, config directory contains various data - for example, ICS or shelf should not be refreshed, // but we refresh direct children to avoid refreshAndFindFile in SchemeManager (to find schemes directory) // ServiceManager inits service under read-action, so, we cannot refresh scheme dir on SchemeManager creation because it leads to error "Calling invokeAndWait from read-action leads to possible deadlock." val refreshAll = ServiceManagerImpl.isUseReadActionToInitService() VfsUtil.markDirtyAndRefresh(false, refreshAll, true, configDir) val optionsDir = configDir.findChild(ApplicationStorageManager.FILE_STORAGE_DIR) if (!refreshAll && optionsDir != null) { // not recursive, options directory contains only files VfsUtil.markDirtyAndRefresh(false, false, true, optionsDir) } } } } } class ApplicationStorageManager(private val application: Application, pathMacroManager: PathMacroManager? = null) : StateStorageManagerImpl("application", pathMacroManager?.createTrackingSubstitutor(), application) { companion object { private val DEFAULT_STORAGE_SPEC = "${PathManager.DEFAULT_OPTIONS_FILE_NAME}${FileStorageCoreUtil.DEFAULT_EXT}" val FILE_STORAGE_DIR = "options" } override fun getOldStorageSpec(component: Any, componentName: String, operation: StateStorageOperation): String? { return if (component is NamedJDOMExternalizable) { "${component.externalFileName}${FileStorageCoreUtil.DEFAULT_EXT}" } else { DEFAULT_STORAGE_SPEC } } override fun getMacroSubstitutor(fileSpec: String) = if (fileSpec == "${PathMacrosImpl.EXT_FILE_NAME}${FileStorageCoreUtil.DEFAULT_EXT}") null else super.getMacroSubstitutor(fileSpec) override protected val isUseXmlProlog: Boolean get() = false override fun dataLoadedFromProvider(storage: FileBasedStorage, element: Element?) { // IDEA-144052 When "Settings repository" is enabled changes in 'Path Variables' aren't saved to default path.macros.xml file causing errors in build process try { if (element == null) { storage.file.delete() } else { FileUtilRt.createParentDirs(storage.file) JDOMUtil.writeElement(element, storage.file.writer(), "\n") } } catch (e: Throwable) { LOG.error(e) } } override fun normalizeFileSpec(fileSpec: String) = removeMacroIfStartsWith(super.normalizeFileSpec(fileSpec), StoragePathMacros.APP_CONFIG) override fun expandMacros(path: String) = if (path[0] == '$') { super.expandMacros(path) } else { "${expandMacro(StoragePathMacros.APP_CONFIG)}/$path" } }
apache-2.0
713190033288645c4e957ad3d7a5449a
44.77193
216
0.763849
4.821627
false
true
false
false
andreyfomenkov/green-cat
plugin/src/ru/fomenkov/plugin/util/PackageNameUtil.kt
1
523
package ru.fomenkov.plugin.util import java.lang.IllegalArgumentException object PackageNameUtil { fun split(packageName: String, ignoreLast: Int = 0): List<String> { if (packageName.isBlank()) { return emptyList() } val parts = packageName.split(".") if (parts.size <= ignoreLast || ignoreLast < 0) { throw IllegalArgumentException("Incorrect ignoreLast value") } return parts.subList(fromIndex = 0, toIndex = parts.size - ignoreLast) } }
apache-2.0
e9615f61962039ac8b71e4992f24f7f3
28.111111
78
0.636711
4.508621
false
false
false
false
colriot/anko
dsl/testData/functional/percent/LayoutsTest.kt
2
5039
private val defaultInit: Any.() -> Unit = {} open class _PercentFrameLayout(ctx: Context): android.support.percent.PercentFrameLayout(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.support.percent.PercentFrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentFrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.support.percent.PercentFrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentFrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: android.support.percent.PercentFrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentFrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.support.percent.PercentFrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentFrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.support.percent.PercentFrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentFrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.widget.FrameLayout.LayoutParams?, init: android.support.percent.PercentFrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentFrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.support.percent.PercentFrameLayout.LayoutParams?, init: android.support.percent.PercentFrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentFrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _PercentRelativeLayout(ctx: Context): android.support.percent.PercentRelativeLayout(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.support.percent.PercentRelativeLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentRelativeLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.support.percent.PercentRelativeLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentRelativeLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.support.percent.PercentRelativeLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentRelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.support.percent.PercentRelativeLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.support.percent.PercentRelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } }
apache-2.0
4759736cf966ab3930f24fac41060f66
39.97561
106
0.66283
4.808206
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/view/EqualizerBar.kt
1
4494
/***************************************************************************** * EqualizerBar.java * * Copyright © 2013 VLC authors and VideoLAN * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. */ package org.videolan.vlc.gui.view import android.annotation.TargetApi import android.content.Context import android.os.Build import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.LinearLayout import android.widget.SeekBar import android.widget.SeekBar.OnSeekBarChangeListener import android.widget.TextView import org.videolan.vlc.R import org.videolan.vlc.interfaces.OnEqualizerBarChangeListener class EqualizerBar : LinearLayout { private lateinit var bandValueTextView: TextView private lateinit var verticalSeekBar: VerticalSeekBar private lateinit var bandTextView: TextView private var listener: OnEqualizerBarChangeListener? = null override fun setNextFocusLeftId(nextFocusLeftId: Int) { super.setNextFocusLeftId(nextFocusLeftId) verticalSeekBar.nextFocusLeftId = nextFocusLeftId } override fun setNextFocusRightId(nextFocusRightId: Int) { super.setNextFocusRightId(nextFocusRightId) verticalSeekBar.nextFocusRightId = nextFocusRightId } private val seekListener = object : OnSeekBarChangeListener { override fun onStartTrackingTouch(seekBar: SeekBar) { listener?.onStartTrackingTouch() } override fun onStopTrackingTouch(seekBar: SeekBar) {} override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { val value = (progress - RANGE) / PRECISION.toFloat() // HACK: VerticalSeekBar programmatically calls onProgress // fromUser will always be false // So use custom getFromUser() instead of fromUser listener?.onProgressChanged(value, isFromUser()) updateValueText() } } private fun isFromUser() = verticalSeekBar.fromUser constructor(context: Context, band: Float) : super(context) { init(context, band) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(context, 0f) } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private fun init(context: Context, band: Float) { LayoutInflater.from(context).inflate(R.layout.equalizer_bar, this, true) verticalSeekBar = findViewById(R.id.equalizer_seek) //Force LTR to fix VerticalSeekBar background problem with RTL layout verticalSeekBar.layoutDirection = View.LAYOUT_DIRECTION_LTR verticalSeekBar.max = 2 * RANGE verticalSeekBar.progress = RANGE verticalSeekBar.setOnSeekBarChangeListener(seekListener) bandTextView = findViewById(R.id.equalizer_band) bandValueTextView = findViewById(R.id.band_value) bandTextView.text = if (band < 999.5f) (band + 0.5f).toInt().toString() + "Hz" else (band / 1000.0f + 0.5f).toInt().toString() + "kHz" updateValueText() } private fun updateValueText() { val newValue = (verticalSeekBar.progress / 10) - 20 bandValueTextView.text = if (newValue > 0) "+${newValue}dB" else "${newValue}dB" } fun setValue(value: Float) { verticalSeekBar.progress = (value * PRECISION + RANGE).toInt() updateValueText() } fun setListener(listener: OnEqualizerBarChangeListener?) { this.listener = listener } fun setProgress(fl: Int) { verticalSeekBar.progress = fl updateValueText() } fun getProgress(): Int = verticalSeekBar.progress companion object { const val PRECISION = 10 const val RANGE = 20 * PRECISION } }
gpl-2.0
70197d35f1e15c60cb00bc9d865b4681
34.377953
92
0.686401
4.59407
false
false
false
false
GeoffreyMetais/vlc-android
application/television/src/main/java/org/videolan/television/ui/browser/TvAdapterUtils.kt
1
2976
/* * ************************************************************************ * TvAdapterUtils.kt * ************************************************************************* * Copyright © 2020 VLC authors and VideoLAN * Author: Nicolas POMEPUY * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * ************************************************************************** * * */ package org.videolan.television.ui.browser import android.animation.ArgbEvaluator import android.animation.ValueAnimator import android.os.Build import androidx.annotation.RequiresApi import androidx.core.content.ContextCompat import org.videolan.libvlc.util.AndroidUtil import org.videolan.television.ui.FocusableConstraintLayout import org.videolan.vlc.R object TvAdapterUtils { @RequiresApi(Build.VERSION_CODES.LOLLIPOP) fun itemFocusChange(hasFocus: Boolean, itemSize: Int, container: FocusableConstraintLayout, isList: Boolean, listener: () -> Unit) { if (hasFocus) { val growFactor = if (isList) 1.05 else 1.1 var newWidth = (itemSize * growFactor).toInt() if (newWidth % 2 == 1) { newWidth-- } val scale = newWidth.toFloat() / itemSize if (AndroidUtil.isLolliPopOrLater) container.animate().scaleX(scale).scaleY(scale).translationZ(scale) else container.animate().scaleX(scale).scaleY(scale) listener() } else { if (AndroidUtil.isLolliPopOrLater) container.animate().scaleX(1f).scaleY(1f).translationZ(1f) else container.animate().scaleX(1f).scaleY(1f) } if (isList) { val colorFrom = ContextCompat.getColor(container.context, R.color.tv_card_content_dark) val colorTo = ContextCompat.getColor(container.context, R.color.tv_card_content) val colorAnimation = if (hasFocus) ValueAnimator.ofObject(ArgbEvaluator(), colorFrom, colorTo) else ValueAnimator.ofObject(ArgbEvaluator(), colorTo, colorFrom) colorAnimation.duration = 250 // milliseconds colorAnimation.addUpdateListener { animator -> container.setBackgroundColor(animator.animatedValue as Int) } colorAnimation.start() } } }
gpl-2.0
c2ddc3533e95361d5713919a764db553
40.915493
171
0.63395
4.837398
false
false
false
false
JVMDeveloperID/kotlin-android-example
app/src/main/kotlin/com/gojek/sample/kotlin/internal/data/local/RealmManagers.kt
1
1299
package com.gojek.sample.kotlin.internal.data.local import com.gojek.sample.kotlin.internal.data.local.dao.ContactDao import com.gojek.sample.kotlin.internal.data.local.dao.ContactsDao import com.gojek.sample.kotlin.internal.data.local.model.Contact import com.gojek.sample.kotlin.internal.data.local.model.Contacts import com.gojek.sample.kotlin.internal.data.local.realm.ContactRealm import com.gojek.sample.kotlin.internal.data.local.realm.ContactsRealm class RealmManagers { internal fun saveOrUpdateContacts(contacts: Contacts) { val data: ContactsRealm = ContactsRealm() val dao: ContactsDao = ContactsDao() data.fill(contacts) dao.saveOrUpdate(data) } internal fun getAllContacts(): List<ContactsRealm> = ContactsDao().findAll() internal fun deleteContacts() { val dao: ContactsDao = ContactsDao() dao.delete() } internal fun saveOrUpdateContact(contact: Contact) { val data: ContactRealm = ContactRealm() val dao: ContactDao = ContactDao() data.fill(contact) dao.saveOrUpdate(data) } internal fun getContactById(id: Int?): ContactRealm? = ContactDao().findById(id) internal fun deleteContact() { val dao: ContactDao = ContactDao() dao.delete() } }
apache-2.0
2e1ab5879f3bc3cda58d66486bc1e08c
32.333333
84
0.714396
4.12381
false
false
false
false
bravelocation/yeltzland-android
app/src/main/java/com/bravelocation/yeltzlandnew/tweet/Tweet.kt
1
1132
package com.bravelocation.yeltzlandnew.tweet import com.google.gson.annotations.SerializedName import java.util.* class Tweet : DisplayTweet { @SerializedName("id_str") var id: String? = null @SerializedName("full_text") override var fullText: String? = null @SerializedName("user") override var user: User? = null @SerializedName("created_at") override var createdDate: Date? = null @SerializedName("entities") override var entities: Entities? = null @SerializedName("extended_entities") override var extendedEntities: ExtendedEntities? = null @SerializedName("retweeted_status") var retweet: Retweet? = null @SerializedName("quoted_status") var quotedTweet: QuotedTweet? = null override val isRetweet: Boolean get() = retweet != null override fun quote(): QuotedTweet? { return quotedTweet } override fun userTwitterUrl(): String { return "https://twitter.com/" + user?.screenName } override fun bodyTwitterUrl(): String { return "https://twitter.com/" + user?.screenName + "/status/" + id } }
mit
fafe80a0377f9d27cd97def9f3c698c0
24.177778
74
0.670495
4.456693
false
false
false
false
ExMCL/ExMCL
ExMCL Mod Installer/src/main/kotlin/com/n9mtq4/exmcl/modinstaller/data/ModData.kt
1
3882
/* * MIT License * * Copyright (c) 2016 Will (n9Mtq4) Bresnahan * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.n9mtq4.exmcl.modinstaller.data import com.n9mtq4.exmcl.modinstaller.utils.msg import com.n9mtq4.exmcl.modinstaller.utils.readModDataFromFile import com.n9mtq4.exmcl.modinstaller.utils.writeToFile import com.n9mtq4.kotlin.extlib.syntax.def import net.minecraft.launcher.profile.ProfileManager import java.io.File import java.io.IOException import java.util.ArrayList import javax.swing.JOptionPane /** * Created by will on 2/14/16 at 10:10 PM. * * @author Will "n9Mtq4" Bresnahan */ class ModData(val profiles: ProfileList, var selectedProfileIndex: Int) { private typealias ProfileList = ArrayList<ModProfile> companion object { private const val MOD_LOCATION = "data/jarmods.json.lzma" } object Loader { fun load(): ModData { // return createNewModData() val file = File(MOD_LOCATION) if (!file.exists()) return createNewModData() try { val modData: ModData = readModDataFromFile(file) if (modData.selectedProfileIndex == -1) modData.selectedProfileIndex = 0 //hotfix return modData }catch (e: Exception) { e.printStackTrace() msg(null, "There was an error loading the ModData.\n" + "We are generating a new one.", "Error", JOptionPane.ERROR_MESSAGE) return createNewModData() } } private fun createNewModData() = def { val modData = ModData() val defaultProfile = ModProfile("Default") modData.addProfile(defaultProfile) modData.selectedProfileIndex = 0 modData } } constructor(): this(ProfileList(), 0) @Throws(IOException::class) fun save() = save(File(MOD_LOCATION)) @Throws(IOException::class) private fun save(file: File) { file.parentFile.mkdirs() writeToFile(file) } fun containsProfileByName(name: String) = profiles.filter { it.profileName == name }.isNotEmpty() fun getSelectedProfile() = def { if (selectedProfileIndex == -1) selectedProfileIndex = 0 profiles[selectedProfileIndex] } fun addProfile(profile: ModProfile) = profiles.add(profile) fun getProfileByName(name: String) = profiles.find { it.profileName == name } fun getProfileNames() = profiles.map { it.profileName } fun removeProfile(profileIndex: Int) = profiles.removeAt(profileIndex) fun removeProfile(modProfile: ModProfile) = profiles.remove(modProfile) fun removeProfileByName(name: String) = profiles.filter { it.profileName == name }.forEach { profiles.remove(it) } fun syncWithProfileManager(profileManager: ProfileManager) { // adds any new profiles profileManager.profiles.filterNot { containsProfileByName(it.key) }.forEach { addProfile(ModProfile(it.key)) } // deletes any old profiles profiles.filter { profileManager.profiles[it.profileName] == null }.forEach { removeProfile(it) } } }
mit
3d930d13cab4d031d4fa1a5be3ea6c84
34.290909
115
0.743946
3.772595
false
false
false
false
cout970/Magneticraft
ignore/test/integration/jei/crushingtable/CrushingTableRecipeWrapper.kt
2
1251
package integration.jei.crushingtable import com.cout970.magneticraft.api.registries.machines.crushingtable.ICrushingTableRecipe import mezz.jei.api.ingredients.IIngredients import mezz.jei.api.recipe.IRecipeWrapper import net.minecraft.client.Minecraft import net.minecraftforge.fluids.FluidStack /** * Created by cout970 on 23/07/2016. */ class CrushingTableRecipeWrapper(val recipe : ICrushingTableRecipe) : IRecipeWrapper { override fun getIngredients(ingredients: IIngredients?) {} override fun drawAnimations(minecraft: Minecraft, recipeWidth: Int, recipeHeight: Int) = Unit override fun drawInfo(minecraft: Minecraft, recipeWidth: Int, recipeHeight: Int, mouseX: Int, mouseY: Int) = Unit override fun getTooltipStrings(mouseX: Int, mouseY: Int): MutableList<String>? = mutableListOf() override fun getFluidInputs(): MutableList<FluidStack>? = mutableListOf() override fun handleClick(minecraft: Minecraft, mouseX: Int, mouseY: Int, mouseButton: Int): Boolean = false override fun getOutputs(): MutableList<Any?>? = mutableListOf(recipe.output) override fun getFluidOutputs(): MutableList<FluidStack>? = mutableListOf() override fun getInputs(): MutableList<Any?>? = mutableListOf(recipe.input) }
gpl-2.0
dc64d88b287d04cec79ae68c68b75068
39.387097
117
0.776978
4.34375
false
false
false
false
olonho/carkot
server/src/main/java/algorithm/RoomBypassingAlgorithm.kt
1
12912
package algorithm import Logger import Logger.log import SonarRequest import algorithm.geometry.* import objects.Car import roomScanner.CarController.Direction.* class RoomBypassingAlgorithm(thisCar: Car) : AbstractAlgorithm(thisCar) { override val ATTEMPTS: Int = 5 override val SMOOTHING = SonarRequest.Smoothing.MEDIAN override val WINDOW_SIZE = 3 private val MAX_DISTANCE_TO_WALL_AHEAD = 55 // reached the corner and should turn left private val OUTER_CORNER_DISTANCE_THRESHOLD = 90 // reached outer corner private val ISOSCALENESS_MIN_DIFF = 5 // have to correct alignment to the wall private val ISOSCALENESS_MAX_DIFF = 50 // almost reached outer corner but not yet, and 120 meas. founds far wall private val DISTANCE_TO_WALL_UPPER_BOUND = 60 // have to move closer to the parallel wall private val DISTANCE_TO_WALL_LOWER_BOUND = 40 // have to move farther to the parallel wall private val ECHO_REFLECTION_DIFF = 70 // we're approaching corner and get spurious reflection from two walls on 60 meas. ! Should be before outer corner case ! private val RANGE_FROM_ZERO_POINT_TO_FINISH_ALG = 50 private var calibrateAfterRotate = false private var isCompleted = false private var circleFound = false private fun noOrthogonalMeasurementFound(anglesDistances: Map<Angle, AngleData>): RouteData { val wallAngle = calculateAngle(anglesDistances) Logger.indent() thisCar.angle = (RoomModel.walls.last().wallAngleOX.degs() - wallAngle.degs()).toDouble() addWall(-wallAngle) Logger.outDent() calibrateAfterRotate = true return RouteData( getIntArray(20, wallAngle.degs(), 75), arrayOf(FORWARD, RIGHT, FORWARD)) } private fun wallAheadFound(anglesDistances: Map<Angle, AngleData>): RouteData { val wallAngle = calculateAngle(anglesDistances) thisCar.angle = (RoomModel.walls.last().wallAngleOX.degs() + wallAngle.degs()).toDouble() addWall(wallAngle) calibrateAfterRotate = true return RouteData(getIntArray(wallAngle.degs(), 15), arrayOf(LEFT, FORWARD)) } private fun tryAlignParallelToWall(anglesDistances: Map<Angle, AngleData>, average: Double): RouteData? { for (i in 0..15 step 5) { val distRightForward = anglesDistances[Angle(70 + i)]!! val distRightBackward = anglesDistances[Angle(110 - i)]!! if (distRightBackward.distance == -1 || distRightForward.distance == -1) { log("Found -1 in angle distances, passing") continue } if (distRightBackward.distance > (average * 1.5) || distRightForward.distance > (average * 1.5) || distRightBackward.distance < (average / 2) || distRightForward.distance < (average / 2)) { continue } if (Math.abs(distRightForward.distance - distRightBackward.distance) <= ISOSCALENESS_MIN_DIFF) { return null } log("Flaw in align found, correcting") val rotationDirection = if (distRightBackward.distance > distRightForward.distance) LEFT else RIGHT return RouteData( getIntArray(Math.min(Math.abs(distRightBackward.distance - distRightForward.distance), 20)), arrayOf(rotationDirection)) } return null } private fun correctDistanceToParallelWall(anglesDistances: Map<Angle, AngleData>): RouteData { val distToWall = anglesDistances[Angle(90)]!!.distance val rotationDirection = if (distToWall > DISTANCE_TO_WALL_UPPER_BOUND) RIGHT else LEFT val backRotationDirection = if (rotationDirection == RIGHT) LEFT else RIGHT val rangeToCorridor = if (distToWall > DISTANCE_TO_WALL_UPPER_BOUND) { distToWall - DISTANCE_TO_WALL_UPPER_BOUND } else { DISTANCE_TO_WALL_LOWER_BOUND - distToWall } return RouteData(getIntArray(2 * rangeToCorridor + 5, 20, (1.5 * rangeToCorridor).toInt()), arrayOf(rotationDirection, FORWARD, backRotationDirection)) } private fun moveForward(distToWall: Int): RouteData { return RouteData(getIntArray(Math.max(distToWall / 4, 20)), arrayOf(FORWARD)) } private fun addWall(angleWithPrevWall: Angle) { log("Adding wall") Logger.indent() updateWalls() Logger.outDent() val firstWall = RoomModel.walls.first() val lastWall = RoomModel.walls.last() if (circleFound) { log("Found circle, finishing algorithm") isCompleted = true RoomModel.finished = true val intersectionPoint = firstWall.rawPoints.last() intersectionPoint.y = lastWall.rawPoints.first().y lastWall.pushBackPoint(intersectionPoint) lastWall.markAsFinished() RoomModel.walls.removeAt(0) } else { RoomModel.walls.add(Wall(lastWall.wallAngleOX + angleWithPrevWall)) } } private fun updateWalls() { synchronized(RoomModel) { val walls = RoomModel.walls if (walls.size < 2) { // no walls to intersect return } val line1 = walls.last().line val line2 = walls[RoomModel.walls.size - 2].line val intersection: Point = line1.intersect(line2) val lastWall = walls[RoomModel.walls.size - 1] lastWall.pushFrontPoint(intersection) if (lastWall.isHorizontal()) { lastWall.line = Line(0.0, 1.0, -intersection.y) } else if (lastWall.isVertical()) { lastWall.line = Line(1.0, 0.0, -intersection.x) } walls[walls.size - 2].pushBackPoint(intersection) walls[walls.size - 2].markAsFinished() } } override fun getCommand(anglesDistances: Map<Angle, AngleData>): RouteData? { val dist0 = anglesDistances[Angle(0)]!! val dist70 = anglesDistances[Angle(70)]!! val dist80 = anglesDistances[Angle(80)]!! val dist90 = anglesDistances[Angle(90)]!! val dist100 = anglesDistances[Angle(100)]!! val sonarAngle = (thisCar.angle - 90).toInt() if (anglesDistances.filter { it.value.angle.degs() >= 60 && it.value.angle.degs() <= 120 && it.value.distance == -1 }.size > anglesDistances.size / 2) { log("Found to many -1 in angle distances, falling back") rollback() //todo Теоретически такая ситуация может быть валидной, если сразу после внутреннего угла идёт внешний return null } val average = (anglesDistances.values .filter { it.angle.degs() >= 60 && it.angle.degs() <= 120 } .filter { it.distance != -1 } .sumByDouble { it.distance.toDouble() }) / anglesDistances.values.size log("Estimated average = $average") log("1. Checking if we just rotated and should re-calibrate") if (calibrateAfterRotate) { log("Calibrating after rotate") Logger.indent() val maybeAlignment = tryAlignParallelToWall(anglesDistances, average) Logger.outDent() if (maybeAlignment != null) { log("Realigning") return maybeAlignment } log("No need to realign") calibrateAfterRotate = false } log("") // Check most basic measurements: 60/90/120 log("2. Check if we have measurement on 90") if (dist90.distance == -1 || dist90.distance > OUTER_CORNER_DISTANCE_THRESHOLD) { log("No orthogonal measurement found") return noOrthogonalMeasurementFound(anglesDistances) } log("") // Add point to room map val point = Point( x = thisCar.x + dist90.distance * Math.cos(Angle(sonarAngle).rads()), y = thisCar.y + dist90.distance * Math.sin(Angle(sonarAngle).rads()) ) log("Adding middle point ${point.toString()} to wall ${RoomModel.walls.last()}") RoomModel.walls.last().pushBackPoint(point) log("") // Check if corner reached log("3. Check if we reached corner, dist0 = ${dist0.distance}") if (dist0.distance != -1 && dist0.distance < MAX_DISTANCE_TO_WALL_AHEAD) { log("Wall ahead found") return wallAheadFound(anglesDistances) } log("") log("Adding other points") for (i in 70..110 step 10) { if (i == 90) { continue // point on 90 was already added } val curDist = anglesDistances[Angle(i)]!!.distance if (curDist > (average * 1.5) || curDist < (average / 2)) { log("For point on ${i} dist = ${curDist}, while window is from ${average * 1.5} till ${average * 2}. Dropping it as outlier") continue } val point = Point( x = thisCar.x + curDist * Math.cos(Angle((thisCar.angle - i).toInt()).rads()), y = thisCar.y + curDist * Math.sin(Angle((thisCar.angle - i).toInt()).rads()) ) log("Adding ${point.toString()} to wall ${RoomModel.walls.last()}") RoomModel.walls.last().pushBackPoint(point) } log("") // Try align parallel to wall log("4. Check if we have to align parallel to the wall") Logger.indent() val maybeAlignment = tryAlignParallelToWall(anglesDistances, average) Logger.outDent() if (maybeAlignment != null) { log("Realigning") return maybeAlignment } log("") // Check if wall is too close or too far log("5. Check if we have to move closer or farther to the wall") if (dist90.distance > DISTANCE_TO_WALL_UPPER_BOUND || dist90.distance < DISTANCE_TO_WALL_LOWER_BOUND) { log("Flaw in distance to the parallel wall found, correcting") return correctDistanceToParallelWall(anglesDistances) } log("") // Approaching inner corner and getting spurious reflection from 2 walls on 60; // Just move forward to get closer to the corner; log("6. Check if we are detecting echo reflections approaching inner corner") if (dist70.distance - dist0.distance > ECHO_REFLECTION_DIFF) { log("Echo reflection detected, moving forward") return moveForward(dist0.distance) } log("") // Approaching outer corner (parallel wall is ending soon, but not yet); // Just move forward to get to the end of the wall log("7. Check if we are detecting far wall approaching outer corner") if (dist80.distance == -1 || Math.abs(dist100.distance - dist80.distance) > ISOSCALENESS_MAX_DIFF) { log("Approaching outer corner, moving forward") return moveForward(dist0.distance) } log("") // default case: everything is ok, just move forward log("8. Default case: moving forward") return moveForward(dist0.distance) } private fun calculateAngle(anglesDistances: Map<Angle, AngleData>): Angle { // TODO: stub here, make proper angle calculation return Angle(90) } private fun getIntArray(vararg args: Int): IntArray { return args } override fun isCompleted(): Boolean { return isCompleted } override fun afterGetCommand(route: RouteData) { val carAngle = thisCar.angle.toInt() route.distances.forEachIndexed { idx, value -> when (route.directions[idx]) { FORWARD -> { thisCar.x += (Math.cos(Angle(carAngle).rads()) * route.distances[idx]).toInt() thisCar.y += (Math.sin(Angle(carAngle).rads()) * route.distances[idx]).toInt() } BACKWARD -> { thisCar.x -= (Math.cos(Angle(carAngle).rads()) * route.distances[idx]).toInt() thisCar.y -= (Math.sin(Angle(carAngle).rads()) * route.distances[idx]).toInt() } else -> { } } } if (Math.round(Math.cos(Angle(thisCar.angle.toInt()).rads())).toInt() == 1 && thisCar.angle.toInt() != 0 && Vector(thisCar.x.toDouble(), thisCar.y.toDouble()).length() < RANGE_FROM_ZERO_POINT_TO_FINISH_ALG) { log("Found circle!") circleFound = true } } }
mit
50ab9d3bd13383fa4f794dc4d8fbb429
41.77
173
0.595168
4.244128
false
false
false
false
groupdocs-comparison/GroupDocs.Comparison-for-Java
Demos/Micronaut/src/main/kotlin/com/groupdocs/ui/usecase/AreFilesSupportedUseCase.kt
1
1240
package com.groupdocs.ui.usecase import com.groupdocs.ui.util.InternalServerException import io.micronaut.context.annotation.Bean import java.nio.file.Paths import kotlin.io.path.extension @Bean class AreFilesSupportedUseCase { operator fun invoke(sourceFileName: String, targetFileName: String): Boolean { sourceFileName.ifBlank { throw AreFilesSupportedException("Source file name can't be blank") } targetFileName.ifBlank { throw AreFilesSupportedException("Target file name can't be blank") } val sourceExtension = Paths.get(sourceFileName).extension val targetExtension = Paths.get(targetFileName).extension return (sourceExtension == targetExtension && sourceExtension in SUPPORTED_EXTENSIONS) } companion object { val SUPPORTED_EXTENSIONS = listOf( "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf", "png", "txt", "html", "htm", "jpg", "jpeg" ) } } class AreFilesSupportedException(message: String, e: Throwable? = null) : InternalServerException(message, e)
mit
37e21f2a123e570e24075ea2262364d2
27.860465
109
0.612097
4.679245
false
false
false
false
ohmae/WheelColorChooser
src/main/java/net/mm2d/color/ColorUtils.kt
1
5708
/* * Copyright (c) 2014 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.color import kotlin.math.roundToInt /** * HSVやRGBの色空間表現を扱う上でのメソッド */ object ColorUtils { /** * Convert given HSV [0.0f, 1.0f] to RGB FloatArray * * @param h Hue * @param s Saturation * @param v Value * @return RGB FloatArray */ fun hsvToRgb(h: Float, s: Float, v: Float): FloatArray = toRGB(hsvToColor(h, s, v)) /** * Convert given HSV [0.0f, 1.0f] to color * * @param h Hue * @param s Saturation * @param v Value * @return color */ fun hsvToColor(h: Float, s: Float, v: Float): Int { if (s <= 0.0f) return toColor(v, v, v) val hue = h * 6.0f // 計算しやすいように[0.0f, 6.0f]で扱う val i = hue.toInt() // hueの整数部 val f = hue - i // hueの小数部 var r = v var g = v var b = v when (i) { 0 -> { // h:[0.0f, 1.0f) g *= 1 - s * (1 - f) b *= 1 - s } 1 -> { // h:[1.0f, 2.0f) r *= 1 - s * f b *= 1 - s } 2 -> { // h:[2.0f, 3.0f) r *= 1 - s b *= 1 - s * (1 - f) } 3 -> { // h:[3.0f, 4.0f) r *= 1 - s g *= 1 - s * f } 4 -> { // h:[4.0f, 5.0f) r *= 1 - s * (1 - f) g *= 1 - s } 5 -> { // h:[5.0f, 6.0f) g *= 1 - s b *= 1 - s * f } else -> { g *= 1 - s * (1 - f) b *= 1 - s } } return toColor(r, g, b) } fun svToMask(s: Float, v: Float): Int { val a = 1f - (s * v) val g = if (a == 0f) 0f else (v * (1f - s) / a).coerceIn(0f, 1f) return toColor(a, g, g, g) } /** * RGB値をHSV表現に変換する * * @param rgb RGB float配列 * @return HSV float配列 */ fun rgbToHsv(rgb: FloatArray): FloatArray = rgbToHsv(rgb[0], rgb[1], rgb[2]) /** * RGB値をHSV表現に変換する * * @param r R * @param g G * @param b B * @return HSV float配列 */ fun rgbToHsv(r: Float, g: Float, b: Float): FloatArray { val max = max(r, g, b) val min = min(r, g, b) val hsv = FloatArray(3) hsv[0] = hue(r, g, b, max, min) hsv[1] = max - min if (max != 0.0f) { hsv[1] /= max } hsv[2] = max return hsv } private fun max(v1: Float, v2: Float, v3: Float): Float = maxOf(maxOf(v1, v2), v3) private fun min(v1: Float, v2: Float, v3: Float): Float = minOf(minOf(v1, v2), v3) /** * rgbおよびrgbの最大値最小値から色相を計算する * * @param r 赤 * @param g 緑 * @param b 青 * @param max 最大 * @param min 最小 * @return 色相 */ private fun hue(r: Float, g: Float, b: Float, max: Float, min: Float): Float { var hue = max - min if (hue > 0.0f) { if (max == r) { hue = (g - b) / hue if (hue < 0.0f) { hue += 6.0f } } else if (max == g) { hue = 2.0f + (b - r) / hue } else { hue = 4.0f + (r - g) / hue } } hue = (hue / 6.0f).coerceIn(0.0f, 1.0f) return hue } private fun toColor(r: Float, g: Float, b: Float): Int = toColor(r.to8bit(), g.to8bit(), b.to8bit()) private fun toColor(a: Float, r: Float, g: Float, b: Float): Int = toColor(a.to8bit(), r.to8bit(), g.to8bit(), b.to8bit()) private fun toColor(r: Int, g: Int, b: Int): Int = 0xff shl 24 or (0xff and r shl 16) or (0xff and g shl 8) or (0xff and b) private fun toColor(a: Int, r: Int, g: Int, b: Int): Int = 0xff and a shl 24 or (0xff and r shl 16) or (0xff and g shl 8) or (0xff and b) /** * int値で表現されたRGB値をint[3]に変換する。 * α値は無視される。 * * @param color intで表現されたRGB値 * @return RGB int配列 */ fun toRGBInt(color: Int): IntArray = intArrayOf( 0xff and color.ushr(16), 0xff and color.ushr(8), 0xff and color ) /** * int値で表現されたRGB値をfloat[3]に変換する。 * α値は無視される。 * * @param color intで表現されたRGB値 * @return RGB float配列 */ fun toRGB(color: Int): FloatArray = floatArrayOf( color.ushr(16).toRatio(), color.ushr(8).toRatio(), color.toRatio() ) } /** * Overwrite alpha value of color * * @receiver color * @param alpha Alpha * @return alpha applied color */ fun Int.setAlpha(alpha: Float): Int = setAlpha((0xff * alpha.coerceIn(0f, 1f)).toInt()) /** * Overwrite alpha value of color * * @receiver color * @param alpha Alpha * @return alpha applied color */ fun Int.setAlpha(alpha: Int): Int = this and 0xffffff or (alpha shl 24) /** * Convert [0, 255] to [0.0f, 1.0f] * * @receiver [0, 255] * @return [0.0f, 1.0f] */ fun Int.toRatio(): Float = this / 255f /** * Convert [0.0f, 1.0f] to [0, 255] * * @receiver [0.0f, 1.0f] * @return [0, 255] */ fun Float.to8bit(): Int = (this * 255f).roundToInt().coerceIn(0, 255)
mit
9f54a1d94333cb1f514e52438bb7b6db
24.07907
87
0.452708
2.946448
false
false
false
false
ivan-osipov/Clabo
src/main/kotlin/com/github/ivan_osipov/clabo/api/model/Sticker.kt
1
493
package com.github.ivan_osipov.clabo.api.model import com.google.gson.annotations.SerializedName class Sticker : AbstractFileDescriptor() { @SerializedName("width") private var _width: Int? = null val width: Int get() = _width!! @SerializedName("height") private var _height: Int? = null val height: Int get() = _height!! @SerializedName("thumb") var thumb: PhotoSize? = null @SerializedName("emoji") var emoji: String? = null }
apache-2.0
32aada8e0f9db75c7b9c080529b6d8de
18.76
49
0.64503
4.00813
false
false
false
false
openstreetview/android
app/src/main/java/com/telenav/osv/data/collector/phonedata/service/ServiceHandler.kt
1
27469
package com.telenav.osv.data.collector.phonedata.service import android.content.Context import android.os.* import com.telenav.osv.data.collector.datatype.util.LibraryUtil import com.telenav.osv.data.collector.phonedata.collector.* import com.telenav.osv.data.collector.phonedata.manager.PhoneDataListener import timber.log.Timber class ServiceHandler internal constructor(looper: Looper?, private val context: Context?) : Handler(looper) { private var accelerometerCollector: AccelerometerCollector? = null private var linearAccelerationCollector: LinearAccelerationCollector? = null private var gyroCollector: GyroCollector? = null private var compassCollector: CompassCollector? = null private var headingCollector: HeadingCollector? = null private var pressureCollector: PressureCollector? = null private var gravityCollector: GravityCollector? = null private var rotationVectorCollector: RotationVectorCollector? = null private var gameRotationVectorCollector: GameRotationVectorCollector? = null private var temperatureCollector: TemperatureCollector? = null private var lightCollector: LightCollector? = null private var stepCounterCollector: StepCounterCollector? = null private var proximityCollector: ProximityCollector? = null private var humidityCollector: HumidityCollector? = null private var gpsCollector: GPSCollector? = null private var batteryCollector: BatteryCollector? = null private var wifiCollector: WifiCollector? = null private var mobileDataCollector: MobileDataCollector? = null private var hardwareInfoCollector: HardwareInfoCollector? = null private var osInfoCollector: OSInfoCollector? = null private var deviceIDCollector: DeviceIDCollector? = null private var applicationIDCollector: ApplicationIDCollector? = null private var clientAppNameCollector: ClientAppNameCollector? = null private var clientAppVersionCollector: ClientAppVersionCollector? = null /** * handler thread used for moving phone sensor collection off the UI thread */ private val phoneHandlerThread: HandlerThread = HandlerThread("PhoneHandlerThread") /** * Default frequency for phone sensors */ private val defaultFrequency = 0 private var phoneDataListener: PhoneDataListener? = null override fun handleMessage(msg: Message) { val bundle = msg.data if (bundle != null && !bundle.isEmpty) { handleSensorOperation(bundle) } } /** * Sets the data listener in order to be able to notify about updates * when a sensor event occurs * * @param phoneDataListener The listener that has to be notified */ fun setDataListener(phoneDataListener: PhoneDataListener?) { this.phoneDataListener = phoneDataListener } fun cleanup() { unregisterAllSensors() phoneHandlerThread.quit() } /** * Unregisters all registered sensors */ fun unregisterAllSensors() { if (accelerometerCollector != null) { accelerometerCollector!!.unregisterListener() } if (linearAccelerationCollector != null) { linearAccelerationCollector!!.unregisterListener() } if (compassCollector != null) { compassCollector!!.unregisterListener() } if (gpsCollector != null) { gpsCollector!!.unregisterListener() } if (gravityCollector != null) { gravityCollector!!.unregisterListener() } if (gyroCollector != null) { gyroCollector!!.unregisterListener() } if (humidityCollector != null) { humidityCollector!!.unregisterListener() } if (headingCollector != null) { headingCollector!!.unregisterListener() } if (lightCollector != null) { lightCollector!!.unregisterListener() } if (pressureCollector != null) { pressureCollector!!.unregisterListener() } if (proximityCollector != null) { proximityCollector!!.unregisterListener() } if (rotationVectorCollector != null) { rotationVectorCollector!!.unregisterListener() } if (gameRotationVectorCollector != null) { gameRotationVectorCollector!!.unregisterListener() } if (stepCounterCollector != null) { stepCounterCollector!!.unregisterListener() } if (temperatureCollector != null) { temperatureCollector!!.unregisterListener() } if (batteryCollector != null) { batteryCollector!!.unregisterReceiver() } if (wifiCollector != null) { wifiCollector!!.unregisterReceiver() } } /** * Handles a later sensor registration/unregistration or a later frequency setting * * @param b The data sent from the client */ private fun handleSensorOperation(b: Bundle) { val operation = b.getString(LibraryUtil.SENSOR_OPERATION_TAG) if (operation != null) { when (operation) { LibraryUtil.REGISTER_SENSOR_TAG -> handleSensorsRegistration(b) LibraryUtil.SET_FREQUENCY_TAG -> handleSensorsFrequency(b) LibraryUtil.UNREGISTER_SENSOR_TAG -> handleSensorsUnregistration(b) else -> Timber.tag(TAG).e("Unknown sensor operation!") } } } /** * Handles later registration of sensors from client * * @param bundle The data sent from the client */ private fun handleSensorsRegistration(bundle: Bundle?) { if (bundle != null) { registerSensors(bundle.getStringArray(LibraryUtil.SENSOR_TYPE_TAG), bundle.getSerializable(LibraryUtil.FREQUENCY_TAG) as Map<String, Int>) } } /** * Handles later frequency setting from client * * @param bundle The data sent from the client */ private fun handleSensorsFrequency(bundle: Bundle) { val sensortype = bundle.getString(LibraryUtil.SENSOR_TYPE_TAG) val frequency = bundle.getInt(LibraryUtil.FREQUENCY_TAG) sensortype?.let { setFrequency(it, frequency) } } /** * Handles later unregistration of sensors from client * * @param bundle The data sent from the client */ private fun handleSensorsUnregistration(bundle: Bundle) { val sensorsType = bundle.getStringArray(LibraryUtil.SENSOR_TYPE_TAG) if (sensorsType != null) { for (sensor in sensorsType) { unregisterSensor(sensor) } } } /** * Iterates an array of strings in order to register the sensors that should * be collected * * @param sensors String array with sensors that has to be registered * @param sensorsFrequency Map used to extract the registered frequency for each sensor */ private fun registerSensors(sensors: Array<String>?, sensorsFrequency: Map<String, Int>?) { if (sensors != null && sensors.size > 0 && !sensors[0].isEmpty() && context != null) { for (sensor in sensors) { var frequency = 0 if (sensorsFrequency != null) { frequency = sensorsFrequency[sensor]!! } registerSensor(sensor, frequency) } } } /** * Registers a specific sensor at the specified frequency * * @param sensor The sensor that should be registered * @param frequency The desired frequency of the sensor */ private fun registerSensor(sensor: String, frequency: Int) { when (sensor) { LibraryUtil.ACCELEROMETER -> { if (accelerometerCollector == null) { accelerometerCollector = AccelerometerCollector(phoneDataListener, this) } accelerometerCollector!!.registerAccelerometerListener(context!!, frequency) } LibraryUtil.LINEAR_ACCELERATION -> { if (linearAccelerationCollector == null) { linearAccelerationCollector = LinearAccelerationCollector(phoneDataListener, this) } linearAccelerationCollector!!.registerLinearAccelerationListener(context!!, frequency) } LibraryUtil.GYROSCOPE -> { if (gyroCollector == null) { gyroCollector = GyroCollector(phoneDataListener, this) } gyroCollector!!.registerGyroListener(context!!, frequency) } LibraryUtil.GRAVITY -> { if (gravityCollector == null) { gravityCollector = GravityCollector(phoneDataListener, this) } gravityCollector!!.registerGravityListener(context!!, frequency) } LibraryUtil.PHONE_GPS_ACCURACY, LibraryUtil.PHONE_GPS_ALTITUDE, LibraryUtil.PHONE_GPS_BEARING, LibraryUtil.PHONE_GPS_SPEED, LibraryUtil.PHONE_GPS, LibraryUtil.GPS_DATA, LibraryUtil.NMEA_DATA -> { if (gpsCollector == null) { gpsCollector = GPSCollector(phoneDataListener, this) } gpsCollector!!.registerLocationListener(context!!) } LibraryUtil.HUMIDITY -> { if (humidityCollector == null) { humidityCollector = HumidityCollector(phoneDataListener, this) } humidityCollector!!.registerHumiditytListener(context!!, frequency) } LibraryUtil.HEADING -> { if (headingCollector == null) { headingCollector = HeadingCollector(phoneDataListener, this) } headingCollector!!.registerHeadingListener(context!!, frequency) } LibraryUtil.LIGHT -> { if (lightCollector == null) { lightCollector = LightCollector(phoneDataListener, this) } lightCollector!!.registerLightListener(context!!, frequency) } LibraryUtil.MAGNETIC -> { if (compassCollector == null) { compassCollector = CompassCollector(phoneDataListener, this) } compassCollector!!.registerCompassListener(context!!, frequency) } LibraryUtil.PRESSURE -> { if (pressureCollector == null) { pressureCollector = PressureCollector(phoneDataListener, this) } pressureCollector!!.registerPressureListener(context!!, frequency) } LibraryUtil.PROXIMITY -> { if (proximityCollector == null) { proximityCollector = ProximityCollector(phoneDataListener, this) } proximityCollector!!.registerProximityListener(context!!, frequency) } LibraryUtil.ROTATION_VECTOR_NORTH_REFERENCE -> { if (rotationVectorCollector == null) { rotationVectorCollector = RotationVectorCollector(phoneDataListener, this) } rotationVectorCollector!!.registerRotationVectorListener(context!!, frequency) } LibraryUtil.ROTATION_VECTOR_RAW -> { if (gameRotationVectorCollector == null) { gameRotationVectorCollector = GameRotationVectorCollector(phoneDataListener, this) } gameRotationVectorCollector!!.registerGameRotationVectorListener(context!!, frequency) } LibraryUtil.STEP_COUNT -> { if (stepCounterCollector == null) { stepCounterCollector = StepCounterCollector(phoneDataListener, this) } stepCounterCollector!!.registerStepCounterListener(context!!, frequency) } LibraryUtil.TEMPERATURE -> { if (temperatureCollector == null) { temperatureCollector = TemperatureCollector(phoneDataListener, this) } temperatureCollector!!.registerTemperatureListener(context!!, frequency) } LibraryUtil.BATTERY -> { if (batteryCollector == null) { batteryCollector = BatteryCollector(context!!, phoneDataListener, this) } batteryCollector!!.startCollectingBatteryData() } LibraryUtil.HARDWARE_TYPE -> { if (hardwareInfoCollector == null) { hardwareInfoCollector = HardwareInfoCollector(phoneDataListener, this) } hardwareInfoCollector!!.sendHardwareInformation() } LibraryUtil.OS_INFO -> { if (osInfoCollector == null) { osInfoCollector = OSInfoCollector(phoneDataListener, this) } osInfoCollector!!.sendOSInformation() } LibraryUtil.DEVICE_ID -> { if (deviceIDCollector == null) { deviceIDCollector = DeviceIDCollector(phoneDataListener, this) } deviceIDCollector!!.sendDeviceID(context!!) } LibraryUtil.APPLICATION_ID -> { if (applicationIDCollector == null) { applicationIDCollector = ApplicationIDCollector(phoneDataListener, this) } applicationIDCollector!!.sendApplicationID(context!!) } LibraryUtil.CLIENT_APP_NAME -> { if (clientAppNameCollector == null) { clientAppNameCollector = ClientAppNameCollector(phoneDataListener, this) } clientAppNameCollector!!.sendClientAppName(context!!) } LibraryUtil.CLIENT_APP_VERSION -> { if (clientAppVersionCollector == null) { clientAppVersionCollector = ClientAppVersionCollector(phoneDataListener, this) } clientAppVersionCollector!!.sendClientVersion(context) } LibraryUtil.MOBILE_DATA -> { if (mobileDataCollector == null) { mobileDataCollector = MobileDataCollector(context!!, phoneDataListener, this) } mobileDataCollector!!.sendMobileDataInformation() } LibraryUtil.WIFI -> { if (wifiCollector == null) { wifiCollector = WifiCollector(context!!, phoneDataListener, this) } wifiCollector!!.startCollectingWifiData() } else -> Timber.tag(TAG).e(LibraryUtil.INVALID_DATA + " : " + sensor) } } /** * Unregister a sensor * * @param sensor The type of the sensor that has to be unregisterd */ private fun unregisterSensor(sensor: String) { when (sensor) { LibraryUtil.ACCELEROMETER -> if (accelerometerCollector != null) { accelerometerCollector!!.unregisterListener() } LibraryUtil.LINEAR_ACCELERATION -> if (linearAccelerationCollector != null) { linearAccelerationCollector!!.unregisterListener() } LibraryUtil.GYROSCOPE -> if (gyroCollector != null) { gyroCollector!!.unregisterListener() } LibraryUtil.GRAVITY -> if (gravityCollector != null) { gravityCollector!!.unregisterListener() } LibraryUtil.PHONE_GPS_ACCURACY, LibraryUtil.PHONE_GPS_ALTITUDE, LibraryUtil.PHONE_GPS_BEARING, LibraryUtil.PHONE_GPS_SPEED, LibraryUtil.PHONE_GPS -> if (gpsCollector != null) { gpsCollector!!.unregisterListener() } LibraryUtil.HUMIDITY -> if (humidityCollector != null) { humidityCollector!!.unregisterListener() } LibraryUtil.HEADING -> if (headingCollector != null) { headingCollector!!.unregisterListener() } LibraryUtil.LIGHT -> if (lightCollector != null) { lightCollector!!.unregisterListener() } LibraryUtil.MAGNETIC -> if (compassCollector != null) { compassCollector!!.unregisterListener() } LibraryUtil.PRESSURE -> if (pressureCollector != null) { pressureCollector!!.unregisterListener() } LibraryUtil.PROXIMITY -> if (proximityCollector != null) { proximityCollector!!.unregisterListener() } LibraryUtil.ROTATION_VECTOR_NORTH_REFERENCE -> if (rotationVectorCollector != null) { rotationVectorCollector!!.unregisterListener() } LibraryUtil.ROTATION_VECTOR_RAW -> if (gameRotationVectorCollector != null) { gameRotationVectorCollector!!.unregisterListener() } LibraryUtil.STEP_COUNT -> if (stepCounterCollector != null) { stepCounterCollector!!.unregisterListener() } LibraryUtil.TEMPERATURE -> if (temperatureCollector != null) { temperatureCollector!!.unregisterListener() } LibraryUtil.BATTERY -> if (batteryCollector != null) { batteryCollector!!.unregisterReceiver() } LibraryUtil.WIFI -> if (wifiCollector != null) { wifiCollector!!.unregisterReceiver() } LibraryUtil.APPLICATION_ID, LibraryUtil.CLIENT_APP_NAME, LibraryUtil.CLIENT_APP_VERSION, LibraryUtil.DEVICE_ID, LibraryUtil.HARDWARE_TYPE, LibraryUtil.MOBILE_DATA, LibraryUtil.OS_INFO -> { } else -> Timber.tag(TAG).e("The sensor $sensor is not valid") } } /** * Set sensor frequency * * @param type The type of the sensor that has to be unregisterd */ private fun setFrequency(type: String, frequency: Int) { when (type) { LibraryUtil.ACCELEROMETER -> if (accelerometerCollector != null && context != null) { accelerometerCollector!!.unregisterListener() accelerometerCollector!!.registerAccelerometerListener(context, frequency) } LibraryUtil.LINEAR_ACCELERATION -> if (linearAccelerationCollector != null && context != null) { linearAccelerationCollector!!.unregisterListener() linearAccelerationCollector!!.registerLinearAccelerationListener(context, frequency) } LibraryUtil.GYROSCOPE -> if (gyroCollector != null && context != null) { gyroCollector!!.unregisterListener() gyroCollector!!.registerGyroListener(context, frequency) } LibraryUtil.GRAVITY -> if (gravityCollector != null && context != null) { gravityCollector!!.unregisterListener() gravityCollector!!.registerGravityListener(context, frequency) } LibraryUtil.HUMIDITY -> if (humidityCollector != null && context != null) { humidityCollector!!.unregisterListener() humidityCollector!!.registerHumiditytListener(context, frequency) } LibraryUtil.HEADING -> if (headingCollector != null && context != null) { headingCollector!!.unregisterListener() headingCollector!!.registerHeadingListener(context, frequency) } LibraryUtil.LIGHT -> if (lightCollector != null && context != null) { lightCollector!!.unregisterListener() lightCollector!!.registerLightListener(context, frequency) } LibraryUtil.MAGNETIC -> if (compassCollector != null && context != null) { compassCollector!!.unregisterListener() compassCollector!!.registerCompassListener(context, frequency) } LibraryUtil.PRESSURE -> if (pressureCollector != null && context != null) { pressureCollector!!.unregisterListener() pressureCollector!!.registerPressureListener(context, frequency) } LibraryUtil.PROXIMITY -> if (proximityCollector != null && context != null) { proximityCollector!!.unregisterListener() proximityCollector!!.registerProximityListener(context, frequency) } LibraryUtil.ROTATION_VECTOR_NORTH_REFERENCE -> if (rotationVectorCollector != null && context != null) { rotationVectorCollector!!.unregisterListener() rotationVectorCollector!!.registerRotationVectorListener(context, frequency) } LibraryUtil.ROTATION_VECTOR_RAW -> if (gameRotationVectorCollector != null && context != null) { gameRotationVectorCollector!!.unregisterListener() gameRotationVectorCollector!!.registerGameRotationVectorListener(context, frequency) } LibraryUtil.STEP_COUNT -> if (stepCounterCollector != null && context != null) { stepCounterCollector!!.unregisterListener() stepCounterCollector!!.registerStepCounterListener(context, frequency) } LibraryUtil.TEMPERATURE -> if (temperatureCollector != null && context != null) { temperatureCollector!!.unregisterListener() temperatureCollector!!.registerTemperatureListener(context, frequency) } else -> Timber.tag(TAG).e("The sensor $type is not valid") } } /** * Register all sensors with a default frequency */ private fun registerAllSensors() { if (context != null) { if (accelerometerCollector == null) { accelerometerCollector = AccelerometerCollector(phoneDataListener, this) } if (linearAccelerationCollector == null) { linearAccelerationCollector = LinearAccelerationCollector(phoneDataListener, this) } if (gyroCollector == null) { gyroCollector = GyroCollector(phoneDataListener, this) } if (compassCollector == null) { compassCollector = CompassCollector(phoneDataListener, this) } if (headingCollector == null) { headingCollector = HeadingCollector(phoneDataListener, this) } if (pressureCollector == null) { pressureCollector = PressureCollector(phoneDataListener, this) } if (gravityCollector == null) { gravityCollector = GravityCollector(phoneDataListener, this) } if (rotationVectorCollector == null) { rotationVectorCollector = RotationVectorCollector(phoneDataListener, this) } if (gameRotationVectorCollector == null) { gameRotationVectorCollector = GameRotationVectorCollector(phoneDataListener, this) } if (temperatureCollector == null) { temperatureCollector = TemperatureCollector(phoneDataListener, this) } if (lightCollector == null) { lightCollector = LightCollector(phoneDataListener, this) } if (stepCounterCollector == null) { stepCounterCollector = StepCounterCollector(phoneDataListener, this) } if (proximityCollector == null) { proximityCollector = ProximityCollector(phoneDataListener, this) } if (humidityCollector == null) { humidityCollector = HumidityCollector(phoneDataListener, this) } if (gpsCollector == null) { gpsCollector = GPSCollector(phoneDataListener, this) } if (batteryCollector == null) { batteryCollector = BatteryCollector(context, phoneDataListener, this) } if (wifiCollector == null) { wifiCollector = WifiCollector(context, phoneDataListener, this) } if (mobileDataCollector == null) { mobileDataCollector = MobileDataCollector(context, phoneDataListener, this) } if (hardwareInfoCollector == null) { hardwareInfoCollector = HardwareInfoCollector(phoneDataListener, this) } if (osInfoCollector == null) { osInfoCollector = OSInfoCollector(phoneDataListener, this) } if (deviceIDCollector == null) { deviceIDCollector = DeviceIDCollector(phoneDataListener, this) } if (applicationIDCollector == null) { applicationIDCollector = ApplicationIDCollector(phoneDataListener, this) } if (clientAppNameCollector == null) { clientAppNameCollector = ClientAppNameCollector(phoneDataListener, this) } if (clientAppVersionCollector == null) { clientAppVersionCollector = ClientAppVersionCollector(phoneDataListener, this) } accelerometerCollector!!.registerAccelerometerListener(context, defaultFrequency) linearAccelerationCollector!!.registerLinearAccelerationListener(context, defaultFrequency) gyroCollector!!.registerGyroListener(context, defaultFrequency) compassCollector!!.registerCompassListener(context, defaultFrequency) headingCollector!!.registerHeadingListener(context, defaultFrequency) pressureCollector!!.registerPressureListener(context, defaultFrequency) gravityCollector!!.registerGravityListener(context, defaultFrequency) rotationVectorCollector!!.registerRotationVectorListener(context, defaultFrequency) gameRotationVectorCollector!!.registerGameRotationVectorListener(context, defaultFrequency) temperatureCollector!!.registerTemperatureListener(context, defaultFrequency) lightCollector!!.registerLightListener(context, defaultFrequency) stepCounterCollector!!.registerStepCounterListener(context, defaultFrequency) proximityCollector!!.registerProximityListener(context, defaultFrequency) humidityCollector!!.registerHumiditytListener(context, defaultFrequency) batteryCollector!!.startCollectingBatteryData() mobileDataCollector!!.sendMobileDataInformation() hardwareInfoCollector!!.sendHardwareInformation() osInfoCollector!!.sendOSInformation() deviceIDCollector!!.sendDeviceID(context) applicationIDCollector!!.sendApplicationID(context) clientAppNameCollector!!.sendClientAppName(context) clientAppVersionCollector!!.sendClientVersion(context) wifiCollector!!.startCollectingWifiData() gpsCollector!!.registerLocationListener(context) } } companion object { private const val TAG = "PhoneServiceHandler" } init { phoneHandlerThread.start() } }
lgpl-3.0
0344e1768ac063d61417d1df7e108ff4
45.168067
207
0.610324
5.688341
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/BaseFragment.kt
1
4960
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[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 de.vanita5.twittnuker.fragment import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.text.BidiFormatter import com.bumptech.glide.Glide import com.bumptech.glide.RequestManager import com.squareup.otto.Bus import com.twitter.Validator import nl.komponents.kovenant.Promise import okhttp3.Dns import org.mariotaku.restfu.http.RestHttpClient import de.vanita5.twittnuker.fragment.iface.IBaseFragment import de.vanita5.twittnuker.model.DefaultFeatures import de.vanita5.twittnuker.util.* import de.vanita5.twittnuker.util.dagger.GeneralComponent import de.vanita5.twittnuker.util.gifshare.GifShareProvider import de.vanita5.twittnuker.util.premium.ExtraFeaturesService import de.vanita5.twittnuker.util.schedule.StatusScheduleProvider import de.vanita5.twittnuker.util.sync.SyncPreferences import de.vanita5.twittnuker.util.sync.TimelineSyncManager import javax.inject.Inject open class BaseFragment : Fragment(), IBaseFragment<BaseFragment> { // Utility classes @Inject lateinit var twitterWrapper: AsyncTwitterWrapper @Inject lateinit var readStateManager: ReadStateManager @Inject lateinit var bus: Bus @Inject lateinit var multiSelectManager: MultiSelectManager @Inject lateinit var userColorNameManager: UserColorNameManager @Inject lateinit var preferences: SharedPreferences @Inject lateinit var notificationManager: NotificationManagerWrapper @Inject lateinit var bidiFormatter: BidiFormatter @Inject lateinit var errorInfoStore: ErrorInfoStore @Inject lateinit var validator: Validator @Inject lateinit var extraFeaturesService: ExtraFeaturesService @Inject lateinit var defaultFeatures: DefaultFeatures @Inject lateinit var statusScheduleProviderFactory: StatusScheduleProvider.Factory @Inject lateinit var timelineSyncManagerFactory: TimelineSyncManager.Factory @Inject lateinit var gifShareProviderFactory: GifShareProvider.Factory @Inject lateinit var restHttpClient: RestHttpClient @Inject lateinit var dns: Dns @Inject lateinit var syncPreferences: SyncPreferences @Inject lateinit var externalThemeManager: ExternalThemeManager lateinit var requestManager: RequestManager private set protected val statusScheduleProvider: StatusScheduleProvider? get() = statusScheduleProviderFactory.newInstance(context) protected val timelineSyncManager: TimelineSyncManager? get() = timelineSyncManagerFactory.get() protected val gifShareProvider: GifShareProvider? get() = gifShareProviderFactory.newInstance(context) private val actionHelper = IBaseFragment.ActionHelper<BaseFragment>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requestManager = Glide.with(this) } override fun onStart() { super.onStart() requestManager.onStart() } override fun onStop() { requestManager.onStop() super.onStop() } override fun onResume() { super.onResume() actionHelper.dispatchOnResumeFragments(this) } override fun onPause() { actionHelper.dispatchOnPause() super.onPause() } override fun onDestroy() { requestManager.onDestroy() extraFeaturesService.release() super.onDestroy() DebugModeUtils.watchReferenceLeak(this) } override fun onAttach(context: Context) { super.onAttach(context) GeneralComponent.get(context).inject(this) } override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) requestApplyInsets() } override fun executeAfterFragmentResumed(useHandler: Boolean, action: (BaseFragment) -> Unit) : Promise<Unit, Exception> { return actionHelper.executeAfterFragmentResumed(this, useHandler, action) } }
gpl-3.0
6b3a21665f87ed52867b458ea7aecbaa
31.854305
97
0.75121
4.755513
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/Utils.kt
1
25705
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[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 de.vanita5.twittnuker.util import android.accounts.AccountManager import android.annotation.SuppressLint import android.app.ActionBar import android.app.Activity import android.content.* import android.content.pm.ActivityInfo import android.content.pm.PackageManager import android.graphics.Rect import android.graphics.drawable.Drawable import android.net.ConnectivityManager import android.net.Uri import android.nfc.NfcAdapter import android.nfc.NfcAdapter.CreateNdefMessageCallback import android.os.BatteryManager import android.os.Build import android.os.Bundle import android.support.annotation.DrawableRes import android.support.annotation.StringRes import android.support.v4.net.ConnectivityManagerCompat import android.support.v4.view.GravityCompat import android.support.v4.view.MenuItemCompat import android.support.v4.view.accessibility.AccessibilityEventCompat import android.support.v7.app.AppCompatActivity import android.text.TextUtils import android.text.format.DateFormat import android.text.format.DateUtils import android.util.Log import android.util.TypedValue import android.view.* import android.view.accessibility.AccessibilityEvent import android.view.accessibility.AccessibilityManager import android.widget.Toast import org.mariotaku.kpreferences.get import org.mariotaku.ktextension.getNullableTypedArray import org.mariotaku.ktextension.toLocalizedString import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.GoogleApiAvailability import org.mariotaku.pickncrop.library.PNCUtils import org.mariotaku.sqliteqb.library.AllColumns import org.mariotaku.sqliteqb.library.Columns import org.mariotaku.sqliteqb.library.Columns.Column import org.mariotaku.sqliteqb.library.Expression import org.mariotaku.sqliteqb.library.Selectable import de.vanita5.twittnuker.R import de.vanita5.twittnuker.TwittnukerConstants.LOGTAG import de.vanita5.twittnuker.TwittnukerConstants.SHARED_PREFERENCES_NAME import de.vanita5.twittnuker.TwittnukerConstants.TAB_CODE_DIRECT_MESSAGES import de.vanita5.twittnuker.TwittnukerConstants.TAB_CODE_HOME_TIMELINE import de.vanita5.twittnuker.TwittnukerConstants.TAB_CODE_NOTIFICATIONS_TIMELINE import de.vanita5.twittnuker.annotation.CustomTabType import de.vanita5.twittnuker.annotation.ProfileImageSize import de.vanita5.twittnuker.constant.CompatibilityConstants.EXTRA_ACCOUNT_ID import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_ACCOUNT_KEY import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_ACCOUNT_KEYS import de.vanita5.twittnuker.constant.IntentConstants.INTENT_ACTION_PEBBLE_NOTIFICATION import de.vanita5.twittnuker.constant.SharedPreferenceConstants.* import de.vanita5.twittnuker.constant.bandwidthSavingModeKey import de.vanita5.twittnuker.constant.defaultAccountKey import de.vanita5.twittnuker.constant.mediaPreviewKey import de.vanita5.twittnuker.fragment.AbsStatusesFragment import de.vanita5.twittnuker.menu.FavoriteItemProvider import de.vanita5.twittnuker.model.ParcelableStatus import de.vanita5.twittnuker.model.ParcelableUserMention import de.vanita5.twittnuker.model.PebbleMessage import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.model.util.AccountUtils import de.vanita5.twittnuker.provider.TwidereDataStore.CachedUsers import de.vanita5.twittnuker.util.TwidereLinkify.PATTERN_TWITTER_PROFILE_IMAGES import de.vanita5.twittnuker.view.TabPagerIndicator import java.io.File import java.util.* import java.util.regex.Pattern object Utils { private val PATTERN_XML_RESOURCE_IDENTIFIER = Pattern.compile("res/xml/([\\w_]+)\\.xml") private val PATTERN_RESOURCE_IDENTIFIER = Pattern.compile("@([\\w_]+)/([\\w_]+)") private val HOME_TABS_URI_MATCHER = UriMatcher(UriMatcher.NO_MATCH) init { HOME_TABS_URI_MATCHER.addURI(CustomTabType.HOME_TIMELINE, null, TAB_CODE_HOME_TIMELINE) HOME_TABS_URI_MATCHER.addURI(CustomTabType.NOTIFICATIONS_TIMELINE, null, TAB_CODE_NOTIFICATIONS_TIMELINE) HOME_TABS_URI_MATCHER.addURI(CustomTabType.DIRECT_MESSAGES, null, TAB_CODE_DIRECT_MESSAGES) } fun announceForAccessibilityCompat(context: Context, view: View, text: CharSequence, cls: Class<*>) { val accessibilityManager = context .getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager if (!accessibilityManager.isEnabled) return // Prior to SDK 16, announcements could only be made through FOCUSED // events. Jelly Bean (SDK 16) added support for speaking text verbatim // using the ANNOUNCEMENT event type. val eventType: Int if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { eventType = AccessibilityEvent.TYPE_VIEW_FOCUSED } else { eventType = AccessibilityEventCompat.TYPE_ANNOUNCEMENT } // Construct an accessibility event with the minimum recommended // attributes. An event without a class name or package may be dropped. val event = AccessibilityEvent.obtain(eventType) event.text.add(text) event.className = cls.name event.packageName = context.packageName event.setSource(view) // Sends the event directly through the accessibility manager. If your // application only targets SDK 14+, you should just call // getParent().requestSendAccessibilityEvent(this, event); accessibilityManager.sendAccessibilityEvent(event) } fun deleteMedia(context: Context, uri: Uri): Boolean { try { return PNCUtils.deleteMedia(context, uri) } catch (e: SecurityException) { return false } } fun sanitizeMimeType(contentType: String?): String? { if (contentType == null) return null when (contentType) { "image/jpg" -> return "image/jpeg" } return contentType } fun createStatusShareIntent(context: Context, status: ParcelableStatus): Intent { val intent = Intent(Intent.ACTION_SEND) intent.type = "text/plain" intent.putExtra(Intent.EXTRA_SUBJECT, IntentUtils.getStatusShareSubject(context, status)) intent.putExtra(Intent.EXTRA_TEXT, IntentUtils.getStatusShareText(context, status)) intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION return intent } fun getAccountKeys(context: Context, args: Bundle?): Array<UserKey>? { if (args == null) return null if (args.containsKey(EXTRA_ACCOUNT_KEYS)) { return args.getNullableTypedArray(EXTRA_ACCOUNT_KEYS) } else if (args.containsKey(EXTRA_ACCOUNT_KEY)) { val accountKey = args.getParcelable<UserKey>(EXTRA_ACCOUNT_KEY) ?: return emptyArray() return arrayOf(accountKey) } else if (args.containsKey(EXTRA_ACCOUNT_ID)) { val accountId = args.get(EXTRA_ACCOUNT_ID).toString() try { if (java.lang.Long.parseLong(accountId) <= 0) return null } catch (e: NumberFormatException) { // Ignore } val accountKey = DataStoreUtils.findAccountKey(context, accountId) args.putParcelable(EXTRA_ACCOUNT_KEY, accountKey) if (accountKey == null) return arrayOf(UserKey(accountId, null)) return arrayOf(accountKey) } return null } fun getAccountKey(context: Context, args: Bundle?): UserKey? { return getAccountKeys(context, args)?.firstOrNull() } fun getReadPositionTagWithAccount(tag: String, accountKey: UserKey?): String { if (accountKey == null) return tag return "$accountKey:$tag" } fun formatSameDayTime(context: Context, timestamp: Long): String? { if (DateUtils.isToday(timestamp)) return DateUtils.formatDateTime(context, timestamp, if (DateFormat.is24HourFormat(context)) DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_24HOUR else DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_12HOUR) return DateUtils.formatDateTime(context, timestamp, DateUtils.FORMAT_SHOW_DATE) } fun formatToLongTimeString(context: Context, timestamp: Long): String? { val formatFlags = DateUtils.FORMAT_NO_NOON_MIDNIGHT or DateUtils.FORMAT_ABBREV_ALL or DateUtils.FORMAT_CAP_AMPM or DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME return DateUtils.formatDateTime(context, timestamp, formatFlags) } fun getAccountNotificationId(notificationType: Int, accountId: String): Int { return Arrays.hashCode(longArrayOf(notificationType.toLong(), java.lang.Long.parseLong(accountId))) } fun isComposeNowSupported(context: Context): Boolean { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) return false return hasNavBar(context) } fun setLastSeen(context: Context, entities: Array<ParcelableUserMention>?, time: Long): Boolean { if (entities == null) return false var result = false for (entity in entities) { result = result or setLastSeen(context, entity.key, time) } return result } fun setLastSeen(context: Context, userKey: UserKey, time: Long): Boolean { val cr = context.contentResolver val values = ContentValues() if (time > 0) { values.put(CachedUsers.LAST_SEEN, time) } else { // Zero or negative value means remove last seen values.putNull(CachedUsers.LAST_SEEN) } val where = Expression.equalsArgs(CachedUsers.USER_KEY).sql val selectionArgs = arrayOf(userKey.toString()) return cr.update(CachedUsers.CONTENT_URI, values, where, selectionArgs) > 0 } fun getColumnsFromProjection(projection: Array<String>?): Selectable { if (projection == null) return AllColumns() val length = projection.size val columns = arrayOfNulls<Column>(length) for (i in 0 until length) { columns[i] = Column(projection[i]) } return Columns(*columns) } fun getDefaultAccountKey(context: Context): UserKey? { val prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE) val accountKey = prefs[defaultAccountKey] val accountKeys = DataStoreUtils.getAccountKeys(context) return accountKeys.find { it.maybeEquals(accountKey) } ?: run { if (!accountKeys.contains(accountKey)) { return@run accountKeys.firstOrNull() } return@run null } } fun getInternalCacheDir(context: Context?, cacheDirName: String): File { if (context == null) throw NullPointerException() val cacheDir = File(context.cacheDir, cacheDirName) if (cacheDir.isDirectory || cacheDir.mkdirs()) return cacheDir return File(context.cacheDir, cacheDirName) } fun getExternalCacheDir(context: Context, cacheDirName: String, sizeInBytes: Long): File? { val externalCacheDir = try { context.externalCacheDir } catch (e: SecurityException) { null } ?: return null val cacheDir = File(externalCacheDir, cacheDirName) if (sizeInBytes > 0 && externalCacheDir.freeSpace < sizeInBytes / 10) { // Less then 10% space available return null } if (cacheDir.isDirectory || cacheDir.mkdirs()) return cacheDir return null } fun getLocalizedNumber(locale: Locale, number: Number): String { return number.toLocalizedString(locale) } fun getOriginalTwitterProfileImage(url: String): String { val matcher = PATTERN_TWITTER_PROFILE_IMAGES.matcher(url) if (matcher.matches()) return matcher.replaceFirst("$1$2/profile_images/$3/$4$6") return url } fun getQuoteStatus(context: Context?, status: ParcelableStatus): String? { if (context == null) return null var quoteFormat: String = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).getString( KEY_QUOTE_FORMAT, DEFAULT_QUOTE_FORMAT) if (TextUtils.isEmpty(quoteFormat)) { quoteFormat = DEFAULT_QUOTE_FORMAT } var result = quoteFormat.replace(FORMAT_PATTERN_LINK, LinkCreator.getStatusWebLink(status).toString()) result = result.replace(FORMAT_PATTERN_NAME, status.user_screen_name) result = result.replace(FORMAT_PATTERN_TEXT, status.text_plain) return result } fun getResId(context: Context?, string: String?): Int { if (context == null || string == null) return 0 var m = PATTERN_RESOURCE_IDENTIFIER.matcher(string) val res = context.resources if (m.matches()) return res.getIdentifier(m.group(2), m.group(1), context.packageName) m = PATTERN_XML_RESOURCE_IDENTIFIER.matcher(string) if (m.matches()) return res.getIdentifier(m.group(1), "xml", context.packageName) return 0 } fun getTabDisplayOption(context: Context): String { val defaultOption = context.getString(R.string.default_tab_display_option) val prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE) return prefs.getString(KEY_TAB_DISPLAY_OPTION, defaultOption) ?: defaultOption } fun getTabDisplayOptionInt(context: Context): Int { return getTabDisplayOptionInt(getTabDisplayOption(context)) } fun getTabDisplayOptionInt(option: String): Int { if (VALUE_TAB_DISPLAY_OPTION_ICON == option) return TabPagerIndicator.DisplayOption.ICON else if (VALUE_TAB_DISPLAY_OPTION_LABEL == option) return TabPagerIndicator.DisplayOption.LABEL return TabPagerIndicator.DisplayOption.BOTH } fun hasNavBar(context: Context): Boolean { val resources = context.resources ?: return false val id = resources.getIdentifier("config_showNavigationBar", "bool", "android") if (id > 0) { return resources.getBoolean(id) } else { // Check for keys return !KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK) && !KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_HOME) } } fun getTwitterProfileImageOfSize(url: String, size: String): String { if (ProfileImageSize.ORIGINAL == size) { return getOriginalTwitterProfileImage(url) } val matcher = PATTERN_TWITTER_PROFILE_IMAGES.matcher(url) if (matcher.matches()) { return matcher.replaceFirst("$1$2/profile_images/$3/$4_$size$6") } return url } @DrawableRes fun getUserTypeIconRes(isVerified: Boolean, isProtected: Boolean): Int { if (isVerified) return R.drawable.ic_user_type_verified else if (isProtected) return R.drawable.ic_user_type_protected return 0 } @StringRes fun getUserTypeDescriptionRes(isVerified: Boolean, isProtected: Boolean): Int { if (isVerified) return R.string.user_type_verified else if (isProtected) return R.string.user_type_protected return 0 } fun isBatteryOkay(context: Context?): Boolean { if (context == null) return false val app = context.applicationContext val filter = IntentFilter(Intent.ACTION_BATTERY_CHANGED) val intent: Intent? try { intent = app.registerReceiver(null, filter) } catch (e: Exception) { return false } if (intent == null) return false val plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0 val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0).toFloat() val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100).toFloat() return plugged || level / scale > 0.15f } fun isMyAccount(context: Context, accountKey: UserKey): Boolean { val am = AccountManager.get(context) return AccountUtils.findByAccountKey(am, accountKey) != null } fun isMyAccount(context: Context, screenName: String): Boolean { val am = AccountManager.get(context) return AccountUtils.findByScreenName(am, screenName) != null } fun isMyRetweet(status: ParcelableStatus?): Boolean { return status != null && isMyRetweet(status.account_key, status.retweeted_by_user_key, status.my_retweet_id) } fun isMyRetweet(accountKey: UserKey, retweetedByKey: UserKey?, myRetweetId: String?): Boolean { return accountKey == retweetedByKey || myRetweetId != null } fun matchTabCode(uri: Uri): Int { return HOME_TABS_URI_MATCHER.match(uri) } @CustomTabType fun matchTabType(uri: Uri): String? { return getTabType(matchTabCode(uri)) } @CustomTabType fun getTabType(code: Int): String? { when (code) { TAB_CODE_HOME_TIMELINE -> { return CustomTabType.HOME_TIMELINE } TAB_CODE_NOTIFICATIONS_TIMELINE -> { return CustomTabType.NOTIFICATIONS_TIMELINE } TAB_CODE_DIRECT_MESSAGES -> { return CustomTabType.DIRECT_MESSAGES } } return null } fun setNdefPushMessageCallback(activity: Activity, callback: CreateNdefMessageCallback): Boolean { try { val adapter = NfcAdapter.getDefaultAdapter(activity) ?: return false adapter.setNdefPushMessageCallback(callback, activity) return true } catch (e: SecurityException) { Log.w(LOGTAG, e) } return false } fun getInsetsTopWithoutActionBarHeight(context: Context, top: Int): Int { val actionBarHeight: Int if (context is AppCompatActivity) { actionBarHeight = getActionBarHeight(context.supportActionBar) } else if (context is Activity) { actionBarHeight = getActionBarHeight(context.actionBar) } else { return top } if (actionBarHeight > top) { return top } return top - actionBarHeight } fun restartActivity(activity: Activity?) { if (activity == null) return val enterAnim = android.R.anim.fade_in val exitAnim = android.R.anim.fade_out activity.finish() activity.overridePendingTransition(enterAnim, exitAnim) activity.startActivity(activity.intent) activity.overridePendingTransition(enterAnim, exitAnim) } internal fun isMyStatus(status: ParcelableStatus): Boolean { if (isMyRetweet(status)) return true return status.account_key.maybeEquals(status.user_key) } fun showMenuItemToast(v: View, text: CharSequence, isBottomBar: Boolean) { val screenPos = IntArray(2) val displayFrame = Rect() v.getLocationOnScreen(screenPos) v.getWindowVisibleDisplayFrame(displayFrame) val width = v.width val height = v.height val screenWidth = v.resources.displayMetrics.widthPixels val cheatSheet = Toast.makeText(v.context.applicationContext, text, Toast.LENGTH_SHORT) if (isBottomBar) { // Show along the bottom center cheatSheet.setGravity(Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL, 0, height) } else { // Show along the top; follow action buttons cheatSheet.setGravity(Gravity.TOP or GravityCompat.END, screenWidth - screenPos[0] - width / 2, height) } cheatSheet.show() } internal fun getMetadataDrawable(pm: PackageManager?, info: ActivityInfo?, key: String?): Drawable? { if (pm == null || info == null || info.metaData == null || key == null || !info.metaData.containsKey(key)) return null return pm.getDrawable(info.packageName, info.metaData.getInt(key), info.applicationInfo) } fun getActionBarHeight(actionBar: ActionBar?): Int { if (actionBar == null) return 0 val context = actionBar.themedContext val tv = TypedValue() val height = actionBar.height if (height > 0) return height if (context.theme.resolveAttribute(android.R.attr.actionBarSize, tv, true)) { return TypedValue.complexToDimensionPixelSize(tv.data, context.resources.displayMetrics) } return 0 } fun retweet(status: ParcelableStatus, twitter: AsyncTwitterWrapper) { if (isMyRetweet(status)) { twitter.cancelRetweetAsync(status.account_key, status.id, status.my_retweet_id) } else { twitter.retweetStatusAsync(status.account_key, status) } } fun favorite(status: ParcelableStatus, twitter: AsyncTwitterWrapper, item: MenuItem) { if (status.is_favorite) { twitter.destroyFavoriteAsync(status.account_key, status.id) } else { val provider = MenuItemCompat.getActionProvider(item) if (provider is FavoriteItemProvider) { provider.invokeItem(item, AbsStatusesFragment.DefaultOnLikedListener(twitter, status, null)) } else { twitter.createFavoriteAsync(status.account_key, status) } } } fun getActionBarHeight(actionBar: android.support.v7.app.ActionBar?): Int { if (actionBar == null) return 0 val context = actionBar.themedContext val tv = TypedValue() val height = actionBar.height if (height > 0) return height if (context.theme.resolveAttribute(R.attr.actionBarSize, tv, true)) { return TypedValue.complexToDimensionPixelSize(tv.data, context.resources.displayMetrics) } return 0 } fun getNotificationId(baseId: Int, accountKey: UserKey?): Int { var result = baseId result = 31 * result + (accountKey?.hashCode() ?: 0) return result } @SuppressLint("InlinedApi") fun isCharging(context: Context?): Boolean { if (context == null) return false val intent = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) ?: return false val plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS } fun isMediaPreviewEnabled(context: Context, preferences: SharedPreferences): Boolean { if (!preferences[mediaPreviewKey]) return false val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager return !ConnectivityManagerCompat.isActiveNetworkMetered(cm) || !preferences[bandwidthSavingModeKey] } /** * Send Notifications to Pebble smart watches * @param context Context * * * @param title String * * * @param message String */ fun sendPebbleNotification(context: Context, title: String?, message: String) { val appName: String if (title == null) { appName = context.getString(R.string.app_name) } else { appName = "${context.getString(R.string.app_name)} - $title" } if (TextUtils.isEmpty(message)) return val prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE) if (prefs.getBoolean(KEY_PEBBLE_NOTIFICATIONS, false)) { val messages = ArrayList<PebbleMessage>() messages.add(PebbleMessage(appName, message)) val intent = Intent(INTENT_ACTION_PEBBLE_NOTIFICATION) intent.putExtra("messageType", "PEBBLE_ALERT") intent.putExtra("sender", appName) intent.putExtra("notificationData", JsonSerializer.serializeList(messages, PebbleMessage::class.java)) context.applicationContext.sendBroadcast(intent) } } fun checkPlayServices(activity: Activity): Boolean { val apiAvailability = GoogleApiAvailability.getInstance() val resultCode = apiAvailability.isGooglePlayServicesAvailable(activity) if (resultCode != ConnectionResult.SUCCESS) { if (apiAvailability.isUserResolvableError(resultCode)) { apiAvailability.getErrorDialog(activity, resultCode, 9000) .show() } else { Log.i("PlayServices", "This device is not supported.") } return false } return true } }
gpl-3.0
fe058e0cf9848212a6ee099a279431e4
39.228482
127
0.677611
4.61573
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/api/TwidereRestRequestFactory.kt
1
2176
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[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 de.vanita5.twittnuker.util.api import de.vanita5.microblog.library.MicroBlogException import org.mariotaku.restfu.RestConverter import org.mariotaku.restfu.RestMethod import org.mariotaku.restfu.RestRequest import org.mariotaku.restfu.http.ValueMap /** * Convert rest method to rest request */ class TwidereRestRequestFactory( private val extraRequestParams: Map<String, String>? ) : RestRequest.Factory<MicroBlogException> { override fun create(restMethod: RestMethod<MicroBlogException>, factory: RestConverter.Factory<MicroBlogException>, valuePool: ValueMap?): RestRequest { val method = restMethod.method val path = restMethod.path val headers = restMethod.getHeaders(valuePool) val queries = restMethod.getQueries(valuePool) val params = restMethod.getParams(factory, valuePool) val rawValue = restMethod.rawValue val bodyType = restMethod.bodyType val extras = restMethod.extras if (extraRequestParams != null) { for ((key, value) in extraRequestParams) { queries.add(key, value) } } return RestRequest(method.value, method.allowBody, path, headers, queries, params, rawValue, bodyType, extras) } }
gpl-3.0
05ce61eb49181372ad7d536803c38daf
36.534483
100
0.715533
4.334661
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/model/ActivityTitleSummaryMessage.kt
1
16592
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[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 de.vanita5.twittnuker.model import android.content.Context import android.content.res.Resources import android.graphics.Typeface import android.support.v4.content.ContextCompat import android.text.SpannableString import android.text.SpannableStringBuilder import android.text.Spanned import android.text.style.StyleSpan import de.vanita5.microblog.library.twitter.model.Activity import de.vanita5.twittnuker.R import de.vanita5.twittnuker.extension.model.activityStatus import de.vanita5.twittnuker.text.style.NonBreakEllipseSpan import de.vanita5.twittnuker.util.UserColorNameManager import org.oshkimaadziig.george.androidutils.SpanFormatter class ActivityTitleSummaryMessage private constructor(val icon: Int, val color: Int, val title: CharSequence, val summary: CharSequence?) { companion object { fun get(context: Context, manager: UserColorNameManager, activity: ParcelableActivity, sources: Array<ParcelableLiteUser>, defaultColor: Int, shouldUseStarsForLikes: Boolean, nameFirst: Boolean): ActivityTitleSummaryMessage? { val resources = context.resources when (activity.action) { Activity.Action.FOLLOW -> { val typeIcon = R.drawable.ic_activity_action_follow val color = ContextCompat.getColor(context, R.color.highlight_follow) val title = getTitleStringAboutMe(resources, manager, R.string.activity_about_me_follow, R.string.activity_about_me_follow_multi, sources, nameFirst) return ActivityTitleSummaryMessage(typeIcon, color, title, null) } Activity.Action.FAVORITE -> { val typeIcon: Int val color: Int val title: CharSequence if (shouldUseStarsForLikes) { typeIcon = R.drawable.ic_activity_action_favorite color = ContextCompat.getColor(context, R.color.highlight_favorite) title = getTitleStringAboutMe(resources, manager, R.string.activity_about_me_favorite, R.string.activity_about_me_favorite_multi, sources, nameFirst) } else { typeIcon = R.drawable.ic_activity_action_like color = ContextCompat.getColor(context, R.color.highlight_like) title = getTitleStringAboutMe(resources, manager, R.string.activity_about_me_like, R.string.activity_about_me_like_multi, sources, nameFirst) } val summary = generateTextOnlySummary(activity.summary_line) return ActivityTitleSummaryMessage(typeIcon, color, title, summary) } Activity.Action.RETWEET -> { val typeIcon = R.drawable.ic_activity_action_retweet val color = ContextCompat.getColor(context, R.color.highlight_retweet) val title = getTitleStringAboutMe(resources, manager, R.string.activity_about_me_retweet, R.string.activity_about_me_retweet_multi, sources, nameFirst) val summary = generateTextOnlySummary(activity.summary_line) return ActivityTitleSummaryMessage(typeIcon, color, title, summary) } Activity.Action.FAVORITED_RETWEET -> { val typeIcon: Int val color: Int val title: CharSequence if (shouldUseStarsForLikes) { typeIcon = R.drawable.ic_activity_action_favorite color = ContextCompat.getColor(context, R.color.highlight_favorite) title = getTitleStringAboutMe(resources, manager, R.string.activity_about_me_favorited_retweet, R.string.activity_about_me_favorited_retweet_multi, sources, nameFirst) } else { typeIcon = R.drawable.ic_activity_action_like color = ContextCompat.getColor(context, R.color.highlight_like) title = getTitleStringAboutMe(resources, manager, R.string.activity_about_me_liked_retweet, R.string.activity_about_me_liked_retweet_multi, sources, nameFirst) } val summary = generateStatusTextSummary(context, manager, activity.summary_line, nameFirst) return ActivityTitleSummaryMessage(typeIcon, color, title, summary) } Activity.Action.RETWEETED_RETWEET -> { val typeIcon = R.drawable.ic_activity_action_retweet val color = ContextCompat.getColor(context, R.color.highlight_retweet) val title = getTitleStringAboutMe(resources, manager, R.string.activity_about_me_retweeted_retweet, R.string.activity_about_me_retweeted_retweet_multi, sources, nameFirst) val summary = generateStatusTextSummary(context, manager, activity.summary_line, nameFirst) return ActivityTitleSummaryMessage(typeIcon, color, title, summary) } Activity.Action.RETWEETED_MENTION -> { val typeIcon = R.drawable.ic_activity_action_retweet val color = ContextCompat.getColor(context, R.color.highlight_retweet) val title = getTitleStringAboutMe(resources, manager, R.string.activity_about_me_retweeted_mention, R.string.activity_about_me_retweeted_mention_multi, sources, nameFirst) val summary = generateStatusTextSummary(context, manager, activity.summary_line, nameFirst) return ActivityTitleSummaryMessage(typeIcon, color, title, summary) } Activity.Action.FAVORITED_MENTION -> { val typeIcon: Int val color: Int val title: CharSequence if (shouldUseStarsForLikes) { typeIcon = R.drawable.ic_activity_action_favorite color = ContextCompat.getColor(context, R.color.highlight_favorite) title = getTitleStringAboutMe(resources, manager, R.string.activity_about_me_favorited_mention, R.string.activity_about_me_favorited_mention_multi, sources, nameFirst) } else { typeIcon = R.drawable.ic_activity_action_like color = ContextCompat.getColor(context, R.color.highlight_like) title = getTitleStringAboutMe(resources, manager, R.string.activity_about_me_liked_mention, R.string.activity_about_me_liked_mention_multi, sources, nameFirst) } val summary = generateStatusTextSummary(context, manager, activity.summary_line, nameFirst) return ActivityTitleSummaryMessage(typeIcon, color, title, summary) } Activity.Action.LIST_MEMBER_ADDED -> { val title: CharSequence val icon = R.drawable.ic_activity_action_list_added if (sources.size == 1 && activity.summary_line?.size == 1) { val firstDisplayName = SpannableString(manager.getDisplayName( sources[0], nameFirst)) val listName = SpannableString(activity.summary_line[0].content) firstDisplayName.setSpan(StyleSpan(Typeface.BOLD), 0, firstDisplayName.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) listName.setSpan(StyleSpan(Typeface.BOLD), 0, listName.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) val format = context.getString(R.string.activity_about_me_list_member_added_with_name) title = SpanFormatter.format(format, firstDisplayName, listName) } else { title = getTitleStringAboutMe(resources, manager, R.string.activity_about_me_list_member_added, R.string.activity_about_me_list_member_added_multi, sources, nameFirst) } return ActivityTitleSummaryMessage(icon, defaultColor, title, null) } Activity.Action.MENTION, Activity.Action.REPLY, Activity.Action.QUOTE -> { val status = activity.activityStatus ?: return null val title = SpannableString(manager.getDisplayName(status, nameFirst)) title.setSpan(StyleSpan(Typeface.BOLD), 0, title.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) return ActivityTitleSummaryMessage(0, 0, title, status.text_unescaped) } Activity.Action.JOINED_TWITTER -> { val typeIcon = R.drawable.ic_activity_action_follow val color = ContextCompat.getColor(context, R.color.highlight_follow) val title = getTitleStringAboutMe(resources, manager, R.string.activity_joined_twitter, R.string.activity_joined_twitter_multi, sources, nameFirst) return ActivityTitleSummaryMessage(typeIcon, color, title, null) } Activity.Action.MEDIA_TAGGED -> { val typeIcon = R.drawable.ic_activity_action_media_tagged val color = ContextCompat.getColor(context, R.color.highlight_tagged) val title = getTitleStringAboutMe(resources, manager, R.string.activity_about_me_media_tagged, R.string.activity_about_me_media_tagged_multi, sources, nameFirst) val summary = generateStatusTextSummary(context, manager, activity.summary_line, nameFirst) return ActivityTitleSummaryMessage(typeIcon, color, title, summary) } Activity.Action.FAVORITED_MEDIA_TAGGED -> { val typeIcon: Int val color: Int val title: CharSequence if (shouldUseStarsForLikes) { typeIcon = R.drawable.ic_activity_action_favorite color = ContextCompat.getColor(context, R.color.highlight_favorite) title = getTitleStringAboutMe(resources, manager, R.string.activity_about_me_favorited_media_tagged, R.string.activity_about_me_favorited_media_tagged_multi, sources, nameFirst) } else { typeIcon = R.drawable.ic_activity_action_like color = ContextCompat.getColor(context, R.color.highlight_like) title = getTitleStringAboutMe(resources, manager, R.string.activity_about_me_liked_media_tagged, R.string.activity_about_me_liked_media_tagged_multi, sources, nameFirst) } val summary = generateStatusTextSummary(context, manager, activity.summary_line, nameFirst) return ActivityTitleSummaryMessage(typeIcon, color, title, summary) } Activity.Action.RETWEETED_MEDIA_TAGGED -> { val typeIcon = R.drawable.ic_activity_action_retweet val color = ContextCompat.getColor(context, R.color.highlight_retweet) val title = getTitleStringAboutMe(resources, manager, R.string.activity_about_me_retweeted_media_tagged, R.string.activity_about_me_retweeted_media_tagged_multi, sources, nameFirst) val summary = generateStatusTextSummary(context, manager, activity.summary_line, nameFirst) return ActivityTitleSummaryMessage(typeIcon, color, title, summary) } } return null } private fun generateStatusTextSummary(context: Context, manager: UserColorNameManager, statuses: Array<ParcelableActivity.SummaryLine>?, nameFirst: Boolean): Spanned? { return statuses?.joinTo(SpannableStringBuilder(), separator = "\n") { status -> val displayName = SpannableString(manager.getDisplayName(status.key, status.name, status.screen_name, nameFirst)).also { it.setSpan(StyleSpan(Typeface.BOLD), 0, it.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } val statusText = if (statuses.size > 1) { SpannableString(status.content.replace('\n', ' ')).also { it.setSpan(NonBreakEllipseSpan(), 0, it.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } } else { status.content } return@joinTo SpanFormatter.format(context.getString(R.string.title_summary_line_format), displayName, statusText) } } private fun generateTextOnlySummary(lines: Array<ParcelableActivity.SummaryLine>?): CharSequence? { return lines?.joinTo(SpannableStringBuilder(), separator = "\n") { status -> if (lines.size > 1) { return@joinTo SpannableString(status.content.replace('\n', ' ')).also { it.setSpan(NonBreakEllipseSpan(), 0, it.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } } else { return@joinTo status.content } } } private fun getTitleStringAboutMe(resources: Resources, manager: UserColorNameManager, stringRes: Int, stringResMulti: Int, sources: Array<ParcelableLiteUser>, nameFirst: Boolean): CharSequence { val firstDisplayName = SpannableString(manager.getDisplayName(sources[0], nameFirst)) firstDisplayName.setSpan(StyleSpan(Typeface.BOLD), 0, firstDisplayName.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) if (sources.size == 1) { val format = resources.getString(stringRes) return SpanFormatter.format(format, firstDisplayName) } else if (sources.size == 2) { val format = resources.getString(stringResMulti) val secondDisplayName = SpannableString(manager.getDisplayName(sources[1], nameFirst)) secondDisplayName.setSpan(StyleSpan(Typeface.BOLD), 0, secondDisplayName.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) return SpanFormatter.format(format, firstDisplayName, secondDisplayName) } else { val othersCount = sources.size - 1 val nOthers = resources.getQuantityString(R.plurals.N_others, othersCount, othersCount) val format = resources.getString(stringResMulti) return SpanFormatter.format(format, firstDisplayName, nOthers) } } } }
gpl-3.0
b8505470161c7ac88fd0083a6116dd4d
60.455556
139
0.590164
5.149597
false
false
false
false
UnsignedInt8/d.Wallet-Core
android/lib/src/main/java/dWallet/core/bitcoin/application/bip32/Derivation.kt
1
2585
package dwallet.core.bitcoin.application.bip32 /** * Created by Jesion on 2015-01-19. */ class Derivation(private val root: ExtendedKey) { @Throws(Exception::class) fun derive(path: String): ExtendedKey { val p = path.split("/") if (p.size == 2) { val sequence = Integer.parseInt(p[1]) return basic(sequence) } else if (p.size == 3) { val accountType = Integer.parseInt(p[2]) val account = Integer.parseInt(p[1]) return accountMaster(accountType, account) } else if (p.size == 4) { val accountType = Integer.parseInt(p[2]) val account = Integer.parseInt(p[1]) val key = Integer.parseInt(p[3]) return accountKey(accountType, account, key) } throw Exception("Invalid derivation path") } /** * Level 1 * * Path m/i * * @param sequence * @return * @throws Exception */ @Throws(Exception::class) fun basic(sequence: Int): ExtendedKey { return root.derive(sequence) } /** * Account Master * * Path m/k/0 or m/k/1 * * @param account * @param type * @return * @throws Exception */ @Throws(Exception::class) fun accountMaster(type: Int, account: Int): ExtendedKey { if (type == 0) { return externalAccountMaster(account) } else if (type == 1) { return internalAccountMaster(account) } throw Exception("Account type not recognized") } /** * External Account Master * * Path m/k/0 * * @param account * @return * @throws Exception */ @Throws(Exception::class) fun externalAccountMaster(account: Int): ExtendedKey { val base = root.derive(account) return base.derive(0) } /** * Internal Account Master * * Path m/k/1 * * @param account * @return * @throws Exception */ @Throws(Exception::class) fun internalAccountMaster(account: Int): ExtendedKey { val base = root.derive(account) return base.derive(1) } /** * Account Key * * Path m/k/0/i or m/k/1/i * * @param accountType * @param account * @param key * @return * @throws Exception */ @Throws(Exception::class) fun accountKey(accountType: Int, account: Int, key: Int): ExtendedKey { val base = accountMaster(accountType, account) return base.derive(key) } }
gpl-3.0
a142d223452a3b41d643fb5fcc0dde33
22.5
75
0.548162
3.995363
false
false
false
false
syrop/Victor-Events
events/src/main/kotlin/pl/org/seva/events/main/extension/Fragment.kt
1
5515
/* * Copyright (C) 2019 Wiktor Nizio * * 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/>. * * If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp */ package pl.org.seva.events.main.extension import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.pm.PackageManager import android.net.Uri import android.widget.Toast import androidx.activity.OnBackPressedCallback import androidx.annotation.IdRes import androidx.annotation.StringRes import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.* import androidx.navigation.fragment.findNavController import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.SupportMapFragment import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine import pl.org.seva.events.main.ui.InteractiveMapHolder import pl.org.seva.events.main.ui.MapHolder import pl.org.seva.events.main.data.Permissions import kotlin.coroutines.resume fun Fragment.nav(@IdRes resId: Int): Boolean { findNavController().navigate(resId) return true } fun Fragment.back(): Boolean { findNavController().popBackStack() return true } fun Fragment.createMapHolder(@IdRes map: Int, block: MapHolder.() -> Unit = {}) = MapHolder().apply(block).also { withMapHolder(it to map) } fun Fragment.createInteractiveMapHolder(@IdRes map: Int, block: InteractiveMapHolder.() -> Unit = {}) = InteractiveMapHolder().apply(block).also { withMapHolder(it to map) } private fun Fragment.withMapHolder(pair: Pair<MapHolder, Int>) { val (holder, id) = pair lifecycleScope.launch { holder withMap googleMap(id) } } fun Fragment.check(permission: String) = ContextCompat.checkSelfPermission(requireContext(), permission) == PackageManager.PERMISSION_GRANTED var Fragment.title: CharSequence get() = checkNotNull(checkNotNull((requireActivity()).actionBar).title) set(value) { checkNotNull((requireActivity() as AppCompatActivity).supportActionBar).title = value } fun Fragment.inBrowser(uri: String) { val i = Intent(Intent.ACTION_VIEW) i.data = Uri.parse(uri) startActivity(i) } fun Fragment.request(requestCode: Int, requests: Array<Permissions.PermissionRequest>) { watchPermissions(requestCode, requests) requestPermissions(requests.map { it.permission }.toTypedArray(), requestCode) } private fun Fragment.watchPermissions(requestCode: Int, requests: Array<Permissions.PermissionRequest>) { lifecycleScope.launch { viewModels<Permissions.ViewModel>().value.watch(requestCode, requests) } } fun Fragment.prefs(name: String): SharedPreferences = requireContext().getSharedPreferences(name, Context.MODE_PRIVATE) suspend fun Fragment.googleMap(@IdRes id: Int) = suspendCancellableCoroutine<GoogleMap> { continuation -> val mapFragment = childFragmentManager.findFragmentById(id) as SupportMapFragment mapFragment.getMapAsync { map -> continuation.resume(map) } } fun Fragment.requestLocationPermission(onGranted: () -> Unit) { if (check(Manifest.permission.ACCESS_COARSE_LOCATION)) onGranted() else request( Permissions.DEFAULT_PERMISSION_REQUEST_ID, arrayOf(Permissions.PermissionRequest( Manifest.permission.ACCESS_COARSE_LOCATION, onGranted = onGranted))) } fun Fragment.enableMyLocationOnResume(map: GoogleMap) { lifecycle.addObserver(object : LifecycleEventObserver { @SuppressLint("MissingPermission") override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { if (event == Lifecycle.Event.ON_RESUME && check(Manifest.permission.ACCESS_COARSE_LOCATION)) { map.isMyLocationEnabled = true } } }) } fun Fragment.onBack(block: () -> Unit) { val callback = object : OnBackPressedCallback(true) { override fun handleOnBackPressed() = block() } requireActivity().onBackPressedDispatcher.addCallback(this, callback) } fun Fragment.question(message: String, yes: () -> Unit = {}, no: () -> Unit = {}) = requireContext().question(message, yes, no) val Fragment.versionName get() = requireContext().versionName fun Fragment.longToast(message: CharSequence) = toast(message, Toast.LENGTH_LONG) fun Fragment.toast(@StringRes id: Int, duration: Int = Toast.LENGTH_SHORT) = toast(getString(id), duration) fun Fragment.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) { requireContext().toast(message, duration) }
gpl-3.0
8aae0354e7b978b8fe1aa6b46b73d556
35.766667
108
0.733454
4.429719
false
false
false
false
syrop/Victor-Events
events/src/main/kotlin/pl/org/seva/events/main/MainActivity.kt
1
1829
package pl.org.seva.events.main import android.app.Activity import android.app.SearchManager import android.content.Intent import android.os.Bundle import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupActionBarWithNavController import kotlinx.android.synthetic.main.ac_main.* import pl.org.seva.events.R import pl.org.seva.events.comm.CommAddFragment import pl.org.seva.events.comm.CommAddViewModel import pl.org.seva.events.login.LoginActivity class MainActivity : AppCompatActivity() { private val navController by lazy { findNavController(R.id.nav_host_fragment) } private val commAddViewModel by viewModels<CommAddViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.ac_main) setSupportActionBar(toolbar) val appBarConfiguration = AppBarConfiguration(navController.graph) setupActionBarWithNavController(navController, appBarConfiguration) } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) if (Intent.ACTION_SEARCH == intent.action) { commAddViewModel.query(intent.getStringExtra(SearchManager.QUERY)!!) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == CommAddFragment.LOGIN_CREATE_COMM_REQUEST && resultCode == Activity.RESULT_OK) { commAddViewModel.commToCreate.value = checkNotNull(data).getStringExtra(LoginActivity.COMMUNITY_NAME) } } override fun onSupportNavigateUp() = navController.navigateUp() }
gpl-3.0
dcd2b98e5c556090be8122125032fca8
38.76087
113
0.765992
4.775457
false
true
false
false
stripe/stripe-android
paymentsheet/src/test/java/com/stripe/android/paymentsheet/PaymentOptionsViewModelTest.kt
1
14080
package com.stripe.android.paymentsheet import androidx.appcompat.app.AppCompatActivity import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.SavedStateHandle import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat import com.stripe.android.core.Logger import com.stripe.android.core.injection.DUMMY_INJECTOR_KEY import com.stripe.android.link.LinkPaymentLauncher import com.stripe.android.link.model.AccountStatus import com.stripe.android.model.CardBrand import com.stripe.android.model.PaymentIntentFixtures import com.stripe.android.model.PaymentMethodCreateParams import com.stripe.android.model.PaymentMethodCreateParamsFixtures.DEFAULT_CARD import com.stripe.android.model.PaymentMethodFixtures import com.stripe.android.paymentsheet.PaymentOptionsViewModel.TransitionTarget import com.stripe.android.paymentsheet.analytics.EventReporter import com.stripe.android.paymentsheet.model.FragmentConfigFixtures import com.stripe.android.paymentsheet.model.PaymentSelection import com.stripe.android.paymentsheet.model.SavedSelection import com.stripe.android.paymentsheet.viewmodels.BaseSheetViewModel import com.stripe.android.ui.core.forms.resources.StaticLpmResourceRepository import com.stripe.android.utils.FakeCustomerRepository import com.stripe.android.utils.TestUtils.idleLooper import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.Rule import org.junit.runner.RunWith import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.robolectric.RobolectricTestRunner import kotlin.test.Test @ExperimentalCoroutinesApi @RunWith(RobolectricTestRunner::class) internal class PaymentOptionsViewModelTest { @get:Rule val rule = InstantTaskExecutorRule() private val testDispatcher = StandardTestDispatcher() private val eventReporter = mock<EventReporter>() private val prefsRepository = FakePrefsRepository() private val customerRepository = FakeCustomerRepository() private val paymentMethodRepository = FakeCustomerRepository(PAYMENT_METHOD_REPOSITORY_PARAMS) private val lpmResourceRepository = StaticLpmResourceRepository(mock()) private val linkLauncher = mock<LinkPaymentLauncher>() @Test fun `onUserSelection() when selection has been made should set the view state to process result`() { var paymentOptionResult: PaymentOptionResult? = null val viewModel = createViewModel() viewModel.paymentOptionResult.observeForever { paymentOptionResult = it } viewModel.updateSelection(SELECTION_SAVED_PAYMENT_METHOD) viewModel.onUserSelection() assertThat(paymentOptionResult).isEqualTo( PaymentOptionResult.Succeeded( SELECTION_SAVED_PAYMENT_METHOD, listOf() ) ) verify(eventReporter).onSelectPaymentOption(SELECTION_SAVED_PAYMENT_METHOD) } @Test fun `onUserSelection() when new card selection with no save should set the view state to process result`() = runTest { var paymentOptionResult: PaymentOptionResult? = null val viewModel = createViewModel() viewModel.paymentOptionResult.observeForever { paymentOptionResult = it } viewModel.updateSelection(NEW_REQUEST_DONT_SAVE_PAYMENT_SELECTION) viewModel.onUserSelection() assertThat(paymentOptionResult) .isEqualTo( PaymentOptionResult.Succeeded( NEW_REQUEST_DONT_SAVE_PAYMENT_SELECTION, listOf() ) ) verify(eventReporter).onSelectPaymentOption(NEW_REQUEST_DONT_SAVE_PAYMENT_SELECTION) assertThat(prefsRepository.getSavedSelection(true, true)) .isEqualTo(SavedSelection.None) } @Test fun `onUserSelection() new card with save should complete with succeeded view state`() = runTest { paymentMethodRepository.savedPaymentMethod = PaymentMethodFixtures.CARD_PAYMENT_METHOD var paymentOptionResult: PaymentOptionResult? = null val viewModel = createViewModel() viewModel.paymentOptionResult.observeForever { paymentOptionResult = it } viewModel.updateSelection(NEW_REQUEST_SAVE_PAYMENT_SELECTION) viewModel.onUserSelection() val paymentOptionResultSucceeded = paymentOptionResult as PaymentOptionResult.Succeeded assertThat((paymentOptionResultSucceeded).paymentSelection) .isEqualTo(NEW_REQUEST_SAVE_PAYMENT_SELECTION) verify(eventReporter).onSelectPaymentOption(paymentOptionResultSucceeded.paymentSelection) } @Test fun `resolveTransitionTarget no new card`() { val viewModel = createViewModel( args = PAYMENT_OPTION_CONTRACT_ARGS.copy(newLpm = null) ) var transitionTarget: BaseSheetViewModel.Event<TransitionTarget?>? = null viewModel.transition.observeForever { transitionTarget = it } // no customer, no new card, no paymentMethods val fragmentConfig = FragmentConfigFixtures.DEFAULT viewModel.resolveTransitionTarget(fragmentConfig) assertThat(transitionTarget!!.peekContent()).isNull() } @Test fun `resolveTransitionTarget new card saved`() { val viewModel = createViewModel( args = PAYMENT_OPTION_CONTRACT_ARGS.copy( newLpm = NEW_CARD_PAYMENT_SELECTION.copy( customerRequestedSave = PaymentSelection.CustomerRequestedSave.RequestReuse ) ) ) val transitionTarget = mutableListOf<BaseSheetViewModel.Event<TransitionTarget?>>() viewModel.transition.observeForever { transitionTarget.add(it) } val fragmentConfig = FragmentConfigFixtures.DEFAULT viewModel.resolveTransitionTarget(fragmentConfig) assertThat(transitionTarget).hasSize(2) assertThat(transitionTarget[0].peekContent()).isNull() assertThat(transitionTarget[1].peekContent()).isInstanceOf(TransitionTarget.AddPaymentMethodFull::class.java) } @Test fun `resolveTransitionTarget new card NOT saved`() { val viewModel = createViewModel( args = PAYMENT_OPTION_CONTRACT_ARGS.copy( newLpm = NEW_CARD_PAYMENT_SELECTION.copy( customerRequestedSave = PaymentSelection.CustomerRequestedSave.RequestNoReuse ) ) ) val transitionTarget = mutableListOf<BaseSheetViewModel.Event<TransitionTarget?>>() viewModel.transition.observeForever { transitionTarget.add(it) } val fragmentConfig = FragmentConfigFixtures.DEFAULT viewModel.resolveTransitionTarget(fragmentConfig) assertThat(transitionTarget).hasSize(2) assertThat(transitionTarget[1].peekContent()) .isInstanceOf(TransitionTarget.AddPaymentMethodFull::class.java) viewModel.resolveTransitionTarget(fragmentConfig) assertThat(transitionTarget).hasSize(2) } @Test fun `removePaymentMethod removes it from payment methods list`() = runTest { val cards = PaymentMethodFixtures.createCards(3) val viewModel = createViewModel( args = PAYMENT_OPTION_CONTRACT_ARGS.copy(paymentMethods = cards) ) viewModel.removePaymentMethod(cards[1]) idleLooper() assertThat(viewModel.paymentMethods.value) .containsExactly(cards[0], cards[2]) } @Test fun `Removing selected payment method clears selection`() = runTest { val cards = PaymentMethodFixtures.createCards(3) val viewModel = createViewModel( args = PAYMENT_OPTION_CONTRACT_ARGS.copy(paymentMethods = cards) ) val selection = PaymentSelection.Saved(cards[1]) viewModel.updateSelection(selection) assertThat(viewModel.selection.value).isEqualTo(selection) viewModel.removePaymentMethod(selection.paymentMethod) idleLooper() assertThat(viewModel.selection.value).isNull() } @Test fun `when paymentMethods is empty, primary button and text below button are gone`() = runTest { val paymentMethod = PaymentMethodFixtures.US_BANK_ACCOUNT val viewModel = createViewModel( args = PAYMENT_OPTION_CONTRACT_ARGS.copy( paymentMethods = listOf(paymentMethod) ) ) viewModel.removePaymentMethod(paymentMethod) idleLooper() assertThat(viewModel.paymentMethods.value) .isEmpty() assertThat(viewModel.primaryButtonUIState.value).isNull() assertThat(viewModel.notesText.value).isNull() } @Test fun `setupLink() selects Link when account status is Verified`() = runTest { whenever(linkLauncher.getAccountStatusFlow(any())).thenReturn(flowOf(AccountStatus.Verified)) val viewModel = createViewModel() viewModel.setupLink(PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD) assertThat(viewModel.selection.value).isEqualTo(PaymentSelection.Link) assertThat(viewModel.activeLinkSession.value).isTrue() assertThat(viewModel.isLinkEnabled.value).isTrue() } @Test fun `setupLink() selects Link when account status is VerificationStarted`() = runTest { whenever(linkLauncher.getAccountStatusFlow(any())).thenReturn(flowOf(AccountStatus.VerificationStarted)) val viewModel = createViewModel() viewModel.setupLink(PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD) assertThat(viewModel.selection.value).isEqualTo(PaymentSelection.Link) assertThat(viewModel.activeLinkSession.value).isFalse() assertThat(viewModel.isLinkEnabled.value).isTrue() } @Test fun `setupLink() selects Link when account status is NeedsVerification`() = runTest { whenever(linkLauncher.getAccountStatusFlow(any())).thenReturn(flowOf(AccountStatus.NeedsVerification)) val viewModel = createViewModel() viewModel.setupLink(PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD) assertThat(viewModel.selection.value).isEqualTo(PaymentSelection.Link) assertThat(viewModel.activeLinkSession.value).isFalse() assertThat(viewModel.isLinkEnabled.value).isTrue() } @Test fun `setupLink() enables Link when account status is SignedOut`() = runTest { whenever(linkLauncher.getAccountStatusFlow(any())).thenReturn(flowOf(AccountStatus.SignedOut)) val viewModel = createViewModel() viewModel.setupLink(PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD) assertThat(viewModel.activeLinkSession.value).isFalse() assertThat(viewModel.isLinkEnabled.value).isTrue() } @Test fun `setupLink() disables Link when account status is Error`() = runTest { whenever(linkLauncher.getAccountStatusFlow(any())).thenReturn(flowOf(AccountStatus.Error)) val viewModel = createViewModel() viewModel.setupLink(PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD) assertThat(viewModel.activeLinkSession.value).isFalse() assertThat(viewModel.isLinkEnabled.value).isFalse() } private fun createViewModel( args: PaymentOptionContract.Args = PAYMENT_OPTION_CONTRACT_ARGS ) = PaymentOptionsViewModel( args = args, prefsRepositoryFactory = { prefsRepository }, eventReporter = eventReporter, customerRepository = customerRepository, workContext = testDispatcher, application = ApplicationProvider.getApplicationContext(), logger = Logger.noop(), injectorKey = DUMMY_INJECTOR_KEY, lpmResourceRepository = lpmResourceRepository, addressResourceRepository = mock(), savedStateHandle = SavedStateHandle(), linkLauncher = linkLauncher ) private companion object { private val SELECTION_SAVED_PAYMENT_METHOD = PaymentSelection.Saved( PaymentMethodFixtures.CARD_PAYMENT_METHOD ) private val DEFAULT_PAYMENT_METHOD_CREATE_PARAMS: PaymentMethodCreateParams = DEFAULT_CARD private val NEW_REQUEST_SAVE_PAYMENT_SELECTION = PaymentSelection.New.Card( DEFAULT_PAYMENT_METHOD_CREATE_PARAMS, CardBrand.Visa, customerRequestedSave = PaymentSelection.CustomerRequestedSave.RequestReuse ) private val NEW_REQUEST_DONT_SAVE_PAYMENT_SELECTION = PaymentSelection.New.Card( DEFAULT_PAYMENT_METHOD_CREATE_PARAMS, CardBrand.Visa, customerRequestedSave = PaymentSelection.CustomerRequestedSave.NoRequest ) private val NEW_CARD_PAYMENT_SELECTION = PaymentSelection.New.Card( DEFAULT_CARD, CardBrand.Discover, customerRequestedSave = PaymentSelection.CustomerRequestedSave.NoRequest ) private val PAYMENT_OPTION_CONTRACT_ARGS = PaymentOptionContract.Args( stripeIntent = PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD, paymentMethods = emptyList(), config = PaymentSheetFixtures.CONFIG_CUSTOMER_WITH_GOOGLEPAY, isGooglePayReady = true, newLpm = null, statusBarColor = PaymentSheetFixtures.STATUS_BAR_COLOR, injectorKey = DUMMY_INJECTOR_KEY, enableLogging = false, productUsage = mock() ) private val PAYMENT_METHOD_REPOSITORY_PARAMS = listOf(PaymentMethodFixtures.CARD_PAYMENT_METHOD) } private class MyHostActivity : AppCompatActivity() }
mit
03a4c54674fa9ea36186e2e075f1c7ca
39.576369
117
0.704474
5.261584
false
true
false
false
Xenoage/Zong
core/src/com/xenoage/zong/core/text/FormattedTextParagraph.kt
1
8618
package com.xenoage.zong.core.text import com.xenoage.utils.* import com.xenoage.utils.collections.* import com.xenoage.utils.font.TextMetrics import kotlin.math.max /** * One paragraph within a [FormattedText]. */ class FormattedTextParagraph( /** The elemens of this paragraph */ val elements: List<FormattedTextElement>, /** The horizontal alignment of this paragraph */ val alignment: Alignment ) { /** The measurements of this paragraph. */ val metrics: TextMetrics init { //compute ascent, descent and leading val ascent = elements.max({ it.metrics.ascent }, 0f) val descent = elements.max({ it.metrics.descent }, 0f) val leading = elements.max({ it.metrics.leading }, 0f) val width = elements.sumFloat { it.metrics.width } this.metrics = TextMetrics(ascent, descent, leading, width) } /** The plain text. */ val rawText: String get() = elements.joinToString("") val length: Int get() = elements.sumBy { it.length } /** The height of this paragraph in mm. */ val heightMm: Float get() { var maxAscent = 0f var maxDescentAndLeading = 0f for (element in elements) { val m = element.metrics maxAscent = max(maxAscent, m.ascent) maxDescentAndLeading = max(maxDescentAndLeading, m.descent + m.leading) } return maxAscent + maxDescentAndLeading } /** * Breaks this paragraph up into one or more lines so * that it fits into the given width and returns the result. */ fun lineBreak(width: Float): List<FormattedTextParagraph> { val ret = mutableListOf<FormattedTextParagraph>() if (elements.size == 0) { //nothing to break up ret.add(this) } else { //queue with elements still to format val queue = Queue<FormattedTextElement>(elements.size) queue.addAll(elements) //loop through all elements while (queue.size > 0) { //create list to collect elements for current line val line = Queue<FormattedTextElement>() var lineWidth = 0f //add elements to the line until width is reached do { val currentElement = queue.removeFirst() line.addLast(currentElement) lineWidth += currentElement.metrics.width } while (lineWidth <= width && queue.size > 0) //line too wide? if (lineWidth > width) { //yes. we have to do a line break. //for string elements, we can divide the text and put one part in this //line and the other part into the next one. for symbols, we always begin a new line. val last = line.last() if (last is FormattedTextString) { val lineWidthBeforeLineBreak = lineWidth //first test if line is wide enough for at least one character (if it is a String) //or the whole symbol (if it is a symbol) val firstCharElement = FormattedTextString(last.text.substring(0, 1), last.style) if (firstCharElement.metrics.width > width) { //not enough space for even one character. return empty list. return emptyList() } //spacing character within this line? var lineBreakSuccess = false if (line.containsLineBreakCharacter()) { //go back until the last spacing character. //search for element to cut var searchCuttedElement = line.removeLast() as FormattedTextString lineWidth -= searchCuttedElement.metrics.width var queuedElementsCount = 0 while (false == searchCuttedElement.text.containsLineBreakCharacter()) { queue.addFirst(searchCuttedElement) queuedElementsCount++ searchCuttedElement = line.removeLast() as FormattedTextString lineWidth -= searchCuttedElement.metrics.width } val cuttedElement = searchCuttedElement //find last spacing character that fits into the given width and split the //cuttedElement there var forThisLine: FormattedTextString? = null var forThisLineTrimRight: FormattedTextString? = null for (i in cuttedElement.text.length - 1 downTo 0) { val c = cuttedElement.text[i] if (c.isLineBreakCharacter) { forThisLine = FormattedTextString( cuttedElement.text.substring(0, i + 1), cuttedElement.style) //ignore spaces at the end val forThisLineTrimRightText = forThisLine.text.trimRight() forThisLineTrimRight = if (forThisLineTrimRightText.length > 0) FormattedTextString(forThisLineTrimRightText, forThisLine.style) else null if (forThisLineTrimRight == null || lineWidth + forThisLineTrimRight.metrics.width <= width) break } } //if the left side of the cutted line is now short enough to fit into the width, we had //success and apply the linebreak. otherwise we must do a linebreak in the middle of a word. if (forThisLine != null && (forThisLineTrimRight == null || lineWidth + forThisLineTrimRight.metrics.width <= width)) { lineBreakSuccess = true //complete this line line.addLast(forThisLine) ret.add(FormattedTextParagraph(line.toList(), alignment)) //begin next line if (forThisLine.text.length < cuttedElement.text.length) { val forNextLine = FormattedTextString( cuttedElement.text.substring(forThisLine.text.length), cuttedElement.style) queue.addFirst(forNextLine) } } else { lineBreakSuccess = false lineWidth = lineWidthBeforeLineBreak //restore original line and queue for (i in 0 until queuedElementsCount) { line.addLast(queue.removeFirst()) } line.addLast(cuttedElement) } } if (!lineBreakSuccess) { //there is no spacing character in this line or we had no success using it, //so we have to do a linebreak in the middle of a word. //since we have added element after element, the possible line break must be //within the last element. val cuttedElement = line.removeLast() as FormattedTextString lineWidth -= cuttedElement.metrics.width var forThisLine: FormattedTextString? = null for (i in cuttedElement.text.length - 1 downTo -1) { if (i >= 0) { forThisLine = FormattedTextString( cuttedElement.text.substring(0, i + 1), cuttedElement.style) //ignore spaces at the end val forThisLineTrimRightText = forThisLine.text.trimRight() val forThisLineTrimRight = if (forThisLineTrimRightText.length > 0) FormattedTextString(forThisLineTrimRightText, forThisLine.style) else null if (forThisLineTrimRight == null || lineWidth + forThisLineTrimRight.metrics.width <= width) { break } } else { forThisLine = null } } //complete this line if (forThisLine != null) { line.addLast(forThisLine) } ret.add(FormattedTextParagraph(line.toList(), alignment)) //begin next line if (forThisLine == null || forThisLine.text.length < cuttedElement.text.length) { val forNextLine = FormattedTextString( if (forThisLine != null) cuttedElement.text.substring(forThisLine.text.length) else cuttedElement.text, cuttedElement.style) queue.addFirst(forNextLine) } } } else if (last is FormattedTextSymbol) { if (line.size > 1) { //at least two elements, so one can be placed in this line //move symbol into next line val symbol = line.removeLast() ret.add(FormattedTextParagraph(line.toList(), alignment)) //begin next line queue.addFirst(symbol) } else { //not enough space for even one symbol. return empty list. return emptyList() } } } else { //no. we can use exactly that line. that means, this was //the last line and we are finished. ret.add(FormattedTextParagraph(line.toList(), alignment)) break } } } return ret } /** * Returns true, if a line break character is found in this list * of formatted text elements, but not at the end (trailing spaces are ignored). */ private fun List<FormattedTextElement>.containsLineBreakCharacter(): Boolean { val last = elements.last() for (element in elements) { if (element !== last) { if (element.text.containsLineBreakCharacter()) return true } else { return element.text.trimRight().containsLineBreakCharacter() } } return false } override fun toString(): String = elements.joinToString("") companion object { val defaultAlignment = Alignment.Left } }
agpl-3.0
fe05ac8b95cc8f1d7b085eb7cbcb8f8d
35.516949
103
0.662335
3.881982
false
false
false
false
AndroidX/androidx
wear/compose/integration-tests/demos/src/main/java/androidx/wear/compose/integration/demos/Demos.kt
3
1943
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.integration.demos import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextAlign import androidx.wear.compose.material.Text val Info = DemoCategory( "App Info", listOf( ComposableDemo("App Version") { val version = @Suppress("DEPRECATION") LocalContext.current.packageManager .getPackageInfo(LocalContext.current.packageName, 0).versionName Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = "Version: $version", textAlign = TextAlign.Center, ) } } ), ) /** * [DemoCategory] containing all the top level demo categories. */ val WearComposeDemos = DemoCategory( "Wear Compose Demos", listOf( WearFoundationDemos, WearMaterialDemos, Info ) )
apache-2.0
1d62ceecc5a4dc6e25b2dfa137ab9ef2
30.852459
84
0.668554
4.845387
false
false
false
false
QingMings/flashair
src/main/kotlin/com/iezview/controller/LogController.kt
1
3280
package com.iezview.controller import com.iezview.util.ArrowFactory import com.iezview.util.Config import com.iezview.util.LoggerFormat import com.iezview.util.PathUtil import com.iezview.view.consoleViewStyle import javafx.geometry.Pos import javafx.scene.Node import javafx.scene.layout.HBox import org.fxmisc.richtext.CodeArea import org.fxmisc.richtext.LineNumberFactory import tornadofx.* import java.nio.file.Paths import java.time.LocalDate import java.util.function.IntFunction import java.util.logging.FileHandler import java.util.logging.Level /** * Created by shishifanbuxie on 2017/4/16. * 日志 Controller */ class LogController:Controller(){ companion object{ val GREEN="green" val RED="red" val ORANGE="orange" } val consoleView: CodeArea=CodeArea()//日志输出视图 //配置 log输出位置 val logPath= Paths.get(Config.log)!! val logfilePath= logPath.resolve(LocalDate.now().toString()+".log")!! init { importStylesheet(consoleViewStyle::class) writeLogToFile("log组件初始化") PathUtil.resolvePath(logPath) PathUtil.resolvefile(logfilePath) val fileHandler =FileHandler(logfilePath.toString(),true) fileHandler.formatter=LoggerFormat() log.addHandler(fileHandler) subscribe<writeLogEvent>{event-> writeOutLog(event.loglevel,event.message)} subscribe<cleanLogEvent>{cleanlog()} } /** * RichText 控件,用来显示日志输出 */ fun regConsoleView():CodeArea{ var numberF= LineNumberFactory.get(consoleView)//行号 var arrowF= ArrowFactory(consoleView.currentParagraphProperty())//箭头指示 var graphicF = IntFunction<Node> { line -> val hbox = HBox( arrowF.apply(line)) hbox.alignment = Pos.CENTER_LEFT return@IntFunction hbox } consoleView.setParagraphGraphicFactory(graphicF) consoleView.isEditable=false//禁止编辑 return consoleView } /** * 写日志 */ fun writeOutLog(logLevel:Level, message:String):Unit{ if(logLevel==Level.INFO){ log(message, GREEN) log.info(message) }else if(logLevel== Level.WARNING){ log(message, ORANGE) log.warning(message) }else{ log(message, RED) log.warning(message) } } /** * 写日志到文件 */ fun writeLogToFile(message: String){ log.info(message) } /** * 打印日志 */ private fun log(message: String,color:String){ var range = consoleView.selection var start =range.start; consoleView.appendText(message+"\n") range = consoleView.selection consoleView.setStyleClass(start,range.end,color) consoleView.moveTo(consoleView.paragraphs.size-1,0) consoleView.requestFollowCaret() consoleView.isAutoScrollOnDragDesired=true } /** * 清理日志 */ fun cleanlog():Unit=consoleView.clear() } class writeLogEvent(val loglevel: Level,val message: String) :FXEvent(EventBus.RunOn.ApplicationThread)//写日志事件 class cleanLogEvent :FXEvent(EventBus.RunOn.ApplicationThread)//清除日志事件
mit
3441b3d4f14d97292e037e292d3ae76c
29.553398
110
0.667514
4.033333
false
false
false
false
hotchemi/khronos
src/main/kotlin/khronos/Duration.kt
1
652
package khronos import java.util.* class Duration(internal val unit: Int, internal val value: Int) { val ago = calculate(from = Date(), value = -value) val since = calculate(from = Date(), value = value) private fun calculate(from: Date, value: Int): Date { calendar.time = from calendar.add(unit, value) return calendar.time } override fun hashCode() = Objects.hashCode(unit) * Objects.hashCode(value) override fun equals(other: Any?): Boolean { if (other == null || other !is Duration) { return false } return unit == other.unit && value == other.value } }
apache-2.0
8cb53bc47522ed55a8f28e02b3443e2f
26.208333
78
0.613497
4.075
false
false
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-api/src/main/kotlin/org/nd4j/samediff/frameworkimport/runner/DefaultImportRunner.kt
1
19619
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.runner import org.nd4j.autodiff.functions.DifferentialFunction import org.nd4j.autodiff.samediff.SameDiff import org.nd4j.autodiff.samediff.VariableType import org.nd4j.common.io.ReflectionUtils import org.nd4j.graph.OpType import org.nd4j.ir.OpNamespace import org.nd4j.linalg.api.ndarray.INDArray import org.nd4j.linalg.api.ops.CustomOp import org.nd4j.linalg.api.ops.DynamicCustomOp import org.nd4j.linalg.api.ops.Op import org.nd4j.linalg.factory.Nd4j import org.nd4j.samediff.frameworkimport.context.MappingContext import org.nd4j.samediff.frameworkimport.convertNd4jDataTypeFromNameSpaceTensorDataType import org.nd4j.samediff.frameworkimport.ndarrayFromNameSpaceTensor import org.nd4j.samediff.frameworkimport.setNameForFunctionFromDescriptors import org.nd4j.shade.protobuf.GeneratedMessageV3 import org.nd4j.shade.protobuf.ProtocolMessageEnum import org.nd4j.weightinit.impl.ZeroInitScheme import java.lang.IllegalArgumentException import java.lang.reflect.Modifier /** * The default implementation of [ImportRunner]. * * @author Adam Gibson */ class DefaultImportRunner<GRAPH_TYPE: GeneratedMessageV3, NODE_TYPE : GeneratedMessageV3, OP_DEF_TYPE : GeneratedMessageV3, TENSOR_TYPE : GeneratedMessageV3, ATTR_DEF_TYPE : GeneratedMessageV3, ATTR_VALUE_TYPE : GeneratedMessageV3, DATA_TYPE: ProtocolMessageEnum> : ImportRunner<GRAPH_TYPE, NODE_TYPE, OP_DEF_TYPE, TENSOR_TYPE, ATTR_DEF_TYPE, ATTR_VALUE_TYPE, DATA_TYPE> { override fun <GRAPH_TYPE : GeneratedMessageV3, NODE_TYPE : GeneratedMessageV3, OP_DEF_TYPE : GeneratedMessageV3, TENSOR_TYPE : GeneratedMessageV3, ATTR_DEF_TYPE : GeneratedMessageV3, ATTR_VALUE_TYPE : GeneratedMessageV3, DATA_TYPE : ProtocolMessageEnum> initAttributes( df: DifferentialFunction, sd: SameDiff, descriptorAndContext: Pair<MappingContext<GRAPH_TYPE, NODE_TYPE, OP_DEF_TYPE, TENSOR_TYPE, ATTR_DEF_TYPE, ATTR_VALUE_TYPE, DATA_TYPE>, OpNamespace.OpDescriptor> ) { val applied = descriptorAndContext val mappingContext = applied.first when (df.opType()) { Op.Type.CUSTOM,Op.Type.LOGIC -> { val dynamicCustomOp = df as DynamicCustomOp val grouped = descriptorAndContext.second.argDescriptorList.groupBy { descriptor -> descriptor.argType } val sortedMap = HashMap<OpNamespace.ArgDescriptor.ArgType, List<OpNamespace.ArgDescriptor>>() grouped.forEach { (argType, list) -> sortedMap[argType] = list.sortedBy { arg -> arg.argIndex } } sortedMap.forEach { (argType, listOfArgsSortedByIndex) -> when (argType) { OpNamespace.ArgDescriptor.ArgType.INPUT_TENSOR -> { if(df.opType() != Op.Type.LOGIC) { val opInputs = sd.ops[dynamicCustomOp.ownName] if(opInputs == null) throw IllegalArgumentException("No op with name ${dynamicCustomOp.ownName} found!") for(input in opInputs!!.inputsToOp) { val name = if(mappingContext.graph().hasConstantInitializer(input)) { input } else { "${input}:0" } //removes the suffix if(!sd.hasVariable(input)) { if(mappingContext.graph().hasConstantInitializer("${input}:0") || sd.hasVariable(name)) { sd.renameVariable(name,input) } } } val args = dynamicCustomOp.args() val arraysToAdd = ArrayList<INDArray>() listOfArgsSortedByIndex.forEachIndexed { index, argDescriptor -> val convertedTensor = ndarrayFromNameSpaceTensor(argDescriptor.inputValue) if (index < args.size) { val arg = args[index] if (arg.variableType != VariableType.ARRAY) { if (arg.shape == null) { val emptyLongArray = LongArray(0) arg.setShape(*emptyLongArray) } arraysToAdd.add(convertedTensor) } } } //note we don't add arrays one at a time because addInputArgument requires all the input arrays to be added at once //dynamicCustomOp.addInputArgument(*arraysToAdd.toTypedArray()) } } OpNamespace.ArgDescriptor.ArgType.INT64, OpNamespace.ArgDescriptor.ArgType.INT32 -> { listOfArgsSortedByIndex.forEach { dynamicCustomOp.addIArgument(it.int64Value) } } OpNamespace.ArgDescriptor.ArgType.DOUBLE, OpNamespace.ArgDescriptor.ArgType.FLOAT -> { listOfArgsSortedByIndex.forEach { dynamicCustomOp.addTArgument(it.doubleValue) } } OpNamespace.ArgDescriptor.ArgType.OUTPUT_TENSOR -> { listOfArgsSortedByIndex.forEach { val convertedTensor = ndarrayFromNameSpaceTensor(it.inputValue) dynamicCustomOp.addOutputArgument(convertedTensor) } } //allow strings, but only for cases of setting a value in java OpNamespace.ArgDescriptor.ArgType.STRING -> {} OpNamespace.ArgDescriptor.ArgType.BOOL -> { listOfArgsSortedByIndex.forEach { dynamicCustomOp.addBArgument(it.boolValue) } } OpNamespace.ArgDescriptor.ArgType.DATA_TYPE -> { listOfArgsSortedByIndex.forEach { val dtype = convertNd4jDataTypeFromNameSpaceTensorDataType(it.dataTypeValue!!) val dtypeJavaClass = Class.forName("org.nd4j.linalg.api.buffer.DataType") dynamicCustomOp.addDArgument(dtype) df.javaClass.declaredFields.forEach { field -> if (!Modifier.isStatic(field.modifiers) && !Modifier.isFinal(field.modifiers) && dtypeJavaClass.isAssignableFrom(field.type) ) { field.isAccessible = true ReflectionUtils.setField(field, df, dtype) } } } } else -> { throw IllegalArgumentException("Illegal type") } } //set any left over fields if they're found setNameForFunctionFromDescriptors(listOfArgsSortedByIndex, df) } val customOp = df as CustomOp //important to call this as we may not have configured all fields customOp.configureFromArguments() df.configureWithSameDiff(sd) } Op.Type.SCALAR -> { applied.second.argDescriptorList.forEach { argDescriptor -> val field = ReflectionUtils.findField(df.javaClass, argDescriptor.name) if (field != null) { field.isAccessible = true when (argDescriptor.name) { "x", "y", "z" -> { val createdNDArray = mappingContext.tensorInputFor(argDescriptor.name).toNd4jNDArray() ReflectionUtils.setField(field, df, createdNDArray) } else -> { val scalarField = ReflectionUtils.findField(df.javaClass, "scalarValue") scalarField.isAccessible = true //access the first input (should have been set) and make sure the scalar type is the //the same val firstValue = df.arg(0) val dtype = firstValue.dataType() when (argDescriptor.argType) { OpNamespace.ArgDescriptor.ArgType.DOUBLE -> { val nd4jScalarValue = Nd4j.scalar(argDescriptor.doubleValue).castTo(dtype) ReflectionUtils.setField(scalarField, df, nd4jScalarValue) } OpNamespace.ArgDescriptor.ArgType.FLOAT -> { val nd4jScalarValue = Nd4j.scalar(argDescriptor.floatValue).castTo(dtype) ReflectionUtils.setField(scalarField, df, nd4jScalarValue) } OpNamespace.ArgDescriptor.ArgType.INT32 -> { val nd4jScalarValue = Nd4j.scalar(argDescriptor.int32Value).castTo(dtype) ReflectionUtils.setField(scalarField, df, nd4jScalarValue) } OpNamespace.ArgDescriptor.ArgType.INT64 -> { val nd4jScalarValue = Nd4j.scalar(argDescriptor.int64Value).castTo(dtype) ReflectionUtils.setField(scalarField, df, nd4jScalarValue) } OpNamespace.ArgDescriptor.ArgType.BOOL -> { val nd4jScalarValue = Nd4j.scalar(argDescriptor.boolValue).castTo(dtype) ReflectionUtils.setField(scalarField, df, nd4jScalarValue) } OpNamespace.ArgDescriptor.ArgType.STRING -> { val nd4jScalarValue = Nd4j.scalar(argDescriptor.stringValue).castTo(dtype) ReflectionUtils.setField(scalarField, df, nd4jScalarValue) } else -> { throw IllegalArgumentException("Trying to convert invalid argument type " + argDescriptor.argType) } } } } } else { if (argDescriptor.argType in listOf( OpNamespace.ArgDescriptor.ArgType.INT64, OpNamespace.ArgDescriptor.ArgType.DOUBLE, OpNamespace.ArgDescriptor.ArgType.INT32, OpNamespace.ArgDescriptor.ArgType.FLOAT ) ) { val scalarField = ReflectionUtils.findField(df.javaClass, "scalarValue") scalarField.isAccessible = true //access the first input (should have been set) and make sure the scalar type is the //the same val irNode = mappingContext.irNode() val firstValue = sd.getVariable(irNode.inputAt(0)) val dtype = firstValue.dataType() when (argDescriptor.argType) { OpNamespace.ArgDescriptor.ArgType.DOUBLE -> { val nd4jScalarValue = Nd4j.scalar(argDescriptor.doubleValue).castTo(dtype) ReflectionUtils.setField(scalarField, df, nd4jScalarValue) } OpNamespace.ArgDescriptor.ArgType.FLOAT -> { val nd4jScalarValue = Nd4j.scalar(argDescriptor.floatValue).castTo(dtype) ReflectionUtils.setField(scalarField, df, nd4jScalarValue) } OpNamespace.ArgDescriptor.ArgType.INT32 -> { val nd4jScalarValue = Nd4j.scalar(argDescriptor.int32Value).castTo(dtype) ReflectionUtils.setField(scalarField, df, nd4jScalarValue) } OpNamespace.ArgDescriptor.ArgType.INT64 -> { val nd4jScalarValue = Nd4j.scalar(argDescriptor.int64Value).castTo(dtype) ReflectionUtils.setField(scalarField, df, nd4jScalarValue) } OpNamespace.ArgDescriptor.ArgType.BOOL -> { val nd4jScalarValue = Nd4j.scalar(argDescriptor.boolValue).castTo(dtype) ReflectionUtils.setField(scalarField, df, nd4jScalarValue) } OpNamespace.ArgDescriptor.ArgType.STRING -> { val nd4jScalarValue = Nd4j.scalar(argDescriptor.stringValue).castTo(dtype) ReflectionUtils.setField(scalarField, df, nd4jScalarValue) } else -> { throw IllegalArgumentException("Trying to convert invalid argument type " + argDescriptor.argType) } } } } } //set any left over fields if they're found setNameForFunctionFromDescriptors(applied.second.argDescriptorList, df) } else -> { var hasDimensions = false if(df.opType() == Op.Type.REDUCE_LONG || df.opType() == Op.Type.REDUCE_BOOL || df.opType() == Op.Type.REDUCE_FLOAT || df.opType() == Op.Type.REDUCE_SAME || df.opType() == Op.Type.INDEXREDUCE && df.args().size > 1) { hasDimensions = true } applied.second.argDescriptorList.forEach { argDescriptor -> if (argDescriptor.name == "dimensions") hasDimensions = true val field = ReflectionUtils.findField(df.javaClass, argDescriptor.name) if (field != null) { field.isAccessible = true when (argDescriptor.name) { "x", "y", "z" -> { val createdNDArray = mappingContext.tensorInputFor(argDescriptor.name).toNd4jNDArray() ReflectionUtils.setField(field, df, createdNDArray) } "keepDims" -> ReflectionUtils.setField(field, df, argDescriptor.boolValue) else -> { } } } } if (hasDimensions) { //dimensions sorted by index val dimArgs: IntArray = when { df.args().size > 1 && df.arg(1).arr != null -> { df.arg(1).arr.toIntVector() } else -> { applied.second.argDescriptorList.filter { argDescriptor -> argDescriptor.name.contains("dimensions") } .sortedBy { argDescriptor -> argDescriptor.argIndex } .map { argDescriptor -> argDescriptor.int64Value.toInt() }.toIntArray() } } val dimensionsField = ReflectionUtils.findField(df.javaClass, "dimensions") val dimensionzField = ReflectionUtils.findField(df.javaClass, "dimensionz") val isEmptyReduce = ReflectionUtils.findField(df.javaClass,"isEmptyReduce") if (dimensionsField != null) { dimensionsField.isAccessible = true if (intArrayOf(0).javaClass.isAssignableFrom(dimensionsField.type)) { ReflectionUtils.setField(dimensionsField, df, dimArgs) } } if (dimensionzField != null) { dimensionzField.isAccessible = true if (INDArray::class.java.isAssignableFrom(dimensionzField.type)) { val buffer = Nd4j.createBuffer(dimArgs) val createdArr = Nd4j.create(buffer) ReflectionUtils.setField(dimensionzField, df, createdArr) } } if(isEmptyReduce != null) { isEmptyReduce.isAccessible = true if(dimArgs.isEmpty()) { ReflectionUtils.setField(isEmptyReduce,df,true) } } } //set any left over fields if they're found setNameForFunctionFromDescriptors(applied.second.argDescriptorList, df) } } } }
apache-2.0
e41f5af45379ff3305ff41db213bef16
51.741935
273
0.482491
5.826849
false
false
false
false
google/dokka
runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/Utils.kt
2
1936
package org.jetbrains.dokka.gradle import com.intellij.rt.execution.junit.FileComparisonFailure import java.io.File import java.io.IOException import java.nio.file.* import java.nio.file.attribute.BasicFileAttributes fun File.writeStructure(builder: StringBuilder, relativeTo: File = this, spaces: Int = 0) { builder.append(" ".repeat(spaces)) val out = if (this != relativeTo) this.relativeTo(relativeTo) else this builder.append(out) if (this.isDirectory) { builder.appendln("/") this.listFiles().sortedBy { it.name }.forEach { it.writeStructure(builder, this, spaces + 4) } } else { builder.appendln() } } fun assertEqualsIgnoringSeparators(expectedFile: File, output: String) { if (!expectedFile.exists()) expectedFile.createNewFile() val expectedText = expectedFile.readText().replace("\r\n", "\n") val actualText = output.replace("\r\n", "\n") if (expectedText != actualText) throw FileComparisonFailure("", expectedText, actualText, expectedFile.canonicalPath) } class CopyFileVisitor(private var sourcePath: Path?, private val targetPath: Path) : SimpleFileVisitor<Path>() { @Throws(IOException::class) override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult { if (sourcePath == null) { sourcePath = dir } else { Files.createDirectories(targetPath.resolve(sourcePath?.relativize(dir))) } return FileVisitResult.CONTINUE } @Throws(IOException::class) override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { Files.copy(file, targetPath.resolve(sourcePath?.relativize(file)), StandardCopyOption.REPLACE_EXISTING) return FileVisitResult.CONTINUE } } fun Path.copy(to: Path) { Files.walkFileTree(this, CopyFileVisitor(this, to)) }
apache-2.0
b05518751479c477f4f2c1462a9bdc86
33.571429
112
0.680785
4.598575
false
false
false
false
androidx/androidx
health/health-services-client/src/main/java/androidx/health/services/client/VersionApiService.kt
3
1788
/* * Copyright (C) 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.health.services.client import android.app.Service import android.content.Intent import android.os.IBinder import android.util.Log import androidx.annotation.RestrictTo import androidx.annotation.RestrictTo.Scope import androidx.health.services.client.impl.IVersionApiService import androidx.health.services.client.impl.IpcConstants /** Service that allows querying the canonical SDK version used to compile this app. */ @RestrictTo(Scope.LIBRARY) public class VersionApiService : Service() { private val stub: VersionApiServiceStub = VersionApiServiceStub() override fun onBind(intent: Intent?): IBinder? { if (intent?.action != IpcConstants.VERSION_API_BIND_ACTION) { Log.w(TAG, "Bind request with invalid action [${intent?.action}]") return null } return stub } private class VersionApiServiceStub : IVersionApiService.Stub() { override fun getVersionApiServiceVersion(): Int = VERSION_API_SERVICE_VERSION override fun getSdkVersion(): Int = CANONICAL_SDK_VERSION } private companion object { private const val TAG = "VersionApiService" } }
apache-2.0
3fa92d9ad02ac9fd9ff1e996dc72fb79
34.058824
87
0.734899
4.403941
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/chat/prv/sync/MessengerWorker.kt
1
16999
package me.proxer.app.chat.prv.sync import android.content.Context import androidx.work.Constraints import androidx.work.Data import androidx.work.ExistingWorkPolicy import androidx.work.NetworkType import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkInfo import androidx.work.WorkManager import androidx.work.Worker import androidx.work.WorkerParameters import com.rubengees.rxbus.RxBus import me.proxer.app.chat.prv.LocalConference import me.proxer.app.chat.prv.LocalMessage import me.proxer.app.chat.prv.conference.ConferenceFragmentPingEvent import me.proxer.app.chat.prv.message.MessengerFragmentPingEvent import me.proxer.app.exception.ChatException import me.proxer.app.exception.ChatMessageException import me.proxer.app.exception.ChatSendMessageException import me.proxer.app.exception.ChatSynchronizationException import me.proxer.app.util.WorkerUtils import me.proxer.app.util.data.PreferenceHelper import me.proxer.app.util.data.StorageHelper import me.proxer.app.util.extension.safeInject import me.proxer.app.util.extension.toInstantBP import me.proxer.app.util.extension.toLocalConference import me.proxer.app.util.extension.toLocalMessage import me.proxer.library.ProxerApi import me.proxer.library.ProxerCall import me.proxer.library.ProxerException import me.proxer.library.entity.messenger.Conference import me.proxer.library.entity.messenger.Message import org.koin.core.KoinComponent import timber.log.Timber import java.util.LinkedHashSet import java.util.concurrent.TimeUnit /** * @author Ruben Gees */ class MessengerWorker( context: Context, workerParams: WorkerParameters ) : Worker(context, workerParams), KoinComponent { companion object : KoinComponent { const val CONFERENCES_ON_PAGE = 48 const val MESSAGES_ON_PAGE = 30 private const val NAME = "MessengerWorker" private const val CONFERENCE_ID_ARGUMENT = "conference_id" val isRunning get() = workManager.getWorkInfosForUniqueWork(NAME).get() .all { info -> info.state == WorkInfo.State.RUNNING } private val bus by safeInject<RxBus>() private val workManager by safeInject<WorkManager>() private val storageHelper by safeInject<StorageHelper>() private val preferenceHelper by safeInject<PreferenceHelper>() fun enqueueSynchronizationIfPossible() = when { canSchedule() -> enqueueSynchronization() else -> cancel() } fun enqueueSynchronization() = doEnqueue() fun enqueueMessageLoad(conferenceId: Long) = doEnqueue(conferenceId = conferenceId) fun cancel() { workManager.cancelUniqueWork(NAME) } private fun reschedule(synchronizationResult: SynchronizationResult) { if (canSchedule() && synchronizationResult != SynchronizationResult.ERROR) { if (synchronizationResult == SynchronizationResult.CHANGES || bus.post(MessengerFragmentPingEvent())) { storageHelper.resetChatInterval() doEnqueue(3_000L) } else if (bus.post(ConferenceFragmentPingEvent())) { storageHelper.resetChatInterval() doEnqueue(10_000L) } else { storageHelper.incrementChatInterval() doEnqueue(storageHelper.chatInterval) } } } private fun doEnqueue(startTime: Long? = null, conferenceId: Long? = null) { val workRequest = OneTimeWorkRequestBuilder<MessengerWorker>() .setConstraints( Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() ) .apply { if (startTime != null) setInitialDelay(startTime, TimeUnit.MILLISECONDS) } .setInputData(Data.Builder() .apply { if (conferenceId != null) putLong(CONFERENCE_ID_ARGUMENT, conferenceId) } .build() ) .build() workManager.beginUniqueWork(NAME, ExistingWorkPolicy.REPLACE, workRequest).enqueue() } private fun canSchedule() = preferenceHelper.areChatNotificationsEnabled || bus.post(ConferenceFragmentPingEvent()) || bus.post(MessengerFragmentPingEvent()) private fun canShowNotification() = preferenceHelper.areChatNotificationsEnabled && !bus.post(ConferenceFragmentPingEvent()) && !bus.post(MessengerFragmentPingEvent()) } private val conferenceId: Long get() = inputData.getLong(CONFERENCE_ID_ARGUMENT, 0L) private val api by safeInject<ProxerApi>() private val storageHelper by safeInject<StorageHelper>() private val messengerDatabase by safeInject<MessengerDatabase>() private val messengerDao by safeInject<MessengerDao>() private var currentCall: ProxerCall<*>? = null override fun onStopped() { currentCall?.cancel() } override fun doWork(): Result { if (!storageHelper.isLoggedIn) return Result.failure() val synchronizationResult = when (conferenceId) { 0L -> try { handleSynchronization() } catch (error: Throwable) { handleSynchronizationError(error) } else -> try { handleLoadMoreMessages(conferenceId) } catch (error: Throwable) { handleLoadMoreMessagesError(error) } } reschedule(synchronizationResult) return if (synchronizationResult != SynchronizationResult.ERROR) Result.success() else Result.failure() } private fun handleSynchronization(): SynchronizationResult { val newConferencesAndMessages = synchronize() storageHelper.areConferencesSynchronized = true val maxNewDate = newConferencesAndMessages.flatMap { it.value }.maxBy { it.date }?.date if (!isStopped && newConferencesAndMessages.isNotEmpty()) { bus.post(SynchronizationEvent()) } if (!isStopped && maxNewDate != null && maxNewDate > storageHelper.lastChatMessageDate) { if (canShowNotification()) { showNotification(applicationContext) } storageHelper.lastChatMessageDate = maxNewDate } MessengerShortcuts.updateShareTargets(applicationContext) return when (newConferencesAndMessages.isNotEmpty()) { true -> SynchronizationResult.CHANGES false -> SynchronizationResult.NO_CHANGES } } private fun handleSynchronizationError(error: Throwable): SynchronizationResult { Timber.e(error) if (!isStopped) { when (error) { is ChatException -> bus.post(MessengerErrorEvent(error)) else -> bus.post(MessengerErrorEvent(ChatSynchronizationException(error))) } } return when (WorkerUtils.shouldRetryForError(error)) { true -> SynchronizationResult.NO_CHANGES false -> SynchronizationResult.ERROR } } private fun handleLoadMoreMessagesError(error: Throwable): SynchronizationResult { Timber.e(error) if (!isStopped) { when (error) { is ChatException -> bus.post(MessengerErrorEvent(error)) else -> bus.post(MessengerErrorEvent(ChatMessageException(error))) } } return when (WorkerUtils.shouldRetryForError(error)) { true -> SynchronizationResult.NO_CHANGES false -> SynchronizationResult.ERROR } } private fun handleLoadMoreMessages(conferenceId: Long): SynchronizationResult { val fetchedMessages = loadMoreMessages(conferenceId) fetchedMessages.maxBy { it.date }?.date?.toInstantBP()?.let { mostRecentDate -> if (mostRecentDate.isAfter(storageHelper.lastChatMessageDate)) { storageHelper.lastChatMessageDate = mostRecentDate } } return SynchronizationResult.CHANGES } @Suppress("RethrowCaughtException") private fun synchronize(): Map<LocalConference, List<LocalMessage>> { val sentMessages = sendMessages() val newConferencesAndMessages = try { markConferencesAsRead( messengerDao.getConferencesToMarkAsRead() .asSequence() .plus(sentMessages.map { messengerDao.findConference(it.conferenceId) }) .distinct() .filterNotNull() .toList() ) fetchConferences().associate { conference -> fetchNewMessages(conference).let { (messages, isFullyLoaded) -> val isLocallyFullyLoaded = messengerDao.findConference(conference.id.toLong()) ?.isFullyLoaded == true conference.toLocalConference(isLocallyFullyLoaded || isFullyLoaded) to messages.map { it.toLocalMessage() }.asReversed() } } } catch (error: Throwable) { messengerDatabase.runInTransaction { sentMessages.forEach { messengerDao.deleteMessageToSend(it.id) } } throw error } messengerDatabase.runInTransaction { newConferencesAndMessages.let { messengerDao.insertConferences(it.keys.toList()) messengerDao.insertMessages(it.values.flatten()) } sentMessages.forEach { messengerDao.deleteMessageToSend(it.id) } } return newConferencesAndMessages } private fun loadMoreMessages(conferenceId: Long): List<Message> { val fetchedMessages = fetchMoreMessages(conferenceId) messengerDatabase.runInTransaction { messengerDao.insertMessages(fetchedMessages.map { it.toLocalMessage() }) if (fetchedMessages.size < MESSAGES_ON_PAGE) { messengerDao.markConferenceAsFullyLoaded(conferenceId) } } return fetchedMessages } @Suppress("RethrowCaughtException") private fun sendMessages() = messengerDao.getMessagesToSend().apply { forEachIndexed { index, (messageId, conferenceId, _, _, message) -> val result = try { api.messenger.sendMessage(conferenceId.toString(), message) .build() .also { currentCall = it } .execute() } catch (error: ProxerException) { if (error.cause?.stackTrace?.find { it.methodName.contains("read") } != null) { Timber.w("Error while sending message. Removing it to avoid sending duplicate.") // The message was sent, but we did not receive a proper api answer due to slow network, return // non-null to handle it like the non-empty result case. "error" } else { // The message was most likely not sent, but the previous ones are. Delete them to avoid resending. messengerDatabase.runInTransaction { for (i in 0 until index) { messengerDao.deleteMessageToSend(get(i).id) } } throw error } } // Per documentation: The api may return some String in case something went wrong. if (result != null) { // Delete all messages we have correctly sent already. messengerDatabase.runInTransaction { for (i in 0..index) { messengerDao.deleteMessageToSend(get(i).id) } } throw ChatSendMessageException( ProxerException( ProxerException.ErrorType.SERVER, ProxerException.ServerErrorType.MESSAGES_INVALID_MESSAGE, result ), messageId ) } } } private fun markConferencesAsRead(conferenceToMarkAsRead: List<LocalConference>) = conferenceToMarkAsRead.forEach { api.messenger.markConferenceAsRead(it.id.toString()) .build() .also { call -> currentCall = call } .execute() } private fun fetchConferences(): Collection<Conference> { val changedConferences = LinkedHashSet<Conference>() var page = 0 while (true) { val fetchedConferences = api.messenger.conferences() .page(page) .build() .also { currentCall = it } .safeExecute() changedConferences += fetchedConferences.filter { it != messengerDao.findConference(it.id.toLong())?.toNonLocalConference() } if (changedConferences.size / (page + 1) < CONFERENCES_ON_PAGE) { break } else { page++ } } return changedConferences } private fun fetchNewMessages(conference: Conference): Pair<List<Message>, Boolean> { val mostRecentLocalMessage = messengerDao.findMostRecentMessageForConference(conference.id.toLong()) return when (val mostRecentMessage = mostRecentLocalMessage?.toNonLocalMessage()) { null -> fetchForEmptyConference(conference) else -> fetchForExistingConference(conference, mostRecentMessage) } } private fun fetchForEmptyConference(conference: Conference): Pair<List<Message>, Boolean> { val newMessages = mutableListOf<Message>() var unreadAmount = 0 var nextId = "0" while (unreadAmount < conference.unreadMessageAmount) { val fetchedMessages = api.messenger.messages() .conferenceId(conference.id) .messageId(nextId) .markAsRead(false) .build() .also { currentCall = it } .safeExecute() newMessages += fetchedMessages if (fetchedMessages.size < MESSAGES_ON_PAGE) { return newMessages to true } else { unreadAmount += fetchedMessages.size nextId = fetchedMessages.first().id } } return newMessages to false } private fun fetchForExistingConference( conference: Conference, mostRecentMessage: Message ): Pair<List<Message>, Boolean> { val mostRecentMessageIdBeforeUpdate = mostRecentMessage.id.toLong() val newMessages = mutableListOf<Message>() var existingUnreadMessageAmount = messengerDao.getUnreadMessageAmountForConference( conference.id.toLong(), conference.lastReadMessageId.toLong() ) var currentMessage: Message = mostRecentMessage var nextId = "0" while (currentMessage.date < conference.date || existingUnreadMessageAmount < conference.unreadMessageAmount) { val fetchedMessages = api.messenger.messages() .conferenceId(conference.id) .messageId(nextId) .markAsRead(false) .build() .also { currentCall = it } .safeExecute() newMessages += fetchedMessages if (fetchedMessages.size < MESSAGES_ON_PAGE) { return newMessages.filter { it.id.toLong() > mostRecentMessageIdBeforeUpdate } to true } else { existingUnreadMessageAmount += fetchedMessages.size currentMessage = fetchedMessages.last() nextId = fetchedMessages.first().id } } return newMessages.filter { it.id.toLong() > mostRecentMessageIdBeforeUpdate } to false } private fun fetchMoreMessages(conferenceId: Long) = api.messenger.messages() .conferenceId(conferenceId.toString()) .messageId(messengerDao.findOldestMessageForConference(conferenceId)?.id?.toString() ?: "0") .markAsRead(false) .build() .also { currentCall = it } .safeExecute() .asReversed() private fun showNotification(context: Context) { val unreadMap = messengerDao.getUnreadConferences().associateWith { messengerDao .getMostRecentMessagesForConference(it.id, it.unreadMessageAmount) .asReversed() } MessengerNotifications.showOrUpdate(context, unreadMap) } class SynchronizationEvent private enum class SynchronizationResult { CHANGES, NO_CHANGES, ERROR } }
gpl-3.0
56df7cc7514bbea02b17e54e5cfcbbc8
35.714903
119
0.615448
5.338882
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/nbt/lang/format/NbttFormattingModelBuilder.kt
1
2744
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.lang.format import com.demonwav.mcdev.nbt.lang.NbttLanguage import com.demonwav.mcdev.nbt.lang.gen.psi.NbttTypes import com.intellij.formatting.FormattingContext import com.intellij.formatting.FormattingModel import com.intellij.formatting.FormattingModelBuilder import com.intellij.formatting.FormattingModelProvider import com.intellij.formatting.Indent import com.intellij.formatting.SpacingBuilder import com.intellij.psi.codeStyle.CodeStyleSettings class NbttFormattingModelBuilder : FormattingModelBuilder { override fun createModel(formattingContext: FormattingContext): FormattingModel { val block = NbttBlock(formattingContext.node, formattingContext.codeStyleSettings, Indent.getNoneIndent(), null) return FormattingModelProvider.createFormattingModelForPsiFile( formattingContext.containingFile, block, formattingContext.codeStyleSettings ) } companion object { fun createSpacingBuilder(settings: CodeStyleSettings): SpacingBuilder { val nbttSettings = settings.getCustomSettings(NbttCodeStyleSettings::class.java) val commonSettings = settings.getCommonSettings(NbttLanguage) val spacesBeforeComma = if (commonSettings.SPACE_BEFORE_COMMA) 1 else 0 val spacesBeforeColon = if (nbttSettings.SPACE_BEFORE_COLON) 1 else 0 val spacesAfterColon = if (nbttSettings.SPACE_AFTER_COLON) 1 else 0 return SpacingBuilder(settings, NbttLanguage) .before(NbttTypes.COLON).spacing(spacesBeforeColon, spacesBeforeColon, 0, false, 0) .after(NbttTypes.COLON).spacing(spacesAfterColon, spacesAfterColon, 0, false, 0) // Empty blocks .between(NbttTypes.LBRACKET, NbttTypes.RBRACKET).spacing(0, 0, 0, false, 0) .between(NbttTypes.LPAREN, NbttTypes.RPAREN).spacing(0, 0, 0, false, 0) .between(NbttTypes.LBRACE, NbttTypes.RBRACE).spacing(0, 0, 0, false, 0) // Non-empty blocks .withinPair(NbttTypes.LBRACKET, NbttTypes.RBRACKET).spaceIf(commonSettings.SPACE_WITHIN_BRACKETS, true) .withinPair(NbttTypes.LPAREN, NbttTypes.RPAREN).spaceIf(commonSettings.SPACE_WITHIN_PARENTHESES, true) .withinPair(NbttTypes.LBRACE, NbttTypes.RBRACE).spaceIf(commonSettings.SPACE_WITHIN_BRACES, true) .before(NbttTypes.COMMA).spacing(spacesBeforeComma, spacesBeforeComma, 0, false, 0) .after(NbttTypes.COMMA).spaceIf(commonSettings.SPACE_AFTER_COMMA) } } }
mit
29b0212760ce8c77d81aa85ebfc43a88
47.140351
120
0.715743
4.611765
false
false
false
false
konrad-jamrozik/utilities
src/test/kotlin/com/konradjamrozik/PathExtensionsKtTest.kt
1
1496
// Author: Konrad Jamrozik, github.com/konrad-jamrozik package com.konradjamrozik import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.containsInAnyOrder import org.hamcrest.core.IsEqual import org.junit.jupiter.api.Test import java.nio.file.Path internal class PathExtensionsKtTest { @Test fun `removes second column`() { val fooText = """ |headerText_no1 second.column.title Third-Column:sub.title | 0.0 0 0.1 | 20.0 10 .7 | 300.0 50 33 """.trimMargin() // Act val actual = fooText.removeColumn(2) assertThat(actual, IsEqual(""" |headerText_no1 Third-Column:sub.title | 0.0 0.1 | 20.0 .7 | 300.0 33 """.trimMargin())) } @Test fun `replaces text in all files in dir`() { val fooText = "contents 1\nabc-contentsX-cde 2" val barText = "3contentscont\nents3" val quxText = "do not replace contents" val dir: Path = mapOf( "foo.txt" to fooText, "bar.txt" to barText, "subdir/qux.txt" to quxText) .toInMemoryDir() // Act dir.replaceTextInAllFiles("contents","X") assertThat(dir.allFilesTexts, containsInAnyOrder( fooText.replace("contents", "X"), barText.replace("contents", "X"))) val actualQuxText = dir.resolveRegularFile("subdir/qux.txt").text assertThat(actualQuxText, IsEqual(quxText)) } }
mit
a3bc754ab650bd41b966a11c7123035c
25.245614
69
0.60762
3.721393
false
true
false
false
ohmae/DmsExplorer
mobile/src/main/java/net/mm2d/android/util/ActivityLifecycleCallbacksAdapter.kt
1
936
/* * Copyright (c) 2017 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.android.util import android.app.Activity import android.app.Application.ActivityLifecycleCallbacks import android.os.Bundle /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ open class ActivityLifecycleCallbacksAdapter : ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit override fun onActivityStarted(activity: Activity) = Unit override fun onActivityResumed(activity: Activity) = Unit override fun onActivityPaused(activity: Activity) = Unit override fun onActivityStopped(activity: Activity) = Unit override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit override fun onActivityDestroyed(activity: Activity) = Unit }
mit
d98be5d840cf49478acec9de255e641f
35.8
90
0.773913
4.693878
false
false
false
false
VKCOM/vk-android-sdk
core/src/main/java/com/vk/api/sdk/exceptions/VKApiCodes.kt
1
8849
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ package com.vk.api.sdk.exceptions object VKApiCodes { const val CODE_COMPOSITE_EXECUTE_ERROR = Int.MIN_VALUE const val CODE_MALFORMED_RESPONSE = -3 const val CODE_IGNORED_ACCESS_TOKEN = -2 const val CODE_IO_ERROR = -1 const val CODE_UNKNOWN_ERROR = 1 const val CODE_APP_DISABLED = 2 const val CODE_UNKNOWN_METHOD = 3 const val CODE_INVALID_SIGNATURE = 4 const val CODE_AUTHORIZATION_FAILED = 5 const val CODE_TOO_MANY_REQUESTS_PER_SECOND = 6 const val CODE_NO_PERMISSIONS = 7 const val CODE_INVALID_REQUEST = 8 const val CODE_TOO_MANY_SIMILAR_REQUESTS = 9 const val CODE_INTERNAL_SERVER_ERROR = 10 const val CODE_INTERNAL_EXECUTE_ERROR = 13 const val CODE_APP_MUST_BE_TURNED_OFF_WHILE_TESTING = 11 const val CODE_CAPTCHA_REQUIRED = 14 const val CODE_ACCESS_DENIED = 15 const val CODE_HTTPS_REQUIRED = 16 const val CODE_USER_VALIDATION_REQUIRED = 17 const val CODE_USER_WAS_DELETED_OR_BANNED = 18 const val CODE_CONTENT_BLOCKED = 19 const val CODE_OPERATION_DENIED_FOR_NON_STANDALONE_APP = 20 const val CODE_OPERATION_AVAILABLE_ONLY_FOR_STANDALONE_AND_OPEN_API_APPS = 21 const val CODE_INVALID_PHOTO_UPLOAD = 22 const val CODE_METHOD_NOT_SUPPORTED = 23 const val CODE_USER_CONFIRM_REQUIRED = 24 const val CODE_TOKEN_CONFIRMATION_REQUIRED = 25 const val CODE_RATE_LIMIT_REACHED = 29 const val CODE_PRIVATE_PROFILE = 30 const val CODE_CLIENT_VERSION_DEPRECATED = 34 const val CODE_CLIENT_UPDATE_NEEDED = 35 const val CODE_REQUIRED_ARG_NOT_FOUND = 100 const val CODE_INVALID_APP_IDENTIFIER = 101 const val CODE_ERROR_LIMITS = 103 const val SUBCODE_TOO_MANY_COMMUNITIES = 1 const val CODE_TOO_MANY_CHAT_USERS = CODE_ERROR_LIMITS const val CODE_NOT_FOUND = 104 const val CODE_INVALID_USER_IDENTIFIER = 113 const val CODE_INVALID_PHOTO_FORMAT = 129 const val CODE_INVALID_TIMESTAMP = 150 const val CODE_ACCESS_DENIED_TO_ALBUM = 200 const val CODE_ACCESS_DENIED_TO_AUDIO = 201 const val CODE_ACCESS_DENIED_TO_GROUP = 203 const val CODE_ERROR_WALL_ACCESS_REPLIES = 212 const val CODE_ACCESS_POLLS_WITHOUT_VOTE = 253 const val CODE_PHOTO_ALBUM_LIMIT_EXCEED = 300 const val CODE_OPERATION_NOT_PERMITTED = 500 const val CODE_VK_PAY_NOT_ENOUGH_MONEY = 504 const val CODE_VK_PAY_INVALID_AMOUNT = 506 const val CODE_VK_PAY_INVALID_PIN = 509 const val CODE_ADVERTISE_CABINET_NO_PERMISSIONS_FOR_OPERATION = 600 const val CODE_ADVERTISE_CABINET_ERROR = 603 const val CODE_INVITE_LINK_AVAILABLE_FOR_CLOSED_GROUPS = 713 const val CODE_INVITE_LINK_EXPIRED = 714 const val CODE_VIDEO_ALREADY_ADDED = 800 const val CODE_ERROR_VIDEO_COMMENTS_CLOSED = 801 const val CODE_MSG_SEND_RECIPIENT_BLACKLISTED = 900 const val CODE_MSG_SEND_RECIPIENT_FORBID_GROUPS_MSGS = 901 const val CODE_MSG_SEND_VIOLATION_OF_PRIVACY_SETTINGS = 902 const val CODE_MSG_SEND_TO_MANY_FWDS = 913 const val CODE_MSG_SEND_MSG_TOO_LONG = 914 const val CODE_MSG_SEND_NO_ACCESS_TO_CHAT = 917 const val CODE_MSG_SEND_FAIL_TO_RESEND_FWDS = 921 const val CODE_CLEAR_CACHE_REQUESTED = 907 const val CODE_CLEAR_CACHE_REQUESTED2 = 908 const val CODE_CHAT_ACCESS_DENIED = 917 const val CODE_CHAT_INVITE_MAKE_LINK_DENIED = 919 const val CODE_MSG_DELETE_FOR_ALL_FAILED = 924 const val CODE_CHAT_NOT_ADMIN = 925 const val CODE_CHAT_DOES_NOT_EXIST = 927 const val CODE_CHAT_MR_ALREADY_SEND = 939 const val CODE_ADD_CHAT_MEMBER_ACCESS_TO_GROUP_DENIED = 947 const val CODE_CALL_HAS_BEEN_FINISHED = 951 const val CODE_CALL_INVALID_SECRET = 952 const val CODE_TOO_MANY_CONTACTS_TO_SYNC = 937 const val CODE_INVALID_NAME = 953 const val CODE_INVALID_JOIN_LINK = 954 const val CODE_INVALID_AUDIO_TRANSCRIPTION = 959 const val CODE_CALL_REQUIRES_AUTH = 960 const val CODE_CALL_LINK_OUTDATED = 961 const val CODE_CHAT_ALREADY_IN_ARCHIVE = 964 const val CODE_CHAT_NOT_IN_ARCHIVE = 965 const val CODE_TRANSLATE_UNSUPPORTED_LANGUAGE = 968 const val CODE_TRANSLATE_INVALID_MESSAGE = 971 const val CODE_TRANSLATE_CANT_TRANSLATE = 972 const val CODE_TRANSLATE_INVALID_LANGUAGES = 973 const val CODE_FOLDER_NOT_FOUND = 974 const val CODE_FOLDERS_LIMIT_REACHED = 975 const val CODE_FOLDER_CONVERSATIONS_LIMIT_REACHED = 976 const val CODE_OUTDATED_ROOM_LINK = 977 const val CODE_PHONE_PARAM_PHONE = 1000 const val CODE_PHONE_ALREADY_USED = 1004 const val CODE_ALREADY_IN_CALL = 1008 const val CODE_PHONE_AUTH_DELAY = 1112 const val CODE_INVALID_SID = 1113 const val CODE_SIGN_UP_CODE_INCORRECT = 1110 const val CODE_SIGN_UP_PASSWORD_UNALLOWABLE = 1111 const val CODE_ANONYM_TOKEN_EXPIRED = 1114 const val CODE_SUPER_APP_TOKEN_INVALID = 1115 const val CODE_ANONYM_TOKEN_INVALID = 1116 const val CODE_ACCESS_TOKEN_EXPIRED = 1117 const val CODE_STICKERS_DISABLED = 1191 const val CODE_ERROR_APPS_MENU_TOO_MANY_APPS = 1259 const val CODE_ACCOUNT_INVALID_SCREEN_NAME = 1260 const val CODE_ERROR_MARKET_COMMENTS_CLOSED = 1401 const val CODE_ERROR_MARKET_ITEM_NOT_FOUND = 1403 const val CODE_TEXT_LIVE_EMPTY_MESSAGE = 2600 const val CODE_TEXT_LIVE_MORE_ONE_ATTACH = 2601 const val CODE_TEXT_LIVE_WRONG_AUTHOR = 2602 const val CODE_TEXT_LIVE_FINISHED = 2603 const val CODE_TEXT_LIVE_UNAVAILABLE = 2604 const val CODE_TEXT_LIVE_SERVER_ERROR = 2605 const val CODE_TEXT_LIVE_LARGE_MESSAGE = 2606 const val CODE_ERROR_NEED_TOKEN_EXTENSION = 3609 const val CODE_ERROR_USER_DEACTIVATED = 3610 const val CODE_ERROR_ALREADY_HAS_EXTERNAL_BINDING = 3612 const val CODE_COMMUNITY_NOT_FOUND = 4519 const val CODE_INVALID_PHOTO_ID = 4520 const val CODE_PHOTO_ACCESS_ERROR = 4525 const val CODE_ERROR_USER_IS_LOCKED = 4526 const val CODE_PRODUCT_DUPLICATE_ERROR = 4527 const val CODE_ERROR_UPLOAD_PHOTO_DECODE_FAILED = 4600 const val CODE_ERROR_UPLOAD_PHOTO_WRONG_IMAGE_SIZE = 4601 const val CODE_ERROR_UPLOAD_PHOTO_PREPROCESS_FAILED = 4602 const val CODE_ERROR_UNAVAILABLE_REGISTRATION = 5400 const val CODE_ERROR_CANNOT_TRANSFER_MONEY_YOURSELF = 5800 const val CODE_ERROR_TOO_MANY_PROFILE_BUTTONS = 1262 const val CODE_CHANNEL_IN_ARCHIVE = 3 const val CODE_CHANNEL_NOT_IN_ARCHIVE = 3 const val CODE_CHANNEL_INVITE_LINK_INVALID = 7401 const val CODE_CHANNEL_USER_ALREADY_JOINED = 7402 const val EXTRA_CAPTCHA_SID = "captcha_sid" const val EXTRA_CAPTCHA_KEY = "captcha_key" const val EXTRA_CAPTCHA_IMG = "captcha_img" const val EXTRA_CAPTCHA_IMG_HEIGHT = "captcha_height" const val EXTRA_CAPTCHA_IMG_WIDTH = "captcha_width" const val EXTRA_CONFIRM = "confirm" const val EXTRA_VALIDATION_URL = "validation_url" const val EXTRA_USER_BAN_INFO = "user_ban_info" const val EXTRA_CONFIRMATION_TEXT = "confirmation_text" const val EXTRA_EXTENSION_HASH = "extend_hash" const val EXTRA_ACCESS_TOKEN = "access_token" const val EXTRA_AUTH_ERROR = "error" const val EXTRA_VW_LOGIN_ERROR = "vw_login_error" const val PARAM_DEVICE_ID = "device_id" const val PARAM_LANG = "lang" const val PARAM_REDIRECT_URI = "redirect_uri" const val PARAM_CONFIRM_TEXT = "confirmation_text" const val PARAM_ERROR = "error" const val PARAM_ERROR_CODE = "error_code" const val PARAM_EXECUTE_ERRORS = "execute_errors" const val PARAM_BAN_INFO = "ban_info" }
mit
dc1ca155f38ccfe8f0b2bab782b47b02
42.382353
81
0.707312
3.641564
false
false
false
false
jeffgbutler/mybatis-dynamic-sql
src/main/kotlin/org/mybatis/dynamic/sql/util/kotlin/spring/NamedParameterJdbcTemplateExtensions.kt
1
12282
/* * Copyright 2016-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("TooManyFunctions") package org.mybatis.dynamic.sql.util.kotlin.spring import org.mybatis.dynamic.sql.BasicColumn import org.mybatis.dynamic.sql.SqlTable import org.mybatis.dynamic.sql.delete.render.DeleteStatementProvider import org.mybatis.dynamic.sql.insert.render.BatchInsert import org.mybatis.dynamic.sql.insert.render.GeneralInsertStatementProvider import org.mybatis.dynamic.sql.insert.render.InsertSelectStatementProvider import org.mybatis.dynamic.sql.insert.render.InsertStatementProvider import org.mybatis.dynamic.sql.insert.render.MultiRowInsertStatementProvider import org.mybatis.dynamic.sql.select.render.SelectStatementProvider import org.mybatis.dynamic.sql.update.render.UpdateStatementProvider import org.mybatis.dynamic.sql.util.kotlin.CountCompleter import org.mybatis.dynamic.sql.util.kotlin.DeleteCompleter import org.mybatis.dynamic.sql.util.kotlin.GeneralInsertCompleter import org.mybatis.dynamic.sql.util.kotlin.InsertSelectCompleter import org.mybatis.dynamic.sql.util.kotlin.KotlinBatchInsertCompleter import org.mybatis.dynamic.sql.util.kotlin.KotlinInsertCompleter import org.mybatis.dynamic.sql.util.kotlin.KotlinMultiRowInsertCompleter import org.mybatis.dynamic.sql.util.kotlin.MyBatisDslMarker import org.mybatis.dynamic.sql.util.kotlin.SelectCompleter import org.mybatis.dynamic.sql.util.kotlin.UpdateCompleter import org.springframework.dao.EmptyResultDataAccessException import org.springframework.jdbc.core.RowMapper import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource import org.springframework.jdbc.core.namedparam.MapSqlParameterSource import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils import org.springframework.jdbc.support.KeyHolder import java.sql.ResultSet import kotlin.reflect.KClass fun NamedParameterJdbcTemplate.count(selectStatement: SelectStatementProvider): Long = queryForObject(selectStatement.selectStatement, selectStatement.parameters, Long::class.java)!! fun NamedParameterJdbcTemplate.count(column: BasicColumn, completer: CountCompleter): Long = count(org.mybatis.dynamic.sql.util.kotlin.spring.count(column, completer)) fun NamedParameterJdbcTemplate.countDistinct(column: BasicColumn, completer: CountCompleter): Long = count(org.mybatis.dynamic.sql.util.kotlin.spring.countDistinct(column, completer)) fun NamedParameterJdbcTemplate.countFrom(table: SqlTable, completer: CountCompleter): Long = count(org.mybatis.dynamic.sql.util.kotlin.spring.countFrom(table, completer)) fun NamedParameterJdbcTemplate.delete(deleteStatement: DeleteStatementProvider): Int = update(deleteStatement.deleteStatement, deleteStatement.parameters) fun NamedParameterJdbcTemplate.deleteFrom(table: SqlTable, completer: DeleteCompleter): Int = delete(org.mybatis.dynamic.sql.util.kotlin.spring.deleteFrom(table, completer)) // batch insert fun <T> NamedParameterJdbcTemplate.insertBatch(insertStatement: BatchInsert<T>): IntArray = batchUpdate(insertStatement.insertStatementSQL, SqlParameterSourceUtils.createBatch(insertStatement.records)) fun <T : Any> NamedParameterJdbcTemplate.insertBatch( vararg records: T, completer: KotlinBatchInsertCompleter<T> ): IntArray = insertBatch(records.asList(), completer) fun <T : Any> NamedParameterJdbcTemplate.insertBatch( records: List<T>, completer: KotlinBatchInsertCompleter<T> ): IntArray = insertBatch(org.mybatis.dynamic.sql.util.kotlin.spring.insertBatch(records, completer)) // single row insert fun <T> NamedParameterJdbcTemplate.insert(insertStatement: InsertStatementProvider<T>): Int = update(insertStatement.insertStatement, BeanPropertySqlParameterSource(insertStatement.row)) fun <T> NamedParameterJdbcTemplate.insert( insertStatement: InsertStatementProvider<T>, keyHolder: KeyHolder ): Int = update(insertStatement.insertStatement, BeanPropertySqlParameterSource(insertStatement.row), keyHolder) fun <T : Any> NamedParameterJdbcTemplate.insert(row: T, completer: KotlinInsertCompleter<T>): Int = insert(org.mybatis.dynamic.sql.util.kotlin.spring.insert(row, completer)) // general insert fun NamedParameterJdbcTemplate.generalInsert(insertStatement: GeneralInsertStatementProvider): Int = update(insertStatement.insertStatement, insertStatement.parameters) fun NamedParameterJdbcTemplate.generalInsert( insertStatement: GeneralInsertStatementProvider, keyHolder: KeyHolder ): Int = update(insertStatement.insertStatement, MapSqlParameterSource(insertStatement.parameters), keyHolder) fun NamedParameterJdbcTemplate.insertInto(table: SqlTable, completer: GeneralInsertCompleter): Int = generalInsert(org.mybatis.dynamic.sql.util.kotlin.spring.insertInto(table, completer)) // multiple row insert fun <T : Any> NamedParameterJdbcTemplate.insertMultiple( vararg records: T, completer: KotlinMultiRowInsertCompleter<T> ): Int = insertMultiple(records.asList(), completer) fun <T : Any> NamedParameterJdbcTemplate.insertMultiple( records: List<T>, completer: KotlinMultiRowInsertCompleter<T> ): Int = insertMultiple(org.mybatis.dynamic.sql.util.kotlin.spring.insertMultiple(records, completer)) fun <T> NamedParameterJdbcTemplate.insertMultiple(insertStatement: MultiRowInsertStatementProvider<T>): Int = update(insertStatement.insertStatement, BeanPropertySqlParameterSource(insertStatement)) fun <T> NamedParameterJdbcTemplate.insertMultiple( insertStatement: MultiRowInsertStatementProvider<T>, keyHolder: KeyHolder ): Int = update(insertStatement.insertStatement, BeanPropertySqlParameterSource(insertStatement), keyHolder) fun NamedParameterJdbcTemplate.insertSelect(completer: InsertSelectCompleter): Int = insertSelect(org.mybatis.dynamic.sql.util.kotlin.spring.insertSelect(completer)) fun NamedParameterJdbcTemplate.insertSelect(insertStatement: InsertSelectStatementProvider): Int = update(insertStatement.insertStatement, MapSqlParameterSource(insertStatement.parameters)) fun NamedParameterJdbcTemplate.insertSelect( insertStatement: InsertSelectStatementProvider, keyHolder: KeyHolder ): Int = update(insertStatement.insertStatement, MapSqlParameterSource(insertStatement.parameters), keyHolder) // insert with KeyHolder support fun NamedParameterJdbcTemplate.withKeyHolder(keyHolder: KeyHolder, block: KeyHolderHelper.() -> Int): Int = KeyHolderHelper(keyHolder, this).run(block) fun NamedParameterJdbcTemplate.select( vararg selectList: BasicColumn, completer: SelectCompleter ): SelectListMapperGatherer = select(selectList.toList(), completer) fun NamedParameterJdbcTemplate.select( selectList: List<BasicColumn>, completer: SelectCompleter ): SelectListMapperGatherer = SelectListMapperGatherer(org.mybatis.dynamic.sql.util.kotlin.spring.select(selectList, completer), this) fun NamedParameterJdbcTemplate.selectDistinct( vararg selectList: BasicColumn, completer: SelectCompleter ): SelectListMapperGatherer = selectDistinct(selectList.toList(), completer) fun NamedParameterJdbcTemplate.selectDistinct( selectList: List<BasicColumn>, completer: SelectCompleter ): SelectListMapperGatherer = SelectListMapperGatherer( org.mybatis.dynamic.sql.util.kotlin.spring.selectDistinct(selectList, completer), this ) fun <T> NamedParameterJdbcTemplate.selectList( selectStatement: SelectStatementProvider, rowMapper: (rs: ResultSet, rowNum: Int) -> T ): List<T> = selectList(selectStatement, RowMapper(rowMapper)) fun <T> NamedParameterJdbcTemplate.selectList( selectStatement: SelectStatementProvider, rowMapper: RowMapper<T> ): List<T> = query(selectStatement.selectStatement, selectStatement.parameters, rowMapper) fun <T : Any> NamedParameterJdbcTemplate.selectList( selectStatement: SelectStatementProvider, type: KClass<T> ): List<T> = queryForList(selectStatement.selectStatement, selectStatement.parameters, type.java) fun NamedParameterJdbcTemplate.selectOne( vararg selectList: BasicColumn, completer: SelectCompleter ): SelectOneMapperGatherer = selectOne(selectList.toList(), completer) fun NamedParameterJdbcTemplate.selectOne( selectList: List<BasicColumn>, completer: SelectCompleter ): SelectOneMapperGatherer = SelectOneMapperGatherer( org.mybatis.dynamic.sql.util.kotlin.spring.select(selectList, completer), this ) fun <T> NamedParameterJdbcTemplate.selectOne( selectStatement: SelectStatementProvider, rowMapper: (rs: ResultSet, rowNum: Int) -> T ): T? = selectOne(selectStatement, RowMapper(rowMapper)) @SuppressWarnings("SwallowedException") fun <T> NamedParameterJdbcTemplate.selectOne( selectStatement: SelectStatementProvider, rowMapper: RowMapper<T> ): T? = try { queryForObject(selectStatement.selectStatement, selectStatement.parameters, rowMapper) } catch (e: EmptyResultDataAccessException) { null } @SuppressWarnings("SwallowedException") fun <T : Any> NamedParameterJdbcTemplate.selectOne( selectStatement: SelectStatementProvider, type: KClass<T> ): T? = try { queryForObject(selectStatement.selectStatement, selectStatement.parameters, type.java) } catch (e: EmptyResultDataAccessException) { null } fun NamedParameterJdbcTemplate.update(updateStatement: UpdateStatementProvider): Int = update(updateStatement.updateStatement, updateStatement.parameters) fun NamedParameterJdbcTemplate.update(table: SqlTable, completer: UpdateCompleter): Int = update(org.mybatis.dynamic.sql.util.kotlin.spring.update(table, completer)) // support classes for select DSL @MyBatisDslMarker class SelectListMapperGatherer( private val selectStatement: SelectStatementProvider, private val template: NamedParameterJdbcTemplate ) { fun <T> withRowMapper(rowMapper: (rs: ResultSet, rowNum: Int) -> T): List<T> = template.selectList(selectStatement, rowMapper) fun <T> withRowMapper(rowMapper: RowMapper<T>): List<T> = template.selectList(selectStatement, rowMapper) } @MyBatisDslMarker class SelectOneMapperGatherer( private val selectStatement: SelectStatementProvider, private val template: NamedParameterJdbcTemplate ) { fun <T> withRowMapper(rowMapper: (rs: ResultSet, rowNum: Int) -> T): T? = template.selectOne(selectStatement, rowMapper) fun <T> withRowMapper(rowMapper: RowMapper<T>): T? = template.selectOne(selectStatement, rowMapper) } @MyBatisDslMarker class KeyHolderHelper(private val keyHolder: KeyHolder, private val template: NamedParameterJdbcTemplate) { fun insertInto(table: SqlTable, completer: GeneralInsertCompleter): Int = template.generalInsert(org.mybatis.dynamic.sql.util.kotlin.spring.insertInto(table, completer), keyHolder) fun <T : Any> insert(row: T, completer: KotlinInsertCompleter<T>): Int = template.insert(org.mybatis.dynamic.sql.util.kotlin.spring.insert(row, completer), keyHolder) fun <T : Any> insertMultiple(vararg records: T, completer: KotlinMultiRowInsertCompleter<T>): Int = insertMultiple(records.asList(), completer) fun <T : Any> insertMultiple(records: List<T>, completer: KotlinMultiRowInsertCompleter<T>): Int = template.insertMultiple(org.mybatis.dynamic.sql.util.kotlin.spring.insertMultiple(records, completer), keyHolder) fun insertSelect(completer: InsertSelectCompleter): Int = template.insertSelect(org.mybatis.dynamic.sql.util.kotlin.spring.insertSelect(completer), keyHolder) }
apache-2.0
3f8b7b78543d6e7b262f62415b35f263
43.021505
114
0.797916
4.347611
false
false
false
false
rhdunn/xquery-intellij-plugin
src/plugin-api/main/uk/co/reecedunn/intellij/plugin/processor/log/lang/highlighter/LogFileSyntaxHighlighter.kt
1
3506
/* * Copyright (C) 2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.processor.log.lang.highlighter import com.intellij.lexer.Lexer import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.fileTypes.SyntaxHighlighterBase import com.intellij.psi.tree.IElementType import uk.co.reecedunn.intellij.plugin.processor.log.LogFileContentType @Suppress("PropertyName", "unused") abstract class LogFileSyntaxHighlighter : SyntaxHighlighterBase() { // region SyntaxHighlighter abstract override fun getHighlightingLexer(): Lexer override fun getTokenHighlights(type: IElementType): Array<out TextAttributesKey> { return KEYS.getOrDefault(type, TextAttributesKey.EMPTY_ARRAY) } abstract val KEYS: Map<IElementType, Array<TextAttributesKey>> // endregion // region Syntax Highlighting :: Log Lines val DATE_TIME_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.DATE_TIME_KEY) val THREAD_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.THREAD_KEY) val SERVER_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.SERVER_KEY) // endregion // region Syntax Highlighting :: Log Levels :: Verbose val VERBOSE_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.VERBOSE_KEY) val FINEST_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.FINEST_KEY) val FINER_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.FINER_KEY) val FINE_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.FINE_KEY) // endregion // region Syntax Highlighting :: Log Levels :: Debug val DEBUG_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.DEBUG_KEY) // endregion // region Syntax Highlighting :: Log Levels :: Information val INFO_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.INFO_KEY) val CONFIG_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.CONFIG_KEY) val OK_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.OK_KEY) val REQUEST_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.REQUEST_KEY) // endregion // region Syntax Highlighting :: Log Levels :: Warning val WARNING_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.WARNING_KEY) val NOTICE_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.NOTICE_KEY) // endregion // region Syntax Highlighting :: Log Levels :: Error val ERROR_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.ERROR_KEY) val CRITICAL_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.CRITICAL_KEY) val ALERT_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.ALERT_KEY) // endregion // region Syntax Highlighting :: Log Levels :: Fatal val FATAL_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.FATAL_KEY) val EMERGENCY_KEYS: Array<TextAttributesKey> = pack(LogFileContentType.EMERGENCY_KEY) // endregion }
apache-2.0
e934e9d8b14f6146d1cc2d12e5f3b5f6
40.738095
89
0.755847
4.415617
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/xquery/XQueryCompElemConstructorPsiImpl.kt
1
2171
/* * Copyright (C) 2016, 2019-2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xquery.psi.impl.xquery import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.xdm.types.XdmAttributeNode import uk.co.reecedunn.intellij.plugin.xdm.types.XdmNamespaceNode import uk.co.reecedunn.intellij.plugin.xdm.types.XdmNode import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue import uk.co.reecedunn.intellij.plugin.xpath.ast.filterExpressions import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathExpr import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryCompElemConstructor class XQueryCompElemConstructorPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XQueryCompElemConstructor { // region XpmExpression override val expressionElement: PsiElement get() = this // endregion // region XdmElementNode override val attributes: Sequence<XdmAttributeNode> get() = filterExpressions() override val nodeName: XsQNameValue? get() = children().filterIsInstance<XsQNameValue>().firstOrNull() override val parentNode: XdmNode? get() = when (val parent = parent) { is XdmNode -> parent is XPathExpr -> parent.parent as? XdmNode else -> null } override val stringValue: String? get() = null override val namespaceAttributes: Sequence<XdmNamespaceNode> get() = emptySequence() // endregion }
apache-2.0
0de8ad8f6381d20bff57f5097a101477
35.79661
111
0.743897
4.273622
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/domain/comment/mapper/CommentsDataMapper.kt
1
2973
package org.stepik.android.domain.comment.mapper import org.stepik.android.domain.comment.model.CommentsData import org.stepik.android.domain.latex.mapper.LatexTextMapper import org.stepik.android.domain.latex.model.LatexData import org.stepik.android.presentation.comment.model.CommentItem import javax.inject.Inject class CommentsDataMapper @Inject constructor( private val latexTextMapper: LatexTextMapper ) { fun mapToCommentDataItems( commentIds: LongArray, commentsData: CommentsData, discussionId: Long? = null, cachedCommentItems: List<CommentItem.Data> = emptyList() ): List<CommentItem.Data> = commentsData .comments .mapNotNull { comment -> val user = commentsData .users .find { it.id == comment.user } ?: return@mapNotNull null val vote = commentsData .votes .find { it.id == comment.vote } ?: return@mapNotNull null val solution = comment .submission ?.let { submissionId -> commentsData .submissions .find { it.id == submissionId } } ?.let { submission -> commentsData .attempts .find { it.id == submission.attempt } ?.let { attempt -> CommentItem.Data.Solution(attempt, submission) } } val latexData = latexTextMapper.mapToLatexText(comment.text ?: "") val result = if (latexData is LatexData.Web) { latexData } else { latexTextMapper.mapToLatexText(comment.text?.replace("\n", "<br>") ?: "") } CommentItem.Data( comment = comment, textData = result, user = user, voteStatus = CommentItem.Data.VoteStatus.Resolved(vote), isFocused = discussionId == comment.id, solution = solution ) } .let { newItems -> val items = newItems + cachedCommentItems val comments = items .associateBy { it.comment.id } commentIds .flatMap { commentId -> val comment = comments[commentId] if (comment != null) { listOf(comment) + (comment.comment.replies?.mapNotNull(comments::get) ?: emptyList()) } else { emptyList() } } } }
apache-2.0
875fb174b33d2f15a3917c957d54f9c4
35.268293
113
0.465187
5.795322
false
false
false
false
ScheNi/android-material-stepper
sample/src/main/java/com/stepstone/stepper/sample/PassDataBetweenStepsActivity.kt
2
2319
/* Copyright 2017 StepStone Services 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.stepstone.stepper.sample import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.stepstone.stepper.StepperLayout import com.stepstone.stepper.sample.adapter.PassDataBetweenStepsFragmentStepAdapter import butterknife.BindView import butterknife.ButterKnife class PassDataBetweenStepsActivity : AppCompatActivity(), DataManager { companion object { private const val CURRENT_STEP_POSITION_KEY = "position" private const val DATA = "data" } @BindView(R.id.stepperLayout) lateinit var stepperLayout: StepperLayout private var data: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) title = "Stepper sample" setContentView(R.layout.activity_pass_data_between_steps) ButterKnife.bind(this) val startingStepPosition = savedInstanceState?.getInt(CURRENT_STEP_POSITION_KEY) ?: 0 data = savedInstanceState?.getString(DATA) stepperLayout.setAdapter(PassDataBetweenStepsFragmentStepAdapter(supportFragmentManager, this), startingStepPosition) } override fun onSaveInstanceState(outState: Bundle) { outState.putInt(CURRENT_STEP_POSITION_KEY, stepperLayout.currentStepPosition) outState.putString(DATA, data) super.onSaveInstanceState(outState) } override fun onBackPressed() { val currentStepPosition = stepperLayout.currentStepPosition if (currentStepPosition > 0) { stepperLayout.onBackClicked() } else { finish() } } override fun saveData(data: String?) { this.data = data } override fun getData(): String? { return data } }
apache-2.0
40c2da2763da4782ea3298951cafd7e3
29.513158
125
0.729194
4.811203
false
false
false
false
suchaHassle/kotNES
src/CPU.kt
1
4651
package kotNES import instructionSize import isBitSet import kotNES.Opcodes.AddressMode import toHexString class CPU(var memory: CpuMemory) { enum class Interrupts(val value: Int) { NMI(0), IRQ(1), RESET(2) } var registers = Register() var statusFlags = StatusFlag() private var idleCycles = 0 private var interruptHandlerOffsets = intArrayOf(0xFFFA, 0xFFFE, 0xFFFC) private var interrupts = BooleanArray(2) private var opcodes = Opcodes() var opcode: Int = 0 var cycles: Int = 0 fun tick(): Int { if (idleCycles > 0) { idleCycles-- return 1 } val initCycle = cycles for (i in 0..1) if (interrupts[i]) { pushWord(registers.PC) push(statusFlags.asByte()) registers.PC = memory.readWord(interruptHandlerOffsets[i]) statusFlags.InterruptDisable = true interrupts[i] = false } opcode = memory[registers.PC] registers.P = statusFlags.asByte() opcodes.pageCrossed = false //println(toString()) val address: Int = opcodes.getAddress(AddressMode.values()[opcodes.addressModes[opcode] - 1], this) registers.tick(instructionSize(opcode)) opcodes.opcode[opcode].also { it.op(this, address) } return cycles - initCycle } fun reset() { registers.reset() registers.PC = memory.readWord(0xFFFC) //registers.PC = 0xC000 statusFlags.reset() idleCycles = 0 cycles = 0 } override fun toString(): String { return registers.PC.toHexString() + " " + opcode.toHexString() + " " + registers.toString() + " " } fun push(data: Int) { memory[0x100 or registers.S--] = data } fun pushWord(data: Int) { push(data shr 8) push(data and 0xFF) } fun pop(): Int = memory[0x100 or ++registers.S] fun popWord(): Int = pop() or (pop() shl 8) fun triggerInterrupt(type: Interrupts) { if (!statusFlags.InterruptDisable || type == Interrupts.NMI) interrupts[type.value] = true } fun addIdleCycles(i: Int) { idleCycles += i } } data class Register ( private var _A: Int = 0, private var _X: Int = 0, private var _Y: Int = 0, private var _S: Int = 0, private var _P: Int = 0, private var _PC: Int = 0 ) { var A: Int get()= _A and 0xFF set(value) { _A = value and 0xFF } var X: Int get() = _X and 0xFF set(value) { _X = value and 0xFF } var Y: Int get() = _Y and 0xFF set(value) { _Y = value and 0xFF } var S: Int get() = _S and 0xFF set(value) { _S = value and 0xFF } var P: Int get() = _P and 0xFF set(value) { _P = value and 0xFF } var PC: Int get() = _PC and 0xFFFF set(value) { _PC = value and 0xFFFF} fun reset() { A = 0 X = 0 Y = 0 S = 0xFD P = 0 } fun tick(count: Int) { PC += count } override fun toString(): String = "A:${A.toHexString()} " + "X:${X.toHexString()} " + "Y:${Y.toHexString()} " + "P:${P.toHexString()} " + "SP:${S.toHexString()}" } data class StatusFlag ( var Carry: Boolean = false, var Zero: Boolean = true, var InterruptDisable: Boolean = true, var DecimalMode: Boolean = false, var BreakCommand: Boolean = false, var Overflow: Boolean = false, var Negative: Boolean = false ) { fun reset() { toFlags(0x24) } fun asByte() = ((if (Negative) (1 shl 7) else 0) or (if (Overflow) (1 shl 6) else 0) or (1 shl 5) or // Special logic needed for the B flag... (if (BreakCommand) (1 shl 4) else 0) or (if (DecimalMode) (1 shl 3) else 0) or (if (InterruptDisable) (1 shl 2) else 0) or (if (Zero) (1 shl 1) else 0) or (if (Carry) 1 else 0)) fun toFlags(status: Int) { Carry = status.isBitSet(0) Zero = status.isBitSet(1) InterruptDisable = status.isBitSet(2) DecimalMode = status.isBitSet(3) BreakCommand = status.isBitSet(4) Overflow = status.isBitSet(6) Negative = status.isBitSet(7) } fun setZn(value: Int) { val value = value and 0xFF Zero = (value == 0) Negative = ((value shr 7) and 1) == 1 } }
mit
5a9dad1976edea6cbcd327988442697b
25.577143
107
0.528704
3.781301
false
false
false
false
redutan/nbase-arc-monitoring
src/main/kotlin/io/redutan/nbasearc/monitoring/collector/Parser.kt
1
724
package io.redutan.nbasearc.monitoring.collector import java.time.LocalDateTime const val UNKNOWN = "?" val UNKNOWN_HEADER = NbaseArcLogHeader(LocalDateTime.now(), UNKNOWN) /** * * @author myeongju.jung */ interface Parser<out T : NbaseArcLog> { fun parse(current: LocalDateTime, line: String): T } interface HeaderParser { fun isHeader(line: String): Boolean fun parse(line: String): NbaseArcLogHeader } data class NbaseArcLogHeader(val current: LocalDateTime, val clusterName: String, override val errorDescription: String = "") : NbaseArcLog { override val loggedAt: LocalDateTime get() = current override fun isUnknown(): Boolean { return UNKNOWN == clusterName } }
apache-2.0
0c551bec6b1dad5571859b9eb48292a0
23.133333
125
0.71547
4.309524
false
false
false
false
saletrak/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/widgets/buttons/vote/base/BaseVoteButton.kt
1
1540
package io.github.feelfreelinux.wykopmobilny.ui.widgets.buttons.vote.base import android.content.Context import android.util.AttributeSet import android.widget.TextView import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.WykopApp import io.github.feelfreelinux.wykopmobilny.ui.dialogs.showExceptionDialog import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi import javax.inject.Inject @Suppress("LeakingThis") abstract class BaseVoteButton : TextView { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs, R.attr.MirkoButtonStyle) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) @Inject lateinit var userManager : UserManagerApi abstract fun vote() abstract fun unvote() init { WykopApp.uiInjector.inject(this) setBackgroundResource(R.drawable.button_vote_background_state_list) setOnClickListener { userManager.runIfLoggedIn(context) { if (isSelected) unvote() else vote() } } } var voteCount : Int get() = text.toString().toInt() set(value) { text = context.getString(R.string.votes_count, value) } var isButtonSelected: Boolean get() = isSelected set(value) { isSelected = value } fun showErrorDialog(e : Throwable) = context.showExceptionDialog(e) }
mit
9089483811fc95f2022d996c96e874eb
31.104167
111
0.709091
4.597015
false
false
false
false
square/wire
wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InteropTest.kt
1
13381
/* * Copyright 2020 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire import com.google.protobuf.Duration import okio.ByteString import org.junit.Ignore import org.junit.Test import squareup.proto3.java.interop.InteropTest.InteropWrappers import squareup.proto2.java.interop.InteropBoxOneOf as InteropBoxOneOfJ2 import squareup.proto2.java.interop.InteropCamelCase as InteropCamelCaseJ2 import squareup.proto2.java.interop.InteropDuration as InteropDurationJ2 import squareup.proto2.java.interop.InteropJsonName as InteropJsonNameJ2 import squareup.proto2.java.interop.InteropTest.InteropCamelCase as InteropCamelCaseP2 import squareup.proto2.java.interop.InteropTest.InteropJsonName as InteropJsonNameP2 import squareup.proto2.java.interop.InteropTest.InteropUint64 as InteropUint64P2 import squareup.proto2.java.interop.InteropUint64 as InteropUint64J2 import squareup.proto2.kotlin.interop.InteropBoxOneOf as InteropBoxOneOfK2 import squareup.proto2.kotlin.interop.InteropCamelCase as InteropCamelCaseK2 import squareup.proto2.kotlin.interop.InteropDuration as InteropDurationK2 import squareup.proto2.kotlin.interop.InteropJsonName as InteropJsonNameK2 import squareup.proto2.kotlin.interop.InteropUint64 as InteropUint64K2 import squareup.proto3.java.interop.InteropBoxOneOf as InteropBoxOneOfJ3 import squareup.proto3.java.interop.InteropCamelCase as InteropCamelCaseJ3 import squareup.proto3.java.interop.InteropDuration as InteropDurationJ3 import squareup.proto3.java.interop.InteropJsonName as InteropJsonNameJ3 import squareup.proto3.java.interop.InteropOptional as InteropOptionalJ3 import squareup.proto3.java.interop.InteropTest.InteropBoxOneOf as InteropBoxOneOfP3 import squareup.proto3.java.interop.InteropTest.InteropCamelCase as InteropCamelCaseP3 import squareup.proto3.java.interop.InteropTest.InteropDuration as InteropDurationP3 import squareup.proto3.java.interop.InteropTest.InteropJsonName as InteropJsonNameP3 import squareup.proto3.java.interop.InteropTest.InteropUint64 as InteropUint64P3 import squareup.proto3.java.interop.InteropUint64 as InteropUint64J3 import squareup.proto3.java.interop.InteropWrappers as InteropWrappersJ3 import squareup.proto3.kotlin.interop.InteropBoxOneOf as InteropBoxOneOfK3 import squareup.proto3.kotlin.interop.InteropCamelCase as InteropCamelCaseK3 import squareup.proto3.kotlin.interop.InteropDuration as InteropDurationK3 import squareup.proto3.kotlin.interop.InteropJsonName as InteropJsonNameK3 import squareup.proto3.kotlin.interop.InteropOptional as InteropOptionalK3 import squareup.proto3.kotlin.interop.InteropUint64 as InteropUint64K3 import squareup.proto3.kotlin.interop.InteropWrappers as InteropWrappersK3 import squareup.proto3.kotlin.interop.TestProto3Optional.InteropOptional as InteropOptionalP3 class InteropTest { @Test fun duration() { val checker = InteropChecker( protocMessage = InteropDurationP3.newBuilder() .setValue( Duration.newBuilder() .setSeconds(99L) .setNanos(987_654_321) .build() ) .build(), canonicalJson = """{"value":"99.987654321s"}""", wireAlternateJsons = listOf( // TODO: move to alternateJsons once we can use ignoringUnknownFields(). """{"unused": false, "value":"99.987654321s"}""", ), ) checker.check(InteropDurationK3(durationOfSeconds(99, 987_654_321L))) checker.check(InteropDurationJ3(durationOfSeconds(99, 987_654_321L))) checker.check(InteropDurationK2(durationOfSeconds(99, 987_654_321L))) checker.check(InteropDurationJ2(durationOfSeconds(99, 987_654_321L))) } @Test fun uint64() { val zero = InteropChecker( protocMessage = InteropUint64P3.newBuilder() .setValue(0L) .build(), canonicalJson = """{}""", alternateJsons = listOf( """{"value":"0"}""", """{"value":0}""", """{"value":"-0"}""", ), ) zero.check(InteropUint64K3(0L)) zero.check(InteropUint64J3(0L)) val one = InteropChecker( protocMessage = InteropUint64P3.newBuilder() .setValue(1L) .build(), canonicalJson = """{"value":"1"}""", alternateJsons = listOf( """{"value":1}""", """{"value":"1"}""", """{"value":"1.0"}""", ), ) one.check(InteropUint64K3(1L)) one.check(InteropUint64J3(1L)) val max = InteropChecker( protocMessage = InteropUint64P3.newBuilder() .setValue(-1L) .build(), canonicalJson = """{"value":"18446744073709551615"}""", wireAlternateJsons = listOf( """{"value":"-1"}""" ), ) max.check(InteropUint64K3(-1L)) max.check(InteropUint64J3(-1L)) } @Test fun `uint64 proto 2`() { val max = InteropChecker( protocMessage = InteropUint64P2.newBuilder() .setValue(-1L) .build(), canonicalJson = """{"value":"18446744073709551615"}""", wireCanonicalJson = """{"value":18446744073709551615}""", alternateJsons = listOf( """{"value":"18446744073709551615"}""", """{"value":18446744073709551615}""", ), wireAlternateJsons = listOf( """{"value":"-1"}""" ), ) max.check(InteropUint64K2(-1L)) max.check(InteropUint64J2(-1L)) } @Test fun `camel case`() { val checker = InteropChecker( protocMessage = InteropCamelCaseP3.newBuilder() .setHelloWorld("1") .setAB("2") .setCccDdd("3") .setEEeeFfGGg("4") .setABC("5") .setGHI("6") .setKLM("7") .setTUV("8") .setXYZ("9") .build(), canonicalJson = """{"helloWorld":"1","aB":"2","CccDdd":"3","EEeeFfGGg":"4","aBC":"5","GHI":"6","KLM":"7","TUV":"8","XYZ":"9"}""", alternateJsons = listOf( """{"hello_world": "1", "a__b": "2", "_Ccc_ddd": "3", "EEee_ff_gGg": "4", "a_b_c": "5", "GHI": "6", "K_L_M": "7", "__T__U__V__": "8", "_x_y_z_": "9"}""", ), ) checker.check(InteropCamelCaseK3("1", "2", "3", "4", "5", "6", "7", "8", "9")) checker.check(InteropCamelCaseJ3("1", "2", "3", "4", "5", "6", "7", "8", "9")) } @Test fun `camel case proto 2`() { val checker = InteropChecker( protocMessage = InteropCamelCaseP2.newBuilder() .setHelloWorld("1") .setAB("2") .setCccDdd("3") .setEEeeFfGGg("4") .setABC("5") .setGHI("6") .setKLM("7") .setTUV("8") .setXYZ("9") .build(), canonicalJson = """{"helloWorld":"1","aB":"2","CccDdd":"3","EEeeFfGGg":"4","aBC":"5","GHI":"6","KLM":"7","TUV":"8","XYZ":"9"}""", """{"hello_world":"1","a__b":"2","_Ccc_ddd":"3","EEee_ff_gGg":"4","a_b_c":"5","GHI":"6","K_L_M":"7","__T__U__V__":"8","_x_y_z_":"9"}""", alternateJsons = listOf( // TODO(bquenaudon): support reading camelCase proto2 messages. // """{"helloWorld":"1","aB":"2","CccDdd":"3","eEeeFfGGg":"4"}""", ) ) checker.check(InteropCamelCaseK2("1", "2", "3", "4", "5", "6", "7", "8", "9")) checker.check(InteropCamelCaseJ2("1", "2", "3", "4", "5", "6", "7", "8", "9")) } @Test fun `json names`() { val checked = InteropChecker( protocMessage = InteropJsonNameP3.newBuilder() .setA("1") .setPublic("2") .setCamelCase("3") .build(), canonicalJson = """{"one":"1","two":"2","three":"3"}""", alternateJsons = listOf( """{"a":"1","public":"2","camel_case":"3"}""", ), ) checked.check(InteropJsonNameJ3("1", "2", "3")) checked.check(InteropJsonNameK3("1", "2", "3")) } @Test fun `json names proto2`() { val checked = InteropChecker( protocMessage = InteropJsonNameP2.newBuilder() .setA("1") .setPublic("2") .setCamelCase("3") .build(), canonicalJson = """{"one":"1","two":"2","three":"3"}""", alternateJsons = listOf( """{"a":"1","public":"2","camel_case":"3"}""", ), ) checked.check(InteropJsonNameJ2("1", "2", "3")) checked.check(InteropJsonNameK2("1", "2", "3")) } @Test fun optionalNonIdentity() { val checker = InteropChecker( protocMessage = InteropOptionalP3.newBuilder() .setValue("hello") .build(), canonicalJson = """{"value":"hello"}""", wireAlternateJsons = listOf( """{"unused": false, "value":"hello"}""", ), ) checker.check(InteropOptionalK3("hello")) checker.check(InteropOptionalJ3("hello")) } @Test fun optionalIdentity() { val checker = InteropChecker( protocMessage = InteropOptionalP3.newBuilder() .setValue("") .build(), canonicalJson = """{"value":""}""", wireAlternateJsons = listOf( """{"unused": false, "value":""}""", ), ) checker.check(InteropOptionalK3("")) checker.check(InteropOptionalJ3("")) } @Test fun boxOneOfsKotlin() { val checker = InteropChecker( protocMessage = InteropBoxOneOfP3.newBuilder() .setA("Hello") .build(), canonicalJson = """{"a":"Hello"}""", ) checker.check( InteropBoxOneOfK2.Builder() .option(OneOf(InteropBoxOneOfK2.OPTION_A, "Hello")) .build() ) checker.check( InteropBoxOneOfK3.Builder() .option(OneOf(InteropBoxOneOfK3.OPTION_A, "Hello")) .build() ) } @Ignore("Needs to implement boxed oneofs in Java.") @Test fun boxOneOfsJava() { val checker = InteropChecker( protocMessage = InteropBoxOneOfP3.newBuilder() .setA("Hello") .build(), canonicalJson = """{"a":"Hello"}""", ) checker.check(InteropBoxOneOfJ2.Builder().a("Hello").build()) checker.check(InteropBoxOneOfJ3.Builder().a("Hello").build()) } @Test fun wrappersDoesNotOmitWrappedIdentityValues() { val checker = InteropChecker( protocMessage = InteropWrappers.newBuilder() .setDoubleValue(0.0.toDoubleValue()) .setFloatValue(0f.toFloatValue()) .setInt64Value(0L.toInt64Value()) .setUint64Value(0L.toUInt64Value()) .setInt32Value(0.toInt32Value()) .setUint32Value(0.toUInt32Value()) .setBoolValue(false.toBoolValue()) .setStringValue("".toStringValue()) .setBytesValue(ByteString.EMPTY.toBytesValue()) .build(), canonicalJson = """{"doubleValue":0.0,"floatValue":0.0,"int64Value":"0","uint64Value":"0","int32Value":0,"uint32Value":0,"boolValue":false,"stringValue":"","bytesValue":""}""", ) checker.check( InteropWrappersJ3.Builder() .double_value(0.0) .float_value(0f) .int64_value(0L) .uint64_value(0L) .int32_value(0) .uint32_value(0) .bool_value(false) .string_value("") .bytes_value(ByteString.EMPTY) .build() ) checker.check( InteropWrappersK3.Builder() .double_value(0.0) .float_value(0f) .int64_value(0L) .uint64_value(0L) .int32_value(0) .uint32_value(0) .bool_value(false) .string_value("") .bytes_value(ByteString.EMPTY) .build() ) } @Test fun wrappersWithNulls() { val checker = InteropChecker( protocMessage = InteropWrappers.newBuilder().build(), canonicalJson = """{}""", ) checker.check(InteropWrappersJ3.Builder().build()) checker.check(InteropWrappersK3.Builder().build()) } @Test fun wrappers() { val checker = InteropChecker( protocMessage = InteropWrappers.newBuilder() .setDoubleValue(1.0.toDoubleValue()) .setFloatValue(2f.toFloatValue()) .setInt64Value(3L.toInt64Value()) .setUint64Value(4L.toUInt64Value()) .setInt32Value(5.toInt32Value()) .setUint32Value(6.toUInt32Value()) .setBoolValue(true.toBoolValue()) .setStringValue("string".toStringValue()) .setBytesValue(ByteString.of(1).toBytesValue()) .build(), canonicalJson = """{"doubleValue":1.0,"floatValue":2.0,"int64Value":"3","uint64Value":"4","int32Value":5,"uint32Value":6,"boolValue":true,"stringValue":"string","bytesValue":"AQ=="}""", ) checker.check( InteropWrappersJ3.Builder() .double_value(1.0) .float_value(2f) .int64_value(3L) .uint64_value(4L) .int32_value(5) .uint32_value(6) .bool_value(true) .string_value("string") .bytes_value(ByteString.of(1)) .build() ) checker.check( InteropWrappersK3.Builder() .double_value(1.0) .float_value(2f) .int64_value(3L) .uint64_value(4L) .int32_value(5) .uint32_value(6) .bool_value(true) .string_value("string") .bytes_value(ByteString.of(1)) .build() ) } }
apache-2.0
2a493fd28debbc83abe00608cde4eb12
34.306069
191
0.629699
3.503797
false
true
false
false
Maccimo/intellij-community
platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarProcessStartedAction.kt
1
5419
// 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.execution.runToolbar import com.intellij.execution.runToolbar.FixWidthSegmentedActionToolbarComponent.Companion.RUN_CONFIG_SCALED_WIDTH import com.intellij.execution.runToolbar.components.MouseListenerHelper import com.intellij.execution.runToolbar.components.TrimmedMiddleLabel import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.ActionToolbar import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.actionSystem.ex.ComboBoxAction import com.intellij.openapi.actionSystem.impl.segmentedActionBar.SegmentedCustomPanel import com.intellij.openapi.util.Key import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import net.miginfocom.swing.MigLayout import java.awt.Dimension import java.awt.Font import java.beans.PropertyChangeEvent import javax.swing.JComponent import javax.swing.JLabel class RunToolbarProcessStartedAction : ComboBoxAction(), RTRunConfiguration { companion object { val PROP_ACTIVE_ENVIRONMENT = Key<ExecutionEnvironment>("PROP_ACTIVE_ENVIRONMENT") fun updatePresentation(e: AnActionEvent) { e.presentation.isEnabledAndVisible = e.project?.let { project -> e.runToolbarData()?.let { it.environment?.let { environment -> e.presentation.putClientProperty(PROP_ACTIVE_ENVIRONMENT, environment) environment.contentToReuse?.let { contentDescriptor -> e.presentation.setText(contentDescriptor.displayName, false) e.presentation.icon = contentDescriptor.icon } ?: run { e.presentation.text = "" e.presentation.icon = null } e.presentation.description = RunToolbarData.prepareDescription(e.presentation.text, ActionsBundle.message("action.RunToolbarShowHidePopupAction.click.to.open.toolwindow.text")) true } ?: false } ?: false } ?: false } } override fun createPopupActionGroup(button: JComponent?): DefaultActionGroup = DefaultActionGroup() override fun actionPerformed(e: AnActionEvent) { } override fun checkMainSlotVisibility(state: RunToolbarMainSlotState): Boolean { return state == RunToolbarMainSlotState.PROCESS } override fun update(e: AnActionEvent) { super.update(e) updatePresentation(e) if (!RunToolbarProcess.isExperimentalUpdatingEnabled) { e.mainState()?.let { e.presentation.isEnabledAndVisible = e.presentation.isEnabledAndVisible && checkMainSlotVisibility(it) } } } override fun createCustomComponent(presentation: Presentation, place: String): JComponent { return object : SegmentedCustomPanel(presentation) { val PROP_ACTIVE_ENVIRONMENT = Key<ExecutionEnvironment>("PROP_ACTIVE_ENVIRONMENT") private val setting = object : TrimmedMiddleLabel() { override fun getFont(): Font { return UIUtil.getToolbarFont() } } private val process = object : JLabel() { override fun getFont(): Font { return UIUtil.getToolbarFont() } }.apply { foreground = UIUtil.getLabelInfoForeground() } init { MouseListenerHelper.addListener(this, { showPopup() }, { doShiftClick() }, { doRightClick() }) fill() } override fun presentationChanged(event: PropertyChangeEvent) { setting.icon = presentation.icon setting.text = presentation.text presentation.getClientProperty(RunToolbarProcessStartedAction.PROP_ACTIVE_ENVIRONMENT)?.let { environment -> environment.getRunToolbarProcess()?.let { updatePresentation(it) if (environment.isProcessTerminating()) { process.text = ActionsBundle.message("action.RunToolbarRemoveSlotAction.terminating") } true } } } private fun updatePresentation(toolbarProcess: RunToolbarProcess) { setting.text = presentation.text setting.icon = presentation.icon isEnabled = true toolTipText = presentation.description process.text = toolbarProcess.name background = toolbarProcess.pillColor } private fun fill() { layout = MigLayout("ins 0 0 0 3, novisualpadding, gap 0, fill", "4[shp 1]3[grow]push") add(setting, "ay center, pushx, wmin 10") add(process, "ay center, pushx, wmin 0") setting.border = JBUI.Borders.empty() process.border = JBUI.Borders.empty() } private fun showPopup() { presentation.getClientProperty(PROP_ACTIVE_ENVIRONMENT)?.showToolWindowTab() } private fun doRightClick() { RunToolbarRunConfigurationsAction.doRightClick(ActionToolbar.getDataContextFor(this)) } private fun doShiftClick() { ActionToolbar.getDataContextFor(this).editConfiguration() } override fun getPreferredSize(): Dimension { val d = super.getPreferredSize() d.width = RUN_CONFIG_SCALED_WIDTH return d } } } }
apache-2.0
9e8fcf81a76fc68496ca2816a3b772ce
34.657895
158
0.699945
5.008318
false
false
false
false
ahmedeltaher/MVP-RX-Android-Sample
app/src/androidTest/java/com/task/ui/component/details/DetailsActivityTest.kt
1
2166
package com.task.ui.component.details import android.content.Intent import androidx.test.espresso.Espresso.onView import androidx.test.espresso.IdlingRegistry import androidx.test.espresso.IdlingResource import androidx.test.espresso.action.ViewActions.scrollTo import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.rule.ActivityTestRule import com.task.R import com.task.RECIPE_ITEM_KEY import com.task.TestUtil.initData import com.task.TestUtil.recipes import com.task.utils.EspressoIdlingResource import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test /** * Created by AhmedEltaher */ @HiltAndroidTest class DetailsActivityTest { @get:Rule var hiltRule = HiltAndroidRule(this) @get:Rule var mActivityTestRule = ActivityTestRule(DetailsActivity::class.java, true, false) private var mIdlingResource: IdlingResource? = null @Before fun setup() { initData() val intent: Intent = Intent().apply { putExtra(RECIPE_ITEM_KEY, recipes.recipesList[0]) } mActivityTestRule.launchActivity(intent) IdlingRegistry.getInstance().register(EspressoIdlingResource.countingIdlingResource) } @Test fun testRecipeDetails() { //Assert Title onView(withId(R.id.tv_name)).check(matches(isDisplayed())) onView(withId(R.id.tv_name)).check(matches(withText(recipes.recipesList[0].name))) //Assert Recipe Description onView(withId(R.id.tv_description)).perform(scrollTo()) onView(withId(R.id.tv_description)).check(matches(withText(recipes.recipesList[0].description))) //Assert Add to Favorite onView(withId(R.id.add_to_favorite)).check(matches(isDisplayed())) onView(withId(R.id.add_to_favorite)).check(matches(isClickable())) } @After fun unregisterIdlingResource() { if (mIdlingResource != null) { IdlingRegistry.getInstance().unregister() } } }
apache-2.0
32f10507f02f1b91e23f4ba6081814bf
31.328358
104
0.731302
4.255403
false
true
false
false
Maccimo/intellij-community
platform/platform-impl/src/com/intellij/toolWindow/ToolWindowToolbar.kt
2
2649
// 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.toolWindow import com.intellij.openapi.actionSystem.ActionPlaces.TOOLWINDOW_TOOLBAR_BAR import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowAnchor import com.intellij.openapi.wm.impl.AbstractDroppableStripe import com.intellij.openapi.wm.impl.LayoutData import com.intellij.openapi.wm.impl.SquareStripeButton import com.intellij.ui.ComponentUtil import com.intellij.util.ui.JBUI import java.awt.BorderLayout import java.awt.Point import java.awt.Rectangle import javax.swing.JComponent import javax.swing.JPanel internal abstract class ToolWindowToolbar : JPanel() { lateinit var defaults: List<String> init { layout = BorderLayout() isOpaque = true background = JBUI.CurrentTheme.ToolWindow.background() } abstract fun getStripeFor(anchor: ToolWindowAnchor): AbstractDroppableStripe abstract fun getButtonFor(toolWindowId: String): StripeButtonManager? abstract fun getStripeFor(screenPoint: Point): AbstractDroppableStripe? fun removeStripeButton(toolWindow: ToolWindow, anchor: ToolWindowAnchor) { remove(getStripeFor(anchor), toolWindow) } abstract fun reset() fun startDrag() { revalidate() repaint() } fun stopDrag() = startDrag() protected fun tryDroppingOnGap(data: LayoutData, gap: Int, dropRectangle: Rectangle, doLayout: () -> Unit) { val sideDistance = data.eachY + gap - dropRectangle.y + dropRectangle.height if (sideDistance > 0) { data.dragInsertPosition = -1 data.dragToSide = false data.dragTargetChosen = true doLayout() } } companion object { fun updateButtons(panel: JComponent) { ComponentUtil.findComponentsOfType(panel, SquareStripeButton::class.java).forEach { it.update() } panel.revalidate() panel.repaint() } fun remove(panel: AbstractDroppableStripe, toolWindow: ToolWindow) { val component = panel.components.firstOrNull { it is SquareStripeButton && it.toolWindow.id == toolWindow.id } ?: return panel.remove(component) panel.revalidate() panel.repaint() } } open class ToolwindowActionToolbar(val panel: JComponent) : ActionToolbarImpl(TOOLWINDOW_TOOLBAR_BAR, DefaultActionGroup(), false) { override fun actionsUpdated(forced: Boolean, newVisibleActions: List<AnAction>) = updateButtons(panel) } }
apache-2.0
e9bfa40acecf1bade42c0ec81bfac891
32.974359
134
0.760664
4.444631
false
false
false
false
Maccimo/intellij-community
plugins/settings-sync/src/com/intellij/settingsSync/SettingsSyncIdeMediatorImpl.kt
1
11274
package com.intellij.settingsSync import com.intellij.application.options.editor.EditorOptionsPanel import com.intellij.codeInsight.hints.ParameterHintsPassFactory import com.intellij.concurrency.ConcurrentCollectionFactory import com.intellij.configurationStore.* import com.intellij.configurationStore.schemeManager.SchemeManagerFactoryBase import com.intellij.configurationStore.schemeManager.SchemeManagerImpl import com.intellij.ide.projectView.ProjectView import com.intellij.ide.ui.LafManager import com.intellij.ide.ui.UISettings.Companion.getInstance import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.application.PathManager.OPTIONS_DIRECTORY import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.application.invokeLater import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.StateStorage import com.intellij.openapi.diagnostic.Attachment import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.IconLoader import com.intellij.settingsSync.plugins.SettingsSyncPluginManager import com.intellij.ui.JBColor import com.intellij.util.SmartList import com.intellij.util.io.* import com.intellij.util.ui.StartupUiUtil import java.io.InputStream import java.nio.file.Path import java.time.Instant import java.util.concurrent.locks.ReadWriteLock import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.withLock import kotlin.io.path.pathString internal class SettingsSyncIdeMediatorImpl(private val componentStore: ComponentStoreImpl, private val rootConfig: Path, private val enabledCondition: () -> Boolean) : StreamProvider, SettingsSyncIdeMediator { companion object { val LOG = logger<SettingsSyncIdeMediatorImpl>() } private val appConfig: Path get() = rootConfig.resolve(OPTIONS_DIRECTORY) private val fileSpecsToLocks = ConcurrentCollectionFactory.createConcurrentMap<String, ReadWriteLock>() override val isExclusive: Boolean get() = true override val enabled: Boolean get() = enabledCondition() override fun isApplicable(fileSpec: String, roamingType: RoamingType): Boolean { return true } override fun applyToIde(snapshot: SettingsSnapshot) { // todo race between this code and SettingsSyncStreamProvider.write which can write other user settings at the same time // 1. update SettingsSyncSettings first to apply changes in categories val settingsSyncFileState = snapshot.fileStates.find { it.file == "$OPTIONS_DIRECTORY/${SettingsSyncSettings.FILE_SPEC}" } if (settingsSyncFileState != null) { updateSettings(listOf(settingsSyncFileState)) } // 2. update plugins val pluginsFileState = snapshot.fileStates.find { it.file == "$OPTIONS_DIRECTORY/${SettingsSyncPluginManager.FILE_SPEC}" } if (pluginsFileState != null) { val pluginManager = SettingsSyncPluginManager.getInstance() pluginManager.doWithNoUpdateFromIde { updateSettings(listOf(pluginsFileState)) pluginManager.pushChangesToIde() } } // 3. after that update the rest of changed settings val regularFileStates = snapshot.fileStates.filter { it != settingsSyncFileState && it != pluginsFileState } updateSettings(regularFileStates) invokeLater { updateUI() } } override fun activateStreamProvider() { componentStore.storageManager.addStreamProvider(this, true) } override fun removeStreamProvider() { componentStore.storageManager.removeStreamProvider(this::class.java) } override fun collectFilesToExportFromSettings(appConfigPath: Path): () -> Collection<Path> { return { getExportableItemsFromLocalStorage(getExportableComponentsMap(false), componentStore.storageManager).keys } } override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) { val file = getFileRelativeToRootConfig(fileSpec) writeUnderLock(file) { rootConfig.resolve(file).write(content, 0, size) } if (!isSyncEnabled(fileSpec, roamingType)) { return } val snapshot = SettingsSnapshot(SettingsSnapshot.MetaInfo(Instant.now()), setOf(FileState.Modified(file, content, size))) SettingsSyncEvents.getInstance().fireSettingsChanged(SyncSettingsEvent.IdeChange(snapshot)) } override fun read(fileSpec: String, roamingType: RoamingType, consumer: (InputStream?) -> Unit): Boolean { val path = appConfig.resolve(fileSpec) val adjustedSpec = getFileRelativeToRootConfig(fileSpec) return readUnderLock(adjustedSpec) { try { consumer(path.inputStreamIfExists()) true } catch (e: Throwable) { val attachment = try { Attachment(fileSpec, path.readText()) } catch (errorReadingFile: Throwable) { Attachment("file-read-error", errorReadingFile) } LOG.error("Couldn't read $fileSpec", e, attachment) false } } } override fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean): Boolean { rootConfig.resolve(path).directoryStreamIfExists({ filter(it.fileName.toString()) }) { fileStream -> for (file in fileStream) { val shouldProceed = file.inputStream().use { inputStream -> val fileSpec = rootConfig.relativize(file).systemIndependentPath read(fileSpec) { processor(file.fileName.toString(), inputStream, false) } } if (!shouldProceed) { break } } } // this method is called only for reading => no SETTINGS_CHANGED_TOPIC message is needed return true } override fun delete(fileSpec: String, roamingType: RoamingType): Boolean { val adjustedSpec = getFileRelativeToRootConfig(fileSpec) val file = rootConfig.resolve(adjustedSpec) if (!file.exists()) { LOG.debug("File $file doesn't exist, no need to delete") return true } val deleted = writeUnderLock(adjustedSpec) { deleteOrLogError(file) } if (deleted) { val snapshot = SettingsSnapshot(SettingsSnapshot.MetaInfo(Instant.now()), setOf(FileState.Deleted(adjustedSpec))) SettingsSyncEvents.getInstance().fireSettingsChanged(SyncSettingsEvent.IdeChange(snapshot)) } return deleted } private fun deleteOrLogError(file: Path): Boolean { try { file.delete() return true } catch (e: Exception) { LOG.error("Couldn't delete ${file.pathString}", e) return false } } private fun getFileRelativeToRootConfig(fileSpecPassedToProvider: String): String { // For PersistentStateComponents the fileSpec is passed without the 'options' folder, e.g. 'editor.xml' or 'mac/keymaps.xml' // OTOH for schemas it is passed together with the containing folder, e.g. 'keymaps/mykeymap.xml' return if (!fileSpecPassedToProvider.contains("/") || fileSpecPassedToProvider.startsWith(getPerOsSettingsStorageFolderName() + "/")) { OPTIONS_DIRECTORY + "/" + fileSpecPassedToProvider } else { fileSpecPassedToProvider } } private fun updateSettings(fileStates: Collection<FileState>) { val changedFileSpecs = ArrayList<String>() val deletedFileSpecs = ArrayList<String>() for (fileState in fileStates) { val fileSpec = fileState.file.removePrefix("$OPTIONS_DIRECTORY/") if (isSyncEnabled(fileSpec, RoamingType.DEFAULT)) { val file = rootConfig.resolve(fileState.file) // todo handle exceptions when modifying the file system when (fileState) { is FileState.Modified -> { writeUnderLock(fileSpec) { file.write(fileState.content, 0, fileState.size) } changedFileSpecs.add(fileSpec) } is FileState.Deleted -> { writeUnderLock(fileSpec) { file.delete() } deletedFileSpecs.add(fileSpec) } } } } invokeAndWaitIfNeeded { reloadComponents(changedFileSpecs, deletedFileSpecs) } } private fun <R> writeUnderLock(fileSpec: String, writingProcedure: () -> R): R { return getOrCreateLock(fileSpec).writeLock().withLock { writingProcedure() } } private fun <R> readUnderLock(fileSpec: String, readingProcedure: () -> R): R { return getOrCreateLock(fileSpec).readLock().withLock { readingProcedure() } } private fun getOrCreateLock(fileSpec: String) = fileSpecsToLocks.computeIfAbsent(fileSpec) { ReentrantReadWriteLock() } private fun reloadComponents(changedFileSpecs: List<String>, deletedFileSpecs: List<String>) { val schemeManagerFactory = SchemeManagerFactory.getInstance() as SchemeManagerFactoryBase val storageManager = componentStore.storageManager as StateStorageManagerImpl val (changed, deleted) = storageManager.getCachedFileStorages(changedFileSpecs, deletedFileSpecs, null) val schemeManagersToReload = SmartList<SchemeManagerImpl<*, *>>() schemeManagerFactory.process { schemeManagersToReload.add(it) } val changedComponentNames = LinkedHashSet<String>() updateStateStorage(changedComponentNames, changed, false) updateStateStorage(changedComponentNames, deleted, true) for (schemeManager in schemeManagersToReload) { schemeManager.reload() } val notReloadableComponents = componentStore.getNotReloadableComponents(changedComponentNames) componentStore.reinitComponents(changedComponentNames, changed.toSet(), notReloadableComponents) } private fun updateStateStorage(changedComponentNames: MutableSet<String>, stateStorages: Collection<StateStorage>, deleted: Boolean) { for (stateStorage in stateStorages) { try { // todo maybe we don't need "from stream provider" here since we modify the settings in place? (stateStorage as XmlElementStorage).updatedFromStreamProvider(changedComponentNames, deleted) } catch (e: Throwable) { LOG.error(e) } } } // todo copypasted from the CloudConfigManager private fun updateUI() { // TODO: separate and move this code to specific managers val lafManager = LafManager.getInstance() val lookAndFeel = lafManager.currentLookAndFeel if (lookAndFeel != null) { lafManager.setCurrentLookAndFeel(lookAndFeel, true) } val darcula = StartupUiUtil.isUnderDarcula() JBColor.setDark(darcula) IconLoader.setUseDarkIcons(darcula) ActionToolbarImpl.updateAllToolbarsImmediately() lafManager.updateUI() getInstance().fireUISettingsChanged() ParameterHintsPassFactory.forceHintsUpdateOnNextPass() EditorOptionsPanel.reinitAllEditors() EditorOptionsPanel.restartDaemons() for (project in ProjectManager.getInstance().openProjects) { ProjectView.getInstance(project).refresh() } } }
apache-2.0
2fad53646d89dc3797f793f79387cdbe
37.613014
139
0.719975
4.984085
false
true
false
false
DuncanCasteleyn/DiscordModBot
src/main/kotlin/be/duncanc/discordmodbot/bot/sequences/RevokeWarnPoints.kt
1
3738
package be.duncanc.discordmodbot.bot.sequences import be.duncanc.discordmodbot.bot.commands.CommandModule import be.duncanc.discordmodbot.bot.services.MuteRole import be.duncanc.discordmodbot.data.entities.GuildWarnPoints import be.duncanc.discordmodbot.data.repositories.jpa.GuildWarnPointsRepository import net.dv8tion.jda.api.MessageBuilder import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.MessageChannel import net.dv8tion.jda.api.entities.User import net.dv8tion.jda.api.events.message.MessageReceivedEvent import org.springframework.stereotype.Component import java.util.* import java.util.concurrent.TimeUnit @Component class RevokeWarnPoints( val guildWarnPointsRepository: GuildWarnPointsRepository, val muteRole: MuteRole ) : CommandModule( arrayOf("RevokeWarnPoints", "RevokePoints"), "Mention a user", "This command is used to remove points from a user, the user will be informed about this", requiredPermissions = arrayOf(Permission.KICK_MEMBERS), ignoreWhitelist = true ) { override fun commandExec(event: MessageReceivedEvent, command: String, arguments: String?) { val userId = try { event.message.contentRaw.substring(command.length + 2).trimStart('<', '@', '!').trimEnd('>').toLong() } catch (stringIndexOutOfBoundsException: StringIndexOutOfBoundsException) { throw IllegalArgumentException("A mention is required to use this command", stringIndexOutOfBoundsException) } val userGuildWarnPoints = guildWarnPointsRepository.findById(GuildWarnPoints.GuildWarnPointsId(userId, event.guild.idLong)) userGuildWarnPoints.ifPresentOrElse( { event.jda.addEventListener(RevokePointsSequence(event.author, event.channel, it)) }, { event.channel.sendMessage("This user id has no warnings or the user does not exist.").queue { it.delete().queueAfter(1, TimeUnit.MINUTES) } } ) } inner class RevokePointsSequence( user: User, channel: MessageChannel, private val userGuildWarnPoints: GuildWarnPoints ) : Sequence( user, channel ), MessageSequence { init { val messageBuilder = MessageBuilder("The user has had the following warnings in the past:\n\n") userGuildWarnPoints.points.forEach { userWarnPoints -> messageBuilder.append("$userWarnPoints\n\n") } messageBuilder.append("\n\nPlease enter the ID of the warning to revoke it.") messageBuilder.buildAll(MessageBuilder.SplitPolicy.NEWLINE).forEach { channel.sendMessage(it).queue { sendMessage -> super.addMessageToCleaner(sendMessage) } } } override fun onMessageReceivedDuringSequence(event: MessageReceivedEvent) { val selectedUUID: UUID = UUID.fromString(event.message.contentRaw) val selectedUserWarnPoints = userGuildWarnPoints.points.find { it.id == selectedUUID } if (selectedUserWarnPoints != null) { userGuildWarnPoints.points.remove(selectedUserWarnPoints) guildWarnPointsRepository.save(userGuildWarnPoints) channel.sendMessage("The warning has been revoked.").queue { it.delete().queueAfter(1, TimeUnit.MINUTES) } super.destroy() } else { channel.sendMessage("The warning with that id was not found.").queue { it.delete().queueAfter(1, TimeUnit.MINUTES) } super.destroy() } } } }
apache-2.0
795512db80de850aacc87d154fdcbf75
42.976471
120
0.667737
4.786172
false
false
false
false
KotlinNLP/SimpleDNN
src/test/kotlin/core/layers/feedforward/highway/HighwayLayerStructureSpec.kt
1
4820
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain contexte at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package core.layers.feedforward.highway import com.kotlinnlp.simplednn.core.optimizer.getErrorsOf import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import kotlin.test.assertTrue /** * */ class HighwayLayerStructureSpec : Spek({ describe("a HighwayLayer") { context("forward") { val layer = HighwayLayerStructureUtils.buildLayer() layer.forward() it("should match the expected input unit") { assertTrue { layer.inputUnit.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.39693, -0.796878, 0.0, 0.701374)), tolerance = 1.0e-06) } } it("should match the expected transform gate") { assertTrue { layer.transformGate.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.85321, 0.432907, 0.116089, 0.519989)), tolerance = 1.0e-06) } } it("should match the expected outputArray") { assertTrue { layer.outputArray.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.456097, -0.855358, -0.79552, 0.844718)), tolerance = 1.0e-06) } } } context("backward") { val layer = HighwayLayerStructureUtils.buildLayer() layer.forward() layer.outputArray.assignErrors(HighwayLayerStructureUtils.getOutputErrors()) val paramsErrors = layer.backward(propagateToInput = true) val params = layer.params it("should match the expected errors of the outputArray") { assertTrue { layer.outputArray.errors.equals( HighwayLayerStructureUtils.getOutputErrors(), tolerance = 1.0e-06) } } it("should match the expected errors of the input unit") { assertTrue { layer.inputUnit.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.409706, 0.118504, -0.017413, 0.433277)), tolerance = 1.0e-06) } } it("should match the expected errors of the transform gate") { assertTrue { layer.transformGate.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.028775, 0.018987, -0.013853, -0.122241)), tolerance = 1.0e-06) } } it("should match the expected errors of the input unit biases") { assertTrue { paramsErrors.getErrorsOf(params.input.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.409706, 0.118504, -0.017413, 0.433277)), tolerance = 1.0e-06) } } it("should match the expected errors of the transform gate biases") { assertTrue { paramsErrors.getErrorsOf(params.transformGate.biases)!!.values.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.028775, 0.018987, -0.013853, -0.122241)), tolerance = 1.0e-06) } } it("should match the expected errors of the input unit weights") { assertTrue { (paramsErrors.getErrorsOf(params.input.weights)!!.values).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(-0.327765, -0.368736, -0.368736, 0.409706), doubleArrayOf(-0.094803, -0.106653, -0.106653, 0.118504), doubleArrayOf(0.013931, 0.015672, 0.015672, -0.017413), doubleArrayOf(-0.346622, -0.389949, -0.389949, 0.433277) )), tolerance = 1.0e-06) } } it("should match the expected errors of the transform gate weights") { assertTrue { (paramsErrors.getErrorsOf(params.transformGate.weights)!!.values).equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(-0.023020, -0.025897, -0.025897, 0.028775), doubleArrayOf(-0.015190, -0.017088, -0.017088, 0.018987), doubleArrayOf(0.011082, 0.012467, 0.012467, -0.013853), doubleArrayOf(0.097793, 0.110017, 0.110017, -0.122241) )), tolerance = 1.0e-06) } } it("should match the expected errors of the inputArray") { assertTrue { layer.inputArray.errors.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.822397, 0.132596, -0.437003, 0.446894)), tolerance = 1.0e-06) } } } } })
mpl-2.0
d186d5beef00dcfc1066f7d0450769ad
33.676259
97
0.611411
4.009983
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantExplicitTypeInspection.kt
3
4297
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.ProblemsHolder import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.intentions.RemoveExplicitTypeIntention import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.descriptorUtil.isCompanionObject import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.AbbreviatedType import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class RedundantExplicitTypeInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = propertyVisitor(fun(property) { val typeReference = property.typeReference ?: return if (hasRedundantType(property)) { holder.registerProblem( typeReference, KotlinBundle.message("explicitly.given.type.is.redundant.here"), IntentionWrapper(RemoveExplicitTypeIntention()) ) } }) companion object { fun hasRedundantType(property: KtProperty): Boolean { if (!property.isLocal) return false val typeReference = property.typeReference ?: return false if (typeReference.annotationEntries.isNotEmpty()) return false val initializer = property.initializer ?: return false val type = property.resolveToDescriptorIfAny()?.type ?: return false if (type is AbbreviatedType) return false when (initializer) { is KtConstantExpression -> { when (initializer.node.elementType) { KtNodeTypes.BOOLEAN_CONSTANT -> { if (!KotlinBuiltIns.isBoolean(type)) return false } KtNodeTypes.INTEGER_CONSTANT -> { if (initializer.text.endsWith("L")) { if (!KotlinBuiltIns.isLong(type)) return false } else { if (!KotlinBuiltIns.isInt(type)) return false } } KtNodeTypes.FLOAT_CONSTANT -> { if (initializer.text.endsWith("f") || initializer.text.endsWith("F")) { if (!KotlinBuiltIns.isFloat(type)) return false } else { if (!KotlinBuiltIns.isDouble(type)) return false } } KtNodeTypes.CHARACTER_CONSTANT -> { if (!KotlinBuiltIns.isChar(type)) return false } else -> return false } } is KtStringTemplateExpression -> { if (!KotlinBuiltIns.isString(type)) return false } is KtNameReferenceExpression -> { if (typeReference.text != initializer.getReferencedName()) return false val initializerType = initializer.getType(property.analyze(BodyResolveMode.PARTIAL)) if (initializerType != type && initializerType.isCompanionObject()) return false } is KtCallExpression -> { if (typeReference.text != initializer.calleeExpression?.text) return false } else -> return false } return true } private fun KotlinType?.isCompanionObject() = this?.constructor?.declarationDescriptor?.isCompanionObject() == true } }
apache-2.0
8eb5f09c79f046c7beecd7900ccdd63a
47.292135
120
0.590877
6.018207
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ControlFlowWithEmptyBodyInspection.kt
1
4169
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.inspections.collections.isCalling import org.jetbrains.kotlin.idea.util.hasComments import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class ControlFlowWithEmptyBodyInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() { override fun visitIfExpression(expression: KtIfExpression) { val then = expression.then val elseKeyword = expression.elseKeyword val thenEmpty = then?.isEmptyBody() val elseEmpty = expression.`else`?.isEmptyBody() expression.ifKeyword.takeIf { thenEmpty != false && (elseEmpty != false || then?.hasComments() != true) }?.let { holder.registerProblem(expression, it) } elseKeyword?.takeIf { elseEmpty != false && (thenEmpty != false || expression.`else`?.hasComments() != true) }?.let { holder.registerProblem(expression, it) } } override fun visitWhenExpression(expression: KtWhenExpression) { if (expression.entries.isNotEmpty()) return holder.registerProblem(expression, expression.whenKeyword) } override fun visitForExpression(expression: KtForExpression) { if (expression.body.isEmptyBodyOrNull()) { holder.registerProblem(expression, expression.forKeyword) } } override fun visitWhileExpression(expression: KtWhileExpression) { val keyword = expression.allChildren.firstOrNull { it.node.elementType == KtTokens.WHILE_KEYWORD } ?: return val body = expression.body if (body?.hasComments() != true && body.isEmptyBodyOrNull()) { holder.registerProblem(expression, keyword) } } override fun visitDoWhileExpression(expression: KtDoWhileExpression) { val keyword = expression.allChildren.firstOrNull { it.node.elementType == KtTokens.DO_KEYWORD } ?: return val body = expression.body if (body?.hasComments() != true && body.isEmptyBodyOrNull()) { holder.registerProblem(expression, keyword) } } override fun visitCallExpression(expression: KtCallExpression) { val callee = expression.calleeExpression ?: return val body = when (val argument = expression.valueArguments.singleOrNull()?.getArgumentExpression()) { is KtLambdaExpression -> argument.bodyExpression is KtNamedFunction -> argument.bodyBlockExpression else -> return } if (body.isEmptyBodyOrNull() && expression.isCalling(controlFlowFunctions)) { holder.registerProblem(expression, callee) } } } private fun KtExpression?.isEmptyBodyOrNull(): Boolean = this?.isEmptyBody() ?: true private fun KtExpression.isEmptyBody(): Boolean = this is KtBlockExpression && statements.isEmpty() private fun ProblemsHolder.registerProblem(expression: KtExpression, keyword: PsiElement) { val keywordText = if (expression is KtDoWhileExpression) "do while" else keyword.text registerProblem( expression, keyword.textRange.shiftLeft(expression.startOffset), KotlinBundle.message("0.has.empty.body", keywordText) ) } companion object { private val controlFlowFunctions = listOf("kotlin.also").map { FqName(it) } } }
apache-2.0
1d9a3ed0580d391bbf9d95935222ff8f
44.326087
158
0.675462
5.290609
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/RedundantAsSequenceInspection.kt
1
4801
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.collections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.DefaultBuiltIns import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.inspections.dfa.fqNameEquals import org.jetbrains.kotlin.idea.intentions.RemoveExplicitTypeArgumentsIntention import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.idea.util.textRangeIn import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class RedundantAsSequenceInspection : AbstractKotlinInspection() { companion object { private val allowedSequenceFunctionFqNames = listOf( FqName("kotlin.sequences.asSequence"), FqName("kotlin.collections.asSequence") ) private val terminations = collectionTerminationFunctionNames.associateWith { FqName("kotlin.sequences.$it") } private val transformationsAndTerminations = collectionTransformationFunctionNames.associateWith { FqName("kotlin.sequences.$it") } + terminations } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = qualifiedExpressionVisitor(fun(qualified) { val call = qualified.callExpression ?: return val callee = call.calleeExpression ?: return if (callee.text != "asSequence") return val context = qualified.analyze(BodyResolveMode.PARTIAL) if (!call.isCalling(allowedSequenceFunctionFqNames, context)) { return } val receiverType = qualified.receiverExpression.getType(context) ?: return when { receiverType.fqNameEquals("kotlin.sequences.Sequence") -> { val typeArgumentList = call.typeArgumentList if (typeArgumentList != null && !typeArgumentList.isRedundant()) return registerProblem(holder, qualified, callee) } else -> { if (!receiverType.isIterable(DefaultBuiltIns.Instance)) return val parent = qualified.getQualifiedExpressionForReceiver() val parentCall = parent?.callExpression ?: return if (!parentCall.isTermination(context)) return val grandParentCall = parent.getQualifiedExpressionForReceiver()?.callExpression if (grandParentCall?.isTransformationOrTermination(context) == true) return registerProblem(holder, qualified, callee) } } }) private fun KtTypeArgumentList.isRedundant() = RemoveExplicitTypeArgumentsIntention.isApplicableTo(this, approximateFlexible = false) private fun registerProblem(holder: ProblemsHolder, qualified: KtQualifiedExpression, callee: KtExpression) { holder.registerProblem( qualified, callee.textRangeIn(qualified), KotlinBundle.message("inspection.redundant.assequence.call"), RemoveAsSequenceFix() ) } private fun KtCallExpression.isTermination(context: BindingContext): Boolean { val fqName = terminations[calleeExpression?.text] ?: return false return isCalling(fqName, context) } private fun KtCallExpression.isTransformationOrTermination(context: BindingContext): Boolean { val fqName = transformationsAndTerminations[calleeExpression?.text] ?: return false return isCalling(fqName, context) } private class RemoveAsSequenceFix : LocalQuickFix { override fun getName() = KotlinBundle.message("remove.assequence.call.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val qualified = descriptor.psiElement as? KtQualifiedExpression ?: return val commentSaver = CommentSaver(qualified) val replaced = qualified.replaced(qualified.receiverExpression) commentSaver.restore(replaced) } } }
apache-2.0
ff56abbdc583725b728f501a1400ead8
47.505051
158
0.729431
5.406532
false
false
false
false
mdaniel/intellij-community
platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/model/KtScope.kt
1
7506
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.codegen.deft.model import com.intellij.psi.PsiElement import com.intellij.psi.PsiManager import com.intellij.psi.util.PsiTreeUtil import com.intellij.workspaceModel.storage.WorkspaceEntity import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Open import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.psi.* class KtScope(val parent: KtScope?, var owner: Any? = null) { val ktInterface: KtInterface? get() = owner as? KtInterface override fun toString(): String = if (parent == null) owner.toString() else "$parent.${owner.toString()}" val isRoot get() = parent == null // for merging package related files into one scope var sharedScope: KtScope? = null val parts = mutableListOf<KtScope>() val _own = mutableMapOf<String, KtScope>() val own: Map<String, KtScope> get() = _own // import x.* val importedScopes = mutableListOf<KtScope>() // import x.y val importedNames = mutableMapOf<String, KtPackage>() // dependency founded via PSI analyze private val psiImportedNames = mutableMapOf<String, KtScope>() val file: KtFile? get() { var i = this while (i.owner !is KtFile) i = i.parent ?: return null return i.owner as KtFile } fun def(name: String, value: KtScope) { _own[name] = value sharedScope?._own?.let { it[name] = value } } fun resolve(typeName: String): KtScope? { var result: KtScope? = this typeName.split('.').forEach { result = result?.resolveSimpleName(it) } if (result == null) { val ktFile = owner as? KtFile ?: parent?.owner as? KtFile ?: return null result = resolveFromPsi(ktFile, typeName) if (result != null) { when { owner is KtFile -> psiImportedNames[typeName] = result!! parent?.owner is KtFile -> parent.psiImportedNames[typeName] = result!! } } } return result } private fun resolveSimpleName(typeName: String): KtScope? { val names = sharedScope?._own ?: _own return names[typeName] ?: resolveFromImportedNames(typeName) ?: resolveFromImportedScopes(typeName) ?: resolveFromPsiImportedNames(typeName) ?: parent?.resolve(typeName) } private fun resolveFromImportedNames(typeName: String) = importedNames[typeName]?.scope?.resolve(typeName) private fun resolveFromImportedScopes(typeName: String): KtScope? { importedScopes.forEach { val i = it.resolve(typeName) if (i != null) return i } return null } private fun resolveFromPsiImportedNames(typeName: String) = psiImportedNames[typeName] private fun resolveFromPsi(ktFile: KtFile, typeName: String): KtScope? { val module = ktFile.module if (module.project == null) return null if (typeName == WorkspaceEntity::class.java.simpleName) return null val psiFile = PsiManager.getInstance(module.project).findFile(ktFile.virtualFile!!) ?: return null if (psiFile !is org.jetbrains.kotlin.psi.KtFile) return null var resolvedType: PsiElement? = null PsiTreeUtil.processElements(psiFile) { psiElement -> if (psiElement is KtTypeReference && psiElement.text == typeName) { resolvedType = (psiElement.typeElement as KtUserType).referenceExpression?.mainReference?.resolve() return@processElements false } else if (psiElement is KtUserType && psiElement.text == typeName) { resolvedType = psiElement.referenceExpression?.mainReference?.resolve() return@processElements false } return@processElements true } val ktClass = resolvedType as? KtClass ?: return null val superTypes = ktClass.superTypeListEntries // Code for checking supertype FQN //((superType.typeReference?.typeElement as? KtUserType)?.referenceExpression?.mainReference?.resolve() as? KtClass)?.fqName?.toString() val workspaceEntitySuperType = superTypes.find { superType -> superType.isWorkspaceEntity() } val nameRange = ktClass.identifyingElement!!.textRange val src = Src(ktClass.name!!) { ktClass.containingFile.text } val ktTypes = superTypes.map { KtType(SrcRange(src, it.textRange.startOffset until it.textRange.endOffset)) } val annotations = KtAnnotations() listOf(Open::class.simpleName, Abstract::class.simpleName).forEach { annotationName -> val annotation = ktClass.annotationEntries.find { it.shortName?.identifier == annotationName } if (annotation != null) { val intRange = (annotation.textRange.startOffset + 1) until annotation.textRange.endOffset val annotationSrc = Src(annotation.shortName?.identifier!!) { ktClass.containingFile.text } annotations.list.add(KtAnnotation(SrcRange(annotationSrc, intRange), emptyList())) } } val predefinedKind = when { ktClass.isData() -> WsData ktClass.isEnum() -> WsEnum ktClass.isSealed() -> WsSealed ktClass.isInterface() && workspaceEntitySuperType != null -> WsPsiEntityInterface else -> null } return KtScope(this, KtInterface(module, this, SrcRange(src, nameRange.startOffset until nameRange.endOffset), ktTypes, null, predefinedKind, annotations, true)) } // val importList = psiFile.importList // val children = importList?.children ?: return null // for (child in children) { // child as KtImportDirective // val resolve = child.importedReference?.getQualifiedElementSelector()?.mainReference?.resolve() ?: return null // val importedFile = resolve.containingFile ?: return null // println("${child.text} ${importedFile.name} ${importedFile.fileType}") // when (importedFile) { // is org.jetbrains.kotlin.psi.KtFile -> { // val `class` = importedFile.classes[0] // //`class`.methods.forEach { // // println(it.name) // //} // `class`.implementsListTypes.forEach { // println(it.className) // } // println("") // } // is ClsFileImpl -> { // val `class` = importedFile.classes[0] // //`class`.allMethods.forEach { // // println(it.name) // //} // `class`.implementsListTypes.forEach { // println(it.className) // } // println("") // } // else -> { // error("Unsupported file type") // } // } // println("----------------------------------------") // } //} //return null fun visitTypes(result: MutableList<DefType>) { own.values.forEach { inner -> inner.ktInterface?.objType?.let { result.add(it) inner.visitTypes(result) } } } fun visitSimpleTypes(result: MutableList<DefType>) { own.values.forEach { inner -> inner.ktInterface?.simpleType?.let { result.add(it) inner.visitSimpleTypes(result) } } } private fun KtSuperTypeListEntry.isWorkspaceEntity(): Boolean { val resolvedType = typeAsUserType?.referenceExpression?.mainReference?.resolve() ?: return false val ktClass = resolvedType as? KtClass ?: return false if (ktClass.name == WorkspaceEntity::class.java.simpleName) return true return ktClass.superTypeListEntries.any { it.isWorkspaceEntity() } } }
apache-2.0
7d8f410bb69372fb2104b0fc270e64db
36.163366
140
0.658806
4.407516
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/NewJavaToKotlinConverter.kt
4
11368
// 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.nj2k import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.util.Computable import com.intellij.psi.* import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.j2k.* import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.nj2k.externalCodeProcessing.NewExternalCodeProcessing import org.jetbrains.kotlin.nj2k.printing.JKCodeBuilder import org.jetbrains.kotlin.nj2k.types.JKTypeFactory import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtImportList import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.resolve.ImportPath class NewJavaToKotlinConverter( val project: Project, val targetModule: Module?, val settings: ConverterSettings, val oldConverterServices: JavaToKotlinConverterServices ) : JavaToKotlinConverter() { val converterServices = object : NewJavaToKotlinServices { override val oldServices = oldConverterServices } val phasesCount = J2KConversionPhase.values().size override fun filesToKotlin( files: List<PsiJavaFile>, postProcessor: PostProcessor, progress: ProgressIndicator ): FilesResult = filesToKotlin(files, postProcessor, progress, null) fun filesToKotlin( files: List<PsiJavaFile>, postProcessor: PostProcessor, progress: ProgressIndicator, bodyFilter: ((PsiElement) -> Boolean)?, ): FilesResult { val withProgressProcessor = NewJ2kWithProgressProcessor(progress, files, postProcessor.phasesCount + phasesCount) return withProgressProcessor.process { val (results, externalCodeProcessing, context) = ApplicationManager.getApplication().runReadAction(Computable { elementsToKotlin(files, withProgressProcessor, bodyFilter) }) val kotlinFiles = results.mapIndexed { i, result -> runUndoTransparentActionInEdt(inWriteAction = true) { val javaFile = files[i] withProgressProcessor.updateState( fileIndex = i, phase = J2KConversionPhase.CREATE_FILES, description = "Creating files..." ) KtPsiFactory(project).createFileWithLightClassSupport( javaFile.name.replace(".java", ".kt"), result!!.text, files[i] ).apply { addImports(result.importsToAdd) } } } postProcessor.doAdditionalProcessing( JKMultipleFilesPostProcessingTarget(kotlinFiles), context ) { phase, description -> withProgressProcessor.updateState(fileIndex = null, phase = phase + phasesCount, description = description) } FilesResult(kotlinFiles.map { it.text }, externalCodeProcessing) } } fun elementsToKotlin(inputElements: List<PsiElement>, processor: WithProgressProcessor, bodyFilter: ((PsiElement) -> Boolean)?): Result { val phaseDescription = KotlinNJ2KBundle.message("phase.converting.j2k") val contextElement = inputElements.firstOrNull() ?: return Result(emptyList(), null, null) val resolver = JKResolver(project, targetModule, contextElement) val symbolProvider = JKSymbolProvider(resolver) val typeFactory = JKTypeFactory(symbolProvider) symbolProvider.typeFactory = typeFactory symbolProvider.preBuildTree(inputElements) val languageVersion = when { contextElement.isPhysical -> contextElement.languageVersionSettings else -> LanguageVersionSettingsImpl.DEFAULT } val importStorage = JKImportStorage(languageVersion) val treeBuilder = JavaToJKTreeBuilder(symbolProvider, typeFactory, converterServices, importStorage, bodyFilter) // we want to leave all imports as is in the case when user is converting only imports val saveImports = inputElements.all { element -> element is PsiComment || element is PsiWhiteSpace || element is PsiImportStatementBase || element is PsiImportList || element is PsiPackageStatement } val asts = inputElements.mapIndexed { i, element -> processor.updateState(i, J2KConversionPhase.BUILD_AST, phaseDescription) element to treeBuilder.buildTree(element, saveImports) } val inConversionContext = { element: PsiElement -> inputElements.any { inputElement -> if (inputElement == element) return@any true inputElement.isAncestor(element, true) } } val externalCodeProcessing = NewExternalCodeProcessing(oldConverterServices.referenceSearcher, inConversionContext) val context = NewJ2kConverterContext( symbolProvider, typeFactory, this, inConversionContext, importStorage, JKElementInfoStorage(), externalCodeProcessing, languageVersion.supportsFeature(LanguageFeature.FunctionalInterfaceConversion) ) ConversionsRunner.doApply(asts.mapNotNull { it.second }, context) { conversionIndex, conversionCount, i, desc -> processor.updateState( J2KConversionPhase.RUN_CONVERSIONS.phaseNumber, conversionIndex, conversionCount, i, desc ) } val results = asts.mapIndexed { i, elementWithAst -> processor.updateState(i, J2KConversionPhase.PRINT_CODE, phaseDescription) val (element, ast) = elementWithAst if (ast == null) return@mapIndexed null val code = JKCodeBuilder(context).run { printCodeOut(ast) } val parseContext = when (element) { is PsiStatement, is PsiExpression -> ParseContext.CODE_BLOCK else -> ParseContext.TOP_LEVEL } ElementResult( code, importsToAdd = importStorage.getImports(), parseContext = parseContext ) } return Result( results, externalCodeProcessing.takeIf { it.isExternalProcessingNeeded() }, context ) } override fun elementsToKotlin(inputElements: List<PsiElement>): Result { return elementsToKotlin(inputElements, NewJ2kWithProgressProcessor.DEFAULT) } override fun elementsToKotlin(inputElements: List<PsiElement>, processor: WithProgressProcessor): Result { return elementsToKotlin(inputElements, processor, null) } companion object { fun KtFile.addImports(imports: Collection<FqName>) { val factory = KtPsiFactory(this) if (imports.isEmpty()) return val importPsi = factory.createImportDirectives( imports.map { ImportPath(it, isAllUnder = false) } ) val createdImportList = importPsi.first().parent as KtImportList val importList = importList if (importList == null) { addImportList(createdImportList) } else { val updatedList = if (importList.firstChild != null) { createdImportList.addRangeBefore(importList.firstChild, importList.lastChild, createdImportList.firstChild) } else createdImportList importList.replace(updatedList) } } private fun KtFile.addImportList(importList: KtImportList): KtImportList { if (packageDirective != null) { return addAfter(importList, packageDirective) as KtImportList } val firstDeclaration = findChildByClass(KtDeclaration::class.java) if (firstDeclaration != null) { return addBefore(importList, firstDeclaration) as KtImportList } return add(importList) as KtImportList } } } class NewJ2kWithProgressProcessor( private val progress: ProgressIndicator?, private val files: List<PsiJavaFile>?, private val phasesCount: Int ) : WithProgressProcessor { companion object { val DEFAULT = NewJ2kWithProgressProcessor(null, null, 0) } init { progress?.isIndeterminate = false } override fun updateState(fileIndex: Int?, phase: Int, description: String) { if (fileIndex == null) updateState(phase, 1, 1, null, description) else updateState(phase, 0, 1, fileIndex, description) } override fun updateState( phase: Int, subPhase: Int, subPhaseCount: Int, fileIndex: Int?, description: String ) { progress?.checkCanceled() val singlePhaseFraction = 1.0 / phasesCount.toDouble() val singleSubPhaseFraction = singlePhaseFraction / subPhaseCount.toDouble() var resultFraction = phase * singlePhaseFraction + subPhase * singleSubPhaseFraction if (files != null && fileIndex != null && files.isNotEmpty()) { val fileFraction = singleSubPhaseFraction / files.size.toDouble() resultFraction += fileFraction * fileIndex } progress?.fraction = resultFraction if (subPhaseCount > 1) { progress?.text = KotlinNJ2KBundle.message( "subphase.progress.text", description, subPhase, subPhaseCount, phase + 1, phasesCount ) } else { progress?.text = KotlinNJ2KBundle.message("progress.text", description, phase + 1, phasesCount) } progress?.text2 = when { !files.isNullOrEmpty() && fileIndex != null -> files[fileIndex].virtualFile.presentableUrl + if (files.size > 1) " ($fileIndex/${files.size})" else "" else -> "" } } override fun <TInputItem, TOutputItem> processItems( fractionPortion: Double, inputItems: Iterable<TInputItem>, processItem: (TInputItem) -> TOutputItem ): List<TOutputItem> { throw AbstractMethodError("Should not be called for new J2K") } override fun <T> process(action: () -> T): T = action() } internal fun WithProgressProcessor.updateState(fileIndex: Int?, phase: J2KConversionPhase, description: String) { updateState(fileIndex, phase.phaseNumber, description) } internal enum class J2KConversionPhase(val phaseNumber: Int) { BUILD_AST(0), RUN_CONVERSIONS(1), PRINT_CODE(2), CREATE_FILES(3) }
apache-2.0
723c95758e2af34cfa126b96dec71ec9
38.475694
162
0.641274
5.619377
false
false
false
false
ingokegel/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildSingleFirstEntityImpl.kt
1
10269
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneParent import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ChildSingleFirstEntityImpl : ChildSingleFirstEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentSingleAbEntity::class.java, ChildSingleAbstractBaseEntity::class.java, ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, false) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } @JvmField var _commonData: String? = null override val commonData: String get() = _commonData!! override val parentEntity: ParentSingleAbEntity get() = snapshot.extractOneToAbstractOneParent(PARENTENTITY_CONNECTION_ID, this)!! @JvmField var _firstData: String? = null override val firstData: String get() = _firstData!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ChildSingleFirstEntityData?) : ModifiableWorkspaceEntityBase<ChildSingleFirstEntity>(), ChildSingleFirstEntity.Builder { constructor() : this(ChildSingleFirstEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ChildSingleFirstEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isCommonDataInitialized()) { error("Field ChildSingleAbstractBaseEntity#commonData should be initialized") } if (_diff != null) { if (_diff.extractOneToAbstractOneParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field ChildSingleAbstractBaseEntity#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field ChildSingleAbstractBaseEntity#parentEntity should be initialized") } } if (!getEntityData().isFirstDataInitialized()) { error("Field ChildSingleFirstEntity#firstData should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ChildSingleFirstEntity this.entitySource = dataSource.entitySource this.commonData = dataSource.commonData this.firstData = dataSource.firstData if (parents != null) { this.parentEntity = parents.filterIsInstance<ParentSingleAbEntity>().single() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var commonData: String get() = getEntityData().commonData set(value) { checkModificationAllowed() getEntityData().commonData = value changedProperty.add("commonData") } override var parentEntity: ParentSingleAbEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentSingleAbEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentSingleAbEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToAbstractOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override var firstData: String get() = getEntityData().firstData set(value) { checkModificationAllowed() getEntityData().firstData = value changedProperty.add("firstData") } override fun getEntityData(): ChildSingleFirstEntityData = result ?: super.getEntityData() as ChildSingleFirstEntityData override fun getEntityClass(): Class<ChildSingleFirstEntity> = ChildSingleFirstEntity::class.java } } class ChildSingleFirstEntityData : WorkspaceEntityData<ChildSingleFirstEntity>() { lateinit var commonData: String lateinit var firstData: String fun isCommonDataInitialized(): Boolean = ::commonData.isInitialized fun isFirstDataInitialized(): Boolean = ::firstData.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildSingleFirstEntity> { val modifiable = ChildSingleFirstEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): ChildSingleFirstEntity { val entity = ChildSingleFirstEntityImpl() entity._commonData = commonData entity._firstData = firstData entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ChildSingleFirstEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ChildSingleFirstEntity(commonData, firstData, entitySource) { this.parentEntity = parents.filterIsInstance<ParentSingleAbEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(ParentSingleAbEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildSingleFirstEntityData if (this.entitySource != other.entitySource) return false if (this.commonData != other.commonData) return false if (this.firstData != other.firstData) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildSingleFirstEntityData if (this.commonData != other.commonData) return false if (this.firstData != other.firstData) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + commonData.hashCode() result = 31 * result + firstData.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + commonData.hashCode() result = 31 * result + firstData.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
a6e7bfeeb5f6a40d8ad17bafeffe1d43
36.206522
165
0.703184
5.673481
false
false
false
false
googlearchive/android-PdfRendererBasic
kotlinApp/Application/src/main/java/com/example/android/pdfrendererbasic/PdfRendererBasicFragment.kt
2
7475
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.pdfrendererbasic import android.content.Context import android.graphics.Bitmap import android.graphics.Bitmap.createBitmap import android.graphics.pdf.PdfRenderer import android.os.Bundle import android.os.ParcelFileDescriptor import android.support.v4.app.Fragment import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView import java.io.File import java.io.FileOutputStream import java.io.IOException /** * This fragment has a big [ImageView] that shows PDF pages, and 2 [Button]s to move between pages. * We use a [PdfRenderer] to render PDF pages as [Bitmap]s. */ class PdfRendererBasicFragment : Fragment(), View.OnClickListener { /** * The filename of the PDF. */ private val FILENAME = "sample.pdf" /** * Key string for saving the state of current page index. */ private val STATE_CURRENT_PAGE_INDEX = "current_page_index" /** * String for logging. */ private val TAG = "PdfRendererBasicFragment" /** * The initial page index of the PDF. */ private val INITIAL_PAGE_INDEX = 0 /** * File descriptor of the PDF. */ private lateinit var fileDescriptor: ParcelFileDescriptor /** * [PdfRenderer] to render the PDF. */ private lateinit var pdfRenderer: PdfRenderer /** * Page that is currently shown on the screen. */ private lateinit var currentPage: PdfRenderer.Page /** * [ImageView] that shows a PDF page as a [Bitmap]. */ private lateinit var imageView: ImageView /** * [Button] to move to the previous page. */ private lateinit var btnPrevious: Button /** * [Button] to move to the next page. */ private lateinit var btnNext: Button /** * PDF page index. */ private var pageIndex: Int = INITIAL_PAGE_INDEX override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_pdf_renderer_basic, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) imageView = view.findViewById(R.id.image) btnPrevious = view.findViewById<Button>(R.id.previous).also { it.setOnClickListener(this) } btnNext = view.findViewById<Button>(R.id.next).also { it.setOnClickListener(this)} // If there is a savedInstanceState (screen orientations, etc.), we restore the page index. if (savedInstanceState != null) { pageIndex = savedInstanceState.getInt(STATE_CURRENT_PAGE_INDEX, INITIAL_PAGE_INDEX) } else { pageIndex = INITIAL_PAGE_INDEX } } override fun onStart() { super.onStart() try { openRenderer(activity) showPage(pageIndex) } catch (e: IOException) { Log.d(TAG, e.toString()) } } override fun onStop() { try { closeRenderer() } catch (e: IOException) { Log.d(TAG, e.toString()) } super.onStop() } override fun onSaveInstanceState(outState: Bundle) { outState.putInt(STATE_CURRENT_PAGE_INDEX, currentPage.index) super.onSaveInstanceState(outState) } /** * Sets up a [PdfRenderer] and related resources. */ @Throws(IOException::class) private fun openRenderer(context: Context?) { if (context == null) return // In this sample, we read a PDF from the assets directory. val file = File(context.cacheDir, FILENAME) if (!file.exists()) { // Since PdfRenderer cannot handle the compressed asset file directly, we copy it into // the cache directory. val asset = context.assets.open(FILENAME) val output = FileOutputStream(file) val buffer = ByteArray(1024) var size = asset.read(buffer) while (size != -1) { output.write(buffer, 0, size) size = asset.read(buffer) } asset.close() output.close() } fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) // This is the PdfRenderer we use to render the PDF. pdfRenderer = PdfRenderer(fileDescriptor) currentPage = pdfRenderer.openPage(pageIndex) } /** * Closes the [PdfRenderer] and related resources. * * @throws IOException When the PDF file cannot be closed. */ @Throws(IOException::class) private fun closeRenderer() { currentPage.close() pdfRenderer.close() fileDescriptor.close() } /** * Shows the specified page of PDF to the screen. * * @param index The page index. */ private fun showPage(index: Int) { if (pdfRenderer.pageCount <= index) return // Make sure to close the current page before opening another one. currentPage.close() // Use `openPage` to open a specific page in PDF. currentPage = pdfRenderer.openPage(index) // Important: the destination bitmap must be ARGB (not RGB). val bitmap = createBitmap(currentPage.width, currentPage.height, Bitmap.Config.ARGB_8888) // Here, we render the page onto the Bitmap. // To render a portion of the page, use the second and third parameter. Pass nulls to get // the default result. // Pass either RENDER_MODE_FOR_DISPLAY or RENDER_MODE_FOR_PRINT for the last parameter. currentPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY) // We are ready to show the Bitmap to user. imageView.setImageBitmap(bitmap) updateUi() } /** * Updates the state of 2 control buttons in response to the current page index. */ private fun updateUi() { val index = currentPage.index val pageCount = pdfRenderer.pageCount btnPrevious.isEnabled = (0 != index) btnNext.isEnabled = (index + 1 < pageCount) activity?.title = getString(R.string.app_name_with_index, index + 1, pageCount) } /** * Returns the page count of of the PDF. */ fun getPageCount() = pdfRenderer.pageCount override fun onClick(view: View) { when (view.id) { R.id.previous -> { // Move to the previous page/ showPage(currentPage.index - 1) } R.id.next -> { // Move to the next page. showPage(currentPage.index + 1) } } } }
apache-2.0
4d349ce2c0795c43198d764aa0e775a5
30.540084
99
0.631438
4.470694
false
false
false
false
GunoH/intellij-community
plugins/stream-debugger/src/com/intellij/debugger/streams/trace/dsl/impl/java/JavaTypes.kt
12
4421
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.debugger.streams.trace.dsl.impl.java import com.intellij.debugger.streams.trace.dsl.Types import com.intellij.debugger.streams.trace.impl.handler.type.* import com.intellij.psi.CommonClassNames import com.intellij.psi.PsiClass import com.intellij.psi.PsiType import com.intellij.psi.util.InheritanceUtil import com.intellij.psi.util.TypeConversionUtil import one.util.streamex.StreamEx import org.jetbrains.annotations.Contract /** * @author Vitaliy.Bibaev */ object JavaTypes : Types { override val ANY: GenericType = ClassTypeImpl(CommonClassNames.JAVA_LANG_OBJECT, "new java.lang.Object()") override val INT: GenericType = GenericTypeImpl("int", CommonClassNames.JAVA_LANG_INTEGER, "0") override val BOOLEAN: GenericType = GenericTypeImpl("boolean", CommonClassNames.JAVA_LANG_BOOLEAN, "false") override val DOUBLE: GenericType = GenericTypeImpl("double", CommonClassNames.JAVA_LANG_DOUBLE, "0.") override val EXCEPTION: GenericType = ClassTypeImpl(CommonClassNames.JAVA_LANG_THROWABLE) override val VOID: GenericType = GenericTypeImpl("void", CommonClassNames.JAVA_LANG_VOID, "null") override val TIME: GenericType = ClassTypeImpl("java.util.concurrent.atomic.AtomicInteger", "new java.util.concurrent.atomic.AtomicInteger()") override val STRING: GenericType = ClassTypeImpl(CommonClassNames.JAVA_LANG_STRING, "\"\"") override val LONG: GenericType = GenericTypeImpl("long", CommonClassNames.JAVA_LANG_LONG, "0L") override fun array(elementType: GenericType): ArrayType = ArrayTypeImpl(elementType, { "$it[]" }, { "new ${elementType.variableTypeName}[$it]" }) override fun map(keyType: GenericType, valueType: GenericType): MapType = MapTypeImpl(keyType, valueType, { keys, values -> "java.util.Map<$keys, $values>" }, "new java.util.HashMap<>()") override fun linkedMap(keyType: GenericType, valueType: GenericType): MapType = MapTypeImpl(keyType, valueType, { keys, values -> "java.util.Map<$keys, $values>" }, "new java.util.LinkedHashMap<>()") override fun list(elementsType: GenericType): ListType = ListTypeImpl(elementsType, { "java.util.List<$it>" }, "new java.util.ArrayList<>()") override fun nullable(typeSelector: Types.() -> GenericType): GenericType = this.typeSelector() private val optional: GenericType = ClassTypeImpl(CommonClassNames.JAVA_UTIL_OPTIONAL) private val optionalInt: GenericType = ClassTypeImpl("java.util.OptionalInt") private val optionalLong: GenericType = ClassTypeImpl("java.util.OptionalLong") private val optionalDouble: GenericType = ClassTypeImpl("java.util.OptionalDouble") private val OPTIONAL_TYPES = StreamEx.of(optional, optionalInt, optionalLong, optionalDouble).toSet() fun fromStreamPsiType(streamPsiType: PsiType): GenericType { return when { InheritanceUtil.isInheritor(streamPsiType, CommonClassNames.JAVA_UTIL_STREAM_INT_STREAM) -> INT InheritanceUtil.isInheritor(streamPsiType, CommonClassNames.JAVA_UTIL_STREAM_LONG_STREAM) -> LONG InheritanceUtil.isInheritor(streamPsiType, CommonClassNames.JAVA_UTIL_STREAM_DOUBLE_STREAM) -> DOUBLE PsiType.VOID == streamPsiType -> VOID else -> ANY } } fun fromPsiClass(psiClass: PsiClass): GenericType { return when { InheritanceUtil.isInheritor(psiClass, CommonClassNames.JAVA_UTIL_STREAM_INT_STREAM) -> INT InheritanceUtil.isInheritor(psiClass, CommonClassNames.JAVA_UTIL_STREAM_LONG_STREAM) -> LONG InheritanceUtil.isInheritor(psiClass, CommonClassNames.JAVA_UTIL_STREAM_DOUBLE_STREAM) -> DOUBLE else -> ANY } } fun fromPsiType(type: PsiType): GenericType { return when (type) { PsiType.VOID -> VOID PsiType.INT -> INT PsiType.DOUBLE -> DOUBLE PsiType.LONG -> LONG PsiType.BOOLEAN -> BOOLEAN else -> ClassTypeImpl(TypeConversionUtil.erasure(type).canonicalText) } } @Contract(pure = true) private fun isOptional(type: GenericType): Boolean { return OPTIONAL_TYPES.contains(type) } fun unwrapOptional(type: GenericType): GenericType { assert(isOptional(type)) return when (type) { optionalInt -> INT optionalLong -> LONG optionalDouble -> DOUBLE else -> ANY } } }
apache-2.0
a2d5432e082c89186015d17c3d26ce1a
44.122449
140
0.735806
4.390268
false
false
false
false
GunoH/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/modules/ModulesTreeItemRenderer.kt
7
2546
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.modules import com.intellij.icons.AllIcons import com.intellij.ui.ColoredTreeCellRenderer import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.speedSearch.SpeedSearchUtil import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled import javax.swing.JTree import javax.swing.tree.DefaultMutableTreeNode class ModulesTreeItemRenderer : ColoredTreeCellRenderer() { override fun customizeCellRenderer( tree: JTree, value: Any?, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean ) { if (value !is DefaultMutableTreeNode) return clear() @Suppress("MagicNumber") // Swing dimension constants iconTextGap = 4.scaled() when (val nodeTarget = value.userObject as TargetModules) { TargetModules.None, is TargetModules.All -> { icon = AllIcons.Nodes.ModuleGroup append( PackageSearchBundle.message("packagesearch.ui.toolwindow.allModules"), SimpleTextAttributes.REGULAR_ATTRIBUTES ) } is TargetModules.One -> { val projectModule = nodeTarget.module.projectModule icon = projectModule.moduleType.icon ?: AllIcons.Nodes.Module append(projectModule.name, SimpleTextAttributes.REGULAR_ATTRIBUTES) } } SpeedSearchUtil.applySpeedSearchHighlighting(tree, this, true, selected) } }
apache-2.0
b3f476aaf58b3d1a9b38886c6d918601
38.78125
91
0.656716
5.227926
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/jobs/MultiDeviceContactSyncJob.kt
1
5667
package org.thoughtcrime.securesms.jobs import org.signal.core.util.logging.Log import org.signal.libsignal.protocol.InvalidMessageException import org.thoughtcrime.securesms.database.IdentityDatabase.VerifiedStatus import org.thoughtcrime.securesms.database.SignalDatabase import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.jobmanager.Data import org.thoughtcrime.securesms.jobmanager.Job import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.net.NotPushRegisteredException import org.thoughtcrime.securesms.profiles.AvatarHelper import org.thoughtcrime.securesms.providers.BlobProvider import org.thoughtcrime.securesms.recipients.Recipient import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentPointer import org.whispersystems.signalservice.api.messages.multidevice.DeviceContact import org.whispersystems.signalservice.api.messages.multidevice.DeviceContactsInputStream import org.whispersystems.signalservice.api.messages.multidevice.VerifiedMessage.VerifiedState import org.whispersystems.signalservice.api.push.exceptions.MissingConfigurationException import org.whispersystems.signalservice.api.util.AttachmentPointerUtil import java.io.File import java.io.IOException import java.io.InputStream /** * Sync contact data from primary device. */ class MultiDeviceContactSyncJob(parameters: Parameters, private val attachmentPointer: ByteArray) : BaseJob(parameters) { constructor(contactsAttachment: SignalServiceAttachmentPointer) : this( Parameters.Builder() .setQueue("MultiDeviceContactSyncJob") .build(), AttachmentPointerUtil.createAttachmentPointer(contactsAttachment).toByteArray() ) override fun serialize(): Data { return Data.Builder() .putBlobAsString(KEY_ATTACHMENT_POINTER, attachmentPointer) .build() } override fun getFactoryKey(): String { return KEY } override fun onRun() { if (!Recipient.self().isRegistered) { throw NotPushRegisteredException() } if (SignalStore.account().isPrimaryDevice) { Log.i(TAG, "Not linked device, aborting...") return } val contactAttachment: SignalServiceAttachmentPointer = AttachmentPointerUtil.createSignalAttachmentPointer(attachmentPointer) try { val contactsFile: File = BlobProvider.getInstance().forNonAutoEncryptingSingleSessionOnDisk(context) ApplicationDependencies.getSignalServiceMessageReceiver() .retrieveAttachment(contactAttachment, contactsFile, MAX_ATTACHMENT_SIZE) .use(this::processContactFile) } catch (e: MissingConfigurationException) { throw IOException(e) } catch (e: InvalidMessageException) { throw IOException(e) } } private fun processContactFile(inputStream: InputStream) { val deviceContacts = DeviceContactsInputStream(inputStream) val recipients = SignalDatabase.recipients val threads = SignalDatabase.threads var contact: DeviceContact? = deviceContacts.read() while (contact != null) { val recipient = Recipient.externalPush(contact.address.serviceId, contact.address.number.orElse(null), true) if (recipient.isSelf) { contact = deviceContacts.read() continue } if (contact.name.isPresent) { recipients.setSystemContactName(recipient.id, contact.name.get()) } if (contact.expirationTimer.isPresent) { recipients.setExpireMessages(recipient.id, contact.expirationTimer.get()) } if (contact.profileKey.isPresent) { val profileKey = contact.profileKey.get() recipients.setProfileKey(recipient.id, profileKey) } if (contact.verified.isPresent) { val verifiedStatus: VerifiedStatus = when (contact.verified.get().verified) { VerifiedState.VERIFIED -> VerifiedStatus.VERIFIED VerifiedState.UNVERIFIED -> VerifiedStatus.UNVERIFIED else -> VerifiedStatus.DEFAULT } ApplicationDependencies.getProtocolStore().aci().identities().saveIdentityWithoutSideEffects( recipient.id, contact.verified.get().identityKey, verifiedStatus, false, contact.verified.get().timestamp, true ) } recipients.setBlocked(recipient.id, contact.isBlocked) val threadRecord = threads.getThreadRecord(threads.getThreadIdFor(recipient.id)) if (threadRecord != null && contact.isArchived != threadRecord.isArchived) { if (contact.isArchived) { threads.archiveConversation(threadRecord.threadId) } else { threads.unarchiveConversation(threadRecord.threadId) } } if (contact.avatar.isPresent) { try { AvatarHelper.setSyncAvatar(context, recipient.id, contact.avatar.get().inputStream) } catch (e: IOException) { Log.w(TAG, "Unable to set sync avatar for ${recipient.id}") } } contact = deviceContacts.read() } } override fun onShouldRetry(e: Exception): Boolean = false override fun onFailure() = Unit class Factory : Job.Factory<MultiDeviceContactSyncJob> { override fun create(parameters: Parameters, data: Data): MultiDeviceContactSyncJob { return MultiDeviceContactSyncJob(parameters, data.getStringAsBlob(KEY_ATTACHMENT_POINTER)) } } companion object { const val KEY = "MultiDeviceContactSyncJob" const val KEY_ATTACHMENT_POINTER = "attachment_pointer" private const val MAX_ATTACHMENT_SIZE: Long = 100 * 1024 * 1024 private val TAG = Log.tag(MultiDeviceContactSyncJob::class.java) } }
gpl-3.0
c353fe131871732f07b66777526b3ec4
35.798701
130
0.739192
4.626122
false
false
false
false
ktorio/ktor
ktor-shared/ktor-websockets/jvm/src/io/ktor/websocket/internals/DeflaterUtils.kt
1
2302
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.websocket.internals import io.ktor.util.cio.* import io.ktor.utils.io.core.* import io.ktor.utils.io.pool.* import java.nio.* import java.util.zip.* private val PADDED_EMPTY_CHUNK: ByteArray = byteArrayOf(0, 0, 0, 0xff.toByte(), 0xff.toByte()) private val EMPTY_CHUNK: ByteArray = byteArrayOf(0, 0, 0xff.toByte(), 0xff.toByte()) internal fun Deflater.deflateFully(data: ByteArray): ByteArray { setInput(data) val deflatedBytes = buildPacket { KtorDefaultPool.useInstance { buffer -> while (!needsInput()) { deflateTo(this@deflateFully, buffer, false) } while (deflateTo(this@deflateFully, buffer, true) != 0) {} } } if (deflatedBytes.endsWith(PADDED_EMPTY_CHUNK)) { return deflatedBytes.readBytes(deflatedBytes.remaining.toInt() - EMPTY_CHUNK.size).also { deflatedBytes.release() } } return buildPacket { writePacket(deflatedBytes) writeByte(0) }.readBytes() } internal fun Inflater.inflateFully(data: ByteArray): ByteArray { val dataToInflate = data + EMPTY_CHUNK setInput(dataToInflate) val packet = buildPacket { KtorDefaultPool.useInstance { buffer -> val limit = dataToInflate.size + bytesRead while (bytesRead < limit) { buffer.clear() val inflated = inflate(buffer.array(), buffer.position(), buffer.limit()) buffer.position(buffer.position() + inflated) buffer.flip() writeFully(buffer) } } } return packet.readBytes() } private fun BytePacketBuilder.deflateTo( deflater: Deflater, buffer: ByteBuffer, flush: Boolean ): Int { buffer.clear() val deflated = if (flush) { deflater.deflate(buffer.array(), buffer.position(), buffer.limit(), Deflater.SYNC_FLUSH) } else { deflater.deflate(buffer.array(), buffer.position(), buffer.limit()) } if (deflated == 0) { return 0 } buffer.position(buffer.position() + deflated) buffer.flip() writeFully(buffer) return deflated }
apache-2.0
526431e0d1565ca19027f3dea57c62ed
26.404762
119
0.627281
4.162749
false
false
false
false
linkedin/LiTr
litr/src/test/java/com/linkedin/android/litr/render/AudioRendererShould.kt
1
8265
package com.linkedin.android.litr.render import android.media.MediaCodec import android.media.MediaFormat import com.linkedin.android.litr.codec.Encoder import com.linkedin.android.litr.codec.Frame import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.MockitoAnnotations import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import java.nio.ByteBuffer import java.util.concurrent.Callable import java.util.concurrent.CountDownLatch import kotlin.test.assertNotNull private const val INPUT_FRAME_TAG = 0 private const val OUTPUT_FRAME_TAG_1 = 1 private const val OUTPUT_FRAME_TAG_2 = 2 private const val INPUT_BUFFER_SIZE = 40 private const val PRESENTATION_TIME = 100L private const val ENCODER_BUFFER_CAPACITY = 42 private const val EXTRA_INPUT_BYTES = 10 private const val SOURCE_SAMPLE_RATE = 44100 private const val TARGET_SAMPLE_RATE = 44100 class AudioRendererShould { @Mock private lateinit var encoder: Encoder private val encoderInputFrame1 = Frame(OUTPUT_FRAME_TAG_1, ByteBuffer.allocate(ENCODER_BUFFER_CAPACITY), MediaCodec.BufferInfo()) private val encoderInputFrame2 = Frame(OUTPUT_FRAME_TAG_2, ByteBuffer.allocate(ENCODER_BUFFER_CAPACITY), MediaCodec.BufferInfo()) private lateinit var audioRenderer: AudioRenderer @Before fun setup() { MockitoAnnotations.openMocks(this) whenever(encoder.dequeueInputFrame(any())).thenReturn(OUTPUT_FRAME_TAG_1).thenReturn(OUTPUT_FRAME_TAG_2) whenever(encoder.getInputFrame(OUTPUT_FRAME_TAG_1)).thenReturn(encoderInputFrame1) whenever(encoder.getInputFrame(OUTPUT_FRAME_TAG_2)).thenReturn(encoderInputFrame2) audioRenderer = AudioRenderer(encoder) } @Test fun `send a copy of stereo input frame to encoder when no resampling is needed`() { val sourceMediaFormat = createMediaFormat(2, SOURCE_SAMPLE_RATE) val targetMediaFormat = createMediaFormat(2, TARGET_SAMPLE_RATE) audioRenderer.init(null, sourceMediaFormat, targetMediaFormat) val frameCollector = encoder.collectOutputFrames(1) val inputFrame = createFrame(INPUT_BUFFER_SIZE, PRESENTATION_TIME, 0) audioRenderer.renderFrame(inputFrame, PRESENTATION_TIME) val outputFrames = frameCollector.call() verify(encoder).getInputFrame(OUTPUT_FRAME_TAG_1) assertThat(outputFrames.size, equalTo(1)) verifyOutputFrame(inputFrame, outputFrames[0]) } @Test fun `send a copy of mono input frame to encoder when no resampling is needed`() { val sourceMediaFormat = createMediaFormat(1, SOURCE_SAMPLE_RATE) val targetMediaFormat = createMediaFormat(1, TARGET_SAMPLE_RATE) audioRenderer.init(null, sourceMediaFormat, targetMediaFormat) val frameCollector = encoder.collectOutputFrames(1) val inputFrame = createFrame(INPUT_BUFFER_SIZE, PRESENTATION_TIME, 0) audioRenderer.renderFrame(inputFrame, PRESENTATION_TIME) val outputFrames = frameCollector.call() verify(encoder).getInputFrame(OUTPUT_FRAME_TAG_1) assertThat(outputFrames.size, equalTo(1)) verifyOutputFrame(inputFrame, outputFrames[0]) } @Test fun `use multiple output buffers to encode large input buffer`() { val channelCount = 2 val sourceMediaFormat = createMediaFormat(channelCount, SOURCE_SAMPLE_RATE) val targetMediaFormat = createMediaFormat(channelCount, TARGET_SAMPLE_RATE) audioRenderer.init(null, sourceMediaFormat, targetMediaFormat) val frameCollector = encoder.collectOutputFrames(2) val inputFrame = createFrame( ENCODER_BUFFER_CAPACITY + EXTRA_INPUT_BYTES, PRESENTATION_TIME, MediaCodec.BUFFER_FLAG_END_OF_STREAM) audioRenderer.renderFrame(inputFrame, PRESENTATION_TIME) val outputFrames = frameCollector.call() verify(encoder).getInputFrame(OUTPUT_FRAME_TAG_1) verify(encoder).getInputFrame(OUTPUT_FRAME_TAG_2) assertThat(outputFrames.size, equalTo(2)) // first encoder input frame should be filled and start at input presentation time val expectedByteBuffer1 = ByteBuffer.allocate(ENCODER_BUFFER_CAPACITY) repeat(ENCODER_BUFFER_CAPACITY) { expectedByteBuffer1.put(it.toByte()) } val expectedBufferInfo1 = MediaCodec.BufferInfo() expectedBufferInfo1.offset = 0 expectedBufferInfo1.size = ENCODER_BUFFER_CAPACITY expectedBufferInfo1.presentationTimeUs = PRESENTATION_TIME expectedBufferInfo1.flags = 0 // EOS flag should be cleared from the first buffer val expectedOutputFrame1 = Frame(OUTPUT_FRAME_TAG_1, expectedByteBuffer1, expectedBufferInfo1) // second encoder frame should contain remaining bytes and start at adjusted presentation time val expectedByteBuffer2 = ByteBuffer.allocate(ENCODER_BUFFER_CAPACITY) repeat(EXTRA_INPUT_BYTES) { expectedByteBuffer2.put((it + ENCODER_BUFFER_CAPACITY).toByte()) } val expectedBufferInfo2 = MediaCodec.BufferInfo() expectedBufferInfo2.offset = 0 expectedBufferInfo2.size = EXTRA_INPUT_BYTES expectedBufferInfo2.presentationTimeUs = inputFrame.bufferInfo.presentationTimeUs + ((ENCODER_BUFFER_CAPACITY / (channelCount * 2)) * (1_000_000f / TARGET_SAMPLE_RATE)).toLong() expectedBufferInfo2.flags = inputFrame.bufferInfo.flags // EOS flag should not be cleared from the second buffer val expectedOutputFrame2 = Frame(OUTPUT_FRAME_TAG_2, expectedByteBuffer2, expectedBufferInfo2) verifyOutputFrame(expectedOutputFrame1, outputFrames[0]) verifyOutputFrame(expectedOutputFrame2, outputFrames[1]) } private fun verifyOutputFrame(expectedFrame: Frame, actualFrame: Frame) { // compare buffer info assertThat(actualFrame.bufferInfo.size, equalTo(expectedFrame.bufferInfo.size)) assertThat(actualFrame.bufferInfo.presentationTimeUs, equalTo(expectedFrame.bufferInfo.presentationTimeUs)) assertThat(actualFrame.bufferInfo.flags, equalTo(expectedFrame.bufferInfo.flags)) // compare buffer contents assertNotNull(expectedFrame.buffer) assertNotNull(actualFrame.buffer) expectedFrame.buffer?.let { expectedBuffer -> actualFrame.buffer?.let { actualBuffer -> expectedBuffer.rewind() actualBuffer.rewind() repeat(expectedBuffer.limit()) { assertThat(expectedBuffer.get(), equalTo(actualBuffer.get())) } } } } private fun createFrame(size: Int, presentationTime: Long, flags: Int): Frame { val buffer = ByteBuffer.allocate(size) repeat(size) { buffer.put(it.toByte()) } buffer.flip() val bufferInfo = MediaCodec.BufferInfo().apply { this.offset = 0 this.size = size this.presentationTimeUs = presentationTime this.flags = flags } return Frame(INPUT_FRAME_TAG, buffer, bufferInfo) } private fun createMediaFormat(channelCount: Int, sampleRate: Int): MediaFormat { val mediaFormat = mock<MediaFormat>() whenever(mediaFormat.containsKey(MediaFormat.KEY_CHANNEL_COUNT)).thenReturn(true) whenever(mediaFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT)).thenReturn(channelCount) whenever(mediaFormat.containsKey(MediaFormat.KEY_SAMPLE_RATE)).thenReturn(true) whenever(mediaFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE)).thenReturn(sampleRate) return mediaFormat } private fun Encoder.collectOutputFrames(count: Int) : Callable<List<Frame>> { val latch = CountDownLatch(count) val frames = mutableListOf<Frame>() whenever(this.queueInputFrame(any())).thenAnswer { frames.add(it.arguments[0] as Frame) latch.countDown() } return Callable { latch.await() frames } } }
bsd-2-clause
814e9b9d50075029316f72685949eb88
41.603093
120
0.70974
4.484536
false
false
false
false
ayatk/biblio
app/src/main/kotlin/com/ayatk/biblio/data/DefaultPrefsSchema.kt
1
1237
/* * Copyright (c) 2016-2018 ayatk. * * 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.ayatk.biblio.data import androidx.annotation.StyleRes import com.ayatk.biblio.BuildConfig import com.ayatk.biblio.R import com.rejasupotaro.android.kvs.annotations.Key import com.rejasupotaro.android.kvs.annotations.Table @Suppress("unused") @Table(name = "${BuildConfig.APPLICATION_ID}_preferences") class DefaultPrefsSchema { @Key(name = "app_theme") @StyleRes val appTheme = R.style.AppTheme @Key(name = "text_background_color") val textBackgroundColor = "ffffff" @Key(name = "show_tag_at_library") val showTagAtLibrary = false @Key(name = "home_page_state") val homePageState = R.id.nav_library }
apache-2.0
4fca6ee6b52eee93108c33733ec4ad46
29.170732
75
0.742926
3.638235
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/settings/internal/SettingsAppHelper.kt
1
9944
/* * 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.settings.internal import org.hisp.dhis.android.core.settings.* @Suppress("TooManyFunctions") internal object SettingsAppHelper { fun getDataSetSettingList(dataSetSettings: DataSetSettings): List<DataSetSetting> { return dataSetSettings.specificSettings().values + dataSetSettings.globalSettings() } fun getProgramSettingList(programSettings: ProgramSettings): List<ProgramSetting> { return (programSettings.specificSettings().values + programSettings.globalSettings()).filterNotNull() } fun getFilterSettingsList(appearanceSettings: AppearanceSettings): List<FilterSetting> { val result: MutableList<FilterSetting> = arrayListOf() appearanceSettings.filterSorting()?.let { result.addAll(getHomeFilters(it.home())) result.addAll(getDataSetFilters(it.dataSetSettings())) result.addAll(getProgramFilters(it.programSettings())) } return result } private fun getHomeFilters(filters: MutableMap<HomeFilter, FilterSetting>) = filters.map { entry -> entry.value.toBuilder() .scope(HomeFilter::class.simpleName) .filterType(entry.key.name) .build() } private fun getDataSetFilters(dataSetScope: DataSetFilters): List<FilterSetting> { val globalFilters = dataSetScope.globalSettings().map { entry -> entry.value.toBuilder() .scope(DataSetFilter::class.simpleName) .filterType(entry.key.name) .build() } val specificFilters = dataSetScope.specificSettings().flatMap { entry -> entry.value.map { filter -> filter.value.toBuilder() .scope(DataSetFilter::class.simpleName) .filterType(filter.key.name) .uid(entry.key) .build() } } return listOf(globalFilters, specificFilters).flatten() } private fun getProgramFilters(programScope: ProgramFilters): List<FilterSetting> { val globalFilters = programScope.globalSettings().map { entry -> entry.value.toBuilder() .scope(ProgramFilter::class.simpleName) .filterType(entry.key.name) .build() } val specificFilters = programScope.specificSettings().flatMap { entry -> entry.value.map { filter -> filter.value.toBuilder() .scope(ProgramFilter::class.simpleName) .filterType(filter.key.name) .uid(entry.key) .build() } } return listOf(globalFilters, specificFilters).flatten() } fun getProgramConfigurationSettingList( appearanceSettings: AppearanceSettings ): List<ProgramConfigurationSetting> { val list = mutableListOf<ProgramConfigurationSetting>() appearanceSettings.programConfiguration()?.let { settings -> settings.globalSettings()?.let { list.add(it) } list.addAll( settings.specificSettings()?.map { entry -> entry.value.toBuilder() .uid(entry.key) .build() } ?: emptyList() ) } return list } fun getAnalyticsDhisVisualizations(analyticsSettings: AnalyticsSettings): List<AnalyticsDhisVisualization> { val result = mutableListOf<AnalyticsDhisVisualization>() analyticsSettings.dhisVisualizations()?.let { visualizationsSetting -> getHomeVisualizations(visualizationsSetting.home())?.let { result.addAll(it) } getProgramVisualizations(visualizationsSetting.program())?.let { result.addAll(it) } getDataSetVisualizations(visualizationsSetting.dataSet())?.let { result.addAll(it) } } return result } private fun getHomeVisualizations(analyticsDhisVisualizationsGroups: List<AnalyticsDhisVisualizationsGroup>?) = analyticsDhisVisualizationsGroups?.flatMap { group -> group.visualizations().map { visualization -> visualization.toBuilder() .groupUid(group.id()) .groupName(group.name()) .scope(AnalyticsDhisVisualizationScope.HOME) .build() } } private fun getProgramVisualizations(programVisualizations: Map<String, List<AnalyticsDhisVisualizationsGroup>>?) = programVisualizations?.flatMap { entry -> entry.value.flatMap { group -> group.visualizations().map { visualization -> visualization.toBuilder() .groupUid(group.id()) .groupName(group.name()) .scope(AnalyticsDhisVisualizationScope.PROGRAM) .scopeUid(entry.key) .build() } } } private fun getDataSetVisualizations(dataSetVisualizations: Map<String, List<AnalyticsDhisVisualizationsGroup>>?) = dataSetVisualizations?.flatMap { entry -> entry.value.flatMap { group -> group.visualizations().map { visualization -> visualization.toBuilder() .groupUid(group.id()) .groupName(group.name()) .scope(AnalyticsDhisVisualizationScope.DATA_SET) .scopeUid(entry.key) .build() } } } @JvmStatic fun buildAnalyticsTeiSettings( teiSettings: List<AnalyticsTeiSetting>, teiDataElements: List<AnalyticsTeiDataElement>, teiIndicators: List<AnalyticsTeiIndicator>, teiAttributes: List<AnalyticsTeiAttribute>, teiWhoNutritionData: List<AnalyticsTeiWHONutritionData> ): List<AnalyticsTeiSetting> { return teiSettings.map { buildAnalyticsTeiSetting(it, teiDataElements, teiIndicators, teiAttributes, teiWhoNutritionData) } } @JvmStatic fun buildAnalyticsTeiSetting( teiSetting: AnalyticsTeiSetting, teiDataElements: List<AnalyticsTeiDataElement>, teiIndicators: List<AnalyticsTeiIndicator>, teiAttributes: List<AnalyticsTeiAttribute>, teiWhoNutritionData: List<AnalyticsTeiWHONutritionData> ): AnalyticsTeiSetting { return when (teiSetting.type()) { ChartType.WHO_NUTRITION -> { val whoData = teiWhoNutritionData.find { it.teiSetting() == teiSetting.uid() }?.let { it.toBuilder() .x(buildWhoComponent(teiSetting, WHONutritionComponent.X, teiDataElements, teiIndicators)) .y(buildWhoComponent(teiSetting, WHONutritionComponent.Y, teiDataElements, teiIndicators)) .build() } teiSetting.toBuilder().whoNutritionData(whoData).build() } else -> { val data = AnalyticsTeiData.builder() .dataElements(teiDataElements.filter { it.teiSetting() == teiSetting.uid() }) .indicators(teiIndicators.filter { it.teiSetting() == teiSetting.uid() }) .attributes(teiAttributes.filter { it.teiSetting() == teiSetting.uid() }) .build() teiSetting.toBuilder().data(data).build() } } } private fun buildWhoComponent( teiSetting: AnalyticsTeiSetting, whoComponent: WHONutritionComponent, teiDataElements: List<AnalyticsTeiDataElement>, teiIndicators: List<AnalyticsTeiIndicator> ): AnalyticsTeiWHONutritionItem { return AnalyticsTeiWHONutritionItem.builder() .dataElements( teiDataElements.filter { it.teiSetting() == teiSetting.uid() && it.whoComponent() == whoComponent } ) .indicators( teiIndicators.filter { it.teiSetting() == teiSetting.uid() && it.whoComponent() == whoComponent } ) .build() } }
bsd-3-clause
b40a8b2dbf6e529cb23bce4625daafb6
40.261411
119
0.61967
5.068298
false
false
false
false
reinterpretcat/utynote
app/src/main/java/com/utynote/components/search/data/geojson/JsonSearchProcessor.kt
1
2282
package com.utynote.components.search.data.geojson import com.utynote.components.search.data.SearchProcessor import com.utynote.components.search.data.SearchResult import com.utynote.components.search.data.geojson.entities.SearchData import com.utynote.entities.GeoCoordinate import com.utynote.entities.Place import org.reactivestreams.Subscriber import org.reactivestreams.Subscription import java.util.* class JsonSearchProcessor(private val service: SearchService) : SearchProcessor() { private var subscription: rx.Subscription? = null private val subscribers: MutableList<Subscriber<in SearchResult>> init { this.subscribers = ArrayList<Subscriber<in SearchResult>>() } override fun subscribe(subscriber: Subscriber<in SearchResult>) { subscribers.add(subscriber) subscriber.onSubscribe(object : Subscription { override fun request(n: Long) {} override fun cancel() { subscribers.remove(subscriber) } }) } override fun onSubscribe(s: Subscription) { s.request(java.lang.Long.MAX_VALUE) } override fun onNext(term: String) { if (subscription != null) { subscription!!.unsubscribe() } if (subscribers.isEmpty()) { return } subscription = service .search(term) .subscribe ( { data -> notifySubscribers(term, data)}, { error -> subscribers.forEach { s -> s.onError(error) } }) } override fun onError(t: Throwable) {} override fun onComplete() {} private fun notifySubscribers(term: String, data: SearchData) { val places = data.features!! .filter { f -> "Point" == f.geometry!!.type } .map { f -> Place(id = f.properties!!.id!!, name = f.properties!!.name!!, country = f.properties!!.country!!, coordinate = GeoCoordinate( f.geometry!!.coordinates!![1], f.geometry!!.coordinates!![0])) } subscribers.forEach { s -> s.onNext(SearchResult(term, places)) } } }
agpl-3.0
de4c8b4d731178493895c0aad3b116c8
33.059701
89
0.588519
4.845011
false
false
false
false
jguerinet/MyMartlet-Android
app/src/main/java/ui/transcript/semester/SemesterActivity.kt
2
2852
/* * Copyright 2014-2019 Julien Guerinet * * 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.guerinet.mymartlet.ui.transcript.semester import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import com.guerinet.mymartlet.R import com.guerinet.mymartlet.ui.BaseActivity import com.guerinet.mymartlet.util.Constants import com.guerinet.mymartlet.util.extensions.assertNotNull import com.guerinet.mymartlet.viewmodel.SemesterViewModel import com.guerinet.suitcase.lifecycle.observe import com.guerinet.suitcase.log.TimberTag import kotlinx.android.synthetic.main.activity_semester.* import org.koin.androidx.viewmodel.ext.android.viewModel /** * Displays information about a semester from the user's transcript * @author Julien Guerinet * @since 1.0.0 */ class SemesterActivity : BaseActivity(), TimberTag { override val tag: String = "SemesterActivity" private val semesterViewModel by viewModel<SemesterViewModel>() private val adapter: SemesterAdapter by lazy { SemesterAdapter() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_semester) setUpToolbar() val semesterId = intent.getIntExtra(Constants.ID, -1) list.layoutManager = LinearLayoutManager(this) list.adapter = adapter observe(semesterViewModel.getSemester(semesterId)) { // Make sure it's not null before continuing assertNotNull(it, "Semester")?.also { semester -> // Set the title as this current semester title = semester.getName(this) degreeName.text = semester.bachelor program.text = semester.program gpa.text = getString(R.string.transcript_termGPA, semester.gpa.toString()) credits.text = getString(R.string.semester_termCredits, semester.credits.toString()) fullTime.setText( if (semester.isFullTime) { R.string.semester_fullTime } else { R.string.semester_partTime } ) } } observe(semesterViewModel.getTranscriptCourses(semesterId)) { adapter.update(it) } } }
apache-2.0
afc1b44c4bd3f48c7ccfe8172a6110dc
35.564103
100
0.684783
4.607431
false
false
false
false
iSoron/uhabits
uhabits-server/src/main/kotlin/org/isoron/uhabits/sync/links/LinkManager.kt
1
1582
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker 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. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits.sync.links import org.isoron.uhabits.sync.* import org.isoron.uhabits.sync.utils.* class LinkManager( private val timeoutInMillis: Long = 900_000, ) { private val links = HashMap<String, Link>() fun register(syncKey: String): Link { val link = Link( id = randomString(64), syncKey = syncKey, createdAt = System.currentTimeMillis(), ) links[link.id] = link return link } fun get(id: String): Link { val link = links[id] ?: throw KeyNotFoundException() val ageInMillis = System.currentTimeMillis() - link.createdAt if (ageInMillis > timeoutInMillis) { links.remove(id) throw KeyNotFoundException() } return link } }
gpl-3.0
d694aadb218449622fe72d7a9e3fb4c5
31.285714
78
0.669829
4.227273
false
false
false
false
cdietze/klay
klay-demo/src/main/kotlin/klay/tests/core/UI.kt
1
1809
package klay.tests.core import klay.core.* import klay.scene.ImageLayer import klay.scene.Pointer class UI(private val game: TestsGame) { val BUTTON_FMT: TextFormat = TextFormat(Font("Helvetica", 24f)) val TEXT_FMT: TextFormat = TextFormat(Font("Helvetica", 12f)) fun formatText(format: TextFormat, text: String, border: Boolean): Texture { val layout = game.graphics.layoutText(text, format) val margin = (if (border) 10 else 0).toFloat() val width = layout.size.width + 2 * margin val height = layout.size.height + 2 * margin val canvas = game.graphics.createCanvas(width, height) if (border) canvas.setFillColor(0xFFCCCCCC.toInt()).fillRect(0f, 0f, canvas.width, canvas.height) canvas.setFillColor(0xFF000000.toInt()).fillText(layout, margin, margin) if (border) canvas.setStrokeColor(0xFF000000.toInt()).strokeRect(0f, 0f, width - 1, height - 1) return canvas.toTexture() } fun formatText(text: String, border: Boolean): Texture { return formatText(TEXT_FMT, text, border) } fun wrapText(text: String, width: Float, align: TextBlock.Align): Texture { val layouts = game.graphics.layoutText(text, TEXT_FMT, TextWrap(width)) val canvas = TextBlock(layouts).toCanvas(game.graphics, align, 0xFF000000.toInt()) return canvas.toTexture() } fun formatButton(label: String): Texture { return formatText(BUTTON_FMT, label, true) } fun createButton(label: String, onClick: () -> Unit): ImageLayer { val layer = ImageLayer(formatButton(label)) layer.events().connect(object : Pointer.Listener { override fun onStart(iact: Pointer.Interaction) { onClick() } }) return layer } }
apache-2.0
21b5718e3785f6bc1b2fbb745174ec9e
38.326087
105
0.657269
3.941176
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/ActAbout.kt
1
6249
package jp.juggler.subwaytooter import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.Gravity import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.AppCompatButton import jp.juggler.subwaytooter.util.openBrowser import jp.juggler.util.LogCategory import jp.juggler.util.getPackageInfoCompat class ActAbout : AppCompatActivity() { class Translators( val name: String, val acct: String?, val lang: String, ) companion object { val log = LogCategory("ActAbout") const val EXTRA_SEARCH = "search" const val developer_acct = "[email protected]" const val official_acct = "[email protected]" const val url_release = "https://github.com/tateisu/SubwayTooter/releases" const val url_weblate = "https://hosted.weblate.org/projects/subway-tooter/" // git log --pretty=format:"%an %s" |grep "Translated using Weblate"|sort|uniq val translators = arrayOf( Translators("Allan Nordhøy", null, "English, Norwegian Bokmål"), Translators("ayiniho", null, "French"), Translators("ButterflyOfFire", "@[email protected]", "Arabic, French, Kabyle"), Translators("Ch", null, "Korean"), Translators("chinnux", "@[email protected]", "Chinese (Simplified)"), Translators("Dyxang", null, "Chinese (Simplified)"), Translators("Elizabeth Sherrock", null, "Chinese (Simplified)"), Translators("Gennady Archangorodsky", null, "Hebrew"), Translators("inqbs Siina", null, "Korean"), Translators("J. Lavoie", null, "French, German"), Translators("Jeong Arm", "@[email protected]", "Korean"), Translators("Joan Pujolar", "@[email protected]", "Catalan"), Translators("Kai Zhang", "@[email protected]", "Chinese (Simplified)"), Translators("koyu", null, "German"), Translators("Liaizon Wakest", null, "English"), Translators("lingcas", null, "Chinese (Traditional)"), Translators("Love Xu", null, "Chinese (Simplified)"), Translators("lptprjh", null, "Korean"), Translators("mv87", null, "German"), Translators("mynameismonkey", null, "Welsh"), Translators("Nathan", null, "French"), Translators("Niek Visser", null, "Dutch"), Translators("Owain Rhys Lewis", null, "Welsh"), Translators("Remi Rampin", null, "French"), Translators("Sachin", null, "Kannada"), Translators("Swann Martinet", null, "French"), Translators("takubunn", null, "Chinese (Simplified)"), Translators("Whod", null, "Bulgarian"), Translators("yucj", null, "Chinese (Traditional)"), Translators("邓志诚", null, "Chinese (Simplified)"), Translators("배태길", null, "Korea"), ) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) App1.setActivityTheme(this) setContentView(R.layout.act_about) App1.initEdgeToEdge(this) Styler.fixHorizontalPadding(findViewById(R.id.svContent)) try { packageManager.getPackageInfoCompat(packageName)?.let { pInfo -> findViewById<TextView>(R.id.tvVersion) ?.text = getString(R.string.version_is, pInfo.versionName) } } catch (ex: Throwable) { log.trace(ex, "can't get app version.") } fun setButton(btnId: Int, caption: String, onClick: () -> Unit) { val b: Button = findViewById(btnId) b.text = caption b.setOnClickListener { onClick() } } fun searchAcct(acct: String) { setResult(Activity.RESULT_OK, Intent().apply { putExtra(EXTRA_SEARCH, acct) }) finish() } setButton( R.id.btnDeveloper, getString(R.string.search_for, developer_acct) ) { searchAcct(developer_acct) } setButton( R.id.btnOfficialAccount, getString(R.string.search_for, official_acct) ) { searchAcct(official_acct) } setButton(R.id.btnReleaseNote, url_release) { openBrowser(url_release) } // setButton(R.id.btnIconDesign, url_futaba) // { openUrl(url_futaba) } setButton(R.id.btnWeblate, getString(R.string.please_help_translation)) { openBrowser(url_weblate) } val ll = findViewById<LinearLayout>(R.id.llContributors) val density = resources.displayMetrics.density val marginTop = (0.5f + density * 8).toInt() val padding = (0.5f + density * 8).toInt() for (who in translators) { AppCompatButton(this).apply { // layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ).apply { if (ll.childCount != 0) topMargin = marginTop } // setBackgroundResource(R.drawable.btn_bg_transparent_round6dp) setPadding(padding, padding, padding, padding) isAllCaps = false // val acct = who.acct ?: "@?@?" text = "${who.name}\n$acct\n${getString(R.string.thanks_for, who.lang)}" gravity = Gravity.START or Gravity.CENTER_VERTICAL setOnClickListener { val data = Intent() data.putExtra(EXTRA_SEARCH, who.acct ?: who.name) setResult(Activity.RESULT_OK, data) finish() } }.let { ll.addView(it) } } } }
apache-2.0
b25a20a0b48f09ef55864e4dacd09183
37.713376
98
0.569848
4.215686
false
false
false
false
pflammertsma/cryptogram
app/src/main/java/com/pixplicity/cryptogram/views/KeyboardImageButton.kt
1
4617
package com.pixplicity.cryptogram.views import android.content.Context import android.graphics.Rect import android.graphics.drawable.Drawable import android.os.Build import android.util.AttributeSet import android.view.HapticFeedbackConstants import android.view.MotionEvent import androidx.appcompat.content.res.AppCompatResources import androidx.appcompat.widget.AppCompatImageButton import androidx.core.content.ContextCompat import com.pixplicity.cryptogram.R import com.pixplicity.cryptogram.events.PuzzleEvent import com.pixplicity.cryptogram.utils.EventProvider import com.pixplicity.cryptogram.utils.KeyboardUtils import com.pixplicity.cryptogram.utils.PrefsUtils import com.squareup.otto.Subscribe import kotlin.math.roundToInt class KeyboardImageButton @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.keyboardImageButtonStyle) : AppCompatImageButton(context, attrs, defStyleAttr), KeyboardUtils.Contract { companion object { private const val REPETITION_INITIAL_DELAY = 500L private const val REPETITION_SUBSEQUENT_DELAY = 180L } override var keyIndex: Int = 0 private val mViewBounds = Rect() private var mAlpha = 255 private var dispatched = 0L private val keyRepeater = object : Runnable { override fun run() { // Clear the dispatch time so we don't dispatch on MotionEvent.ACTION_UP dispatched = 0L dispatchKey() handler.postDelayed(this, REPETITION_SUBSEQUENT_DELAY) } } init { val a = context.theme.obtainStyledAttributes( attrs, R.styleable.KeyboardImageButton, defStyleAttr, R.style.KeyboardButton_Image) try { keyIndex = a.getInteger(R.styleable.KeyboardImageButton_key, 0) } finally { a.recycle() } setOnClickListener { if (dispatched > 0L) { dispatchKey() } } setOnTouchListener { _, motionEvent -> var consume = false when (motionEvent.action) { MotionEvent.ACTION_DOWN -> { vibrate(this, true) dispatched = System.currentTimeMillis() if (KeyboardUtils.hasRepetition(this)) { handler.postDelayed(keyRepeater, REPETITION_INITIAL_DELAY) consume = true } } MotionEvent.ACTION_MOVE -> { // FIXME check if motion left bounds; if so cancel keyRepeater } MotionEvent.ACTION_CANCEL -> { handler.removeCallbacks(keyRepeater) } MotionEvent.ACTION_UP -> { handler.removeCallbacks(keyRepeater) if (!motionEvent.x.isNaN() && !motionEvent.y.isNaN()) { if (mViewBounds.contains(motionEvent.x.roundToInt(), motionEvent.y.roundToInt())) { performClick() } consume = true } } } consume } val drawable: Drawable? = AppCompatResources.getDrawable(getContext(), KeyboardUtils.getKeyIcon(this)) drawable!!.alpha = mAlpha setImageDrawable(drawable) } private fun dispatchKey() { if (System.currentTimeMillis() - dispatched > 120L) { vibrate(this, false) } KeyboardUtils.dispatch(this) } override fun onAttachedToWindow() { super.onAttachedToWindow() EventProvider.bus.register(this) } override fun onDetachedFromWindow() { EventProvider.bus.unregister(this) super.onDetachedFromWindow() } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) // Store view dimensions getDrawingRect(mViewBounds) } @Subscribe fun onPuzzleProgress(event: PuzzleEvent.PuzzleProgressEvent) { var input = false if (PrefsUtils.showUsedChars) { val keyText = KeyboardUtils.getKeyText(this) if (keyText != null && keyText.isNotEmpty()) { event.puzzle?.let { input = it.isUserCharInput(keyText[0]) } } } mAlpha = if (input) KeyboardUtils.Contract.ALPHA_GREYED else 255 invalidate() } }
mit
7e9c993be3e6df94466a333174ef65d3
33.2
230
0.602556
5.101657
false
false
false
false
flesire/ontrack
ontrack-extension-general/src/test/java/net/nemerosa/ontrack/extension/general/validation/FractionValidationDataTypeTest.kt
1
4280
package net.nemerosa.ontrack.extension.general.validation import net.nemerosa.ontrack.extension.general.GeneralExtensionFeature import net.nemerosa.ontrack.json.jsonOf import net.nemerosa.ontrack.model.exceptions.ValidationRunDataInputException import net.nemerosa.ontrack.model.structure.ValidationRunStatusID import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull class FractionValidationDataTypeTest { private val dataType = FractionValidationDataType(GeneralExtensionFeature()) @Test fun toJson() { val json = dataType.toJson( FractionValidationData(12, 50) ) assertEquals(12, json["numerator"].asInt()) assertEquals(50, json["denominator"].asInt()) } @Test fun fromJson() { val data = dataType.fromJson( jsonOf( "numerator" to 12, "denominator" to 50 ) ) assertEquals(12, data?.numerator) assertEquals(50, data?.denominator) } @Test fun getForm() { val form = dataType.getForm(null) assertNotNull(form.getField("numerator")) assertNotNull(form.getField("denominator")) } @Test fun fromFormNull() { assertNull(dataType.fromForm(null)) } @Test fun fromForm() { val data = dataType.fromForm( jsonOf( "numerator" to 12, "denominator" to 50 ) ) assertEquals(12, data?.numerator) assertEquals(50, data?.denominator) } @Test(expected = ValidationRunDataInputException::class) fun validateDataNull() { dataType.validateData(ThresholdConfig(50, 75, false), null) } @Test(expected = ValidationRunDataInputException::class) fun validateDataNumeratorNegative() { dataType.validateData(ThresholdConfig(50, 75, false), FractionValidationData(-1, 24)) } @Test(expected = ValidationRunDataInputException::class) fun validateDataDenominatorZero() { dataType.validateData(ThresholdConfig(50, 75, false), FractionValidationData(1, 0)) } @Test(expected = ValidationRunDataInputException::class) fun validateDataDenominatorNegative() { dataType.validateData(ThresholdConfig(50, 75, false), FractionValidationData(1, -1)) } @Test(expected = ValidationRunDataInputException::class) fun validateDataGreatherThan1() { dataType.validateData(ThresholdConfig(50, 75, false), FractionValidationData(13, 12)) } @Test fun computeStatus() { val config = ThresholdConfig(50, 25, true) assertEquals(ValidationRunStatusID.STATUS_PASSED.id, dataType.computeStatus(config, FractionValidationData(24, 24))?.id) assertEquals(ValidationRunStatusID.STATUS_PASSED.id, dataType.computeStatus(config, FractionValidationData(13, 24))?.id) assertEquals(ValidationRunStatusID.STATUS_PASSED.id, dataType.computeStatus(config, FractionValidationData(12, 24))?.id) assertEquals(ValidationRunStatusID.STATUS_WARNING.id, dataType.computeStatus(config, FractionValidationData(11, 24))?.id) assertEquals(ValidationRunStatusID.STATUS_WARNING.id, dataType.computeStatus(config, FractionValidationData(6, 24))?.id) assertEquals(ValidationRunStatusID.STATUS_FAILED.id, dataType.computeStatus(config, FractionValidationData(5, 24))?.id) assertEquals(ValidationRunStatusID.STATUS_FAILED.id, dataType.computeStatus(config, FractionValidationData(0, 24))?.id) } @Test fun `Status with threshold at 100%`() { val config = ThresholdConfig(100, 80, true) assertEquals(ValidationRunStatusID.STATUS_PASSED.id, dataType.computeStatus(config, FractionValidationData(10000, 10000))?.id) assertEquals(ValidationRunStatusID.STATUS_WARNING.id, dataType.computeStatus(config, FractionValidationData(9999, 10000))?.id) assertEquals(ValidationRunStatusID.STATUS_WARNING.id, dataType.computeStatus(config, FractionValidationData(8000, 10000))?.id) assertEquals(ValidationRunStatusID.STATUS_FAILED.id, dataType.computeStatus(config, FractionValidationData(7999, 10000))?.id) } }
mit
e2e6505037fbb39504460f2283b6880c
38.638889
134
0.697897
4.553191
false
true
false
false
paplorinc/intellij-community
plugins/github/src/org/jetbrains/plugins/github/util/CachingGithubUserAvatarLoader.kt
1
3062
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.util import com.google.common.cache.CacheBuilder import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.Computable import com.intellij.openapi.util.LowMemoryWatcher import com.intellij.util.ImageLoader import com.intellij.util.concurrency.AppExecutorUtil import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.GithubApiRequests import org.jetbrains.plugins.github.api.data.GithubUser import java.awt.Image import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit import java.util.function.Supplier class CachingGithubUserAvatarLoader(private val progressManager: ProgressManager) : Disposable { private val LOG = logger<CachingGithubUserAvatarLoader>() private val executor = AppExecutorUtil.getAppExecutorService() private val progressIndicator: EmptyProgressIndicator = NonReusableEmptyProgressIndicator() private val avatarCache = CacheBuilder.newBuilder() .expireAfterAccess(5, TimeUnit.MINUTES) .build<GithubUser, CompletableFuture<Image?>>() init { LowMemoryWatcher.register(Runnable { avatarCache.invalidateAll() }, this) } fun requestAvatar(requestExecutor: GithubApiRequestExecutor, user: GithubUser): CompletableFuture<Image?> { val indicator = progressIndicator // store images at maximum used size with maximum reasonable scale to avoid upscaling (3 for system scale, 2 for user scale) val imageSize = MAXIMUM_ICON_SIZE * 6 return avatarCache.get(user) { val url = user.avatarUrl if (url == null) CompletableFuture.completedFuture(null) else CompletableFuture.supplyAsync(Supplier { try { progressManager.runProcess(Computable { loadAndDownscale(requestExecutor, indicator, url, imageSize) }, indicator) } catch (e: ProcessCanceledException) { null } }, executor) } } private fun loadAndDownscale(requestExecutor: GithubApiRequestExecutor, indicator: EmptyProgressIndicator, url: String, maximumSize: Int): Image? { try { val image = requestExecutor.execute(indicator, GithubApiRequests.CurrentUser.getAvatar(url)) return if (image.getWidth(null) <= maximumSize && image.getHeight(null) <= maximumSize) image else ImageLoader.scaleImage(image, maximumSize) } catch (e: ProcessCanceledException) { return null } catch (e: Exception) { LOG.debug("Error loading image from $url", e) return null } } override fun dispose() { progressIndicator.cancel() } companion object { private const val MAXIMUM_ICON_SIZE = 40 } }
apache-2.0
dac145900a96688ecbfb7d0b4ea7ca97
38.269231
140
0.756042
4.883573
false
false
false
false
paplorinc/intellij-community
java/java-tests/testSrc/com/intellij/java/psi/impl/search/JavaNullMethodArgumentIndexTest.kt
16
3696
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.java.psi.impl.search import com.intellij.openapi.fileTypes.StdFileTypes import com.intellij.psi.impl.search.JavaNullMethodArgumentIndex import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase import com.intellij.util.indexing.FileContentImpl import com.intellij.util.indexing.IndexingDataKeys import org.intellij.lang.annotations.Language class JavaNullMethodArgumentIndexTest : LightPlatformCodeInsightFixtureTestCase() { fun testIndex() { @Language("JAVA") val file = myFixture.configureByText(StdFileTypes.JAVA, """ package org.some; class Main111 { Main111(Object o) { } void someMethod(Object o, Object o2, Object o3) { } static void staticMethod(Object o, Object o2, Object o3) { } public static void main(String[] args) { staticMethod(null, "", ""); org.some.Main111.staticMethod("", "", null); new Main111(null).someMethod("", "", null); Main111 m = new Main111(null); m.someMethod(null, "", ""); } static class SubClass { SubClass(Object o) { } } static class SubClass2 { SubClass2(Object o) { } } static void main() { new org.some.Main111(null); new org.some.Main111.SubClass(null); new SubClass2(null); new ParametrizedRunnable(null) { @Override void run() { }}; } abstract class ParametrizedRunnable { Object parameter; ParametrizedRunnable(Object parameter){ this.parameter = parameter; } abstract void run(); } } """).virtualFile val content = FileContentImpl.createByFile(file) content.putUserData(IndexingDataKeys.PROJECT, project) val data = JavaNullMethodArgumentIndex().indexer.map(content).keys assertSize(8, data) assertContainsElements(data, JavaNullMethodArgumentIndex.MethodCallData("staticMethod", 0), JavaNullMethodArgumentIndex.MethodCallData("staticMethod", 2), JavaNullMethodArgumentIndex.MethodCallData("someMethod", 0), JavaNullMethodArgumentIndex.MethodCallData("someMethod", 2), JavaNullMethodArgumentIndex.MethodCallData("Main111", 0), JavaNullMethodArgumentIndex.MethodCallData("SubClass", 0), JavaNullMethodArgumentIndex.MethodCallData("SubClass2", 0), JavaNullMethodArgumentIndex.MethodCallData("ParametrizedRunnable", 0)) } }
apache-2.0
92480285b2a640ba5a4e89b88d7c6d4c
34.548077
97
0.576028
5.73913
false
false
false
false
google/intellij-community
python/src/com/jetbrains/python/packaging/repository/PyRepositoryListItem.kt
3
4428
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.jetbrains.python.packaging.repository import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty import com.intellij.openapi.observable.properties.PropertyGraph import com.intellij.openapi.ui.NamedConfigurable import com.intellij.openapi.util.NlsSafe import com.intellij.ui.components.JBTextField import com.intellij.ui.dsl.builder.bindText import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.util.ui.JBUI import com.jetbrains.python.PyBundle.message import org.jetbrains.annotations.ApiStatus import java.awt.BorderLayout import java.awt.Dimension import javax.swing.JComponent import javax.swing.JPanel @ApiStatus.Experimental class PyRepositoryListItem(val repository: PyPackageRepository) : NamedConfigurable<PyPackageRepository>(true, null) { @NlsSafe private var currentName = repository.name!! private var password = repository.getPassword() private val propertyGraph = PropertyGraph() private val urlProperty = propertyGraph.graphProperty { repository.repositoryUrl ?: "" } private val loginProperty = propertyGraph.graphProperty { repository.login ?: "" } private val passwordProperty = propertyGraph.graphProperty { repository.getPassword() ?: "" } private val authorizationTypeProperty = propertyGraph.graphProperty { repository.authorizationType } override fun getDisplayName(): String { return currentName } override fun isModified(): Boolean { return currentName != repository.name || repository.repositoryUrl != urlProperty.get() || repository.authorizationType != authorizationTypeProperty.get() || password != passwordProperty.get() } override fun apply() { if (currentName != repository.name) { repository.clearCredentials() } repository.name = currentName val newUrl = urlProperty.get().trim() repository.repositoryUrl = if (newUrl.endsWith("/")) newUrl else "$newUrl/" repository.authorizationType = authorizationTypeProperty.get() if (repository.authorizationType == PyPackageRepositoryAuthenticationType.HTTP) { repository.login = loginProperty.get() repository.setPassword(passwordProperty.get()) } else { repository.login = "" repository.clearCredentials() } } override fun setDisplayName(name: String) { currentName = name } override fun getEditableObject(): PyPackageRepository { return repository } @Suppress("DialogTitleCapitalization") override fun getBannerSlogan(): String { return displayName } override fun createOptionsPanel(): JComponent { val mainPanel = JPanel().apply { border = JBUI.Borders.empty(10) layout = BorderLayout() } val repositoryForm = panel { row(message("python.packaging.repository.form.url")) { cell(JBTextField(repository.repositoryUrl)) .horizontalAlign(HorizontalAlign.FILL) .bindText(urlProperty) } row(message("python.packaging.repository.form.authorization")) { segmentedButton(PyPackageRepositoryAuthenticationType.values().toList(), PyPackageRepositoryAuthenticationType::text) .bind(authorizationTypeProperty) } val row1 = row(message("python.packaging.repository.form.login")) { cell(JBTextField(repository.login)).apply { component.preferredSize = Dimension(250, component.preferredSize.height) } .bindText(loginProperty) }.visible(repository.authorizationType != PyPackageRepositoryAuthenticationType.NONE) val row2 = row(message("python.packaging.repository.form.password")) { passwordField().applyToComponent { text = repository.getPassword() } .apply { component.preferredSize = Dimension(250, component.preferredSize.height) } .bindText(passwordProperty) }.visible(repository.authorizationType != PyPackageRepositoryAuthenticationType.NONE) authorizationTypeProperty.afterChange { val state = authorizationTypeProperty.get() row1.visible(state != PyPackageRepositoryAuthenticationType.NONE) row2.visible(state != PyPackageRepositoryAuthenticationType.NONE) } } mainPanel.add(repositoryForm, BorderLayout.CENTER) return mainPanel } }
apache-2.0
4f8dc43ec54be407d87ba6e413ea5f95
38.544643
126
0.743451
5.101382
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/view/course/ui/activity/CourseActivity.kt
1
27104
package org.stepik.android.view.course.ui.activity import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.activity.viewModels import androidx.annotation.StringRes import androidx.appcompat.app.AppCompatDelegate import androidx.browser.customtabs.CustomTabColorSchemeParams import androidx.browser.customtabs.CustomTabsIntent import androidx.fragment.app.DialogFragment import androidx.lifecycle.ViewModelProvider import androidx.viewpager.widget.ViewPager import com.google.firebase.remoteconfig.FirebaseRemoteConfig import com.google.firebase.remoteconfig.ktx.get import kotlinx.android.synthetic.main.activity_course.* import kotlinx.android.synthetic.main.error_course_not_found.* import kotlinx.android.synthetic.main.error_no_connection_with_button.* import kotlinx.android.synthetic.main.header_course.* import kotlinx.android.synthetic.main.header_course_placeholder.* import org.stepic.droid.R import org.stepic.droid.analytic.AmplitudeAnalytic import org.stepic.droid.analytic.Analytic import org.stepic.droid.analytic.experiments.CoursePurchaseWebviewSplitTest import org.stepic.droid.base.App import org.stepic.droid.base.FragmentActivityBase import org.stepic.droid.configuration.RemoteConfig import org.stepic.droid.ui.dialogs.LoadingProgressDialogFragment import org.stepic.droid.ui.dialogs.UnauthorizedDialogFragment import org.stepic.droid.ui.util.snackbar import org.stepic.droid.util.ProgressHelper import org.stepic.droid.util.resolveColorAttribute import org.stepik.android.domain.base.analytic.BUNDLEABLE_ANALYTIC_EVENT import org.stepik.android.domain.base.analytic.toAnalyticEvent import org.stepik.android.domain.course.analytic.CourseJoinedEvent import org.stepik.android.domain.course.analytic.CourseViewSource import org.stepik.android.domain.course_news.analytic.CourseNewsScreenOpenedAnalyticEvent import org.stepik.android.domain.course_payments.model.DeeplinkPromoCode import org.stepik.android.domain.course_purchase.analytic.CoursePurchaseSource import org.stepik.android.domain.last_step.model.LastStep import org.stepik.android.model.Course import org.stepik.android.presentation.course.CoursePresenter import org.stepik.android.presentation.course.CourseView import org.stepik.android.presentation.course.model.EnrollmentError import org.stepik.android.presentation.course_purchase.model.CoursePurchaseData import org.stepik.android.presentation.user_courses.model.UserCourseAction import org.stepik.android.presentation.wishlist.model.WishlistAction import org.stepik.android.view.base.web.CustomTabsHelper import org.stepik.android.view.course.routing.CourseDeepLinkBuilder import org.stepik.android.view.course.routing.CourseScreenTab import org.stepik.android.view.course.routing.getCourseIdFromDeepLink import org.stepik.android.view.course.routing.getCourseTabFromDeepLink import org.stepik.android.view.course.routing.getPromoCodeFromDeepLink import org.stepik.android.view.course.ui.adapter.CoursePagerAdapter import org.stepik.android.view.course.ui.delegates.CourseHeaderDelegate import org.stepik.android.view.course_content.ui.fragment.CourseContentFragment import org.stepik.android.view.course_news.ui.fragment.CourseNewsFragment import org.stepik.android.view.course_purchase.ui.dialog.CoursePurchaseBottomSheetDialogFragment import org.stepik.android.view.course_reviews.ui.fragment.CourseReviewsFragment import org.stepik.android.view.course_search.dialog.CourseSearchDialogFragment import org.stepik.android.view.fragment_pager.FragmentDelegateScrollStateChangeListener import org.stepik.android.view.in_app_web_view.ui.dialog.InAppWebViewDialogFragment import org.stepik.android.view.injection.course.CourseHeaderDelegateFactory import org.stepik.android.view.magic_links.ui.dialog.MagicLinkDialogFragment import org.stepik.android.view.ui.delegate.ViewStateDelegate import ru.nobird.android.view.base.ui.extension.showIfNotExists import javax.inject.Inject class CourseActivity : FragmentActivityBase(), CourseView, InAppWebViewDialogFragment.Callback, MagicLinkDialogFragment.Callback, CoursePurchaseBottomSheetDialogFragment.Callback { companion object { private const val EXTRA_COURSE = "course" private const val EXTRA_COURSE_ID = "course_id" private const val EXTRA_AUTO_ENROLL = "auto_enroll" private const val EXTRA_TAB = "tab" private const val EXTRA_SOURCE = "source" private const val EXTRA_DEEPLINK_PROMO_CODE = "deeplink_promo_code" private const val EXTRA_CONTINUE_LEARNING = "continue_learning" private const val NO_ID = -1L private const val NO_TITLE = "" private const val UNAUTHORIZED_DIALOG_TAG = "unauthorized_dialog" private const val QUERY_PARAM_PROMO = "promo" fun createIntent(context: Context, course: Course, source: CourseViewSource, autoEnroll: Boolean = false, continueLearning: Boolean = false, tab: CourseScreenTab = CourseScreenTab.INFO): Intent = Intent(context, CourseActivity::class.java) .putExtra(EXTRA_COURSE, course) .putExtra(EXTRA_SOURCE, source) .putExtra(EXTRA_AUTO_ENROLL, autoEnroll) .putExtra(EXTRA_CONTINUE_LEARNING, continueLearning) .putExtra(EXTRA_TAB, tab.ordinal) fun createIntent(context: Context, courseId: Long, source: CourseViewSource, tab: CourseScreenTab = CourseScreenTab.INFO): Intent = Intent(context, CourseActivity::class.java) .putExtra(EXTRA_COURSE_ID, courseId) .putExtra(EXTRA_SOURCE, source) .putExtra(EXTRA_TAB, tab.ordinal) fun createIntent(context: Context, courseId: Long, source: CourseViewSource, tab: CourseScreenTab = CourseScreenTab.INFO, deeplinkPromoCode: DeeplinkPromoCode): Intent = Intent(context, CourseActivity::class.java) .putExtra(EXTRA_COURSE_ID, courseId) .putExtra(EXTRA_SOURCE, source) .putExtra(EXTRA_TAB, tab.ordinal) .putExtra(EXTRA_DEEPLINK_PROMO_CODE, deeplinkPromoCode) init { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) } } private var courseId: Long = NO_ID private var courseTitle: String = NO_TITLE private val analyticsOnPageChangeListener = object : ViewPager.SimpleOnPageChangeListener() { override fun onPageSelected(page: Int) { when (coursePagerAdapter.getItem(page)) { is CourseReviewsFragment -> analytic .reportAmplitudeEvent( AmplitudeAnalytic.CourseReview.SCREEN_OPENED, mapOf(AmplitudeAnalytic.CourseReview.Params.COURSE to courseId.toString()) ) is CourseNewsFragment -> analytic.report(CourseNewsScreenOpenedAnalyticEvent(courseId, courseTitle)) is CourseContentFragment -> analytic .reportAmplitudeEvent( AmplitudeAnalytic.Sections.SCREEN_OPENED, mapOf(AmplitudeAnalytic.Sections.Params.COURSE to courseId.toString()) ) } } } private lateinit var coursePagerAdapter: CoursePagerAdapter private val coursePresenter: CoursePresenter by viewModels { viewModelFactory } private lateinit var courseHeaderDelegate: CourseHeaderDelegate private var unauthorizedDialogFragment: DialogFragment? = null private val progressDialogFragment: DialogFragment = LoadingProgressDialogFragment.newInstance() private val viewStateDelegate = ViewStateDelegate<CourseView.State>() private var viewPagerScrollState: Int = ViewPager.SCROLL_STATE_IDLE private var isInSwipeableViewState = false private var hasSavedInstanceState: Boolean = false @Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory @Inject internal lateinit var firebaseRemoteConfig: FirebaseRemoteConfig @Inject internal lateinit var coursePurchaseWebviewSplitTest: CoursePurchaseWebviewSplitTest @Inject internal lateinit var courseDeeplinkBuilder: CourseDeepLinkBuilder @Inject internal lateinit var courseHeaderDelegateFactory: CourseHeaderDelegateFactory override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_course) setSupportActionBar(courseToolbar) val actionBar = this.supportActionBar ?: throw IllegalStateException("support action bar should be set") with(actionBar) { setDisplayShowTitleEnabled(false) setDisplayHomeAsUpEnabled(true) } val course: Course? = intent.getParcelableExtra(EXTRA_COURSE) val deepLinkCourseId = intent.getCourseIdFromDeepLink() if (savedInstanceState == null && deepLinkCourseId != null) { analytic.reportEvent(Analytic.DeepLink.USER_OPEN_COURSE_DETAIL_LINK, deepLinkCourseId.toString()) analytic.reportEvent(Analytic.DeepLink.USER_OPEN_LINK_GENERAL) // handle wrong deeplink interceptions intent.data?.let { uri -> screenManager.redirectToWebBrowserIfNeeded(this, uri) } } if (course != null) { courseTitle = course.title.orEmpty() courseToolbarTitle.text = course.title } courseId = intent.getLongExtra(EXTRA_COURSE_ID, NO_ID) .takeIf { it != NO_ID } ?: course?.id ?: deepLinkCourseId ?: NO_ID injectComponent(courseId) if (savedInstanceState == null) { val analyticEvent = intent .getBundleExtra(BUNDLEABLE_ANALYTIC_EVENT) ?.toAnalyticEvent() if (analyticEvent != null) { analytic.report(analyticEvent) } } val courseViewSource = (intent.getSerializableExtra(EXTRA_SOURCE) as? CourseViewSource) ?: intent.getCourseIdFromDeepLink()?.let { CourseViewSource.DeepLink(intent?.dataString ?: "") } ?: CourseViewSource.Unknown courseHeaderDelegate = courseHeaderDelegateFactory .create( courseActivity = this, coursePresenter = coursePresenter, courseViewSource = courseViewSource, isAuthorized = sharedPreferenceHelper.authResponseFromStore != null, mustShowCourseRevenue = firebaseRemoteConfig.getBoolean(RemoteConfig.IS_COURSE_REVENUE_AVAILABLE_ANDROID) && course?.actions?.viewRevenue?.enabled == true, showCourseRevenueAction = { screenManager.showCourseRevenue(this, courseId, course?.title) }, onSubmissionCountClicked = { screenManager.showCachedAttempts(this, courseId) }, isLocalSubmissionsEnabled = firebaseRemoteConfig[RemoteConfig.IS_LOCAL_SUBMISSIONS_ENABLED].asBoolean(), showCourseSearchAction = { CourseSearchDialogFragment .newInstance(courseId, course?.title.orEmpty()) .showIfNotExists(supportFragmentManager, CourseSearchDialogFragment.TAG) }, coursePurchaseFlowAction = { coursePurchaseData, isNeedRestoreMessage -> showCoursePurchaseBottomSheetDialogFragment(coursePurchaseData, isNeedRestoreMessage) } ) initViewPager(courseId, course?.title.toString()) initViewStateDelegate() hasSavedInstanceState = savedInstanceState != null setDataToPresenter(courseViewSource) courseSwipeRefresh.setOnRefreshListener { setDataToPresenter(courseViewSource, forceUpdate = true) } tryAgain.setOnClickListener { setDataToPresenter(courseViewSource, forceUpdate = true) } goToCatalog.setOnClickListener { screenManager.showCatalog(this) finish() } } private fun setDataToPresenter(courseViewSource: CourseViewSource, forceUpdate: Boolean = false) { val course: Course? = intent.getParcelableExtra(EXTRA_COURSE) if (course != null) { coursePresenter.onCourse(course, courseViewSource, forceUpdate) } else { /** * Fallback to DeeplinkPromoCode from LessonDemoCompleteBottomSheetDialogFragment */ coursePresenter.onCourseId(courseId, courseViewSource, intent.getPromoCodeFromDeepLink() ?: intent.getParcelableExtra<DeeplinkPromoCode>(EXTRA_DEEPLINK_PROMO_CODE)?.name, forceUpdate) } } private fun injectComponent(courseId: Long) { App.componentManager() .courseComponent(courseId) .coursePresentationComponentBuilder() .build() .inject(this) } private fun releaseComponent(courseId: Long) { App.componentManager() .releaseCourseComponent(courseId) } override fun onStart() { super.onStart() coursePresenter.attachView(this) } override fun onResume() { super.onResume() if (coursePurchaseWebviewSplitTest.currentGroup != CoursePurchaseWebviewSplitTest.Group.InAppWebview) { coursePresenter.handleCoursePurchasePressed() } coursePager.addOnPageChangeListener(analyticsOnPageChangeListener) if (!hasSavedInstanceState) { setCurrentTab() } } override fun onPause() { coursePager.removeOnPageChangeListener(analyticsOnPageChangeListener) super.onPause() } override fun onStop() { coursePresenter.detachView(this) super.onStop() } private fun setCurrentTab() { val tab = CourseScreenTab .values() .getOrNull(intent.getIntExtra(EXTRA_TAB, -1)) ?: intent.getCourseTabFromDeepLink() coursePager.currentItem = when (tab) { CourseScreenTab.REVIEWS -> 1 CourseScreenTab.NEWS -> 2 CourseScreenTab.SYLLABUS -> 3 else -> 0 } if (coursePager.currentItem == 0) { analyticsOnPageChangeListener.onPageSelected(0) } } private fun initViewPager(courseId: Long, courseTitle: String) { coursePagerAdapter = CoursePagerAdapter(courseId, courseTitle, this, supportFragmentManager) coursePager.adapter = coursePagerAdapter val onPageChangeListener = object : ViewPager.SimpleOnPageChangeListener() { override fun onPageScrollStateChanged(scrollState: Int) { viewPagerScrollState = scrollState resolveSwipeRefreshState() } } coursePager.addOnPageChangeListener(FragmentDelegateScrollStateChangeListener(coursePager, coursePagerAdapter)) coursePager.addOnPageChangeListener(onPageChangeListener) courseTabs.setupWithViewPager(coursePager) } private fun initViewStateDelegate() { viewStateDelegate.addState<CourseView.State.EmptyCourse>(courseEmpty) viewStateDelegate.addState<CourseView.State.NetworkError>(errorNoConnection) viewStateDelegate.addState<CourseView.State.CourseLoaded>(courseHeader, courseTabs, coursePager) viewStateDelegate.addState<CourseView.State.BlockingLoading>(courseHeader, courseTabs, coursePager) viewStateDelegate.addState<CourseView.State.Loading>(courseHeaderPlaceholder, courseTabs, coursePager) viewStateDelegate.addState<CourseView.State.Idle>(courseHeaderPlaceholder, courseTabs, coursePager) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.course_activity_menu, menu) courseHeaderDelegate.onOptionsMenuCreated(menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean = if (item.itemId == android.R.id.home) { onBackPressed() true } else { courseHeaderDelegate.onOptionsItemSelected(item) || super.onOptionsItemSelected(item) } override fun applyTransitionPrev() { // no-op } private fun resolveSwipeRefreshState() { courseSwipeRefresh.isEnabled = viewPagerScrollState == ViewPager.SCROLL_STATE_IDLE && isInSwipeableViewState } override fun setState(state: CourseView.State) { courseSwipeRefresh.isRefreshing = false isInSwipeableViewState = (state is CourseView.State.CourseLoaded || state is CourseView.State.NetworkError) resolveSwipeRefreshState() when (state) { is CourseView.State.CourseLoaded -> { courseHeaderDelegate.courseHeaderData = state.courseHeaderData if (intent.getBooleanExtra(EXTRA_AUTO_ENROLL, false)) { intent.removeExtra(EXTRA_AUTO_ENROLL) coursePresenter.autoEnroll() analytic.report( CourseJoinedEvent( CourseJoinedEvent.SOURCE_PREVIEW, state.courseHeaderData.course, state.courseHeaderData.course.isInWishlist ) ) } if (intent.getBooleanExtra(EXTRA_CONTINUE_LEARNING, false)) { intent.removeExtra(EXTRA_CONTINUE_LEARNING) coursePresenter.continueLearning() } /** * Obtain promo code from LessonDemoCompleteBottomSheetDialog */ val deeplinkPromoCode = intent.getParcelableExtra<DeeplinkPromoCode>(EXTRA_DEEPLINK_PROMO_CODE) if (deeplinkPromoCode != null) { intent.removeExtra(EXTRA_DEEPLINK_PROMO_CODE) val queryParams = if (deeplinkPromoCode != DeeplinkPromoCode.EMPTY) { mapOf(QUERY_PARAM_PROMO to listOf(deeplinkPromoCode.name)) } else { null } coursePresenter.openCoursePurchaseInWeb(queryParams) } ProgressHelper.dismiss(supportFragmentManager, LoadingProgressDialogFragment.TAG) } is CourseView.State.BlockingLoading -> { courseHeaderDelegate.courseHeaderData = state.courseHeaderData ProgressHelper.activate(progressDialogFragment, supportFragmentManager, LoadingProgressDialogFragment.TAG) } } viewStateDelegate.switchState(state) invalidateOptionsMenu() } override fun showEmptyAuthDialog(course: Course) { if (unauthorizedDialogFragment?.isAdded != true) { unauthorizedDialogFragment = UnauthorizedDialogFragment.newInstance(course) unauthorizedDialogFragment?.show(supportFragmentManager, UNAUTHORIZED_DIALOG_TAG) } } override fun showEnrollmentError(errorType: EnrollmentError) { @StringRes val errorMessage = when (errorType) { EnrollmentError.NO_CONNECTION -> R.string.course_error_enroll EnrollmentError.FORBIDDEN -> R.string.join_course_web_exception EnrollmentError.UNAUTHORIZED -> R.string.unauthorization_detail EnrollmentError.BILLING_ERROR -> R.string.course_purchase_billing_error EnrollmentError.BILLING_CANCELLED -> R.string.course_purchase_billing_cancelled EnrollmentError.BILLING_NOT_AVAILABLE -> R.string.course_purchase_billing_not_available EnrollmentError.COURSE_ALREADY_OWNED -> R.string.course_purchase_already_owned EnrollmentError.BILLING_NO_PURCHASES_TO_RESTORE -> R.string.course_purchase_billing_no_purchases_to_restore } coursePager.snackbar(messageRes = errorMessage) } override fun shareCourse(course: Course) { startActivity(shareHelper.getIntentForCourseSharing(course)) } override fun showCourseShareTooltip() { courseHeaderDelegate.showCourseShareTooltip() } override fun showSaveUserCourseSuccess(userCourseAction: UserCourseAction) { @StringRes val successMessage = when (userCourseAction) { UserCourseAction.ADD_FAVORITE -> R.string.course_action_favorites_add_success UserCourseAction.REMOVE_FAVORITE -> R.string.course_action_favorites_remove_success UserCourseAction.ADD_ARCHIVE -> R.string.course_action_archive_add_success UserCourseAction.REMOVE_ARCHIVE -> R.string.course_action_archive_remove_success } coursePager.snackbar(messageRes = successMessage) } override fun showSaveUserCourseError(userCourseAction: UserCourseAction) { @StringRes val errorMessage = when (userCourseAction) { UserCourseAction.ADD_FAVORITE -> R.string.course_action_favorites_add_failure UserCourseAction.REMOVE_FAVORITE -> R.string.course_action_favorites_remove_failure UserCourseAction.ADD_ARCHIVE -> R.string.course_action_archive_add_failure UserCourseAction.REMOVE_ARCHIVE -> R.string.course_action_archive_remove_failure } coursePager.snackbar(messageRes = errorMessage) } override fun showWishlistActionSuccess(wishlistAction: WishlistAction) { @StringRes val successMessage = if (wishlistAction == WishlistAction.ADD) { R.string.wishlist_action_add_success } else { R.string.wishlist_action_remove_success } coursePager.snackbar(messageRes = successMessage) } override fun showWishlistActionFailure(wishlistAction: WishlistAction) { @StringRes val errorMessage = if (wishlistAction == WishlistAction.ADD) { R.string.wishlist_action_add_failure } else { R.string.wishlist_action_remove_failure } coursePager.snackbar(messageRes = errorMessage) } override fun openCoursePurchaseInWeb(courseId: Long, queryParams: Map<String, List<String>>?) { val url = courseDeeplinkBuilder.createCourseLink(courseId, CourseScreenTab.PAY, queryParams) when (coursePurchaseWebviewSplitTest.currentGroup) { CoursePurchaseWebviewSplitTest.Group.Control -> { MagicLinkDialogFragment .newInstance(url) .showIfNotExists(supportFragmentManager, MagicLinkDialogFragment.TAG) } CoursePurchaseWebviewSplitTest.Group.InAppWebview -> { InAppWebViewDialogFragment .newInstance(getString(R.string.course_purchase), url, isProvideAuth = true) .showIfNotExists(supportFragmentManager, InAppWebViewDialogFragment.TAG) } CoursePurchaseWebviewSplitTest.Group.ChromeTab -> { MagicLinkDialogFragment .newInstance(url, handleUrlInParent = true) .showIfNotExists(supportFragmentManager, MagicLinkDialogFragment.TAG) } } } override fun showTrialLesson(lessonId: Long, unitId: Long) { screenManager.showTrialLesson(this, lessonId, unitId) } override fun onDestroy() { releaseComponent(courseId) super.onDestroy() } override fun showCourse(course: Course, source: CourseViewSource, isAdaptive: Boolean) { if (isAdaptive) { screenManager.continueAdaptiveCourse(this, course) } else { coursePager.snackbar(messageRes = R.string.course_error_continue_learning) } } override fun showSteps(course: Course, source: CourseViewSource, lastStep: LastStep) { screenManager.continueCourse(this, lastStep) } override fun setBlockingLoading(isLoading: Boolean) { if (isLoading) { ProgressHelper.activate(progressDialogFragment, supportFragmentManager, LoadingProgressDialogFragment.TAG) } else { ProgressHelper.dismiss(supportFragmentManager, LoadingProgressDialogFragment.TAG) } } override fun onDismissed() { coursePresenter.handleCoursePurchasePressed() } override fun handleUrl(url: String) { val builder = CustomTabsIntent.Builder() builder.setShowTitle(true) builder.setDefaultColorSchemeParams( CustomTabColorSchemeParams.Builder() .setToolbarColor(resolveColorAttribute(R.attr.colorSurface)) .setSecondaryToolbarColor(resolveColorAttribute(R.attr.colorSurface)) .build() ) val customTabsIntent = builder.build() val packageName = CustomTabsHelper.getPackageNameToUse(this) analytic.reportAmplitudeEvent( AmplitudeAnalytic.ChromeTab.CHROME_TAB_OPENED, mapOf(AmplitudeAnalytic.ChromeTab.Params.FALLBACK to (packageName == null)) ) if (packageName == null) { InAppWebViewDialogFragment .newInstance(getString(R.string.course_purchase), url, isProvideAuth = false) .showIfNotExists(supportFragmentManager, InAppWebViewDialogFragment.TAG) } else { customTabsIntent.intent.`package` = packageName customTabsIntent.launchUrl(this, Uri.parse(url)) } } override fun openCoursePurchaseInApp(coursePurchaseData: CoursePurchaseData) { showCoursePurchaseBottomSheetDialogFragment(coursePurchaseData, isNeedRestoreMessage = false) } override fun continueLearning() { coursePresenter.continueLearning() } private fun showCoursePurchaseBottomSheetDialogFragment(coursePurchaseData: CoursePurchaseData, isNeedRestoreMessage: Boolean) { CoursePurchaseBottomSheetDialogFragment .newInstance(coursePurchaseData, coursePurchaseSource = CoursePurchaseSource.COURSE_SCREEN_SOURCE, isNeedRestoreMessage = isNeedRestoreMessage) .showIfNotExists(supportFragmentManager, CoursePurchaseBottomSheetDialogFragment.TAG) } }
apache-2.0
43819230ed13eb34f0342456eb98f48c
41.484326
203
0.674587
5.317638
false
false
false
false