repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryNavigationView.kt
3
7884
package eu.kanade.tachiyomi.ui.library import android.content.Context import android.util.AttributeSet import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.widget.ExtendedNavigationView import eu.kanade.tachiyomi.widget.ExtendedNavigationView.Item.MultiSort.Companion.SORT_ASC import eu.kanade.tachiyomi.widget.ExtendedNavigationView.Item.MultiSort.Companion.SORT_DESC import eu.kanade.tachiyomi.widget.ExtendedNavigationView.Item.MultiSort.Companion.SORT_NONE import uy.kohesive.injekt.injectLazy /** * The navigation view shown in a drawer with the different options to show the library. */ class LibraryNavigationView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ExtendedNavigationView(context, attrs) { /** * Preferences helper. */ private val preferences: PreferencesHelper by injectLazy() /** * List of groups shown in the view. */ private val groups = listOf(FilterGroup(), SortGroup(), DisplayGroup(), BadgeGroup()) /** * Adapter instance. */ private val adapter = Adapter(groups.map { it.createItems() }.flatten()) /** * Click listener to notify the parent fragment when an item from a group is clicked. */ var onGroupClicked: (Group) -> Unit = {} init { recycler.adapter = adapter addView(recycler) groups.forEach { it.initModels() } } /** * Returns true if there's at least one filter from [FilterGroup] active. */ fun hasActiveFilters(): Boolean { return (groups[0] as FilterGroup).items.any { it.checked } } /** * Adapter of the recycler view. */ inner class Adapter(items: List<Item>) : ExtendedNavigationView.Adapter(items) { override fun onItemClicked(item: Item) { if (item is GroupedItem) { item.group.onItemClicked(item) onGroupClicked(item.group) } } } /** * Filters group (unread, downloaded, ...). */ inner class FilterGroup : Group { private val downloaded = Item.CheckboxGroup(R.string.action_filter_downloaded, this) private val unread = Item.CheckboxGroup(R.string.action_filter_unread, this) private val completed = Item.CheckboxGroup(R.string.completed, this) override val items = listOf(downloaded, unread, completed) override val header = Item.Header(R.string.action_filter) override val footer = Item.Separator() override fun initModels() { downloaded.checked = preferences.filterDownloaded().getOrDefault() unread.checked = preferences.filterUnread().getOrDefault() completed.checked = preferences.filterCompleted().getOrDefault() } override fun onItemClicked(item: Item) { item as Item.CheckboxGroup item.checked = !item.checked when (item) { downloaded -> preferences.filterDownloaded().set(item.checked) unread -> preferences.filterUnread().set(item.checked) completed -> preferences.filterCompleted().set(item.checked) } adapter.notifyItemChanged(item) } } /** * Sorting group (alphabetically, by last read, ...) and ascending or descending. */ inner class SortGroup : Group { private val alphabetically = Item.MultiSort(R.string.action_sort_alpha, this) private val total = Item.MultiSort(R.string.action_sort_total, this) private val lastRead = Item.MultiSort(R.string.action_sort_last_read, this) private val lastUpdated = Item.MultiSort(R.string.action_sort_last_updated, this) private val unread = Item.MultiSort(R.string.action_filter_unread, this) private val source = Item.MultiSort(R.string.manga_info_source_label, this) override val items = listOf(alphabetically, lastRead, lastUpdated, unread, total, source) override val header = Item.Header(R.string.action_sort) override val footer = Item.Separator() override fun initModels() { val sorting = preferences.librarySortingMode().getOrDefault() val order = if (preferences.librarySortingAscending().getOrDefault()) SORT_ASC else SORT_DESC alphabetically.state = if (sorting == LibrarySort.ALPHA) order else SORT_NONE lastRead.state = if (sorting == LibrarySort.LAST_READ) order else SORT_NONE lastUpdated.state = if (sorting == LibrarySort.LAST_UPDATED) order else SORT_NONE unread.state = if (sorting == LibrarySort.UNREAD) order else SORT_NONE total.state = if (sorting == LibrarySort.TOTAL) order else SORT_NONE source.state = if (sorting == LibrarySort.SOURCE) order else SORT_NONE } override fun onItemClicked(item: Item) { item as Item.MultiStateGroup val prevState = item.state item.group.items.forEach { (it as Item.MultiStateGroup).state = SORT_NONE } item.state = when (prevState) { SORT_NONE -> SORT_ASC SORT_ASC -> SORT_DESC SORT_DESC -> SORT_ASC else -> throw Exception("Unknown state") } preferences.librarySortingMode().set(when (item) { alphabetically -> LibrarySort.ALPHA lastRead -> LibrarySort.LAST_READ lastUpdated -> LibrarySort.LAST_UPDATED unread -> LibrarySort.UNREAD total -> LibrarySort.TOTAL source -> LibrarySort.SOURCE else -> throw Exception("Unknown sorting") }) preferences.librarySortingAscending().set(if (item.state == SORT_ASC) true else false) item.group.items.forEach { adapter.notifyItemChanged(it) } } } inner class BadgeGroup : Group { private val downloadBadge = Item.CheckboxGroup(R.string.action_display_download_badge, this) override val header = null override val footer = null override val items = listOf(downloadBadge) override fun initModels() { downloadBadge.checked = preferences.downloadBadge().getOrDefault() } override fun onItemClicked(item: Item) { item as Item.CheckboxGroup item.checked = !item.checked preferences.downloadBadge().set((item.checked)) adapter.notifyItemChanged(item) } } /** * Display group, to show the library as a list or a grid. */ inner class DisplayGroup : Group { private val grid = Item.Radio(R.string.action_display_grid, this) private val list = Item.Radio(R.string.action_display_list, this) override val items = listOf(grid, list) override val header = Item.Header(R.string.action_display) override val footer = null override fun initModels() { val asList = preferences.libraryAsList().getOrDefault() grid.checked = !asList list.checked = asList } override fun onItemClicked(item: Item) { item as Item.Radio if (item.checked) return item.group.items.forEach { (it as Item.Radio).checked = false } item.checked = true preferences.libraryAsList().set(if (item == list) true else false) item.group.items.forEach { adapter.notifyItemChanged(it) } } } }
apache-2.0
676a1e6387e6c130787418bc38855b48
34.341014
100
0.618341
4.884758
false
false
false
false
vanniktech/Emoji
emoji/src/androidMain/kotlin/com/vanniktech/emoji/EmojiLayoutFactory.kt
1
1708
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vanniktech.emoji import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater.Factory2 import android.view.View /** Layout Factory that substitutes certain Views to add automatic Emoji support. */ open class EmojiLayoutFactory( private val delegate: Factory2? = null, ) : Factory2 { override fun onCreateView(parent: View?, name: String, context: Context, attrs: AttributeSet) = when { name == "TextView" -> EmojiTextView(context, attrs) name == "EditText" -> EmojiEditText(context, attrs) name == "Button" -> EmojiButton(context, attrs) name == "Checkbox" -> EmojiCheckbox(context, attrs) name == "AutoCompleteTextView" -> EmojiAutoCompleteTextView(context, attrs) name == "MultiAutoCompleteTextView" -> EmojiMultiAutoCompleteTextView(context, attrs) delegate != null -> delegate.onCreateView(parent, name, context, attrs) else -> null } override fun onCreateView(name: String, context: Context, attrs: AttributeSet) = onCreateView(null, name, context, attrs) }
apache-2.0
2ae7e11ba02e694d9aa09d2040d6291c
40.609756
104
0.737984
4.308081
false
false
false
false
jitsi/jitsi-videobridge
jvb/src/test/kotlin/org/jitsi/videobridge/cc/allocation/BitrateControllerTest.kt
1
61367
/* * Copyright @ 2018 - present 8x8, Inc. * Copyright @ 2021 - Vowel, 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.videobridge.cc.allocation import io.kotest.core.spec.IsolationMode import io.kotest.core.spec.Spec import io.kotest.core.spec.style.ShouldSpec import io.kotest.matchers.collections.shouldContainInOrder import io.kotest.matchers.longs.shouldBeWithinPercentageOf import io.kotest.matchers.shouldBe import io.mockk.CapturingSlot import io.mockk.every import io.mockk.mockk import org.jitsi.config.setNewConfig import org.jitsi.nlj.MediaSourceDesc import org.jitsi.nlj.PacketInfo import org.jitsi.nlj.RtpEncodingDesc import org.jitsi.nlj.RtpLayerDesc import org.jitsi.nlj.VideoType import org.jitsi.nlj.format.RtxPayloadType import org.jitsi.nlj.rtp.VideoRtpPacket import org.jitsi.nlj.util.Bandwidth import org.jitsi.nlj.util.bps import org.jitsi.nlj.util.kbps import org.jitsi.nlj.util.mbps import org.jitsi.utils.logging.DiagnosticContext import org.jitsi.utils.logging2.createLogger import org.jitsi.utils.ms import org.jitsi.utils.secs import org.jitsi.utils.time.FakeClock import org.jitsi.videobridge.cc.config.BitrateControllerConfig import org.jitsi.videobridge.message.ReceiverVideoConstraintsMessage import org.jitsi.videobridge.util.TaskPools import java.time.Instant import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit import java.util.function.Supplier class BitrateControllerTest : ShouldSpec() { override fun isolationMode() = IsolationMode.InstancePerLeaf private val logger = createLogger() private val clock = FakeClock() private val bc = BitrateControllerWrapper(createEndpoints("A", "B", "C", "D"), clock = clock) private val A = bc.endpoints.find { it.id == "A" }!! as TestEndpoint private val B = bc.endpoints.find { it.id == "B" }!! as TestEndpoint private val C = bc.endpoints.find { it.id == "C" }!! as TestEndpoint private val D = bc.endpoints.find { it.id == "D" }!! as TestEndpoint override suspend fun beforeSpec(spec: Spec) = super.beforeSpec(spec).also { // We disable the threshold, causing [BandwidthAllocator] to make a new decision every time BWE changes. This is // because these tests are designed to test the decisions themselves and not necessarily when they are made. setNewConfig( """ videobridge.cc { bwe-change-threshold = 0 // Effectively disable periodic updates. max-time-between-calculations = 1 hour } """.trimIndent(), true ) } override suspend fun afterSpec(spec: Spec) = super.afterSpec(spec).also { bc.bc.expire() setNewConfig("", true) } init { context("Expire") { val captureDelay = CapturingSlot<Long>() val captureDelayTimeunit = CapturingSlot<TimeUnit>() val captureCancel = CapturingSlot<Boolean>() val executor: ScheduledExecutorService = mockk { every { schedule(any(), capture(captureDelay), capture(captureDelayTimeunit)) } returns mockk { every { cancel(capture(captureCancel)) } returns true } } TaskPools.SCHEDULED_POOL = executor val bc = BitrateControllerWrapper(createEndpoints(), clock = clock) val delayMs = TimeUnit.MILLISECONDS.convert(captureDelay.captured, captureDelayTimeunit.captured) delayMs.shouldBeWithinPercentageOf( BitrateControllerConfig.config.maxTimeBetweenCalculations().toMillis(), 10.0 ) captureCancel.isCaptured shouldBe false bc.bc.expire() captureCancel.isCaptured shouldBe true TaskPools.resetScheduledPool() } context("Prioritization") { context("Without selection") { val sources = createSources("s6", "s5", "s4", "s3", "s2", "s1") val ordered = prioritize(sources) ordered.map { it.sourceName } shouldBe listOf("s6", "s5", "s4", "s3", "s2", "s1") } context("With one selected") { val sources = createSources("s6", "s5", "s4", "s3", "s2", "s1") val ordered = prioritize(sources, listOf("s2")) ordered.map { it.sourceName } shouldBe listOf("s2", "s6", "s5", "s4", "s3", "s1") } context("With multiple selected") { val sources = createSources("s6", "s5", "s4", "s3", "s2", "s1") val ordered = prioritize(sources, listOf("s2", "s1", "s5")) ordered.map { it.sourceName } shouldBe listOf("s2", "s1", "s5", "s6", "s4", "s3") } } context("Allocation") { context("Stage view") { context("When LastN is not set") { context("and the dominant speaker is on stage") { listOf(true, false).forEach { screensharing -> context("With ${if (screensharing) "screensharing" else "camera"}") { if (screensharing) { A.mediaSources[0].videoType = VideoType.DESKTOP } bc.setEndpointOrdering(A, B, C, D) bc.setStageView("A-v0") bc.bc.allocationSettings.lastN shouldBe -1 bc.bc.allocationSettings.selectedSources shouldBe emptyList() bc.bc.allocationSettings.onStageSources shouldBe listOf("A-v0") runBweLoop() verifyStageView(screensharing) } } } context("and a non-dominant speaker is on stage") { bc.setEndpointOrdering(B, A, C, D) bc.setStageView("A-v0") bc.bc.allocationSettings.lastN shouldBe -1 bc.bc.allocationSettings.selectedSources shouldBe emptyList() bc.bc.allocationSettings.onStageSources shouldBe listOf("A-v0") runBweLoop() verifyStageView() } } context("When LastN=0") { // LastN=0 is used when the client goes in "audio-only" mode. bc.setEndpointOrdering(A, B, C, D) bc.setStageView("A", lastN = 0) bc.bc.allocationSettings.lastN shouldBe 0 bc.bc.allocationSettings.selectedSources shouldBe emptyList() bc.bc.allocationSettings.onStageSources shouldBe listOf("A") runBweLoop() verifyLastN0() } context("When LastN=1") { // LastN=1 is used when the client goes in "audio-only" mode, but someone starts a screenshare. context("and the dominant speaker is on-stage") { bc.setEndpointOrdering(A, B, C, D) bc.setStageView("A-v0", lastN = 1) bc.bc.allocationSettings.lastN shouldBe 1 bc.bc.allocationSettings.selectedSources shouldBe emptyList() bc.bc.allocationSettings.onStageSources shouldBe listOf("A-v0") runBweLoop() verifyStageViewLastN1() } context("and a non-dominant speaker is on stage") { bc.setEndpointOrdering(B, A, C, D) bc.setStageView("A-v0", lastN = 1) bc.bc.allocationSettings.lastN shouldBe 1 bc.bc.allocationSettings.selectedSources shouldBe emptyList() bc.bc.allocationSettings.onStageSources shouldBe listOf("A-v0") runBweLoop() verifyStageViewLastN1() } } } context("Tile view") { bc.setEndpointOrdering(A, B, C, D) bc.setTileView("A-v0", "B-v0", "C-v0", "D-v0") bc.bc.allocationSettings.lastN shouldBe -1 bc.bc.allocationSettings.selectedSources shouldBe listOf("A-v0", "B-v0", "C-v0", "D-v0") context("When LastN is not set") { runBweLoop() verifyTileView() } context("When LastN=0") { bc.setTileView("A-v0", "B-v0", "C-v0", "D-v0", lastN = 0) runBweLoop() verifyLastN0() } context("When LastN=1") { bc.setTileView("A-v0", "B-v0", "C-v0", "D-v0", lastN = 1) runBweLoop() verifyTileViewLastN1() } } context("Tile view 360p") { bc.setEndpointOrdering(A, B, C, D) bc.setTileView("A-v0", "B-v0", "C-v0", "D-v0", maxFrameHeight = 360) bc.bc.allocationSettings.lastN shouldBe -1 // The legacy API (currently used by jitsi-meet) uses "selected count > 0" to infer TileView, // and in tile view we do not use selected endpoints. bc.bc.allocationSettings.selectedSources shouldBe listOf("A-v0", "B-v0", "C-v0", "D-v0") context("When LastN is not set") { runBweLoop() verifyTileView360p() } context("When LastN=0") { bc.setTileView("A-v0", "B-v0", "C-v0", "D-v0", lastN = 0, maxFrameHeight = 360) runBweLoop() verifyLastN0() } context("When LastN=1") { bc.setTileView("A-v0", "B-v0", "C-v0", "D-v0", lastN = 1, maxFrameHeight = 360) runBweLoop() verifyTileViewLastN1(360) } } context("Selected sources should override the dominant speaker (with new signaling)") { // A is dominant speaker, A and B are selected. With LastN=2 we should always forward the selected // sources regardless of who is speaking. // The exact flow of this scenario was taken from a (non-jitsi-meet) client. bc.setEndpointOrdering(A, B, C, D) bc.bc.setBandwidthAllocationSettings( ReceiverVideoConstraintsMessage( selectedSources = listOf("A-v0", "B-v0"), constraints = mapOf("A-v0" to VideoConstraints(720), "B-v0" to VideoConstraints(720)) ) ) bc.effectiveConstraintsHistory.last().event shouldBe mapOf( "A-v0" to VideoConstraints(720), "B-v0" to VideoConstraints(720), "C-v0" to VideoConstraints(180), "D-v0" to VideoConstraints(180) ) bc.bc.setBandwidthAllocationSettings(ReceiverVideoConstraintsMessage(lastN = 2)) bc.effectiveConstraintsHistory.last().event shouldBe mapOf( "A-v0" to VideoConstraints(720), "B-v0" to VideoConstraints(720), "C-v0" to VideoConstraints(0), "D-v0" to VideoConstraints(0) ) bc.bc.allocationSettings.lastN shouldBe 2 bc.bc.allocationSettings.selectedSources shouldBe listOf("A-v0", "B-v0") clock.elapse(20.secs) bc.bwe = 10.mbps bc.forwardedSourcesHistory.last().event.shouldBe(setOf("A-v0", "B-v0")) clock.elapse(2.secs) // B becomes dominant speaker. bc.setEndpointOrdering(B, A, C, D) bc.forwardedSourcesHistory.last().event.shouldBe(setOf("A-v0", "B-v0")) clock.elapse(2.secs) bc.bc.setBandwidthAllocationSettings( ReceiverVideoConstraintsMessage( constraints = mapOf("A-v0" to VideoConstraints(360), "B-v0" to VideoConstraints(360)) ) ) bc.effectiveConstraintsHistory.last().event shouldBe mapOf( "A-v0" to VideoConstraints(360), "B-v0" to VideoConstraints(360), "C-v0" to VideoConstraints(0), "D-v0" to VideoConstraints(0) ) clock.elapse(2.secs) // This should change nothing, the selection didn't change. bc.bc.setBandwidthAllocationSettings( ReceiverVideoConstraintsMessage(selectedSources = listOf("A-v0", "B-v0")) ) bc.forwardedSourcesHistory.last().event.shouldBe(setOf("A-v0", "B-v0")) clock.elapse(2.secs) bc.bc.setBandwidthAllocationSettings(ReceiverVideoConstraintsMessage(lastN = -1)) bc.effectiveConstraintsHistory.last().event shouldBe mapOf( "A-v0" to VideoConstraints(360), "B-v0" to VideoConstraints(360), "C-v0" to VideoConstraints(180), "D-v0" to VideoConstraints(180) ) bc.forwardedSourcesHistory.last().event.shouldBe(setOf("A-v0", "B-v0", "C-v0", "D-v0")) bc.bc.setBandwidthAllocationSettings(ReceiverVideoConstraintsMessage(lastN = 2)) bc.effectiveConstraintsHistory.last().event shouldBe mapOf( "A-v0" to VideoConstraints(360), "B-v0" to VideoConstraints(360), "C-v0" to VideoConstraints(0), "D-v0" to VideoConstraints(0) ) clock.elapse(2.secs) bc.forwardedSourcesHistory.last().event.shouldBe(setOf("A-v0", "B-v0")) clock.elapse(2.secs) // D is now dominant speaker, but it should not override the selected endpoints. bc.setEndpointOrdering(D, B, A, C) bc.forwardedSourcesHistory.last().event.shouldBe(setOf("A-v0", "B-v0")) bc.bwe = 10.mbps bc.forwardedSourcesHistory.last().event.shouldBe(setOf("A-v0", "B-v0")) clock.elapse(2.secs) bc.bwe = 0.mbps clock.elapse(2.secs) bc.bwe = 10.mbps bc.forwardedSourcesHistory.last().event.shouldBe(setOf("A-v0", "B-v0")) clock.elapse(2.secs) // C is now dominant speaker, but it should not override the selected endpoints. bc.setEndpointOrdering(C, D, A, B) bc.forwardedSourcesHistory.last().event.shouldBe(setOf("A-v0", "B-v0")) } } } private fun runBweLoop() { for (bwe in 0..5_000_000 step 10_000) { bc.bwe = bwe.bps clock.elapse(100.ms) } logger.info("Forwarded sources history: ${bc.forwardedSourcesHistory}") logger.info("Effective constraints history: ${bc.effectiveConstraintsHistory}") logger.info("Allocation history: ${bc.allocationHistory}") } private fun verifyStageViewScreensharing() { // At this stage the purpose of this is just to document current behavior. // TODO: The results with bwe==-1 are wrong. bc.forwardedSourcesHistory.map { it.event }.shouldContainInOrder( setOf("A-v0"), setOf("A-v0", "B-v0"), setOf("A-v0", "B-v0", "C-v0"), setOf("A-v0", "B-v0", "C-v0", "D-v0") ) bc.effectiveConstraintsHistory.last().event shouldBe mapOf( "A-v0" to VideoConstraints(720), "B-v0" to VideoConstraints(180), "C-v0" to VideoConstraints(180), "D-v0" to VideoConstraints(180) ) // At this stage the purpose of this is just to document current behavior. // TODO: the allocations for bwe=-1 are wrong. bc.allocationHistory.removeIf { it.bwe < 0.bps } bc.allocationHistory.shouldMatchInOrder( // We expect to be oversending when screensharing is used. Event( 0.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = sd30), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ), oversending = true ) ), Event( 160.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd7_5), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ), oversending = true ) ), Event( 660.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd7_5), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ), oversending = false ) ), Event( 1320.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd15), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 2000.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 2050.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = ld7_5), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 2100.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = ld7_5), SingleAllocation(C, targetLayer = ld7_5), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 2150.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = ld7_5), SingleAllocation(C, targetLayer = ld7_5), SingleAllocation(D, targetLayer = ld7_5) ) ) ), Event( 2200.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = ld15), SingleAllocation(C, targetLayer = ld7_5), SingleAllocation(D, targetLayer = ld7_5) ) ) ), Event( 2250.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = ld15), SingleAllocation(C, targetLayer = ld15), SingleAllocation(D, targetLayer = ld7_5) ) ) ), Event( 2300.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = ld15), SingleAllocation(C, targetLayer = ld15), SingleAllocation(D, targetLayer = ld15) ) ) ), Event( 2350.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = ld30), SingleAllocation(C, targetLayer = ld15), SingleAllocation(D, targetLayer = ld15) ) ) ), Event( 2400.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = ld30), SingleAllocation(C, targetLayer = ld30), SingleAllocation(D, targetLayer = ld15) ) ) ), Event( 2460.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = ld30), SingleAllocation(C, targetLayer = ld30), SingleAllocation(D, targetLayer = ld30) ) ) ) ) } private fun verifyStageView(screensharing: Boolean = false) { when (screensharing) { true -> verifyStageViewScreensharing() false -> verifyStageViewCamera() } } private fun verifyStageViewCamera() { // At this stage the purpose of this is just to document current behavior. // TODO: The results with bwe==-1 are wrong. bc.forwardedSourcesHistory.removeIf { it.bwe < 0.bps } bc.forwardedSourcesHistory.map { it.event }.shouldContainInOrder( setOf("A-v0"), setOf("A-v0", "B-v0"), setOf("A-v0", "B-v0", "C-v0"), setOf("A-v0", "B-v0", "C-v0", "D-v0") ) // TODO add forwarded sources history here bc.effectiveConstraintsHistory.last().event shouldBe mapOf( "A-v0" to VideoConstraints(720), "B-v0" to VideoConstraints(180), "C-v0" to VideoConstraints(180), "D-v0" to VideoConstraints(180) ) // At this stage the purpose of this is just to document current behavior. // TODO: the allocations for bwe=-1 are wrong. bc.allocationHistory.removeIf { it.bwe < 0.bps } bc.allocationHistory.shouldMatchInOrder( Event( 50.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld7_5), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ), oversending = false ) ), Event( 100.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld15), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 150.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld30), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 500.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = sd30), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 550.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = sd30), SingleAllocation(B, targetLayer = ld7_5), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 600.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = sd30), SingleAllocation(B, targetLayer = ld7_5), SingleAllocation(C, targetLayer = ld7_5), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 650.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = sd30), SingleAllocation(B, targetLayer = ld7_5), SingleAllocation(C, targetLayer = ld7_5), SingleAllocation(D, targetLayer = ld7_5) ) ) ), Event( 700.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = sd30), SingleAllocation(B, targetLayer = ld15), SingleAllocation(C, targetLayer = ld7_5), SingleAllocation(D, targetLayer = ld7_5) ) ) ), Event( 750.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = sd30), SingleAllocation(B, targetLayer = ld15), SingleAllocation(C, targetLayer = ld15), SingleAllocation(D, targetLayer = ld7_5) ) ) ), Event( 800.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = sd30), SingleAllocation(B, targetLayer = ld15), SingleAllocation(C, targetLayer = ld15), SingleAllocation(D, targetLayer = ld15) ) ) ), Event( 850.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = sd30), SingleAllocation(B, targetLayer = ld30), SingleAllocation(C, targetLayer = ld15), SingleAllocation(D, targetLayer = ld15) ) ) ), Event( 900.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = sd30), SingleAllocation(B, targetLayer = ld30), SingleAllocation(C, targetLayer = ld30), SingleAllocation(D, targetLayer = ld15) ) ) ), Event( 960.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = sd30), SingleAllocation(B, targetLayer = ld30), SingleAllocation(C, targetLayer = ld30), SingleAllocation(D, targetLayer = ld30) ) ) ), Event( 2150.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = ld7_5), SingleAllocation(C, targetLayer = ld7_5), SingleAllocation(D, targetLayer = ld7_5) ) ) ), Event( 2200.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = ld15), SingleAllocation(C, targetLayer = ld7_5), SingleAllocation(D, targetLayer = ld7_5) ) ) ), Event( 2250.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = ld15), SingleAllocation(C, targetLayer = ld15), SingleAllocation(D, targetLayer = ld7_5) ) ) ), Event( 2300.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = ld15), SingleAllocation(C, targetLayer = ld15), SingleAllocation(D, targetLayer = ld15) ) ) ), Event( 2350.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = ld30), SingleAllocation(C, targetLayer = ld15), SingleAllocation(D, targetLayer = ld15) ) ) ), Event( 2400.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = ld30), SingleAllocation(C, targetLayer = ld30), SingleAllocation(D, targetLayer = ld15) ) ) ), Event( 2460.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = ld30), SingleAllocation(C, targetLayer = ld30), SingleAllocation(D, targetLayer = ld30) ) ) ) ) } private fun verifyLastN0() { // No video forwarded even with high BWE. bc.forwardedSourcesHistory.size shouldBe 0 bc.effectiveConstraintsHistory.last().event shouldBe mapOf( "A-v0" to VideoConstraints(0), "B-v0" to VideoConstraints(0), "C-v0" to VideoConstraints(0), "D-v0" to VideoConstraints(0) ) // TODO: The history contains 3 identical elements, which is probably a bug. bc.allocationHistory.last().event.shouldMatch( BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = noVideo), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ) } private fun verifyStageViewLastN1() { // At this stage the purpose of this is just to document current behavior. // TODO: The results with bwe==-1 are wrong. bc.forwardedSourcesHistory.removeIf { it.bwe < 0.bps } bc.forwardedSourcesHistory.map { it.event }.shouldContainInOrder( setOf("A-v0") ) bc.effectiveConstraintsHistory.last().event shouldBe mapOf( "A-v0" to VideoConstraints(720), "B-v0" to VideoConstraints(0), "C-v0" to VideoConstraints(0), "D-v0" to VideoConstraints(0) ) // At this stage the purpose of this is just to document current behavior. // TODO: the allocations for bwe=-1 are wrong. bc.allocationHistory.removeIf { it.bwe < 0.bps } bc.allocationHistory.shouldMatchInOrder( Event( 50.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld7_5), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 100.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld15), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 150.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld30), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 500.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = sd30), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 2010.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = hd30), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ) ) } private fun verifyTileView() { // At this stage the purpose of this is just to document current behavior. // TODO: The results with bwe==-1 are wrong. bc.forwardedSourcesHistory.removeIf { it.bwe < 0.bps } bc.forwardedSourcesHistory.map { it.event }.shouldContainInOrder( setOf("A-v0"), setOf("A-v0", "B-v0"), setOf("A-v0", "B-v0", "C-v0"), setOf("A-v0", "B-v0", "C-v0", "D-v0") ) bc.allocationHistory.shouldMatchInOrder( Event( (-1).bps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = noVideo), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 50.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld7_5), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 100.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld7_5), SingleAllocation(B, targetLayer = ld7_5), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 150.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld7_5), SingleAllocation(B, targetLayer = ld7_5), SingleAllocation(C, targetLayer = ld7_5), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 200.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld7_5), SingleAllocation(B, targetLayer = ld7_5), SingleAllocation(C, targetLayer = ld7_5), SingleAllocation(D, targetLayer = ld7_5) ) ) ), Event( 250.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld15), SingleAllocation(B, targetLayer = ld7_5), SingleAllocation(C, targetLayer = ld7_5), SingleAllocation(D, targetLayer = ld7_5) ) ) ), Event( 300.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld15), SingleAllocation(B, targetLayer = ld15), SingleAllocation(C, targetLayer = ld7_5), SingleAllocation(D, targetLayer = ld7_5) ) ) ), Event( 350.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld15), SingleAllocation(B, targetLayer = ld15), SingleAllocation(C, targetLayer = ld15), SingleAllocation(D, targetLayer = ld7_5) ) ) ), Event( 400.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld15), SingleAllocation(B, targetLayer = ld15), SingleAllocation(C, targetLayer = ld15), SingleAllocation(D, targetLayer = ld15) ) ) ), Event( 450.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld30), SingleAllocation(B, targetLayer = ld15), SingleAllocation(C, targetLayer = ld15), SingleAllocation(D, targetLayer = ld15) ) ) ), Event( 500.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld30), SingleAllocation(B, targetLayer = ld30), SingleAllocation(C, targetLayer = ld15), SingleAllocation(D, targetLayer = ld15) ) ) ), Event( 550.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld30), SingleAllocation(B, targetLayer = ld30), SingleAllocation(C, targetLayer = ld30), SingleAllocation(D, targetLayer = ld15) ) ) ), Event( 610.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld30), SingleAllocation(B, targetLayer = ld30), SingleAllocation(C, targetLayer = ld30), SingleAllocation(D, targetLayer = ld30) ) ) ) ) } private fun verifyTileView360p() { // At this stage the purpose of this is just to document current behavior. // TODO: The results with bwe==-1 are wrong. bc.forwardedSourcesHistory.removeIf { it.bwe < 0.bps } bc.forwardedSourcesHistory.map { it.event }.shouldContainInOrder( setOf("A-v0"), setOf("A-v0", "B-v0"), setOf("A-v0", "B-v0", "C-v0"), setOf("A-v0", "B-v0", "C-v0", "D-v0") ) bc.allocationHistory.shouldMatchInOrder( Event( (-1).bps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = noVideo), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 50.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld7_5), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ), oversending = false ) ), Event( 100.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld7_5), SingleAllocation(B, targetLayer = ld7_5), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 150.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld7_5), SingleAllocation(B, targetLayer = ld7_5), SingleAllocation(C, targetLayer = ld7_5), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 200.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld7_5), SingleAllocation(B, targetLayer = ld7_5), SingleAllocation(C, targetLayer = ld7_5), SingleAllocation(D, targetLayer = ld7_5) ) ) ), Event( 250.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld15), SingleAllocation(B, targetLayer = ld7_5), SingleAllocation(C, targetLayer = ld7_5), SingleAllocation(D, targetLayer = ld7_5) ) ) ), Event( 300.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld15), SingleAllocation(B, targetLayer = ld15), SingleAllocation(C, targetLayer = ld7_5), SingleAllocation(D, targetLayer = ld7_5) ) ) ), Event( 350.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld15), SingleAllocation(B, targetLayer = ld15), SingleAllocation(C, targetLayer = ld15), SingleAllocation(D, targetLayer = ld7_5) ) ) ), Event( 400.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld15), SingleAllocation(B, targetLayer = ld15), SingleAllocation(C, targetLayer = ld15), SingleAllocation(D, targetLayer = ld15) ) ) ), Event( 450.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld30), SingleAllocation(B, targetLayer = ld15), SingleAllocation(C, targetLayer = ld15), SingleAllocation(D, targetLayer = ld15) ) ) ), Event( 500.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld30), SingleAllocation(B, targetLayer = ld30), SingleAllocation(C, targetLayer = ld15), SingleAllocation(D, targetLayer = ld15) ) ) ), Event( 550.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld30), SingleAllocation(B, targetLayer = ld30), SingleAllocation(C, targetLayer = ld30), SingleAllocation(D, targetLayer = ld15) ) ) ), Event( 610.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld30), SingleAllocation(B, targetLayer = ld30), SingleAllocation(C, targetLayer = ld30), SingleAllocation(D, targetLayer = ld30) ) ) ), Event( 960.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = sd30), SingleAllocation(B, targetLayer = ld30), SingleAllocation(C, targetLayer = ld30), SingleAllocation(D, targetLayer = ld30) ) ) ), Event( 1310.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = sd30), SingleAllocation(B, targetLayer = sd30), SingleAllocation(C, targetLayer = ld30), SingleAllocation(D, targetLayer = ld30) ) ) ), Event( 1660.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = sd30), SingleAllocation(B, targetLayer = sd30), SingleAllocation(C, targetLayer = sd30), SingleAllocation(D, targetLayer = ld30) ) ) ), Event( 2010.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = sd30), SingleAllocation(B, targetLayer = sd30), SingleAllocation(C, targetLayer = sd30), SingleAllocation(D, targetLayer = sd30) ) ) ) ) } private fun verifyTileViewLastN1(maxFrameHeight: Int = 180) { // At this stage the purpose of this is just to document current behavior. // TODO: The results with bwe==-1 are wrong. bc.forwardedSourcesHistory.removeIf { it.bwe < 0.bps } bc.forwardedSourcesHistory.map { it.event }.shouldContainInOrder( setOf("A-v0") ) bc.effectiveConstraintsHistory.last().event shouldBe mapOf( "A-v0" to VideoConstraints(maxFrameHeight), "B-v0" to VideoConstraints(0), "C-v0" to VideoConstraints(0), "D-v0" to VideoConstraints(0) ) val expectedAllocationHistory = mutableListOf( // TODO: do we want to oversend in tile view? Event( (-1).bps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = noVideo), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ), oversending = true ) ), Event( 50.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld7_5), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 100.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld15), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ), Event( 160.kbps, // TODO: why 160 instead of 150? weird. BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = ld30), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ) ) if (maxFrameHeight > 180) { expectedAllocationHistory.addAll( listOf( Event( 510.kbps, BandwidthAllocation( setOf( SingleAllocation(A, targetLayer = sd30), SingleAllocation(B, targetLayer = noVideo), SingleAllocation(C, targetLayer = noVideo), SingleAllocation(D, targetLayer = noVideo) ) ) ) ) ) } bc.allocationHistory.shouldMatchInOrder(*expectedAllocationHistory.toTypedArray()) } } class BitrateControllerWrapper(initialEndpoints: List<MediaSourceContainer>, val clock: FakeClock = FakeClock()) { var endpoints: List<MediaSourceContainer> = initialEndpoints val logger = createLogger() var bwe = (-1).bps set(value) { logger.debug("Setting bwe=$value") field = value bc.bandwidthChanged(value.bps.toLong()) } // Save the output. val effectiveConstraintsHistory: History<Map<String, VideoConstraints>> = mutableListOf() val forwardedSourcesHistory: History<Set<String>> = mutableListOf() val allocationHistory: History<BandwidthAllocation> = mutableListOf() val bc = BitrateController( object : BitrateController.EventHandler { override fun forwardedEndpointsChanged(forwardedEndpoints: Set<String>) { } override fun forwardedSourcesChanged(forwardedSources: Set<String>) { Event(bwe, forwardedSources, clock.instant()).apply { logger.info("Forwarded sources changed: $this") forwardedSourcesHistory.add(this) } } override fun effectiveVideoConstraintsChanged( oldEffectiveConstraints: EffectiveConstraintsMap, newEffectiveConstraints: EffectiveConstraintsMap ) { Event(bwe, newEffectiveConstraints.mapKeys { it.key.sourceName }, clock.instant()).apply { logger.info("Effective constraints changed: $this") effectiveConstraintsHistory.add(this) } } override fun keyframeNeeded(endpointId: String?, ssrc: Long) {} override fun allocationChanged(allocation: BandwidthAllocation) { Event( bwe, allocation, clock.instant() ).apply { logger.info("Allocation changed: $this") allocationHistory.add(this) } } }, Supplier { endpoints }, DiagnosticContext(), logger, true, // TODO merge BitrateControllerNewTest with old and use this flag clock ) fun setEndpointOrdering(vararg endpoints: TestEndpoint) { logger.info("Set endpoints ${endpoints.map{ it.id }.joinToString(",")}") this.endpoints = endpoints.toList() bc.endpointOrderingChanged() } fun setStageView(onStageSource: String, lastN: Int? = null) { bc.setBandwidthAllocationSettings( ReceiverVideoConstraintsMessage( lastN = lastN, onStageSources = listOf(onStageSource), constraints = mapOf(onStageSource to VideoConstraints(720)) ) ) } fun setTileView( vararg selectedSources: String, maxFrameHeight: Int = 180, lastN: Int? = null ) { bc.setBandwidthAllocationSettings( ReceiverVideoConstraintsMessage( lastN = lastN, selectedSources = listOf(*selectedSources), constraints = selectedSources.map { it to VideoConstraints(maxFrameHeight) }.toMap() ) ) } init { // The BC only starts working 10 seconds after it first received media, so fake that. bc.transformRtp(PacketInfo(VideoRtpPacket(ByteArray(100), 0, 100))) clock.elapse(15.secs) // Adaptivity is disabled when RTX support is not signalled. bc.addPayloadType(RtxPayloadType(123, mapOf("apt" to "124"))) } } class TestEndpoint( override val id: String, override val mediaSources: Array<MediaSourceDesc> = emptyArray() ) : MediaSourceContainer fun createEndpoints(vararg ids: String): MutableList<TestEndpoint> { return MutableList(ids.size) { i -> TestEndpoint( ids[i], arrayOf( createSourceDesc( 3 * i + 1, 3 * i + 2, 3 * i + 3, ids[i] + "-v0", ids[i] ) ) ) } } fun createSources(vararg ids: String): MutableList<MediaSourceDesc> { return MutableList(ids.size) { i -> createSourceDesc( 3 * i + 1, 3 * i + 2, 3 * i + 3, ids[i], ids[i] ) } } fun createSourceDesc( ssrc1: Int, ssrc2: Int, ssrc3: Int, sourceName: String, owner: String ): MediaSourceDesc = MediaSourceDesc( arrayOf( RtpEncodingDesc(ssrc1.toLong(), arrayOf(ld7_5, ld15, ld30)), RtpEncodingDesc(ssrc2.toLong(), arrayOf(sd7_5, sd15, sd30)), RtpEncodingDesc(ssrc3.toLong(), arrayOf(hd7_5, hd15, hd30)) ), sourceName = sourceName, owner = owner ) val bitrateLd = 150.kbps val bitrateSd = 500.kbps val bitrateHd = 2000.kbps val ld7_5 get() = MockRtpLayerDesc(tid = 0, eid = 0, height = 180, frameRate = 7.5, bitrate = bitrateLd * 0.33) val ld15 get() = MockRtpLayerDesc(tid = 1, eid = 0, height = 180, frameRate = 15.0, bitrate = bitrateLd * 0.66) val ld30 get() = MockRtpLayerDesc(tid = 2, eid = 0, height = 180, frameRate = 30.0, bitrate = bitrateLd) val sd7_5 get() = MockRtpLayerDesc(tid = 0, eid = 1, height = 360, frameRate = 7.5, bitrate = bitrateSd * 0.33) val sd15 get() = MockRtpLayerDesc(tid = 1, eid = 1, height = 360, frameRate = 15.0, bitrate = bitrateSd * 0.66) val sd30 get() = MockRtpLayerDesc(tid = 2, eid = 1, height = 360, frameRate = 30.0, bitrate = bitrateSd) val hd7_5 get() = MockRtpLayerDesc(tid = 0, eid = 2, height = 720, frameRate = 7.5, bitrate = bitrateHd * 0.33) val hd15 get() = MockRtpLayerDesc(tid = 1, eid = 2, height = 720, frameRate = 15.0, bitrate = bitrateHd * 0.66) val hd30 get() = MockRtpLayerDesc(tid = 2, eid = 2, height = 720, frameRate = 30.0, bitrate = bitrateHd) val noVideo: RtpLayerDesc? = null /** * An [RtpLayerDesc] whose bitrate can be set externally. We inherit directly from [RtpLayerDesc], because mocking with * mockk absolutely kills the performance. */ class MockRtpLayerDesc( tid: Int, eid: Int, height: Int, frameRate: Double, /** * Note: this mock impl does not model the dependency layers, so the cumulative bitrate should be provided. */ var bitrate: Bandwidth, sid: Int = -1 ) : RtpLayerDesc(eid, tid, sid, height, frameRate) { override fun getBitrate(nowMs: Long): Bandwidth = bitrate override fun hasZeroBitrate(nowMs: Long): Boolean = bitrate == 0.bps } typealias History<T> = MutableList<Event<T>> data class Event<T>( val bwe: Bandwidth, val event: T, val time: Instant = Instant.MIN ) { override fun toString(): String = "\n[time=${time.toEpochMilli()} bwe=$bwe] $event" override fun equals(other: Any?): Boolean { if (other !is Event<*>) return false // Ignore this.time return bwe == other.bwe && event == other.event } }
apache-2.0
f8c3f69ca97db38992735665d9f9192c
38.363053
120
0.474815
5.60378
false
false
false
false
mplatvoet/kovenant
projects/ui/src/main/kotlin/callbacks-api.kt
1
4592
/* * Copyright (c) 2015 Mark Platvoet<[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * THE SOFTWARE. */ @file:JvmName("KovenantUiApi") package nl.komponents.kovenant.ui import nl.komponents.kovenant.* @JvmOverloads fun <V> promiseOnUi(uiContext: UiContext = KovenantUi.uiContext, context: Context = Kovenant.context, alwaysSchedule: Boolean = false, body: () -> V): Promise<V, Exception> { if (directExecutionAllowed(alwaysSchedule, uiContext.dispatcher)) { return try { Promise.ofSuccess(context = context, value = body()) } catch(e: Exception) { Promise.ofFail(context = context, value = e) } } else { val deferred = deferred<V, Exception>(context) uiContext.dispatcher.offer { try { val result = body() deferred.resolve(result) } catch(e: Exception) { deferred.reject(e) } } return deferred.promise } } public infix fun <V, E> Promise<V, E>.successUi(body: (value: V) -> Unit): Promise<V, E> = successUi(alwaysSchedule = false, body = body) @JvmOverloads public fun <V, E> Promise<V, E>.successUi(uiContext: UiContext = KovenantUi.uiContext, alwaysSchedule: Boolean, body: (value: V) -> Unit): Promise<V, E> { val dispatcherContext = uiContext.dispatcherContextFor(context) if (isDone() && directExecutionAllowed(alwaysSchedule, dispatcherContext.dispatcher)) { if (isSuccess()) { try { body(get()) } catch(e: Exception) { dispatcherContext.errorHandler(e) } } } else { success(dispatcherContext, body) } return this } public infix fun <V, E> Promise<V, E>.failUi(body: (error: E) -> Unit): Promise<V, E> = failUi(alwaysSchedule = false, body = body) @JvmOverloads public fun <V, E> Promise<V, E>.failUi(uiContext: UiContext = KovenantUi.uiContext, alwaysSchedule: Boolean, body: (error: E) -> Unit): Promise<V, E> { val dispatcherContext = uiContext.dispatcherContextFor(context) if (isDone() && directExecutionAllowed(alwaysSchedule, dispatcherContext.dispatcher)) { if (isFailure()) { try { body(getError()) } catch(e: Exception) { dispatcherContext.errorHandler(e) } } } else { fail(dispatcherContext, body) } return this } public infix fun <V, E> Promise<V, E>.alwaysUi(body: () -> Unit): Promise<V, E> = alwaysUi(alwaysSchedule = false, body = body) @JvmOverloads public fun <V, E> Promise<V, E>.alwaysUi(uiContext: UiContext = KovenantUi.uiContext, alwaysSchedule: Boolean, body: () -> Unit): Promise<V, E> { val dispatcherContext = uiContext.dispatcherContextFor(context) if (isDone() && directExecutionAllowed(alwaysSchedule, dispatcherContext.dispatcher)) { try { body() } catch(e: Exception) { dispatcherContext.errorHandler(e) } } else { always(dispatcherContext, body) } return this } private fun directExecutionAllowed(alwaysSchedule: Boolean, dispatcher: Dispatcher): Boolean { return !alwaysSchedule && dispatcher is ProcessAwareDispatcher && dispatcher.ownsCurrentProcess() }
mit
e580d99ab36ec7a2edf8dc5785a7769f
38.25641
137
0.611934
4.633703
false
false
false
false
GyrosWorkshop/WukongAndroid
wukong/src/main/java/com/senorsen/wukong/network/SocketClient.kt
1
5158
package com.senorsen.wukong.network import android.content.Context import android.os.Build import android.os.Handler import android.util.Log import com.google.common.net.HttpHeaders import com.google.gson.Gson import com.senorsen.wukong.BuildConfig import com.senorsen.wukong.network.message.Protocol import com.senorsen.wukong.network.message.WebSocketReceiveProtocol import okhttp3.* import okhttp3.internal.ws.RealWebSocket import java.util.concurrent.TimeUnit class SocketClient( private val wsUrl: String, val cookies: String, userAgent: String, private val channelId: String, private val reconnectCallback: ChannelListener, private val socketReceiver: SocketReceiver ) { private val TAG = javaClass.simpleName var ws: RealWebSocket? = null companion object { val CLOSE_NORMAL_CLOSURE = 1000 val CLOSE_GOING_AWAY = 1001 } var disconnected = true val client = OkHttpClient.Builder() .readTimeout(0, TimeUnit.MILLISECONDS) .pingInterval(5, TimeUnit.SECONDS) .build() private val request = Request.Builder() .header(HttpHeaders.COOKIE, cookies) .header(HttpHeaders.USER_AGENT, userAgent) .url(wsUrl).build() private var listener: ActualWebSocketListener? = null @Synchronized fun connect() { disconnected = false Log.i(TAG, "Connect ws $this: $wsUrl") listener?.channelListener = null ws?.close(CLOSE_GOING_AWAY, "Going away") listener = ActualWebSocketListener(socketReceiver, reconnectCallback) ws = client.newWebSocket(request, listener) as RealWebSocket } fun disconnect() { disconnected = true ws?.close(CLOSE_NORMAL_CLOSURE, "Bye") } interface SocketReceiver { fun onEventMessage(protocol: WebSocketReceiveProtocol) } interface ChannelListener { fun error() fun disconnect(cause: String) } inner class ActualWebSocketListener(private val socketReceiver: SocketReceiver, var channelListener: ChannelListener?) : WebSocketListener() { var alonePingCount = 0 var recentlySendPingCount = 0 private val pingCheck = PingPongCheckerRunnable() private var disconnectCause: String = "-" override fun onOpen(webSocket: WebSocket, response: Response) { Log.i(TAG, "WebSocket open") } override fun onMessage(webSocket: WebSocket, text: String) { Log.d(TAG, "Receiving: " + text) val receiveProtocol = Gson().fromJson(text, WebSocketReceiveProtocol::class.java) when (receiveProtocol.eventName) { Protocol.DISCONNECT -> disconnectCause = receiveProtocol.cause ?: "" else -> socketReceiver.onEventMessage(receiveProtocol) } } override fun onPing(webSocket: WebSocket) { this.alonePingCount++; recentlySendPingCount++ Log.d(TAG, "ping sent") pingCheck.run() } override fun onPong(webSocket: WebSocket, sendPingCount: Int, pongCount: Int) { alonePingCount = 0 Log.d(TAG, "pong received from server, alone $alonePingCount, sent $sendPingCount received $pongCount.") } override fun onClosing(webSocket: WebSocket, code: Int, reason: String) { Log.i(TAG, "Closing: $code $reason") if (code != CLOSE_NORMAL_CLOSURE) { Log.i(TAG, "Reconnect") channelListener?.error() channelListener = null } else if (!disconnected) { Log.i(TAG, "Server sent normal closure, disconnected") disconnected = true channelListener?.disconnect(disconnectCause) channelListener = null } } override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { Log.e(TAG, "failure, reconnect") t.printStackTrace() channelListener?.error() channelListener = null } inner class PingPongCheckerRunnable : Runnable { private val pingTimeoutThreshold = 2 override fun run() { if (disconnected) return var tryReconnect = false if (alonePingCount > pingTimeoutThreshold) { tryReconnect = true Log.i(TAG, "ping-timeout threshold $pingTimeoutThreshold reached, reconnecting") } if (recentlySendPingCount == 0) { tryReconnect = true Log.i(TAG, "recently sent ping count = 0, reconnecting") } if (tryReconnect) { disconnected = true channelListener?.error() channelListener = null } else { Log.d(TAG, "ping-pong check ok") } recentlySendPingCount = 0 } } } }
agpl-3.0
a29b8efe176fc222c7bfff653cdbab41
32.934211
116
0.597712
5.022395
false
false
false
false
JayNewstrom/ScreenSwitcher
sample-screen-color/src/main/java/screenswitchersample/color/ColorPresenter.kt
1
1330
package screenswitchersample.color import android.graphics.Color import android.view.View import android.widget.TextView import android.widget.Toast import androidx.annotation.LayoutRes import screenswitchersample.core.view.ViewPresenter import javax.inject.Inject internal class ColorPresenter private constructor(view: View, component: ColorComponent) : ViewPresenter(view) { companion object { @LayoutRes fun layoutId() = R.layout.color_view fun bindView(view: View, component: ColorComponent) = ColorPresenter(view, component) } @Inject @ColorHex lateinit var colorHex: String @Inject lateinit var navigator: ColorScreenNavigator private val newColorEditText = bindView<TextView>(R.id.edit_text) init { component.inject(this) bindView<View>(R.id.color_view).setBackgroundColor(Color.parseColor(colorHex)) bindView<TextView>(R.id.color_text_view).text = colorHex bindClick(R.id.submit_button, ::submitClicked) } private fun submitClicked() { val color = newColorEditText.text.toString() try { Color.parseColor(color) navigator.colorSubmitted(color, view) } catch (e: IllegalArgumentException) { Toast.makeText(context, "Invalid Color", Toast.LENGTH_LONG).show() } } }
apache-2.0
0a3c487d91376b4c659808e07b311e92
33.102564
112
0.712782
4.403974
false
false
false
false
jainaman224/Algo_Ds_Notes
Sieve_Of_Eratosthenes/Sieve_Of_Eratosthenes.kt
1
749
import java.util.Scanner fun main() { // Let we want to find the Prime Numbers below a certain number. val scanner = Scanner(System.`in`) print("Enter an Integer : ") var num = scanner.nextInt() var prime = Array(num){ true } var sqre = square_root(num.toFloat()) for (i in 2 until sqre.toInt()) { if (prime[i]) { for (j in (2 * i)..(num) step i) { prime[j] = false } } } // Printing Prime Numbers In the range of (1 to given Number) for (primes in 2 until num) { if (prime[primes]) { print("$primes ") } } } // Input:- Enter an Integer : 89 // Output:- 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83
gpl-3.0
68a953e7d1a07176f7c6bb43478d370c
27.807692
76
0.538051
3.583732
false
false
false
false
wordpress-mobile/WordPress-FluxC-Android
fluxc/src/main/java/org/wordpress/android/fluxc/store/EncryptedLogStore.kt
2
13747
package org.wordpress.android.fluxc.store import kotlinx.coroutines.delay import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.Payload import org.wordpress.android.fluxc.action.EncryptedLogAction import org.wordpress.android.fluxc.action.EncryptedLogAction.RESET_UPLOAD_STATES import org.wordpress.android.fluxc.action.EncryptedLogAction.UPLOAD_LOG import org.wordpress.android.fluxc.annotations.action.Action import org.wordpress.android.fluxc.model.encryptedlogging.EncryptedLog import org.wordpress.android.fluxc.model.encryptedlogging.EncryptedLogUploadState.FAILED import org.wordpress.android.fluxc.model.encryptedlogging.EncryptedLogUploadState.UPLOADING import org.wordpress.android.fluxc.model.encryptedlogging.LogEncrypter import org.wordpress.android.fluxc.network.BaseRequest.BaseNetworkError import org.wordpress.android.fluxc.network.rest.wpcom.encryptedlog.EncryptedLogRestClient import org.wordpress.android.fluxc.network.rest.wpcom.encryptedlog.UploadEncryptedLogResult.LogUploadFailed import org.wordpress.android.fluxc.network.rest.wpcom.encryptedlog.UploadEncryptedLogResult.LogUploaded import org.wordpress.android.fluxc.persistence.EncryptedLogSqlUtils import org.wordpress.android.fluxc.store.EncryptedLogStore.EncryptedLogUploadFailureType.CLIENT_FAILURE import org.wordpress.android.fluxc.store.EncryptedLogStore.EncryptedLogUploadFailureType.CONNECTION_FAILURE import org.wordpress.android.fluxc.store.EncryptedLogStore.EncryptedLogUploadFailureType.IRRECOVERABLE_FAILURE import org.wordpress.android.fluxc.store.EncryptedLogStore.OnEncryptedLogUploaded.EncryptedLogFailedToUpload import org.wordpress.android.fluxc.store.EncryptedLogStore.OnEncryptedLogUploaded.EncryptedLogUploadedSuccessfully import org.wordpress.android.fluxc.store.EncryptedLogStore.UploadEncryptedLogError.InvalidRequest import org.wordpress.android.fluxc.store.EncryptedLogStore.UploadEncryptedLogError.MissingFile import org.wordpress.android.fluxc.store.EncryptedLogStore.UploadEncryptedLogError.NoConnection import org.wordpress.android.fluxc.store.EncryptedLogStore.UploadEncryptedLogError.TooManyRequests import org.wordpress.android.fluxc.store.EncryptedLogStore.UploadEncryptedLogError.Unknown import org.wordpress.android.fluxc.store.EncryptedLogStore.UploadEncryptedLogError.UnsatisfiedLinkException import org.wordpress.android.fluxc.tools.CoroutineEngine import org.wordpress.android.fluxc.utils.PreferenceUtils.PreferenceUtilsWrapper import org.wordpress.android.util.AppLog import org.wordpress.android.util.AppLog.T.API import java.io.File import java.util.Date import javax.inject.Inject import javax.inject.Singleton /** * Depending on the error type, we'll keep a record of the earliest date we can try another encrypted log upload. * * The most important example of this is `TOO_MANY_REQUESTS` error which results in server refusing any uploads for * an hour. */ private const val ENCRYPTED_LOG_UPLOAD_UNAVAILABLE_UNTIL_DATE = "ENCRYPTED_LOG_UPLOAD_UNAVAILABLE_UNTIL_DATE_PREF_KEY" private const val UPLOAD_NEXT_DELAY = 3000L // 3 seconds private const val TOO_MANY_REQUESTS_ERROR_DELAY = 60 * 60 * 1000L // 1 hour private const val REGULAR_UPLOAD_FAILURE_DELAY = 60 * 1000L // 1 minute private const val MAX_RETRY_COUNT = 3 private const val HTTP_STATUS_CODE_500 = 500 private const val HTTP_STATUS_CODE_599 = 599 @Singleton class EncryptedLogStore @Inject constructor( private val encryptedLogRestClient: EncryptedLogRestClient, private val encryptedLogSqlUtils: EncryptedLogSqlUtils, private val coroutineEngine: CoroutineEngine, private val logEncrypter: LogEncrypter, private val preferenceUtils: PreferenceUtilsWrapper, dispatcher: Dispatcher ) : Store(dispatcher) { override fun onRegister() { AppLog.d(API, this.javaClass.name + ": onRegister") } @Subscribe(threadMode = ThreadMode.ASYNC) override fun onAction(action: Action<*>) { val actionType = action.type as? EncryptedLogAction ?: return when (actionType) { UPLOAD_LOG -> { coroutineEngine.launch(API, this, "EncryptedLogStore: On UPLOAD_LOG") { queueLogForUpload(action.payload as UploadEncryptedLogPayload) } } RESET_UPLOAD_STATES -> { coroutineEngine.launch(API, this, "EncryptedLogStore: On RESET_UPLOAD_STATES") { resetUploadStates() } } } } /** * A method for the client to use to start uploading any encrypted logs that might have been queued. * * This method should be called within a coroutine, possibly in GlobalScope so it's not attached to any one context. */ @Suppress("unused") suspend fun uploadQueuedEncryptedLogs() { uploadNext() } private suspend fun queueLogForUpload(payload: UploadEncryptedLogPayload) { // If the log file is not valid, there is nothing we can do if (!isValidFile(payload.file)) { emitChange( EncryptedLogFailedToUpload( uuid = payload.uuid, file = payload.file, error = MissingFile, willRetry = false ) ) return } val encryptedLog = EncryptedLog( uuid = payload.uuid, file = payload.file ) encryptedLogSqlUtils.insertOrUpdateEncryptedLog(encryptedLog) if (payload.shouldStartUploadImmediately) { uploadNext() } } private fun resetUploadStates() { encryptedLogSqlUtils.insertOrUpdateEncryptedLogs(encryptedLogSqlUtils.getUploadingEncryptedLogs().map { it.copy(uploadState = FAILED) }) } private suspend fun uploadNextWithDelay(delay: Long) { addUploadDelay(delay) // Add a few seconds buffer to avoid possible millisecond comparison issues delay(delay + UPLOAD_NEXT_DELAY) uploadNext() } private suspend fun uploadNext() { if (!isUploadAvailable()) { return } // We want to upload a single file at a time encryptedLogSqlUtils.getEncryptedLogsForUpload().firstOrNull()?.let { uploadEncryptedLog(it) } } @Suppress("SwallowedException") private suspend fun uploadEncryptedLog(encryptedLog: EncryptedLog) { // If the log file doesn't exist, fail immediately and try the next log file if (!isValidFile(encryptedLog.file)) { handleFailedUpload(encryptedLog, MissingFile) uploadNext() return } try { val encryptedText = logEncrypter.encrypt(text = encryptedLog.file.readText(), uuid = encryptedLog.uuid) // Update the upload state of the log encryptedLog.copy(uploadState = UPLOADING).let { encryptedLogSqlUtils.insertOrUpdateEncryptedLog(it) } when (val result = encryptedLogRestClient.uploadLog(encryptedLog.uuid, encryptedText)) { is LogUploaded -> handleSuccessfulUpload(encryptedLog) is LogUploadFailed -> handleFailedUpload(encryptedLog, result.error) } } catch (e: UnsatisfiedLinkError) { handleFailedUpload(encryptedLog, UnsatisfiedLinkException) } } private suspend fun handleSuccessfulUpload(encryptedLog: EncryptedLog) { deleteEncryptedLog(encryptedLog) emitChange(EncryptedLogUploadedSuccessfully(uuid = encryptedLog.uuid, file = encryptedLog.file)) uploadNext() } private suspend fun handleFailedUpload(encryptedLog: EncryptedLog, error: UploadEncryptedLogError) { val failureType = mapUploadEncryptedLogError(error) val (isFinalFailure, finalFailureCount) = when (failureType) { IRRECOVERABLE_FAILURE -> { Pair(true, encryptedLog.failedCount + 1) } CONNECTION_FAILURE -> { Pair(false, encryptedLog.failedCount) } CLIENT_FAILURE -> { val newFailedCount = encryptedLog.failedCount + 1 Pair(newFailedCount >= MAX_RETRY_COUNT, newFailedCount) } } if (isFinalFailure) { deleteEncryptedLog(encryptedLog) } else { encryptedLogSqlUtils.insertOrUpdateEncryptedLog( encryptedLog.copy( uploadState = FAILED, failedCount = finalFailureCount ) ) } emitChange( EncryptedLogFailedToUpload( uuid = encryptedLog.uuid, file = encryptedLog.file, error = error, willRetry = !isFinalFailure ) ) // If a log failed to upload for the final time, we don't need to add any delay since the log is the problem. // Otherwise, the only special case that requires an extra long delay is `TOO_MANY_REQUESTS` upload error. if (isFinalFailure) { uploadNext() } else { if (error is TooManyRequests) { uploadNextWithDelay(TOO_MANY_REQUESTS_ERROR_DELAY) } else { uploadNextWithDelay(REGULAR_UPLOAD_FAILURE_DELAY) } } } private fun mapUploadEncryptedLogError(error: UploadEncryptedLogError): EncryptedLogUploadFailureType { return when (error) { is NoConnection -> { CONNECTION_FAILURE } is TooManyRequests -> { CONNECTION_FAILURE } is InvalidRequest -> { IRRECOVERABLE_FAILURE } is MissingFile -> { IRRECOVERABLE_FAILURE } is UnsatisfiedLinkException -> { IRRECOVERABLE_FAILURE } is Unknown -> { when { (HTTP_STATUS_CODE_500..HTTP_STATUS_CODE_599).contains(error.statusCode) -> { CONNECTION_FAILURE } else -> { CLIENT_FAILURE } } } } } private fun deleteEncryptedLog(encryptedLog: EncryptedLog) { encryptedLogSqlUtils.deleteEncryptedLogs(listOf(encryptedLog)) } private fun isValidFile(file: File): Boolean = file.exists() && file.canRead() /** * Checks if encrypted logs can be uploaded at this time. * * If we are already uploading another encrypted log or if we are manually delaying the uploads due to server errors * encrypted log uploads will not be available. */ private fun isUploadAvailable(): Boolean { if (encryptedLogSqlUtils.getNumberOfUploadingEncryptedLogs() > 0) { // We are already uploading another log file return false } preferenceUtils.getFluxCPreferences().getLong(ENCRYPTED_LOG_UPLOAD_UNAVAILABLE_UNTIL_DATE, -1L).let { return it <= Date().time } } private fun addUploadDelay(delayDuration: Long) { val date = Date().time + delayDuration preferenceUtils.getFluxCPreferences().edit().putLong(ENCRYPTED_LOG_UPLOAD_UNAVAILABLE_UNTIL_DATE, date).apply() } /** * Payload to be used to queue a file to be encrypted and uploaded. * * [shouldStartUploadImmediately] property will be used by [EncryptedLogStore] to decide whether the encryption and * upload should be initiated immediately. Since the main use case to queue a log file to be uploaded is a crash, * the default value is `false`. If we try to upload the log file during a crash, there won't be enough time to * encrypt and upload it, which means it'll just fail. On the other hand, for developer initiated crash monitoring * events, it'd be good, but not essential, to set it to `true` so we can upload it as soon as possible. */ class UploadEncryptedLogPayload( val uuid: String, val file: File, val shouldStartUploadImmediately: Boolean = false ) : Payload<BaseNetworkError>() sealed class OnEncryptedLogUploaded(val uuid: String, val file: File) : Store.OnChanged<UploadEncryptedLogError>() { class EncryptedLogUploadedSuccessfully(uuid: String, file: File) : OnEncryptedLogUploaded(uuid, file) class EncryptedLogFailedToUpload( uuid: String, file: File, error: UploadEncryptedLogError, val willRetry: Boolean ) : OnEncryptedLogUploaded(uuid, file) { init { this.error = error } } } sealed class UploadEncryptedLogError : OnChangedError { class Unknown(val statusCode: Int? = null, val message: String? = null) : UploadEncryptedLogError() object InvalidRequest : UploadEncryptedLogError() object TooManyRequests : UploadEncryptedLogError() object NoConnection : UploadEncryptedLogError() object MissingFile : UploadEncryptedLogError() object UnsatisfiedLinkException : UploadEncryptedLogError() } /** * These are internal failure types to make it easier to deal with encrypted log upload errors. */ private enum class EncryptedLogUploadFailureType { IRRECOVERABLE_FAILURE, CONNECTION_FAILURE, CLIENT_FAILURE } }
gpl-2.0
01bf4bf9c397165dde30285cdb6b24e9
41.560372
120
0.668728
5.275134
false
false
false
false
lgou2w/MoonLakeLauncher
src/main/kotlin/com/minecraft/moonlake/launcher/controller/MuiControllerUtils.kt
1
2514
package com.minecraft.moonlake.launcher.controller import com.minecraft.moonlake.launcher.annotation.MuiControllerFXML import javafx.fxml.FXMLLoader import javafx.fxml.JavaFXBuilderFactory import javafx.scene.Scene import javafx.scene.layout.Pane import javafx.stage.Stage object MuiControllerUtils { @JvmStatic private fun <P: Pane> setPanePrefSize(pane: P, width: Double, height: Double): P { pane.setPrefSize(width, height) return pane } @JvmStatic @Throws(IllegalArgumentException::class) fun <P: Pane, T: MuiController<P>> loadControllerPane(clazz: Class<T>): P { val muiControllerFxml = clazz.getAnnotation(MuiControllerFXML::class.java) if(muiControllerFxml != null && (muiControllerFxml.width > .0 || muiControllerFxml.height > .0)) return setPanePrefSize(FXMLLoader.load<P>(clazz.classLoader.getResource(muiControllerFxml.value)), muiControllerFxml.width, muiControllerFxml.height) else if(muiControllerFxml != null) return FXMLLoader.load<P>(clazz.classLoader.getResource(muiControllerFxml.value)) throw IllegalArgumentException("参数控制器类没有被 MuiControllerFXML 注解.") } @JvmStatic @Throws(IllegalArgumentException::class) fun <P: Pane, T: MuiController<P>> loadControllerScene(clazz: Class<T>): Scene = Scene(loadControllerPane(clazz)) @JvmStatic @Throws(IllegalArgumentException::class) fun <S: Stage, P: Pane, T: MuiStageController<S, P>> loadStageControllerPane(stage: S, clazz: Class<T>): P { val muiControllerFxml = clazz.getAnnotation(MuiControllerFXML::class.java) if(muiControllerFxml != null) { val loader = FXMLLoader() loader.builderFactory = JavaFXBuilderFactory() loader.location = clazz.classLoader.getResource(muiControllerFxml.value) val pane = loader.load<P>() loader.getController<T>().setStage(stage) if(muiControllerFxml.width > .0 || muiControllerFxml.height > .0) return setPanePrefSize(pane, muiControllerFxml.width, muiControllerFxml.height) return pane } throw IllegalArgumentException("参数控制器类没有被 MuiControllerFXML 注解.") } @JvmStatic @Throws(IllegalArgumentException::class) fun <S: Stage, P: Pane, T: MuiStageController<S, P>> loadStageControllerScene(stage: S, clazz: Class<T>): Scene = Scene(loadStageControllerPane(stage, clazz)) }
gpl-3.0
fa750bd147d04e8163b616bcb4193b56
43.909091
161
0.704858
4.52381
false
false
false
false
alygin/intellij-rust
src/test/kotlin/org/rust/lang/core/completion/RsStdlibCompletionTest.kt
1
1324
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.completion import com.intellij.testFramework.LightProjectDescriptor class RsStdlibCompletionTest : RsCompletionTestBase() { override fun getProjectDescriptor(): LightProjectDescriptor = WithStdlibRustProjectDescriptor fun testPrelude() = checkSingleCompletion("drop()", """ fn main() { dr/*caret*/ } """) fun testPreludeVisibility() = checkNoCompletion(""" mod m {} fn main() { m::dr/*caret*/ } """) fun testIter() = checkSingleCompletion("iter_mut()", """ fn main() { let vec: Vec<i32> = Vec::new(); let iter = vec.iter_m/*caret*/ } """) fun testDerivedTraitMethod() = checkSingleCompletion("fmt", """ #[derive(Debug)] struct Foo; fn bar(foo: Foo) { foo.fm/*caret*/ } """) fun `test macro`() = doSingleCompletion(""" fn main() { unimpl/*caret*/ } """, """ fn main() { unimplemented!(/*caret*/) } """) fun `test macro with square brackets`() = doSingleCompletion(""" fn main() { vec/*caret*/ } """, """ fn main() { vec![/*caret*/] } """) }
mit
feabd43df405f1bff7bc6530f51ed688
23.981132
97
0.543807
4.565517
false
true
false
false
requery/requery
requery-kotlin/src/main/kotlin/io/requery/kotlin/PropertyExtensions.kt
1
8766
/* * Copyright 2017 requery.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.requery.kotlin import io.requery.meta.Attribute import io.requery.meta.AttributeDelegate import io.requery.meta.NumericAttributeDelegate import io.requery.meta.StringAttributeDelegate import io.requery.meta.Type import io.requery.query.Expression import io.requery.query.OrderingExpression import io.requery.query.Return import io.requery.query.RowExpression import io.requery.query.function.Abs import io.requery.query.function.Avg import io.requery.query.function.Lower import io.requery.query.function.Max import io.requery.query.function.Min import io.requery.query.function.Round import io.requery.query.function.Substr import io.requery.query.function.Sum import io.requery.query.function.Trim import io.requery.query.function.Upper import kotlin.reflect.KProperty1 inline fun <reified T : Any, R> KProperty1<T, R>.asc(): OrderingExpression<R> = findAttribute(this).asc() inline fun <reified T : Any, R> KProperty1<T, R>.desc(): OrderingExpression<R> = findAttribute(this).desc() inline fun <reified T : Any, R> KProperty1<T, R>.abs(): Abs<R> = findNumericAttribute(this).abs() inline fun <reified T : Any, R> KProperty1<T, R>.max(): Max<R> = findNumericAttribute(this).max() inline fun <reified T : Any, R> KProperty1<T, R>.min(): Min<R> = findNumericAttribute(this).min() inline fun <reified T : Any, R> KProperty1<T, R>.avg(): Avg<R> = findNumericAttribute(this).avg() inline fun <reified T : Any, R> KProperty1<T, R>.sum(): Sum<R> = findNumericAttribute(this).sum() inline fun <reified T : Any, R> KProperty1<T, R>.round(): Round<R> = findNumericAttribute(this).round() inline fun <reified T : Any, R> KProperty1<T, R>.round(decimals: Int): Round<R> = findNumericAttribute(this).round(decimals) inline fun <reified T : Any, R> KProperty1<T, R>.trim(chars: String?): Trim<R> = findStringAttribute(this).trim(chars) inline fun <reified T : Any, R> KProperty1<T, R>.trim(): Trim<R> = findStringAttribute(this).trim() inline fun <reified T : Any, R> KProperty1<T, R>.substr(offset: Int, length: Int): Substr<R> = findStringAttribute(this).substr(offset, length) inline fun <reified T : Any, R> KProperty1<T, R>.upper(): Upper<R> = findStringAttribute(this).upper() inline fun <reified T : Any, R> KProperty1<T, R>.lower(): Lower<R> = findStringAttribute(this).lower() inline infix fun <reified T : Any, R> KProperty1<T, R>.eq(value: R): Logical<out Expression<R>, R> = findAttribute(this).eq(value) inline infix fun <reified T : Any, R> KProperty1<T, R>.ne(value: R): Logical<out Expression<R>, R> = findAttribute(this).ne(value) inline infix fun <reified T : Any, R> KProperty1<T, R>.lt(value: R): Logical<out Expression<R>, R> = findAttribute(this).lt(value) inline infix fun <reified T : Any, R> KProperty1<T, R>.gt(value: R): Logical<out Expression<R>, R> = findAttribute(this).gt(value) inline infix fun <reified T : Any, R> KProperty1<T, R>.lte(value: R): Logical<out Expression<R>, R> = findAttribute(this).lte(value) inline infix fun <reified T : Any, R> KProperty1<T, R>.gte(value: R): Logical<out Expression<R>, R> = findAttribute(this).gte(value) inline infix fun <reified T : Any, R, reified U : Any> KProperty1<T, R>.eq(value: KProperty1<U, R>): Logical<out Expression<R>, out Expression<R>> = findAttribute(this).eq(findAttribute(value)) inline infix fun <reified T : Any, R, reified U : Any> KProperty1<T, R>.ne(value: KProperty1<U, R>): Logical<out Expression<R>, out Expression<R>> = findAttribute(this).ne(findAttribute(value)) inline infix fun <reified T : Any, R, reified U : Any> KProperty1<T, R>.lt(value: KProperty1<U, R>): Logical<out Expression<R>, out Expression<R>> = findAttribute(this).lt(findAttribute(value)) inline infix fun <reified T : Any, R, reified U : Any> KProperty1<T, R>.gt(value: KProperty1<U, R>): Logical<out Expression<R>, out Expression<R>> = findAttribute(this).gt(findAttribute(value)) inline infix fun <reified T : Any, R, reified U : Any> KProperty1<T, R>.lte(value: KProperty1<U, R>): Logical<out Expression<R>, out Expression<R>> = findAttribute(this).lte(findAttribute(value)) inline infix fun <reified T : Any, R, reified U : Any> KProperty1<T, R>.gte(value: KProperty1<U, R>): Logical<out Expression<R>, out Expression<R>> = findAttribute(this).gte(findAttribute(value)) inline infix fun <reified T : Any, R> KProperty1<T, R>.eq(value: Expression<R>): Logical<out Expression<R>, out Expression<R>> = findAttribute(this).eq(value) inline infix fun <reified T : Any, R> KProperty1<T, R>.ne(value: Expression<R>): Logical<out Expression<R>, out Expression<R>> = findAttribute(this).ne(value) inline infix fun <reified T : Any, R> KProperty1<T, R>.lt(value: Expression<R>): Logical<out Expression<R>, out Expression<R>> = findAttribute(this).lt(value) inline infix fun <reified T : Any, R> KProperty1<T, R>.gt(value: Expression<R>): Logical<out Expression<R>, out Expression<R>> = findAttribute(this).gt(value) inline infix fun <reified T : Any, R> KProperty1<T, R>.lte(value: Expression<R>): Logical<out Expression<R>, out Expression<R>> = findAttribute(this).lte(value) inline infix fun <reified T : Any, R> KProperty1<T, R>.gte(value: Expression<R>): Logical<out Expression<R>, out Expression<R>> = findAttribute(this).gte(value) inline infix fun <reified T : Any, R> KProperty1<T, R>.`in`(value: Collection<R>): Logical<out Expression<R>, out Collection<R>> = findAttribute(this).`in`(value) inline infix fun <reified T : Any, R> KProperty1<T, R>.notIn(value: Collection<R>): Logical<out Expression<R>, out Collection<R>> = findAttribute(this).notIn(value) inline infix fun <reified T : Any, R> KProperty1<T, R>.`in`(query: Return<*>): Logical<out Expression<R>, out Return<*>> = findAttribute(this).`in`(query) inline infix fun <reified T : Any, R> KProperty1<T, R>.notIn(query: Return<*>): Logical<out Expression<R>, out Return<*>> = findAttribute(this).notIn(query) inline fun <reified T : Any, R> KProperty1<T, R>.isNull(): Logical<out Expression<R>, out R> = findAttribute(this).isNull() inline fun <reified T : Any, R> KProperty1<T, R>.notNull(): Logical<out Expression<R>, out R> = findAttribute(this).notNull() inline fun <reified T : Any, R> KProperty1<T, R>.like(expression: String): Logical<out Expression<R>, out String> = findAttribute(this).like(expression) inline fun <reified T : Any, R> KProperty1<T, R>.notLike(expression: String): Logical<out Expression<R>, out String> = findAttribute(this).notLike(expression) inline fun <reified T : Any, R> KProperty1<T, R>.between(start: R, end: R): Logical<out Expression<R>, Any> = findAttribute(this).between(start, end) inline fun <reified T : Any, R> rowExpressionOf(vararg expressions: KProperty1<T, R>): RowExpression { val list = ArrayList<Expression<*>>() expressions.forEach { e -> list.add(findAttribute(e)) } return RowExpression.of(list) } /** Given a property find the corresponding generated attribute for it */ inline fun <reified T : Any, R> findAttribute(property: KProperty1<T, R>): AttributeDelegate<T, R> { val type: Type<*>? = AttributeDelegate.types .filter { type -> (type.classType == T::class.java || type.baseType == T::class.java)} .firstOrNull() if (type == null) { throw UnsupportedOperationException(T::class.java.simpleName + "." + property.name + " cannot be used in query") } val attribute: Attribute<*, *>? = type.attributes .filter { attribute -> attribute.propertyName.replaceFirst("get", "") .equals(property.name, ignoreCase = true) }.firstOrNull() if (attribute !is AttributeDelegate) { throw UnsupportedOperationException(T::class.java.simpleName + "." + property.name + " cannot be used in query") } @Suppress("UNCHECKED_CAST") return attribute as AttributeDelegate<T, R> } inline fun <reified T : Any, R> findStringAttribute(property: KProperty1<T, R>): StringAttributeDelegate<T, R> { return findAttribute(property) as StringAttributeDelegate<T, R> } inline fun <reified T : Any, R> findNumericAttribute(property: KProperty1<T, R>): NumericAttributeDelegate<T, R> { return findAttribute(property) as NumericAttributeDelegate<T, R> }
apache-2.0
3cbd989cde7b257caa61309315352152
70.852459
195
0.718686
3.521896
false
false
false
false
iMeePwni/LCExercise
src/main/kotlin/DiameterOfBinaryTree.kt
1
546
/** * Created by guofeng on 2017/7/12. */ class DiameterOfBinaryTree { fun single(treeNode: TreeNode?): Int { if (treeNode == null) return 0 return Math.max(single(treeNode.left), single(treeNode.right)) + 1 } fun solution(treeNode: TreeNode?): Int { if (treeNode == null) return 0 val lr = single(treeNode.left) + single(treeNode.right) val ls = solution(treeNode.left) val rs = solution(treeNode.right) return Math.max(Math.max(ls, rs), lr) } }
apache-2.0
2fe47c4d20427b08fc074d13dbb4efb6
26.35
74
0.586081
3.765517
false
false
false
false
mixitconf/mixit
src/main/kotlin/mixit/user/handler/dto/UserDto.kt
1
1470
package mixit.user.handler.dto import mixit.talk.model.Language import mixit.user.handler.logoType import mixit.user.handler.logoWebpUrl import mixit.user.model.Link import mixit.user.model.PhotoShape import mixit.user.model.Role import mixit.user.model.User import mixit.util.markFoundOccurrences import mixit.util.toHTML import mixit.util.toUrlPath class UserDto( val login: String, val firstname: String, val lastname: String, var email: String? = null, var company: String? = null, var description: String, var emailHash: String? = null, var photoUrl: String? = null, val photoShape: PhotoShape? = null, val role: Role, var links: List<Link>, val logoType: String?, val logoWebpUrl: String? = null, val isAbsoluteLogo: Boolean = photoUrl?.startsWith("http") ?: false, val path: String = login.toUrlPath(), val newsletterSubscriber: Boolean = false ) fun User.toDto(language: Language, searchTerms: List<String> = emptyList()) = UserDto( login, firstname.markFoundOccurrences(searchTerms), lastname.markFoundOccurrences(searchTerms), email, company, description[language]?.toHTML()?.markFoundOccurrences(searchTerms) ?: "", emailHash, photoUrl, photoShape ?: PhotoShape.Square, role, links, logoType(photoUrl), logoWebpUrl(photoUrl), newsletterSubscriber = newsletterSubscriber )
apache-2.0
f94057a14b01dae635463d61fb0c7097
29
81
0.689116
4.106145
false
false
false
false
infinum/android_dbinspector
dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/content/shared/ContentAdapter.kt
1
1299
package com.infinum.dbinspector.ui.content.shared import android.view.LayoutInflater import android.view.ViewGroup import androidx.paging.PagingDataAdapter import com.infinum.dbinspector.databinding.DbinspectorItemCellBinding import com.infinum.dbinspector.domain.shared.models.Cell import com.infinum.dbinspector.ui.shared.diffutils.CellDiffUtil internal class ContentAdapter : PagingDataAdapter<Cell, ContentViewHolder>(CellDiffUtil()) { var headersCount: Int = 0 var onCellClicked: ((Cell) -> Unit)? = null init { stateRestorationPolicy = StateRestorationPolicy.PREVENT_WHEN_EMPTY } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContentViewHolder = ContentViewHolder( DbinspectorItemCellBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) override fun onBindViewHolder(holder: ContentViewHolder, position: Int) { if (headersCount > 0) { val item = getItem(position) holder.bind(item, position / headersCount, onCellClicked) } } override fun onViewRecycled(holder: ContentViewHolder) = with(holder) { unbind() super.onViewRecycled(this) } }
apache-2.0
6d84562ddc472025ae122b1cfa36a0fa
31.475
92
0.685142
4.939163
false
false
false
false
infinum/android_dbinspector
dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/shared/base/BaseViewModel.kt
1
2691
package com.infinum.dbinspector.ui.shared.base import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.infinum.dbinspector.di.LibraryKoin import com.infinum.dbinspector.di.LibraryKoinComponent import com.infinum.dbinspector.logger.Logger import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext internal abstract class BaseViewModel<State, Event> : ViewModel(), LibraryKoinComponent { private val logger: Logger? = LibraryKoin.koin().getOrNull() private val supervisorJob = SupervisorJob() protected val runningScope = viewModelScope protected val runningDispatchers = Dispatchers.IO private var mainDispatchers = Dispatchers.Main private val mutableStateFlow: MutableStateFlow<State?> = MutableStateFlow(value = null) private val mutableEventFlow: MutableSharedFlow<Event?> = MutableSharedFlow(replay = 1) private val mutableErrorFlow: MutableStateFlow<Throwable?> = MutableStateFlow(value = null) val stateFlow: StateFlow<State?> get() = mutableStateFlow.asStateFlow() val eventFlow: SharedFlow<Event?> get() = mutableEventFlow.asSharedFlow() val errorFlow: StateFlow<Throwable?> get() = mutableErrorFlow.asStateFlow() protected open val errorHandler = CoroutineExceptionHandler { _, throwable -> throwable.message?.let { logger?.error(it) } mutableErrorFlow.value = throwable } override fun onCleared() { super.onCleared() runningDispatchers.cancel() runningScope.cancel() supervisorJob.cancel() } protected fun launch( scope: CoroutineScope = runningScope, block: suspend CoroutineScope.() -> Unit ) { scope.launch(errorHandler + mainDispatchers + supervisorJob) { block.invoke(this) } } protected suspend fun <T> io(block: suspend CoroutineScope.() -> T) = withContext(context = runningDispatchers) { block.invoke(this) } protected fun setState(state: State) { mutableStateFlow.value = state } protected suspend fun emitEvent(event: Event) { mutableEventFlow.emit(event) } protected fun setError(error: Throwable) { mutableErrorFlow.value = error } }
apache-2.0
e41601e1eb002a678cc6070e46cbb31f
35.863014
95
0.755853
4.946691
false
false
false
false
Automattic/wp-calypso
.teamcity/_self/projects/WPComPlugins.kt
1
9740
package _self.projects import _self.bashNodeScript import _self.lib.wpcom.WPComPluginBuild import jetbrains.buildServer.configs.kotlin.v2019_2.Project import jetbrains.buildServer.configs.kotlin.v2019_2.BuildType import jetbrains.buildServer.configs.kotlin.v2019_2.BuildSteps import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.ScriptBuildStep object WPComPlugins : Project({ id("WPComPlugins") name = "WPCom Plugins" description = "Builds for WordPress.com plugins developed in calypso and deployed to wp-admin." // Default params for WPcom Plugins. params { param("docker_image", "registry.a8c.com/calypso/ci-wpcom:latest") param("build.prefix", "1") checkbox( name = "skip_release_diff", value = "false", label = "Skip release diff", description = "Skips the diff against the previous successful build, uploading the artifact as the latest successful build.", checked = "true", unchecked = "false" ) } buildType(EditingToolkit) buildType(WpcomBlockEditor) buildType(Notifications) buildType(O2Blocks) buildType(HappyBlocks) buildType(Happychat) buildType(InlineHelp) buildType(GutenbergUploadSourceMapsToSentry); cleanup { keepRule { id = "keepReleaseBuilds" keepAtLeast = allBuilds() applyToBuilds { inBranches { branchFilter = patterns("+:<default>") } withStatus = successful() withTags = anyOf( "notifications-release-build", "etk-release-build", "wpcom-block-editor-release-build", "o2-blocks-release-build", "happy-blocks-release-build", ) } dataToKeep = everything() applyPerEachBranch = true preserveArtifactsDependencies = true } } }) private object EditingToolkit : WPComPluginBuild( buildId = "WPComPlugins_EditorToolKit", buildName = "Editing ToolKit", releaseTag = "etk-release-build", pluginSlug = "editing-toolkit", archiveDir = "./editing-toolkit-plugin/", docsLink = "PCYsg-mMA-p2", normalizeFiles = "sed -i -e \"/^\\s\\* Version:/c\\ * Version: %build.number%\" -e \"/^define( 'A8C_ETK_PLUGIN_VERSION'/c\\define( 'A8C_ETK_PLUGIN_VERSION', '%build.number%' );\" ./release-archive/full-site-editing-plugin.php && sed -i -e \"/^Stable tag:\\s/c\\Stable tag: %build.number%\" ./release-archive/readme.txt\n", withSlackNotify = "false", buildSteps = { bashNodeScript { name = "Update version" scriptContent = """ cd apps/editing-toolkit # Update plugin version in the plugin file and readme.txt. sed -i -e "/^\s\* Version:/c\ * Version: %build.number%" -e "/^define( 'A8C_ETK_PLUGIN_VERSION'/c\define( 'A8C_ETK_PLUGIN_VERSION', '%build.number%' );" ./editing-toolkit-plugin/full-site-editing-plugin.php sed -i -e "/^Stable tag:\s/c\Stable tag: %build.number%" ./editing-toolkit-plugin/readme.txt """ } bashNodeScript { name = "Run JS tests" scriptContent = """ cd apps/editing-toolkit yarn test:js --reporters=default --reporters=jest-teamcity --maxWorkers=${'$'}JEST_MAX_WORKERS """ } // Note: We run the PHP lint after the build to verify that the newspack-blocks // code is also formatted correctly. bashNodeScript { name = "Run PHP Lint" scriptContent = """ cd apps/editing-toolkit if [ ! -d "./editing-toolkit-plugin/newspack-blocks/synced-newspack-blocks" ] ; then echo "Newspack blocks were not built correctly." exit 1 fi yarn lint:php """ } }, buildParams = { param("build.prefix", "3") } ) private object WpcomBlockEditor : WPComPluginBuild( buildId = "WPComPlugins_WpcomBlockEditor", buildName = "Wpcom Block Editor", pluginSlug = "wpcom-block-editor", archiveDir = "./dist/", buildEnv = "development", docsLink = "PCYsg-l4k-p2", ) private object Notifications : WPComPluginBuild( buildId = "WPComPlugins_Notifications", buildName = "Notifications", pluginSlug = "notifications", archiveDir = "./dist/", docsLink = "PCYsg-elI-p2", // This param is executed in bash right before the build script compares // the build with the previous release version. The purpose of this code // is to remove sources of randomness so that the diff operation only // compares legitimate changes. normalizeFiles = """ function get_hash { # If the stylesheet in the HTML file is pointing at "build.min.css?foobar123", # this will just return the "foobar123" portion of the file. This # is a source of randomness which needs to be eliminated. echo `sed -nE 's~.*<link rel="stylesheet" href="build.min.css\?([a-zA-Z0-9]+)">.*~\1~p' ${'$'}1` } new_hash=`get_hash dist/index.html` old_hash=`get_hash release-archive/index.html` # All scripts and styles use the same "hash" version, so replace any # instances of the hash in the *old* files with the newest version. sed -i "s~${'$'}old_hash~${'$'}new_hash~g" release-archive/index.html release-archive/rtl.html # Replace the old cache buster with the new one in the previous release html files. if [ -f './release-archive/build_meta.json' ] ; then old_cache_buster=`jq -r '.cache_buster' ./release-archive/build_meta.json` else old_cache_buster=`cat ./release-archive/cache-buster.txt` fi new_cache_buster=`jq -r '.cache_buster' ./dist/build_meta.json` sed -i "s~${'$'}old_cache_buster~${'$'}new_cache_buster~g" release-archive/index.html release-archive/rtl.html """.trimIndent(), ) private object O2Blocks : WPComPluginBuild( buildId="WPComPlugins_O2Blocks", buildName = "O2 Blocks", pluginSlug = "o2-blocks", archiveDir = "./release-files/", docsLink = "PCYsg-r7r-p2", buildSteps = { bashNodeScript { name = "Create release directory" scriptContent = """ cd apps/o2-blocks # Copy existing dist files to release directory mkdir release-files cp -r dist release-files/dist/ # Add index.php file cp index.php release-files/ """ } } ) private object HappyBlocks : WPComPluginBuild( buildId="WPComPlugins_HappyBlocks", buildName = "Happy Blocks", pluginSlug = "happy-blocks", archiveDir = "./release-files/", docsLink = "PCYsg-r7r-p2", buildSteps = { bashNodeScript { name = "Create release directory" scriptContent = """ cd apps/happy-blocks # Copy existing dist files to release directory mkdir release-files cp -r dist release-files/dist/ # Add index.php file cp index.php release-files/ """ } } ) private object Happychat : WPComPluginBuild( buildId = "WPComPlugins_Happychat", buildName = "Happychat", pluginSlug = "happychat", archiveDir = "./dist/", docsLink = "TODO", withPRNotify = "false", ) private object InlineHelp : WPComPluginBuild( buildId = "WPComPlugins_InlineHelp", buildName = "Inline Help", pluginSlug = "inline-help", archiveDir = "./dist/", docsLink = "TODO", withPRNotify = "false", ) private object GutenbergUploadSourceMapsToSentry: BuildType() { init { name = "Upload Source Maps"; description = "Uploads sourcemaps for various WordPress.com plugins to Sentry. Often triggered per-comment by a WPCOM post-deploy job."; id("WPComPlugins_GutenbergUploadSourceMapsToSentry"); // Only needed so that we can test the job in different branches. vcs { root(Settings.WpCalypso) cleanCheckout = true } params { text( name = "GUTENBERG_VERSION", value = "", label = "Gutenberg version", description = "The Gutenberg version to upload source maps for (include the whole string, including the `v` prefix)", allowEmpty = false ) } params { text( name = "SENTRY_RELEASE_NAME", value = "", label = "Sentry release name", description = "The WPCOM Sentry release to upload the source-maps to", allowEmpty = false ) } steps { bashNodeScript { name = "Upload Gutenberg source maps to Sentry" scriptContent = """ rm -rf gutenberg gutenberg.zip wget https://github.com/WordPress/gutenberg/releases/download/%GUTENBERG_VERSION%/gutenberg.zip unzip gutenberg.zip -d gutenberg cd gutenberg # Upload the .js and .js.map files to Sentry for the given release. sentry-cli releases files %SENTRY_RELEASE_NAME% upload-sourcemaps . \ --auth-token %SENTRY_AUTH_TOKEN% \ --org a8c \ --project wpcom-gutenberg-wp-admin \ --url-prefix "~/wp-content/plugins/gutenberg-core/%GUTENBERG_VERSION%/" """ } uploadPluginSourceMaps( slug = "editing-toolkit", buildId = "calypso_WPComPlugins_EditorToolKit", buildTag = "etk-release-build", wpcomURL = "~/wp-content/plugins/editing-toolkit-plugin/prod/" ) uploadPluginSourceMaps( slug = "wpcom-block-editor", buildId = "calypso_WPComPlugins_WpcomBlockEditor", wpcomURL = "~/wpcom-block-editor" ) uploadPluginSourceMaps( slug = "notifications", buildId = "calypso_WPComPlugins_Notifications", wpcomURL = "~/notifications" ) } } } // Given the plugin information, get the source code and upload any sourcemaps // to Sentry. fun BuildSteps.uploadPluginSourceMaps( slug: String, buildId: String, wpcomURL: String, buildTag: String = "$slug-release-build", ): ScriptBuildStep { return bashNodeScript { name = "Upload $slug source maps to Sentry" scriptContent = """ rm -rf code code.zip # Downloads the latest release build for the plugin. wget "%teamcity.serverUrl%/repository/download/$buildId/$buildTag.tcbuildtag/$slug.zip?guest=1&branch=trunk" -O ./code.zip unzip -q ./code.zip -d ./code cd code # Upload the .js and .js.map files to Sentry for the given release. sentry-cli releases files %SENTRY_RELEASE_NAME% upload-sourcemaps . \ --auth-token %SENTRY_AUTH_TOKEN% \ --org a8c \ --project wpcom-gutenberg-wp-admin \ --url-prefix "$wpcomURL" """ } }
gpl-2.0
a40441098f375d932612f2a94221bf3a
29.628931
323
0.690862
3.405594
false
false
false
false
Kotlin/kotlinx.serialization
formats/json/nativeMain/src/kotlinx/serialization/json/JsonSchemaCache.kt
1
2272
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.json import kotlinx.serialization.json.internal.* import kotlin.native.ref.* import kotlin.random.* /** * This maps emulate thread-locality of DescriptorSchemaCache for Native. * * Custom JSON instances are considered thread-safe (in JVM) and can be frozen and transferred to different workers (in Native). * Therefore, DescriptorSchemaCache should be either a concurrent freeze-aware map or thread local. * Each JSON instance have it's own schemaCache, and it's impossible to use @ThreadLocal on non-global vals. * Thus we make @ThreadLocal this special map: it provides schemaCache for a particular Json instance * and should be used instead of a member `_schemaCache` on Native. * * To avoid memory leaks (when Json instance is no longer in use), WeakReference is used with periodical self-cleaning. */ @ThreadLocal private val jsonToCache: MutableMap<WeakJson, DescriptorSchemaCache> = mutableMapOf() /** * Because WeakReference itself does not have proper equals/hashCode */ private class WeakJson(json: Json) { private val ref = WeakReference(json) private val initialHashCode = json.hashCode() val isDead: Boolean get() = ref.get() == null override fun equals(other: Any?): Boolean { if (other !is WeakJson) return false val thiz = this.ref.get() ?: return false val that = other.ref.get() ?: return false return thiz == that } override fun hashCode(): Int = initialHashCode } /** * To maintain O(1) access, we cleanup the table from dead references with 1/size probability */ private fun cleanUpWeakMap() { val size = jsonToCache.size if (size <= 10) return // 10 is arbitrary small number to ignore polluting // Roll 1/size probability if (Random.nextInt(0, size) == 0) { val iter = jsonToCache.iterator() while (iter.hasNext()) { if (iter.next().key.isDead) iter.remove() } } } /** * Accessor for DescriptorSchemaCache */ internal actual val Json.schemaCache: DescriptorSchemaCache get() = jsonToCache.getOrPut(WeakJson(this)) { DescriptorSchemaCache() }.also { cleanUpWeakMap() }
apache-2.0
94879142ebd992def6cf718b43d5f073
35.063492
128
0.711268
4.238806
false
false
false
false
LISTEN-moe/android-app
app/src/main/kotlin/me/echeung/moemoekyun/ui/common/Toolbar.kt
1
1153
package me.echeung.moemoekyun.ui.common import android.app.Activity import androidx.annotation.StringRes import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import me.echeung.moemoekyun.R @Composable fun Toolbar( @StringRes titleResId: Int, showUpButton: Boolean = false, ) { val context = LocalContext.current TopAppBar( title = { Text(text = stringResource(titleResId)) }, navigationIcon = { if (showUpButton) { IconButton(onClick = { (context as? Activity)?.finish() }) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = stringResource(R.string.action_back), ) } } }, ) }
mit
6c5af8d3683ebf3f3274dacfb82cb7a2
29.342105
82
0.661752
4.784232
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/duchy/deploy/common/server/ComputationsServer.kt
1
5189
// Copyright 2020 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.duchy.deploy.common.server import io.grpc.ManagedChannel import java.time.Duration import org.wfanet.measurement.common.crypto.SigningCerts import org.wfanet.measurement.common.grpc.CommonServer import org.wfanet.measurement.common.grpc.buildMutualTlsChannel import org.wfanet.measurement.common.grpc.withShutdownTimeout import org.wfanet.measurement.common.identity.DuchyInfoFlags import org.wfanet.measurement.common.identity.withDuchyId import org.wfanet.measurement.duchy.db.computation.ComputationProtocolStageDetailsHelper import org.wfanet.measurement.duchy.db.computation.ComputationProtocolStagesEnumHelper import org.wfanet.measurement.duchy.db.computation.ComputationsDatabase import org.wfanet.measurement.duchy.db.computation.ComputationsDatabaseReader import org.wfanet.measurement.duchy.db.computation.ComputationsDatabaseTransactor import org.wfanet.measurement.duchy.deploy.common.CommonDuchyFlags import org.wfanet.measurement.duchy.deploy.common.SystemApiFlags import org.wfanet.measurement.duchy.service.internal.computations.ComputationsService import org.wfanet.measurement.duchy.service.internal.computationstats.ComputationStatsService import org.wfanet.measurement.internal.duchy.ComputationDetails import org.wfanet.measurement.internal.duchy.ComputationStage import org.wfanet.measurement.internal.duchy.ComputationStageDetails import org.wfanet.measurement.internal.duchy.ComputationTypeEnum.ComputationType import org.wfanet.measurement.system.v1alpha.ComputationLogEntriesGrpcKt.ComputationLogEntriesCoroutineStub import picocli.CommandLine private typealias ComputationsDb = ComputationsDatabaseTransactor< ComputationType, ComputationStage, ComputationStageDetails, ComputationDetails > /** gRPC server for Computations service. */ abstract class ComputationsServer : Runnable { @CommandLine.Mixin protected lateinit var flags: Flags private set abstract val protocolStageEnumHelper: ComputationProtocolStagesEnumHelper<ComputationType, ComputationStage> abstract val computationProtocolStageDetails: ComputationProtocolStageDetailsHelper< ComputationType, ComputationStage, ComputationStageDetails, ComputationDetails > protected fun run( computationsDatabaseReader: ComputationsDatabaseReader, computationDb: ComputationsDb ) { val clientCerts = SigningCerts.fromPemFiles( certificateFile = flags.server.tlsFlags.certFile, privateKeyFile = flags.server.tlsFlags.privateKeyFile, trustedCertCollectionFile = flags.server.tlsFlags.certCollectionFile ) val channel: ManagedChannel = buildMutualTlsChannel(flags.systemApiFlags.target, clientCerts, flags.systemApiFlags.certHost) .withShutdownTimeout(flags.channelShutdownTimeout) val computationLogEntriesClient = ComputationLogEntriesCoroutineStub(channel).withDuchyId(flags.duchy.duchyName) val computationsDatabase = newComputationsDatabase(computationsDatabaseReader, computationDb) CommonServer.fromFlags( flags.server, javaClass.name, ComputationsService( computationsDatabase = computationsDatabase, computationLogEntriesClient = computationLogEntriesClient, duchyName = flags.duchy.duchyName ), ComputationStatsService(computationsDatabase) ) .start() .blockUntilShutdown() } private fun newComputationsDatabase( computationsDatabaseReader: ComputationsDatabaseReader, computationDb: ComputationsDb ): ComputationsDatabase { return object : ComputationsDatabase, ComputationsDatabaseReader by computationsDatabaseReader, ComputationsDb by computationDb, ComputationProtocolStagesEnumHelper< ComputationType, ComputationStage > by protocolStageEnumHelper {} } protected class Flags { @CommandLine.Mixin lateinit var server: CommonServer.Flags private set @CommandLine.Mixin lateinit var duchy: CommonDuchyFlags private set @CommandLine.Mixin lateinit var duchyInfo: DuchyInfoFlags private set @CommandLine.Option( names = ["--channel-shutdown-timeout"], defaultValue = "3s", description = ["How long to allow for the gRPC channel to shutdown."], required = true ) lateinit var channelShutdownTimeout: Duration private set @CommandLine.Mixin lateinit var systemApiFlags: SystemApiFlags private set } companion object { const val SERVICE_NAME = "Computations" } }
apache-2.0
eb83bf2002cace13bd71478d60250be9
37.723881
107
0.788977
5.102262
false
false
false
false
cfig/Android_boot_image_editor
bbootimg/src/main/kotlin/bootimg/v2/BootHeaderV2.kt
1
6482
// Copyright 2021 [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 cfig.bootimg.v2 import cc.cfig.io.Struct import cfig.helper.Helper import cfig.bootimg.Common import org.slf4j.LoggerFactory import java.io.InputStream import kotlin.math.pow open class BootHeaderV2( var kernelLength: Int = 0, var kernelOffset: Long = 0L, //UInt var ramdiskLength: Int = 0, var ramdiskOffset: Long = 0L, //UInt var secondBootloaderLength: Int = 0, var secondBootloaderOffset: Long = 0L, //UInt var recoveryDtboLength: Int = 0, var recoveryDtboOffset: Long = 0L,//Q var dtbLength: Int = 0, var dtbOffset: Long = 0L,//Q var tagsOffset: Long = 0L, //UInt var pageSize: Int = 0, var headerSize: Int = 0, var headerVersion: Int = 0, var board: String = "", var cmdline: String = "", var hash: ByteArray? = null, var osVersion: String? = null, var osPatchLevel: String? = null) { @Throws(IllegalArgumentException::class) constructor(iS: InputStream?) : this() { if (iS == null) { return } log.warn("BootImgHeader constructor") val info = Struct(FORMAT_STRING).unpack(iS) check(20 == info.size) if (info[0] != magic) { throw IllegalArgumentException("stream doesn't look like Android Boot Image Header") } this.kernelLength = (info[1] as UInt).toInt() this.kernelOffset = (info[2] as UInt).toLong() this.ramdiskLength = (info[3] as UInt).toInt() this.ramdiskOffset = (info[4] as UInt).toLong() this.secondBootloaderLength = (info[5] as UInt).toInt() this.secondBootloaderOffset = (info[6] as UInt).toLong() this.tagsOffset = (info[7] as UInt).toLong() this.pageSize = (info[8] as UInt).toInt() this.headerVersion = (info[9] as UInt).toInt() val osNPatch = info[10] as UInt if (0U != osNPatch) { //treated as 'reserved' in this boot image this.osVersion = Common.parseOsVersion(osNPatch.toInt() shr 11) this.osPatchLevel = Common.parseOsPatchLevel((osNPatch and 0x7ff.toUInt()).toInt()) } this.board = info[11] as String this.cmdline = (info[12] as String) + (info[14] as String) this.hash = info[13] as ByteArray if (this.headerVersion > 0) { this.recoveryDtboLength = (info[15] as UInt).toInt() this.recoveryDtboOffset = (info[16] as ULong).toLong() } this.headerSize = (info[17] as UInt).toInt() check(this.headerSize.toInt() in intArrayOf(BOOT_IMAGE_HEADER_V2_SIZE, BOOT_IMAGE_HEADER_V1_SIZE, BOOT_IMAGE_HEADER_V0_SIZE)) { "header size ${this.headerSize} illegal" } if (this.headerVersion > 1) { this.dtbLength = (info[18] as UInt).toInt() this.dtbOffset = (info[19] as ULong).toLong() } } private fun get_recovery_dtbo_offset(): Long { return Helper.round_to_multiple(this.headerSize.toLong(), pageSize.toLong()) + Helper.round_to_multiple(this.kernelLength, pageSize) + Helper.round_to_multiple(this.ramdiskLength, pageSize) + Helper.round_to_multiple(this.secondBootloaderLength, pageSize) } fun encode(): ByteArray { val pageSizeChoices: MutableSet<Long> = mutableSetOf<Long>().apply { (11..14).forEach { add(2.0.pow(it).toLong()) } } check(pageSizeChoices.contains(pageSize.toLong())) { "invalid parameter [pageSize=$pageSize], (choose from $pageSizeChoices)" } return Struct(FORMAT_STRING).pack( magic, //10I kernelLength, kernelOffset, ramdiskLength, ramdiskOffset, secondBootloaderLength, secondBootloaderOffset, tagsOffset, pageSize, headerVersion, (Common.packOsVersion(osVersion) shl 11) or Common.packOsPatchLevel(osPatchLevel), //16s board, //512s cmdline.substring(0, minOf(512, cmdline.length)), //32b hash!!, //1024s if (cmdline.length > 512) cmdline.substring(512) else "", //I recoveryDtboLength, //Q if (headerVersion > 0) recoveryDtboOffset else 0, //I when (headerVersion) { 0 -> BOOT_IMAGE_HEADER_V0_SIZE 1 -> BOOT_IMAGE_HEADER_V1_SIZE 2 -> BOOT_IMAGE_HEADER_V2_SIZE else -> java.lang.IllegalArgumentException("headerVersion $headerVersion illegal") }, //I dtbLength, //Q if (headerVersion > 1) dtbOffset else 0 ) } companion object { internal val log = LoggerFactory.getLogger(BootHeaderV2::class.java) const val magic = "ANDROID!" const val FORMAT_STRING = "8s" + //"ANDROID!" "10I" + "16s" + //board name "512s" + //cmdline part 1 "32b" + //hash digest "1024s" + //cmdline part 2 "I" + //dtbo length [v1] "Q" + //dtbo offset [v1] "I" + //header size [v1] "I" + //dtb length [v2] "Q" //dtb offset [v2] const val BOOT_IMAGE_HEADER_V2_SIZE = 1660 const val BOOT_IMAGE_HEADER_V1_SIZE = 1648 const val BOOT_IMAGE_HEADER_V0_SIZE = 0 init { check(BOOT_IMAGE_HEADER_V2_SIZE == Struct(FORMAT_STRING).calcSize()) } } }
apache-2.0
0272faedee0a5e48ed3a634648cb964a
36.252874
135
0.558315
4.149808
false
false
false
false
debop/debop4k
debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/timeranges/WeekRangeCollection.kt
1
1716
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package debop4k.timeperiod.timeranges import debop4k.core.kodatimes.today import debop4k.timeperiod.DefaultTimeCalendar import debop4k.timeperiod.ITimeCalendar import debop4k.timeperiod.utils.startTimeOfWeek import debop4k.timeperiod.utils.weekRangeSequence import org.joda.time.DateTime /** * Created by debop */ open class WeekRangeCollection @JvmOverloads constructor(startTime: DateTime = today(), weekCount: Int = 1, calendar: ITimeCalendar = DefaultTimeCalendar) : WeekTimeRange(startTime.startTimeOfWeek(), weekCount, calendar) { @JvmOverloads constructor(weekyear: Int, weekOfWeekyear: Int, weekCount: Int = 1, calendar: ITimeCalendar = DefaultTimeCalendar) : this(startTimeOfWeek(weekyear, weekOfWeekyear), weekCount, calendar) fun weekSequence(): Sequence<WeekRange> { return weekRangeSequence(start, weekCount, calendar) } fun weeks(): List<WeekRange> { return weekSequence().toList() } }
apache-2.0
8e7f9ec32fb436f124baccd513da2323
34.040816
103
0.69697
4.515789
false
false
false
false
faceofcat/Tesla-Powered-Thingies
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/fluidburner/FluidBurnerCategory.kt
1
4015
package net.ndrei.teslapoweredthingies.machines.fluidburner import com.google.common.collect.Lists import mezz.jei.api.IModRegistry import mezz.jei.api.gui.IDrawable import mezz.jei.api.gui.IRecipeLayout import mezz.jei.api.ingredients.IIngredients import mezz.jei.api.recipe.IRecipeCategoryRegistration import mezz.jei.api.recipe.IRecipeWrapper import net.minecraft.client.Minecraft import net.minecraftforge.fluids.FluidStack import net.minecraftforge.fml.relauncher.Side import net.minecraftforge.fml.relauncher.SideOnly import net.ndrei.teslapoweredthingies.client.ThingiesTexture import net.ndrei.teslapoweredthingies.integrations.jei.BaseCategory import net.ndrei.teslapoweredthingies.integrations.jei.TeslaThingyJeiCategory /** * Created by CF on 2017-06-30. */ @TeslaThingyJeiCategory object FluidBurnerCategory : BaseCategory<FluidBurnerCategory.FluidBurnerRecipeWrapper>(FluidBurnerBlock) { private lateinit var fuelOverlay: IDrawable private lateinit var coolantOverlay: IDrawable override fun setRecipe(recipeLayout: IRecipeLayout, recipeWrapper: FluidBurnerRecipeWrapper, ingredients: IIngredients) { val fluids = recipeLayout.fluidStacks val capacity = if (recipeWrapper.coolant != null) Math.max(recipeWrapper.fuel.fluid.amount, recipeWrapper.coolant.fluid.amount) else recipeWrapper.fuel.fluid.amount fluids.init(0, true, 8, 8, 8, 27, capacity, false, fuelOverlay) fluids.set(0, ingredients.getInputs(FluidStack::class.java)[0]) if (ingredients.getInputs(FluidStack::class.java).size == 2) { fluids.init(1, true, 20, 8, 8, 27, capacity, false, coolantOverlay) fluids.set(1, ingredients.getInputs(FluidStack::class.java)[1]) } } class FluidBurnerRecipeWrapper(val fuel: FluidBurnerFuelRecipe, val coolant: FluidBurnerCoolantRecipe?) : IRecipeWrapper { override fun getIngredients(ingredients: IIngredients) { if (this.coolant == null) { ingredients.setInput(FluidStack::class.java, FluidStack(this.fuel.fluid, this.fuel.fluid.amount)) } else { ingredients.setInputs(FluidStack::class.java, Lists.newArrayList( FluidStack(this.fuel.fluid, this.fuel.fluid.amount), FluidStack(this.coolant.fluid, this.coolant.fluid.amount) )) } } @SideOnly(Side.CLIENT) override fun drawInfo(minecraft: Minecraft, recipeWidth: Int, recipeHeight: Int, mouseX: Int, mouseY: Int) { super.drawInfo(minecraft, recipeWidth, recipeHeight, mouseX, mouseY) var ticks = this.fuel.baseTicks if (this.coolant != null) ticks = Math.round(ticks.toFloat() * this.coolant.timeMultiplier) val duration = String.format("%,d ticks", ticks) val power = String.format("%,d T", ticks * 80) minecraft.fontRenderer.drawString(duration, 36, 12, 0x007F7F) minecraft.fontRenderer.drawString(power, 36, 12 + minecraft.fontRenderer.FONT_HEIGHT, 0x007F7F) } } override fun register(registry: IRecipeCategoryRegistration) { super.register(registry) this.recipeBackground = this.guiHelper.createDrawable(ThingiesTexture.JEI_TEXTURES.resource, 0, 66, 124, 66) fuelOverlay = this.guiHelper.createDrawable(ThingiesTexture.JEI_TEXTURES.resource, 8, 74, 8, 27) coolantOverlay = this.guiHelper.createDrawable(ThingiesTexture.JEI_TEXTURES.resource, 20, 74, 8, 27) } override fun register(registry: IModRegistry) { super.register(registry) val recipes = Lists.newArrayList<FluidBurnerRecipeWrapper>() for (fuel in FluidBurnerRecipes.fuels) { recipes.add(FluidBurnerRecipeWrapper(fuel, null)) FluidBurnerRecipes.coolants.mapTo(recipes) { FluidBurnerRecipeWrapper(fuel, it) } } registry.addRecipes(recipes, this.uid) } }
mit
517a1b7f122a21ac9d33637abfcb9361
43.611111
125
0.703362
4.284952
false
false
false
false
FHannes/intellij-community
platform/projectModel-api/src/com/intellij/util/jdom.kt
2
4732
/* * 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.util import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.reference.SoftReference import com.intellij.util.io.inputStream import com.intellij.util.io.outputStream import com.intellij.util.text.CharSequenceReader import org.jdom.Document import org.jdom.Element import org.jdom.JDOMException import org.jdom.Parent import org.jdom.filter.ElementFilter import org.jdom.input.SAXBuilder import org.jdom.input.SAXHandler import org.xml.sax.EntityResolver import org.xml.sax.InputSource import org.xml.sax.XMLReader import java.io.* import java.nio.file.Path import javax.xml.XMLConstants private val cachedSaxBuilder = ThreadLocal<SoftReference<SAXBuilder>>() private fun getSaxBuilder(): SAXBuilder { val reference = cachedSaxBuilder.get() var saxBuilder = SoftReference.dereference<SAXBuilder>(reference) if (saxBuilder == null) { saxBuilder = object : SAXBuilder() { override fun configureParser(parser: XMLReader, contentHandler: SAXHandler?) { super.configureParser(parser, contentHandler) try { parser.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) } catch (ignore: Exception) { } } } saxBuilder.ignoringBoundaryWhitespace = true saxBuilder.ignoringElementContentWhitespace = true saxBuilder.entityResolver = EntityResolver { publicId, systemId -> InputSource(CharArrayReader(ArrayUtil.EMPTY_CHAR_ARRAY)) } cachedSaxBuilder.set(SoftReference<SAXBuilder>(saxBuilder)) } return saxBuilder } @JvmOverloads @Throws(IOException::class) fun Parent.write(file: Path, lineSeparator: String = "\n") { write(file.outputStream(), lineSeparator) } @JvmOverloads fun Parent.write(output: OutputStream, lineSeparator: String = "\n") { output.bufferedWriter().use { writer -> if (this is Document) { JDOMUtil.writeDocument(this, writer, lineSeparator) } else { JDOMUtil.writeElement(this as Element, writer, lineSeparator) } } } @Throws(IOException::class, JDOMException::class) fun loadElement(chars: CharSequence) = loadElement(CharSequenceReader(chars)) @Throws(IOException::class, JDOMException::class) fun loadElement(reader: Reader): Element = loadDocument(reader).detachRootElement() @Throws(IOException::class, JDOMException::class) fun loadElement(stream: InputStream): Element = loadDocument(stream.reader()).detachRootElement() @Throws(IOException::class, JDOMException::class) fun loadElement(path: Path): Element = loadDocument(path.inputStream().bufferedReader()).detachRootElement() fun loadDocument(reader: Reader): Document = reader.use { getSaxBuilder().build(it) } fun Element?.isEmpty() = this == null || JDOMUtil.isEmpty(this) fun Element.getOrCreate(name: String): Element { var element = getChild(name) if (element == null) { element = Element(name) addContent(element) } return element } fun Element.get(name: String): Element? = getChild(name) fun Element.element(name: String): Element { val element = Element(name) addContent(element) return element } fun Element.attribute(name: String, value: String?): Element = setAttribute(name, value) fun <T> Element.remove(name: String, transform: (child: Element) -> T): List<T> { val result = SmartList<T>() val groupIterator = getContent(ElementFilter(name)).iterator() while (groupIterator.hasNext()) { val child = groupIterator.next() result.add(transform(child)) groupIterator.remove() } return result } fun Element.toByteArray(): ByteArray { val out = BufferExposingByteArrayOutputStream(512) JDOMUtil.write(this, out, "\n") return out.toByteArray() } fun Element.addOptionTag(name: String, value: String) { val element = Element("option") element.setAttribute("name", name) element.setAttribute("value", value) addContent(element) } fun Parent.toBufferExposingByteArray(lineSeparator: String = "\n"): BufferExposingByteArrayOutputStream { val out = BufferExposingByteArrayOutputStream(512) JDOMUtil.write(this, out, lineSeparator) return out }
apache-2.0
39cb0179de7948a953d83b57debe5cd5
32.097902
129
0.750634
4.198758
false
false
false
false
google/modernstorage
sample/src/main/java/com/google/modernstorage/sample/mediastore/AddMediaScreen.kt
1
7309
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.modernstorage.sample.mediastore import androidx.activity.compose.rememberLauncherForActivityResult import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.AlertDialog import androidx.compose.material.Button import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import com.google.modernstorage.permissions.RequestAccess import com.google.modernstorage.permissions.StoragePermissions import com.google.modernstorage.sample.Demos import com.google.modernstorage.sample.HomeRoute import com.google.modernstorage.sample.R import com.google.modernstorage.sample.mediastore.MediaStoreViewModel.MediaType import com.google.modernstorage.sample.ui.shared.MediaPreviewCard import kotlinx.coroutines.launch @ExperimentalFoundationApi @Composable fun AddMediaScreen(navController: NavController, viewModel: MediaStoreViewModel = viewModel()) { val addedFile by viewModel.addedFile.collectAsState() var openPermissionDialog by remember { mutableStateOf(false) } val scope = rememberCoroutineScope() val scaffoldState = rememberScaffoldState() val permissions = StoragePermissions(LocalContext.current) val toastMessage = stringResource(R.string.authorization_dialog_success_toast) val requestPermission = rememberLauncherForActivityResult(RequestAccess()) { hasAccess -> if (hasAccess) { scope.launch { scaffoldState.snackbarHostState.showSnackbar(toastMessage) } } } if (openPermissionDialog) { AlertDialog( title = { Text(stringResource(R.string.authorization_dialog_title)) }, text = { Text(stringResource(R.string.authorization_dialog_add_files_description)) }, confirmButton = { TextButton( onClick = { openPermissionDialog = false requestPermission.launch( RequestAccess.Args( action = StoragePermissions.Action.READ_AND_WRITE, types = listOf(StoragePermissions.FileType.Document), createdBy = StoragePermissions.CreatedBy.Self ) ) } ) { Text(stringResource(R.string.authorization_dialog_confirm_label)) } }, onDismissRequest = { openPermissionDialog = false }, dismissButton = { TextButton(onClick = { openPermissionDialog = false }) { Text(stringResource(R.string.authorization_dialog_cancel_label)) } } ) } fun checkAndRequestStoragePermission(onSuccess: () -> Unit) { val isGranted = permissions.hasAccess( action = StoragePermissions.Action.READ_AND_WRITE, types = listOf( StoragePermissions.FileType.Image, StoragePermissions.FileType.Video, StoragePermissions.FileType.Audio ), createdBy = StoragePermissions.CreatedBy.Self ) if (isGranted) { onSuccess() } else { openPermissionDialog = true } } Scaffold( scaffoldState = scaffoldState, topBar = { TopAppBar( title = { Text(stringResource(Demos.AddMedia.name)) }, navigationIcon = { IconButton(onClick = { navController.popBackStack(HomeRoute, false) }) { Icon( Icons.Filled.ArrowBack, contentDescription = stringResource(R.string.back_button_label) ) } } ) }, content = { paddingValues -> LazyColumn(Modifier.padding(paddingValues)) { item { Button( modifier = Modifier .padding(4.dp) .fillMaxWidth(), onClick = { checkAndRequestStoragePermission { viewModel.addMedia(MediaType.IMAGE) } } ) { Text(stringResource(R.string.demo_add_image_label)) } } item { Button( modifier = Modifier .padding(4.dp) .fillMaxWidth(), onClick = { checkAndRequestStoragePermission { viewModel.addMedia(MediaType.VIDEO) } } ) { Text(stringResource(R.string.demo_add_video_label)) } } item { Button( modifier = Modifier .padding(4.dp) .fillMaxWidth(), onClick = { checkAndRequestStoragePermission { viewModel.addMedia(MediaType.AUDIO) } } ) { Text(stringResource(R.string.demo_add_audio_label)) } } addedFile?.let { item { MediaPreviewCard(it) } } } } ) }
apache-2.0
3cd8a9c533a4cec653086a93062ca7d4
38.722826
100
0.591052
5.773302
false
false
false
false
grassrootza/grassroot-android-v2
app/src/main/kotlin/za/org/grassroot2/view/fragment/MeFragment.kt
1
9663
package za.org.grassroot2.view.fragment import android.Manifest import android.app.Activity import android.content.Intent import android.graphics.drawable.BitmapDrawable import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI import android.support.v4.app.Fragment import android.support.v4.graphics.drawable.RoundedBitmapDrawable import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory import android.support.v7.app.AppCompatActivity import android.support.v7.widget.PopupMenu import android.text.Editable import android.text.TextWatcher import android.view.* import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import android.widget.ArrayAdapter import com.squareup.picasso.Callback import com.squareup.picasso.Picasso import com.tbruyelle.rxpermissions2.RxPermissions import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.fragment_me.* import timber.log.Timber import za.org.grassroot2.BuildConfig import za.org.grassroot2.R import za.org.grassroot2.dagger.activity.ActivityComponent import za.org.grassroot2.model.UserProfile import za.org.grassroot2.presenter.MePresenter import za.org.grassroot2.view.MeView import za.org.grassroot2.view.activity.WelcomeActivity import javax.inject.Inject class MeFragment : GrassrootFragment(), MeView { override val layoutResourceId: Int get() = R.layout.fragment_me @Inject lateinit var presenter: MePresenter @Inject lateinit var rxPermission: RxPermissions private lateinit var languagesAdapter: ArrayAdapter<Language> private val dataChangeWatcher = ProfileDataChangeWatcher() override fun onInject(activityComponent: ActivityComponent) = get().inject(this) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { Timber.e("Creating me fragment view ..."); progress = activity!!.findViewById(R.id.progress) return inflater.inflate(layoutResourceId, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) profilePhoto.setOnClickListener { showPopup(profilePhoto) } changePhoto.setOnClickListener { showPopup(changePhoto) } initToolbar() displayNameInput.addTextChangedListener(dataChangeWatcher) phoneNumberInput.addTextChangedListener(dataChangeWatcher) emailInput.addTextChangedListener(dataChangeWatcher) languageInput.onItemSelectedListener = dataChangeWatcher saveBtn.setOnClickListener { val language = languageInput.selectedItem as Language? val languageCode = language?.code ?: "en" presenter.updateProfileData( displayNameInput.text.toString(), phoneNumberInput.text.toString(), emailInput.text.toString(), languageCode ) } presenter.attach(this) presenter.onViewCreated() } private fun initToolbar() { toolbar.inflateMenu(R.menu.fragment_me); toolbar.setTitle(R.string.title_me) toolbar.setOnMenuItemClickListener { item -> if (item?.itemId == R.id.menu_logout) presenter.logout() super.onOptionsItemSelected(item) } } override fun onResume() { super.onResume() Timber.e("resuming fragment, invalidating options menu") (activity as AppCompatActivity).invalidateOptionsMenu() } private fun showPopup(v: View) { val popup = PopupMenu(activity!!, v) val inflater = popup.menuInflater inflater.inflate(R.menu.change_image_options, popup.menu) popup.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.fromGallery -> presenter.pickFromGallery() R.id.useCamera -> presenter.takePhoto() } true } popup.show() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { Timber.d("Showing solitary progress bar in MeFragment") showProgressBar() if (resultCode == Activity.RESULT_OK) { if (requestCode == REQUEST_TAKE_PHOTO) { presenter.cameraResult() } else { presenter.handlePickResult(data!!.data) } } } override fun ensureWriteExteralStoragePermission(): Observable<Boolean> { return rxPermission.request(Manifest.permission.WRITE_EXTERNAL_STORAGE) } override fun displayUserData(profile: UserProfile) { displayNameInput.setText(profile.displayName) phoneNumberInput.setText(profile.msisdn) emailInput.setText(profile.emailAddress) val languageObservable = presenter.getLanguages() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { languageMap -> val langaugeList = languageMap.toList().map { Language(it.first, it.second) } var selectedPosition = 0 for ((index, lang) in langaugeList.withIndex()) { if (lang.code == profile.languageCode) selectedPosition = index } languagesAdapter = ArrayAdapter(activity, R.layout.item_language, langaugeList) languageInput.adapter = languagesAdapter languageInput.setSelection(selectedPosition) }, { Timber.e(it) } ) presenter.addDisposableOnDetach(languageObservable) loadProfilePic(profile.uid) submitActions.visibility = View.INVISIBLE } override fun invalidateProfilePicCache(userUid: String) { val url = BuildConfig.API_BASE + "v2/api/image/user/" + userUid Picasso.get().invalidate(url) loadProfilePic(userUid) } private fun loadProfilePic(userUid: String) { val url = BuildConfig.API_BASE + "v2/api/image/user/" + userUid Timber.d("Fetching user image profile: %s", url) Picasso.get() .load(url) .resizeDimen(R.dimen.profile_photo_width, R.dimen.profile_photo_height) .placeholder(R.drawable.user) .error(R.drawable.user) .centerCrop() .into(profilePhoto, object : Callback { override fun onSuccess() { val imageBitmap = (profilePhoto.drawable as BitmapDrawable).bitmap val imageDrawable: RoundedBitmapDrawable = RoundedBitmapDrawableFactory.create(resources, imageBitmap) imageDrawable.isCircular = true imageDrawable.cornerRadius = Math.max(imageBitmap.width, imageBitmap.height) / 2.0f profilePhoto.setImageDrawable(imageDrawable) } override fun onError(e: Exception?) { profilePhoto?.setImageResource(R.drawable.user) } }) } override fun onDestroyView() { super.onDestroyView() presenter.detach(this) } override fun cameraForResult(contentProviderPath: String, s: String) { val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse(contentProviderPath)) cameraIntent.putExtra("MY_UID", s) startActivityForResult(cameraIntent, REQUEST_TAKE_PHOTO) } override fun pickFromGallery() { val intent = Intent(Intent.ACTION_PICK, EXTERNAL_CONTENT_URI) intent.type = "image/*" startActivityForResult(intent, REQUEST_GALLERY) } companion object { private const val REQUEST_TAKE_PHOTO = 1 private const val REQUEST_GALLERY = 2 fun newInstance(): Fragment { return MeFragment() } } inner class ProfileDataChangeWatcher : TextWatcher, OnItemSelectedListener { override fun afterTextChanged(p0: Editable?) {} override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { submitActions.visibility = View.VISIBLE } override fun onNothingSelected(p0: AdapterView<*>?) {} override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, p3: Long) { val selectedLanguage = languagesAdapter.getItem(position) if (selectedLanguage == null || !presenter.isCurrentLanguage(selectedLanguage.code)) submitActions.visibility = View.VISIBLE } } class Language(val code: String, val name: String) { override fun toString(): String { return name } } override fun returnToWelcomeActivity() { val intent = Intent(context, WelcomeActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK startActivity(intent) activity?.finish() } }
bsd-3-clause
bafc9f8963eb80776e4e193b98738995
36.02682
126
0.644313
5.109995
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/test/org/videolan/vlc/repository/ExternalSubRepositoryTest.kt
1
7212
/******************************************************************************* * ExternalSubRepositoryTest.kt * **************************************************************************** * Copyright © 2018 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.repository import android.net.Uri import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.MutableLiveData import kotlinx.coroutines.runBlocking import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.hasItem import org.hamcrest.MatcherAssert.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith import org.mockito.ArgumentMatchers import org.mockito.Mockito.* import org.powermock.api.mockito.PowerMockito import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner import org.videolan.vlc.database.ExternalSubDao import org.videolan.vlc.database.MediaDatabase import org.videolan.vlc.mediadb.models.ExternalSub import org.videolan.vlc.util.* @RunWith(PowerMockRunner::class) @PrepareForTest(Uri::class) class ExternalSubRepositoryTest { private val externalSubDao = mock<ExternalSubDao>() private lateinit var externalSubRepository: ExternalSubRepository @Rule @JvmField val instantExecutorRule = InstantTaskExecutorRule() @Rule @JvmField var temp = TemporaryFolder() @Before fun init() { val db = mock<MediaDatabase>() `when`(db.externalSubDao()).thenReturn(externalSubDao) externalSubRepository = ExternalSubRepository(externalSubDao) } @Test fun saveTwoSubtitleForTwoMedia_GetShouldReturnZero() = runBlocking { val foo = "/storage/emulated/foo.mkv" val bar = "/storage/emulated/bar.mkv" val fakeFooSubtitles = TestUtil.createExternalSubsForMedia(foo, "foo", 2) val fakeBarSubtitles = TestUtil.createExternalSubsForMedia(bar, "bar", 2) fakeFooSubtitles.forEach { externalSubRepository.saveDownloadedSubtitle(it.idSubtitle, it.subtitlePath, it.mediaPath, it.subLanguageID, it.movieReleaseName) } fakeBarSubtitles.forEach { externalSubRepository.saveDownloadedSubtitle(it.idSubtitle, it.subtitlePath, it.mediaPath, it.subLanguageID, it.movieReleaseName) } PowerMockito.mockStatic(Uri::class.java) PowerMockito.`when`<Any>(Uri::class.java, "decode", anyString()).thenAnswer { it.arguments[0] as String } val inserted = argumentCaptor<org.videolan.vlc.mediadb.models.ExternalSub>() verify(externalSubDao, times(4)).insert(inserted.capture() ?: uninitialized()) assertThat(inserted.allValues.size, `is`(4)) assertThat(inserted.allValues, hasItem(fakeFooSubtitles[0])) assertThat(inserted.allValues, hasItem(fakeFooSubtitles[1])) assertThat(inserted.allValues, hasItem(fakeBarSubtitles[0])) assertThat(inserted.allValues, hasItem(fakeBarSubtitles[1])) val fakeFooLiveDataSubtitles = MutableLiveData<List<org.videolan.vlc.mediadb.models.ExternalSub>>() val fakeBarLiveDataSubtitles = MutableLiveData<List<org.videolan.vlc.mediadb.models.ExternalSub>>() fakeFooLiveDataSubtitles.value = fakeFooSubtitles fakeBarLiveDataSubtitles.value = fakeBarSubtitles `when`(externalSubDao.get(foo)).thenReturn(fakeFooLiveDataSubtitles) `when`(externalSubDao.get(bar)).thenReturn(fakeBarLiveDataSubtitles) val fooSubtitles = getValue(externalSubRepository.getDownloadedSubtitles(Uri.parse(foo))) val barSubtitles = getValue(externalSubRepository.getDownloadedSubtitles(Uri.parse(bar))) verify(externalSubDao, times(2)).get(ArgumentMatchers.anyString()) assertThat(fooSubtitles.size, `is`(0)) } @Test fun saveTwoSubtitleForTwoMediaCreateTemporaryFilesForThem_GetShouldReturnTwoForEach() { val foo = "/storage/emulated/foo.mkv" val bar = "/storage/emulated/bar.mkv" val fakeFooSubtitles = (0 until 2).map { val file = temp.newFile("foo.$it.srt") externalSubRepository.saveDownloadedSubtitle("1$it", file.path, foo, "en", "foo" ) TestUtil.createExternalSub("1$it", file.path, foo, "en", "foo") } val fakeBarSubtitles = (0 until 2).map { val file = temp.newFile("bar.$it.srt") externalSubRepository.saveDownloadedSubtitle("2$it", file.path, bar, "en", "bar") TestUtil.createExternalSub("2$it", file.path, bar, "en", "bar") } PowerMockito.mockStatic(Uri::class.java) PowerMockito.`when`<Any>(Uri::class.java, "decode", anyString()).thenAnswer { it.arguments[0] as String } val inserted = argumentCaptor<org.videolan.vlc.mediadb.models.ExternalSub>() verify(externalSubDao, times(4)).insert(inserted.capture() ?: uninitialized()) assertThat(inserted.allValues.size, `is`(4)) assertThat(inserted.allValues, hasItem(fakeFooSubtitles[0])) assertThat(inserted.allValues, hasItem(fakeFooSubtitles[1])) assertThat(inserted.allValues, hasItem(fakeBarSubtitles[0])) assertThat(inserted.allValues, hasItem(fakeBarSubtitles[1])) val fakeFooLiveDataSubtitles = MutableLiveData<List<org.videolan.vlc.mediadb.models.ExternalSub>>() val fakeBarLiveDataSubtitles = MutableLiveData<List<org.videolan.vlc.mediadb.models.ExternalSub>>() fakeFooLiveDataSubtitles.value = fakeFooSubtitles fakeBarLiveDataSubtitles.value = fakeBarSubtitles `when`(externalSubDao.get(foo)).thenReturn(fakeFooLiveDataSubtitles) `when`(externalSubDao.get(bar)).thenReturn(fakeBarLiveDataSubtitles) val fooSubtitles = getValue(externalSubRepository.getDownloadedSubtitles(Uri.parse(foo))) val barSubtitles = getValue(externalSubRepository.getDownloadedSubtitles(Uri.parse(bar))) verify(externalSubDao, times(2)).get(ArgumentMatchers.anyString()) assertThat(fooSubtitles.size, `is`(2)) assertThat(barSubtitles.size, `is`(2)) assertThat(fooSubtitles, hasItem(fakeFooSubtitles[0])) assertThat(fooSubtitles, hasItem(fakeFooSubtitles[1])) assertThat(barSubtitles, hasItem(fakeBarSubtitles[0])) assertThat(barSubtitles, hasItem(fakeBarSubtitles[1])) } }
gpl-2.0
d3fb3c4ce74115e879e449bbd3369c88
45.824675
141
0.709194
4.816967
false
true
false
false
chrislo27/Baristron
src/chrislo27/discordbot/cmd/impl/ServerLockdownCommand.kt
1
2462
/* * 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 chrislo27.discordbot.cmd.impl import chrislo27.discordbot.Bot import chrislo27.discordbot.cmd.Command import chrislo27.discordbot.cmd.CommandContext import chrislo27.discordbot.cmd.HelpData import chrislo27.discordbot.impl.baristron.Permission import chrislo27.discordbot.util.builder import chrislo27.discordbot.util.sendMessage import sx.blah.discord.handle.obj.Permissions import sx.blah.discord.handle.obj.VerificationLevel import sx.blah.discord.util.EmbedBuilder import sx.blah.discord.util.RequestBuffer class ServerLockdownCommand<B : Bot<B>>(permission: Permission, vararg aliases: String) : Command<B>(permission, *aliases) { override fun handle(context: CommandContext<B>) { if (context.guild == null) return if (context.guild.id == "208023865127862272" && context.user.getPermissionsForGuild(context.guild).contains( Permissions.ADMINISTRATOR)) { val newSet = context.channel.guild.everyoneRole.permissions newSet.remove(Permissions.EMBED_LINKS) newSet.remove(Permissions.CREATE_INVITE) newSet.remove(Permissions.ATTACH_FILES) RequestBuffer.request { context.channel.guild.changeVerificationLevel(VerificationLevel.HIGH) context.channel.guild.everyoneRole.changePermissions(newSet) sendMessage(builder(context.channel).withEmbed(EmbedBuilder().withDesc( "Server has been locked down. Verification level is on high, and invites + link embedding" + " " + "disabled.").withColor(255, 0, 0).build())) } } } override fun getHelp(): HelpData { return HelpData( "Locks down D4J. Sets the verification level to HIGH, and revokes link embedding, invite creating, and file attaching from the everyone role.", linkedMapOf("" to "Locks down D4J.")) } }
gpl-3.0
73a9193e55be8e8d1707fb3ba99dac88
41.448276
147
0.745735
3.945513
false
false
false
false
SpineEventEngine/core-java
buildSrc/src/main/kotlin/io/spine/internal/dependency/LicenseReport.kt
2
1674
/* * Copyright 2022, TeamDev. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * 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 io.spine.internal.dependency // https://github.com/jk1/Gradle-License-Report @Suppress("unused") object LicenseReport { private const val version = "1.16" const val lib = "com.github.jk1:gradle-license-report:${version}" object GradlePlugin { const val version = LicenseReport.version const val id = "com.github.jk1.dependency-license-report" const val lib = LicenseReport.lib } }
apache-2.0
2a76be9b4263f6d0b4f5c8d86949ef8c
40.85
73
0.741338
4.227273
false
false
false
false
songzhw/AndroidArchitecture
deprecated/MVI/MVI101/MVI_Client/app/src/main/java/ca/six/mvi/biz/home/HomeModel.kt
1
1118
package ca.six.mvi.biz.home import ca.six.mvi.utils.http.HttpCode import ca.six.mvi.utils.http.HttpEngine import io.reactivex.Flowable import org.json.JSONArray import org.json.JSONObject class HomeModel { fun getTodoList(): Flowable<HomeData> { val flow = HttpEngine().get("http://192.168.2.26:8899/todos") // 取到Flowable<Response> .map { resp -> val responseJson = JSONObject(resp.body()?.string()) val respCode = responseJson.get("code") val isOkay = respCode == HttpCode.OK if (isOkay) { val todoJsonArray = responseJson["todos"] as JSONArray val todoList: List<Todo> = Todo.createWithJsonArray(todoJsonArray) HomeData(todoList) } else { HomeData(RuntimeException("error : code = $respCode")) } } // .startWith(HomeData(isLoading = true)) //TODO .onErrorReturn { error -> HomeData(error) } return flow } }
apache-2.0
7f36cb25502bf14de0f35e930565385b
37.448276
93
0.543986
4.510121
false
false
false
false
didi/DoraemonKit
Android/dokit-mc/src/main/java/com/didichuxing/doraemonkit/kit/mc/oldui/host/HostDoKitView.kt
1
1563
package com.didichuxing.doraemonkit.kit.mc.oldui.host import android.content.Context import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.widget.FrameLayout import com.didichuxing.doraemonkit.kit.core.AbsDoKitView import com.didichuxing.doraemonkit.kit.core.DoKitViewLayoutParams import com.didichuxing.doraemonkit.kit.mc.ui.McPages import com.didichuxing.doraemonkit.kit.mc.utils.McPageUtils import com.didichuxing.doraemonkit.mc.R import com.didichuxing.doraemonkit.util.ConvertUtils /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2021/6/17-14:37 * 描 述: * 修订历史: * ================================================ */ class HostDoKitView : AbsDoKitView() { override fun onCreate(context: Context?) { } override fun onCreateView(context: Context?, rootView: FrameLayout?): View { val view = LayoutInflater.from(context).inflate(R.layout.dk_dokitview_host, rootView, false) return view } override fun onViewCreated(rootView: FrameLayout?) { rootView?.setOnClickListener { McPageUtils.startFragment(McPages.HOST) } } override fun initDokitViewLayoutParams(params: DoKitViewLayoutParams) { params.width = ConvertUtils.dp2px(70.0f) params.height = ConvertUtils.dp2px(70.0f) params.gravity = Gravity.TOP or Gravity.LEFT params.x = ConvertUtils.dp2px(280f) params.y = ConvertUtils.dp2px(25f) } }
apache-2.0
7a00a4b12e0216b05c473df9e5b56987
31.978261
100
0.678312
3.981627
false
false
false
false
pgutkowski/KGraphQL
src/main/kotlin/com/github/pgutkowski/kgraphql/schema/dsl/PropertyDSL.kt
1
2245
package com.github.pgutkowski.kgraphql.schema.dsl import com.github.pgutkowski.kgraphql.Context import com.github.pgutkowski.kgraphql.schema.model.FunctionWrapper import com.github.pgutkowski.kgraphql.schema.model.InputValueDef import com.github.pgutkowski.kgraphql.schema.model.PropertyDef import java.lang.IllegalArgumentException class PropertyDSL<T : Any, R>(val name : String, block : PropertyDSL<T, R>.() -> Unit) : LimitedAccessItemDSL<T>(), ResolverDSL.Target { init { block() } internal lateinit var functionWrapper : FunctionWrapper<R> private val inputValues = mutableListOf<InputValueDef<*>>() private fun resolver(function: FunctionWrapper<R>): ResolverDSL { functionWrapper = function return ResolverDSL(this) } fun resolver(function: (T) -> R) = resolver(FunctionWrapper.on(function, true)) fun <E>resolver(function: (T, E) -> R) = resolver(FunctionWrapper.on(function, true)) fun <E, W>resolver(function: (T, E, W) -> R) = resolver(FunctionWrapper.on(function, true)) fun <E, W, Q>resolver(function: (T, E, W, Q) -> R) = resolver(FunctionWrapper.on(function, true)) fun <E, W, Q, A>resolver(function: (T, E, W, Q, A) -> R) = resolver(FunctionWrapper.on(function, true)) fun <E, W, Q, A, S>resolver(function: (T, E, W, Q, A, S) -> R) = resolver(FunctionWrapper.on(function, true)) fun accessRule(rule: (T, Context) -> Exception?){ val accessRuleAdapter: (T?, Context) -> Exception? = { parent, ctx -> if (parent != null) rule(parent, ctx) else IllegalArgumentException("Unexpected null parent of kotlin property") } this.accessRuleBlock = accessRuleAdapter } fun toKQLProperty() = PropertyDef.Function<T, R>( name = name, resolver = functionWrapper, description = description, isDeprecated = isDeprecated, deprecationReason = deprecationReason, inputValues = inputValues, accessRule = accessRuleBlock ) override fun addInputValues(inputValues: Collection<InputValueDef<*>>) { this.inputValues.addAll(inputValues) } }
mit
d85666c61fd88f002c7f8b611b392810
33.553846
136
0.649443
4.243856
false
false
false
false
sungmin-park/Klask
src/main/kotlin/com/klask/urlfor.kt
1
575
package com.klask.urlfor import com.klask.currentApp import java.util.regex.Pattern fun buildUrl(rule: String, values: Array<out Pair<String, Any>>): String { val residual = values.toArrayList() val url = rule.replaceAll("<([^>:]+)(:[^>]+)?>") { it.group(1) val pair = residual.first { i -> i.first == it.group(1) } residual.remove(pair) pair.second.toString() } return url } public fun urlfor(endpoint: String, vararg values: Pair<String, Any>): String { return buildUrl(currentApp.router.findUrl(endpoint), values) }
mit
e987ba64308d5fd04112c0e2ad793871
27.75
79
0.646957
3.549383
false
false
false
false
arturbosch/detekt
detekt-gradle-plugin/src/main/kotlin/io/gitlab/arturbosch/detekt/report/XmlReportMerger.kt
1
2153
package io.gitlab.arturbosch.detekt.report import org.w3c.dom.Document import org.w3c.dom.Node import java.io.File import javax.xml.parsers.DocumentBuilderFactory import javax.xml.transform.OutputKeys import javax.xml.transform.TransformerFactory import javax.xml.transform.dom.DOMSource import javax.xml.transform.stream.StreamResult /** * A naive implementation to merge xml assuming all input xml are written by detekt. */ object XmlReportMerger { private val documentBuilder by lazy { DocumentBuilderFactory.newInstance().newDocumentBuilder() } fun merge(inputs: Collection<File>, output: File) { val document = documentBuilder.newDocument().apply { xmlStandalone = true val checkstyleNode = createElement("checkstyle") checkstyleNode.setAttribute("version", "4.3") appendChild(checkstyleNode) } inputs.filter { it.exists() }.forEach { importNodesFromInput(it, document) } TransformerFactory.newInstance().newTransformer().run { setOutputProperty(OutputKeys.INDENT, "yes") setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2") transform(DOMSource(document), StreamResult(output.writer())) } } private fun importNodesFromInput(input: File, document: Document) { val checkstyleNode = documentBuilder.parse(input.inputStream()).documentElement.also { removeWhitespaces(it) } (0 until checkstyleNode.childNodes.length).forEach { val node = checkstyleNode.childNodes.item(it) document.documentElement.appendChild(document.importNode(node, true)) } } /** * Use code instead of XSLT to exclude whitespaces. */ private fun removeWhitespaces(node: Node) { (node.childNodes.length - 1 downTo 0).forEach { idx -> val childNode = node.childNodes.item(idx) if (childNode.nodeType == Node.TEXT_NODE && childNode.textContent.isBlank()) { node.removeChild(childNode) } else { removeWhitespaces(childNode) } } } }
apache-2.0
d422a22d69375724f183f7e2c1881d57
36.77193
118
0.667905
4.721491
false
false
false
false
ofalvai/BPInfo
app/src/main/java/com/ofalvai/bpinfo/notifications/NotificationMaker.kt
1
2634
/* * Copyright 2018 Olivér Falvai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ofalvai.bpinfo.notifications import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import androidx.core.content.getSystemService import com.ofalvai.bpinfo.R import com.ofalvai.bpinfo.ui.alertlist.AlertListActivity import java.util.* object NotificationMaker { const val INTENT_EXTRA_ALERT_ID = "alert_id" private const val INTENT_REQUEST_CODE = 0 fun make(context: Context, id: String, title: String, text: String) { val intent = Intent(context, AlertListActivity::class.java) intent.putExtra(INTENT_EXTRA_ALERT_ID, id) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) val pendingIntent = PendingIntent.getActivity( context, INTENT_REQUEST_CODE, intent, PendingIntent.FLAG_ONE_SHOT ) val bigTextStyle = NotificationCompat.BigTextStyle() bigTextStyle.setBigContentTitle(title) bigTextStyle.bigText(text) val channelId = context.getString(R.string.notif_channel_alerts_id) val notificationBuilder = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.ic_notification_default) .setContentTitle(title) .setContentText(text) .setStyle(bigTextStyle) .setAutoCancel(true) .setContentIntent(pendingIntent) .setColor(ContextCompat.getColor(context, R.color.primary)) .setShowWhen(true) .setWhen(Date().time) val notificationManager = context.getSystemService<NotificationManager>() val notificationId = parseAlertNumericalId(id) notificationManager?.notify(notificationId, notificationBuilder.build()) } private fun parseAlertNumericalId(id: String): Int { return try { id.split("-")[1].toInt() } catch (ex: Exception) { -1 } } }
apache-2.0
46e131c8799ce152ec2a90922b77142c
34.594595
80
0.701861
4.563258
false
false
false
false
bbodi/KotlinReactSpringBootstrap
frontend/src/hu/nevermind/common/JQueryExt.kt
1
2550
package hu.nevermind.common import org.w3c.dom.Element import jquery.JQuery import org.w3c.dom.Node import org.w3c.dom.HTMLElement import org.w3c.dom.Window @Suppress("UNUSED_PARAMETER") public @native fun Node.querySelector(selector: String): Node = noImpl @Suppress("UNUSED_PARAMETER") public @native("$") fun jq(win: Window): JQuery = noImpl public @native fun JQuery.hide(): Unit = noImpl public @native("$") val jq: JQuery = noImpl public @native fun JQuery.show(): Unit = noImpl public @native fun JQuery.focus(): Unit = noImpl public @native fun JQuery.blur(): Unit = noImpl public @native fun JQuery.empty(): Unit = noImpl @Suppress("UNUSED_PARAMETER") public @native fun JQuery.css(s1: String, s: String): JQuery = noImpl @Suppress("UNUSED_PARAMETER") public @native fun JQuery.css(s1: String): String = noImpl @Suppress("UNUSED_PARAMETER") public @native fun JQuery.append(element: Element): Unit = noImpl @Suppress("UNUSED_PARAMETER") public @native fun JQuery.on(eventName: String, callback: (event: dynamic)->Unit): Unit = noImpl @Suppress("UNUSED_PARAMETER") public @native fun JQuery.off(eventName: String, callback: (event: dynamic)->Unit): Unit = noImpl public @native fun JQuery.remove(): Unit = noImpl @Suppress("UNUSED_PARAMETER") public @native fun JQuery.get(index: Int): HTMLElement? = noImpl @Suppress("UNUSED_PARAMETER") public @native fun JQuery.find(str: String): JQuery = noImpl public @native fun JQuery.size(): Int = noImpl @Suppress("UNUSED_PARAMETER") public @native fun JQuery.`is`(str: String): Boolean = noImpl @Suppress("UNUSED_PARAMETER") public @native fun JQuery.prepend(str: Any): JQuery = noImpl @Suppress("UNUSED_PARAMETER") public @native fun JQuery.append(str: Any): JQuery = noImpl @Suppress("UNUSED_PARAMETER") public @native fun JQuery.replaceWith(str: Any): JQuery = noImpl public @native fun JQuery.highcharts(): dynamic = noImpl @Suppress("UNUSED_PARAMETER") public @native fun JQuery.highcharts(param: dynamic): Unit = noImpl @Suppress("UNUSED_PARAMETER") public @native fun JQuery.notify(text: String, params: dynamic = null): Unit = noImpl public @native fun JQuery.block(): Unit = noImpl public @native fun JQuery.unblock(): Unit = noImpl @Suppress("UNUSED_PARAMETER") public @native("val") fun JQuery.value(value: String?): Unit= noImpl @Suppress("UNUSED_PARAMETER") public @native("prop") fun JQuery.prop(propName: String): Any= noImpl // jQuery Caret public @native fun JQuery.caret(): Int = noImpl @Suppress("UNUSED_PARAMETER") public @native fun JQuery.caret(pos: Int): Unit = noImpl
mit
3d9f6f801b3c8cbd4956b837f81a3baf
54.456522
127
0.749804
3.834586
false
false
false
false
oboehm/jfachwert
src/main/kotlin/de/jfachwert/pruefung/Mod97Verfahren.kt
1
3082
/* * Copyright (c) 2017-2022 by Oliver Boehm * * 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 orimplied. * See the License for the specific language governing permissions and * limitations under the License. * * (c)reated 21.03.2017 by oboehm ([email protected]) */ package de.jfachwert.pruefung import de.jfachwert.PruefzifferVerfahren import java.math.BigDecimal /** * Die Klasse Mod97Verfahren implementiert das Modulo97-Verfahren nach * ISO 7064, das fuer die Validierung einer IBAN verwendet wird. * * @author oboehm * @since 0.1.0 */ open class Mod97Verfahren private constructor() : PruefzifferVerfahren<String> { /** * Bei der IBAN ist die Pruefziffer 2-stellig und folgt der Laenderkennung. * * @param wert z.B. "DE68 2105 0170 0012 3456 78" * @return z.B. "68" */ override fun getPruefziffer(wert: String): String { return wert.substring(2, 4) } /** * Berechnet die Pruefziffer des uebergebenen Wertes (ohne Pruefziffer). * Ohne Pruefziffer heisst dabei, dass anstelle der Pruefziffer die * uebergebene IBAN eine "00" enthalten kann. * * Die Pruefziffer selbst wird dabei nach dem Verfahren umgesetzt, das in * Wikipedia beschrieben ist: * * 1. Setze die beiden Pruefziffern auf 00 (die IBAN beginnt dann z. B. * mit DE00 für Deutschland). * 2. Stelle die vier ersten Stellen an das Ende der IBAN. * 3. Ersetze alle Buchstaben durch Zahlen, wobei A = 10, B = 11, …, Z = 35. * 4. Berechne den ganzzahligen Rest, der bei Division durch 97 bleibt. * 5. Subtrahiere den Rest von 98, das Ergebnis sind die beiden * Pruefziffern. Falls das Ergebnis einstellig ist, wird es mit * einer fuehrenden Null ergaenzt. * * @param wert z.B. "DE00 2105 0170 0012 3456 78" * @return z.B. "68" */ override fun berechnePruefziffer(wert: String): String { val land = wert.substring(0, 2).uppercase().toCharArray() val umgestellt = wert.substring(4) + toZahl(land[0]) + toZahl(land[1]) + "00" val number = BigDecimal(umgestellt) val modulo = number.remainder(BigDecimal.valueOf(97)) val ergebnis: Int = 98 - modulo.toInt() return String.format("%02d", ergebnis) } companion object { private val INSTANCE = Mod97Verfahren() /** * Liefert die einzige Instanz dieses Verfahrens. * * @return the instance */ @JvmStatic val instance: PruefzifferVerfahren<String> get() = INSTANCE private fun toZahl(c: Char): Int { return 10 + c.code - 'A'.code } } }
apache-2.0
35ced5731cc10125acfd564404d22173
32.478261
85
0.655408
3.596963
false
false
false
false
soywiz/korge
korge-dragonbones/src/commonMain/kotlin/com/dragonbones/parser/ObjectDataParser.kt
1
89496
/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.dragonbones.parser import com.dragonbones.core.* import com.dragonbones.model.* import com.dragonbones.util.* import com.dragonbones.util.length import com.soywiz.kds.* import com.soywiz.kds.iterators.* import com.soywiz.klogger.* import com.soywiz.kmem.* import com.soywiz.korim.color.* import com.soywiz.korma.geom.* import kotlin.math.* /** * @private */ enum class FrameValueType(val index: kotlin.Int) { STEP(0), INT(1), FLOAT(2), } /** * @private */ @Suppress("UNCHECKED_CAST", "NAME_SHADOWING", "UNUSED_CHANGED_VALUE") open class ObjectDataParser(pool: BaseObjectPool = BaseObjectPool()) : DataParser(pool) { companion object { // dynamic tools internal fun Any?.getDynamic(key: String): Any? = when (this) { null -> null is Map<*, *> -> (this as Map<String, Any?>)[key] else -> error("Can't getDynamic $this['$key'] (${this::class})") } internal inline fun Any?.containsDynamic(key: String): Boolean = this.getDynamic(key) != null internal fun Any?.asFastArrayList() = (this as List<Any?>).toFastList() as FastArrayList<Any?> internal val Any?.dynKeys: List<String> get() = when (this) { null -> listOf() is Map<*, *> -> keys.map { it.toString() } else -> error("Can't get keys of $this (${this::class})") } internal val Any?.dynList: List<Any?> get() = when (this) { null -> listOf() is List<*> -> this is Iterable<*> -> this.toList() else -> error("Not a list $this (${this::class})") } internal val Any?.doubleArray: DoubleArray get() { if (this is DoubleArray) return this if (this is DoubleArrayList) return this.toDoubleArray() if (this is List<*>) return this.map { (it as Number).toDouble() }.toDoubleArray() error("Can't cast '$this' to doubleArray") } internal val Any?.doubleArrayList: DoubleArrayList get() { if (this is DoubleArray) return DoubleArrayList(*this) if (this is DoubleArrayList) return this if (this is DoubleArrayList) return this.toDoubleList() if (this is List<*>) return DoubleArrayList(*this.map { (it as Number).toDouble() }.toDoubleArray()) error("Can't cast '$this' to doubleArrayList") } internal val Any?.intArrayList: IntArrayList get() { if (this is IntArray) return IntArrayList(*this) if (this is IntArrayList) return this if (this is DoubleArrayList) return this.toIntArrayList() if (this is List<*>) return IntArrayList(*this.map { (it as Number).toInt() }.toIntArray()) error("Can't '$this' cast to intArrayList") } fun _getBoolean(rawData: Any?, key: String, defaultValue: Boolean): Boolean { val value = rawData.getDynamic(key) return when (value) { null -> defaultValue is Boolean -> value is Number -> value.toDouble() != 0.0 is String -> when (value) { "0", "NaN", "", "false", "null", "undefined" -> false else -> true } else -> defaultValue } } fun _getNumber(rawData: Any?, key: String, defaultValue: Double): Double { val value = rawData.getDynamic(key) as? Number? return if (value != null && value != Double.NaN) { value.toDouble() } else { defaultValue } } fun _getInt(rawData: Any?, key: String, defaultValue: Int): Int { val value = rawData.getDynamic(key) as? Number? return if (value != null && value != Double.NaN) { value.toInt() } else { defaultValue } } fun _getString(rawData: Any?, key: String, defaultValue: String): String { return rawData.getDynamic(key)?.toString() ?: defaultValue } //private var _objectDataParserInstance = ObjectDataParser() ///** // * - Deprecated, please refer to {@link dragonBones.BaseFactory#parseDragonBonesData()}. // * deprecated // * @language en_US // */ ///** // * - 已废弃,请参考 {@link dragonBones.BaseFactory#parseDragonBonesData()}。 // * deprecated // * @language zh_CN // */ //fun getInstance(): ObjectDataParser = ObjectDataParser._objectDataParserInstance } protected var _rawTextureAtlasIndex: Int = 0 protected val _rawBones: FastArrayList<BoneData> = FastArrayList() protected var _data: DragonBonesData? = null // protected var _armature: ArmatureData? = null // protected var _bone: BoneData? = null // protected var _geometry: GeometryData? = null // protected var _slot: SlotData? = null // protected var _skin: SkinData? = null // protected var _mesh: MeshDisplayData? = null // protected var _animation: AnimationData? = null // protected var _timeline: TimelineData? = null // protected var _rawTextureAtlases: FastArrayList<Any?>? = null private var _frameValueType: FrameValueType = FrameValueType.STEP private var _defaultColorOffset: Int = -1 //private var _prevClockwise: Int = 0 private var _prevClockwise: Double = 0.0 private var _prevRotation: Double = 0.0 private var _frameDefaultValue: Double = 0.0 private var _frameValueScale: Double = 1.0 private val _helpMatrixA: Matrix = Matrix() private val _helpMatrixB: Matrix = Matrix() private val _helpTransform: TransformDb = TransformDb() private val _helpColorTransform: ColorTransform = ColorTransform() private val _helpPoint: Point = Point() private val _helpArray: DoubleArrayList = DoubleArrayList() private val _intArray: IntArrayList = IntArrayList() private val _floatArray: DoubleArrayList = DoubleArrayList() //private val _frameIntArray: DoubleArrayList = DoubleArrayList() private val _frameIntArray: IntArrayList = IntArrayList() private val _frameFloatArray: DoubleArrayList = DoubleArrayList() private val _frameArray: DoubleArrayList = DoubleArrayList() private val _timelineArray: DoubleArrayList = DoubleArrayList() //private val _colorArray: DoubleArrayList = DoubleArrayList() private val _colorArray: IntArrayList = IntArrayList() private val _cacheRawMeshes: FastArrayList<Any> = FastArrayList() private val _cacheMeshes: FastArrayList<MeshDisplayData> = FastArrayList() private val _actionFrames: FastArrayList<ActionFrame> = FastArrayList() private val _weightSlotPose: LinkedHashMap<String, DoubleArrayList> = LinkedHashMap() private val _weightBonePoses: LinkedHashMap<String, DoubleArrayList> = LinkedHashMap() private val _cacheBones: LinkedHashMap<String, FastArrayList<BoneData>> = LinkedHashMap() private val _slotChildActions: LinkedHashMap<String, FastArrayList<ActionData>> = LinkedHashMap() private fun _getCurvePoint( x1: Double, y1: Double, x2: Double, y2: Double, x3: Double, y3: Double, x4: Double, y4: Double, t: Double, result: Point ) { val l_t = 1.0 - t val powA = l_t * l_t val powB = t * t val kA = l_t * powA val kB = 3.0 * t * powA val kC = 3.0 * l_t * powB val kD = t * powB result.xf = (kA * x1 + kB * x2 + kC * x3 + kD * x4).toFloat() result.yf = (kA * y1 + kB * y2 + kC * y3 + kD * y4).toFloat() } private fun _samplingEasingCurve(curve: DoubleArrayList, samples: DoubleArrayList): Boolean { val curveCount = curve.size if (curveCount % 3 == 1) { var stepIndex = -2 val l = samples.size for (i in 0 until samples.size) { val t: Double = (i + 1) / (l.toDouble() + 1) // float while ((if (stepIndex + 6 < curveCount) curve[stepIndex + 6] else 1.0) < t) { // stepIndex + 3 * 2 stepIndex += 6 } val isInCurve = stepIndex >= 0 && stepIndex + 6 < curveCount val x1 = if (isInCurve) curve[stepIndex] else 0.0 val y1 = if (isInCurve) curve[stepIndex + 1] else 0.0 val x2 = curve[stepIndex + 2] val y2 = curve[stepIndex + 3] val x3 = curve[stepIndex + 4] val y3 = curve[stepIndex + 5] val x4 = if (isInCurve) curve[stepIndex + 6] else 1.0 val y4 = if (isInCurve) curve[stepIndex + 7] else 1.0 var lower = 0.0 var higher = 1.0 while (higher - lower > 0.0001) { val percentage = (higher + lower) * 0.5 this._getCurvePoint(x1, y1, x2, y2, x3, y3, x4, y4, percentage, this._helpPoint) if (t - this._helpPoint.xf > 0.0) { lower = percentage } else { higher = percentage } } samples[i] = this._helpPoint.yf.toDouble() } return true } else { var stepIndex = 0 val l = samples.size for (i in 0 until samples.size) { val t = (i + 1) / (l + 1) // float while (curve[stepIndex + 6] < t) { // stepIndex + 3 * 2 stepIndex += 6 } val x1 = curve[stepIndex] val y1 = curve[stepIndex + 1] val x2 = curve[stepIndex + 2] val y2 = curve[stepIndex + 3] val x3 = curve[stepIndex + 4] val y3 = curve[stepIndex + 5] val x4 = curve[stepIndex + 6] val y4 = curve[stepIndex + 7] var lower = 0.0 var higher = 1.0 while (higher - lower > 0.0001) { val percentage = (higher + lower) * 0.5 this._getCurvePoint(x1, y1, x2, y2, x3, y3, x4, y4, percentage, this._helpPoint) if (t - this._helpPoint.xf > 0.0) { lower = percentage } else { higher = percentage } } samples[i] = this._helpPoint.yf.toDouble() } return false } } private fun _parseActionDataInFrame(rawData: Any?, frameStart: Int, bone: BoneData?, slot: SlotData?) { if (rawData.containsDynamic(DataParser.EVENT)) { this._mergeActionFrame(rawData.getDynamic(DataParser.EVENT)!!, frameStart, ActionType.Frame, bone, slot) } if (rawData.containsDynamic(DataParser.SOUND)) { this._mergeActionFrame(rawData.getDynamic(DataParser.SOUND)!!, frameStart, ActionType.Sound, bone, slot) } if (rawData.containsDynamic(DataParser.ACTION)) { this._mergeActionFrame(rawData.getDynamic(DataParser.ACTION)!!, frameStart, ActionType.Play, bone, slot) } if (rawData.containsDynamic(DataParser.EVENTS)) { this._mergeActionFrame(rawData.getDynamic(DataParser.EVENTS)!!, frameStart, ActionType.Frame, bone, slot) } if (rawData.containsDynamic(DataParser.ACTIONS)) { this._mergeActionFrame(rawData.getDynamic(DataParser.ACTIONS)!!, frameStart, ActionType.Play, bone, slot) } } private fun _mergeActionFrame(rawData: Any?, frameStart: Int, type: ActionType, bone: BoneData?, slot: SlotData?) { val actionOffset = this._armature!!.actions.size val actions = this._parseActionData(rawData, type, bone, slot) var frameIndex = 0 var frame: ActionFrame? = null actions.fastForEach { action -> this._armature?.addAction(action, false) } if (this._actionFrames.size == 0) { // First frame. frame = ActionFrame() frame.frameStart = 0 this._actionFrames.add(frame) frame = null } for (eachFrame in this._actionFrames) { // Get same frame. if (eachFrame.frameStart == frameStart) { frame = eachFrame break } else if (eachFrame.frameStart > frameStart) { break } frameIndex++ } if (frame == null) { // Create and cache frame. frame = ActionFrame() frame.frameStart = frameStart this._actionFrames.splice(frameIndex, 0, frame) } for (i in 0 until actions.size) { // Cache action offsets. frame.actions.push(actionOffset + i) } } protected fun _parseArmature(rawData: Any?, scale: Double): ArmatureData { val armature = pool.armatureData.borrow() armature.name = ObjectDataParser._getString(rawData, DataParser.NAME, "") armature.frameRate = ObjectDataParser._getInt(rawData, DataParser.FRAME_RATE, this._data!!.frameRate) armature.scale = scale if (rawData.containsDynamic(DataParser.TYPE) && rawData.getDynamic(DataParser.TYPE) is String) { armature.type = DataParser._getArmatureType(rawData.getDynamic(DataParser.TYPE)?.toString()) } else { armature.type = ArmatureType[ObjectDataParser._getInt(rawData, DataParser.TYPE, ArmatureType.Armature.id)] } if (armature.frameRate == 0) { // Data error. armature.frameRate = 24 } this._armature = armature if (rawData.containsDynamic(DataParser.CANVAS)) { val rawCanvas = rawData.getDynamic(DataParser.CANVAS) val canvas = pool.canvasData.borrow() canvas.hasBackground = rawCanvas.containsDynamic(DataParser.COLOR) canvas.color = ObjectDataParser._getInt(rawCanvas, DataParser.COLOR, 0) canvas.x = (ObjectDataParser._getInt(rawCanvas, DataParser.X, 0) * armature.scale).toInt() canvas.y = (ObjectDataParser._getInt(rawCanvas, DataParser.Y, 0) * armature.scale).toInt() canvas.width = (ObjectDataParser._getInt(rawCanvas, DataParser.WIDTH, 0) * armature.scale).toInt() canvas.height = (ObjectDataParser._getInt(rawCanvas, DataParser.HEIGHT, 0) * armature.scale).toInt() armature.canvas = canvas } if (rawData.containsDynamic(DataParser.AABB)) { val rawAABB = rawData.getDynamic(DataParser.AABB) armature.aabb.x = ObjectDataParser._getNumber(rawAABB, DataParser.X, 0.0) * armature.scale armature.aabb.y = ObjectDataParser._getNumber(rawAABB, DataParser.Y, 0.0) * armature.scale armature.aabb.width = ObjectDataParser._getNumber(rawAABB, DataParser.WIDTH, 0.0) * armature.scale armature.aabb.height = ObjectDataParser._getNumber(rawAABB, DataParser.HEIGHT, 0.0) * armature.scale } if (rawData.containsDynamic(DataParser.BONE)) { val rawBones = rawData.getDynamic(DataParser.BONE) (rawBones as List<Any?>).fastForEach { rawBone -> val parentName = ObjectDataParser._getString(rawBone, DataParser.PARENT, "") val bone = this._parseBone(rawBone) if (parentName.isNotEmpty()) { // Get bone parent. val parent = armature.getBone(parentName) if (parent != null) { bone.parent = parent } else { // Cache. if (!(this._cacheBones.containsDynamic(parentName))) { this._cacheBones[parentName] = FastArrayList() } this._cacheBones[parentName]?.add(bone) } } if (this._cacheBones.containsDynamic(bone.name)) { for (child in this._cacheBones[bone.name]!!) { child.parent = bone } this._cacheBones.remove(bone.name) } armature.addBone(bone) this._rawBones.add(bone) // Cache raw bones sort. } } if (rawData.containsDynamic(DataParser.IK)) { val rawIKS = rawData.getDynamic(DataParser.IK) as List<Map<String, Any?>> rawIKS.fastForEach { rawIK -> val constraint = this._parseIKConstraint(rawIK) if (constraint != null) { armature.addConstraint(constraint) } } } armature.sortBones() if (rawData.containsDynamic(DataParser.SLOT)) { var zOrder = 0 val rawSlots = rawData.getDynamic(DataParser.SLOT) as List<Map<String, Any?>> rawSlots.fastForEach { rawSlot -> armature.addSlot(this._parseSlot(rawSlot, zOrder++)) } } if (rawData.containsDynamic(DataParser.SKIN)) { val rawSkins = rawData.getDynamic(DataParser.SKIN) as List<Any?> rawSkins.fastForEach { rawSkin -> armature.addSkin(this._parseSkin(rawSkin)) } } if (rawData.containsDynamic(DataParser.PATH_CONSTRAINT)) { val rawPaths = rawData.getDynamic(DataParser.PATH_CONSTRAINT) as List<Any?> rawPaths.fastForEach { rawPath -> val constraint = this._parsePathConstraint(rawPath) if (constraint != null) { armature.addConstraint(constraint) } } } //for (var i = 0, l = this._cacheRawMeshes.length; i < l; ++i) { // Link mesh. for (i in 0 until this._cacheRawMeshes.length) { val rawData = this._cacheRawMeshes[i] val shareName = ObjectDataParser._getString(rawData, DataParser.SHARE, "") if (shareName.isEmpty()) { continue } var skinName = ObjectDataParser._getString(rawData, DataParser.SKIN, DataParser.DEFAULT_NAME) if (skinName.isEmpty()) { // skinName = DataParser.DEFAULT_NAME } val shareMesh = armature.getMesh(skinName, "", shareName) // TODO slot; if (shareMesh == null) { continue // Error. } val mesh = this._cacheMeshes[i] mesh.geometry.shareFrom(shareMesh.geometry) } if (rawData.containsDynamic(DataParser.ANIMATION)) { val rawAnimations = rawData.getDynamic(DataParser.ANIMATION) as List<Any?> rawAnimations.fastForEach { rawAnimation -> val animation = this._parseAnimation(rawAnimation) armature.addAnimation(animation) } } if (rawData.containsDynamic(DataParser.DEFAULT_ACTIONS)) { val actions = this._parseActionData(rawData.getDynamic(DataParser.DEFAULT_ACTIONS), ActionType.Play, null, null) actions.fastForEach { action -> armature.addAction(action, true) if (action.type == ActionType.Play) { // Set default animation from default action. val animation = armature.getAnimation(action.name) if (animation != null) { armature.defaultAnimation = animation } } } } if (rawData.containsDynamic(DataParser.ACTIONS)) { val actions = this._parseActionData(rawData.getDynamic(DataParser.ACTIONS), ActionType.Play, null, null) actions.fastForEach { action -> armature.addAction(action, false) } } // Clear helper. this._rawBones.lengthSet = 0 this._cacheRawMeshes.length = 0 this._cacheMeshes.length = 0 this._armature = null this._weightSlotPose.clear() this._weightBonePoses.clear() this._cacheBones.clear() this._slotChildActions.clear() return armature } protected fun _parseBone(rawData: Any?): BoneData { val isSurface: Boolean if (rawData.containsDynamic(DataParser.TYPE) && rawData.getDynamic(DataParser.TYPE) is String) { isSurface = DataParser._getBoneTypeIsSurface(rawData.getDynamic(DataParser.TYPE)?.toString()) } else { isSurface = ObjectDataParser._getInt(rawData, DataParser.TYPE, 0) == 1 } if (!isSurface) { val scale = this._armature!!.scale val bone = pool.boneData.borrow() bone.inheritTranslation = ObjectDataParser._getBoolean(rawData, DataParser.INHERIT_TRANSLATION, true) bone.inheritRotation = ObjectDataParser._getBoolean(rawData, DataParser.INHERIT_ROTATION, true) bone.inheritScale = ObjectDataParser._getBoolean(rawData, DataParser.INHERIT_SCALE, true) bone.inheritReflection = ObjectDataParser._getBoolean(rawData, DataParser.INHERIT_REFLECTION, true) bone.length = ObjectDataParser._getNumber(rawData, DataParser.LENGTH, 0.0) * scale bone.alpha = ObjectDataParser._getNumber(rawData, DataParser.ALPHA, 1.0) bone.name = ObjectDataParser._getString(rawData, DataParser.NAME, "") if (rawData.containsDynamic(DataParser.TRANSFORM)) { this._parseTransform(rawData.getDynamic(DataParser.TRANSFORM), bone.transform, scale) } return bone } else { val surface = pool.surfaceData.borrow() surface.alpha = ObjectDataParser._getNumber(rawData, DataParser.ALPHA, 1.0) surface.name = ObjectDataParser._getString(rawData, DataParser.NAME, "") surface.segmentX = ObjectDataParser._getInt(rawData, DataParser.SEGMENT_X, 0) surface.segmentY = ObjectDataParser._getInt(rawData, DataParser.SEGMENT_Y, 0) this._parseGeometry(rawData, surface.geometry) return surface } } protected fun _parseIKConstraint(rawData: Any?): ConstraintData? { val bone = this._armature?.getBone(ObjectDataParser._getString(rawData, DataParser.BONE, "")) ?: return null val target = this._armature?.getBone(ObjectDataParser._getString(rawData, DataParser.TARGET, "")) ?: return null val chain = ObjectDataParser._getInt(rawData, DataParser.CHAIN, 0) val constraint = pool.iKConstraintData.borrow() constraint.scaleEnabled = ObjectDataParser._getBoolean(rawData, DataParser.SCALE, false) constraint.bendPositive = ObjectDataParser._getBoolean(rawData, DataParser.BEND_POSITIVE, true) constraint.weight = ObjectDataParser._getNumber(rawData, DataParser.WEIGHT, 1.0) constraint.name = ObjectDataParser._getString(rawData, DataParser.NAME, "") constraint.type = ConstraintType.IK constraint.target = target if (chain > 0 && bone.parent != null) { constraint.root = bone.parent constraint.bone = bone } else { constraint.root = bone constraint.bone = null } return constraint } protected fun _parsePathConstraint(rawData: Any?): ConstraintData? { val target = this._armature?.getSlot(ObjectDataParser._getString(rawData, DataParser.TARGET, "")) ?: return null val defaultSkin = this._armature?.defaultSkin ?: return null //TODO val targetDisplay = defaultSkin.getDisplay( target.name, ObjectDataParser._getString(rawData, DataParser.TARGET_DISPLAY, target.name) ) if (targetDisplay == null || !(targetDisplay is PathDisplayData)) { return null } val bones = rawData.getDynamic(DataParser.BONES) as? List<String>? if (bones == null || bones.isEmpty()) { return null } val constraint = pool.pathConstraintData.borrow() constraint.name = ObjectDataParser._getString(rawData, DataParser.NAME, "") constraint.type = ConstraintType.Path constraint.pathSlot = target constraint.pathDisplayData = targetDisplay constraint.target = target.parent constraint.positionMode = DataParser._getPositionMode(ObjectDataParser._getString(rawData, DataParser.POSITION_MODE, "")) constraint.spacingMode = DataParser._getSpacingMode(ObjectDataParser._getString(rawData, DataParser.SPACING_MODE, "")) constraint.rotateMode = DataParser._getRotateMode(ObjectDataParser._getString(rawData, DataParser.ROTATE_MODE, "")) constraint.position = ObjectDataParser._getNumber(rawData, DataParser.POSITION, 0.0) constraint.spacing = ObjectDataParser._getNumber(rawData, DataParser.SPACING, 0.0) constraint.rotateOffset = ObjectDataParser._getNumber(rawData, DataParser.ROTATE_OFFSET, 0.0) constraint.rotateMix = ObjectDataParser._getNumber(rawData, DataParser.ROTATE_MIX, 1.0) constraint.translateMix = ObjectDataParser._getNumber(rawData, DataParser.TRANSLATE_MIX, 1.0) // bones.fastForEach { boneName -> val bone = this._armature?.getBone(boneName) if (bone != null) { constraint.AddBone(bone) if (constraint.root == null) { constraint.root = bone } } } return constraint } protected fun _parseSlot(rawData: Any?, zOrder: Int): SlotData { val slot = pool.slotData.borrow() slot.displayIndex = ObjectDataParser._getInt(rawData, DataParser.DISPLAY_INDEX, 0) slot.zOrder = zOrder slot.zIndex = ObjectDataParser._getInt(rawData, DataParser.Z_INDEX, 0) slot.alpha = ObjectDataParser._getNumber(rawData, DataParser.ALPHA, 1.0) slot.name = ObjectDataParser._getString(rawData, DataParser.NAME, "") slot.parent = this._armature?.getBone(ObjectDataParser._getString(rawData, DataParser.PARENT, "")) // if (rawData.containsDynamic(DataParser.BLEND_MODE) && rawData.getDynamic(DataParser.BLEND_MODE) is String) { slot.blendMode = DataParser._getBlendMode(rawData.getDynamic(DataParser.BLEND_MODE)?.toString()) } else { slot.blendMode = BlendMode[ObjectDataParser._getInt(rawData, DataParser.BLEND_MODE, BlendMode.Normal.id)] } if (rawData.containsDynamic(DataParser.COLOR)) { slot.color = SlotData.createColor() this._parseColorTransform(rawData.getDynamic(DataParser.COLOR) as Map<String, Any?>, slot.color!!) } else { slot.color = pool.DEFAULT_COLOR } if (rawData.containsDynamic(DataParser.ACTIONS)) { this._slotChildActions[slot.name] = this._parseActionData(rawData.getDynamic(DataParser.ACTIONS), ActionType.Play, null, null) } return slot } protected fun _parseSkin(rawData: Any?): SkinData { val skin = pool.skinData.borrow() skin.name = ObjectDataParser._getString(rawData, DataParser.NAME, DataParser.DEFAULT_NAME) if (skin.name.isEmpty()) { skin.name = DataParser.DEFAULT_NAME } if (rawData.containsDynamic(DataParser.SLOT)) { val rawSlots = rawData.getDynamic(DataParser.SLOT) this._skin = skin rawSlots.dynList.fastForEach { rawSlot -> val slotName = ObjectDataParser._getString(rawSlot, DataParser.NAME, "") val slot = this._armature?.getSlot(slotName) if (slot != null) { this._slot = slot if (rawSlot.containsDynamic(DataParser.DISPLAY)) { val rawDisplays = rawSlot.getDynamic(DataParser.DISPLAY) for (rawDisplay in rawDisplays.dynList) { if (rawDisplay != null) { skin.addDisplay(slotName, this._parseDisplay(rawDisplay)) } else { skin.addDisplay(slotName, null) } } } this._slot = null // } } this._skin = null // } return skin } protected fun _parseDisplay(rawData: Any?): DisplayData? { val name = ObjectDataParser._getString(rawData, DataParser.NAME, "") val path = ObjectDataParser._getString(rawData, DataParser.PATH, "") var type = DisplayType.Image var display: DisplayData? = null if (rawData.containsDynamic(DataParser.TYPE) && rawData.getDynamic(DataParser.TYPE) is String) { type = DataParser._getDisplayType(rawData.getDynamic(DataParser.TYPE)?.toString()) } else { type = DisplayType[ObjectDataParser._getInt(rawData, DataParser.TYPE, type.id)] } when (type) { DisplayType.Image -> { display = pool.imageDisplayData.borrow() val imageDisplay = display imageDisplay.name = name imageDisplay.path = if (path.length > 0) path else name this._parsePivot(rawData, imageDisplay) } DisplayType.Armature -> { display = pool.armatureDisplayData.borrow() val armatureDisplay = display armatureDisplay.name = name armatureDisplay.path = if (path.length > 0) path else name armatureDisplay.inheritAnimation = true if (rawData.containsDynamic(DataParser.ACTIONS)) { val actions = this._parseActionData(rawData.getDynamic(DataParser.ACTIONS), ActionType.Play, null, null) actions.fastForEach { action -> armatureDisplay.addAction(action) } } else if (this._slot?.name in this._slotChildActions) { val displays = this._skin?.getDisplays(this._slot?.name) if (if (displays == null) this._slot!!.displayIndex == 0 else this._slot!!.displayIndex == displays.length) { this._slotChildActions[this._slot?.name]!!.fastForEach { action -> armatureDisplay.addAction(action) } this._slotChildActions.remove(this._slot?.name) } } } DisplayType.Mesh -> { val meshDisplay = pool.meshDisplayData.borrow() display = meshDisplay meshDisplay.geometry.inheritDeform = ObjectDataParser._getBoolean(rawData, DataParser.INHERIT_DEFORM, true) meshDisplay.name = name meshDisplay.path = if (path.isNotEmpty()) path else name if (rawData.containsDynamic(DataParser.SHARE)) { meshDisplay.geometry.data = this._data this._cacheRawMeshes.add(rawData!!) this._cacheMeshes.add(meshDisplay) } else { this._parseMesh(rawData, meshDisplay) } } DisplayType.BoundingBox -> { val boundingBox = this._parseBoundingBox(rawData) if (boundingBox != null) { val boundingBoxDisplay = pool.boundingBoxDisplayData.borrow() display = boundingBoxDisplay boundingBoxDisplay.name = name boundingBoxDisplay.path = if (path.isNotEmpty()) path else name boundingBoxDisplay.boundingBox = boundingBox } } DisplayType.Path -> { val rawCurveLengths = rawData.getDynamic(DataParser.LENGTHS).doubleArray val pathDisplay = pool.pathDisplayData.borrow() display = pathDisplay pathDisplay.closed = ObjectDataParser._getBoolean(rawData, DataParser.CLOSED, false) pathDisplay.constantSpeed = ObjectDataParser._getBoolean(rawData, DataParser.CONSTANT_SPEED, false) pathDisplay.name = name pathDisplay.path = if (path.isNotEmpty()) path else name pathDisplay.curveLengths = DoubleArray(rawCurveLengths.size) //for (var i = 0, l = rawCurveLengths.length; i < l; ++i) { for (i in 0 until rawCurveLengths.size) { pathDisplay.curveLengths[i] = rawCurveLengths[i] } this._parsePath(rawData, pathDisplay) } else -> { } } if (display != null && rawData.containsDynamic(DataParser.TRANSFORM)) { this._parseTransform(rawData.getDynamic(DataParser.TRANSFORM), display.transform, this._armature!!.scale) } return display } protected fun _parsePath(rawData: Any?, display: PathDisplayData) { this._parseGeometry(rawData, display.geometry) } protected fun _parsePivot(rawData: Any?, display: ImageDisplayData) { if (rawData.containsDynamic(DataParser.PIVOT)) { val rawPivot = rawData.getDynamic(DataParser.PIVOT) display.pivot.xf = ObjectDataParser._getNumber(rawPivot, DataParser.X, 0.0).toFloat() display.pivot.yf = ObjectDataParser._getNumber(rawPivot, DataParser.Y, 0.0).toFloat() } else { display.pivot.xf = 0.5f display.pivot.yf = 0.5f } } protected fun _parseMesh(rawData: Any?, mesh: MeshDisplayData) { this._parseGeometry(rawData, mesh.geometry) if (rawData.containsDynamic(DataParser.WEIGHTS)) { // Cache pose data. val rawSlotPose = rawData.getDynamic(DataParser.SLOT_POSE).doubleArrayList val rawBonePoses = rawData.getDynamic(DataParser.BONE_POSE).doubleArrayList val meshName = "" + this._skin?.name + "_" + this._slot?.name + "_" + mesh.name this._weightSlotPose[meshName] = rawSlotPose this._weightBonePoses[meshName] = rawBonePoses } } protected fun _parseBoundingBox(rawData: Any?): BoundingBoxData? { var boundingBox: BoundingBoxData? = null var type = BoundingBoxType.Rectangle if (rawData.containsDynamic(DataParser.SUB_TYPE) && rawData.getDynamic(DataParser.SUB_TYPE) is String) { type = DataParser._getBoundingBoxType(rawData.getDynamic(DataParser.SUB_TYPE)?.toString()) } else { type = BoundingBoxType[ObjectDataParser._getInt(rawData, DataParser.SUB_TYPE, type.id)] } when (type) { BoundingBoxType.Rectangle -> { boundingBox = pool.rectangleBoundingBoxData.borrow() } BoundingBoxType.Ellipse -> { boundingBox = pool.ellipseBoundingBoxData.borrow() } BoundingBoxType.Polygon -> { boundingBox = this._parsePolygonBoundingBox(rawData) } else -> { } } if (boundingBox != null) { boundingBox.color = ObjectDataParser._getNumber(rawData, DataParser.COLOR, 0x000000.toDouble()).toInt() if (boundingBox.type == BoundingBoxType.Rectangle || boundingBox.type == BoundingBoxType.Ellipse) { boundingBox.width = ObjectDataParser._getNumber(rawData, DataParser.WIDTH, 0.0) boundingBox.height = ObjectDataParser._getNumber(rawData, DataParser.HEIGHT, 0.0) } } return boundingBox } protected fun _parsePolygonBoundingBox(rawData: Any?): PolygonBoundingBoxData { val polygonBoundingBox = pool.polygonBoundingBoxData.borrow() if (rawData.containsDynamic(DataParser.VERTICES)) { val scale = this._armature!!.scale val rawVertices = rawData.getDynamic(DataParser.VERTICES).doubleArray polygonBoundingBox.vertices = DoubleArray(rawVertices.size) val vertices = polygonBoundingBox.vertices //for (var i = 0, l = rawVertices.length; i < l; i += 2) { for (i in 0 until rawVertices.size step 2) { val x = rawVertices[i] * scale val y = rawVertices[i + 1] * scale vertices[i] = x vertices[i + 1] = y // AABB. if (i == 0) { polygonBoundingBox.x = x polygonBoundingBox.y = y polygonBoundingBox.width = x polygonBoundingBox.height = y } else { if (x < polygonBoundingBox.x) { polygonBoundingBox.x = x } else if (x > polygonBoundingBox.width) { polygonBoundingBox.width = x } if (y < polygonBoundingBox.y) { polygonBoundingBox.y = y } else if (y > polygonBoundingBox.height) { polygonBoundingBox.height = y } } } polygonBoundingBox.width -= polygonBoundingBox.x polygonBoundingBox.height -= polygonBoundingBox.y } else { Console.warn("Data error.\n Please reexport DragonBones Data to fixed the bug.") } return polygonBoundingBox } private fun findGeometryInTimeline(timelineName: String): GeometryData? { this._armature!!.skins.fastKeyForEach { skinName -> val skin = this._armature!!.skins.getNull(skinName) skin!!.displays.fastKeyForEach { slontName -> val displays = skin.displays.getNull(slontName)!! displays.fastForEach { display -> if (display != null && display.name == timelineName) { return (display as MeshDisplayData).geometry } } } } return null } protected open fun _parseAnimation(rawData: Any?): AnimationData { val animation = pool.animationData.borrow() animation.blendType = DataParser._getAnimationBlendType(ObjectDataParser._getString(rawData, DataParser.BLEND_TYPE, "")) animation.frameCount = ObjectDataParser._getInt(rawData, DataParser.DURATION, 0) animation.playTimes = ObjectDataParser._getInt(rawData, DataParser.PLAY_TIMES, 1) animation.duration = animation.frameCount.toDouble() / this._armature!!.frameRate.toDouble() // float animation.fadeInTime = ObjectDataParser._getNumber(rawData, DataParser.FADE_IN_TIME, 0.0) animation.scale = ObjectDataParser._getNumber(rawData, DataParser.SCALE, 1.0) animation.name = ObjectDataParser._getString(rawData, DataParser.NAME, DataParser.DEFAULT_NAME) if (animation.name.length == 0) { animation.name = DataParser.DEFAULT_NAME } animation.frameIntOffset = this._frameIntArray.length animation.frameFloatOffset = this._frameFloatArray.length animation.frameOffset = this._frameArray.length this._animation = animation if (rawData.containsDynamic(DataParser.FRAME)) { val rawFrames = rawData.getDynamic(DataParser.FRAME) as List<Any?> val keyFrameCount = rawFrames.size if (keyFrameCount > 0) { //for (var i = 0, frameStart = 0; i < keyFrameCount; ++i) { var frameStart = 0 for (i in 0 until keyFrameCount) { val rawFrame = rawFrames[i] this._parseActionDataInFrame(rawFrame, frameStart, null, null) frameStart += ObjectDataParser._getInt(rawFrame, DataParser.DURATION, 1) } } } if (rawData.containsDynamic(DataParser.Z_ORDER)) { this._animation!!.zOrderTimeline = this._parseTimeline( rawData.getDynamic(DataParser.Z_ORDER), null, DataParser.FRAME, TimelineType.ZOrder, FrameValueType.STEP, 0, this::_parseZOrderFrame ) } if (rawData.containsDynamic(DataParser.BONE)) { val rawTimelines = rawData.getDynamic(DataParser.BONE) as List<Any?> rawTimelines.fastForEach { rawTimeline -> this._parseBoneTimeline(rawTimeline) } } if (rawData.containsDynamic(DataParser.SLOT)) { val rawTimelines = rawData.getDynamic(DataParser.SLOT) as List<Any?> rawTimelines.fastForEach { rawTimeline -> this._parseSlotTimeline(rawTimeline) } } if (rawData.containsDynamic(DataParser.FFD)) { val rawTimelines = rawData.getDynamic(DataParser.FFD) as List<Any?> rawTimelines.fastForEach { rawTimeline -> var skinName = ObjectDataParser._getString(rawTimeline, DataParser.SKIN, DataParser.DEFAULT_NAME) val slotName = ObjectDataParser._getString(rawTimeline, DataParser.SLOT, "") val displayName = ObjectDataParser._getString(rawTimeline, DataParser.NAME, "") if (skinName.isEmpty()) { // skinName = DataParser.DEFAULT_NAME } this._slot = this._armature?.getSlot(slotName) this._mesh = this._armature?.getMesh(skinName, slotName, displayName) if (this._slot == null || this._mesh == null) { return@fastForEach } val timeline = this._parseTimeline( rawTimeline, null, DataParser.FRAME, TimelineType.SlotDeform, FrameValueType.FLOAT, 0, this::_parseSlotDeformFrame ) if (timeline != null) { this._animation?.addSlotTimeline(slotName, timeline) } this._slot = null // this._mesh = null // } } if (rawData.containsDynamic(DataParser.IK)) { val rawTimelines = rawData.getDynamic(DataParser.IK) as List<Any?> rawTimelines.fastForEach { rawTimeline -> val constraintName = ObjectDataParser._getString(rawTimeline, DataParser.NAME, "") @Suppress("UNUSED_VARIABLE") val constraint = this._armature!!.getConstraint(constraintName) ?: return@fastForEach val timeline = this._parseTimeline( rawTimeline, null, DataParser.FRAME, TimelineType.IKConstraint, FrameValueType.INT, 2, this::_parseIKConstraintFrame ) if (timeline != null) { this._animation?.addConstraintTimeline(constraintName, timeline) } } } if (this._actionFrames.length > 0) { this._animation!!.actionTimeline = this._parseTimeline( null, this._actionFrames.asFastArrayList(), "", TimelineType.Action, FrameValueType.STEP, 0, this::_parseActionFrameRaw ) this._actionFrames.length = 0 } if (rawData.containsDynamic(DataParser.TIMELINE)) { val rawTimelines = rawData.getDynamic(DataParser.TIMELINE) rawTimelines.dynList.fastForEach { rawTimeline -> val timelineType = TimelineType[ObjectDataParser._getInt(rawTimeline, DataParser.TYPE, TimelineType.Action.id)] val timelineName = ObjectDataParser._getString(rawTimeline, DataParser.NAME, "") var timeline: TimelineData? = null when (timelineType) { TimelineType.Action -> { // TODO } TimelineType.SlotDisplay, // TODO TimelineType.SlotZIndex, TimelineType.BoneAlpha, TimelineType.SlotAlpha, TimelineType.AnimationProgress, TimelineType.AnimationWeight -> { if ( timelineType == TimelineType.SlotDisplay ) { this._frameValueType = FrameValueType.STEP this._frameValueScale = 1.0 } else { this._frameValueType = FrameValueType.INT if (timelineType == TimelineType.SlotZIndex) { this._frameValueScale = 1.0 } else if ( timelineType == TimelineType.AnimationProgress || timelineType == TimelineType.AnimationWeight ) { this._frameValueScale = 10000.0 } else { this._frameValueScale = 100.0 } } if ( timelineType == TimelineType.BoneAlpha || timelineType == TimelineType.SlotAlpha || timelineType == TimelineType.AnimationWeight ) { this._frameDefaultValue = 1.0 } else { this._frameDefaultValue = 0.0 } if (timelineType == TimelineType.AnimationProgress && animation.blendType != AnimationBlendType.None) { timeline = pool.animationTimelineData.borrow() val animaitonTimeline = timeline animaitonTimeline.x = ObjectDataParser._getNumber(rawTimeline, DataParser.X, 0.0) animaitonTimeline.y = ObjectDataParser._getNumber(rawTimeline, DataParser.Y, 0.0) } timeline = this._parseTimeline( rawTimeline, null, DataParser.FRAME, timelineType, this._frameValueType, 1, this::_parseSingleValueFrame, timeline ) } TimelineType.BoneTranslate, TimelineType.BoneRotate, TimelineType.BoneScale, TimelineType.IKConstraint, TimelineType.AnimationParameter -> { if ( timelineType == TimelineType.IKConstraint || timelineType == TimelineType.AnimationParameter ) { this._frameValueType = FrameValueType.INT if (timelineType == TimelineType.AnimationParameter) { this._frameValueScale = 10000.0 } else { this._frameValueScale = 100.0 } } else { if (timelineType == TimelineType.BoneRotate) { this._frameValueScale = TransformDb.DEG_RAD.toDouble() } else { this._frameValueScale = 1.0 } this._frameValueType = FrameValueType.FLOAT } if ( timelineType == TimelineType.BoneScale || timelineType == TimelineType.IKConstraint ) { this._frameDefaultValue = 1.0 } else { this._frameDefaultValue = 0.0 } timeline = this._parseTimeline( rawTimeline, null, DataParser.FRAME, timelineType, this._frameValueType, 2, this::_parseDoubleValueFrame ) } TimelineType.ZOrder -> { // TODO } TimelineType.Surface -> { val surface = this._armature?.getBone(timelineName) ?: return@fastForEach this._geometry = surface.geometry timeline = this._parseTimeline( rawTimeline, null, DataParser.FRAME, timelineType, FrameValueType.FLOAT, 0, this::_parseDeformFrame ) this._geometry = null // } TimelineType.SlotDeform -> { this._geometry = findGeometryInTimeline(timelineName) if (this._geometry == null) { return@fastForEach } timeline = this._parseTimeline( rawTimeline, null, DataParser.FRAME, timelineType, FrameValueType.FLOAT, 0, this::_parseDeformFrame ) this._geometry = null // } TimelineType.SlotColor -> { timeline = this._parseTimeline( rawTimeline, null, DataParser.FRAME, timelineType, FrameValueType.INT, 1, this::_parseSlotColorFrame ) } else -> { } } if (timeline != null) { when (timelineType) { TimelineType.Action -> { // TODO } TimelineType.ZOrder -> { // TODO } TimelineType.BoneTranslate, TimelineType.BoneRotate, TimelineType.BoneScale, TimelineType.Surface, TimelineType.BoneAlpha -> { this._animation?.addBoneTimeline(timelineName, timeline) } TimelineType.SlotDisplay, TimelineType.SlotColor, TimelineType.SlotDeform, TimelineType.SlotZIndex, TimelineType.SlotAlpha -> { this._animation?.addSlotTimeline(timelineName, timeline) } TimelineType.IKConstraint -> { this._animation?.addConstraintTimeline(timelineName, timeline) } TimelineType.AnimationProgress, TimelineType.AnimationWeight, TimelineType.AnimationParameter -> { this._animation?.addAnimationTimeline(timelineName, timeline) } else -> { } } } } } this._animation = null // return animation } protected fun _parseTimeline( rawData: Any?, rawFrames: FastArrayList<Any?>?, framesKey: String, timelineType: TimelineType, frameValueType: FrameValueType, frameValueCount: Int, frameParser: (rawData: Any?, frameStart: Int, frameCount: Int) -> Int, timeline: TimelineData? = null ): TimelineData? { var timeline = timeline val frameParser = frameParser var rawFrames = rawFrames if (rawData != null && framesKey.isNotEmpty() && rawData.containsDynamic(framesKey)) { rawFrames = (rawData.getDynamic(framesKey) as List<Any?>?)?.toFastList() as? FastArrayList<Any?> } if (rawFrames == null) { return null } val keyFrameCount = rawFrames.length if (keyFrameCount == 0) { return null } val frameIntArrayLength = this._frameIntArray.length val frameFloatArrayLength = this._frameFloatArray.length val timelineOffset = this._timelineArray.length if (timeline == null) { timeline = pool.timelineData.borrow() } timeline.type = timelineType timeline.offset = timelineOffset this._frameValueType = frameValueType this._timeline = timeline this._timelineArray.length += 1 + 1 + 1 + 1 + 1 + keyFrameCount if (rawData != null) { this._timelineArray[timelineOffset + BinaryOffset.TimelineScale] = round(ObjectDataParser._getNumber(rawData, DataParser.SCALE, 1.0) * 100) this._timelineArray[timelineOffset + BinaryOffset.TimelineOffset] = round(ObjectDataParser._getNumber(rawData, DataParser.OFFSET, 0.0) * 100) } else { this._timelineArray[timelineOffset + BinaryOffset.TimelineScale] = 100.0 this._timelineArray[timelineOffset + BinaryOffset.TimelineOffset] = 0.0 } this._timelineArray[timelineOffset + BinaryOffset.TimelineKeyFrameCount] = keyFrameCount.toDouble() this._timelineArray[timelineOffset + BinaryOffset.TimelineFrameValueCount] = frameValueCount.toDouble() when (this._frameValueType) { FrameValueType.STEP -> { this._timelineArray[timelineOffset + BinaryOffset.TimelineFrameValueOffset] = 0.0 } FrameValueType.INT -> { this._timelineArray[timelineOffset + BinaryOffset.TimelineFrameValueOffset] = (frameIntArrayLength - this._animation!!.frameIntOffset).toDouble() } FrameValueType.FLOAT -> { this._timelineArray[timelineOffset + BinaryOffset.TimelineFrameValueOffset] = (frameFloatArrayLength - this._animation!!.frameFloatOffset).toDouble() } } if (keyFrameCount == 1) { // Only one frame. timeline.frameIndicesOffset = -1 this._timelineArray[timelineOffset + BinaryOffset.TimelineFrameOffset + 0] = (frameParser(rawFrames[0], 0, 0) - this._animation!!.frameOffset).toDouble() } else { val totalFrameCount = this._animation!!.frameCount + 1 // One more frame than animation. val frameIndices = this._data!!.frameIndices val frameIndicesOffset = frameIndices.length frameIndices.length += totalFrameCount timeline.frameIndicesOffset = frameIndicesOffset //for (var i = 0, iK = 0, frameStart = 0, frameCount = 0;i < totalFrameCount; ++i) { var iK = 0 var frameStart = 0 var frameCount = 0 for (i in 0 until totalFrameCount) { if (frameStart + frameCount <= i && iK < keyFrameCount) { val rawFrame = rawFrames[iK] frameStart = i // frame.frameStart; if (iK == keyFrameCount - 1) { frameCount = this._animation!!.frameCount - frameStart } else { if (rawFrame is ActionFrame) { frameCount = this._actionFrames[iK + 1].frameStart - frameStart } else { frameCount = ObjectDataParser._getNumber(rawFrame, DataParser.DURATION, 1.0).toInt() } } this._timelineArray[timelineOffset + BinaryOffset.TimelineFrameOffset + iK] = (frameParser(rawFrame, frameStart, frameCount) - this._animation!!.frameOffset).toDouble() iK++ } frameIndices[frameIndicesOffset + i] = iK - 1 } } this._timeline = null // return timeline } protected fun _parseBoneTimeline(rawData: Any?) { val bone = this._armature?.getBone(ObjectDataParser._getString(rawData, DataParser.NAME, "")) ?: return this._bone = bone this._slot = this._armature?.getSlot(this._bone?.name) if (rawData.containsDynamic(DataParser.TRANSLATE_FRAME)) { this._frameDefaultValue = 0.0 this._frameValueScale = 1.0 val timeline = this._parseTimeline( rawData, null, DataParser.TRANSLATE_FRAME, TimelineType.BoneTranslate, FrameValueType.FLOAT, 2, this::_parseDoubleValueFrame ) if (timeline != null) { this._animation?.addBoneTimeline(bone.name, timeline) } } if (rawData.containsDynamic(DataParser.ROTATE_FRAME)) { this._frameDefaultValue = 0.0 this._frameValueScale = 1.0 val timeline = this._parseTimeline( rawData, null, DataParser.ROTATE_FRAME, TimelineType.BoneRotate, FrameValueType.FLOAT, 2, this::_parseBoneRotateFrame ) if (timeline != null) { this._animation?.addBoneTimeline(bone.name, timeline) } } if (rawData.containsDynamic(DataParser.SCALE_FRAME)) { this._frameDefaultValue = 1.0 this._frameValueScale = 1.0 val timeline = this._parseTimeline( rawData, null, DataParser.SCALE_FRAME, TimelineType.BoneScale, FrameValueType.FLOAT, 2, this::_parseBoneScaleFrame ) if (timeline != null) { this._animation?.addBoneTimeline(bone.name, timeline) } } if (rawData.containsDynamic(DataParser.FRAME)) { val timeline = this._parseTimeline( rawData, null, DataParser.FRAME, TimelineType.BoneAll, FrameValueType.FLOAT, 6, this::_parseBoneAllFrame ) if (timeline != null) { this._animation?.addBoneTimeline(bone.name, timeline) } } this._bone = null // this._slot = null // } protected fun _parseSlotTimeline(rawData: Any?) { val slot = this._armature?.getSlot(ObjectDataParser._getString(rawData, DataParser.NAME, "")) ?: return val displayTimeline: TimelineData? val colorTimeline: TimelineData? this._slot = slot if (rawData.containsDynamic(DataParser.DISPLAY_FRAME)) { displayTimeline = this._parseTimeline( rawData, null, DataParser.DISPLAY_FRAME, TimelineType.SlotDisplay, FrameValueType.STEP, 0, this::_parseSlotDisplayFrame ) } else { displayTimeline = this._parseTimeline( rawData, null, DataParser.FRAME, TimelineType.SlotDisplay, FrameValueType.STEP, 0, this::_parseSlotDisplayFrame ) } if (rawData.containsDynamic(DataParser.COLOR_FRAME)) { colorTimeline = this._parseTimeline( rawData, null, DataParser.COLOR_FRAME, TimelineType.SlotColor, FrameValueType.INT, 1, this::_parseSlotColorFrame ) } else { colorTimeline = this._parseTimeline( rawData, null, DataParser.FRAME, TimelineType.SlotColor, FrameValueType.INT, 1, this::_parseSlotColorFrame ) } if (displayTimeline != null) { this._animation?.addSlotTimeline(slot.name, displayTimeline) } if (colorTimeline != null) { this._animation?.addSlotTimeline(slot.name, colorTimeline) } this._slot = null // } @Suppress("UNUSED_PARAMETER") protected fun _parseFrame(rawData: Any?, frameStart: Int, frameCount: Int): Int { val frameOffset = this._frameArray.length this._frameArray.length += 1 this._frameArray[frameOffset + BinaryOffset.FramePosition] = frameStart.toDouble() return frameOffset } protected fun _parseTweenFrame(rawData: Any?, frameStart: Int, frameCount: Int): Int { val frameOffset = this._parseFrame(rawData, frameStart, frameCount) if (frameCount > 0) { if (rawData.containsDynamic(DataParser.CURVE)) { val sampleCount = frameCount + 1 this._helpArray.length = sampleCount val isOmited = this._samplingEasingCurve(rawData.getDynamic(DataParser.CURVE).doubleArrayList, this._helpArray) this._frameArray.length += 1 + 1 + this._helpArray.length this._frameArray[frameOffset + BinaryOffset.FrameTweenType] = TweenType.Curve.id.toDouble() this._frameArray[frameOffset + BinaryOffset.FrameTweenEasingOrCurveSampleCount] = (if (isOmited) sampleCount else -sampleCount).toDouble() //for (var i = 0; i < sampleCount; ++i) { for (i in 0 until sampleCount) { this._frameArray[frameOffset + BinaryOffset.FrameCurveSamples + i] = round(this._helpArray[i] * 10000.0) } } else { val noTween = -2.0 var tweenEasing = noTween if (rawData.containsDynamic(DataParser.TWEEN_EASING)) { tweenEasing = ObjectDataParser._getNumber(rawData, DataParser.TWEEN_EASING, noTween) } if (tweenEasing == noTween) { this._frameArray.length += 1 this._frameArray[frameOffset + BinaryOffset.FrameTweenType] = TweenType.None.id.toDouble() } else if (tweenEasing == 0.0) { this._frameArray.length += 1 this._frameArray[frameOffset + BinaryOffset.FrameTweenType] = TweenType.Line.id.toDouble() } else if (tweenEasing < 0.0) { this._frameArray.length += 1 + 1 this._frameArray[frameOffset + BinaryOffset.FrameTweenType] = TweenType.QuadIn.id.toDouble() this._frameArray[frameOffset + BinaryOffset.FrameTweenEasingOrCurveSampleCount] = round(-tweenEasing * 100.0) } else if (tweenEasing <= 1.0) { this._frameArray.length += 1 + 1 this._frameArray[frameOffset + BinaryOffset.FrameTweenType] = TweenType.QuadOut.id.toDouble() this._frameArray[frameOffset + BinaryOffset.FrameTweenEasingOrCurveSampleCount] = round(tweenEasing * 100.0) } else { this._frameArray.length += 1 + 1 this._frameArray[frameOffset + BinaryOffset.FrameTweenType] = TweenType.QuadInOut.id.toDouble() this._frameArray[frameOffset + BinaryOffset.FrameTweenEasingOrCurveSampleCount] = round(tweenEasing * 100.0 - 100.0) } } } else { this._frameArray.length += 1 this._frameArray[frameOffset + BinaryOffset.FrameTweenType] = TweenType.None.id.toDouble() } return frameOffset } protected fun _parseSingleValueFrame(rawData: Any?, frameStart: Int, frameCount: Int): Int { var frameOffset = 0 when (this._frameValueType) { FrameValueType.STEP -> { frameOffset = this._parseFrame(rawData, frameStart, frameCount) this._frameArray.length += 1 this._frameArray[frameOffset + 1] = ObjectDataParser._getNumber(rawData, DataParser.VALUE, this._frameDefaultValue) } FrameValueType.INT -> { frameOffset = this._parseTweenFrame(rawData, frameStart, frameCount) val frameValueOffset = this._frameIntArray.length this._frameIntArray.length += 1 this._frameIntArray[frameValueOffset] = round( ObjectDataParser._getNumber( rawData, DataParser.VALUE, this._frameDefaultValue ) * this._frameValueScale ).toInt() } FrameValueType.FLOAT -> { frameOffset = this._parseTweenFrame(rawData, frameStart, frameCount) val frameValueOffset = this._frameFloatArray.length this._frameFloatArray.length += 1 this._frameFloatArray[frameValueOffset] = ObjectDataParser._getNumber( rawData, DataParser.VALUE, this._frameDefaultValue ) * this._frameValueScale } } return frameOffset } protected fun _parseDoubleValueFrame(rawData: Any?, frameStart: Int, frameCount: Int): Int { var frameOffset = 0 when (this._frameValueType) { FrameValueType.STEP -> { frameOffset = this._parseFrame(rawData, frameStart, frameCount) this._frameArray.length += 2 this._frameArray[frameOffset + 1] = ObjectDataParser._getNumber(rawData, DataParser.X, this._frameDefaultValue) this._frameArray[frameOffset + 2] = ObjectDataParser._getNumber(rawData, DataParser.Y, this._frameDefaultValue) } FrameValueType.INT -> { frameOffset = this._parseTweenFrame(rawData, frameStart, frameCount) val frameValueOffset = this._frameIntArray.length this._frameIntArray.length += 2 this._frameIntArray[frameValueOffset] = round( ObjectDataParser._getNumber( rawData, DataParser.X, this._frameDefaultValue ) * this._frameValueScale ).toInt() this._frameIntArray[frameValueOffset + 1] = round( ObjectDataParser._getNumber( rawData, DataParser.Y, this._frameDefaultValue ) * this._frameValueScale ).toInt() } FrameValueType.FLOAT -> { frameOffset = this._parseTweenFrame(rawData, frameStart, frameCount) val frameValueOffset = this._frameFloatArray.length this._frameFloatArray.length += 2 this._frameFloatArray[frameValueOffset] = ObjectDataParser._getNumber( rawData, DataParser.X, this._frameDefaultValue ) * this._frameValueScale this._frameFloatArray[frameValueOffset + 1] = ObjectDataParser._getNumber( rawData, DataParser.Y, this._frameDefaultValue ) * this._frameValueScale } } return frameOffset } protected fun _parseActionFrameRaw(frame: Any?, frameStart: Int, frameCount: Int): Int = _parseActionFrame(frame as ActionFrame, frameStart, frameCount) protected fun _parseActionFrame(frame: ActionFrame, frameStart: Int, frameCount: Int): Int { val frameOffset = this._frameArray.length val actionCount = frame.actions.length this._frameArray.length += 1 + 1 + actionCount this._frameArray[frameOffset + BinaryOffset.FramePosition] = frameStart.toDouble() this._frameArray[frameOffset + BinaryOffset.FramePosition + 1] = actionCount.toDouble() // Action count. //for (var i = 0; i < actionCount; ++i) { // Action offsets. for (i in 0 until actionCount) { // Action offsets. this._frameArray[frameOffset + BinaryOffset.FramePosition + 2 + i] = frame.actions[i].toDouble() } return frameOffset } protected fun _parseZOrderFrame(rawData: Any?, frameStart: Int, frameCount: Int): Int { val rawData = rawData as Map<String, Any?> val frameOffset = this._parseFrame(rawData, frameStart, frameCount) if (rawData.containsDynamic(DataParser.Z_ORDER)) { val rawZOrder = rawData[DataParser.Z_ORDER] .doubleArray if (rawZOrder.size > 0) { val slotCount = this._armature!!.sortedSlots.length val unchanged = IntArray(slotCount - rawZOrder.size / 2) val zOrders = IntArray(slotCount) //for (var i = 0; i < unchanged.length; ++i) { for (i in 0 until unchanged.size) { unchanged[i] = 0 } //for (var i = 0; i < slotCount; ++i) { for (i in 0 until slotCount) { zOrders[i] = -1 } var originalIndex = 0 var unchangedIndex = 0 //for (var i = 0, l = rawZOrder.length; i < l; i += 2) { for (i in 0 until rawZOrder.size step 2) { val slotIndex = rawZOrder[i].toInt() val zOrderOffset = rawZOrder[i + 1].toInt() while (originalIndex != slotIndex) { unchanged[unchangedIndex++] = originalIndex++ } val index = originalIndex + zOrderOffset zOrders[index] = originalIndex++ } while (originalIndex < slotCount) { unchanged[unchangedIndex++] = originalIndex++ } this._frameArray.length += 1 + slotCount this._frameArray[frameOffset + 1] = slotCount.toDouble() var i = slotCount while (i-- > 0) { if (zOrders[i] == -1) { this._frameArray[frameOffset + 2 + i] = unchanged[--unchangedIndex].toDouble() } else { this._frameArray[frameOffset + 2 + i] = zOrders[i].toDouble() } } return frameOffset } } this._frameArray.length += 1 this._frameArray[frameOffset + 1] = 0.0 return frameOffset } protected fun _parseBoneAllFrame(rawData: Any?, frameStart: Int, frameCount: Int): Int { this._helpTransform.identity() if (rawData.containsDynamic(DataParser.TRANSFORM)) { this._parseTransform(rawData.getDynamic(DataParser.TRANSFORM), this._helpTransform, 1.0) } // Modify rotation. var rotation = this._helpTransform.rotation if (frameStart != 0) { if (this._prevClockwise == 0.0) { rotation = (this._prevRotation + TransformDb.normalizeRadian(rotation - this._prevRotation)).toFloat() } else { if (if (this._prevClockwise > 0) rotation >= this._prevRotation else rotation <= this._prevRotation) { this._prevClockwise = if (this._prevClockwise > 0) this._prevClockwise - 1 else this._prevClockwise + 1 } rotation = (this._prevRotation + rotation - this._prevRotation + TransformDb.PI_D * this._prevClockwise).toFloat() } } this._prevClockwise = ObjectDataParser._getNumber(rawData, DataParser.TWEEN_ROTATE, 0.0) this._prevRotation = rotation.toDouble() // val frameOffset = this._parseTweenFrame(rawData, frameStart, frameCount) var frameFloatOffset = this._frameFloatArray.length this._frameFloatArray.length += 6 this._frameFloatArray[frameFloatOffset++] = this._helpTransform.xf.toDouble() this._frameFloatArray[frameFloatOffset++] = this._helpTransform.yf.toDouble() this._frameFloatArray[frameFloatOffset++] = rotation.toDouble() this._frameFloatArray[frameFloatOffset++] = this._helpTransform.skew.toDouble() this._frameFloatArray[frameFloatOffset++] = this._helpTransform.scaleX.toDouble() this._frameFloatArray[frameFloatOffset++] = this._helpTransform.scaleY.toDouble() this._parseActionDataInFrame(rawData, frameStart, this._bone, this._slot) return frameOffset } protected fun _parseBoneTranslateFrame(rawData: Any?, frameStart: Int, frameCount: Int): Int { val frameOffset = this._parseTweenFrame(rawData, frameStart, frameCount) var frameFloatOffset = this._frameFloatArray.length this._frameFloatArray.length += 2 this._frameFloatArray[frameFloatOffset++] = ObjectDataParser._getNumber(rawData, DataParser.X, 0.0) this._frameFloatArray[frameFloatOffset++] = ObjectDataParser._getNumber(rawData, DataParser.Y, 0.0) return frameOffset } protected fun _parseBoneRotateFrame(rawData: Any?, frameStart: Int, frameCount: Int): Int { // Modify rotation. var rotation = ObjectDataParser._getNumber(rawData, DataParser.ROTATE, 0.0) * TransformDb.DEG_RAD if (frameStart != 0) { if (this._prevClockwise == 0.0) { rotation = this._prevRotation + TransformDb.normalizeRadian(rotation - this._prevRotation) } else { if (if (this._prevClockwise > 0) rotation >= this._prevRotation else rotation <= this._prevRotation) { this._prevClockwise = if (this._prevClockwise > 0) this._prevClockwise - 1 else this._prevClockwise + 1 } rotation = this._prevRotation + rotation - this._prevRotation + TransformDb.PI_D * this._prevClockwise } } this._prevClockwise = ObjectDataParser._getNumber(rawData, DataParser.CLOCK_WISE, 0.0) this._prevRotation = rotation // val frameOffset = this._parseTweenFrame(rawData, frameStart, frameCount) var frameFloatOffset = this._frameFloatArray.length this._frameFloatArray.length += 2 this._frameFloatArray[frameFloatOffset++] = rotation this._frameFloatArray[frameFloatOffset++] = ObjectDataParser._getNumber(rawData, DataParser.SKEW, 0.0) * TransformDb.DEG_RAD return frameOffset } protected fun _parseBoneScaleFrame(rawData: Any?, frameStart: Int, frameCount: Int): Int { val frameOffset = this._parseTweenFrame(rawData, frameStart, frameCount) var frameFloatOffset = this._frameFloatArray.length this._frameFloatArray.length += 2 this._frameFloatArray[frameFloatOffset++] = ObjectDataParser._getNumber(rawData, DataParser.X, 1.0) this._frameFloatArray[frameFloatOffset++] = ObjectDataParser._getNumber(rawData, DataParser.Y, 1.0) return frameOffset } protected fun _parseSlotDisplayFrame(rawData: Any?, frameStart: Int, frameCount: Int): Int { val frameOffset = this._parseFrame(rawData, frameStart, frameCount) this._frameArray.length += 1 if (rawData.containsDynamic(DataParser.VALUE)) { this._frameArray[frameOffset + 1] = ObjectDataParser._getNumber(rawData, DataParser.VALUE, 0.0) } else { this._frameArray[frameOffset + 1] = ObjectDataParser._getNumber(rawData, DataParser.DISPLAY_INDEX, 0.0) } this._parseActionDataInFrame(rawData, frameStart, this._slot?.parent, this._slot) return frameOffset } protected fun _parseSlotColorFrame(rawData: Any?, frameStart: Int, frameCount: Int): Int { val frameOffset = this._parseTweenFrame(rawData, frameStart, frameCount) var colorOffset = -1 if (rawData.containsDynamic(DataParser.VALUE) || rawData.containsDynamic(DataParser.COLOR)) { val rawColor = rawData.getDynamic(DataParser.VALUE) ?: rawData.getDynamic(DataParser.COLOR) // @TODO: Kotlin-JS: Caused by: java.lang.IllegalStateException: Value at LOOP_RANGE_ITERATOR_RESOLVED_CALL must not be null for BINARY_WITH_TYPE //for (k in (rawColor as List<Any?>)) { // Detects the presence of color. //for (let k in rawColor) { // Detects the presence of color. for (k in rawColor.dynKeys) { // Detects the presence of color. this._parseColorTransform(rawColor, this._helpColorTransform) colorOffset = this._colorArray.length this._colorArray.length += 8 this._colorArray[colorOffset++] = round(this._helpColorTransform.alphaMultiplier * 100).toInt() this._colorArray[colorOffset++] = round(this._helpColorTransform.redMultiplier * 100).toInt() this._colorArray[colorOffset++] = round(this._helpColorTransform.greenMultiplier * 100).toInt() this._colorArray[colorOffset++] = round(this._helpColorTransform.blueMultiplier * 100).toInt() this._colorArray[colorOffset++] = round(this._helpColorTransform.alphaOffset.toDouble()).toInt() this._colorArray[colorOffset++] = round(this._helpColorTransform.redOffset.toDouble()).toInt() this._colorArray[colorOffset++] = round(this._helpColorTransform.greenOffset.toDouble()).toInt() this._colorArray[colorOffset++] = round(this._helpColorTransform.blueOffset.toDouble()).toInt() colorOffset -= 8 break } } if (colorOffset < 0) { if (this._defaultColorOffset < 0) { colorOffset = this._colorArray.length this._defaultColorOffset = colorOffset this._colorArray.length += 8 this._colorArray[colorOffset++] = 100 this._colorArray[colorOffset++] = 100 this._colorArray[colorOffset++] = 100 this._colorArray[colorOffset++] = 100 this._colorArray[colorOffset++] = 0 this._colorArray[colorOffset++] = 0 this._colorArray[colorOffset++] = 0 this._colorArray[colorOffset++] = 0 } colorOffset = this._defaultColorOffset } val frameIntOffset = this._frameIntArray.length this._frameIntArray.length += 1 this._frameIntArray[frameIntOffset] = colorOffset return frameOffset } protected fun _parseSlotDeformFrame(rawData: Any?, frameStart: Int, frameCount: Int): Int { val frameFloatOffset = this._frameFloatArray.length val frameOffset = this._parseTweenFrame(rawData, frameStart, frameCount) val rawVertices = rawData.getDynamic(DataParser.VERTICES)?.doubleArray val offset = ObjectDataParser._getInt(rawData, DataParser.OFFSET, 0) // uint val vertexCount = this._intArray[this._mesh!!.geometry.offset + BinaryOffset.GeometryVertexCount] val meshName = "" + this._mesh?.parent?.name + "_" + this._slot?.name + "_" + this._mesh?.name val weight = this._mesh?.geometry!!.weight var x: Float var y: Float var iB = 0 var iV = 0 if (weight != null) { val rawSlotPose = this._weightSlotPose[meshName] this._helpMatrixA.copyFromArray(rawSlotPose!!.data, 0) this._frameFloatArray.length += weight.count * 2 iB = weight.offset + BinaryOffset.WeigthBoneIndices + weight.bones.length } else { this._frameFloatArray.length += vertexCount * 2 } //for (var i = 0; i < vertexCount * 2; i += 2) { for (i in 0 until vertexCount * 2 step 2) { if (rawVertices == null) { // Fill 0. x = 0f y = 0f } else { if (i < offset || i - offset >= rawVertices.size) { x = 0f } else { x = rawVertices[i - offset].toFloat() } if (i + 1 < offset || i + 1 - offset >= rawVertices.size) { y = 0f } else { y = rawVertices[i + 1 - offset].toFloat() } } if (weight != null) { // If mesh is skinned, transform point by bone bind pose. val rawBonePoses = this._weightBonePoses[meshName]!! val vertexBoneCount = this._intArray[iB++] this._helpMatrixA.deltaTransformPoint(x, y, this._helpPoint) x = this._helpPoint.xf y = this._helpPoint.yf //for (var j = 0; j < vertexBoneCount; ++j) { for (j in 0 until vertexBoneCount) { val boneIndex = this._intArray[iB++] this._helpMatrixB.copyFromArray(rawBonePoses.data, boneIndex * 7 + 1) this._helpMatrixB.invert() this._helpMatrixB.deltaTransformPoint(x, y, this._helpPoint) this._frameFloatArray[frameFloatOffset + iV++] = this._helpPoint.xf.toDouble() this._frameFloatArray[frameFloatOffset + iV++] = this._helpPoint.yf.toDouble() } } else { this._frameFloatArray[frameFloatOffset + i] = x.toDouble() this._frameFloatArray[frameFloatOffset + i + 1] = y.toDouble() } } if (frameStart == 0) { val frameIntOffset = this._frameIntArray.length this._frameIntArray.length += 1 + 1 + 1 + 1 + 1 this._frameIntArray[frameIntOffset + BinaryOffset.DeformVertexOffset] = this._mesh!!.geometry.offset this._frameIntArray[frameIntOffset + BinaryOffset.DeformCount] = this._frameFloatArray.length - frameFloatOffset this._frameIntArray[frameIntOffset + BinaryOffset.DeformValueCount] = this._frameFloatArray.length - frameFloatOffset this._frameIntArray[frameIntOffset + BinaryOffset.DeformValueOffset] = 0 this._frameIntArray[frameIntOffset + BinaryOffset.DeformFloatOffset] = frameFloatOffset - this._animation!!.frameFloatOffset this._timelineArray[this._timeline!!.offset + BinaryOffset.TimelineFrameValueCount] = (frameIntOffset - this._animation!!.frameIntOffset).toDouble() } return frameOffset } protected fun _parseIKConstraintFrame(rawData: Any?, frameStart: Int, frameCount: Int): Int { val frameOffset = this._parseTweenFrame(rawData, frameStart, frameCount) var frameIntOffset = this._frameIntArray.length this._frameIntArray.length += 2 this._frameIntArray[frameIntOffset++] = if (ObjectDataParser._getBoolean(rawData, DataParser.BEND_POSITIVE, true)) 1 else 0 this._frameIntArray[frameIntOffset++] = round(ObjectDataParser._getNumber(rawData, DataParser.WEIGHT, 1.0) * 100.0).toInt() return frameOffset } protected fun _parseActionData( rawData: Any?, type: ActionType, bone: BoneData?, slot: SlotData? ): FastArrayList<ActionData> { val actions = FastArrayList<ActionData>() if (rawData is String) { val action = pool.actionData.borrow() action.type = type action.name = rawData action.bone = bone action.slot = slot actions.add(action) } else if (rawData is List<*>) { (rawData as List<Map<String, Any?>>).fastForEach { rawAction -> val action = pool.actionData.borrow() if (rawAction.containsDynamic(DataParser.GOTO_AND_PLAY)) { action.type = ActionType.Play action.name = ObjectDataParser._getString(rawAction, DataParser.GOTO_AND_PLAY, "") } else { if (rawAction.containsDynamic(DataParser.TYPE) && rawAction[DataParser.TYPE] is String) { action.type = DataParser._getActionType(rawAction[DataParser.TYPE]?.toString()) } else { action.type = ActionType[ObjectDataParser._getInt(rawAction, DataParser.TYPE, type.id)] } action.name = ObjectDataParser._getString(rawAction, DataParser.NAME, "") } if (rawAction.containsDynamic(DataParser.BONE)) { val boneName = ObjectDataParser._getString(rawAction, DataParser.BONE, "") action.bone = this._armature?.getBone(boneName) } else { action.bone = bone } if (rawAction.containsDynamic(DataParser.SLOT)) { val slotName = ObjectDataParser._getString(rawAction, DataParser.SLOT, "") action.slot = this._armature?.getSlot(slotName) } else { action.slot = slot } var userData: UserData? = null if (rawAction.containsDynamic(DataParser.INTS)) { if (userData == null) { userData = pool.userData.borrow() } val rawInts = rawAction[DataParser.INTS] .intArrayList for (rawValue in rawInts) { userData.addInt(rawValue) } } if (rawAction.containsDynamic(DataParser.FLOATS)) { if (userData == null) { userData = pool.userData.borrow() } val rawFloats = rawAction[DataParser.FLOATS].doubleArrayList for (rawValue in rawFloats) { userData.addFloat(rawValue) } } if (rawAction.containsDynamic(DataParser.STRINGS)) { if (userData == null) { userData = pool.userData.borrow() } val rawStrings = rawAction[DataParser.STRINGS] as List<String> for (rawValue in rawStrings) { userData.addString(rawValue) } } action.data = userData actions.add(action) } } return actions } protected fun _parseDeformFrame(rawData: Any?, frameStart: Int, frameCount: Int): Int { val frameFloatOffset = this._frameFloatArray.length val frameOffset = this._parseTweenFrame(rawData, frameStart, frameCount) val rawVertices = if (rawData.containsDynamic(DataParser.VERTICES)) rawData.getDynamic(DataParser.VERTICES)?.doubleArrayList else rawData.getDynamic(DataParser.VALUE)?.doubleArrayList val offset = ObjectDataParser._getNumber(rawData, DataParser.OFFSET, 0.0).toInt() // uint val vertexCount = this._intArray[this._geometry!!.offset + BinaryOffset.GeometryVertexCount] val weight = this._geometry!!.weight var x: Double var y: Double if (weight != null) { // TODO } else { this._frameFloatArray.length += vertexCount * 2 //for (var i = 0;i < vertexCount * 2;i += 2) { for (i in 0 until (vertexCount * 2) step 2) { if (rawVertices != null) { if (i < offset || i - offset >= rawVertices.length) { x = 0.0 } else { x = rawVertices[i - offset] } if (i + 1 < offset || i + 1 - offset >= rawVertices.length) { y = 0.0 } else { y = rawVertices[i + 1 - offset] } } else { x = 0.0 y = 0.0 } this._frameFloatArray[frameFloatOffset + i] = x this._frameFloatArray[frameFloatOffset + i + 1] = y } } if (frameStart == 0) { val frameIntOffset = this._frameIntArray.length this._frameIntArray.length += 1 + 1 + 1 + 1 + 1 this._frameIntArray[frameIntOffset + BinaryOffset.DeformVertexOffset] = this._geometry!!.offset this._frameIntArray[frameIntOffset + BinaryOffset.DeformCount] = this._frameFloatArray.length - frameFloatOffset this._frameIntArray[frameIntOffset + BinaryOffset.DeformValueCount] = this._frameFloatArray.length - frameFloatOffset this._frameIntArray[frameIntOffset + BinaryOffset.DeformValueOffset] = 0 this._frameIntArray[frameIntOffset + BinaryOffset.DeformFloatOffset] = frameFloatOffset - this._animation!!.frameFloatOffset this._timelineArray[this._timeline!!.offset + BinaryOffset.TimelineFrameValueCount] = (frameIntOffset - this._animation!!.frameIntOffset).toDouble() } return frameOffset } protected fun _parseTransform(rawData: Any?, transform: TransformDb, scale: Double) { transform.xf = (ObjectDataParser._getNumber(rawData, DataParser.X, 0.0) * scale).toFloat() transform.yf = (ObjectDataParser._getNumber(rawData, DataParser.Y, 0.0) * scale).toFloat() if (rawData.containsDynamic(DataParser.ROTATE) || rawData.containsDynamic(DataParser.SKEW)) { transform.rotation = TransformDb.normalizeRadian( ObjectDataParser._getNumber( rawData, DataParser.ROTATE, 0.0 ) * TransformDb.DEG_RAD ).toFloat() transform.skew = TransformDb.normalizeRadian( ObjectDataParser._getNumber( rawData, DataParser.SKEW, 0.0 ) * TransformDb.DEG_RAD ).toFloat() } else if (rawData.containsDynamic(DataParser.SKEW_X) || rawData.containsDynamic(DataParser.SKEW_Y)) { transform.rotation = TransformDb.normalizeRadian( ObjectDataParser._getNumber( rawData, DataParser.SKEW_Y, 0.0 ) * TransformDb.DEG_RAD ).toFloat() transform.skew = (TransformDb.normalizeRadian( ObjectDataParser._getNumber( rawData, DataParser.SKEW_X, 0.0 ) * TransformDb.DEG_RAD ) - transform.rotation).toFloat() } transform.scaleX = ObjectDataParser._getNumber(rawData, DataParser.SCALE_X, 1.0).toFloat() transform.scaleY = ObjectDataParser._getNumber(rawData, DataParser.SCALE_Y, 1.0).toFloat() } protected fun _parseColorTransform(rawData: Any?, color: ColorTransform) { color.alphaMultiplier = ObjectDataParser._getNumber(rawData, DataParser.ALPHA_MULTIPLIER, 100.0) * 0.01 color.redMultiplier = ObjectDataParser._getNumber(rawData, DataParser.RED_MULTIPLIER, 100.0) * 0.01 color.greenMultiplier = ObjectDataParser._getNumber(rawData, DataParser.GREEN_MULTIPLIER, 100.0) * 0.01 color.blueMultiplier = ObjectDataParser._getNumber(rawData, DataParser.BLUE_MULTIPLIER, 100.0) * 0.01 color.alphaOffset = ObjectDataParser._getInt(rawData, DataParser.ALPHA_OFFSET, 0) color.redOffset = ObjectDataParser._getInt(rawData, DataParser.RED_OFFSET, 0) color.greenOffset = ObjectDataParser._getInt(rawData, DataParser.GREEN_OFFSET, 0) color.blueOffset = ObjectDataParser._getInt(rawData, DataParser.BLUE_OFFSET, 0) } open protected fun _parseGeometry(rawData: Any?, geometry: GeometryData) { val rawVertices = rawData.getDynamic(DataParser.VERTICES).doubleArray val vertexCount: Int = rawVertices.size / 2 // uint var triangleCount = 0 val geometryOffset = this._intArray.length val verticesOffset = this._floatArray.length // geometry.offset = geometryOffset geometry.data = this._data // this._intArray.length += 1 + 1 + 1 + 1 this._intArray[geometryOffset + BinaryOffset.GeometryVertexCount] = vertexCount this._intArray[geometryOffset + BinaryOffset.GeometryFloatOffset] = verticesOffset this._intArray[geometryOffset + BinaryOffset.GeometryWeightOffset] = -1 // // this._floatArray.length += vertexCount * 2 //for (var i = 0, l = vertexCount * 2; i < l; ++i) { for (i in 0 until vertexCount * 2) { this._floatArray[verticesOffset + i] = rawVertices[i] } if (rawData.containsDynamic(DataParser.TRIANGLES)) { val rawTriangles = rawData.getDynamic(DataParser.TRIANGLES).doubleArray triangleCount = rawTriangles.size / 3 // uint // this._intArray.length += triangleCount * 3 //for (var i = 0, l = triangleCount * 3; i < l; ++i) { for (i in 0 until triangleCount * 3) { this._intArray[geometryOffset + BinaryOffset.GeometryVertexIndices + i] = rawTriangles[i].toInt() } } // Fill triangle count. this._intArray[geometryOffset + BinaryOffset.GeometryTriangleCount] = triangleCount if (rawData.containsDynamic(DataParser.UVS)) { val rawUVs = rawData.getDynamic(DataParser.UVS).doubleArray val uvOffset = verticesOffset + vertexCount * 2 this._floatArray.length += vertexCount * 2 //for (var i = 0, l = vertexCount * 2; i < l; ++i) { for (i in 0 until vertexCount * 2) { this._floatArray[uvOffset + i] = rawUVs[i] } } if (rawData.containsDynamic(DataParser.WEIGHTS)) { val rawWeights = rawData.getDynamic(DataParser.WEIGHTS).doubleArray val weightCount = (rawWeights.size - vertexCount) / 2 // uint val weightOffset = this._intArray.length val floatOffset = this._floatArray.length var weightBoneCount = 0 val sortedBones = this._armature?.sortedBones val weight = pool.weightData.borrow() weight.count = weightCount weight.offset = weightOffset this._intArray.length += 1 + 1 + weightBoneCount + vertexCount + weightCount this._intArray[weightOffset + BinaryOffset.WeigthFloatOffset] = floatOffset if (rawData.containsDynamic(DataParser.BONE_POSE)) { val rawSlotPose = rawData.getDynamic(DataParser.SLOT_POSE).doubleArray val rawBonePoses = rawData.getDynamic(DataParser.BONE_POSE).doubleArray val weightBoneIndices = IntArrayList() weightBoneCount = (rawBonePoses.size / 7) // uint weightBoneIndices.length = weightBoneCount //for (var i = 0; i < weightBoneCount; ++i) { for (i in 0 until weightBoneCount) { val rawBoneIndex = rawBonePoses[i * 7].toInt() // uint val bone = this._rawBones[rawBoneIndex] weight.addBone(bone) weightBoneIndices[i] = rawBoneIndex this._intArray[weightOffset + BinaryOffset.WeigthBoneIndices + i] = sortedBones!!.indexOf(bone) } this._floatArray.length += weightCount * 3 this._helpMatrixA.copyFromArray(rawSlotPose, 0) // for (var i = 0, iW = 0, iB = weightOffset + BinaryOffset.WeigthBoneIndices + weightBoneCount, iV = floatOffset; i < vertexCount; ++i) { var iW = 0 var iB = weightOffset + BinaryOffset.WeigthBoneIndices + weightBoneCount var iV = floatOffset for (i in 0 until vertexCount) { val iD = i * 2 val vertexBoneCount = rawWeights[iW++].toInt() // uint this._intArray[iB++] = vertexBoneCount var x = this._floatArray[verticesOffset + iD].toFloat() var y = this._floatArray[verticesOffset + iD + 1].toFloat() this._helpMatrixA.transform(x, y, this._helpPoint) x = this._helpPoint.xf y = this._helpPoint.yf //for (var j = 0; j < vertexBoneCount; ++j) { for (j in 0 until vertexBoneCount) { val rawBoneIndex = rawWeights[iW++].toInt() // uint val boneIndex = weightBoneIndices.indexOf(rawBoneIndex) this._helpMatrixB.copyFromArray(rawBonePoses, boneIndex * 7 + 1) this._helpMatrixB.invert() this._helpMatrixB.transform(x, y, this._helpPoint) this._intArray[iB++] = boneIndex this._floatArray[iV++] = rawWeights[iW++] this._floatArray[iV++] = this._helpPoint.xf.toDouble() this._floatArray[iV++] = this._helpPoint.yf.toDouble() } } } else { val rawBones = rawData.getDynamic(DataParser.BONES).doubleArray weightBoneCount = rawBones.size //for (var i = 0; i < weightBoneCount; i++) { for (i in 0 until weightBoneCount) { val rawBoneIndex = rawBones[i].toInt() val bone = this._rawBones[rawBoneIndex] weight.addBone(bone) this._intArray[weightOffset + BinaryOffset.WeigthBoneIndices + i] = sortedBones!!.indexOf(bone) } this._floatArray.length += weightCount * 3 //for (var i = 0, iW = 0, iV = 0, iB = weightOffset + BinaryOffset.WeigthBoneIndices + weightBoneCount, iF = floatOffset; i < weightCount; i++) { var iW = 0 var iV = 0 var iB = weightOffset + BinaryOffset.WeigthBoneIndices + weightBoneCount var iF = floatOffset for (i in 0 until weightCount) { val vertexBoneCount = rawWeights[iW++].toInt() this._intArray[iB++] = vertexBoneCount //for (var j = 0; j < vertexBoneCount; j++) { for (j in 0 until vertexBoneCount) { val boneIndex = rawWeights[iW++] val boneWeight = rawWeights[iW++] val x = rawVertices[iV++] val y = rawVertices[iV++] this._intArray[iB++] = rawBones.indexOf(boneIndex) this._floatArray[iF++] = boneWeight this._floatArray[iF++] = x this._floatArray[iF++] = y } } } geometry.weight = weight } } protected open fun _parseArray(@Suppress("UNUSED_PARAMETER") rawData: Any?) { this._intArray.length = 0 this._floatArray.length = 0 this._frameIntArray.length = 0 this._frameFloatArray.length = 0 this._frameArray.length = 0 this._timelineArray.length = 0 this._colorArray.length = 0 } protected fun _modifyArray() { // Align. if ((this._intArray.length % 2) != 0) { this._intArray.push(0) } if ((this._frameIntArray.length % 2) != 0) { this._frameIntArray.push(0) } if ((this._frameArray.length % 2) != 0) { this._frameArray.push(0.0) } if ((this._timelineArray.length % 2) != 0) { //this._timelineArray.push(0) this._timelineArray.push(0.0) } if ((this._timelineArray.length % 2) != 0) { this._colorArray.push(0) } val l1 = this._intArray.length * 2 val l2 = this._floatArray.length * 4 val l3 = this._frameIntArray.length * 2 val l4 = this._frameFloatArray.length * 4 val l5 = this._frameArray.length * 2 val l6 = this._timelineArray.length * 2 val l7 = this._colorArray.length * 2 val lTotal = l1 + l2 + l3 + l4 + l5 + l6 + l7 // val binary = MemBufferAlloc(lTotal) val intArray = binary.sliceInt16BufferByteOffset(0, this._intArray.length) val floatArray = binary.sliceFloat32BufferByteOffset(l1, this._floatArray.length) val frameIntArray = binary.sliceInt16BufferByteOffset(l1 + l2, this._frameIntArray.length) val frameFloatArray = binary.sliceFloat32BufferByteOffset(l1 + l2 + l3, this._frameFloatArray.length) val frameArray = binary.sliceInt16BufferByteOffset(l1 + l2 + l3 + l4, this._frameArray.length) val timelineArray = binary.sliceUint16BufferByteOffset(l1 + l2 + l3 + l4 + l5, this._timelineArray.length) val colorArray = binary.sliceInt16BufferByteOffset(l1 + l2 + l3 + l4 + l5 + l6, this._colorArray.length) for (i in 0 until this._intArray.length) { intArray[i] = this._intArray[i].toShort() } for (i in 0 until this._floatArray.length) { floatArray[i] = this._floatArray[i].toFloat() } //for (var i = 0, l = this._frameIntArray.length; i < l; ++i) { for (i in 0 until this._frameIntArray.length) { frameIntArray[i] = this._frameIntArray[i].toShort() } //for (var i = 0, l = this._frameFloatArray.length; i < l; ++i) { for (i in 0 until this._frameFloatArray.length) { frameFloatArray[i] = this._frameFloatArray[i].toFloat() } //for (var i = 0, l = this._frameArray.length; i < l; ++i) { for (i in 0 until this._frameArray.length) { frameArray[i] = this._frameArray[i].toInt().toShort() } //for (var i = 0, l = this._timelineArray.length; i < l; ++i) { for (i in 0 until this._timelineArray.length) { timelineArray[i] = this._timelineArray[i].toInt() } //for (var i = 0, l = this._colorArray.length; i < l; ++i) { for (i in 0 until this._colorArray.length) { colorArray[i] = this._colorArray[i].toShort() } this._data?.binary = binary this._data?.intArray = intArray this._data?.floatArray = floatArray this._data?.frameIntArray = frameIntArray.toFloat() this._data?.frameFloatArray = frameFloatArray this._data?.frameArray = frameArray this._data?.timelineArray = timelineArray this._data?.colorArray = colorArray this._defaultColorOffset = -1 } override fun parseDragonBonesData(rawData: Any?, scale: Double): DragonBonesData? { //console.assert(rawData != null && rawData != null, "Data error.") val version = ObjectDataParser._getString(rawData, DataParser.VERSION, "") val compatibleVersion = ObjectDataParser._getString(rawData, DataParser.COMPATIBLE_VERSION, "") if ( DataParser.DATA_VERSIONS.indexOf(version) >= 0 || DataParser.DATA_VERSIONS.indexOf(compatibleVersion) >= 0 ) { val data = pool.dragonBonesData.borrow() data.version = version data.name = ObjectDataParser._getString(rawData, DataParser.NAME, "") data.frameRate = ObjectDataParser._getInt(rawData, DataParser.FRAME_RATE, 24) if (data.frameRate == 0) { // Data error. data.frameRate = 24 } if (rawData.containsDynamic(DataParser.ARMATURE)) { this._data = data this._parseArray(rawData) val rawArmatures = rawData.getDynamic(DataParser.ARMATURE) as List<Any?> rawArmatures.fastForEach { rawArmature -> data.addArmature(this._parseArmature(rawArmature, scale)) } if (this._data?.binary == null) { // DragonBones.webAssembly ? 0 : null; this._modifyArray() } if (rawData.containsDynamic(DataParser.STAGE)) { data.stage = data.getArmature(ObjectDataParser._getString(rawData, DataParser.STAGE, "")) } else if (data.armatureNames.length > 0) { data.stage = data.getArmature(data.armatureNames[0]) } this._data = null } if (rawData.containsDynamic(DataParser.TEXTURE_ATLAS)) { this._rawTextureAtlases = rawData.getDynamic(DataParser.TEXTURE_ATLAS).asFastArrayList() } return data } else { Console.assert( false, "Nonsupport data version: " + version + "\n" + "Please convert DragonBones data to support version.\n" + "Read more: https://github.com/DragonBones/Tools/" ) } return null } override fun parseTextureAtlasData(rawData: Any?, textureAtlasData: TextureAtlasData, scale: Double): Boolean { if (rawData == null) { if (this._rawTextureAtlases == null || this._rawTextureAtlases!!.length == 0) { return false } val rawTextureAtlas = this._rawTextureAtlases!![this._rawTextureAtlasIndex++] this.parseTextureAtlasData(rawTextureAtlas, textureAtlasData, scale) if (this._rawTextureAtlasIndex >= this._rawTextureAtlases!!.length) { this._rawTextureAtlasIndex = 0 this._rawTextureAtlases = null } return true } // Texture format. textureAtlasData.width = ObjectDataParser._getInt(rawData, DataParser.WIDTH, 0) textureAtlasData.height = ObjectDataParser._getInt(rawData, DataParser.HEIGHT, 0) textureAtlasData.scale = if (scale == 1.0) (1.0 / ObjectDataParser._getNumber(rawData, DataParser.SCALE, 1.0)) else scale textureAtlasData.name = ObjectDataParser._getString(rawData, DataParser.NAME, "") textureAtlasData.imagePath = ObjectDataParser._getString(rawData, DataParser.IMAGE_PATH, "") if (rawData.containsDynamic(DataParser.SUB_TEXTURE)) { val rawTextures = rawData.getDynamic(DataParser.SUB_TEXTURE).asFastArrayList() //for (var i = 0, l = rawTextures.length; i < l; ++i) { for (i in 0 until rawTextures.length) { val rawTexture = rawTextures[i] val frameWidth = ObjectDataParser._getNumber(rawTexture, DataParser.FRAME_WIDTH, -1.0) val frameHeight = ObjectDataParser._getNumber(rawTexture, DataParser.FRAME_HEIGHT, -1.0) val textureData = textureAtlasData.createTexture() textureData.rotated = ObjectDataParser._getBoolean(rawTexture, DataParser.ROTATED, false) textureData.name = ObjectDataParser._getString(rawTexture, DataParser.NAME, "") textureData.region.x = ObjectDataParser._getNumber(rawTexture, DataParser.X, 0.0) textureData.region.y = ObjectDataParser._getNumber(rawTexture, DataParser.Y, 0.0) textureData.region.width = ObjectDataParser._getNumber(rawTexture, DataParser.WIDTH, 0.0) textureData.region.height = ObjectDataParser._getNumber(rawTexture, DataParser.HEIGHT, 0.0) if (frameWidth > 0.0 && frameHeight > 0.0) { textureData.frame = TextureData.createRectangle() textureData.frame!!.x = ObjectDataParser._getNumber(rawTexture, DataParser.FRAME_X, 0.0) textureData.frame!!.y = ObjectDataParser._getNumber(rawTexture, DataParser.FRAME_Y, 0.0) textureData.frame!!.width = frameWidth textureData.frame!!.height = frameHeight } textureAtlasData.addTexture(textureData) } } return true } } /** * @private */ class ActionFrame { var frameStart: Int = 0 //public val actions: DoubleArrayList = DoubleArrayList() val actions: IntArrayList = IntArrayList() }
apache-2.0
7695860b26c579e57599f402cecdf8f9
34.706305
149
0.69572
3.868067
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/users/UserListRelatedUsersLoader.kt
1
3825
/* * 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.loader.users import android.content.Context import de.vanita5.microblog.library.MicroBlog import de.vanita5.microblog.library.MicroBlogException import de.vanita5.microblog.library.twitter.model.PageableResponseList import de.vanita5.microblog.library.twitter.model.Paging import de.vanita5.microblog.library.twitter.model.User import de.vanita5.twittnuker.annotation.AccountType import de.vanita5.twittnuker.exception.APINotSupportedException import de.vanita5.twittnuker.extension.model.api.microblog.mapToPaginated import de.vanita5.twittnuker.extension.model.api.toParcelable import de.vanita5.twittnuker.extension.model.newMicroBlogInstance import de.vanita5.twittnuker.model.AccountDetails import de.vanita5.twittnuker.model.ParcelableUser import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.model.pagination.PaginatedList abstract class UserListRelatedUsersLoader( context: Context, accountKey: UserKey?, private val listId: String?, private val userKey: UserKey?, private val screenName: String?, private val listName: String?, data: List<ParcelableUser>?, fromUser: Boolean ) : AbsRequestUsersLoader(context, accountKey, data, fromUser) { @Throws(MicroBlogException::class) override final fun getUsers(details: AccountDetails, paging: Paging): PaginatedList<ParcelableUser> { when (details.type) { AccountType.TWITTER -> return getTwitterUsers(details, paging).mapToPaginated { it.toParcelable(details, profileImageSize = profileImageSize) } else -> { throw APINotSupportedException(details.type) } } } protected abstract fun getByListId(microBlog: MicroBlog, listId: String, paging: Paging): PageableResponseList<User> protected abstract fun getByUserKey(microBlog: MicroBlog, listName: String, userKey: UserKey, paging: Paging): PageableResponseList<User> protected abstract fun getByScreenName(microBlog: MicroBlog, listName: String, screenName: String, paging: Paging): PageableResponseList<User> @Throws(MicroBlogException::class) private fun getTwitterUsers(details: AccountDetails, paging: Paging): PageableResponseList<User> { val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java) when { listId != null -> { return getByListId(microBlog, listId, paging) } listName != null && userKey != null -> { return getByUserKey(microBlog, listName.replace(' ', '-'), userKey, paging) } listName != null && screenName != null -> { return getByScreenName(microBlog, listName.replace(' ', '-'), screenName, paging) } } throw MicroBlogException("list_id or list_name and user_id (or screen_name) required") } }
gpl-3.0
f5f9137dec249cea6f53bb2b99c6c08e
42.977011
146
0.721307
4.647631
false
false
false
false
SapuSeven/BetterUntis
app/src/main/java/com/sapuseven/untis/data/databases/UserDatabase.kt
1
19920
package com.sapuseven.untis.data.databases import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.Cursor.FIELD_TYPE_INTEGER import android.database.Cursor.FIELD_TYPE_STRING import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.provider.BaseColumns import com.sapuseven.untis.R import com.sapuseven.untis.helpers.SerializationUtils.getJSON import com.sapuseven.untis.helpers.UserDatabaseQueryHelper.generateCreateTable import com.sapuseven.untis.helpers.UserDatabaseQueryHelper.generateDropTable import com.sapuseven.untis.helpers.UserDatabaseQueryHelper.generateValues import com.sapuseven.untis.interfaces.TableModel import com.sapuseven.untis.models.TimetableBookmark import com.sapuseven.untis.models.untis.UntisMasterData import com.sapuseven.untis.models.untis.UntisSettings import com.sapuseven.untis.models.untis.UntisUserData import com.sapuseven.untis.models.untis.masterdata.* import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString private const val DATABASE_VERSION = 7 private const val DATABASE_NAME = "userdata.db" class UserDatabase private constructor(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { companion object { const val COLUMN_NAME_USER_ID = "_user_id" private var instance: UserDatabase? = null fun createInstance(context: Context): UserDatabase { return instance ?: UserDatabase(context) } } override fun onCreate(db: SQLiteDatabase) { db.execSQL(UserDatabaseContract.Users.SQL_CREATE_ENTRIES_V7) db.execSQL(generateCreateTable<AbsenceReason>()) db.execSQL(generateCreateTable<Department>()) db.execSQL(generateCreateTable<Duty>()) db.execSQL(generateCreateTable<EventReason>()) db.execSQL(generateCreateTable<EventReasonGroup>()) db.execSQL(generateCreateTable<ExcuseStatus>()) db.execSQL(generateCreateTable<Holiday>()) db.execSQL(generateCreateTable<Klasse>()) db.execSQL(generateCreateTable<Room>()) db.execSQL(generateCreateTable<Subject>()) db.execSQL(generateCreateTable<Teacher>()) db.execSQL(generateCreateTable<TeachingMethod>()) db.execSQL(generateCreateTable<SchoolYear>()) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { var currentVersion = oldVersion while (currentVersion < newVersion) { when (currentVersion) { 1 -> { db.execSQL("ALTER TABLE ${UserDatabaseContract.Users.TABLE_NAME} RENAME TO ${UserDatabaseContract.Users.TABLE_NAME}_v1") db.execSQL(UserDatabaseContract.Users.SQL_CREATE_ENTRIES_V2) db.execSQL("INSERT INTO ${UserDatabaseContract.Users.TABLE_NAME} SELECT _id, apiUrl, NULL, user, ${UserDatabaseContract.Users.TABLE_NAME}_v1.\"key\", anonymous, timeGrid, masterDataTimestamp, userData, settings, time_created FROM ${UserDatabaseContract.Users.TABLE_NAME}_v1;") db.execSQL("DROP TABLE ${UserDatabaseContract.Users.TABLE_NAME}_v1") } 2 -> { db.execSQL("ALTER TABLE ${UserDatabaseContract.Users.TABLE_NAME} RENAME TO ${UserDatabaseContract.Users.TABLE_NAME}_v2") db.execSQL(UserDatabaseContract.Users.SQL_CREATE_ENTRIES_V3) db.execSQL("INSERT INTO ${UserDatabaseContract.Users.TABLE_NAME} SELECT * FROM ${UserDatabaseContract.Users.TABLE_NAME}_v2;") db.execSQL("DROP TABLE ${UserDatabaseContract.Users.TABLE_NAME}_v2") } 3 -> { db.execSQL("ALTER TABLE ${UserDatabaseContract.Users.TABLE_NAME} RENAME TO ${UserDatabaseContract.Users.TABLE_NAME}_v3") db.execSQL(UserDatabaseContract.Users.SQL_CREATE_ENTRIES_V4) db.execSQL("INSERT INTO ${UserDatabaseContract.Users.TABLE_NAME} SELECT * FROM ${UserDatabaseContract.Users.TABLE_NAME}_v3;") db.execSQL("DROP TABLE ${UserDatabaseContract.Users.TABLE_NAME}_v3") } 4 -> { db.execSQL("ALTER TABLE ${UserDatabaseContract.Users.TABLE_NAME} RENAME TO ${UserDatabaseContract.Users.TABLE_NAME}_v4") db.execSQL(UserDatabaseContract.Users.SQL_CREATE_ENTRIES_V5) db.execSQL( "INSERT INTO ${UserDatabaseContract.Users.TABLE_NAME} SELECT " + "${BaseColumns._ID}," + "'', " + "${UserDatabaseContract.Users.COLUMN_NAME_APIURL}, " + "${UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID}, " + "${UserDatabaseContract.Users.COLUMN_NAME_USER}, " + "${UserDatabaseContract.Users.COLUMN_NAME_KEY}, " + "${UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS}, " + "${UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID}, " + "${UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP}, " + "${UserDatabaseContract.Users.COLUMN_NAME_USERDATA}, " + "${UserDatabaseContract.Users.COLUMN_NAME_SETTINGS}, " + "${UserDatabaseContract.Users.COLUMN_NAME_CREATED} " + "FROM ${UserDatabaseContract.Users.TABLE_NAME}_v4;" ) db.execSQL("DROP TABLE ${UserDatabaseContract.Users.TABLE_NAME}_v4") } 5 -> { db.execSQL("ALTER TABLE ${UserDatabaseContract.Users.TABLE_NAME} RENAME TO ${UserDatabaseContract.Users.TABLE_NAME}_v5") db.execSQL(UserDatabaseContract.Users.SQL_CREATE_ENTRIES_V6) db.execSQL( "INSERT INTO ${UserDatabaseContract.Users.TABLE_NAME} SELECT " + "${BaseColumns._ID}," + "${UserDatabaseContract.Users.COLUMN_NAME_PROFILENAME}, " + "'', " + "${UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID}, " + "${UserDatabaseContract.Users.COLUMN_NAME_USER}, " + "${UserDatabaseContract.Users.COLUMN_NAME_KEY}, " + "${UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS}, " + "${UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID}, " + "${UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP}, " + "${UserDatabaseContract.Users.COLUMN_NAME_USERDATA}, " + "${UserDatabaseContract.Users.COLUMN_NAME_SETTINGS}, " + "${UserDatabaseContract.Users.COLUMN_NAME_CREATED} " + "FROM ${UserDatabaseContract.Users.TABLE_NAME}_v5;" ) db.execSQL("DROP TABLE ${UserDatabaseContract.Users.TABLE_NAME}_v5") } 6 -> { db.execSQL("ALTER TABLE ${UserDatabaseContract.Users.TABLE_NAME} RENAME TO ${UserDatabaseContract.Users.TABLE_NAME}_v6") db.execSQL(UserDatabaseContract.Users.SQL_CREATE_ENTRIES_V7) db.execSQL( "INSERT INTO ${UserDatabaseContract.Users.TABLE_NAME} SELECT " + "${BaseColumns._ID}," + "'', " + "${UserDatabaseContract.Users.COLUMN_NAME_APIURL}, " + "${UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID}, " + "${UserDatabaseContract.Users.COLUMN_NAME_USER}, " + "${UserDatabaseContract.Users.COLUMN_NAME_KEY}, " + "${UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS}, " + "${UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID}, " + "${UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP}, " + "${UserDatabaseContract.Users.COLUMN_NAME_USERDATA}, " + "${UserDatabaseContract.Users.COLUMN_NAME_SETTINGS}, " + "${UserDatabaseContract.Users.COLUMN_NAME_CREATED}, " + "'[]' " + "FROM ${UserDatabaseContract.Users.TABLE_NAME}_v6;" ) db.execSQL("DROP TABLE ${UserDatabaseContract.Users.TABLE_NAME}_v6") } } currentVersion++ } } fun resetDatabase(db: SQLiteDatabase) { db.execSQL(UserDatabaseContract.Users.SQL_DELETE_ENTRIES) db.execSQL(generateDropTable<AbsenceReason>()) db.execSQL(generateDropTable<Department>()) db.execSQL(generateDropTable<Duty>()) db.execSQL(generateDropTable<EventReason>()) db.execSQL(generateDropTable<EventReasonGroup>()) db.execSQL(generateDropTable<ExcuseStatus>()) db.execSQL(generateDropTable<Holiday>()) db.execSQL(generateDropTable<Klasse>()) db.execSQL(generateDropTable<Room>()) db.execSQL(generateDropTable<Subject>()) db.execSQL(generateDropTable<Teacher>()) db.execSQL(generateDropTable<TeachingMethod>()) db.execSQL(generateDropTable<SchoolYear>()) } fun addUser(user: User): Long? { val db = writableDatabase val values = ContentValues() values.put(UserDatabaseContract.Users.COLUMN_NAME_PROFILENAME, user.profileName) values.put(UserDatabaseContract.Users.COLUMN_NAME_APIURL, user.apiUrl) values.put(UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID, user.schoolId) values.put(UserDatabaseContract.Users.COLUMN_NAME_USER, user.user) values.put(UserDatabaseContract.Users.COLUMN_NAME_KEY, user.key) values.put(UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS, user.anonymous) values.put(UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID, getJSON().encodeToString<TimeGrid>(user.timeGrid)) values.put(UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP, user.masterDataTimestamp) values.put(UserDatabaseContract.Users.COLUMN_NAME_USERDATA, getJSON().encodeToString<UntisUserData>(user.userData)) user.settings?.let { values.put(UserDatabaseContract.Users.COLUMN_NAME_SETTINGS, getJSON().encodeToString<UntisSettings>(it)) } values.put(UserDatabaseContract.Users.COLUMN_NAME_USERDATA, getJSON().encodeToString<UntisUserData>(user.userData)) user.settings?.let { values.put(UserDatabaseContract.Users.COLUMN_NAME_SETTINGS, getJSON().encodeToString<UntisSettings>(it)) } values.put(UserDatabaseContract.Users.COLUMN_NAME_BOOKMARK_TIMETABLES, getJSON().encodeToString<List<TimetableBookmark>>(user.bookmarks)) val id = db.insert(UserDatabaseContract.Users.TABLE_NAME, null, values) db.close() return if (id == -1L) null else id } fun editUser(user: User): Long? { val db = writableDatabase val values = ContentValues() values.put(UserDatabaseContract.Users.COLUMN_NAME_PROFILENAME, user.profileName) values.put(UserDatabaseContract.Users.COLUMN_NAME_APIURL, user.apiUrl) values.put(UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID, user.schoolId) values.put(UserDatabaseContract.Users.COLUMN_NAME_USER, user.user) values.put(UserDatabaseContract.Users.COLUMN_NAME_KEY, user.key) values.put(UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS, user.anonymous) values.put(UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID, getJSON().encodeToString<TimeGrid>(user.timeGrid)) values.put(UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP, user.masterDataTimestamp) values.put(UserDatabaseContract.Users.COLUMN_NAME_USERDATA, getJSON().encodeToString<UntisUserData>(user.userData)) user.settings?.let { values.put(UserDatabaseContract.Users.COLUMN_NAME_SETTINGS, getJSON().encodeToString<UntisSettings>(it)) } values.put(UserDatabaseContract.Users.COLUMN_NAME_BOOKMARK_TIMETABLES, getJSON().encodeToString<List<TimetableBookmark>>(user.bookmarks)) db.update(UserDatabaseContract.Users.TABLE_NAME, values, BaseColumns._ID + "=?", arrayOf(user.id.toString())) db.close() return user.id } fun deleteUser(userId: Long) { val db = writableDatabase db.delete(UserDatabaseContract.Users.TABLE_NAME, BaseColumns._ID + "=?", arrayOf(userId.toString())) db.close() } fun getUser(id: Long): User? { val db = this.readableDatabase val cursor = db.query( UserDatabaseContract.Users.TABLE_NAME, arrayOf( BaseColumns._ID, UserDatabaseContract.Users.COLUMN_NAME_PROFILENAME, UserDatabaseContract.Users.COLUMN_NAME_APIURL, UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID, UserDatabaseContract.Users.COLUMN_NAME_USER, UserDatabaseContract.Users.COLUMN_NAME_KEY, UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS, UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID, UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP, UserDatabaseContract.Users.COLUMN_NAME_USERDATA, UserDatabaseContract.Users.COLUMN_NAME_SETTINGS, UserDatabaseContract.Users.COLUMN_NAME_CREATED, UserDatabaseContract.Users.COLUMN_NAME_BOOKMARK_TIMETABLES ), BaseColumns._ID + "=?", arrayOf(id.toString()), null, null, UserDatabaseContract.Users.COLUMN_NAME_CREATED + " DESC") if (!cursor.moveToFirst()) return null val user = User( id, cursor.getString(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_PROFILENAME)), cursor.getString(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_APIURL)), cursor.getString(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID)), cursor.getStringOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_USER)), cursor.getStringOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_KEY)), cursor.getIntOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS)) == 1, getJSON().decodeFromString( cursor.getString( cursor.getColumnIndexOrThrow( UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID ) ) ), cursor.getLong(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP)), getJSON().decodeFromString<UntisUserData>( cursor.getString( cursor.getColumnIndexOrThrow( UserDatabaseContract.Users.COLUMN_NAME_USERDATA ) ) ), cursor.getStringOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_SETTINGS)) ?.let { getJSON().decodeFromString<UntisSettings>(it) }, cursor.getLongOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_CREATED)), getJSON().decodeFromString( cursor.getString( cursor.getColumnIndexOrThrow( UserDatabaseContract.Users.COLUMN_NAME_BOOKMARK_TIMETABLES ) ) ), ) cursor.close() db.close() return user } fun getAllUsers(): List<User> { val users = ArrayList<User>() val db = this.readableDatabase val cursor = db.query( UserDatabaseContract.Users.TABLE_NAME, arrayOf( BaseColumns._ID, UserDatabaseContract.Users.COLUMN_NAME_PROFILENAME, UserDatabaseContract.Users.COLUMN_NAME_APIURL, UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID, UserDatabaseContract.Users.COLUMN_NAME_USER, UserDatabaseContract.Users.COLUMN_NAME_KEY, UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS, UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID, UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP, UserDatabaseContract.Users.COLUMN_NAME_USERDATA, UserDatabaseContract.Users.COLUMN_NAME_SETTINGS, UserDatabaseContract.Users.COLUMN_NAME_CREATED, UserDatabaseContract.Users.COLUMN_NAME_BOOKMARK_TIMETABLES ), null, null, null, null, UserDatabaseContract.Users.COLUMN_NAME_CREATED + " DESC") if (cursor.moveToFirst()) { do { users.add(User( cursor.getLongOrNull(cursor.getColumnIndexOrThrow(BaseColumns._ID)), cursor.getString(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_PROFILENAME)), cursor.getString(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_APIURL)), cursor.getString(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID)), cursor.getStringOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_USER)), cursor.getStringOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_KEY)), cursor.getInt(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS)) == 1, getJSON().decodeFromString<TimeGrid>( cursor.getString( cursor.getColumnIndexOrThrow( UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID ) ) ), cursor.getLong(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP)), getJSON().decodeFromString<UntisUserData>( cursor.getString( cursor.getColumnIndexOrThrow( UserDatabaseContract.Users.COLUMN_NAME_USERDATA ) ) ), cursor.getStringOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_SETTINGS)) ?.let { getJSON().decodeFromString<UntisSettings>(it) }, cursor.getLongOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_CREATED)), getJSON().decodeFromString( cursor.getString( cursor.getColumnIndexOrThrow( UserDatabaseContract.Users.COLUMN_NAME_BOOKMARK_TIMETABLES ) ) ) )) } while (cursor.moveToNext()) } cursor.close() db.close() return users } fun getUsersCount(): Int { val db = this.readableDatabase val cursor = db.query( UserDatabaseContract.Users.TABLE_NAME, arrayOf(BaseColumns._ID), null, null, null, null, null) val count = cursor.count cursor.close() db.close() return count } fun setAdditionalUserData( userId: Long, masterData: UntisMasterData ) { val db = writableDatabase db.beginTransaction() listOf( AbsenceReason.TABLE_NAME to masterData.absenceReasons, Department.TABLE_NAME to masterData.departments, Duty.TABLE_NAME to masterData.duties, EventReason.TABLE_NAME to masterData.eventReasons, EventReasonGroup.TABLE_NAME to masterData.eventReasonGroups, ExcuseStatus.TABLE_NAME to masterData.excuseStatuses, Holiday.TABLE_NAME to masterData.holidays, Klasse.TABLE_NAME to masterData.klassen, Room.TABLE_NAME to masterData.rooms, Subject.TABLE_NAME to masterData.subjects, Teacher.TABLE_NAME to masterData.teachers, TeachingMethod.TABLE_NAME to masterData.teachingMethods, SchoolYear.TABLE_NAME to masterData.schoolyears ).forEach { refreshAdditionalUserData(db, userId, it.first, it.second) } val values = ContentValues() values.put(UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP, masterData.timeStamp) db.update( UserDatabaseContract.Users.TABLE_NAME, values, BaseColumns._ID + "=?", arrayOf(userId.toString())) db.setTransactionSuccessful() db.endTransaction() db.close() } private fun refreshAdditionalUserData(db: SQLiteDatabase, userId: Long, tableName: String, items: List<TableModel>?) { db.delete(tableName, "$COLUMN_NAME_USER_ID=?", arrayOf(userId.toString())) items?.forEach { data -> db.insert(tableName, null, generateValues(userId, data)) } } inline fun <reified T : TableModel> getAdditionalUserData(userId: Long, table: TableModel): Map<Int, T>? { val db = readableDatabase val cursor = db.query( table.tableName, table.generateValues().keySet().toTypedArray(), "$COLUMN_NAME_USER_ID=?", arrayOf(userId.toString()), null, null, "id DESC") if (!cursor.moveToFirst()) return null val result = mutableMapOf<Int, T>() if (cursor.moveToFirst()) { do { val data = table.parseCursor(cursor) as T result[(data as TableModel).elementId] = data } while (cursor.moveToNext()) } cursor.close() db.close() return result.toMap() } class User( val id: Long? = null, val profileName: String = "", val apiUrl: String, val schoolId: String, val user: String? = null, val key: String? = null, val anonymous: Boolean = false, val timeGrid: TimeGrid, val masterDataTimestamp: Long, val userData: UntisUserData, val settings: UntisSettings? = null, val created: Long? = null, var bookmarks: List<TimetableBookmark> ) { fun getDisplayedName(context: Context): String { return when { profileName.isNotBlank() -> profileName anonymous -> context.getString(R.string.all_anonymous) else -> userData.displayName } } } } private fun Cursor.getIntOrNull(columnIndex: Int): Int? { return if (getType(columnIndex) == FIELD_TYPE_INTEGER) getInt(columnIndex) else null } private fun Cursor.getLongOrNull(columnIndex: Int): Long? { return if (getType(columnIndex) == FIELD_TYPE_INTEGER) getLong(columnIndex) else null } private fun Cursor.getStringOrNull(columnIndex: Int): String? { return if (getType(columnIndex) == FIELD_TYPE_STRING) getString(columnIndex) else null }
gpl-3.0
2331e946addb72794db8fad4f9582124
40.5
281
0.740361
4.043028
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/dataclient/mwapi/MwQueryPage.kt
1
4414
package org.wikipedia.dataclient.mwapi import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import org.wikipedia.dataclient.page.Protection import org.wikipedia.gallery.ImageInfo import org.wikipedia.page.Namespace @Serializable class MwQueryPage { @SerialName("descriptionsource") val descriptionSource: String? = null @SerialName("imageinfo") private val imageInfo: List<ImageInfo>? = null @SerialName("videoinfo") private val videoInfo: List<ImageInfo>? = null @SerialName("watchlistexpiry") private val watchlistExpiry: String? = null @SerialName("pageviews") val pageViewsMap: Map<String, Long?> = emptyMap() @SerialName("pageid") val pageId = 0 @SerialName("pageprops") val pageProps: PageProps? = null @SerialName("entityterms") val entityTerms: EntityTerms? = null private val ns = 0 private var coordinates: List<Coordinates>? = null private val thumbnail: Thumbnail? = null private val varianttitles: Map<String, String>? = null private val actions: Map<String, List<MwServiceError>>? = null val index = 0 var title: String = "" val langlinks: List<LangLink> = emptyList() val revisions: List<Revision> = emptyList() val protection: List<Protection> = emptyList() val extract: String? = null val description: String? = null private val imagerepository: String? = null var redirectFrom: String? = null var convertedFrom: String? = null var convertedTo: String? = null val watched = false val lastrevid: Long = 0 fun namespace(): Namespace { return Namespace.of(ns) } fun coordinates(): List<Coordinates>? { // TODO: Handle null values in lists during deserialization, perhaps with a new // @RequiredElements annotation and corresponding TypeAdapter coordinates = coordinates?.filterNotNull() return coordinates } fun thumbUrl(): String? { return thumbnail?.source } fun imageInfo(): ImageInfo? { return imageInfo?.get(0) ?: videoInfo?.get(0) } fun appendTitleFragment(fragment: String?) { title += "#$fragment" } fun displayTitle(langCode: String): String { return varianttitles?.get(langCode).orEmpty().ifEmpty { title } } val isImageShared: Boolean get() = imagerepository.orEmpty() == "shared" fun hasWatchlistExpiry(): Boolean { return !watchlistExpiry.isNullOrEmpty() } fun getErrorForAction(actionName: String): List<MwServiceError> { return actions?.get(actionName) ?: emptyList() } @Serializable class Revision { @SerialName("contentformat") private val contentFormat: String? = null @SerialName("contentmodel") private val contentModel: String? = null @SerialName("timestamp") val timeStamp: String = "" private val slots: Map<String, RevisionSlot>? = null val minor = false @SerialName("revid") val revId: Long = 0 @SerialName("parentid") val parentRevId: Long = 0 @SerialName("anon") val isAnon = false val size = 0 val user: String = "" val content: String = "" val comment: String = "" val parsedcomment: String = "" var diffSize = 0 fun getContentFromSlot(slot: String): String { return slots?.get(slot)?.content.orEmpty() } } @Serializable class RevisionSlot(val content: String = "", private val contentformat: String? = null, private val contentmodel: String? = null) @Serializable class LangLink(val lang: String = "", val title: String = "") @Serializable class Coordinates(val lat: Double? = null, val lon: Double? = null) @Serializable internal class Thumbnail(val source: String? = null, private val width: Int = 0, private val height: Int = 0) @Serializable class PageProps { @SerialName("wikibase_item") val wikiBaseItem: String = "" private val disambiguation: String? = null @SerialName("displaytitle") val displayTitle: String? = null } @Serializable class EntityTerms { val alias: List<String> = emptyList() val label: List<String> = emptyList() val description: List<String> = emptyList() } }
apache-2.0
f18f04e00a345698b6fe21fc7c3c3352
31.940299
87
0.645673
4.593132
false
false
false
false
slartus/4pdaClient-plus
forum/forum-impl/src/main/java/org/softeg/slartus/forpdaplus/forum/impl/ui/fingerprints/TopicsItemFingerprint.kt
1
1927
package org.softeg.slartus.forpdaplus.forum.impl.ui.fingerprints import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.BaseViewHolder import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.Item import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.ItemFingerprint import org.softeg.slartus.forpdaplus.forum.impl.R import org.softeg.slartus.forpdaplus.forum.impl.databinding.LayoutTopicsBinding class TopicsItemItemFingerprint( private val onClickListener: (view: View?, item: TopicsItemItem) -> Unit ) : ItemFingerprint<LayoutTopicsBinding, TopicsItemItem> { private val diffUtil = object : DiffUtil.ItemCallback<TopicsItemItem>() { override fun areItemsTheSame( oldItem: TopicsItemItem, newItem: TopicsItemItem ) = oldItem.id == newItem.id override fun areContentsTheSame( oldItem: TopicsItemItem, newItem: TopicsItemItem ) = oldItem == newItem } override fun getLayoutId() = R.layout.layout_topics override fun isRelativeItem(item: Item) = item is TopicsItemItem override fun getViewHolder( layoutInflater: LayoutInflater, parent: ViewGroup ): BaseViewHolder<LayoutTopicsBinding, TopicsItemItem> { val binding = LayoutTopicsBinding.inflate(layoutInflater, parent, false) return TopicsItemViewHolder(binding, onClickListener) } override fun getDiffUtil() = diffUtil } class TopicsItemViewHolder( binding: LayoutTopicsBinding, private val onClickListener: (view: View?, item: TopicsItemItem) -> Unit ) : BaseViewHolder<LayoutTopicsBinding, TopicsItemItem>(binding) { init { itemView.setOnClickListener { v -> onClickListener(v, item) } } } data class TopicsItemItem( val id: String? ) : Item
apache-2.0
19b74abb567773dff4972c7678f402fe
33.428571
80
0.737935
4.781638
false
false
false
false
wendigo/chrome-reactive-kotlin
src/main/kotlin/pl/wendigo/chrome/api/log/Types.kt
1
1685
package pl.wendigo.chrome.api.log /** * Log entry. * * @link [Log#LogEntry](https://chromedevtools.github.io/devtools-protocol/tot/Log#type-LogEntry) type documentation. */ @kotlinx.serialization.Serializable data class LogEntry( /** * Log entry source. */ val source: String, /** * Log entry severity. */ val level: String, /** * Logged text. */ val text: String, /** * Timestamp when this entry was added. */ val timestamp: pl.wendigo.chrome.api.runtime.Timestamp, /** * URL of the resource if known. */ val url: String? = null, /** * Line number in the resource. */ val lineNumber: Int? = null, /** * JavaScript stack trace. */ val stackTrace: pl.wendigo.chrome.api.runtime.StackTrace? = null, /** * Identifier of the network request associated with this entry. */ val networkRequestId: pl.wendigo.chrome.api.network.RequestId? = null, /** * Identifier of the worker associated with this entry. */ val workerId: String? = null, /** * Call arguments. */ val args: List<pl.wendigo.chrome.api.runtime.RemoteObject>? = null ) /** * Violation configuration setting. * * @link [Log#ViolationSetting](https://chromedevtools.github.io/devtools-protocol/tot/Log#type-ViolationSetting) type documentation. */ @kotlinx.serialization.Serializable data class ViolationSetting( /** * Violation type. */ val name: String, /** * Time threshold to trigger upon. */ val threshold: Double )
apache-2.0
561a632a1c96ef563e4f2ee25ca874e6
20.329114
133
0.589911
4.150246
false
false
false
false
ham1/jmeter
src/core/src/main/kotlin/org/apache/jmeter/threads/openmodel/PoissonArrivalsRamp.kt
3
4333
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jmeter.threads.openmodel import org.apiguardian.api.API import org.slf4j.LoggerFactory import java.nio.DoubleBuffer import java.util.PrimitiveIterator import java.util.Random import kotlin.math.min import kotlin.math.sqrt /** * Generates events that represent constant, linearly increasing or linearly decreasing load. * * Sample usage: * * val ramp = PoissonArrivalsRamp() * ramp.prepare(beginRate = 0.0, endRate = 1.0, duration = 10, random = ...) * while(ramp.hasNext()) { * println(ramp.nextDouble()) // -> values from 0..duration * } */ @API(status = API.Status.EXPERIMENTAL, since = "5.5") public class PoissonArrivalsRamp : PrimitiveIterator.OfDouble { private lateinit var events: DoubleBuffer private companion object { private val log = LoggerFactory.getLogger(PoissonArrivalsRamp::class.java) } override fun remove() { TODO("Element removal is not supported") } override fun hasNext(): Boolean = events.hasRemaining() /** * Returns the time of the next event `0..duration`. */ override fun nextDouble(): Double = events.get() private fun ensureCapacity(len: Int) { if (::events.isInitialized && events.capacity() >= len) { events.clear() return } events = DoubleBuffer.allocate(len) } /** * Prepares events for constant, linearly increasing or linearly decreasing load. * @param beginRate the load rate at the beginning of the interval, must be positive * @param endRate the load rate at the end of the interval, must be positive * @param duration the duration of the load interval, must be positive * @param random random number generator */ public fun prepare( beginRate: Double, endRate: Double, duration: Double, random: Random ) { val minRate = min(beginRate, endRate) // 3.7 events means 3, not 4. It ensures we always we do not overflow over duration interval val numEvents = ((beginRate + endRate) / 2 * duration).toInt() ensureCapacity(numEvents) val flatEvents = (minRate * duration).toInt() val events = events if (minRate > 0) { // Generate uniform process with minimal rate repeat(flatEvents) { events.put(random.nextDouble() * duration) } } val eventsLeft = numEvents - flatEvents if (log.isInfoEnabled) { log.info( "Generating {} events, beginRate = {} / sec, endRate = {} / sec, duration = {} sec", numEvents, beginRate, endRate, duration ) } if (beginRate != endRate && eventsLeft != 0) { // The rest is either increasing from 0 or decreasing to 0 load // For "increasing from 0 to 1" load the cumulative distribution function is x*x // so sqrt(random) generates "linearly increasing load" // and 1-sqrt(random) generates "linearly decreasing load" // See https://en.wikipedia.org/wiki/Inverse_transform_sampling repeat(eventsLeft) { var time = sqrt(random.nextDouble()) if (beginRate > endRate) { time = 1 - time } events.put(time * duration) } } events.array().sort(0, events.position()) events.flip() } }
apache-2.0
beb524ce5fd3c328ec6679fd121cfed8
35.720339
100
0.629356
4.494813
false
false
false
false
AndroidX/androidx
compose/material/material/samples/src/main/java/androidx/compose/material/samples/IconButtonSamples.kt
3
1809
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material.samples import androidx.annotation.Sampled import androidx.compose.animation.animateColorAsState import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.IconToggleButton import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color @Sampled @Composable fun IconButtonSample() { IconButton(onClick = { /* doSomething() */ }) { Icon(Icons.Filled.Favorite, contentDescription = "Localized description") } } @Sampled @Composable fun IconToggleButtonSample() { var checked by remember { mutableStateOf(false) } IconToggleButton(checked = checked, onCheckedChange = { checked = it }) { val tint by animateColorAsState(if (checked) Color(0xFFEC407A) else Color(0xFFB0BEC5)) Icon(Icons.Filled.Favorite, contentDescription = "Localized description", tint = tint) } }
apache-2.0
5bd15facd848385a7c080eaae528d51a
35.18
94
0.774461
4.327751
false
false
false
false
SimpleMobileTools/Simple-Notes
app/src/main/kotlin/com/simplemobiletools/notes/pro/interfaces/NotesDao.kt
1
824
package com.simplemobiletools.notes.pro.interfaces import androidx.room.* import com.simplemobiletools.notes.pro.models.Note @Dao interface NotesDao { @Query("SELECT * FROM notes ORDER BY title COLLATE NOCASE ASC") fun getNotes(): List<Note> @Query("SELECT * FROM notes WHERE id = :id") fun getNoteWithId(id: Long): Note? @Query("SELECT id FROM notes WHERE path = :path") fun getNoteIdWithPath(path: String): Long? @Query("SELECT id FROM notes WHERE title = :title COLLATE NOCASE") fun getNoteIdWithTitle(title: String): Long? @Query("SELECT id FROM notes WHERE title = :title") fun getNoteIdWithTitleCaseSensitive(title: String): Long? @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertOrUpdate(note: Note): Long @Delete fun deleteNote(note: Note) }
gpl-3.0
8d1d8a828f1544e453ed1a8835ef8792
28.428571
70
0.712379
4.140704
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/stories/tabs/ConversationListTabsFragment.kt
1
5005
package org.thoughtcrime.securesms.stories.tabs import android.animation.Animator import android.animation.AnimatorSet import android.animation.ValueAnimator import android.os.Bundle import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.core.content.ContextCompat import androidx.core.view.animation.PathInterpolatorCompat import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.airbnb.lottie.LottieAnimationView import com.airbnb.lottie.LottieProperty import com.airbnb.lottie.model.KeyPath import org.signal.core.util.DimensionUnit import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.util.visible import java.text.NumberFormat /** * Displays the "Chats" and "Stories" tab to a user. */ class ConversationListTabsFragment : Fragment(R.layout.conversation_list_tabs) { private val viewModel: ConversationListTabsViewModel by viewModels(ownerProducer = { requireActivity() }) private lateinit var chatsUnreadIndicator: TextView private lateinit var storiesUnreadIndicator: TextView private lateinit var chatsIcon: LottieAnimationView private lateinit var storiesIcon: LottieAnimationView private lateinit var chatsPill: ImageView private lateinit var storiesPill: ImageView private var shouldBeImmediate = true private var pillAnimator: Animator? = null override fun onViewCreated(view: View, savedInstanceState: Bundle?) { chatsUnreadIndicator = view.findViewById(R.id.chats_unread_indicator) storiesUnreadIndicator = view.findViewById(R.id.stories_unread_indicator) chatsIcon = view.findViewById(R.id.chats_tab_icon) storiesIcon = view.findViewById(R.id.stories_tab_icon) chatsPill = view.findViewById(R.id.chats_pill) storiesPill = view.findViewById(R.id.stories_pill) val iconTint = ContextCompat.getColor(requireContext(), R.color.signal_colorOnSecondaryContainer) chatsIcon.addValueCallback( KeyPath("**"), LottieProperty.COLOR ) { iconTint } storiesIcon.addValueCallback( KeyPath("**"), LottieProperty.COLOR ) { iconTint } view.findViewById<View>(R.id.chats_tab_touch_point).setOnClickListener { viewModel.onChatsSelected() } view.findViewById<View>(R.id.stories_tab_touch_point).setOnClickListener { viewModel.onStoriesSelected() } viewModel.state.observe(viewLifecycleOwner) { update(it, shouldBeImmediate) shouldBeImmediate = false } } private fun update(state: ConversationListTabsState, immediate: Boolean) { chatsIcon.isSelected = state.tab == ConversationListTab.CHATS chatsPill.isSelected = state.tab == ConversationListTab.CHATS storiesIcon.isSelected = state.tab == ConversationListTab.STORIES storiesPill.isSelected = state.tab == ConversationListTab.STORIES val hasStateChange = state.tab != state.prevTab if (immediate) { chatsIcon.pauseAnimation() storiesIcon.pauseAnimation() chatsIcon.progress = if (state.tab == ConversationListTab.CHATS) 1f else 0f storiesIcon.progress = if (state.tab == ConversationListTab.STORIES) 1f else 0f runPillAnimation(0, chatsPill, storiesPill) } else if (hasStateChange) { runLottieAnimations(chatsIcon, storiesIcon) runPillAnimation(150, chatsPill, storiesPill) } chatsUnreadIndicator.visible = state.unreadChatsCount > 0 chatsUnreadIndicator.text = formatCount(state.unreadChatsCount) storiesUnreadIndicator.visible = state.unreadStoriesCount > 0 storiesUnreadIndicator.text = formatCount(state.unreadStoriesCount) requireView().visible = state.visibilityState.isVisible() } private fun runLottieAnimations(vararg toAnimate: LottieAnimationView) { toAnimate.forEach { if (it.isSelected) { it.resumeAnimation() } else { if (it.isAnimating) { it.pauseAnimation() } it.progress = 0f } } } private fun runPillAnimation(duration: Long, vararg toAnimate: ImageView) { val (selected, unselected) = toAnimate.partition { it.isSelected } pillAnimator?.cancel() pillAnimator = AnimatorSet().apply { this.duration = duration interpolator = PathInterpolatorCompat.create(0.17f, 0.17f, 0f, 1f) playTogether( selected.map { view -> view.visibility = View.VISIBLE ValueAnimator.ofInt(view.paddingLeft, 0).apply { addUpdateListener { view.setPadding(it.animatedValue as Int, 0, it.animatedValue as Int, 0) } } } ) start() } unselected.forEach { val smallPad = DimensionUnit.DP.toPixels(16f).toInt() it.setPadding(smallPad, 0, smallPad, 0) it.visibility = View.INVISIBLE } } private fun formatCount(count: Long): String { if (count > 99L) { return getString(R.string.ConversationListTabs__99p) } return NumberFormat.getInstance().format(count) } }
gpl-3.0
37e67b9b8aacb95c6f42d64a4840ccf6
32.366667
107
0.729271
4.50495
false
false
false
false
androidx/androidx
camera/camera-camera2-pipe-integration/src/test/java/androidx/camera/camera2/pipe/integration/testing/FakeCameraDevicesWithCameraMetaData.kt
3
1580
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.camera2.pipe.integration.testing import androidx.camera.camera2.pipe.CameraDevices import androidx.camera.camera2.pipe.CameraId import androidx.camera.camera2.pipe.CameraMetadata import kotlinx.coroutines.runBlocking class FakeCameraDevicesWithCameraMetaData( private val cameraMetadataMap: Map<CameraId, CameraMetadata>, private val defaultCameraMetadata: CameraMetadata ) : CameraDevices { @Deprecated( message = "findAll may block the calling thread and is deprecated.", replaceWith = ReplaceWith("ids"), level = DeprecationLevel.WARNING ) override fun findAll(): List<CameraId> = runBlocking { ids() } override suspend fun ids(): List<CameraId> = cameraMetadataMap.keys.toList() override suspend fun getMetadata(camera: CameraId): CameraMetadata = awaitMetadata(camera) override fun awaitMetadata(camera: CameraId) = cameraMetadataMap[camera] ?: defaultCameraMetadata }
apache-2.0
74e66ce179f316a738443c17891f799f
40.605263
94
0.756962
4.606414
false
false
false
false
crabzilla/crabzilla
crabzilla-stack/src/main/kotlin/io/github/crabzilla/stack/command/internal/DefaultCommandServiceApi.kt
1
10963
package io.github.crabzilla.stack.command.internal import io.github.crabzilla.core.CommandSession import io.github.crabzilla.stack.* import io.github.crabzilla.stack.CrabzillaContext.Companion.POSTGRES_NOTIFICATION_CHANNEL import io.github.crabzilla.stack.command.CommandServiceApi import io.github.crabzilla.stack.command.CommandServiceConfig import io.github.crabzilla.stack.command.CommandServiceException import io.github.crabzilla.stack.command.CommandServiceException.ConcurrencyException import io.github.crabzilla.stack.command.CommandServiceOptions import io.vertx.core.Future import io.vertx.core.Future.failedFuture import io.vertx.core.Future.succeededFuture import io.vertx.core.Promise import io.vertx.core.json.JsonArray import io.vertx.core.json.JsonObject import io.vertx.sqlclient.* import org.slf4j.LoggerFactory import java.time.Instant import java.util.* internal class DefaultCommandServiceApi<S : Any, C : Any, E : Any>( private val crabzillaContext: CrabzillaContext, private val commandServiceConfig: CommandServiceConfig<S, C, E>, private val serDer: JsonObjectSerDer<S, C, E>, private val options: CommandServiceOptions = CommandServiceOptions(), ) : CommandServiceApi<C> { companion object { const val SQL_LOCK = """ SELECT pg_try_advisory_xact_lock($1, $2) as locked """ const val GET_EVENTS_BY_ID = """ SELECT id, event_type, event_payload, version, causation_id, correlation_id FROM events WHERE state_id = $1 ORDER BY sequence """ const val SQL_APPEND_EVENT = """ INSERT INTO events (event_type, causation_id, correlation_id, state_type, state_id, event_payload, version, id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) returning sequence""" const val SQL_APPEND_CMD = """ INSERT INTO commands (state_id, causation_id, last_causation_id, cmd_payload) VALUES ($1, $2, $3, $4)""" const val correlationIdIndex = 2 const val eventPayloadIndex = 5 const val currentVersionIndex = 6 const val eventIdIndex = 7 } private val streamName = commandServiceConfig.stateClass.simpleName!! private val log = LoggerFactory.getLogger("${DefaultCommandServiceApi::class.java.simpleName}-$streamName") override fun handle(stateId: UUID, command: C, versionPredicate: ((Int) -> Boolean)?): Future<EventMetadata> { return crabzillaContext.pgPool().withTransaction { conn: SqlConnection -> handle(conn, stateId, command, versionPredicate) } } override fun withinTransaction(f: (SqlConnection) -> Future<EventMetadata>): Future<EventMetadata> { return crabzillaContext.pgPool().withTransaction(f) } override fun handle(conn: SqlConnection, stateId: UUID, command: C, versionPredicate: ((Int) -> Boolean)?) : Future<EventMetadata> { fun lock(conn: SqlConnection): Future<Void> { return conn .preparedQuery(SQL_LOCK) .execute(Tuple.of(streamName.hashCode(), stateId.hashCode())) .compose { pgRow -> if (pgRow.first().getBoolean("locked")) { succeededFuture() } else { failedFuture(ConcurrencyException("Can't be locked ${stateId}")) } } } fun appendEvents( conn: SqlConnection, snapshot: Snapshot<S>?, events: List<E>, ): Future<List<EventRecord>> { var resultingVersion = snapshot?.version ?: 0 val eventIds = events.map { UUID.randomUUID() } val causationIds = eventIds.toMutableList() val correlationIds = eventIds.toMutableList() val tuples = events.mapIndexed { index, event -> correlationIds[index] = snapshot?.correlationId ?: causationIds[0] val eventAsJsonObject = serDer.eventToJson(event) val eventId = eventIds[index] val type = eventAsJsonObject.getString("type") if (index == 0) { causationIds[0] = snapshot?.causationId ?: eventIds[0] } else { causationIds[index] = eventIds[(index - 1)] } Tuple.of(type, causationIds[index], correlationIds[index], streamName, stateId, eventAsJsonObject, ++resultingVersion, eventId ) } val appendedEventList = mutableListOf<EventRecord>() return conn.preparedQuery(SQL_APPEND_EVENT) .executeBatch(tuples) .onSuccess { rowSet -> var rs: RowSet<Row>? = rowSet List(tuples.size) { index -> val sequence = rs!!.iterator().next().getLong("sequence") val correlationId = tuples[index].getUUID(correlationIdIndex) val currentVersion = tuples[index].getInteger(currentVersionIndex) val eventId = tuples[index].getUUID(eventIdIndex) val eventPayload = tuples[index].getJsonObject(eventPayloadIndex) val eventMetadata = EventMetadata( stateType = streamName, stateId = stateId, eventId = eventId, correlationId = correlationId, causationId = eventId, eventSequence = sequence, version = currentVersion, tuples[index].getString(0) ) appendedEventList.add(EventRecord(eventMetadata, eventPayload)) rs = rs!!.next() } }.map { appendedEventList } } fun projectEvents(conn: SqlConnection, appendedEvents: List<EventRecord>, subscription: EventProjector) : Future<Void> { log.debug("Will project {} events", appendedEvents.size) val initialFuture = succeededFuture<Void>() return appendedEvents.fold( initialFuture ) { currentFuture: Future<Void>, appendedEvent: EventRecord -> currentFuture.compose { subscription.project(conn, appendedEvent) } }.mapEmpty() } fun appendCommand(conn: SqlConnection, cmdAsJson: JsonObject, stateId: UUID, causationId: UUID, lastCausationId: UUID): Future<Void> { log.debug("Will append command {} as {}", command, cmdAsJson) val params = Tuple.of(stateId, causationId, lastCausationId, cmdAsJson) return conn.preparedQuery(SQL_APPEND_CMD).execute(params).mapEmpty() } return lock(conn) .compose { log.debug("State locked {}", stateId.hashCode()) getSnapshot(conn, stateId) }.compose { snapshot: Snapshot<S>? -> if (snapshot == null) { succeededFuture(null) } else { succeededFuture(snapshot) } }.compose { snapshot: Snapshot<S>? -> log.debug("Got snapshot {}", snapshot) if (versionPredicate != null && !versionPredicate.invoke(snapshot?.version ?: 0)) { val error = "Current version ${snapshot?.version ?: 0} is invalid" failedFuture(ConcurrencyException(error)) } else { try { val session = commandServiceConfig.commandHandler.handle(command, snapshot?.state) succeededFuture(Pair(snapshot, session)) } catch (e: Exception) { val error = CommandServiceException.BusinessException(e.message ?: "Unknown") failedFuture(error) } } }.compose { pair -> val (snapshot: Snapshot<S>?, session: CommandSession<S, E>) = pair log.debug("Command handled") appendEvents(conn, snapshot, session.appliedEvents()) .map { Triple(snapshot, session, it) } }.compose { triple -> val (_, _, appendedEvents) = triple log.debug("Events appended {}", appendedEvents) if (options.eventProjector != null) { projectEvents(conn, appendedEvents, options.eventProjector) .onSuccess { log.debug("Events projected") }.map { triple } } else { log.debug("EventProjector is null, skipping projecting events") succeededFuture(triple) } }.compose { val (_, _, appendedEvents) = it val cmdAsJson = serDer.commandToJson(command) if (options.persistCommands) { appendCommand(conn, cmdAsJson, stateId, appendedEvents.first().metadata.causationId, appendedEvents.last().metadata.causationId) .map { Pair(appendedEvents, cmdAsJson) } } else { succeededFuture(Pair(appendedEvents, cmdAsJson)) } }.compose { log.debug("Command was appended") val (appendedEvents, cmdAsJson) = it if (options.eventBusTopic != null) { val message = JsonObject() .put("stateType", streamName) .put("stateId", stateId.toString()) .put("command", cmdAsJson) .put("events", JsonArray(appendedEvents.map { e -> e.toJsonObject() })) .put("timestamp", Instant.now()) crabzillaContext.vertx().eventBus().publish(options.eventBusTopic, message) log.debug("Published to topic ${options.eventBusTopic} the message ${message.encodePrettily()}") } succeededFuture(appendedEvents.last().metadata) }.onSuccess { val query = "NOTIFY $POSTGRES_NOTIFICATION_CHANNEL, '$streamName'" crabzillaContext.pgPool().preparedQuery(query).execute() .onSuccess { log.debug("Notified postgres: $query") } log.debug("Transaction committed") }.onFailure { log.debug("Transaction aborted {}", it.message) } } private fun getSnapshot(conn: SqlConnection, id: UUID): Future<Snapshot<S>?> { val promise = Promise.promise<Snapshot<S>?>() return conn .prepare(GET_EVENTS_BY_ID) .compose { pq: PreparedStatement -> var state: S? = null var latestVersion = 0 var lastCausationId: UUID? = null var lastCorrelationId: UUID? = null var error: Throwable? = null // Fetch 1000 rows at a time val stream: RowStream<Row> = pq.createStream(options.eventStreamSize, Tuple.of(id)) // Use the stream stream.handler { row: Row -> latestVersion = row.getInteger("version") lastCausationId = row.getUUID("id") lastCorrelationId = row.getUUID("correlation_id") log.debug("Found event version {}, causationId {}, correlationId {}", latestVersion, lastCausationId, lastCorrelationId) state = commandServiceConfig.eventHandler .handle(state, serDer.eventFromJson(JsonObject(row.getValue("event_payload").toString()))) log.debug("State {}", state) } stream.exceptionHandler { error = it } stream.endHandler { stream.close() log.debug("End of stream") if (error != null) { promise.fail(error) } else { if (latestVersion == 0) { promise.complete(null) } else { promise.complete(Snapshot(state!!, latestVersion, lastCausationId!!, lastCorrelationId!!)) } } } promise.future() } } }
apache-2.0
702915419ce16cd6d510a42630407f26
40.214286
119
0.635957
4.592794
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/view/MySimpleAdapter.kt
1
1582
package org.andstatus.app.view import android.content.Context import android.provider.BaseColumns import android.view.View import android.view.ViewGroup import android.widget.SimpleAdapter import org.andstatus.app.context.MyPreferences class MySimpleAdapter(context: Context, data: MutableList<out MutableMap<String, *>>, resource: Int, from: Array<String?>?, to: IntArray?, val hasActionOnClick: Boolean) : SimpleAdapter(context, data, resource, from, to), View.OnClickListener { override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? { val view = super.getView(position, convertView, parent) if (!hasActionOnClick) { view.setOnClickListener(this) } return view } override fun getItemId(position: Int): Long { val item = getItem(position) as MutableMap<String, *> return try { val id = item[BaseColumns._ID] as String? id?.toLong() ?: 0 } catch (e: NumberFormatException) { throw NumberFormatException(e.message + " caused by wrong item: " + item) } } fun getPositionById(itemId: Long): Int { if (itemId != 0L) { for (position in 0 until count) { if (getItemId(position) == itemId) { return position } } } return -1 } override fun onClick(v: View) { if (!MyPreferences.isLongPressToOpenContextMenu() && v.getParent() != null) { v.showContextMenu() } } }
apache-2.0
199bb70eb957726866713f6c0e8d5f52
33.391304
165
0.609987
4.572254
false
false
false
false
crabzilla/crabzilla
crabzilla-stack/src/test/kotlin/io/github/crabzilla/example1/customer/customerDomain.kt
1
3218
package io.github.crabzilla.example1.customer import io.github.crabzilla.core.CommandHandler import io.github.crabzilla.core.CommandSession import io.github.crabzilla.core.EventHandler import io.github.crabzilla.example1.customer.CustomerCommand.* import io.github.crabzilla.example1.customer.CustomerEvent.* import java.util.* sealed interface CustomerEvent { data class CustomerRegistered(val id: UUID) : CustomerEvent data class CustomerRegisteredPrivate(val name: String) : CustomerEvent data class CustomerActivated(val reason: String) : CustomerEvent data class CustomerDeactivated(val reason: String) : CustomerEvent } sealed interface CustomerCommand { data class RegisterCustomer(val customerId: UUID, val name: String) : CustomerCommand data class ActivateCustomer(val reason: String) : CustomerCommand data class DeactivateCustomer(val reason: String) : CustomerCommand data class RegisterAndActivateCustomer( val customerId: UUID, val name: String, val reason: String ) : CustomerCommand } data class Customer(val id: UUID, val name: String? = null, val isActive: Boolean = false, val reason: String? = null) { companion object { fun create(id: UUID, name: String): List<CustomerEvent> { return listOf(CustomerRegistered(id = id), CustomerRegisteredPrivate(name)) } fun fromEvent(event: CustomerRegistered): Customer { return Customer(id = event.id, isActive = false) } } fun activate(reason: String): List<CustomerEvent> { return listOf(CustomerActivated(reason)) } fun deactivate(reason: String): List<CustomerEvent> { return listOf(CustomerDeactivated(reason)) } } val customerEventHandler = EventHandler<Customer, CustomerEvent> { state, event -> when (event) { is CustomerRegistered -> Customer.fromEvent(event) is CustomerRegisteredPrivate -> state!!.copy(name = event.name) is CustomerActivated -> state!!.copy(isActive = true, reason = event.reason) is CustomerDeactivated -> state!!.copy(isActive = false, reason = event.reason) } } class CustomerAlreadyExists(val id: UUID) : IllegalStateException("Customer $id already exists") class CustomerCommandHandler : CommandHandler<Customer, CustomerCommand, CustomerEvent>(customerEventHandler) { override fun handle(command: CustomerCommand, state: Customer?): CommandSession<Customer, CustomerEvent> { return when (command) { is RegisterCustomer -> { if (state != null) throw CustomerAlreadyExists(command.customerId) withNew(Customer.create(command.customerId, command.name)) } is RegisterAndActivateCustomer -> { if (state != null) throw CustomerAlreadyExists(command.customerId) withNew(Customer.create(command.customerId, command.name)) .execute { it.activate(command.reason) } } is ActivateCustomer -> { if (command.reason == "because I want it") throw IllegalArgumentException("Reason cannot be = [${command.reason}], please be polite.") with(state) .execute { it.activate(command.reason) } } is DeactivateCustomer -> { with(state) .execute { it.deactivate(command.reason) } } } } }
apache-2.0
c4c78449ec993f5cfb1216ed6ce21524
39.225
120
0.726227
4.469444
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/mixin/MixinModuleType.kt
1
814
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.platform.AbstractModuleType import com.demonwav.mcdev.platform.PlatformType import javax.swing.Icon object MixinModuleType : AbstractModuleType<MixinModule>("org.spongepowered", "mixin") { const val ID = "MIXIN_MODULE_TYPE" override val platformType = PlatformType.MIXIN override val icon: Icon? = null override val id = ID override val ignoredAnnotations = emptyList<String>() override val listenerAnnotations = emptyList<String>() override val hasIcon = false override fun generateModule(facet: MinecraftFacet) = MixinModule(facet) }
mit
5e1814da927e9d08cdc27869871ae604
26.133333
88
0.751843
4.284211
false
false
false
false
JakeWharton/Reagent
reagent/common/src/test/kotlin/reagent/operator/ObservableConcatMapTest.kt
1
2525
/* * Copyright 2016 Jake Wharton * * 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 reagent.operator class ObservableConcatMapTest { // TODO overload resolution doesn't work here // @Test fun concatMapObservable() = runTest { // val concatMapItems = mutableListOf<String>() // var observableCalled = 0 // // observableOf("Task", "Two") // .concatMap { // concatMapItems.add(it) // observableReturning { ++observableCalled } // } // .testObservable { // item(1) // item(2) // complete() // } // } // // @Test fun concatMapObservableEmpty() = runTest { // emptyActualObservable<String>() // .concatMap { failObservable<String>() } // .testObservable { // complete() // } // } // // @Test fun concatMapObservableError() = runTest { // val exception = RuntimeException("Oops!") // exception.toActualObservable<String>() // .concatMap { failObservable<String>() } // .testObservable { // error(exception) // } // } // // @Test fun concatMapOne() = runTest { // val concatMapItems = mutableListOf<String>() // var oneCalled = 0 // // observableOf("Task", "Two") // .concatMap { // concatMapItems.add(it) // observableReturning { ++oneCalled } // } // .testObservable { // item(1) // item(2) // complete() // } // // assertEquals(listOf("Task", "Two"), concatMapItems) // assertEquals(2, oneCalled) // } // // @Test fun concatMapOneEmpty() = runTest { // emptyActualObservable<String>() // .concatMap { failOne<String>() } // .testObservable { // complete() // } // } // // @Test fun concatMapOneError() = runTest { // val exception = RuntimeException("Oops!") // exception.toActualObservable<String>() // .concatMap { failOne<String>() } // .testObservable { // error(exception) // } // } }
apache-2.0
b2b5e20d963c06ab09d53637cf5ca57d
27.693182
75
0.592475
3.902628
false
true
false
false
jonashao/next-kotlin
app/src/main/java/com/junnanhao/next/data/ObjectBoxMusicSource.kt
1
4215
package com.junnanhao.next.data import android.app.Application import android.support.v4.media.MediaMetadataCompat import com.github.ajalt.timberkt.wtf import com.junnanhao.next.App import com.junnanhao.next.BuildConfig import com.junnanhao.next.data.model.Song import com.junnanhao.next.data.model.remote.TrackResponse import io.objectbox.Box import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory /** * Created by jonashao on 2017/9/11. * Music Provider Source implemented by ObjectBox */ class ObjectBoxMusicSource(application: Application) : MusicProviderSource { private val source: SongsDataSource = SongsRepository(application) private val retrofit: Retrofit private val service: LastFmService private val songBox: Box<Song> = (application as App).boxStore.boxFor(Song::class.java) init { val interceptor = HttpLoggingInterceptor() interceptor.level = HttpLoggingInterceptor.Level.BODY val client = OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor().apply { level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE }).build() retrofit = Retrofit.Builder() .baseUrl("http://ws.audioscrobbler.com/2.0/") .client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync()) .build() service = retrofit.create<LastFmService>(LastFmService::class.java) } override fun iterator(): Iterator<MediaMetadataCompat> { if (!source.isInitialized()) { source.scanMusic().subscribe() } return source.getSongs() .map { song -> if (song.art == null && song.mbid == null) { service.getTrack2(BuildConfig.LAST_FM_API_KEY, song.artist, song.title) .enqueue(object : Callback<TrackResponse> { override fun onFailure(call: Call<TrackResponse>?, t: Throwable?) { wtf { "t :${t?.message}" } } override fun onResponse(call: Call<TrackResponse>?, response: Response<TrackResponse>?) { val track = response?.body()?.track if (track != null) { song.mbid = track.mbid song.art = track.album?.image?. getOrNull(track.album.image.size - 1)?.url songBox.put(song) } } }) } val uri = if (song.art?.startsWith("/storage") == true) "file://${song.art}" else song.art return@map MediaMetadataCompat.Builder() .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, song.resId.toString()) .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, song.album) .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, song.artist) .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, song.duration.toLong()) .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, uri) .putString(MediaMetadataCompat.METADATA_KEY_TITLE, song.title) .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, song.path) .putString(MusicProviderSource.CUSTOM_METADATA_MBID, song.mbid) .build() }.iterator() } }
apache-2.0
7c88a1440bad970f55211eea1cf3b2f2
45.844444
125
0.566785
5.42471
false
false
false
false
bazelbuild/rules_kotlin
src/main/kotlin/io/bazel/kotlin/builder/utils/jars/JarHelper.kt
1
9623
// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Copied from bazel core and there is some code in other branches which will use the some of the unused elements. Fix // this later on. @file:Suppress("unused", "MemberVisibilityCanBePrivate") package io.bazel.kotlin.builder.utils.jars import java.io.FileNotFoundException import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.util.Calendar import java.util.GregorianCalendar import java.util.HashSet import java.util.jar.Attributes import java.util.jar.JarEntry import java.util.jar.JarFile import java.util.jar.JarOutputStream import java.util.zip.CRC32 /** * A simple helper class for creating Jar files. All Jar entries are sorted alphabetically. Allows * normalization of Jar entries by setting the timestamp of non-.class files to the DOS epoch. * Timestamps of .class files are set to the DOS epoch + 2 seconds (The zip timestamp granularity) * Adjusting the timestamp for .class files is necessary since otherwise javac will recompile java * files if both the java file and its .class file are present. */ open class JarHelper internal constructor( // The path to the Jar we want to create protected val jarPath: Path, // The properties to describe how to create the Jar protected val normalize: Boolean = true, protected val verbose: Boolean = false, compression: Boolean = true, ) { private var storageMethod: Int = JarEntry.DEFLATED // The state needed to create the Jar private val names: MutableSet<String> = HashSet() init { setCompression(compression) } /** * Enables or disables compression for the Jar file entries. * * @param compression if true enables compressions for the Jar file entries. */ private fun setCompression(compression: Boolean) { storageMethod = if (compression) JarEntry.DEFLATED else JarEntry.STORED } /** * Returns the normalized timestamp for a jar entry based on its name. This is necessary since * javac will, when loading a class X, prefer a source file to a class file, if both files have * the same timestamp. Therefore, we need to adjust the timestamp for class files to slightly * after the normalized time. * * @param name The name of the file for which we should return the normalized timestamp. * @return the time for a new Jar file entry in milliseconds since the epoch. */ private fun normalizedTimestamp(name: String): Long { return if (name.endsWith(".class")) { DEFAULT_TIMESTAMP + MINIMUM_TIMESTAMP_INCREMENT } else { DEFAULT_TIMESTAMP } } /** * Returns the time for a new Jar file entry in milliseconds since the epoch. Uses JarCreator.DEFAULT_TIMESTAMP] * for normalized entries, [System.currentTimeMillis] otherwise. * * @param filename The name of the file for which we are entering the time * @return the time for a new Jar file entry in milliseconds since the epoch. */ private fun newEntryTimeMillis(filename: String): Long { return if (normalize) normalizedTimestamp(filename) else System.currentTimeMillis() } /** * Writes an entry with specific contents to the jar. Directory entries must include the trailing * '/'. */ @Throws(IOException::class) private fun writeEntry(out: JarOutputStream, name: String, content: ByteArray) { if (names.add(name)) { // Create a new entry val entry = JarEntry(name) entry.time = newEntryTimeMillis(name) val size = content.size entry.size = size.toLong() if (size == 0) { entry.method = JarEntry.STORED entry.crc = 0 out.putNextEntry(entry) } else { entry.method = storageMethod if (storageMethod == JarEntry.STORED) { val crc = CRC32() crc.update(content) entry.crc = crc.value } out.putNextEntry(entry) out.write(content) } out.closeEntry() } } /** * Writes a standard Java manifest entry into the JarOutputStream. This includes the directory * entry for the "META-INF" directory * * @param content the Manifest content to write to the manifest entry. * @throws IOException */ @Throws(IOException::class) protected fun writeManifestEntry(out: JarOutputStream, content: ByteArray) { val oldStorageMethod = storageMethod // Do not compress small manifest files, the compressed one is frequently // larger than the original. The threshold of 256 bytes is somewhat arbitrary. if (content.size < 256) { storageMethod = JarEntry.STORED } try { writeEntry(out, MANIFEST_DIR, byteArrayOf()) writeEntry(out, MANIFEST_NAME, content) } finally { storageMethod = oldStorageMethod } } /** * Copies file or directory entries from the file system into the jar. Directory entries will be * detected and their names automatically '/' suffixed. */ @Throws(IOException::class) protected fun JarOutputStream.copyEntry(name: String, path: Path) { var normalizedName = name if (!names.contains(normalizedName)) { if (!Files.exists(path)) { throw FileNotFoundException("${path.toAbsolutePath()} (No such file or directory)") } val isDirectory = Files.isDirectory(path) if (isDirectory && !normalizedName.endsWith("/")) { normalizedName = "$normalizedName/" // always normalize directory names before checking set } if (names.add(normalizedName)) { if (verbose) { System.err.println("adding $path") } // Create a new entry val size = if (isDirectory) 0 else Files.size(path) val outEntry = JarEntry(normalizedName) val newtime = if (normalize) { normalizedTimestamp(normalizedName) } else { Files.getLastModifiedTime(path) .toMillis() } outEntry.time = newtime outEntry.size = size if (size == 0L) { outEntry.method = JarEntry.STORED outEntry.crc = 0 putNextEntry(outEntry) } else { outEntry.method = storageMethod if (storageMethod == JarEntry.STORED) { // ZipFile requires us to calculate the CRC-32 for any STORED entry. // It would be nicer to do this via DigestInputStream, but // the architecture of ZipOutputStream requires us to know the CRC-32 // before we write the data to the stream. val bytes = Files.readAllBytes(path) val crc = CRC32() crc.update(bytes) outEntry.crc = crc.value putNextEntry(outEntry) write(bytes) } else { putNextEntry(outEntry) Files.copy(path, this) } } closeEntry() } } } /** * Copies a a single entry into the jar. This variant differs from the other [copyEntry] in two ways. Firstly the * jar contents are already loaded in memory and Secondly the [name] and [path] entries don't necessarily have a * correspondence. * * @param path the path used to retrieve the timestamp in case normalize is disabled. * @param data if this is empty array then the entry is a directory. */ protected fun JarOutputStream.copyEntry( name: String, path: Path? = null, data: ByteArray = EMPTY_BYTEARRAY, ) { val outEntry = JarEntry(name) outEntry.time = when { normalize -> normalizedTimestamp(name) else -> Files.getLastModifiedTime(checkNotNull(path)).toMillis() } outEntry.size = data.size.toLong() if (data.isEmpty()) { outEntry.method = JarEntry.STORED outEntry.crc = 0 putNextEntry(outEntry) } else { outEntry.method = storageMethod if (storageMethod == JarEntry.STORED) { val crc = CRC32() crc.update(data) outEntry.crc = crc.value putNextEntry(outEntry) write(data) } else { putNextEntry(outEntry) write(data) } } closeEntry() } companion object { const val MANIFEST_DIR = "META-INF/" const val MANIFEST_NAME = JarFile.MANIFEST_NAME const val SERVICES_DIR = "META-INF/services/" internal val EMPTY_BYTEARRAY = ByteArray(0) // Normalized timestamp for zip entries // We do not include the system's default timezone and locale and additionally avoid the unix epoch // to ensure Java's zip implementation does not add the System's timezone into the extra field of the zip entry val DEFAULT_TIMESTAMP = GregorianCalendar(1980, Calendar.FEBRUARY, 1, 0, 0, 0).getTimeInMillis() // These attributes are used by JavaBuilder, Turbine, and ijar. // They must all be kept in sync. val TARGET_LABEL = Attributes.Name("Target-Label") val INJECTING_RULE_KIND = Attributes.Name("Injecting-Rule-Kind") // ZIP timestamps have a resolution of 2 seconds. // see http://www.info-zip.org/FAQ.html#limits const val MINIMUM_TIMESTAMP_INCREMENT = 2000L } }
apache-2.0
16f6d9d539d56c320a43534d9402b15c
35.176692
118
0.674634
4.473733
false
false
false
false
inorichi/tachiyomi-extensions
multisrc/overrides/fmreader/manhwa18net/src/Manhwa18NetFactory.kt
1
1841
package eu.kanade.tachiyomi.extension.all.manhwa18net import eu.kanade.tachiyomi.annotations.Nsfw import eu.kanade.tachiyomi.multisrc.fmreader.FMReader import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.SourceFactory import eu.kanade.tachiyomi.source.model.FilterList import okhttp3.Request class Manhwa18NetFactory : SourceFactory { override fun createSources(): List<Source> = listOf( Manhwa18Net(), Manhwa18NetRaw(), ) } @Nsfw class Manhwa18Net : FMReader("Manhwa18.net", "https://manhwa18.net", "en") { override fun popularMangaRequest(page: Int): Request = GET("$baseUrl/$requestPath?listType=pagination&page=$page&sort=views&sort_type=DESC&ungenre=raw", headers) override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/$requestPath?listType=pagination&page=$page&sort=last_update&sort_type=DESC&ungenre=raw", headers) override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val noRawsUrl = super.searchMangaRequest(page, query, filters).url.newBuilder().addQueryParameter("ungenre", "raw").toString() return GET(noRawsUrl, headers) } override fun getGenreList() = getAdultGenreList() } @Nsfw class Manhwa18NetRaw : FMReader("Manhwa18.net", "https://manhwa18.net", "ko") { override val requestPath = "manga-list-genre-raw.html" override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val onlyRawsUrl = super.searchMangaRequest(page, query, filters).url.newBuilder().addQueryParameter("genre", "raw").toString() return GET(onlyRawsUrl, headers) } override fun getFilterList() = FilterList(super.getFilterList().filterNot { it == GenreList(getGenreList()) }) }
apache-2.0
15f08ba6b1faafc68ec91573bf516e28
41.813953
134
0.731668
4.010893
false
false
false
false
fredyw/leetcode
src/main/kotlin/leetcode/Problem2178.kt
1
552
package leetcode /** * https://leetcode.com/problems/maximum-split-of-positive-even-integers/ */ class Problem2178 { fun maximumEvenSplit(finalSum: Long): List<Long> { val answer = mutableListOf<Long>() if (finalSum % 2L != 0L) { return answer } var n = finalSum var m = 2L while (true) { if (n - m <= m) { answer += n break } n -= m answer += m m += 2 } return answer } }
mit
96da080f64e46219c828d57dffc8a615
21.08
73
0.447464
4.058824
false
false
false
false
docker-client/docker-compose-v3
src/main/kotlin/de/gesellix/docker/compose/types/RestartPolicy.kt
1
349
package de.gesellix.docker.compose.types import com.squareup.moshi.Json data class RestartPolicy( var condition: String? = null, // Duration Delay var delay: String? = null, @Json(name = "max_attempts") var maxAttempts: Int? = null, // Duration Window var window: String? = null )
mit
812cfd4d14956390ca2ca1a017450585
19.529412
40
0.598854
4.05814
false
false
false
false
MrSugarCaney/DirtyArrows
src/main/kotlin/nl/sugcube/dirtyarrows/bow/ability/TreeBow.kt
1
4987
package nl.sugcube.dirtyarrows.bow.ability import nl.sugcube.dirtyarrows.DirtyArrows import nl.sugcube.dirtyarrows.bow.BowAbility import nl.sugcube.dirtyarrows.bow.BowType import nl.sugcube.dirtyarrows.bow.DefaultBow import nl.sugcube.dirtyarrows.util.isWater import nl.sugcube.dirtyarrows.util.showGrowthParticle import org.bukkit.Material import org.bukkit.TreeType import org.bukkit.entity.Arrow import org.bukkit.entity.Player import org.bukkit.event.entity.ProjectileHitEvent import org.bukkit.inventory.ItemStack import kotlin.random.Random /** * Shoots arrows that summons a tree on impact. * * @author SugarCaney */ open class TreeBow(plugin: DirtyArrows, val tree: Tree) : BowAbility( plugin = plugin, type = tree.bowType, canShootInProtectedRegions = false, protectionRange = 8.0, costRequirements = tree.requiredItems, description = "Spawns ${tree.treeName}." ) { override fun land(arrow: Arrow, player: Player, event: ProjectileHitEvent) { // Try a random tree type. val variant = if (arrow.location.block.isWater()) TreeType.SWAMP else tree.randomTreeType() if (arrow.world.generateTree(arrow.location, variant)) { arrow.location.showGrowthParticle() return } // Try a block lower. if (arrow.world.generateTree(arrow.location.clone().add(0.0, -1.0, 0.0), variant)) { arrow.location.showGrowthParticle() return } // If it didn't work, fallback on the default. if (arrow.world.generateTree(arrow.location, tree.defaultType)) { arrow.location.showGrowthParticle() return } // Try a block lower. if (arrow.world.generateTree(arrow.location.clone().add(0.0, -1.0, 0.0), tree.defaultType)) { arrow.location.showGrowthParticle() return } // If that didn't work, reimburse items. player.reimburseBowItems() } /** * @author SugarCaney */ enum class Tree( /** * Bow type that generates this tree. */ val bowType: BowType, /** * The 'normal' variant of the tree. */ val defaultType: TreeType, /** * The log material. */ val material: Material, /** * The damage value of the log material (for items). */ val damageValue: Short, /** * The amount of saplings required to spawn the default tree. */ val saplingCount: Int, /** * Contains a map of each tree type supported by this kind of tree. * Maps to the frequency of how many times it should generate. */ val treeTypes: Map<TreeType, Int>, /** * The name of the tree w/ article. */ val treeName: String ) { OAK(DefaultBow.OAK, TreeType.TREE, Material.OAK_LOG, 0, 1, mapOf( TreeType.TREE to 7, TreeType.BIG_TREE to 1, TreeType.SWAMP to 1 ), "an oak"), SPRUCE(DefaultBow.SPRUCE, TreeType.REDWOOD, Material.SPRUCE_LOG, 0, 1, mapOf( TreeType.REDWOOD to 7, TreeType.TALL_REDWOOD to 3, TreeType.MEGA_REDWOOD to 1 ), "a spruce tree"), BIRCH(DefaultBow.BIRCH, TreeType.BIRCH, Material.BIRCH_LOG, 0, 1, mapOf( TreeType.BIRCH to 3, TreeType.TALL_BIRCH to 1 ), "a birch"), JUNGLE(DefaultBow.JUNGLE, TreeType.JUNGLE, Material.JUNGLE_LOG, 0, 1, mapOf( TreeType.JUNGLE to 1, TreeType.SMALL_JUNGLE to 7, TreeType.JUNGLE_BUSH to 3 ), "a jungle tree"), ACACIA(DefaultBow.ACACIA, TreeType.ACACIA, Material.ACACIA_LOG, 0, 1, mapOf( TreeType.ACACIA to 1 ), "an acacia tree"), DARK_OAK(DefaultBow.DARK_OAK, TreeType.DARK_OAK, Material.DARK_OAK_LOG, 0, 4, mapOf( TreeType.DARK_OAK to 1 ), "a dark oak"); /** * The items required to use a bow of this tree type. */ val requiredItems = listOf( // ItemStack(Material.SAPLING, saplingCount, (damageValue + if (material == Material.LOG_2) 4 else 0).toShort()), ItemStack(Material.BONE_MEAL, 1) // TODO: Tree Bow required materials ) /** * Get a random TreeType for this tree. */ fun randomTreeType(): TreeType { var total = treeTypes.values.sum() treeTypes.forEach { (type, frequency) -> if (Random.nextInt(total) < frequency) return type total -= frequency } error("Problem in algorthm (total: '$total')") } } }
gpl-3.0
f2b06956849170d0924de29ac889b8cc
30.770701
128
0.566673
4.295435
false
false
false
false
google/filament
android/samples/sample-multi-view/src/main/java/com/google/android/filament/multiview/MainActivity.kt
1
18651
/* * Copyright (C) 2018 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.google.android.filament.multiview import android.animation.ValueAnimator import android.app.Activity import android.opengl.Matrix import android.os.Bundle import android.view.Choreographer import android.view.Surface import android.view.SurfaceView import android.view.animation.LinearInterpolator import com.google.android.filament.* import com.google.android.filament.RenderableManager.* import com.google.android.filament.VertexBuffer.* import com.google.android.filament.android.DisplayHelper import com.google.android.filament.android.UiHelper import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.channels.Channels import java.util.* class MainActivity : Activity() { // Make sure to initialize Filament first // This loads the JNI library needed by most API calls companion object { init { Filament.init() } } // The View we want to render into private lateinit var surfaceView: SurfaceView // UiHelper is provided by Filament to manage SurfaceView and SurfaceTexture private lateinit var uiHelper: UiHelper // Choreographer is used to schedule new frames private lateinit var choreographer: Choreographer // Engine creates and destroys Filament resources // Each engine must be accessed from a single thread of your choosing // Resources cannot be shared across engines private lateinit var engine: Engine // A renderer instance is tied to a single surface (SurfaceView, TextureView, etc.) private lateinit var renderer: Renderer // A scene holds all the renderable, lights, etc. to be drawn private lateinit var scene: Scene // A view defines a viewport, a scene and a camera for rendering private lateinit var view0: View private lateinit var view1: View private lateinit var view2: View private lateinit var view3: View private lateinit var view4: View // We need skybox to set the background color private lateinit var skybox: Skybox // Should be pretty obvious :) private lateinit var camera: Camera private lateinit var material: Material private lateinit var materialInstance: MaterialInstance private lateinit var vertexBuffer: VertexBuffer private lateinit var indexBuffer: IndexBuffer // Filament entity representing a renderable object @Entity private var renderable = 0 @Entity private var light = 0 // A swap chain is Filament's representation of a surface private var swapChain: SwapChain? = null // Performs the rendering and schedules new frames private val frameScheduler = FrameCallback() private val animator = ValueAnimator.ofFloat(0.0f, 360.0f) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) surfaceView = SurfaceView(this) setContentView(surfaceView) choreographer = Choreographer.getInstance() setupSurfaceView() setupFilament() setupViews() setupScene() } private fun setupSurfaceView() { uiHelper = UiHelper(UiHelper.ContextErrorPolicy.DONT_CHECK) uiHelper.renderCallback = SurfaceCallback() // NOTE: To choose a specific rendering resolution, add the following line: // uiHelper.setDesiredSize(1280, 720) uiHelper.attachTo(surfaceView) } private fun setupFilament() { engine = Engine.create() renderer = engine.createRenderer() scene = engine.createScene() view0 = engine.createView() view1 = engine.createView() view2 = engine.createView() view3 = engine.createView() view4 = engine.createView() view0.setName("view0"); view1.setName("view1"); view2.setName("view2"); view3.setName("view3"); view4.setName("view4"); view4.blendMode = View.BlendMode.TRANSLUCENT; skybox = Skybox.Builder().build(engine); scene.skybox = skybox camera = engine.createCamera(engine.entityManager.create()) } private fun setupViews() { view0.camera = camera view1.camera = camera view2.camera = camera view3.camera = camera view4.camera = camera view0.scene = scene view1.scene = scene view2.scene = scene view3.scene = scene view4.scene = scene } private fun setupScene() { loadMaterial() setupMaterial() createMesh() // To create a renderable we first create a generic entity renderable = EntityManager.get().create() // We then create a renderable component on that entity // A renderable is made of several primitives; in this case we declare only 1 // If we wanted each face of the cube to have a different material, we could // declare 6 primitives (1 per face) and give each of them a different material // instance, setup with different parameters RenderableManager.Builder(1) // Overall bounding box of the renderable .boundingBox(Box(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f)) // Sets the mesh data of the first primitive, 6 faces of 6 indices each .geometry(0, PrimitiveType.TRIANGLES, vertexBuffer, indexBuffer, 0, 6 * 6) // Sets the material of the first primitive .material(0, materialInstance) .build(engine, renderable) // Add the entity to the scene to render it scene.addEntity(renderable) // We now need a light, let's create a directional light light = EntityManager.get().create() // Create a color from a temperature (5,500K) val (r, g, b) = Colors.cct(5_500.0f) LightManager.Builder(LightManager.Type.DIRECTIONAL) .color(r, g, b) // Intensity of the sun in lux on a clear day .intensity(110_000.0f) // The direction is normalized on our behalf .direction(0.0f, -0.5f, -1.0f) .castShadows(true) .build(engine, light) // Add the entity to the scene to light it scene.addEntity(light) // Set the exposure on the camera, this exposure follows the sunny f/16 rule // Since we've defined a light that has the same intensity as the sun, it // guarantees a proper exposure camera.setExposure(16.0f, 1.0f / 125.0f, 100.0f) // Move the camera back to see the object camera.lookAt(0.0, 3.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) startAnimation() } private fun loadMaterial() { readUncompressedAsset("materials/lit.filamat").let { material = Material.Builder().payload(it, it.remaining()).build(engine) } } private fun setupMaterial() { // Create an instance of the material to set different parameters on it materialInstance = material.createInstance() // Specify that our color is in sRGB so the conversion to linear // is done automatically for us. If you already have a linear color // you can pass it directly, or use Colors.RgbType.LINEAR materialInstance.setParameter("baseColor", Colors.RgbType.SRGB, 1.0f, 0.85f, 0.57f) // The default value is always 0, but it doesn't hurt to be clear about our intentions // Here we are defining a dielectric material materialInstance.setParameter("metallic", 0.0f) // We increase the roughness to spread the specular highlights materialInstance.setParameter("roughness", 0.3f) } private fun createMesh() { val floatSize = 4 val shortSize = 2 // A vertex is a position + a tangent frame: // 3 floats for XYZ position, 4 floats for normal+tangents (quaternion) val vertexSize = 3 * floatSize + 4 * floatSize // Define a vertex and a function to put a vertex in a ByteBuffer @Suppress("ArrayInDataClass") data class Vertex(val x: Float, val y: Float, val z: Float, val tangents: FloatArray) fun ByteBuffer.put(v: Vertex): ByteBuffer { putFloat(v.x) putFloat(v.y) putFloat(v.z) v.tangents.forEach { putFloat(it) } return this } // 6 faces, 4 vertices per face val vertexCount = 6 * 4 // Create tangent frames, one per face val tfPX = FloatArray(4) val tfNX = FloatArray(4) val tfPY = FloatArray(4) val tfNY = FloatArray(4) val tfPZ = FloatArray(4) val tfNZ = FloatArray(4) MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, tfPX) MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, -1.0f, 0.0f, 0.0f, tfNX) MathUtils.packTangentFrame(-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, tfPY) MathUtils.packTangentFrame(-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, tfNY) MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, tfPZ) MathUtils.packTangentFrame( 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, tfNZ) val vertexData = ByteBuffer.allocate(vertexCount * vertexSize) // It is important to respect the native byte order .order(ByteOrder.nativeOrder()) // Face -Z .put(Vertex(-1.0f, -1.0f, -1.0f, tfNZ)) .put(Vertex(-1.0f, 1.0f, -1.0f, tfNZ)) .put(Vertex( 1.0f, 1.0f, -1.0f, tfNZ)) .put(Vertex( 1.0f, -1.0f, -1.0f, tfNZ)) // Face +X .put(Vertex( 1.0f, -1.0f, -1.0f, tfPX)) .put(Vertex( 1.0f, 1.0f, -1.0f, tfPX)) .put(Vertex( 1.0f, 1.0f, 1.0f, tfPX)) .put(Vertex( 1.0f, -1.0f, 1.0f, tfPX)) // Face +Z .put(Vertex(-1.0f, -1.0f, 1.0f, tfPZ)) .put(Vertex( 1.0f, -1.0f, 1.0f, tfPZ)) .put(Vertex( 1.0f, 1.0f, 1.0f, tfPZ)) .put(Vertex(-1.0f, 1.0f, 1.0f, tfPZ)) // Face -X .put(Vertex(-1.0f, -1.0f, 1.0f, tfNX)) .put(Vertex(-1.0f, 1.0f, 1.0f, tfNX)) .put(Vertex(-1.0f, 1.0f, -1.0f, tfNX)) .put(Vertex(-1.0f, -1.0f, -1.0f, tfNX)) // Face -Y .put(Vertex(-1.0f, -1.0f, 1.0f, tfNY)) .put(Vertex(-1.0f, -1.0f, -1.0f, tfNY)) .put(Vertex( 1.0f, -1.0f, -1.0f, tfNY)) .put(Vertex( 1.0f, -1.0f, 1.0f, tfNY)) // Face +Y .put(Vertex(-1.0f, 1.0f, -1.0f, tfPY)) .put(Vertex(-1.0f, 1.0f, 1.0f, tfPY)) .put(Vertex( 1.0f, 1.0f, 1.0f, tfPY)) .put(Vertex( 1.0f, 1.0f, -1.0f, tfPY)) // Make sure the cursor is pointing in the right place in the byte buffer .flip() // Declare the layout of our mesh vertexBuffer = VertexBuffer.Builder() .bufferCount(1) .vertexCount(vertexCount) // Because we interleave position and color data we must specify offset and stride // We could use de-interleaved data by declaring two buffers and giving each // attribute a different buffer index .attribute(VertexAttribute.POSITION, 0, AttributeType.FLOAT3, 0, vertexSize) .attribute(VertexAttribute.TANGENTS, 0, AttributeType.FLOAT4, 3 * floatSize, vertexSize) .build(engine) // Feed the vertex data to the mesh // We only set 1 buffer because the data is interleaved vertexBuffer.setBufferAt(engine, 0, vertexData) // Create the indices val indexData = ByteBuffer.allocate(6 * 2 * 3 * shortSize) .order(ByteOrder.nativeOrder()) repeat(6) { val i = (it * 4).toShort() indexData .putShort(i).putShort((i + 1).toShort()).putShort((i + 2).toShort()) .putShort(i).putShort((i + 2).toShort()).putShort((i + 3).toShort()) } indexData.flip() // 6 faces, 2 triangles per face, indexBuffer = IndexBuffer.Builder() .indexCount(vertexCount * 2) .bufferType(IndexBuffer.Builder.IndexType.USHORT) .build(engine) indexBuffer.setBuffer(engine, indexData) } private fun startAnimation() { // Animate the triangle animator.interpolator = LinearInterpolator() animator.duration = 6000 animator.repeatMode = ValueAnimator.RESTART animator.repeatCount = ValueAnimator.INFINITE animator.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener { val transformMatrix = FloatArray(16) override fun onAnimationUpdate(a: ValueAnimator) { Matrix.setRotateM(transformMatrix, 0, a.animatedValue as Float, 0.0f, 1.0f, 0.0f) val tcm = engine.transformManager tcm.setTransform(tcm.getInstance(renderable), transformMatrix) } }) animator.start() } override fun onResume() { super.onResume() choreographer.postFrameCallback(frameScheduler) animator.start() } override fun onPause() { super.onPause() choreographer.removeFrameCallback(frameScheduler) animator.cancel() } override fun onDestroy() { super.onDestroy() // Stop the animation and any pending frame choreographer.removeFrameCallback(frameScheduler) animator.cancel(); // Always detach the surface before destroying the engine uiHelper.detach() // Cleanup all resources engine.destroyEntity(light) engine.destroyEntity(renderable) engine.destroyRenderer(renderer) engine.destroyVertexBuffer(vertexBuffer) engine.destroyIndexBuffer(indexBuffer) engine.destroyMaterialInstance(materialInstance) engine.destroyMaterial(material) engine.destroyView(view0) engine.destroyView(view1) engine.destroyView(view2) engine.destroyView(view3) engine.destroyView(view4) engine.destroySkybox(skybox) engine.destroyScene(scene) engine.destroyCameraComponent(camera.entity) // Engine.destroyEntity() destroys Filament related resources only // (components), not the entity itself val entityManager = EntityManager.get() entityManager.destroy(light) entityManager.destroy(renderable) entityManager.destroy(camera.entity) // Destroying the engine will free up any resource you may have forgotten // to destroy, but it's recommended to do the cleanup properly engine.destroy() } inner class FrameCallback : Choreographer.FrameCallback { override fun doFrame(frameTimeNanos: Long) { // Schedule the next frame choreographer.postFrameCallback(this) // This check guarantees that we have a swap chain if (uiHelper.isReadyToRender) { // If beginFrame() returns false you should skip the frame // This means you are sending frames too quickly to the GPU if (renderer.beginFrame(swapChain!!, frameTimeNanos)) { skybox.setColor(0.035f, 0.035f, 0.035f, 1.0f); renderer.render(view0) skybox.setColor(1.0f, 0.0f, 0.0f, 1.0f); renderer.render(view1) skybox.setColor(0.0f, 1.0f, 0.0f, 1.0f); renderer.render(view2) skybox.setColor(0.0f, 0.0f, 1.0f, 1.0f); renderer.render(view3) skybox.setColor(0.0f, 0.0f, 0.0f, 0.0f); renderer.render(view4) renderer.endFrame() } } } } inner class SurfaceCallback : UiHelper.RendererCallback { override fun onNativeWindowChanged(surface: Surface) { swapChain?.let { engine.destroySwapChain(it) } swapChain = engine.createSwapChain(surface) renderer.setDisplayInfo(DisplayHelper.getDisplayInfo(surfaceView.display, Renderer.DisplayInfo())) } override fun onDetachedFromSurface() { swapChain?.let { engine.destroySwapChain(it) // Required to ensure we don't return before Filament is done executing the // destroySwapChain command, otherwise Android might destroy the Surface // too early engine.flushAndWait() swapChain = null } } override fun onResized(width: Int, height: Int) { val aspect = width.toDouble() / height.toDouble() camera.setProjection(45.0, aspect, 0.1, 20.0, Camera.Fov.VERTICAL) view0.viewport = Viewport(0, 0, width / 2, height / 2) view1.viewport = Viewport(width / 2, 0, width / 2, height / 2) view2.viewport = Viewport(0, height / 2, width / 2, height / 2) view3.viewport = Viewport(width / 2, height / 2, width / 2, height / 2) view4.viewport = Viewport(width / 4, height / 4, width / 2, height / 2) } } private fun readUncompressedAsset(assetName: String): ByteBuffer { assets.openFd(assetName).use { fd -> val input = fd.createInputStream() val dst = ByteBuffer.allocate(fd.length.toInt()) val src = Channels.newChannel(input) src.read(dst) src.close() return dst.apply { rewind() } } } }
apache-2.0
55c6321d461756107b21f49e5f9ac86b
38.43129
110
0.605866
4.170617
false
false
false
false
Heiner1/AndroidAPS
automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchTest.kt
1
4413
package info.nightscout.androidaps.plugins.general.automation.actions import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.plugins.general.automation.elements.InputProfileName import info.nightscout.androidaps.queue.Callback import org.junit.Assert import org.junit.Before import org.junit.Test import org.mockito.ArgumentMatchers import org.mockito.ArgumentMatchers.anyLong import org.mockito.Mockito import org.mockito.Mockito.`when` import org.mockito.Mockito.anyInt import org.mockito.Mockito.anyString class ActionProfileSwitchTest : ActionsTestBase() { private lateinit var sut: ActionProfileSwitch private val stringJson = "{\"data\":{\"profileToSwitchTo\":\"Test\"},\"type\":\"info.nightscout.androidaps.plugins.general.automation.actions.ActionProfileSwitch\"}" @Before fun setUp() { `when`(rh.gs(R.string.profilename)).thenReturn("Change profile to") `when`(rh.gs(ArgumentMatchers.eq(R.string.changengetoprofilename), ArgumentMatchers.anyString())).thenReturn("Change profile to %s") `when`(rh.gs(R.string.alreadyset)).thenReturn("Already set") `when`(rh.gs(R.string.notexists)).thenReturn("not exists") `when`(rh.gs(R.string.error_field_must_not_be_empty)).thenReturn("The field must not be empty") `when`(rh.gs(R.string.noprofile)).thenReturn("No profile loaded from NS yet") sut = ActionProfileSwitch(injector) } @Test fun friendlyName() { Assert.assertEquals(R.string.profilename, sut.friendlyName()) } @Test fun shortDescriptionTest() { Assert.assertEquals("Change profile to %s", sut.shortDescription()) } @Test fun doAction() { //Empty input `when`(profileFunction.getProfileName()).thenReturn("Test") sut.inputProfileName = InputProfileName(rh, activePlugin, "") sut.doAction(object : Callback() { override fun run() { Assert.assertFalse(result.success) } }) //Not initialized profileStore `when`(profileFunction.getProfile()).thenReturn(null) sut.inputProfileName = InputProfileName(rh, activePlugin, "someProfile") sut.doAction(object : Callback() { override fun run() { Assert.assertFalse(result.success) } }) //profile already set `when`(profileFunction.getProfile()).thenReturn(validProfile) `when`(profileFunction.getProfileName()).thenReturn("Test") sut.inputProfileName = InputProfileName(rh, activePlugin, "Test") sut.doAction(object : Callback() { override fun run() { Assert.assertTrue(result.success) Assert.assertEquals("Already set", result.comment) } }) // profile doesn't exists `when`(profileFunction.getProfileName()).thenReturn("Active") sut.inputProfileName = InputProfileName(rh, activePlugin, "Test") sut.doAction(object : Callback() { override fun run() { Assert.assertFalse(result.success) Assert.assertEquals("not exists", result.comment) } }) // do profile switch `when`(profileFunction.getProfileName()).thenReturn("Test") `when`(profileFunction.createProfileSwitch(anyObject(), anyString(), anyInt(), anyInt(), anyInt(), anyLong())).thenReturn(true) sut.inputProfileName = InputProfileName(rh, activePlugin, TESTPROFILENAME) sut.doAction(object : Callback() { override fun run() { Assert.assertTrue(result.success) Assert.assertEquals("OK", result.comment) } }) Mockito.verify(profileFunction, Mockito.times(1)).createProfileSwitch(anyObject(), anyString(), anyInt(), anyInt(), anyInt(), anyLong()) } @Test fun hasDialogTest() { Assert.assertTrue(sut.hasDialog()) } @Test fun toJSONTest() { sut.inputProfileName = InputProfileName(rh, activePlugin, "Test") Assert.assertEquals(stringJson, sut.toJSON()) } @Test fun fromJSONTest() { val data = "{\"profileToSwitchTo\":\"Test\"}" sut.fromJSON(data) Assert.assertEquals("Test", sut.inputProfileName.value) } @Test fun iconTest() { Assert.assertEquals(R.drawable.ic_actions_profileswitch, sut.icon()) } }
agpl-3.0
9cbd26ca9128549183649a742512a21c
38.410714
169
0.655337
4.714744
false
true
false
false
jainsahab/AndroidSnooper
Snooper/src/main/java/com/prateekj/snooper/dbreader/activity/TableDetailActivity.kt
1
3285
package com.prateekj.snooper.dbreader.activity import android.graphics.Typeface import android.os.Bundle import android.view.View.GONE import android.view.View.VISIBLE import android.widget.TableRow import android.widget.TextView import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat.getDrawable import com.prateekj.snooper.R import com.prateekj.snooper.dbreader.DatabaseDataReader import com.prateekj.snooper.dbreader.DatabaseReader import com.prateekj.snooper.dbreader.activity.DatabaseDetailActivity.Companion.TABLE_NAME import com.prateekj.snooper.dbreader.model.Table import com.prateekj.snooper.dbreader.view.TableViewCallback import com.prateekj.snooper.infra.BackgroundTaskExecutor import com.prateekj.snooper.networksnooper.activity.SnooperBaseActivity import kotlinx.android.synthetic.main.activity_table_view.* class TableDetailActivity : SnooperBaseActivity(), TableViewCallback { private lateinit var databaseReader: DatabaseReader override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_table_view) initViews() val tableName = intent.getStringExtra(TABLE_NAME) val dbPath = intent.getStringExtra(DatabaseDetailActivity.DB_PATH) val backgroundTaskExecutor = BackgroundTaskExecutor(this) databaseReader = DatabaseReader(this, backgroundTaskExecutor, DatabaseDataReader()) databaseReader.fetchTableContent(this, dbPath, tableName!!) } override fun onTableFetchStarted() { embedded_loader!!.visibility = VISIBLE } override fun onTableFetchCompleted(table: Table) { embedded_loader!!.visibility = GONE updateView(table) } private fun initViews() { setSupportActionBar(toolbar) supportActionBar!!.setDisplayHomeAsUpEnabled(true) } private fun updateView(table: Table) { addTableColumnNames(table) addTableRowsToUi(table) } private fun addTableRowsToUi(table: Table) { val rows = table.rows!! for (i in rows.indices) { table_layout!!.addView(addRowData(rows[i].data, i + 1)) } } private fun addTableColumnNames(table: Table) { val columnRow = TableRow(this) val serialNoCell = getCellView(getString(R.string.serial_number_column_heading)) serialNoCell.setTypeface(null, Typeface.BOLD) columnRow.addView(serialNoCell) for (column in table.columns!!) { val columnView = getCellView(column).apply { setBackgroundColor(ContextCompat.getColor(this@TableDetailActivity, R.color.snooper_grey)) background = getDrawable(this@TableDetailActivity, R.drawable.table_cell_background) setTypeface(null, Typeface.BOLD) } columnRow.addView(columnView) } table_layout!!.addView(columnRow) } private fun addRowData(data: List<String>, serialNumber: Int): TableRow { val row = TableRow(this) row.addView(getCellView(serialNumber.toString())) for (cellValue in data) { row.addView(getCellView(cellValue)) } return row } private fun getCellView(cellValue: String): TextView { val textView = TextView(this) textView.setPadding(1, 0, 0, 0) textView.background = getDrawable(this, R.drawable.table_cell_background) textView.text = cellValue return textView } }
apache-2.0
0c50d92f9afa6f433e488a02567193f6
33.957447
98
0.76347
4.299738
false
false
false
false
k9mail/k-9
app/core/src/main/java/com/fsck/k9/Account.kt
1
16999
package com.fsck.k9 import com.fsck.k9.backend.api.SyncConfig.ExpungePolicy import com.fsck.k9.mail.Address import com.fsck.k9.mail.ServerSettings import java.util.Calendar import java.util.Date /** * Account stores all of the settings for a single account defined by the user. Each account is defined by a UUID. */ class Account(override val uuid: String) : BaseAccount { @get:Synchronized @set:Synchronized var deletePolicy = DeletePolicy.NEVER @get:Synchronized @set:Synchronized private var internalIncomingServerSettings: ServerSettings? = null @get:Synchronized @set:Synchronized private var internalOutgoingServerSettings: ServerSettings? = null var incomingServerSettings: ServerSettings get() = internalIncomingServerSettings ?: error("Incoming server settings not set yet") set(value) { internalIncomingServerSettings = value } var outgoingServerSettings: ServerSettings get() = internalOutgoingServerSettings ?: error("Outgoing server settings not set yet") set(value) { internalOutgoingServerSettings = value } @get:Synchronized @set:Synchronized var oAuthState: String? = null /** * Storage provider ID, used to locate and manage the underlying DB/file storage. */ @get:Synchronized @set:Synchronized var localStorageProviderId: String? = null @get:Synchronized @set:Synchronized override var name: String? = null set(value) { field = value?.takeIf { it.isNotEmpty() } } @get:Synchronized @set:Synchronized var alwaysBcc: String? = null /** * -1 for never. */ @get:Synchronized @set:Synchronized var automaticCheckIntervalMinutes = 0 @get:Synchronized @set:Synchronized var displayCount = 0 set(value) { if (field != value) { field = value.takeIf { it != -1 } ?: K9.DEFAULT_VISIBLE_LIMIT isChangedVisibleLimits = true } } @get:Synchronized @set:Synchronized var chipColor = 0 @get:Synchronized @set:Synchronized var isNotifyNewMail = false @get:Synchronized @set:Synchronized var folderNotifyNewMailMode = FolderMode.ALL @get:Synchronized @set:Synchronized var isNotifySelfNewMail = false @get:Synchronized @set:Synchronized var isNotifyContactsMailOnly = false @get:Synchronized @set:Synchronized var isIgnoreChatMessages = false @get:Synchronized @set:Synchronized var legacyInboxFolder: String? = null @get:Synchronized @set:Synchronized var importedDraftsFolder: String? = null @get:Synchronized @set:Synchronized var importedSentFolder: String? = null @get:Synchronized @set:Synchronized var importedTrashFolder: String? = null @get:Synchronized @set:Synchronized var importedArchiveFolder: String? = null @get:Synchronized @set:Synchronized var importedSpamFolder: String? = null @get:Synchronized @set:Synchronized var inboxFolderId: Long? = null @get:Synchronized @set:Synchronized var outboxFolderId: Long? = null @get:Synchronized @set:Synchronized var draftsFolderId: Long? = null @get:Synchronized @set:Synchronized var sentFolderId: Long? = null @get:Synchronized @set:Synchronized var trashFolderId: Long? = null @get:Synchronized @set:Synchronized var archiveFolderId: Long? = null @get:Synchronized @set:Synchronized var spamFolderId: Long? = null @get:Synchronized var draftsFolderSelection = SpecialFolderSelection.AUTOMATIC private set @get:Synchronized var sentFolderSelection = SpecialFolderSelection.AUTOMATIC private set @get:Synchronized var trashFolderSelection = SpecialFolderSelection.AUTOMATIC private set @get:Synchronized var archiveFolderSelection = SpecialFolderSelection.AUTOMATIC private set @get:Synchronized var spamFolderSelection = SpecialFolderSelection.AUTOMATIC private set @get:Synchronized @set:Synchronized var importedAutoExpandFolder: String? = null @get:Synchronized @set:Synchronized var autoExpandFolderId: Long? = null @get:Synchronized @set:Synchronized var folderDisplayMode = FolderMode.NOT_SECOND_CLASS @get:Synchronized @set:Synchronized var folderSyncMode = FolderMode.FIRST_CLASS @get:Synchronized @set:Synchronized var folderPushMode = FolderMode.NONE @get:Synchronized @set:Synchronized var folderTargetMode = FolderMode.NOT_SECOND_CLASS @get:Synchronized @set:Synchronized var accountNumber = 0 @get:Synchronized @set:Synchronized var isNotifySync = false @get:Synchronized @set:Synchronized var sortType: SortType = SortType.SORT_DATE private val sortAscending: MutableMap<SortType, Boolean> = mutableMapOf() @get:Synchronized @set:Synchronized var showPictures = ShowPictures.NEVER @get:Synchronized @set:Synchronized var isSignatureBeforeQuotedText = false @get:Synchronized @set:Synchronized var expungePolicy = Expunge.EXPUNGE_IMMEDIATELY @get:Synchronized @set:Synchronized var maxPushFolders = 0 @get:Synchronized @set:Synchronized var idleRefreshMinutes = 0 @get:JvmName("useCompression") @get:Synchronized @set:Synchronized var useCompression = true @get:Synchronized @set:Synchronized var searchableFolders = Searchable.ALL @get:Synchronized @set:Synchronized var isSubscribedFoldersOnly = false @get:Synchronized @set:Synchronized var maximumPolledMessageAge = 0 @get:Synchronized @set:Synchronized var maximumAutoDownloadMessageSize = 0 @get:Synchronized @set:Synchronized var messageFormat = MessageFormat.HTML @get:Synchronized @set:Synchronized var isMessageFormatAuto = false @get:Synchronized @set:Synchronized var isMessageReadReceipt = false @get:Synchronized @set:Synchronized var quoteStyle = QuoteStyle.PREFIX @get:Synchronized @set:Synchronized var quotePrefix: String? = null @get:Synchronized @set:Synchronized var isDefaultQuotedTextShown = false @get:Synchronized @set:Synchronized var isReplyAfterQuote = false @get:Synchronized @set:Synchronized var isStripSignature = false @get:Synchronized @set:Synchronized var isSyncRemoteDeletions = false @get:Synchronized @set:Synchronized var openPgpProvider: String? = null set(value) { field = value?.takeIf { it.isNotEmpty() } } @get:Synchronized @set:Synchronized var openPgpKey: Long = 0 @get:Synchronized @set:Synchronized var autocryptPreferEncryptMutual = false @get:Synchronized @set:Synchronized var isOpenPgpHideSignOnly = false @get:Synchronized @set:Synchronized var isOpenPgpEncryptSubject = false @get:Synchronized @set:Synchronized var isOpenPgpEncryptAllDrafts = false @get:Synchronized @set:Synchronized var isMarkMessageAsReadOnView = false @get:Synchronized @set:Synchronized var isMarkMessageAsReadOnDelete = false @get:Synchronized @set:Synchronized var isAlwaysShowCcBcc = false // Temporarily disabled @get:Synchronized @set:Synchronized var isRemoteSearchFullText = false get() = false @get:Synchronized @set:Synchronized var remoteSearchNumResults = 0 set(value) { field = value.coerceAtLeast(0) } @get:Synchronized @set:Synchronized var isUploadSentMessages = false @get:Synchronized @set:Synchronized var lastSyncTime: Long = 0 @get:Synchronized @set:Synchronized var lastFolderListRefreshTime: Long = 0 @get:Synchronized var isFinishedSetup = false private set @get:Synchronized @set:Synchronized var messagesNotificationChannelVersion = 0 @get:Synchronized @set:Synchronized var isChangedVisibleLimits = false private set /** * Database ID of the folder that was last selected for a copy or move operation. * * Note: For now this value isn't persisted. So it will be reset when K-9 Mail is restarted. */ @get:Synchronized var lastSelectedFolderId: Long? = null private set @get:Synchronized @set:Synchronized var identities: MutableList<Identity> = mutableListOf() set(value) { field = value.toMutableList() } @get:Synchronized var notificationSettings = NotificationSettings() private set val displayName: String get() = name ?: email @get:Synchronized @set:Synchronized override var email: String get() = identities[0].email!! set(email) { val newIdentity = identities[0].withEmail(email) identities[0] = newIdentity } @get:Synchronized @set:Synchronized var senderName: String? get() = identities[0].name set(name) { val newIdentity = identities[0].withName(name) identities[0] = newIdentity } @get:Synchronized @set:Synchronized var signatureUse: Boolean get() = identities[0].signatureUse set(signatureUse) { val newIdentity = identities[0].withSignatureUse(signatureUse) identities[0] = newIdentity } @get:Synchronized @set:Synchronized var signature: String? get() = identities[0].signature set(signature) { val newIdentity = identities[0].withSignature(signature) identities[0] = newIdentity } /** * @param automaticCheckIntervalMinutes or -1 for never. */ @Synchronized fun updateAutomaticCheckIntervalMinutes(automaticCheckIntervalMinutes: Int): Boolean { val oldInterval = this.automaticCheckIntervalMinutes this.automaticCheckIntervalMinutes = automaticCheckIntervalMinutes return oldInterval != automaticCheckIntervalMinutes } @Synchronized fun setDraftsFolderId(folderId: Long?, selection: SpecialFolderSelection) { draftsFolderId = folderId draftsFolderSelection = selection } @Synchronized fun hasDraftsFolder(): Boolean { return draftsFolderId != null } @Synchronized fun setSentFolderId(folderId: Long?, selection: SpecialFolderSelection) { sentFolderId = folderId sentFolderSelection = selection } @Synchronized fun hasSentFolder(): Boolean { return sentFolderId != null } @Synchronized fun setTrashFolderId(folderId: Long?, selection: SpecialFolderSelection) { trashFolderId = folderId trashFolderSelection = selection } @Synchronized fun hasTrashFolder(): Boolean { return trashFolderId != null } @Synchronized fun setArchiveFolderId(folderId: Long?, selection: SpecialFolderSelection) { archiveFolderId = folderId archiveFolderSelection = selection } @Synchronized fun hasArchiveFolder(): Boolean { return archiveFolderId != null } @Synchronized fun setSpamFolderId(folderId: Long?, selection: SpecialFolderSelection) { spamFolderId = folderId spamFolderSelection = selection } @Synchronized fun hasSpamFolder(): Boolean { return spamFolderId != null } @Synchronized fun updateFolderSyncMode(syncMode: FolderMode): Boolean { val oldSyncMode = folderSyncMode folderSyncMode = syncMode return (oldSyncMode == FolderMode.NONE && syncMode != FolderMode.NONE) || (oldSyncMode != FolderMode.NONE && syncMode == FolderMode.NONE) } @Synchronized fun isSortAscending(sortType: SortType): Boolean { return sortAscending.getOrPut(sortType) { sortType.isDefaultAscending } } @Synchronized fun setSortAscending(sortType: SortType, sortAscending: Boolean) { this.sortAscending[sortType] = sortAscending } @Synchronized fun replaceIdentities(identities: List<Identity>) { this.identities = identities.toMutableList() } @Synchronized fun getIdentity(index: Int): Identity { if (index !in identities.indices) error("Identity with index $index not found") return identities[index] } fun isAnIdentity(addresses: Array<Address>?): Boolean { if (addresses == null) return false return addresses.any { address -> isAnIdentity(address) } } fun isAnIdentity(address: Address): Boolean { return findIdentity(address) != null } @Synchronized fun findIdentity(address: Address): Identity? { return identities.find { identity -> identity.email.equals(address.address, ignoreCase = true) } } val earliestPollDate: Date? get() { val age = maximumPolledMessageAge.takeIf { it >= 0 } ?: return null val now = Calendar.getInstance() now[Calendar.HOUR_OF_DAY] = 0 now[Calendar.MINUTE] = 0 now[Calendar.SECOND] = 0 now[Calendar.MILLISECOND] = 0 if (age < 28) { now.add(Calendar.DATE, age * -1) } else when (age) { 28 -> now.add(Calendar.MONTH, -1) 56 -> now.add(Calendar.MONTH, -2) 84 -> now.add(Calendar.MONTH, -3) 168 -> now.add(Calendar.MONTH, -6) 365 -> now.add(Calendar.YEAR, -1) } return now.time } val isOpenPgpProviderConfigured: Boolean get() = openPgpProvider != null @Synchronized fun hasOpenPgpKey(): Boolean { return openPgpKey != NO_OPENPGP_KEY } @Synchronized fun setLastSelectedFolderId(folderId: Long) { lastSelectedFolderId = folderId } @Synchronized fun resetChangeMarkers() { isChangedVisibleLimits = false } @Synchronized fun markSetupFinished() { isFinishedSetup = true } @Synchronized fun updateNotificationSettings(block: (oldNotificationSettings: NotificationSettings) -> NotificationSettings) { notificationSettings = block(notificationSettings) } override fun toString(): String { return if (K9.isSensitiveDebugLoggingEnabled) displayName else uuid } override fun equals(other: Any?): Boolean { return if (other is Account) { other.uuid == uuid } else { super.equals(other) } } override fun hashCode(): Int { return uuid.hashCode() } enum class FolderMode { NONE, ALL, FIRST_CLASS, FIRST_AND_SECOND_CLASS, NOT_SECOND_CLASS } enum class SpecialFolderSelection { AUTOMATIC, MANUAL } enum class ShowPictures { NEVER, ALWAYS, ONLY_FROM_CONTACTS } enum class Searchable { ALL, DISPLAYABLE, NONE } enum class QuoteStyle { PREFIX, HEADER } enum class MessageFormat { TEXT, HTML, AUTO } enum class Expunge { EXPUNGE_IMMEDIATELY, EXPUNGE_MANUALLY, EXPUNGE_ON_POLL; fun toBackendExpungePolicy(): ExpungePolicy = when (this) { EXPUNGE_IMMEDIATELY -> ExpungePolicy.IMMEDIATELY EXPUNGE_MANUALLY -> ExpungePolicy.MANUALLY EXPUNGE_ON_POLL -> ExpungePolicy.ON_POLL } } enum class DeletePolicy(@JvmField val setting: Int) { NEVER(0), SEVEN_DAYS(1), ON_DELETE(2), MARK_AS_READ(3); companion object { fun fromInt(initialSetting: Int): DeletePolicy { return values().find { it.setting == initialSetting } ?: error("DeletePolicy $initialSetting unknown") } } } enum class SortType(val isDefaultAscending: Boolean) { SORT_DATE(false), SORT_ARRIVAL(false), SORT_SUBJECT(true), SORT_SENDER(true), SORT_UNREAD(true), SORT_FLAGGED(true), SORT_ATTACHMENT(true); } companion object { /** * Fixed name of outbox - not actually displayed. */ const val OUTBOX_NAME = "Outbox" @JvmField val DEFAULT_SORT_TYPE = SortType.SORT_DATE const val DEFAULT_SORT_ASCENDING = false const val NO_OPENPGP_KEY: Long = 0 const val UNASSIGNED_ACCOUNT_NUMBER = -1 const val INTERVAL_MINUTES_NEVER = -1 const val DEFAULT_SYNC_INTERVAL = 60 } }
apache-2.0
6f65037e4bf5ecfb7aa0ffd446032d55
23.671988
118
0.646509
4.814217
false
false
false
false
k9mail/k-9
cli/html-cleaner-cli/src/main/kotlin/Main.kt
2
1727
package app.k9mail.cli.html.cleaner import app.k9mail.html.cleaner.HtmlHeadProvider import app.k9mail.html.cleaner.HtmlProcessor import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.arguments.argument import com.github.ajalt.clikt.parameters.arguments.optional import com.github.ajalt.clikt.parameters.types.file import com.github.ajalt.clikt.parameters.types.inputStream import java.io.File import okio.buffer import okio.sink import okio.source @Suppress("MemberVisibilityCanBePrivate") class HtmlCleaner : CliktCommand( help = "A tool that modifies HTML to only keep allowed elements and attributes the same way that K-9 Mail does." ) { val input by argument(help = "HTML input file (needs to be UTF-8 encoded)") .inputStream() val output by argument(help = "Output file") .file(mustExist = false, canBeDir = false) .optional() override fun run() { val html = readInput() val processedHtml = cleanHtml(html) writeOutput(processedHtml) } private fun readInput(): String { return input.source().buffer().use { it.readUtf8() } } private fun cleanHtml(html: String): String { val htmlProcessor = HtmlProcessor(object : HtmlHeadProvider { override val headHtml = """<meta name="viewport" content="width=device-width"/>""" }) return htmlProcessor.processForDisplay(html) } private fun writeOutput(data: String) { output?.writeOutput(data) ?: echo(data) } private fun File.writeOutput(data: String) { sink().buffer().use { it.writeUtf8(data) } } } fun main(args: Array<String>) = HtmlCleaner().main(args)
apache-2.0
80371c6a339a74db8080463f3e36b3a1
30.4
116
0.691372
3.988453
false
false
false
false
rbi/HomebankCsvConverter
src/main/kotlin/de/voidnode/homebankCvsConverter/Commerzbank2Homebank.kt
1
1880
/* * This file is part of HomebankCvsConverter. * Copyright (C) 2015 Raik Bieniek <[email protected]> * * HomebankCvsConverter 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. * * HomebankCvsConverter 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 HomebankCvsConverter. If not, see <http://www.gnu.org/licenses/>. */ package de.voidnode.homebankCvsConverter import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.Files; import java.nio.charset.Charset; fun main(args : Array<String>) { if(args.size != 2) { printHelp() return } val input = Paths.get(args.get(0)); val output = Paths.get(args.get(1)); if(!Files.exists(input)) { printHelp() return } convert(input, output) } /** * Converts a CVS file exported from the Commerzbank page into a CVS file that can be imported into the Homebank application. */ private fun convert(input: Path, output: Path) { val utf8 = Charset.forName("UTF-8"); val inputLines = Files.readAllLines(input, utf8) val transactions = readCommerzbankCsv(inputLines) val outputLines = serializeHomeBankCsv(transactions) Files.write(output, outputLines, utf8) } private fun printHelp() { println("Usage: homebankCvsConverter <input CSV> <output CSV>") println(" <input CSV> The CVS file exported from the website of the bank.") println(" <output CSV> The destination path where the CSV file to import into HomeBank should be stored.") }
gpl-3.0
7a260c11b8ef275e1a6cc098cbb12959
31.431034
124
0.740957
3.608445
false
false
false
false
kittttttan/pe
kt/pe/src/main/kotlin/ktn/lab/Perf.kt
1
321
package ktn.lab import java.math.BigInteger object Perf { internal fun fib(n: Int): BigInteger { var a = BigInteger.ONE var b = BigInteger.ZERO var c: BigInteger for (i in 1 until n) { c = a a = a.add(b) b = c } return a } }
mit
f67287a6f2aa52f736e759201e60d3b8
15.894737
42
0.479751
3.776471
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/key/ShortcutOwner.kt
1
4911
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.key import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.command.VimStateMachine import com.maddyhome.idea.vim.helper.mode import org.jetbrains.annotations.NonNls sealed class ShortcutOwnerInfo { data class AllModes(val owner: ShortcutOwner) : ShortcutOwnerInfo() data class PerMode( val normal: ShortcutOwner, val insert: ShortcutOwner, val visual: ShortcutOwner, val select: ShortcutOwner, ) : ShortcutOwnerInfo() { fun toNotation(): String { val owners = HashMap<ShortcutOwner, MutableList<String>>() owners[normal] = (owners[normal] ?: mutableListOf()).also { it.add("n") } owners[insert] = (owners[insert] ?: mutableListOf()).also { it.add("i") } owners[visual] = (owners[visual] ?: mutableListOf()).also { it.add("x") } owners[select] = (owners[select] ?: mutableListOf()).also { it.add("s") } if ("x" in (owners[ShortcutOwner.VIM] ?: emptyList()) && "s" in (owners[ShortcutOwner.VIM] ?: emptyList())) { val existing = owners[ShortcutOwner.VIM] ?: mutableListOf() existing.remove("x") existing.remove("s") existing.add("v") owners[ShortcutOwner.VIM] = existing } if ("x" in (owners[ShortcutOwner.IDE] ?: emptyList()) && "s" in (owners[ShortcutOwner.IDE] ?: emptyList())) { val existing = owners[ShortcutOwner.IDE] ?: mutableListOf() existing.remove("x") existing.remove("s") existing.add("v") owners[ShortcutOwner.IDE] = existing } if ((owners[ShortcutOwner.IDE] ?: emptyList()).isEmpty()) { owners.remove(ShortcutOwner.VIM) owners[ShortcutOwner.VIM] = mutableListOf("a") } if ((owners[ShortcutOwner.VIM] ?: emptyList()).isEmpty()) { owners.remove(ShortcutOwner.IDE) owners[ShortcutOwner.IDE] = mutableListOf("a") } val ideOwners = (owners[ShortcutOwner.IDE] ?: emptyList()).sortedBy { wights[it] ?: 1000 }.joinToString(separator = "-") val vimOwners = (owners[ShortcutOwner.VIM] ?: emptyList()).sortedBy { wights[it] ?: 1000 }.joinToString(separator = "-") return if (ideOwners.isNotEmpty() && vimOwners.isNotEmpty()) { ideOwners + ":" + ShortcutOwner.IDE.ownerName + " " + vimOwners + ":" + ShortcutOwner.VIM.ownerName } else if (ideOwners.isNotEmpty() && vimOwners.isEmpty()) { ideOwners + ":" + ShortcutOwner.IDE.ownerName } else if (ideOwners.isEmpty() && vimOwners.isNotEmpty()) { vimOwners + ":" + ShortcutOwner.VIM.ownerName } else { error("Unexpected state") } } } fun forEditor(editor: VimEditor): ShortcutOwner { return when (this) { is AllModes -> this.owner is PerMode -> when (editor.mode) { VimStateMachine.Mode.COMMAND -> this.normal VimStateMachine.Mode.VISUAL -> this.visual VimStateMachine.Mode.SELECT -> this.visual VimStateMachine.Mode.INSERT -> this.insert VimStateMachine.Mode.CMD_LINE -> this.normal VimStateMachine.Mode.OP_PENDING -> this.normal VimStateMachine.Mode.REPLACE -> this.insert VimStateMachine.Mode.INSERT_NORMAL -> this.normal VimStateMachine.Mode.INSERT_VISUAL -> this.visual VimStateMachine.Mode.INSERT_SELECT -> this.select } } } companion object { @JvmField val allUndefined = AllModes(ShortcutOwner.UNDEFINED) val allVim = AllModes(ShortcutOwner.VIM) val allIde = AllModes(ShortcutOwner.IDE) val allPerModeVim = PerMode(ShortcutOwner.VIM, ShortcutOwner.VIM, ShortcutOwner.VIM, ShortcutOwner.VIM) val allPerModeIde = PerMode(ShortcutOwner.IDE, ShortcutOwner.IDE, ShortcutOwner.IDE, ShortcutOwner.IDE) private val wights = mapOf( "a" to 0, "n" to 1, "i" to 2, "x" to 3, "s" to 4, "v" to 5 ) } } enum class ShortcutOwner(val ownerName: @NonNls String, private val title: @NonNls String) { UNDEFINED("undefined", "Undefined"), IDE(Constants.IDE_STRING, "IDE"), VIM(Constants.VIM_STRING, "Vim"); override fun toString(): String = title private object Constants { const val IDE_STRING: @NonNls String = "ide" const val VIM_STRING: @NonNls String = "vim" } companion object { @JvmStatic fun fromString(s: String): ShortcutOwner = when (s) { Constants.IDE_STRING -> IDE Constants.VIM_STRING -> VIM else -> UNDEFINED } fun fromStringOrNull(s: String): ShortcutOwner? { return when { Constants.IDE_STRING.equals(s, ignoreCase = true) -> IDE Constants.VIM_STRING.equals(s, ignoreCase = true) -> VIM else -> null } } } }
mit
62e1e21cf9439b14ccee3dfd429d95ac
34.586957
126
0.646101
4.15834
false
false
false
false
KotlinNLP/SimpleDNN
src/test/kotlin/core/optimizer/ParamsOptimizerSpec.kt
1
2404
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package core.optimizer import com.kotlinnlp.simplednn.core.functionalities.updatemethods.learningrate.LearningRateMethod import com.kotlinnlp.simplednn.core.layers.models.feedforward.simple.FeedforwardLayerParameters import com.kotlinnlp.simplednn.core.optimizer.ParamsOptimizer import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray 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 ParamsOptimizerSpec : Spek({ describe("a ParamsOptimizer") { val learningRateMethod = LearningRateMethod(learningRate = 0.1) context("update after accumulate") { val optimizer = ParamsOptimizer(learningRateMethod) val params: FeedforwardLayerParameters = ParamsOptimizerUtils.buildParams() val gw1 = params.unit.weights.buildDenseErrors(ParamsOptimizerUtils.buildWeightsErrorsValues1()) val gb1 = params.unit.biases.buildDenseErrors(ParamsOptimizerUtils.buildBiasesErrorsValues1()) val gw2 = params.unit.weights.buildDenseErrors(ParamsOptimizerUtils.buildWeightsErrorsValues2()) val gb2 = params.unit.biases.buildDenseErrors(ParamsOptimizerUtils.buildBiasesErrorsValues2()) optimizer.accumulate(listOf(gw1, gb1, gw2, gb2)) optimizer.update() val w: DenseNDArray = params.unit.weights.values val b: DenseNDArray = params.unit.biases.values it("should match the expected updated weights") { assertTrue { w.equals( DenseNDArrayFactory.arrayOf(listOf( doubleArrayOf(0.2, 0.44, 0.17, -0.12), doubleArrayOf(0.1, -0.15, 0.18, 0.56) )), tolerance = 1.0e-06 ) } } it("should match the expected updated biases") { assertTrue { b.equals( DenseNDArrayFactory.arrayOf(doubleArrayOf(0.36, -0.37)), tolerance = 1.0e-06 ) } } } } })
mpl-2.0
329b52519d158ddc237cc6d05c1b776d
34.880597
102
0.689268
4.435424
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/data/coroutineStackFrames.kt
1
5463
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.coroutine.data import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.engine.JavaStackFrame import com.intellij.debugger.engine.JavaValue import com.intellij.debugger.impl.DebuggerContextImpl import com.intellij.debugger.jdi.StackFrameProxyImpl import com.intellij.debugger.ui.tree.render.DescriptorLabelListener import com.intellij.icons.AllIcons import com.intellij.openapi.application.ReadAction import com.intellij.xdebugger.XSourcePosition import com.intellij.xdebugger.frame.XCompositeNode import com.intellij.xdebugger.frame.XValueChildrenList import com.intellij.xdebugger.impl.frame.XDebuggerFramesList import com.sun.jdi.Location import org.jetbrains.kotlin.idea.debugger.coroutine.KotlinDebuggerCoroutinesBundle import org.jetbrains.kotlin.idea.debugger.coroutine.KotlinVariableNameFinder import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.safeCoroutineStackFrameProxy import org.jetbrains.kotlin.idea.debugger.base.util.safeLocation import org.jetbrains.kotlin.idea.debugger.stackFrame.InlineStackTraceCalculator import org.jetbrains.kotlin.idea.debugger.stackFrame.KotlinStackFrame /** * Coroutine exit frame represented by a stack frames * invokeSuspend():-1 * resumeWith() * */ class CoroutinePreflightFrame( val coroutineInfoData: CoroutineInfoData, val frame: StackFrameProxyImpl, val threadPreCoroutineFrames: List<StackFrameProxyImpl>, val mode: SuspendExitMode, firstFrameVariables: List<JavaValue> ) : CoroutineStackFrame(frame, null, firstFrameVariables) { override fun isInLibraryContent() = false override fun isSynthetic() = false } class CreationCoroutineStackFrame( frame: StackFrameProxyImpl, sourcePosition: XSourcePosition?, val first: Boolean, location: Location? = frame.safeLocation() ) : CoroutineStackFrame(frame, sourcePosition, emptyList(), false, location), XDebuggerFramesList.ItemWithSeparatorAbove { override fun getCaptionAboveOf() = KotlinDebuggerCoroutinesBundle.message("coroutine.dump.creation.trace") override fun hasSeparatorAbove() = first } open class CoroutineStackFrame( frame: StackFrameProxyImpl, private val position: XSourcePosition?, private val spilledVariables: List<JavaValue> = emptyList(), private val includeFrameVariables: Boolean = true, location: Location? = frame.safeLocation(), ) : KotlinStackFrame( safeCoroutineStackFrameProxy(location, spilledVariables, frame), if (spilledVariables.isEmpty() || includeFrameVariables) { InlineStackTraceCalculator.calculateVisibleVariables(frame) } else { listOf() } ) { init { descriptor.updateRepresentation(null, DescriptorLabelListener.DUMMY_LISTENER) } override fun equals(other: Any?): Boolean { if (this === other) return true val frame = other as? JavaStackFrame ?: return false return descriptor.frameProxy == frame.descriptor.frameProxy } override fun hashCode(): Int { return descriptor.frameProxy.hashCode() } override fun buildVariablesThreadAction(debuggerContext: DebuggerContextImpl, children: XValueChildrenList, node: XCompositeNode) { if (includeFrameVariables || spilledVariables.isEmpty()) { super.buildVariablesThreadAction(debuggerContext, children, node) val debugProcess = debuggerContext.debugProcess ?: return addOptimisedVariables(debugProcess, children) } else { // ignore original frame variables for (variable in spilledVariables) { children.add(variable) } } } private fun addOptimisedVariables(debugProcess: DebugProcessImpl, children: XValueChildrenList) { val visibleVariableNames by lazy { children.getUniqueNames() } for (variable in spilledVariables) { val name = variable.name if (name !in visibleVariableNames) { children.add(variable) visibleVariableNames.add(name) } } val declaredVariableNames = findVisibleVariableNames(debugProcess) for (name in declaredVariableNames) { if (name !in visibleVariableNames) { children.add(createOptimisedVariableMessageNode(name)) } } } private fun createOptimisedVariableMessageNode(name: String) = createMessageNode( KotlinDebuggerCoroutinesBundle.message("optimised.variable.message", "\'$name\'"), AllIcons.General.Information ) private fun XValueChildrenList.getUniqueNames(): MutableSet<String> { val names = mutableSetOf<String>() for (i in 0 until size()) { names.add(getName(i)) } return names } private fun findVisibleVariableNames(debugProcess: DebugProcessImpl): List<String> { val location = stackFrameProxy.safeLocation() ?: return emptyList() return ReadAction.nonBlocking<List<String>> { KotlinVariableNameFinder(debugProcess) .findVisibleVariableNames(location) }.executeSynchronously() } override fun getSourcePosition() = position ?: super.getSourcePosition() }
apache-2.0
2dc86ee9cf3888fb10723d1f12d14f20
36.675862
158
0.725792
5.252885
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/fir/testData/quickDoc/DeprecationWithReplaceInfo.kt
4
411
@Deprecated("lol no more mainstream", replaceWith = ReplaceWith(expression = "kek()")) fun <caret>lol() { println("lol") } //INFO: <div class='definition'><pre>@Deprecated(message = &quot;lol no more mainstream&quot;, replaceWith = kotlin/ReplaceWith(expression = &quot;kek()&quot;, )) //INFO: fun lol(): Unit</pre></div><div class='bottom'><icon src="file"/>&nbsp;DeprecationWithReplaceInfo.kt<br/></div>
apache-2.0
83528450a5f3bfbfcc0fa3b2d223b4e0
57.714286
162
0.693431
3.543103
false
false
false
false
csumissu/WeatherForecast
app/src/main/java/csumissu/weatherforecast/di/AppDagger.kt
1
1797
package csumissu.weatherforecast.di import android.app.Application import android.content.Context import csumissu.weatherforecast.App import csumissu.weatherforecast.model.ForecastDataSource import csumissu.weatherforecast.model.ForecastDataStore import csumissu.weatherforecast.model.local.ForecastLocalProvider import csumissu.weatherforecast.model.remote.ForecastApi import csumissu.weatherforecast.model.remote.ForecastRemoteProvider import csumissu.weatherforecast.util.BaseSchedulerProvider import csumissu.weatherforecast.util.SchedulerProvider import dagger.BindsInstance import dagger.Component import dagger.Module import dagger.Provides import dagger.android.support.AndroidSupportInjectionModule import javax.inject.Singleton /** * @author yxsun * @since 07/06/2017 */ @Module class AppModule { @Provides @Singleton @ForApplication fun provideAppContext(app: Application): Context = app.applicationContext @Provides @Singleton @Remote fun provideForecastRemoteProvider(): ForecastDataSource = ForecastRemoteProvider(ForecastApi.getApiService()) @Provides @Singleton @Local fun provideForecastLocalProvider(@ForApplication context: Context): ForecastDataStore = ForecastLocalProvider(context) @Provides @Singleton fun provideScheduleProvider(): BaseSchedulerProvider = SchedulerProvider() } @Singleton @Component(modules = arrayOf( AndroidSupportInjectionModule::class, AppModule::class, ViewModelModule::class, MainUiModule::class )) interface AppComponent { @Component.Builder interface Builder { @BindsInstance fun application(application: Application): Builder fun build(): AppComponent } fun inject(app: App) }
mit
966e51c9b6d2a913f19be317f2d697fd
25.057971
91
0.771842
5.178674
false
false
false
false
jkennethcarino/AnkiEditor
app/src/main/java/com/jkcarino/ankieditor/ui/editor/EditorPresenter.kt
1
4564
/* * Copyright (C) 2018 Jhon Kenneth Carino * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.jkcarino.ankieditor.ui.editor import android.app.Activity import android.content.Intent import com.jkcarino.ankieditor.ui.richeditor.RichEditorActivity import com.jkcarino.ankieditor.util.AnkiDroidHelper import com.jkcarino.ankieditor.util.PlayStoreUtils import pub.devrel.easypermissions.AppSettingsDialog class EditorPresenter( private var editorView: EditorContract.View?, private var ankiDroidHelper: AnkiDroidHelper? ) : EditorContract.Presenter { /** ID of the selected note type */ override var currentNoteTypeId: Long = 0L /** ID of the selected deck */ override var currentDeckId: Long = 0L init { editorView?.setPresenter(this) } override fun start() { } override fun stop() { editorView = null ankiDroidHelper = null } override fun setupNoteTypesAndDecks() { editorView?.let { view -> try { // Display all note types ankiDroidHelper?.noteTypes?.let { noteTypes -> val noteTypeIds = ArrayList<Long>(noteTypes.keys) val noteTypesList = ArrayList<String>(noteTypes.values) view.showNoteTypes(noteTypeIds, noteTypesList) } // Display all note decks ankiDroidHelper?.noteDecks?.let { noteDecks -> val noteDeckIds = ArrayList<Long>(noteDecks.keys) val noteDecksList = ArrayList<String>(noteDecks.values) view.showNoteDecks(noteDeckIds, noteDecksList) } } catch (e: IllegalStateException) { view.showAnkiDroidError(e.localizedMessage) } } } override fun populateNoteTypeFields() { editorView?.let { view -> ankiDroidHelper?.getNoteTypeFields(currentNoteTypeId)?.let { fields -> view.showNoteTypeFields(fields) } } } override fun result(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { PlayStoreUtils.RC_OPEN_PLAY_STORE -> { editorView?.checkAnkiDroidAvailability() } AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE -> { editorView?.checkAnkiDroidReadWritePermission() } EditorFragment.RC_FIELD_EDIT -> { if (resultCode == Activity.RESULT_OK) { data?.extras?.let { val index = it.getInt(RichEditorActivity.EXTRA_FIELD_INDEX) val text = it.getString(RichEditorActivity.EXTRA_FIELD_TEXT, "") editorView?.setRichEditorFieldText(index, text) } } } } } override fun insertClozeAround( index: Int, text: String, selectionStart: Int, selectionEnd: Int ) { editorView?.let { view -> val selectionMin = Math.min(selectionStart, selectionEnd) val selectionMax = Math.max(selectionStart, selectionEnd) val insertedCloze = (text.substring(0, selectionMin) + "{{c1::" + text.substring(selectionMin, selectionMax) + "}}" + text.substring(selectionMax)) view.setInsertedClozeText(index, insertedCloze) } } override fun addNote(fields: Array<String?>) { editorView?.let { view -> val noteId = ankiDroidHelper?.api?.addNote( currentNoteTypeId, currentDeckId, fields, null ) if (noteId != null) { view.setAddNoteSuccess() } else { view.setAddNoteFailure() } } } }
gpl-3.0
fdd5b160611bcb3efe19cda88a72726d
33.575758
88
0.587862
4.993435
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/keyboard/emoji/EmojiKeyboardPageFragment.kt
2
6612
package org.thoughtcrime.securesms.keyboard.emoji import android.os.Bundle import android.view.KeyEvent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE import com.google.android.material.appbar.AppBarLayout import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.emoji.EmojiEventListener import org.thoughtcrime.securesms.components.emoji.EmojiPageView import org.thoughtcrime.securesms.components.emoji.EmojiPageViewGridAdapter import org.thoughtcrime.securesms.components.emoji.EmojiPageViewGridAdapter.EmojiHeader import org.thoughtcrime.securesms.keyboard.KeyboardPageSelected import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.util.ThemedFragment.themedInflate import org.thoughtcrime.securesms.util.adapter.mapping.MappingModel import org.thoughtcrime.securesms.util.fragments.requireListener import java.util.Optional private val DELETE_KEY_EVENT: KeyEvent = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL) class EmojiKeyboardPageFragment : Fragment(), EmojiEventListener, EmojiPageViewGridAdapter.VariationSelectorListener, KeyboardPageSelected { private lateinit var viewModel: EmojiKeyboardPageViewModel private lateinit var emojiPageView: EmojiPageView private lateinit var searchView: View private lateinit var emojiCategoriesRecycler: RecyclerView private lateinit var backspaceView: View private lateinit var eventListener: EmojiEventListener private lateinit var callback: Callback private lateinit var categoriesAdapter: EmojiKeyboardPageCategoriesAdapter private lateinit var searchBar: KeyboardPageSearchView private lateinit var appBarLayout: AppBarLayout private val categoryUpdateOnScroll = UpdateCategorySelectionOnScroll() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return themedInflate(R.layout.keyboard_pager_emoji_page_fragment, inflater, container) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { callback = requireNotNull(requireListener()) emojiPageView = view.findViewById(R.id.emoji_page_view) emojiPageView.initialize(this, this, true) emojiPageView.addOnScrollListener(categoryUpdateOnScroll) searchView = view.findViewById(R.id.emoji_search) searchBar = view.findViewById(R.id.emoji_keyboard_search_text) emojiCategoriesRecycler = view.findViewById(R.id.emoji_categories_recycler) backspaceView = view.findViewById(R.id.emoji_backspace) appBarLayout = view.findViewById(R.id.emoji_keyboard_search_appbar) } @Suppress("DEPRECATION") override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProvider(requireActivity(), EmojiKeyboardPageViewModel.Factory(requireContext())) .get(EmojiKeyboardPageViewModel::class.java) categoriesAdapter = EmojiKeyboardPageCategoriesAdapter { key -> scrollTo(key) viewModel.onKeySelected(key) } emojiCategoriesRecycler.adapter = categoriesAdapter searchBar.callbacks = EmojiKeyboardPageSearchViewCallbacks() searchView.setOnClickListener { callback.openEmojiSearch() } backspaceView.setOnClickListener { eventListener.onKeyEvent(DELETE_KEY_EVENT) } viewModel.categories.observe(viewLifecycleOwner) { categories -> categoriesAdapter.submitList(categories) { (emojiCategoriesRecycler.parent as View).invalidate() emojiCategoriesRecycler.parent.requestLayout() } } viewModel.pages.observe(viewLifecycleOwner) { pages -> emojiPageView.setList(pages) { (emojiPageView.layoutManager as? LinearLayoutManager)?.scrollToPositionWithOffset(1, 0) } } viewModel.selectedKey.observe(viewLifecycleOwner) { updateCategoryTab(it) } eventListener = requireListener() } override fun onResume() { super.onResume() viewModel.refreshRecentEmoji() } override fun onPageSelected() { viewModel.refreshRecentEmoji() } private fun updateCategoryTab(key: String) { emojiCategoriesRecycler.post { val index: Int = categoriesAdapter.indexOfFirst(EmojiKeyboardPageCategoryMappingModel::class.java) { it.key == key } if (index != -1) { emojiCategoriesRecycler.smoothScrollToPosition(index) } } } private fun scrollTo(key: String) { emojiPageView.adapter?.let { adapter -> val index = adapter.indexOfFirst(EmojiHeader::class.java) { it.key == key } if (index != -1) { appBarLayout.setExpanded(false, true) categoryUpdateOnScroll.startAutoScrolling() emojiPageView.smoothScrollToPositionTop(index) } } } override fun onEmojiSelected(emoji: String) { SignalStore.emojiValues().setPreferredVariation(emoji) eventListener.onEmojiSelected(emoji) } override fun onKeyEvent(keyEvent: KeyEvent?) { eventListener.onKeyEvent(keyEvent) } override fun onVariationSelectorStateChanged(open: Boolean) = Unit private inner class EmojiKeyboardPageSearchViewCallbacks : KeyboardPageSearchView.Callbacks { override fun onClicked() { callback.openEmojiSearch() } } private inner class UpdateCategorySelectionOnScroll : RecyclerView.OnScrollListener() { private var doneScrolling: Boolean = true fun startAutoScrolling() { doneScrolling = false } @Override override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { if (newState == SCROLL_STATE_IDLE && !doneScrolling) { doneScrolling = true onScrolled(recyclerView, 0, 0) } } override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { if (recyclerView.layoutManager == null || !doneScrolling) { return } emojiPageView.adapter?.let { adapter -> val layoutManager = recyclerView.layoutManager as LinearLayoutManager val index = layoutManager.findFirstCompletelyVisibleItemPosition() val item: Optional<MappingModel<*>> = adapter.getModel(index) if (item.isPresent && item.get() is EmojiPageViewGridAdapter.HasKey) { viewModel.onKeySelected((item.get() as EmojiPageViewGridAdapter.HasKey).key) } } } } interface Callback { fun openEmojiSearch() } }
gpl-3.0
36829a1c80ac1ae3128c5e25e19a4041
35.530387
140
0.767544
5.051184
false
false
false
false
LoveInShenZhen/Swagger-kotlin
src/main/kotlin/api/doc/swagger/Items.kt
1
1303
package api.doc.swagger /** * Created by kk on 17/4/5. */ class Items { // Required. The internal type of the array. // The value MUST be one of "string", "number", "integer", "boolean", or "array". Files and models are not allowed. var type: String = "" // The extending format for the previously mentioned type. See Data Type Formats for further details. var format: String? = null // Required if type is "array". Describes the type of items in the array. var items: Items? = null // Determines the format of the array if type array is used. Possible values are: // csv - comma separated values foo,bar. // ssv - space separated values foo bar. // tsv - tab separated values foo\tbar. // pipes - pipe separated values foo|bar. // Default value is csv. var collectionFormat: String = "csv" var default:Any? = null var maximum: Number? = null var exclusiveMaximum: Boolean? = null var minimum: Number? = null var exclusiveMinimum: Boolean? = null var maxLength: Int? = null var minLength: Int? = null var pattern: String? = null var maxItems: Int? = null var minItems: Int? = null var uniqueItems: Boolean? = null var enum: List<Any>? = null var multipleOf: Number? = null }
apache-2.0
33c9ec53fb1ded533e6e72f2277e79e2
24.076923
119
0.648503
3.984709
false
false
false
false
evanchooly/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/misc/LocalProperties.kt
1
915
package com.beust.kobalt.misc import com.beust.kobalt.KobaltException import com.google.inject.Singleton import java.nio.file.Files import java.nio.file.Paths import java.util.* @Singleton class LocalProperties { val localProperties: Properties by lazy { val result = Properties() val filePath = Paths.get("local.properties") filePath.let { path -> if (path.toFile().exists()) { Files.newInputStream(path).use { result.load(it) } } } result } fun getNoThrows(name: String, docUrl: String? = null) = localProperties.getProperty(name) fun get(name: String, docUrl: String? = null) : String { val result = getNoThrows(name, docUrl) ?: throw KobaltException("Couldn't find $name in local.properties", docUrl = docUrl) return result as String } }
apache-2.0
ba9fa790e204e3c7a317f2bbfdae73e0
27.59375
100
0.615301
4.357143
false
false
false
false
ayatk/biblio
app/src/main/kotlin/com/ayatk/biblio/data/remote/entity/mapper/IndexMapper.kt
1
1241
/* * 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.remote.entity.mapper import com.ayatk.biblio.data.remote.entity.NarouIndex import com.ayatk.biblio.infrastructure.database.entity.IndexEntity import com.ayatk.biblio.infrastructure.database.entity.enums.ReadingState import java.util.* fun List<NarouIndex>.toEntity(): List<IndexEntity> = map { IndexEntity( id = UUID.nameUUIDFromBytes("${it.ncode}-${it.page}".toByteArray()), code = it.ncode, subtitle = it.title, page = it.page, chapter = it.chapter, readingState = ReadingState.UNREAD, publishDate = it.publishDate, lastUpdate = it.lastUpdate ) }
apache-2.0
aca6ce66b71ad8d77b6889b2a91a374c
33.472222
75
0.721193
3.990354
false
false
false
false
Flocksserver/Androidkt-CleanArchitecture-Template
data/src/main/java/de/flocksserver/data/service/TextService.kt
1
768
package de.flocksserver.data.service import java.security.SecureRandom import java.util.* import javax.inject.Inject /** * Created by marcel on 8/30/17. */ class TextService @Inject constructor(){ private val LENGTH = 21 private val UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" private val LOWER = UPPER.toLowerCase(Locale.ROOT) private val DIGITS = "0123456789" private val alphanum = UPPER + LOWER + DIGITS private var random: Random = SecureRandom() private var symbols: CharArray = alphanum.toCharArray() private var buf: CharArray = CharArray(LENGTH) fun generateText(): String{ for (idx in 0 until buf.size){ buf[idx] = symbols[random.nextInt(symbols.size)] } return String(buf) } }
apache-2.0
d43d62be61f5895ff43c0d9d311a52e9
22.30303
60
0.682292
4.243094
false
false
false
false
binhonglee/LibrarySystem
src/test/kotlin/libsys/BookTest.kt
1
2894
package libsys import org.junit.* /** * Test Book related operations */ class BookTest { private var book1: Book? = null private var book2: Book? = null /** * Set up before testing */ @Before fun prepareTest() { book1 = Book("Book1", 10, "AVAILABLE") book2 = Book("Book2", 12, "NOT AVAILABLE") } init { } /** * Test Book related operations */ @Test fun bookTest() { Assert.assertEquals("Title is \"Book1\"", book1!!.title, "Book1") Assert.assertEquals("Status is \"AVAILABLE\"", book1!!.status, "AVAILABLE") Assert.assertEquals("Book id is 10", book1!!.id, 10) Assert.assertEquals("Title is \"Book2\"", book2!!.title, "Book2") Assert.assertEquals("Status is \"NOT AVAILABLE\"", book2!!.status, "NOT AVAILABLE") Assert.assertEquals("Book id is 12", book2!!.id, 12) val date = intArrayOf(2018, 10, 5) Assert.assertTrue("Rent should be successful", book1!!.rent(date)) Assert.assertEquals("Book status is \"RENTED\"", book1!!.status, "RENTED") Assert.assertEquals("Book due date is 2018/10/5", book1!!.dueDate, date) Assert.assertFalse("Book2 is not rent-able", book2!!.rent(date)) book1!!.returned() Assert.assertTrue("Book1 is \"AVAILABLE\"", book1!!.status == "AVAILABLE") val newBook1Title = "New Book 1" book1!!.title = newBook1Title Assert.assertEquals("Title is \"New Book 1\"", book1!!.title, newBook1Title) val newBook2Title = "New Book 2" book2!!.title = newBook2Title Assert.assertEquals("Title is \"New Book 2\"", book2!!.title, newBook2Title) val testBook1 = Book(10) val testBook2 = Book("Test Title", 20, "RESERVED") val testBook3 = Book(15, "Test Title 2", "RENTED", intArrayOf(2019, 3, 23)) Assert.assertEquals("Book name is \"UNDEFINED\"", testBook1.title, "UNDEFINED") Assert.assertEquals("Book1 id is 10", testBook1.id, 10) Assert.assertEquals("Book1 status is \"NOT AVAILABLE\"", testBook1.status, "NOT AVAILABLE") Assert.assertEquals("Book2 title is \"Test Title\"", testBook2.title, "Test Title") Assert.assertEquals("Book2 id is 20", testBook2.id, 20) Assert.assertEquals("Book2 status is \"RESERVED\"", testBook2.status, "RESERVED") Assert.assertEquals("Book3 title is \"Test Title 2\"", testBook3.title, "Test Title 2") Assert.assertEquals("Book3 id is 15", testBook3.id, 15) Assert.assertEquals("Book3 status is \"RENTED\"", testBook3.status, "RENTED") val dueDate = testBook3.dueDate Assert.assertEquals("Book3 due date year is 2019", dueDate[0], 2019) Assert.assertEquals("Book3 due date month is 3", dueDate[1], 3) Assert.assertEquals("Book3 due date day is 23", dueDate[2], 23) } }
mit
1393007da13b786a27a9a83b31a7dcad
37.078947
99
0.623704
3.942779
false
true
false
false
meik99/CoffeeList
app/src/main/java/rynkbit/tk/coffeelist/ui/item/ItemFragment.kt
1
4028
package rynkbit.tk.coffeelist.ui.item import androidx.lifecycle.ViewModelProviders import android.os.Bundle import android.renderscript.RSInvalidStateException import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.navigation.Navigation import androidx.recyclerview.widget.StaggeredGridLayoutManager import io.reactivex.Single import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.item_fragment.* import rynkbit.tk.coffeelist.R import rynkbit.tk.coffeelist.contract.entity.Customer import rynkbit.tk.coffeelist.contract.entity.InvoiceState import rynkbit.tk.coffeelist.contract.entity.Item import rynkbit.tk.coffeelist.db.facade.InvoiceFacade import rynkbit.tk.coffeelist.db.facade.ItemFacade import rynkbit.tk.coffeelist.ui.MainActivity import rynkbit.tk.coffeelist.ui.MainViewModel import rynkbit.tk.coffeelist.ui.ResponsiveStaggeredGridLayoutManager import rynkbit.tk.coffeelist.ui.entity.UIInvoice import rynkbit.tk.coffeelist.ui.entity.UIItem import java.lang.IllegalStateException import java.util.* class ItemFragment : Fragment() { private lateinit var viewModel: ItemViewModel private lateinit var itemAdapter: ItemAdapter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.item_fragment, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val activityViewModel = ViewModelProvider(activity!!)[MainViewModel::class.java] viewModel = ViewModelProvider(this).get(ItemViewModel::class.java) itemAdapter = ItemAdapter() itemAdapter.onClickListener = { item -> if (item.stock > 0) { showConfirmationDialog(item, activityViewModel.customer) } else { showItemNotInStockMessage(item) } } listItem.layoutManager = ResponsiveStaggeredGridLayoutManager( context!!, StaggeredGridLayoutManager.VERTICAL ) listItem.adapter = itemAdapter } private fun showItemNotInStockMessage(item: Item){ Toast .makeText(context!!, getString(R.string.item_outOfStock, item.name), Toast.LENGTH_SHORT) .show() } private fun showConfirmationDialog(item: Item, customer: Customer?){ BuyItemDialog(item) { it.dismiss() buyItemForCustomer(item, customer) .observe(this, Observer { activity?.runOnUiThread { decreaseItemStock(item).observe(this, Observer { Navigation .findNavController(activity!!, R.id.nav_host) .popBackStack() }) } }) }.show(fragmentManager!!, ItemFragment::class.java.simpleName) } private fun buyItemForCustomer(item: Item, customer: Customer?): LiveData<Long> { return InvoiceFacade() .createInvoiceForCustomerAndItem(item, customer ?: throw IllegalStateException("Customer must not be null")) } private fun decreaseItemStock(item: Item): LiveData<Int> { return ItemFacade() .decreaseItemStock(item) } override fun onResume() { super.onResume() ItemFacade().findAll() .observe(this, Observer { itemAdapter.updateItems(it) }) } }
mit
e33f9022cf40e4ab36c82e7156925657
35.618182
88
0.656902
5.293035
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/packet/PacketOutNamedSoundLegacyAdapter.kt
1
1417
/* * Copyright (C) 2016-Present The MoonLake ([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 com.mcmoonlake.api.packet import com.mcmoonlake.api.isCombatOrLaterVer class PacketOutNamedSoundLegacyAdapter : PacketLegacyAdapterCustom<PacketOutNamedSound, PacketOutNamedSoundLegacy>() { override val packet: Class<PacketOutNamedSound> get() = PacketOutNamedSound::class.java override val packetName: String get() = "PacketPlayOutCustomSoundEffect" // 1.9+ override val packetLegacy: Class<PacketOutNamedSoundLegacy> get() = PacketOutNamedSoundLegacy::class.java override val packetLegacyName: String get() = "PacketPlayOutNamedSoundEffect" // 1.8.x override val isLegacy: Boolean get() = !isCombatOrLaterVer }
gpl-3.0
5247c099dfe808269dc2d0811a9bddad
35.333333
83
0.742414
4.442006
false
false
false
false
tinmegali/android_achitecture_components_sample
app/src/main/java/com/tinmegali/myweather/web/LiveDataCallAdapterFactory.kt
1
1222
package com.tinmegali.myweather.web import android.arch.lifecycle.LiveData import com.tinmegali.myweather.R import com.tinmegali.myweather.models.ApiResponse import java.lang.reflect.ParameterizedType import java.lang.reflect.Type import retrofit2.CallAdapter import retrofit2.Retrofit class LiveDataCallAdapterFactory : CallAdapter.Factory() { override fun get(returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit): CallAdapter<Any, Any>? { if (CallAdapter.Factory.getRawType(returnType) != LiveData::class.java) { return null } val observableType = CallAdapter.Factory.getParameterUpperBound(0, returnType as ParameterizedType) val rawObservableType = CallAdapter.Factory.getRawType(observableType) if (rawObservableType != ApiResponse::class.java) { throw IllegalArgumentException("type must be a resource") } if (observableType !is ParameterizedType) { throw IllegalArgumentException("resource must be parameterized") } val bodyType = CallAdapter.Factory.getParameterUpperBound(0, observableType) return LiveDataCallAdapter<Any>(bodyType) as CallAdapter<Any, Any> } }
apache-2.0
f0ab3df5245cbe7589a5a58e933bfc4e
38.419355
116
0.736498
4.927419
false
false
false
false
CesarValiente/KUnidirectional
app/src/main/kotlin/com/cesarvaliente/kunidirectional/itemslist/recyclerview/ItemsAdapter.kt
1
3842
/** * Copyright (C) 2017 Cesar Valiente & Corey Shaw * * https://github.com/CesarValiente * https://github.com/coshaw * * 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.cesarvaliente.kunidirectional.itemslist.recyclerview import android.support.v7.util.DiffUtil import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.cesarvaliente.kunidirectional.R import com.cesarvaliente.kunidirectional.getStableId import com.cesarvaliente.kunidirectional.store.Item import java.util.Collections internal interface ItemTouchHelperAdapter { fun onItemMove(fromPosition: Int, toPosition: Int) fun onItemDeleted(position: Int) } class ItemsAdapter( private var items: List<Item>, private val itemClick: (Item) -> Unit, private val setFavorite: (Item) -> Unit, private val updateItemsPositions: (List<Item>) -> Unit, private val deleteItem: (Item) -> Unit) : RecyclerView.Adapter<ItemViewHolder>(), ItemTouchHelperAdapter { init { setHasStableIds(true) } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ItemViewHolder { val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_layout, parent, false) return ItemViewHolder(view, itemClick, setFavorite, this::updateItemsPositions) } override fun onBindViewHolder(itemViewHolder: ItemViewHolder, position: Int) { itemViewHolder.bindItem(items[position]) } override fun getItemCount(): Int = items.size fun getItem(position: Int): Item = items[position] override fun getItemId(position: Int): Long = getItem(position).getStableId() fun removeAt(position: Int) { items = items.minus(items[position]) notifyItemRemoved(position) } fun updateItems(newItems: List<Item>) { val oldItems = items items = newItems applyDiff(oldItems, items) } private fun applyDiff(oldItems: List<Item>, newItems: List<Item>) { val diffResult = DiffUtil.calculateDiff(ItemsDiffCallback(oldItems, newItems)) diffResult.dispatchUpdatesTo(this) } private fun updateItemsPositions() { updateItemsPositions(items) } override fun onItemDeleted(position: Int) { deleteItem(items[position]) removeAt(position) } override fun onItemMove(fromPosition: Int, toPosition: Int) { swapItems(fromPosition, toPosition) notifyItemMoved(fromPosition, toPosition) } fun swapItems(fromPosition: Int, toPosition: Int) = if (fromPosition < toPosition) { (fromPosition .. toPosition - 1).forEach { i -> swapPositions(i, i + 1) Collections.swap(items, i, i + 1) } } else { (fromPosition downTo toPosition + 1).forEach { i -> swapPositions(i, i - 1) Collections.swap(items, i, i - 1) } } fun swapPositions(position1: Int, position2: Int) { val item1 = items[position1] val item2 = items[position2] items = items.map { if (it.localId == item1.localId) it.copy(position = item2.position) else if (it.localId == item2.localId) it.copy(position = item1.position) else it } } }
apache-2.0
bb3cad68c9c56cc6682fabd1beb5f196
32.417391
100
0.680375
4.421174
false
false
false
false
jmfayard/skripts
test/kotlin/variances.kt
1
831
package variances data class Producer<out T : Beverage>( val beverage: T ) { fun produce(): T = beverage } class Consumer<in T : Beverage> { fun consume(t: T) = println("Thanks for the drink $t!") } interface Beverage object Coffee : Beverage object Whisky : Beverage fun main(args: Array<String>) { val colombia: Producer<Coffee> = Producer(Coffee) val scottland: Producer<Whisky> = Producer(Whisky) // val noCoffeeThere : Coffee = scottland.produce() // error val beverages: List<Beverage> = listOf(colombia, scottland).map { it.produce() } val starbucks = Consumer<Coffee>() starbucks.consume(colombia.produce()) // starbucks.consume(scottland.produce()) // error val pub = Consumer<Whisky>() pub.consume(scottland.produce()) // pub.consume(colombia.produce()) // error }
apache-2.0
59946734e916e81fefdbe73e37a51950
25.806452
84
0.68231
3.391837
false
false
false
false
paplorinc/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/actions/AbstractCommonCheckinAction.kt
2
4708
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.actions import com.intellij.configurationStore.StoreUtil import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.actionSystem.UpdateInBackground import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vcs.changes.ui.CommitChangeListDialog import com.intellij.util.containers.ContainerUtil.concat import com.intellij.util.ui.UIUtil.removeMnemonic private val LOG = logger<AbstractCommonCheckinAction>() private fun getChangesIn(project: Project, roots: Array<FilePath>): Set<Change> { val manager = ChangeListManager.getInstance(project) return roots.flatMap { manager.getChangesIn(it) }.toSet() } abstract class AbstractCommonCheckinAction : AbstractVcsAction(), UpdateInBackground { override fun update(vcsContext: VcsContext, presentation: Presentation) { val project = vcsContext.project if (project == null || !ProjectLevelVcsManager.getInstance(project).hasActiveVcss()) { presentation.isEnabledAndVisible = false } else if (!approximatelyHasRoots(vcsContext)) { presentation.isEnabled = false } else { getActionName(vcsContext)?.let { presentation.text = "$it..." } presentation.isEnabled = !ProjectLevelVcsManager.getInstance(project).isBackgroundVcsOperationRunning presentation.isVisible = true } } protected abstract fun approximatelyHasRoots(dataContext: VcsContext): Boolean protected open fun getActionName(dataContext: VcsContext): String? = null public override fun actionPerformed(context: VcsContext) { LOG.debug("actionPerformed. ") val project = context.project!! val actionName = getActionName(context)?.let { removeMnemonic(it) } ?: templatePresentation.text val isFreezedDialogTitle = actionName?.let { "Can not $it now" } if (ChangeListManager.getInstance(project).isFreezedWithNotification(isFreezedDialogTitle)) { LOG.debug("ChangeListManager is freezed. returning.") } else if (ProjectLevelVcsManager.getInstance(project).isBackgroundVcsOperationRunning) { LOG.debug("Background operation is running. returning.") } else { val roots = prepareRootsForCommit(getRoots(context), project) ChangeListManager.getInstance(project).invokeAfterUpdate( { performCheckIn(context, project, roots) }, InvokeAfterUpdateMode.SYNCHRONOUS_CANCELLABLE, message("waiting.changelists.update.for.show.commit.dialog.message"), ModalityState.current()) } } @Deprecated("getActionName() will be used instead") protected open fun getMnemonicsFreeActionName(context: VcsContext): String? = null protected abstract fun getRoots(dataContext: VcsContext): Array<FilePath> protected open fun prepareRootsForCommit(roots: Array<FilePath>, project: Project): Array<FilePath> { StoreUtil.saveDocumentsAndProjectSettings(project) return DescindingFilesFilter.filterDescindingFiles(roots, project) } protected open fun performCheckIn(context: VcsContext, project: Project, roots: Array<FilePath>) { LOG.debug("invoking commit dialog after update") val selectedChanges = context.selectedChanges val selectedUnversioned = context.selectedUnversionedFiles val changesToCommit: Collection<Change> val included: Collection<*> if (selectedChanges.isNullOrEmpty() && selectedUnversioned.isEmpty()) { changesToCommit = getChangesIn(project, roots) included = changesToCommit } else { changesToCommit = selectedChanges.orEmpty().toList() included = concat(changesToCommit, selectedUnversioned) } val initialChangeList = getInitiallySelectedChangeList(context, project) CommitChangeListDialog.commitChanges(project, changesToCommit, included, initialChangeList, getExecutor(project), null) } protected open fun getInitiallySelectedChangeList(context: VcsContext, project: Project): LocalChangeList? { val manager = ChangeListManager.getInstance(project) context.selectedChangeLists?.firstOrNull()?.let { return manager.findChangeList(it.name) } context.selectedChanges?.firstOrNull()?.let { return manager.getChangeList(it) } return manager.defaultChangeList } protected open fun getExecutor(project: Project): CommitExecutor? = null }
apache-2.0
8926800637b3201a192fc1ebad68db3c
42.592593
140
0.773789
4.888889
false
false
false
false
vladmm/intellij-community
platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/Variables.kt
1
9599
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.openapi.util.text.StringUtil import com.intellij.util.SmartList import com.intellij.xdebugger.frame.XCompositeNode import com.intellij.xdebugger.frame.XValueChildrenList import org.jetbrains.concurrency.Obsolescent import org.jetbrains.concurrency.ObsolescentFunction import org.jetbrains.concurrency.Promise import org.jetbrains.debugger.values.ValueType import java.util.* import java.util.regex.Pattern private val UNNAMED_FUNCTION_PATTERN = Pattern.compile("^function[\\t ]*\\(") private val NATURAL_NAME_COMPARATOR = object : Comparator<Variable> { override fun compare(o1: Variable, o2: Variable) = naturalCompare(o1.name, o2.name) } // start properties loading to achieve, possibly, parallel execution (properties loading & member filter computation) fun processVariables(context: VariableContext, variables: Promise<List<Variable>>, obsolescent: Obsolescent, consumer: (memberFilter: MemberFilter, variables: List<Variable>) -> Unit) = context.memberFilter .then(object : ValueNodeAsyncFunction<MemberFilter, Any?>(obsolescent) { override fun `fun`(memberFilter: MemberFilter): Promise<Any?> { return variables.then(object : ObsolescentFunction<List<Variable>, Any?> { override fun isObsolete() = obsolescent.isObsolete override fun `fun`(variables: List<Variable>): Void? { consumer(memberFilter, variables) return null } }) } }) fun processScopeVariables(scope: Scope, node: XCompositeNode, context: VariableContext, isLast: Boolean) = processVariables(context, scope.variablesHost.get(), node, { memberFilter, variables -> val additionalVariables = memberFilter.additionalVariables val properties = ArrayList<Variable>(variables.size + additionalVariables.size) val functions = SmartList<Variable>() for (variable in variables) { if (memberFilter.isMemberVisible(variable)) { val value = variable.value if (value != null && value.type == ValueType.FUNCTION && value.valueString != null && !UNNAMED_FUNCTION_PATTERN.matcher(value.valueString).lookingAt()) { functions.add(variable) } else { properties.add(variable) } } } val comparator = if (memberFilter.hasNameMappings()) comparator { o1, o2 -> naturalCompare(memberFilter.rawNameToSource(o1), memberFilter.rawNameToSource(o2)) } else NATURAL_NAME_COMPARATOR Collections.sort(properties, comparator) Collections.sort(functions, comparator) addAditionalVariables(variables, additionalVariables, properties, memberFilter) if (!properties.isEmpty()) { node.addChildren(createVariablesList(properties, context, memberFilter), functions.isEmpty() && isLast) } if (!functions.isEmpty()) { node.addChildren(XValueChildrenList.bottomGroup(VariablesGroup("Functions", functions, context)), isLast) } else if (isLast && properties.isEmpty()) { node.addChildren(XValueChildrenList.EMPTY, true) } }) fun processNamedObjectProperties(variables: List<Variable>, node: XCompositeNode, context: VariableContext, memberFilter: MemberFilter, maxChildrenToAdd: Int, defaultIsLast: Boolean): List<Variable>? { val list = filterAndSort(variables, memberFilter) if (list.isEmpty()) { if (defaultIsLast) { node.addChildren(XValueChildrenList.EMPTY, true) } return null } val to = Math.min(maxChildrenToAdd, list.size) val isLast = to == list.size node.addChildren(createVariablesList(list, 0, to, context, memberFilter), defaultIsLast && isLast) if (isLast) { return null } else { node.tooManyChildren(list.size - to) return list } } fun filterAndSort(variables: List<Variable>, memberFilter: MemberFilter): List<Variable> { if (variables.isEmpty()) { return emptyList() } val additionalVariables = memberFilter.additionalVariables val result = ArrayList<Variable>(variables.size + additionalVariables.size) for (variable in variables) { if (memberFilter.isMemberVisible(variable)) { result.add(variable) } } Collections.sort(result, NATURAL_NAME_COMPARATOR) addAditionalVariables(variables, additionalVariables, result, memberFilter) return result } private fun addAditionalVariables(variables: List<Variable>, additionalVariables: Collection<Variable>, result: MutableList<Variable>, memberFilter: MemberFilter) { ol@ for (variable in additionalVariables) { for (frameVariable in variables) { if (memberFilter.rawNameToSource(frameVariable) == memberFilter.rawNameToSource(variable)) { continue@ol } } result.add(variable) } } // prefixed '_' must be last, fixed case sensitive natural compare private fun naturalCompare(string1: String?, string2: String?): Int { //noinspection StringEquality if (string1 === string2) { return 0 } if (string1 == null) { return -1 } if (string2 == null) { return 1 } val string1Length = string1.length val string2Length = string2.length var i = 0 var j = 0 while (i < string1Length && j < string2Length) { var ch1 = string1[i] var ch2 = string2[j] if ((StringUtil.isDecimalDigit(ch1) || ch1 == ' ') && (StringUtil.isDecimalDigit(ch2) || ch2 == ' ')) { var startNum1 = i while (ch1 == ' ' || ch1 == '0') { // skip leading spaces and zeros startNum1++ if (startNum1 >= string1Length) { break } ch1 = string1[startNum1] } var startNum2 = j while (ch2 == ' ' || ch2 == '0') { // skip leading spaces and zeros startNum2++ if (startNum2 >= string2Length) { break } ch2 = string2[startNum2] } i = startNum1 j = startNum2 // find end index of number while (i < string1Length && StringUtil.isDecimalDigit(string1[i])) { i++ } while (j < string2Length && StringUtil.isDecimalDigit(string2[j])) { j++ } val lengthDiff = (i - startNum1) - (j - startNum2) if (lengthDiff != 0) { // numbers with more digits are always greater than shorter numbers return lengthDiff } while (startNum1 < i) { // compare numbers with equal digit count val diff = string1[startNum1] - string2[startNum2] if (diff != 0) { return diff } startNum1++ startNum2++ } i-- j-- } else if (ch1 != ch2) { if (ch1 == '_') { return 1 } else if (ch2 == '_') { return -1 } else { return ch1 - ch2 } } i++ j++ } // After the loop the end of one of the strings might not have been reached, if the other // string ends with a number and the strings are equal until the end of that number. When // there are more characters in the string, then it is greater. if (i < string1Length) { return 1 } else if (j < string2Length) { return -1 } return string1Length - string2Length } @JvmOverloads fun createVariablesList(variables: List<Variable>, variableContext: VariableContext, memberFilter: MemberFilter? = null): XValueChildrenList { return createVariablesList(variables, 0, variables.size, variableContext, memberFilter) } fun createVariablesList(variables: List<Variable>, from: Int, to: Int, variableContext: VariableContext, memberFilter: MemberFilter?): XValueChildrenList { val list = XValueChildrenList(to - from) var getterOrSetterContext: VariableContext? = null for (i in from..to - 1) { val variable = variables[i] val normalizedName = if (memberFilter == null) variable.name else memberFilter.rawNameToSource(variable) list.add(VariableView(normalizedName, variable, variableContext)) if (variable is ObjectProperty) { if (variable.getter != null) { if (getterOrSetterContext == null) { getterOrSetterContext = NonWatchableVariableContext(variableContext) } list.add(VariableView(VariableImpl("get $normalizedName", variable.getter!!), getterOrSetterContext)) } if (variable.setter != null) { if (getterOrSetterContext == null) { getterOrSetterContext = NonWatchableVariableContext(variableContext) } list.add(VariableView(VariableImpl("set $normalizedName", variable.setter!!), getterOrSetterContext)) } } } return list } private class NonWatchableVariableContext(variableContext: VariableContext) : VariableContextWrapper(variableContext, null) { override fun watchableAsEvaluationExpression() = false }
apache-2.0
b280bf0ffad0caa89bc52fcf9164fd85
34.555556
191
0.66184
4.517176
false
false
false
false
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/yesod/hamlet/highlight/HamletColors.kt
1
823
package org.jetbrains.yesod.hamlet.highlight /** * @author Leyla H */ import com.intellij.openapi.editor.colors.TextAttributesKey interface HamletColors { companion object { val OPERATOR: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HAMLET_OPERATOR") val COMMENT: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HAMLET_COMMENT") val ATTRIBUTE: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HAMLET_ATTRIBUTE") val ATTRIBUTE_VALUE: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HAMLET_ATTRIBUTE_VALUE") val STRING: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HAMLET_STRING") val IDENTIFIER: TextAttributesKey = TextAttributesKey.createTextAttributesKey("HAMLET_IDENTIFIER") } }
apache-2.0
f6daea271398354f25e0d99b481d2fcc
44.722222
116
0.782503
5.755245
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/y2019/Day02.kt
1
639
package com.nibado.projects.advent.y2019 import com.nibado.projects.advent.Day import com.nibado.projects.advent.resourceString object Day02 : Day { private val program = resourceString(2019, 2).split(",").map { it.toLong() } override fun part1() = run(12,2) override fun part2() = (0..99).flatMap { noun -> (0..99).map { verb -> noun to verb } } .first { (noun, verb) -> run(noun, verb) == 19690720 }.let { (noun, verb) -> 100 * noun + verb } private fun run(noun: Int, verb: Int) : Int = IntCode(program).also { it.memory.set(1, noun.toLong());it.memory.set(2, verb);it.run() }.memory.get(0).toInt() }
mit
20d5d7d41237c47e100c364ff89b44b3
41.666667
119
0.638498
3.147783
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/actions/ScratchRunLineMarkerContributor.kt
1
4119
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.scratch.actions import com.intellij.execution.lineMarker.RunLineMarkerContributor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.base.psi.getLineCount import org.jetbrains.kotlin.idea.base.psi.getLineNumber import org.jetbrains.kotlin.idea.scratch.ScratchExpression import org.jetbrains.kotlin.idea.scratch.getScratchFile import org.jetbrains.kotlin.idea.scratch.isKotlinScratch import org.jetbrains.kotlin.idea.scratch.isKotlinWorksheet import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.utils.addToStdlib.safeAs class ScratchRunLineMarkerContributor : RunLineMarkerContributor() { override fun getInfo(element: PsiElement): Info? { element.containingFile.safeAs<KtFile>()?.takeIf { val file = it.virtualFile file.isKotlinWorksheet || file.isKotlinScratch || it.isScript() } ?: return null val declaration = element.getStrictParentOfType<KtNamedDeclaration>() if (declaration != null && declaration !is KtParameter && declaration.nameIdentifier == element) { return isLastExecutedExpression(element) } element.getParentOfType<KtScriptInitializer>(true)?.body?.let { scriptInitializer -> return if (scriptInitializer.findDescendantOfType<LeafPsiElement>() == element) { isLastExecutedExpression(element) } else null } // Show arrow for last added empty line if (declaration is KtScript && element is PsiWhiteSpace) { getLastExecutedExpression(element)?.let { _ -> if (element.getLineNumber() == element.containingFile.getLineCount() || element.getLineNumber(false) == element.containingFile.getLineCount() ) return Info(RunScratchFromHereAction()) } } return null } private fun isLastExecutedExpression(element: PsiElement): Info? { val expression = getLastExecutedExpression(element) ?: return null if (element.getLineNumber(true) != expression.lineStart) { return null } return if (PsiTreeUtil.isAncestor(expression.element, element, false)) { Info(RunScratchFromHereAction()) } else null } private fun getLastExecutedExpression(element: PsiElement): ScratchExpression? { val scratchFile = getSingleOpenedTextEditor(element.containingFile)?.getScratchFile() ?: return null if (!scratchFile.options.isRepl) return null val replExecutor = scratchFile.replScratchExecutor ?: return null return replExecutor.getFirstNewExpression() } /** * This method returns single editor in which passed [psiFile] opened. * If there is no such editor or there is more than one editor, it returns `null`. * * We use [PsiDocumentManager.getCachedDocument] instead of [PsiDocumentManager.getDocument] * so this would not require read action. */ private fun getSingleOpenedTextEditor(psiFile: PsiFile): TextEditor? { val document = PsiDocumentManager.getInstance(psiFile.project).getCachedDocument(psiFile) ?: return null val singleOpenedEditor = EditorFactory.getInstance().getEditors(document, psiFile.project).singleOrNull() ?: return null return TextEditorProvider.getInstance().getTextEditor(singleOpenedEditor) } }
apache-2.0
5493f5788f1b53c52a2582e65b4beb67
46.895349
158
0.733188
5.047794
false
false
false
false
google/j2cl
transpiler/java/com/google/j2cl/transpiler/backend/kotlin/Environment.kt
1
1471
/* * Copyright 2021 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.j2cl.transpiler.backend.kotlin import com.google.j2cl.transpiler.ast.HasName /** Code generation environment. */ data class Environment( /** Name to identifier mapping. */ private val nameToIdentifierMap: Map<HasName, String> = emptyMap(), /** A set of used identifiers, which potentially shadow imports. */ private val identifierSet: Set<String> = emptySet(), /** Mutable map from simple name to qualified name of types to be imported. */ val importedSimpleNameToQualifiedNameMap: MutableMap<String, String> = mutableMapOf() ) { /** Returns identifier for the given name */ fun identifier(hasName: HasName): String = nameToIdentifierMap[hasName] ?: error("No such identifier: $hasName") /** Returns whether the given identifier is used. */ fun containsIdentifier(identifier: String): Boolean = identifierSet.contains(identifier) }
apache-2.0
3d11203847db38fb17fc1be4ca2f8206
38.756757
90
0.743712
4.28863
false
false
false
false
google/iosched
shared/src/main/java/com/google/samples/apps/iosched/shared/fcm/FcmTokenUpdater.kt
3
3032
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.shared.fcm import com.google.firebase.firestore.FieldValue import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.SetOptions import com.google.firebase.iid.FirebaseInstanceId import com.google.samples.apps.iosched.shared.data.document2020 import com.google.samples.apps.iosched.shared.di.ApplicationScope import com.google.samples.apps.iosched.shared.di.MainDispatcher import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import javax.inject.Inject import timber.log.Timber /** * Saves the FCM ID tokens in Firestore. */ class FcmTokenUpdater @Inject constructor( @ApplicationScope private val externalScope: CoroutineScope, @MainDispatcher private val mainDispatcher: CoroutineDispatcher, val firestore: FirebaseFirestore ) { fun updateTokenForUser(userId: String) { FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener { instanceIdResult -> val token = instanceIdResult.token // Write token to /users/<userId>/fcmTokens/<token[0..TOKEN_ID_LENGTH]/ val tokenInfo = mapOf( LAST_VISIT_KEY to FieldValue.serverTimestamp(), TOKEN_ID_KEY to token ) // All Firestore operations start from the main thread to avoid concurrency issues. externalScope.launch(mainDispatcher) { firestore .document2020() .collection(USERS_COLLECTION) .document(userId) .collection(FCM_IDS_COLLECTION) .document(token.take(TOKEN_ID_LENGTH)) .set(tokenInfo, SetOptions.merge()).addOnCompleteListener { if (it.isSuccessful) { Timber.d("FCM ID token successfully uploaded for user $userId\"") } else { Timber.e("FCM ID token: Error uploading for user $userId") } } } } } companion object { private const val USERS_COLLECTION = "users" private const val LAST_VISIT_KEY = "lastVisit" private const val TOKEN_ID_KEY = "tokenId" private const val FCM_IDS_COLLECTION = "fcmTokens" private const val TOKEN_ID_LENGTH = 25 } }
apache-2.0
f47612e4bec4ea19860471ff87d2c68b
38.376623
95
0.663588
4.82035
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsProcessor.kt
1
9439
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.cutPaste import com.intellij.openapi.application.runReadAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiManager import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.suggested.range import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.codeInsight.shorten.runRefactoringAndKeepDelayedRequests import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress import org.jetbrains.kotlin.idea.refactoring.cutPaste.MoveDeclarationsTransferableData.Companion.STUB_RENDERER import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.* import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.getSourceRoot import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset class MoveDeclarationsProcessor( val project: Project, private val sourceContainer: KtDeclarationContainer, private val targetPsiFile: KtFile, val pastedDeclarations: List<KtNamedDeclaration>, private val imports: List<String>, private val sourceDeclarationsText: List<String> ) { companion object { fun build(editor: Editor, cookie: MoveDeclarationsEditorCookie): MoveDeclarationsProcessor? { val data = cookie.data val project = editor.project ?: return null val range = cookie.bounds.range ?: return null val sourceFileUrl = data.sourceFileUrl val sourceFile = VirtualFileManager.getInstance().findFileByUrl(sourceFileUrl) ?: return null if (sourceFile.getSourceRoot(project) == null) return null val psiDocumentManager = PsiDocumentManager.getInstance(project) psiDocumentManager.commitAllDocuments() val targetPsiFile = psiDocumentManager.getPsiFile(editor.document) as? KtFile ?: return null if (targetPsiFile.virtualFile.getSourceRoot(project) == null) return null val sourcePsiFile = PsiManager.getInstance(project).findFile(sourceFile) as? KtFile ?: return null val sourceObject = data.sourceObjectFqName?.let { fqName -> sourcePsiFile.findDescendantOfType<KtObjectDeclaration> { it.fqName?.asString() == fqName } ?: return null } val sourceContainer: KtDeclarationContainer = sourceObject ?: sourcePsiFile if (targetPsiFile == sourceContainer) return null val declarations = MoveDeclarationsCopyPasteProcessor.rangeToDeclarations(targetPsiFile, range) if (declarations.isEmpty() || declarations.any { it.parent !is KtFile }) return null if (sourceContainer == sourcePsiFile && sourcePsiFile.packageFqName == targetPsiFile.packageFqName) return null // check that declarations were cut (not copied) if (sourceContainer.declarations.any { declaration -> declaration.text in data.declarationTexts }) { return null } return MoveDeclarationsProcessor( project, sourceContainer, targetPsiFile, declarations, data.imports, data.declarationTexts ) } } private val sourcePsiFile = (sourceContainer as KtElement).containingKtFile private val psiDocumentManager = PsiDocumentManager.getInstance(project) private val sourceDocument = psiDocumentManager.getDocument(sourcePsiFile)!! fun performRefactoring() { psiDocumentManager.commitAllDocuments() val commandName = KotlinBundle.message("action.usage.update.command") val commandGroupId = Any() // we need to group both commands for undo // temporary revert imports to the state before they have been changed val importsSubstitution = if (sourcePsiFile.importDirectives.size != imports.size) { val startOffset = sourcePsiFile.importDirectives.minOfOrNull { it.startOffset } ?: 0 val endOffset = sourcePsiFile.importDirectives.minOfOrNull { it.endOffset } ?: 0 val importsDeclarationsText = sourceDocument.getText(TextRange(startOffset, endOffset)) val tempImportsText = imports.joinToString(separator = "\n") project.executeWriteCommand(commandName, commandGroupId) { sourceDocument.deleteString(startOffset, endOffset) sourceDocument.insertString(startOffset, tempImportsText) } psiDocumentManager.commitDocument(sourceDocument) ImportsSubstitution(importsDeclarationsText, tempImportsText, startOffset) } else { null } val tmpRangeAndDeclarations = insertStubDeclarations(commandName, commandGroupId, sourceDeclarationsText) assert(tmpRangeAndDeclarations.second.size == pastedDeclarations.size) val stubTexts = tmpRangeAndDeclarations.second.map { STUB_RENDERER.render(it.unsafeResolveToDescriptor()) } project.executeWriteCommand(commandName, commandGroupId) { sourceDocument.deleteString(tmpRangeAndDeclarations.first.startOffset, tmpRangeAndDeclarations.first.endOffset) } psiDocumentManager.commitDocument(sourceDocument) val stubRangeAndDeclarations = insertStubDeclarations(commandName, commandGroupId, stubTexts) val stubDeclarations = stubRangeAndDeclarations.second assert(stubDeclarations.size == pastedDeclarations.size) importsSubstitution?.let { project.executeWriteCommand(commandName, commandGroupId) { sourceDocument.deleteString(it.startOffset, it.startOffset + it.tempImportsText.length) sourceDocument.insertString(it.startOffset, it.originalImportsText) } psiDocumentManager.commitDocument(sourceDocument) } val mover = object : Mover { override fun invoke(declaration: KtNamedDeclaration, targetContainer: KtElement): KtNamedDeclaration { val index = stubDeclarations.indexOf(declaration) assert(index >= 0) declaration.delete() return pastedDeclarations[index] } } val declarationProcessor = MoveKotlinDeclarationsProcessor( MoveDeclarationsDescriptor( moveSource = MoveSource(stubDeclarations), moveTarget = KotlinMoveTargetForExistingElement(targetPsiFile), delegate = MoveDeclarationsDelegate.TopLevel, project = project ), mover ) val declarationUsages = project.runSynchronouslyWithProgress(RefactoringBundle.message("progress.text"), true) { runReadAction { declarationProcessor.findUsages().toList() } } ?: return project.executeWriteCommand(commandName, commandGroupId) { project.runRefactoringAndKeepDelayedRequests { declarationProcessor.execute(declarationUsages) } psiDocumentManager.doPostponedOperationsAndUnblockDocument(sourceDocument) val insertedStubRange = stubRangeAndDeclarations.first assert(insertedStubRange.isValid) sourceDocument.deleteString(insertedStubRange.startOffset, insertedStubRange.endOffset) } } private data class ImportsSubstitution(val originalImportsText: String, val tempImportsText: String, val startOffset: Int) private fun insertStubDeclarations( @NlsContexts.Command commandName: String, commandGroupId: Any?, values: List<String> ): Pair<RangeMarker, List<KtNamedDeclaration>> { val insertedRange = project.executeWriteCommand(commandName, commandGroupId) { val insertionOffset = sourceContainer.declarations.firstOrNull()?.startOffset ?: when (sourceContainer) { is KtFile -> sourceContainer.textLength is KtObjectDeclaration -> sourceContainer.getBody()?.rBrace?.startOffset ?: sourceContainer.endOffset else -> error("Unknown sourceContainer: $sourceContainer") } val textToInsert = "\n//start\n\n${values.joinToString(separator = "\n")}\n//end\n" sourceDocument.insertString(insertionOffset, textToInsert) sourceDocument.createRangeMarker(TextRange(insertionOffset, insertionOffset + textToInsert.length)) } psiDocumentManager.commitDocument(sourceDocument) val declarations = MoveDeclarationsCopyPasteProcessor.rangeToDeclarations( sourcePsiFile, insertedRange.textRange) return Pair(insertedRange, declarations) } }
apache-2.0
eaacbf4095ba92b204ecd4764d1a2f0a
47.410256
158
0.708338
5.830142
false
false
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/model/FeedUnreadCount.kt
1
2665
package com.nononsenseapps.feeder.model import androidx.room.ColumnInfo import androidx.room.Ignore import com.nononsenseapps.feeder.db.COL_CURRENTLY_SYNCING import com.nononsenseapps.feeder.db.room.ID_ALL_FEEDS import com.nononsenseapps.feeder.db.room.ID_UNSET import com.nononsenseapps.feeder.util.sloppyLinkToStrictURLNoThrows import java.net.URL data class FeedUnreadCount @Ignore constructor( var id: Long = ID_UNSET, var title: String = "", var url: URL = sloppyLinkToStrictURLNoThrows(""), var tag: String = "", @ColumnInfo(name = "custom_title") var customTitle: String = "", var notify: Boolean = false, @ColumnInfo(name = COL_CURRENTLY_SYNCING) var currentlySyncing: Boolean = false, @ColumnInfo(name = "image_url") var imageUrl: URL? = null, @ColumnInfo(name = "unread_count") var unreadCount: Int = 0 ) : Comparable<FeedUnreadCount> { constructor() : this(id = ID_UNSET) val displayTitle: String get() = customTitle.ifBlank { title } val isTop: Boolean get() = id == ID_ALL_FEEDS val isTag: Boolean get() = id < 1 && tag.isNotEmpty() override operator fun compareTo(other: FeedUnreadCount): Int { return when { // Top tag is always at the top (implies empty tags) isTop -> -1 other.isTop -> 1 // Feeds with no tags are always last isTag && !other.isTag && other.tag.isEmpty() -> -1 !isTag && other.isTag && tag.isEmpty() -> 1 !isTag && !other.isTag && tag.isNotEmpty() && other.tag.isEmpty() -> -1 !isTag && !other.isTag && tag.isEmpty() && other.tag.isNotEmpty() -> 1 // Feeds with identical tags compare by title tag == other.tag -> displayTitle.compareTo(other.displayTitle, ignoreCase = true) // In other cases it's just a matter of comparing tags else -> tag.compareTo(other.tag, ignoreCase = true) } } override fun equals(other: Any?): Boolean { return when (other) { null -> false is FeedUnreadCount -> { // val f = other as FeedWrapper? if (isTag && other.isTag) { // Compare tags tag == other.tag } else { // Compare items !isTag && !other.isTag && id == other.id } } else -> false } } override fun hashCode(): Int { return if (isTag) { // Tag tag.hashCode() } else { // Item id.hashCode() } } }
gpl-3.0
279f477b263d9c639ebaddae901af937
34.065789
93
0.56773
4.39769
false
false
false
false
CORDEA/MackerelClient
app/src/main/java/jp/cordea/mackerelclient/activity/HostDetailActivity.kt
1
4067
package jp.cordea.mackerelclient.activity import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import dagger.android.AndroidInjection import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.support.HasSupportFragmentInjector import jp.cordea.mackerelclient.ListItemDecoration import jp.cordea.mackerelclient.R import jp.cordea.mackerelclient.adapter.DetailCommonAdapter import jp.cordea.mackerelclient.databinding.ActivityDetailCommonBinding import jp.cordea.mackerelclient.fragment.HostRetireDialogFragment import jp.cordea.mackerelclient.model.DisplayableHost import jp.cordea.mackerelclient.utils.DateUtils import jp.cordea.mackerelclient.utils.StatusUtils import javax.inject.Inject class HostDetailActivity : AppCompatActivity(), HasSupportFragmentInjector { @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment> private lateinit var host: DisplayableHost override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState) val binding = DataBindingUtil .setContentView<ActivityDetailCommonBinding>(this, R.layout.activity_detail_common) supportActionBar?.setDisplayHomeAsUpEnabled(true) host = intent.getParcelableExtra(HOST_KEY) binding.recyclerView.let { it.layoutManager = LinearLayoutManager(this) it.adapter = DetailCommonAdapter(this, createData(host)) it.addItemDecoration(ListItemDecoration(this)) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.host_detail, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> finish() R.id.action_retire -> { HostRetireDialogFragment .newInstance(host) .apply { onSuccess = { setResult(Activity.RESULT_OK) finish() } } .show(supportFragmentManager, "") } } return super.onOptionsItemSelected(item) } override fun supportFragmentInjector(): AndroidInjector<Fragment> = dispatchingAndroidInjector private fun createData(host: DisplayableHost): List<List<Pair<String, Int>>> { val list: MutableList<MutableList<Pair<String, Int>>> = arrayListOf() var inner: MutableList<Pair<String, Int>> = arrayListOf() inner.add(StatusUtils.requestNameToString(host.status) to R.string.host_detail_status) inner.add(host.memo to R.string.host_detail_memo) list.add(inner) inner = arrayListOf() inner.add( host.numberOfRoles.let { when { it <= 1 -> resources.getString(R.string.format_role).format(it) it > 99 -> resources.getString(R.string.format_roles_ex) else -> resources.getString(R.string.format_roles).format(it) } } to R.string.host_detail_roles ) inner.add( DateUtils.stringDateFromEpoch(host.createdAt) to R.string.host_detail_created_at ) list.add(inner) return list } companion object { const val REQUEST_CODE = 0 private const val HOST_KEY = "HostKey" fun createIntent(context: Context, host: DisplayableHost): Intent = Intent(context, HostDetailActivity::class.java).apply { putExtra(HOST_KEY, host) } } }
apache-2.0
d947edc68521ff6fd281fc772692a54f
36.311927
98
0.674945
5.00246
false
false
false
false
spring-projects/spring-framework
spring-tx/src/test/kotlin/org/springframework/transaction/annotation/CoroutinesAnnotationTransactionInterceptorTests.kt
1
4809
/* * Copyright 2002-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. */ package org.springframework.transaction.annotation import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.toList import kotlinx.coroutines.runBlocking import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.fail import org.junit.jupiter.api.Test import org.springframework.aop.framework.ProxyFactory import org.springframework.transaction.interceptor.TransactionInterceptor import org.springframework.transaction.testfixture.ReactiveCallCountingTransactionManager /** * @author Sebastien Deleuze */ class CoroutinesAnnotationTransactionInterceptorTests { private val rtm = ReactiveCallCountingTransactionManager() private val source = AnnotationTransactionAttributeSource() @Test fun suspendingNoValueSuccess() { val proxyFactory = ProxyFactory() proxyFactory.setTarget(TestWithCoroutines()) proxyFactory.addAdvice(TransactionInterceptor(rtm, source)) val proxy = proxyFactory.proxy as TestWithCoroutines runBlocking { proxy.suspendingNoValueSuccess() } assertReactiveGetTransactionAndCommitCount(1) } @Test fun suspendingNoValueFailure() { val proxyFactory = ProxyFactory() proxyFactory.setTarget(TestWithCoroutines()) proxyFactory.addAdvice(TransactionInterceptor(rtm, source)) val proxy = proxyFactory.proxy as TestWithCoroutines runBlocking { try { proxy.suspendingNoValueFailure() } catch (ex: IllegalStateException) { } } assertReactiveGetTransactionAndRollbackCount(1) } @Test fun suspendingValueSuccess() { val proxyFactory = ProxyFactory() proxyFactory.setTarget(TestWithCoroutines()) proxyFactory.addAdvice(TransactionInterceptor(rtm, source)) val proxy = proxyFactory.proxy as TestWithCoroutines runBlocking { assertThat(proxy.suspendingValueSuccess()).isEqualTo("foo") } assertReactiveGetTransactionAndCommitCount(1) } @Test fun suspendingValueFailure() { val proxyFactory = ProxyFactory() proxyFactory.setTarget(TestWithCoroutines()) proxyFactory.addAdvice(TransactionInterceptor(rtm, source)) val proxy = proxyFactory.proxy as TestWithCoroutines runBlocking { try { proxy.suspendingValueFailure() fail("No exception thrown as expected") } catch (ex: IllegalStateException) { } } assertReactiveGetTransactionAndRollbackCount(1) } @Test fun suspendingFlowSuccess() { val proxyFactory = ProxyFactory() proxyFactory.setTarget(TestWithCoroutines()) proxyFactory.addAdvice(TransactionInterceptor(rtm, source)) val proxy = proxyFactory.proxy as TestWithCoroutines runBlocking { assertThat(proxy.suspendingFlowSuccess().toList()).containsExactly("foo", "foo") } assertReactiveGetTransactionAndCommitCount(1) } @Test fun flowSuccess() { val proxyFactory = ProxyFactory() proxyFactory.setTarget(TestWithCoroutines()) proxyFactory.addAdvice(TransactionInterceptor(rtm, source)) val proxy = proxyFactory.proxy as TestWithCoroutines runBlocking { assertThat(proxy.flowSuccess().toList()).containsExactly("foo", "foo") } assertReactiveGetTransactionAndCommitCount(1) } private fun assertReactiveGetTransactionAndCommitCount(expectedCount: Int) { assertThat(rtm.begun).isEqualTo(expectedCount) assertThat(rtm.commits).isEqualTo(expectedCount) } private fun assertReactiveGetTransactionAndRollbackCount(expectedCount: Int) { assertThat(rtm.begun).isEqualTo(expectedCount) assertThat(rtm.rollbacks).isEqualTo(expectedCount) } @Transactional open class TestWithCoroutines { open suspend fun suspendingNoValueSuccess() { delay(10) } open suspend fun suspendingNoValueFailure() { delay(10) throw IllegalStateException() } open suspend fun suspendingValueSuccess(): String { delay(10) return "foo" } open suspend fun suspendingValueFailure(): String { delay(10) throw IllegalStateException() } open fun flowSuccess(): Flow<String> { return flow { emit("foo") delay(10) emit("foo") } } open suspend fun suspendingFlowSuccess(): Flow<String> { delay(10) return flow { emit("foo") delay(10) emit("foo") } } } }
apache-2.0
56b863d23132fe7bb744e385ab765225
27.288235
89
0.768975
4.328533
false
true
false
false
genonbeta/TrebleShot
zxing/src/main/java/org/monora/android/codescanner/BarcodeEncoder.kt
1
2947
/* * Copyright (C) 2012-2018 ZXing authors, Journey Mobile * Copyright (C) 2021 Veli Tasalı * * 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.monora.android.codescanner import android.graphics.Bitmap import com.google.zxing.BarcodeFormat import com.google.zxing.EncodeHintType import com.google.zxing.MultiFormatWriter import com.google.zxing.WriterException import com.google.zxing.common.BitMatrix class BarcodeEncoder { fun createBitmap(matrix: BitMatrix): Bitmap { val width = matrix.width val height = matrix.height val pixels = IntArray(width * height) for (y in 0 until height) { val offset = y * width for (x in 0 until width) { pixels[offset + x] = if (matrix[x, y]) BLACK else WHITE } } val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) bitmap.setPixels(pixels, 0, width, 0, 0, width, height) return bitmap } @Throws(WriterException::class) fun encode(contents: String?, format: BarcodeFormat?, width: Int, height: Int): BitMatrix { return try { MultiFormatWriter().encode(contents, format, width, height) } catch (e: WriterException) { throw e } catch (e: Exception) { throw WriterException(e) } } @Throws(WriterException::class) fun encode( contents: String?, format: BarcodeFormat?, width: Int, height: Int, hints: Map<EncodeHintType?, *>? ): BitMatrix { return try { MultiFormatWriter().encode(contents, format, width, height, hints) } catch (e: WriterException) { throw e } catch (e: Exception) { throw WriterException(e) } } @Throws(WriterException::class) fun encodeBitmap(contents: String?, format: BarcodeFormat?, width: Int, height: Int): Bitmap { return createBitmap(encode(contents, format, width, height)) } @Throws(WriterException::class) fun encodeBitmap( contents: String?, format: BarcodeFormat?, width: Int, height: Int, hints: Map<EncodeHintType?, *>? ): Bitmap { return createBitmap(encode(contents, format, width, height, hints)) } companion object { private const val WHITE = -0x1 private const val BLACK = -0x1000000 } }
gpl-2.0
c2936f5d3f4851ac80d8a499a2e66fc9
31.384615
98
0.637814
4.338733
false
false
false
false
xranby/modern-jogl-examples
src/main/kotlin/main/tut03/vertPositionOffset.kt
1
3463
package main.tut03 import buffer.destroy import com.jogamp.newt.event.KeyEvent import com.jogamp.opengl.GL.* import com.jogamp.opengl.GL2ES3.GL_COLOR import com.jogamp.opengl.GL3 import com.jogamp.opengl.util.glsl.ShaderProgram import extensions.intBufferBig import extensions.toFloatBuffer import glsl.programOf import glsl.shaderCodeOf import main.L import main.SIZE import main.f import main.framework.Framework import main.framework.Semantic import main.glm import vec._2.Vec2 import vec._4.Vec4 /** * Created by elect on 21/02/17. */ fun main(args: Array<String>) { VertPositionOffset_() } class VertPositionOffset_ : Framework("Tutorial 03 - Shader Position Offset") { var theProgram = 0 var offsetLocation = 0 val positionBufferObject = intBufferBig(1) val vao = intBufferBig(1) val vertexPositions = floatArrayOf( +0.25f, +0.25f, 0.0f, 1.0f, +0.25f, -0.25f, 0.0f, 1.0f, -0.25f, -0.25f, 0.0f, 1.0f) var startingTime = 0L override fun init(gl: GL3) = with(gl) { initializeProgram(gl) initializeVertexBuffer(gl) glGenVertexArrays(1, vao) glBindVertexArray(vao[0]) startingTime = System.currentTimeMillis() } fun initializeProgram(gl: GL3) { theProgram = programOf(gl, this::class.java, "tut03", "position-offset.vert", "standard.frag") offsetLocation = gl.glGetUniformLocation(theProgram, "offset") } fun initializeVertexBuffer(gl: GL3) = with(gl){ val vertexBuffer = vertexPositions.toFloatBuffer() glGenBuffers(1, positionBufferObject) glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject[0]) glBufferData(GL_ARRAY_BUFFER, vertexBuffer.SIZE.L, vertexBuffer, GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER, 0) vertexBuffer.destroy() } override fun display(gl: GL3) = with(gl){ val offset = Vec2(0f) computePositionOffsets(offset) glClearBufferfv(GL_COLOR, 0, clearColor.put(0, 0f).put(1, 0f).put(2, 0f).put(3, 1f)) glUseProgram(theProgram) glUniform2f(offsetLocation, offset.x, offset.y) glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject[0]) glEnableVertexAttribArray(Semantic.Attr.POSITION) glVertexAttribPointer(Semantic.Attr.POSITION, 4, GL_FLOAT, false, Vec4.SIZE, 0) glDrawArrays(GL_TRIANGLES, 0, 3) glDisableVertexAttribArray(Semantic.Attr.POSITION) glUseProgram(0) } fun computePositionOffsets(offset: Vec2) { val loopDuration = 5.0f val scale = Math.PI.f * 2f / loopDuration // todo glm val elapsedTime = (System.currentTimeMillis() - startingTime) / 1_000f val currTimeThroughLoop = elapsedTime % loopDuration offset.x = glm.cos(currTimeThroughLoop * scale) * .5f offset.y = glm.sin(currTimeThroughLoop * scale) * .5f } override fun reshape(gl: GL3, w: Int, h: Int) { gl.glViewport(0, 0, w, h) } override fun end(gl: GL3) = with(gl) { glDeleteProgram(theProgram) glDeleteBuffers(1, positionBufferObject) glDeleteVertexArrays(1, vao) positionBufferObject.destroy() vao.destroy() } override fun keyPressed(keyEvent: KeyEvent) { when (keyEvent.keyCode) { KeyEvent.VK_ESCAPE -> { animator.remove(window) window.destroy() } } } }
mit
a3767e1b64573afae52aa8f783d568e0
25.442748
102
0.656656
3.953196
false
false
false
false
code-helix/slatekit
src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_Auth.kt
1
2346
/** <slate_header> author: Kishore Reddy url: www.github.com/code-helix/slatekit copyright: 2015 Kishore Reddy license: www.github.com/code-helix/slatekit/blob/master/LICENSE.md desc: A tool-kit, utility library and server-backend usage: Please refer to license on github for more info. </slate_header> */ package slatekit.examples //<doc:import_required> import slatekit.common.auth.AuthConsole import slatekit.common.auth.User //</doc:import_required> //<doc:import_examples> import slatekit.results.Try import slatekit.results.Success //</doc:import_examples> class Example_Auth : Command("auth") { override fun execute(request: CommandRequest) : Try<Any> { //<doc:setup> // Setup: Setup the Auth wrapper with the user to inspect info about the user // NOTES: // * 1. This component does NOT handle any actual login/logout/authorization features. // * 2. This set of classes are only used to inspect information about a user. // * 3. Since authorization is a fairly complex feature with implementations such as // * OAuth, Social Auth, Slate Kit has purposely left out the Authentication to more reliable // * libraries and frameworks. // * 4. The SlateKit.Api component, while supporting basic api "Keys" based authentication, // * and a roles based authentication, it leaves the login/logout and actual generating // * of tokens to libraries such as OAuth. val user2 = User( "2", "johndoe","john doe", "john doe", "john","doe", "[email protected]", "123-456-7890", "us", false, false, true) val auth = AuthConsole(isAuthenticated = true, user = user2, roles = "admin") //</doc:setup> //<doc:examples> // CASE 1: Use the auth to check user info println ("Checking auth info in desktop/local mode" ) println ( "user info : " + auth.user ) println ( "user id : " + auth.userId ) println ( "is authenticated : " + auth.isAuthenticated ) println ( "is email verified : " + auth.isEmailVerified ) println ( "is phone verified : " + auth.isPhoneVerified ) println ( "is a moderator : " + auth.isInRole( "moderator") ) println ( "is an admin : " + auth.isInRole( "admin" ) ) //</doc:examples> return Success("") } }
apache-2.0
630e79307beb5048cd16b1f4b990139e
36.238095
134
0.655158
3.890547
false
false
false
false
leafclick/intellij-community
platform/configuration-store-impl/src/ExportSettingsAction.kt
1
12209
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.AbstractBundle import com.intellij.DynamicBundle import com.intellij.configurationStore.schemeManager.ROOT_CONFIG import com.intellij.configurationStore.schemeManager.SchemeManagerFactoryBase import com.intellij.ide.IdeBundle import com.intellij.ide.actions.ImportSettingsFilenameFilter import com.intellij.ide.actions.RevealFileAction import com.intellij.ide.plugins.PluginManager import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.components.* import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.options.OptionsBundle import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.project.DumbAware import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.showOkCancelDialog import com.intellij.openapi.util.io.FileUtil import com.intellij.serviceContainer.PlatformComponentManagerImpl import com.intellij.serviceContainer.processAllImplementationClasses import com.intellij.util.ArrayUtil import com.intellij.util.ReflectionUtil import com.intellij.util.containers.putValue import com.intellij.util.io.* import gnu.trove.THashMap import gnu.trove.THashSet import java.io.IOException import java.io.OutputStream import java.io.StringWriter import java.nio.file.Path import java.nio.file.Paths import java.util.* internal fun isImportExportActionApplicable(): Boolean { val app = ApplicationManager.getApplication() val storageManager = app.stateStore.storageManager as? StateStorageManagerImpl ?: return true return !storageManager.isStreamProviderPreventExportAction } // for Rider purpose open class ExportSettingsAction : AnAction(), DumbAware { protected open fun getExportableComponents(): Map<Path, List<ExportableItem>> = getExportableComponentsMap(true, true) protected open fun exportSettings(saveFile: Path, markedComponents: Set<ExportableItem>) { val exportFiles = markedComponents.mapTo(THashSet()) { it.file } saveFile.outputStream().use { exportSettings(exportFiles, it, FileUtil.toSystemIndependentName(PathManager.getConfigPath())) } } override fun update(e: AnActionEvent) { e.presentation.isEnabled = isImportExportActionApplicable() } override fun actionPerformed(e: AnActionEvent) { ApplicationManager.getApplication().saveSettings() val dialog = ChooseComponentsToExportDialog(getExportableComponents(), true, IdeBundle.message("title.select.components.to.export"), IdeBundle.message("prompt.please.check.all.components.to.export")) if (!dialog.showAndGet()) { return } val markedComponents = dialog.exportableComponents if (markedComponents.isEmpty()) { return } val saveFile = dialog.exportFile try { if (saveFile.exists() && showOkCancelDialog( title = IdeBundle.message("title.file.already.exists"), message = IdeBundle.message("prompt.overwrite.settings.file", saveFile.toString()), okText = IdeBundle.message("action.overwrite"), icon = Messages.getWarningIcon()) != Messages.OK) { return } exportSettings(saveFile, markedComponents) RevealFileAction.showDialog(getEventProject(e), IdeBundle.message("message.settings.exported.successfully"), IdeBundle.message("title.export.successful"), saveFile.toFile(), null) } catch (e: IOException) { Messages.showErrorDialog(IdeBundle.message("error.writing.settings", e.toString()), IdeBundle.message("title.error.writing.file")) } } } fun exportSettings(exportFiles: Set<Path>, out: OutputStream, configPath: String) { val filter = THashSet<String>() Compressor.Zip(out).filter { entryName, _ -> filter.add(entryName) }.use { zip -> for (file in exportFiles) { val fileInfo = file.basicAttributesIfExists() ?: continue val relativePath = FileUtil.getRelativePath(configPath, file.toAbsolutePath().systemIndependentPath, '/')!! if (fileInfo.isDirectory) { zip.addDirectory(relativePath, file.toFile()) } else { zip.addFile(relativePath, file.inputStream()) } } exportInstalledPlugins(zip) zip.addFile(ImportSettingsFilenameFilter.SETTINGS_JAR_MARKER, ArrayUtil.EMPTY_BYTE_ARRAY) } } data class ExportableItem(val file: Path, val presentableName: String, val roamingType: RoamingType = RoamingType.DEFAULT) fun exportInstalledPlugins(zip: Compressor) { val plugins = PluginManagerCore.getPlugins().asSequence().filter { !it.isBundled && it.isEnabled }.map { it.pluginId }.toList() if (plugins.isNotEmpty()) { val buffer = StringWriter() PluginManagerCore.writePluginsList(plugins, buffer) zip.addFile(PluginManager.INSTALLED_TXT, buffer.toString().toByteArray()) } } // onlyPaths - include only specified paths (relative to config dir, ends with "/" if directory) fun getExportableComponentsMap(isOnlyExisting: Boolean, isComputePresentableNames: Boolean, storageManager: StateStorageManager = ApplicationManager.getApplication().stateStore.storageManager, onlyPaths: Set<String>? = null): Map<Path, List<ExportableItem>> { val result = LinkedHashMap<Path, MutableList<ExportableItem>>() @Suppress("DEPRECATION") val processor = { component: ExportableComponent -> for (file in component.exportFiles) { val item = ExportableItem(file.toPath(), component.presentableName, RoamingType.DEFAULT) result.putValue(item.file, item) } } val app = ApplicationManager.getApplication() as PlatformComponentManagerImpl @Suppress("DEPRECATION") app.getComponentInstancesOfType(ExportableApplicationComponent::class.java).forEach(processor) @Suppress("DEPRECATION") ServiceBean.loadServicesFromBeans(ExportableComponent.EXTENSION_POINT, ExportableComponent::class.java).forEach(processor) val configPath = storageManager.expandMacros(ROOT_CONFIG) fun isSkipFile(file: Path): Boolean { if (onlyPaths != null) { var relativePath = FileUtil.getRelativePath(configPath, file.systemIndependentPath, '/')!! if (!file.fileName.toString().contains('.') && !file.isFile()) { relativePath += '/' } if (!onlyPaths.contains(relativePath)) { return true } } return isOnlyExisting && !file.exists() } if (isOnlyExisting || onlyPaths != null) { result.keys.removeAll(::isSkipFile) } val fileToContent = THashMap<Path, String>() processAllImplementationClasses(app.picoContainer) { aClass, pluginDescriptor -> val stateAnnotation = getStateSpec(aClass) @Suppress("DEPRECATION") if (stateAnnotation == null || stateAnnotation.name.isEmpty() || ExportableComponent::class.java.isAssignableFrom(aClass)) { return@processAllImplementationClasses true } val storage = stateAnnotation.storages.sortByDeprecated().firstOrNull() ?: return@processAllImplementationClasses true val isRoamable = getEffectiveRoamingType(storage.roamingType, storage.path) != RoamingType.DISABLED if (!isStorageExportable(storage, isRoamable)) { return@processAllImplementationClasses true } val additionalExportFile: Path? val file: Path try { additionalExportFile = getAdditionalExportFile(stateAnnotation, storageManager, ::isSkipFile) file = Paths.get(storageManager.expandMacros(storage.path)) } catch (e: UnknownMacroException) { LOG.error("Cannot expand macro for component \"${stateAnnotation.name}\"", e) return@processAllImplementationClasses true } val isFileIncluded = !isSkipFile(file) if (isFileIncluded || additionalExportFile != null) { if (isComputePresentableNames && isOnlyExisting && additionalExportFile == null && file.fileName.toString().endsWith(".xml")) { val content = fileToContent.getOrPut(file) { file.readText() } if (!content.contains("""<component name="${stateAnnotation.name}"""")) { return@processAllImplementationClasses true } } val presentableName = if (isComputePresentableNames) getComponentPresentableName(stateAnnotation, aClass, pluginDescriptor) else "" if (isFileIncluded) { result.putValue(file, ExportableItem(file, presentableName, storage.roamingType)) } if (additionalExportFile != null) { result.putValue(additionalExportFile, ExportableItem(additionalExportFile, "$presentableName (schemes)", RoamingType.DEFAULT)) } } true } // must be in the end - because most of SchemeManager clients specify additionalExportFile in the State spec (SchemeManagerFactory.getInstance() as SchemeManagerFactoryBase).process { if (it.roamingType != RoamingType.DISABLED && it.fileSpec.getOrNull(0) != '$') { val file = Paths.get(storageManager.expandMacros(ROOT_CONFIG), it.fileSpec) if (!result.containsKey(file) && !isSkipFile(file)) { result.putValue(file, ExportableItem(file, it.presentableName ?: "", it.roamingType)) } } } return result } private inline fun getAdditionalExportFile(stateAnnotation: State, storageManager: StateStorageManager, isSkipFile: (file: Path) -> Boolean): Path? { val additionalExportPath = stateAnnotation.additionalExportFile if (additionalExportPath.isEmpty()) { return null } val additionalExportFile: Path? // backward compatibility - path can contain macro if (additionalExportPath[0] == '$') { additionalExportFile = Paths.get(storageManager.expandMacros(additionalExportPath)) } else { additionalExportFile = Paths.get(storageManager.expandMacros(ROOT_CONFIG), additionalExportPath) } return if (isSkipFile(additionalExportFile)) null else additionalExportFile } private fun isStorageExportable(storage: Storage, isRoamable: Boolean): Boolean = storage.exportable || isRoamable && storage.storageClass == StateStorage::class && storage.path.isNotEmpty() private fun getComponentPresentableName(state: State, aClass: Class<*>, pluginDescriptor: PluginDescriptor?): String { val presentableName = state.presentableName.java if (presentableName != State.NameGetter::class.java) { try { return ReflectionUtil.newInstance(presentableName).get() } catch (e: Exception) { LOG.error(e) } } val defaultName = state.name fun trimDefaultName(): String { // Vcs.Log.App.Settings return defaultName .removeSuffix(".Settings") .removeSuffix(".Settings") } var resourceBundleName: String? if (pluginDescriptor != null && PluginManagerCore.CORE_ID != pluginDescriptor.pluginId) { resourceBundleName = pluginDescriptor.resourceBundleBaseName if (resourceBundleName == null) { if (pluginDescriptor.vendor == "JetBrains") { resourceBundleName = OptionsBundle.BUNDLE } else { return trimDefaultName() } } } else { resourceBundleName = OptionsBundle.BUNDLE } val classLoader = pluginDescriptor?.pluginClassLoader ?: aClass.classLoader if (classLoader != null) { val message = messageOrDefault(classLoader, resourceBundleName, defaultName) if (message !== defaultName) { return message } } return trimDefaultName() } private fun messageOrDefault(classLoader: ClassLoader, bundleName: String, defaultName: String): String { try { return AbstractBundle.messageOrDefault( DynamicBundle.INSTANCE.getResourceBundle(bundleName, classLoader), "exportable.$defaultName.presentable.name", defaultName) } catch (e: MissingResourceException) { LOG.warn("Missing bundle ${bundleName} at ${classLoader}: ${e.message}") return defaultName } }
apache-2.0
00dc293c1037f64c1d0d1ada3f9f43ba
39.430464
149
0.731755
5.074397
false
false
false
false
code-helix/slatekit
src/ext/kotlin/slatekit-providers-aws/src/main/kotlin/slatekit/providers/aws/AwsCloudDocs.kt
1
3136
package slatekit.providers.aws import com.amazonaws.auth.AWSCredentials import com.amazonaws.auth.AWSStaticCredentialsProvider import slatekit.core.docs.CloudDocs import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder import com.amazonaws.services.dynamodbv2.document.DynamoDB import com.amazonaws.services.dynamodbv2.document.Item import com.amazonaws.services.dynamodbv2.document.spec.GetItemSpec import slatekit.results.Outcome import slatekit.results.builders.Outcomes import com.amazonaws.services.dynamodbv2.document.PrimaryKey import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec /** * Conversion to/from no sql * @tparam TPartition * @tparam TCluster */ interface AwsDocMapper<TEntity, TPartition, TCluster> { fun keys(entity:TEntity):Pair<TPartition, TCluster> fun toDoc(entity:TEntity):Item fun ofDoc(doc:Item, partition:TPartition, cluster:TCluster):TEntity } class AwsCloudDocs<TEntity, TPartition, TCluster>( val region:String, val tableName: String, val partitionName:String, val clusterName:String, val mapper:AwsDocMapper<TEntity, TPartition, TCluster>, creds: AWSCredentials) : CloudDocs<TEntity, TPartition, TCluster>{ private val client = AmazonDynamoDBClientBuilder.standard().withCredentials(AWSStaticCredentialsProvider(creds)).build() private val dynamoDB = DynamoDB(client) private val table = dynamoDB.getTable(tableName) override fun create(entity:TEntity): Outcome<TEntity> { return Outcomes.of { val item = mapper.toDoc(entity) val result = table.putItem(item) entity } } override fun update(entity:TEntity): Outcome<TEntity> { return Outcomes.errored(Exception("DynamoDB.update : Not implemented")) } override fun delete(entity:TEntity): Outcome<TEntity> { return Outcomes.of { val keys = mapper.keys(entity) val spec = DeleteItemSpec().withPrimaryKey(PrimaryKey(partitionName, keys.first, clusterName, keys.second)) val item = table.deleteItem(spec) entity } } override fun get(partition: TPartition): Outcome<TEntity> { return Outcomes.invalid() } override fun get(partition: TPartition, cluster: TCluster): Outcome<TEntity> { return Outcomes.of { val spec = GetItemSpec().withPrimaryKey(partitionName, partition, clusterName, cluster) val item = table.getItem(spec) val entity = mapper.ofDoc(item, partition, cluster) entity } } } /* open class AwsCloudDoc<TPartition, TCluster>(override val partition:TPartition, override val cluster:TCluster, override val fields:Map<String, Any?>, override val source:Any ) : CloudDoc<TPartition, TCluster> { constructor(partition:TPartition, cluster:TCluster, fields:Map<String, Any?>): this(partition, cluster, fields, fields) } */
apache-2.0
157e6b4514c932c959b7a8661b97c626
32.731183
124
0.679209
4.666667
false
false
false
false
Scliang/KQuick
demo/src/main/kotlin/DemoActivity.kt
1
9536
package com.scliang.kquick.demo import android.app.Activity import android.os.Bundle import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.scliang.kquick.FullScreenActivity import com.scliang.kquick.NUtils import java.util.* import android.graphics.BitmapFactory import android.graphics.Bitmap import android.os.Environment import android.widget.Button import android.content.Intent import android.graphics.Canvas import android.graphics.Paint import android.util.Log import java.io.ByteArrayInputStream import java.io.File import java.io.PrintStream import java.net.ConnectException import java.net.Socket import java.net.SocketException import java.net.SocketTimeoutException import java.nio.ByteBuffer /** * Created by scliang on 2017/6/12. * KQuick Library Demo */ class DemoActivity : FullScreenActivity<IData>() { private val sCaptureTmpFile = Environment.getExternalStorageDirectory().absolutePath + "/tmp.jpg" var videoRecvable = false // var client: Socket? = null var ori: ImageView? = null // override fun giveWindowColor(): Long { // return 0xffff4444 // } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_demo) val tv: TextView = findViewById(R.id.version_text) val parent = tv.parent as ViewGroup parent.setPadding(0, getStatusBarHeight(), 0, 0) tv.text = String.format(Locale.CHINESE, "v%s", NUtils.getNativeVersion()) // val bmp = BitmapFactory.decodeResource(resources, R.mipmap.walle) ori = findViewById(R.id.imageView) // ori.setImageBitmap(bmp) // val w = bmp.width // val h = bmp.height // // val src = IntArray(w * h) // bmp.getPixels(src, 0, w, 0, 0, w, h) // val dst = IntArray(w * h) // val rect = NUtils.findObject(src, dst, w, h, 0x1982f8) // println("Find Object: ${rect[0]}:${rect[1]}:${rect[2]}:${rect[3]} @ ${rect[4]}:${rect[5]}") // val resultImg = Bitmap.createBitmap(dst, w, h, Bitmap.Config.ARGB_8888) // val gray = findViewById(R.id.imageView_gray) as ImageView // gray.setImageBitmap(resultImg) val camera: Button = findViewById(R.id.camera) camera.setOnClickListener { // if (PackageManager.PERMISSION_GRANTED == // ContextCompat.checkSelfPermission(container!!.context, // Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // val file = File(sCaptureTmpFile) // if (file.exists()) { // file.delete() // } // val uri = Uri.fromFile(file) // val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) // intent.putExtra(MediaStore.EXTRA_OUTPUT, uri) // startActivityForResult(intent, 100) // } else { // ActivityCompat.requestPermissions(container!!.context as Activity, // Array(1, {Manifest.permission.WRITE_EXTERNAL_STORAGE}), // 200) // Toast.makeText(container!!.context, "没有权限", Toast.LENGTH_SHORT).show() // } startFragment(DemoFragment().javaClass) } startRecvWalleVideo() } override fun onDestroy() { stopRecvWalleVideo() super.onDestroy() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == 100 && resultCode == Activity.RESULT_OK) { val file = File(sCaptureTmpFile) if (file.exists()) { val op = BitmapFactory.Options() op.inSampleSize = 3 val bmp = BitmapFactory.decodeFile(file.absolutePath, op) if (bmp != null) { val w = bmp.width val h = bmp.height val src = IntArray(w * h) bmp.getPixels(src, 0, w, 0, 0, w, h) val dst = IntArray(w * h) val rect = NUtils.findObject(src, dst, w, h, 0x1982f8) println("Find Object: ${rect[0]}:${rect[1]}:${rect[2]}:${rect[3]} @ ${rect[4]}:${rect[5]}") val tmp = Bitmap.createBitmap(src, w, h, Bitmap.Config.ARGB_8888) val resultImg = tmp.copy(Bitmap.Config.ARGB_8888, true) tmp.recycle() val canvas = Canvas(resultImg) val r = Math.sqrt(Math.pow((rect[2] - rect[0]).toDouble(), 2.0) + Math.pow((rect[3] - rect[1]).toDouble(), 2.0)) / 2 val paint = Paint() paint.isAntiAlias = true paint.style = Paint.Style.STROKE paint.color = 0xffff4444.toInt() paint.strokeWidth = 2f canvas.drawCircle(rect[4].toFloat(), rect[5].toFloat(), r.toFloat(), paint) val ori: ImageView = findViewById(R.id.imageView) ori.setImageBitmap(resultImg) } } } } fun startRecvWalleVideo() { if (!videoRecvable) { videoRecvable = true // Thread(Runnable { // try { // client = Socket("192.168.2.26", 8869) // client!!.soTimeout = 1000 // val out = PrintStream(client!!.getOutputStream()) // val reader = client!!.getInputStream() // val buffer = ByteArray(10240, { 0 }) //// val bf = ByteArray(buffer.size, {0}) // val byteBuffer = ByteArray(320 * 240, {0}) // val resultImg = Bitmap.createBitmap(320, 240, Bitmap.Config.ARGB_8888) // while (videoRecvable) { // out.write("once".toByteArray()) // out.flush() // var countSum = 0 // val start = System.currentTimeMillis() // while (videoRecvable) { // try { // val count = reader.read(buffer) // if (count != -1) { // System.arraycopy(buffer, 0, byteBuffer, countSum, buffer.size) // countSum += count // Log.d("WalleVideo", "read count $count, Sum: $countSum") // } else { // break // } // } catch (e: SocketException) { // e.printStackTrace() // break // } catch (e: SocketTimeoutException) { // e.printStackTrace() // break // } // } //// Log.d("kQuick", "read sum: $countSum") //// for (d in byteBuffer) { //// Log.d("kQuick", "dstArray: $d") //// } // Log.d("kQuick", "duration1: ${System.currentTimeMillis() - start}") // val targetArray = NUtils.decodeImage(byteBuffer, countSum) // Log.d("kQuick", "duration2: ${System.currentTimeMillis() - start}") // if (targetArray != null) { //// Log.d("kQuick", "read end: $countSum - ${byteBuffer.size} - ${targetArray.size}") //// val resultImg = Bitmap.createBitmap(targetArray, 640, 240, Bitmap.Config.ARGB_8888) // resultImg.setPixels(targetArray, 0, 320, 0, 0, 320, 240) // Log.d("kQuick", "duration3: ${System.currentTimeMillis() - start}") // if (ori != null) { // ori!!.post { // ori!!.setImageBitmap(resultImg) // } // } // } // } // out.write("bye".toByteArray()) // out.flush() // Thread.sleep(1000) // client!!.close() // } catch (e: ConnectException) { // e.printStackTrace() // } // }).start() NUtils.startRecvImage("192.168.88.129", 8869) if (ori != null) { val targetArray = IntArray(320 * 240, {0}) val resultImg = Bitmap.createBitmap(320, 240, Bitmap.Config.ARGB_8888) Thread(Runnable { while (videoRecvable) { NUtils.getRecvImage(targetArray) resultImg.setPixels(targetArray, 0, 320, 0, 0, 320, 240) ori!!.post { ori!!.setImageBitmap(resultImg) } Thread.sleep(40) } }).start() } } } fun stopRecvWalleVideo() { // if (client != null) { // client!!.close() // } NUtils.stopRecvImage() videoRecvable = false } }
apache-2.0
f09acedb3e909d5e58072bd8f655ff6b
41.346667
111
0.489505
4.582973
false
false
false
false
Triple-T/gradle-play-publisher
play/plugin/src/test/kotlin/com/github/triplet/gradle/play/tasks/CommitEditIntegrationTest.kt
1
3646
package com.github.triplet.gradle.play.tasks import com.github.triplet.gradle.androidpublisher.CommitResponse import com.github.triplet.gradle.androidpublisher.FakePlayPublisher import com.github.triplet.gradle.androidpublisher.newSuccessCommitResponse import com.github.triplet.gradle.common.utils.marked import com.github.triplet.gradle.common.utils.safeCreateNewFile import com.github.triplet.gradle.play.helpers.IntegrationTestBase import com.github.triplet.gradle.play.helpers.SharedIntegrationTest import com.google.common.truth.Truth.assertThat import org.gradle.testkit.runner.TaskOutcome.SKIPPED import org.gradle.testkit.runner.TaskOutcome.SUCCESS import org.junit.jupiter.api.Test import java.io.File class CommitEditIntegrationTest : IntegrationTestBase(), SharedIntegrationTest { override fun taskName(taskVariant: String) = ":commitEditForComDotExampleDotPublisher" @Test fun `Commit is not applied by default`() { val editFile = File(appDir, "build/gpp/com.example.publisher.txt") editFile.safeCreateNewFile().writeText("foobar") val result = execute("", ":commitEditForComDotExampleDotPublisher") result.requireTask(outcome = SUCCESS) assertThat(result.output).doesNotContain("commitEdit(") } @Test fun `Commit is not applied if skip requested`() { val editFile = File(appDir, "build/gpp/com.example.publisher.txt") editFile.safeCreateNewFile().writeText("foobar") editFile.marked("skipped").safeCreateNewFile() val result = execute("", ":commitEditForComDotExampleDotPublisher") result.requireTask(outcome = SUCCESS) assertThat(result.output).doesNotContain("commitEdit(") assertThat(result.output).contains("validateEdit(") } @Test fun `Commit is applied if requested`() { val editFile = File(appDir, "build/gpp/com.example.publisher.txt") editFile.safeCreateNewFile().writeText("foobar") editFile.marked("commit").safeCreateNewFile() val result = execute("", "commitEditForComDotExampleDotPublisher") result.requireTask(outcome = SUCCESS) assertThat(result.output).contains("commitEdit(foobar") } @Test fun `Commit task is not run if build failed`() { val editFile = File(appDir, "build/gpp/com.example.publisher.txt") editFile.safeCreateNewFile().writeText("foobar") editFile.marked("commit").safeCreateNewFile() // language=gradle val config = """ afterEvaluate { tasks.named("promoteReleaseArtifact").configure { doFirst { throw new IllegalStateException("Dang :(") } } } """ val result = executeExpectingFailure(config, "promoteReleaseArtifact") result.requireTask(outcome = SKIPPED) assertThat(result.output).doesNotContain("commitEdit(") assertThat(editFile.exists()).isFalse() assertThat(editFile.marked("commit").exists()).isFalse() } companion object { @JvmStatic fun installFactories() { val publisher = object : FakePlayPublisher() { override fun commitEdit(id: String, sendChangesForReview: Boolean): CommitResponse { println("commitEdit($id, $sendChangesForReview)") return newSuccessCommitResponse() } override fun validateEdit(id: String) { println("validateEdit($id)") } } publisher.install() } } }
mit
d7a9a5ff16c390431035a1b73a2aedfd
37.378947
100
0.667581
5.022039
false
true
false
false