content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
/* * Copyright 2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package configurations import common.Os import common.applyPerformanceTestSettings import common.buildToolGradleParameters import common.checkCleanM2AndAndroidUserHome import common.gradleWrapper import common.individualPerformanceTestArtifactRules import common.skipConditionally import jetbrains.buildServer.configs.kotlin.v2019_2.BuildStep import jetbrains.buildServer.configs.kotlin.v2019_2.BuildSteps import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.script import model.CIBuildModel import model.Stage class TestPerformanceTest(model: CIBuildModel, stage: Stage) : BaseGradleBuildType(stage, init = { val os = Os.LINUX val testProject = "smallJavaMultiProject" fun BuildSteps.gradleStep(tasks: List<String>) { gradleWrapper { name = "GRADLE_RUNNER" gradleParams = ( tasks + buildToolGradleParameters(isContinue = false) ).joinToString(separator = " ") skipConditionally() } } fun BuildSteps.adHocPerformanceTest(tests: List<String>) { gradleStep( listOf( "clean", "performance:${testProject}PerformanceAdHocTest", tests.map { """--tests "$it"""" }.joinToString(" "), """--warmups 2 --runs 2 --checks none""", "-PtestJavaVersion=${os.perfTestJavaVersion.major}", "-PtestJavaVendor=${os.perfTestJavaVendor}", "-PautoDownloadAndroidStudio=true", "-PrunAndroidStudioInHeadlessMode=true", os.javaInstallationLocations() ) ) } id("${model.projectId}_TestPerformanceTest") name = "Test performance test tasks - Java8 Linux" description = "Tries to run an adhoc performance test without a database connection to verify this is still working" applyPerformanceTestSettings() artifactRules = individualPerformanceTestArtifactRules steps { script { name = "KILL_GRADLE_PROCESSES" executionMode = BuildStep.ExecutionMode.ALWAYS scriptContent = os.killAllGradleProcesses } adHocPerformanceTest( listOf( "org.gradle.performance.regression.java.JavaIDEModelPerformanceTest.get IDE model for IDEA", "org.gradle.performance.regression.java.JavaUpToDatePerformanceTest.up-to-date assemble (parallel true)", "org.gradle.performance.regression.corefeature.TaskAvoidancePerformanceTest.help with lazy and eager tasks" ) ) checkCleanM2AndAndroidUserHome(os) } applyDefaultDependencies(model, this, true) })
.teamcity/src/main/kotlin/configurations/TestPerformanceTest.kt
200681662
package com.kobe.livedata_mvvm_example.ui.main import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class MainViewModel : ViewModel() { private var number: Int = 1 private val _message = MutableLiveData<String>() //>> this is the public immutable LiveData //>> override the getter here val message: LiveData<String> get() = _message init { _message.value = "This is the ViewModel" } fun shuffleMessage() { _message.value = "Shuffle " + number++ } }
LiveData_MVVM_Example/app/src/main/java/com/kobe/livedata_mvvm_example/ui/main/MainViewModel.kt
37251791
/* * The MIT License (MIT) * * Copyright (c) 2016 QAware GmbH, Munich, Germany * * 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 de.qaware.oss.cloud.control.midi import javax.inject.Qualifier /** * The annotation class used as qualifier for button released device events. */ @Qualifier @Target(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FIELD) @Retention(AnnotationRetention.RUNTIME) annotation class Released
src/main/kotlin/de/qaware/oss/cloud/control/midi/Released.kt
2792075006
/* * Copyright 2013 Maurício Linhares * * Maurício Linhares licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.github.mauricio.async.db.postgresql.encoders import com.github.mauricio.async.db.postgresql.messages.frontend.ClientMessage import io.netty.buffer.ByteBuf interface Encoder { fun encode(message: ClientMessage): ByteBuf }
postgresql-async/src/main/kotlin/com/github/mauricio/async/db/postgresql/encoders/Encoder.kt
3780659959
package com.brentpanther.bitcoinwidget.ui.settings import androidx.annotation.StringRes import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.selection.toggleable import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.* import androidx.compose.material.ripple.LocalRippleTheme import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import com.brentpanther.bitcoinwidget.ui.theme.HighlightRippleTheme import java.lang.Integer.max import java.util.* @Composable fun Setting( modifier: Modifier = Modifier, icon: @Composable () -> Unit = {}, title: @Composable () -> Unit, subtitle: @Composable (() -> Unit)? = null, content: @Composable ((BoxScope).() -> Unit) = {} ) { CompositionLocalProvider(LocalRippleTheme provides HighlightRippleTheme()) { Row( modifier = modifier .fillMaxWidth() .padding(horizontal = 16.dp) .heightIn(min = 72.dp), verticalAlignment = Alignment.CenterVertically ) { Box( contentAlignment = Alignment.Center, modifier = Modifier .padding(end = 16.dp) .size(24.dp) ) { CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { icon() } } Column( verticalArrangement = Arrangement.Center, modifier = Modifier .weight(1f, true) .padding(start = 16.dp) ) { ProvideTextStyle(value = MaterialTheme.typography.subtitle1) { title() } if (subtitle != null) { CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { ProvideTextStyle(value = MaterialTheme.typography.body2) { subtitle() } } } } Box( modifier = Modifier .size(48.dp) .padding(16.dp), contentAlignment = Alignment.Center ) { content() } } } } @Composable fun SettingsHeader(@StringRes title: Int, modifier: Modifier = Modifier, withDivider: Boolean = true) { Surface { if (withDivider) { Divider() } Row( modifier .fillMaxWidth() .height(36.dp) .padding(top = 16.dp, start = 16.dp), verticalAlignment = Alignment.CenterVertically ) { CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { ProvideTextStyle(value = MaterialTheme.typography.subtitle2.copy(color = MaterialTheme.colors.secondary)) { Text(stringResource(id = title), Modifier.padding(start = 56.dp)) } } } } } @Composable fun SettingsSwitch( icon: @Composable () -> Unit = {}, title: @Composable () -> Unit, subtitle: (@Composable () -> Unit)? = null, value: Boolean = false, onChange: (Boolean) -> Unit ) { Setting( modifier = Modifier.toggleable( value = value, role = Role.Switch, onValueChange = onChange ), icon = icon, title = title, subtitle = subtitle ) { Switch( checked = value, onCheckedChange = null, colors = SwitchDefaults.colors( uncheckedThumbColor = Color(0xffdddddd) ) ) } } @Composable fun SettingsEditText( icon: @Composable () -> Unit = {}, title: @Composable () -> Unit, subtitle: (@Composable () -> Unit)? = null, dialogText: (@Composable () -> Unit)? = null, value: String? = null, onChange: (String) -> Unit ) { var dialogVisible by remember { mutableStateOf(false) } Setting( modifier = Modifier.clickable { dialogVisible = true }, icon = icon, title = title, subtitle = subtitle ) { var tempValue by remember { mutableStateOf(value) } if (dialogVisible) { Dialog( onDismissRequest = { dialogVisible = false } ) { Surface( shape = MaterialTheme.shapes.medium, modifier = Modifier.padding(vertical = 8.dp) ) { Column( Modifier.padding(start = 20.dp, top = 20.dp) ) { Row( Modifier.padding(bottom = 12.dp) ) { ProvideTextStyle(value = MaterialTheme.typography.h6) { title() } } Row( Modifier.padding(bottom = 8.dp) ) { dialogText?.invoke() } OutlinedTextField( value = tempValue ?: "", keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Decimal, imeAction = ImeAction.Done ), keyboardActions = KeyboardActions { onChange(tempValue ?: "1") dialogVisible = false }, singleLine = true, onValueChange = { tempValue = it } ) Row( Modifier .fillMaxWidth() .padding(8.dp), horizontalArrangement = Arrangement.End ) { TextButton( onClick = { onChange(tempValue ?: "1") dialogVisible = false } ) { Text( stringResource(android.R.string.ok).uppercase(Locale.getDefault()) ) } TextButton( onClick = { dialogVisible = false } ) { Text( stringResource(android.R.string.cancel).uppercase(Locale.getDefault()) ) } } } } } } } } @Composable fun SettingsList( icon: @Composable () -> Unit = {}, title: @Composable () -> Unit, subtitle: (@Composable (String?) -> Unit)? = null, items: List<String>, itemValues: List<String> = items, value: String? = null, onChange: (String) -> Unit ) { var dialogVisible by remember { mutableStateOf(false) } val currentIndex = itemValues.indexOf(value) SettingsButton( icon = icon, title = title, subtitle = { val subtitleValue = if (currentIndex > -1) items[currentIndex] else null subtitle?.invoke(subtitleValue) }, onClick = { dialogVisible = true } ) if (dialogVisible) { Dialog( onDismissRequest = { dialogVisible = false } ) { Surface( shape = MaterialTheme.shapes.medium, modifier = Modifier.padding(vertical = 8.dp) ) { Column { Row( Modifier.padding(start = 20.dp, top = 20.dp, bottom = 12.dp) ) { ProvideTextStyle(value = MaterialTheme.typography.h6) { title() } } val state = rememberLazyListState(max(0, currentIndex)) LazyColumn(state = state, modifier = Modifier.weight(1f, false)) { itemsIndexed(items) { index, item -> RadioDialogItem( item = item, selected = index == currentIndex, onClick = { onChange(itemValues[index]) dialogVisible = false } ) } } Row( Modifier .fillMaxWidth() .padding(8.dp), horizontalArrangement = Arrangement.End ) { TextButton( onClick = { dialogVisible = false } ) { Text( stringResource(android.R.string.cancel).uppercase(Locale.getDefault()) ) } } } } } } } @Composable fun SettingsButton( icon: @Composable () -> Unit = {}, title: @Composable () -> Unit, subtitle: (@Composable () -> Unit)? = null, onClick: () -> Unit ) { Setting( modifier = Modifier.clickable(onClick = onClick), icon = icon, title = title, subtitle = subtitle ) } @Composable fun SettingsSlider( icon: @Composable () -> Unit = {}, title: @Composable () -> Unit, subtitle: (@Composable () -> Unit)? = null, range: IntRange, value: Int, onChange: (Int) -> Unit ) { Column { Setting( icon = icon, title = title, subtitle = subtitle ) Slider( value.toFloat(), onValueChange = { onChange(it.toInt()) }, valueRange = range.first.toFloat()..range.last.toFloat(), modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) .padding(start = 48.dp), colors = SliderDefaults.colors( thumbColor = MaterialTheme.colors.secondaryVariant, activeTrackColor = MaterialTheme.colors.secondaryVariant ) ) } } @Composable private fun RadioDialogItem( item: String, selected: Boolean, onClick: () -> Unit ) { CompositionLocalProvider(LocalRippleTheme provides HighlightRippleTheme()) { Row( Modifier .fillMaxWidth() .height(48.dp) .selectable( selected = selected, onClick = onClick, role = Role.RadioButton ) .padding(horizontal = 20.dp), verticalAlignment = Alignment.CenterVertically ) { RadioButton( selected = selected, onClick = null ) Text( text = item, style = MaterialTheme.typography.body1, modifier = Modifier.padding(start = 16.dp) ) } } }
bitcoin/src/main/java/com/brentpanther/bitcoinwidget/ui/settings/SettingsComponents.kt
207271346
package com.tonyodev.fetch2 import com.tonyodev.fetch2core.DownloadBlock /** * Listener used by Fetch to report the different statuses and changes of the downloads * managed by Fetch * @see com.tonyodev.fetch2.Status * */ interface FetchListener { /** Called when a new download is added to Fetch. The status of the download will be * Status.ADDED. * @param download An immutable object which contains a current snapshot of all the information * about a specific download managed by Fetch. * */ fun onAdded(download: Download) /** Called when a new download is queued for download. The status of the download will be * Status.QUEUED. * @param download An immutable object which contains a current snapshot of all the information * about a specific download managed by Fetch. * @param waitingOnNetwork Indicates that the download was queued because it is waiting on * the right network condition. For example: Waiting on internet access to be restored or * waiting for a Wifi connection. * */ fun onQueued(download: Download, waitingOnNetwork: Boolean) /** Called when a download is queued and waiting for the right network conditions to start downloading. * The status of the download will be Status.QUEUED. Note this method is called several time on * a background thread. * @param download An immutable object which contains a current snapshot of all the information * about a specific download managed by Fetch. * */ fun onWaitingNetwork(download: Download) /** Called when a download completes. The status of the download will be Status.COMPLETED. * @param download An immutable object which contains a current snapshot of all the information * about a specific download managed by Fetch. * */ fun onCompleted(download: Download) /** Called when an error occurs when downloading a download. The status of the download will be * Status.FAILED. See the download error field on the download for more information * on the specific error that occurred. * @param download An immutable object which contains a current snapshot of all the information * about a specific download managed by Fetch. * @param error the error that occurred * @param throwable the throwable that caused the error to occur. Maybe null. * */ fun onError(download: Download, error: Error, throwable: Throwable?) /** Called several times to report the progress of a download block belonging to a download. * The status of the download will be Status.DOWNLOADING. A download may be downloaded using * several downloading blocks if using the Parallel File Downloader. The Sequential Downloader * only uses 1 downloading block. See Downloader class documentation for more information. * Note: This method is called on a background thread. * @param download An immutable object which contains a current snapshot of all the information * about a specific download managed by Fetch. * @param downloadBlock download's downloading block information. * @param totalBlocks total downloading blocks for a download. * */ fun onDownloadBlockUpdated(download: Download, downloadBlock: DownloadBlock, totalBlocks: Int) /** * Called to report that the download process has started for a request. The status of the download * will be Status.DOWNLOADING. * @param download An immutable object which contains a current snapshot of all the information * @param downloadBlocks list of download's downloading blocks information. * @param totalBlocks total downloading blocks for a download. * about a specific download managed by Fetch. * */ fun onStarted(download: Download, downloadBlocks: List<DownloadBlock>, totalBlocks: Int) /** Called several times to report the progress of a download when downloading. * The status of the download will be Status.DOWNLOADING. * @param download An immutable object which contains a current snapshot of all the information * about a specific download managed by Fetch. * @param etaInMilliSeconds Estimated time remaining in milliseconds for the download to complete. * @param downloadedBytesPerSecond Average downloaded bytes per second. * Can return -1 to indicate that the estimated time remaining is unknown. * */ fun onProgress(download: Download, etaInMilliSeconds: Long, downloadedBytesPerSecond: Long) /** Called when a download is paused. The status of the download will be Status.PAUSED. * @param download An immutable object which contains a current snapshot of all the information * about a specific download managed by Fetch. * */ fun onPaused(download: Download) /** Called when a download is un-paused and queued again for download. * The status of the download will be Status.QUEUED. * @param download An immutable object which contains a current snapshot of all the information * about a specific download managed by Fetch. * */ fun onResumed(download: Download) /** Called when a download is cancelled. The status of the download will be * Status.CANCELLED. The file for this download is not deleted. * @param download An immutable object which contains a current snapshot of all the information * about a specific download managed by Fetch. * */ fun onCancelled(download: Download) /** Called when a download is removed and is no longer managed by Fetch or * contained in the Fetch database. The file for this download is not deleted. * The status of a download will be Status.REMOVED. * @param download An immutable object which contains a current snapshot of all the information * about a specific download managed by Fetch. * */ fun onRemoved(download: Download) /** Called when a download is deleted and is no longer managed by Fetch or contained in * the fetch database. The downloaded file is deleted. The status of a download will be * Status.DELETED. * @param download An immutable object which contains a current snapshot of all the information * about a specific download managed by Fetch. * */ fun onDeleted(download: Download) }
fetch2/src/main/java/com/tonyodev/fetch2/FetchListener.kt
3378697449
package com.jayrave.falkon.sqlBuilders.h2 import com.jayrave.falkon.sqlBuilders.test.delete.TestDelete import org.junit.Test class H2DeleteSqlBuilderIntegrationTests : BaseClassForTesting() { private val deleteSqlBuilder = H2DeleteSqlBuilder() @Test fun `delete all records`() { TestDelete(deleteSqlBuilder, db).`delete all records`() } @Test fun `delete individual record using where#eq`() { TestDelete(deleteSqlBuilder, db).`delete individual record using where#eq`() } @Test fun `delete individual record using where#notEq`() { TestDelete(deleteSqlBuilder, db).`delete individual record using where#notEq`() } @Test fun `delete individual record using where#greaterThan`() { TestDelete(deleteSqlBuilder, db).`delete individual record using where#greaterThan`() } @Test fun `delete individual record using where#greaterThanOrEq`() { TestDelete(deleteSqlBuilder, db).`delete individual record using where#greaterThanOrEq`() } @Test fun `delete individual record using where#lessThan`() { TestDelete(deleteSqlBuilder, db).`delete individual record using where#lessThan`() } @Test fun `delete individual record using where#lessThanOrEq`() { TestDelete(deleteSqlBuilder, db).`delete individual record using where#lessThanOrEq`() } @Test fun `delete individual record using where#like`() { TestDelete(deleteSqlBuilder, db).`delete individual record using where#like`() } @Test fun `delete individual record using where#between`() { TestDelete(deleteSqlBuilder, db).`delete individual record using where#between`() } @Test fun `delete individual record using where#isIn with list`() { TestDelete(deleteSqlBuilder, db).`delete individual record using where#isIn with list`() } @Test fun `delete individual record using where#isIn with sub query`() { TestDelete(deleteSqlBuilder, db).`delete individual record using where#isIn with sub query`() } @Test fun `delete individual record using where#isNotIn with list`() { TestDelete(deleteSqlBuilder, db).`delete individual record using where#isNotIn with list`() } @Test fun `delete individual record using where#isNotIn with sub query`() { TestDelete(deleteSqlBuilder, db).`delete individual record using where#isNotIn with sub query`() } @Test fun `delete individual record using where#isNull`() { TestDelete(deleteSqlBuilder, db).`delete individual record using where#isNull`() } @Test fun `delete individual record using where#isNotNull`() { TestDelete(deleteSqlBuilder, db).`delete individual record using where#isNotNull`() } @Test fun `delete individual record using simple where#and`() { TestDelete(deleteSqlBuilder, db).`delete individual record using simple where#and`() } @Test fun `delete individual record using simple where#or`() { TestDelete(deleteSqlBuilder, db).`delete individual record using simple where#or`() } @Test fun `delete individual record using compound where#and`() { TestDelete(deleteSqlBuilder, db).`delete individual record using compound where#and`() } @Test fun `delete individual record using compound where#or`() { TestDelete(deleteSqlBuilder, db).`delete individual record using compound where#or`() } }
falkon-sql-builder-h2/src/test/kotlin/com/jayrave/falkon/sqlBuilders/h2/H2DeleteSqlBuilderIntegrationTests.kt
4193203502
package com.khmelenko.lab.varis.util import java.util.Random /** * Provides utils methods for the work with Strings * * @author Dmytro Khmelenko */ object StringUtils { /** * Gets random string * * @return Random string */ @JvmStatic fun getRandomString(): String { val length = 10 return getRandomString(length) } /** * Gets random string * * @param length String length * @return Random string */ @JvmStatic fun getRandomString(length: Int): String { val chars = "ABCDEFGHIJKLMONPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray() val builder = StringBuilder() val random = Random() for (i in 0 until length) { val c = chars[random.nextInt(chars.size)] builder.append(c) } return builder.toString() } /** * Checks whether the string is null or not * * @param string String for checking * @return True if string is empty. False otherwise */ @JvmStatic fun isEmpty(string: String?): Boolean { return string == null || string.isEmpty() } }
app-v3/src/main/java/com/khmelenko/lab/varis/util/StringUtils.kt
2273939854
package com.github.davinkevin.podcastserver.find.finders import com.github.davinkevin.podcastserver.find.FindCoverInformation import reactor.kotlin.core.publisher.switchIfEmpty import reactor.kotlin.core.publisher.toMono import java.net.URI import java.util.* import com.github.davinkevin.podcastserver.service.image.ImageService internal fun ImageService.fetchCoverInformationOrOption(url: URI) = this.fetchCoverInformation(url) .map { FindCoverInformation(it.height, it.width, it.url) } .map { Optional.of<FindCoverInformation?>(it) } .switchIfEmpty { Optional.empty<FindCoverInformation>().toMono() }
backend/src/main/kotlin/com/github/davinkevin/podcastserver/find/finders/FindersExtension.kt
1760467993
/* * Copyright 2017 Netflix, 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.netflix.spinnaker.config import com.fasterxml.jackson.databind.ObjectMapper import com.netflix.spectator.api.Registry import com.netflix.spinnaker.kork.jedis.JedisDriverProperties import com.netflix.spinnaker.kork.jedis.JedisPoolFactory import com.netflix.spinnaker.orca.q.QueueShovel import com.netflix.spinnaker.q.Activator import com.netflix.spinnaker.q.DeadMessageCallback import com.netflix.spinnaker.q.metrics.EventPublisher import com.netflix.spinnaker.q.migration.SerializationMigrator import com.netflix.spinnaker.q.redis.AbstractRedisQueue import com.netflix.spinnaker.q.redis.RedisClusterQueue import com.netflix.spinnaker.q.redis.RedisQueue import org.apache.commons.pool2.impl.GenericObjectPoolConfig import org.springframework.beans.factory.BeanInitializationException import org.springframework.beans.factory.annotation.Qualifier import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.condition.ConditionalOnBean import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import redis.clients.jedis.HostAndPort import redis.clients.jedis.Jedis import redis.clients.jedis.JedisCluster import redis.clients.jedis.Protocol import redis.clients.jedis.util.Pool import java.net.URI import java.time.Clock import java.time.Duration import java.util.Optional @Configuration @ConditionalOnProperty(value = ["queue.redis.enabled"], matchIfMissing = true) class RedisQueueShovelConfiguration { @Bean @ConditionalOnProperty("redis.connection-previous") @ConditionalOnExpression("\${redis.previous-cluster-enabled:false} == false") fun previousQueueJedisPool( @Value("\${redis.connection:redis://localhost:6379}") mainConnection: String, @Value("\${redis.connection-previous:#{null}}") previousConnection: String?, @Value("\${redis.timeout:2000}") timeout: Int, redisPoolConfig: GenericObjectPoolConfig<*>, registry: Registry ): Pool<Jedis> { if (mainConnection == previousConnection) { throw BeanInitializationException("previous Redis connection must not be the same as current connection") } return JedisPoolFactory(registry).build( "previousQueue", JedisDriverProperties().apply { connection = previousConnection timeoutMs = timeout poolConfig = redisPoolConfig }, redisPoolConfig ) } @Bean @ConditionalOnProperty("redis.connection-previous") @ConditionalOnExpression("\${redis.previous-cluster-enabled:false} == true") fun previousJedisCluster( @Value("\${redis.connection:redis://localhost:6379}") mainConnection: String, @Value("\${redis.connection-previous}") previousConnection: String, @Value("\${redis.timeout:2000}") timeout: Int, @Value("\${redis.maxattempts:4}") maxAttempts: Int, redisPoolConfig: GenericObjectPoolConfig<*>, registry: Registry ): JedisCluster { if (mainConnection == previousConnection) { throw BeanInitializationException("previous Redis connection must not be the same as current connection") } URI.create(previousConnection).let { cx -> val port = if (cx.port == -1) Protocol.DEFAULT_PORT else cx.port val password = cx.userInfo?.substringAfter(":") return JedisCluster( HostAndPort(cx.host, port), timeout, timeout, maxAttempts, password, redisPoolConfig ) } } @Bean(name = ["previousQueue"]) @ConditionalOnBean(name = ["previousQueueJedisPool"]) fun previousRedisQueue( @Qualifier("previousQueueJedisPool") redisPool: Pool<Jedis>, redisQueueProperties: RedisQueueProperties, clock: Clock, deadMessageHandler: DeadMessageCallback, publisher: EventPublisher, redisQueueObjectMapper: ObjectMapper, serializationMigrator: Optional<SerializationMigrator> ) = RedisQueue( queueName = redisQueueProperties.queueName, pool = redisPool, clock = clock, deadMessageHandlers = listOf(deadMessageHandler), publisher = publisher, ackTimeout = Duration.ofSeconds(redisQueueProperties.ackTimeoutSeconds.toLong()), mapper = redisQueueObjectMapper, serializationMigrator = serializationMigrator ) @Bean(name = ["previousClusterQueue"]) @ConditionalOnBean(name = ["previousJedisCluster"]) fun previousRedisClusterQueue( @Qualifier("previousJedisCluster") cluster: JedisCluster, redisQueueProperties: RedisQueueProperties, clock: Clock, deadMessageHandler: DeadMessageCallback, publisher: EventPublisher, redisQueueObjectMapper: ObjectMapper, serializationMigrator: Optional<SerializationMigrator> ) = RedisClusterQueue( queueName = redisQueueProperties.queueName, jedisCluster = cluster, clock = clock, mapper = redisQueueObjectMapper, deadMessageHandlers = listOf(deadMessageHandler), publisher = publisher, ackTimeout = Duration.ofSeconds(redisQueueProperties.ackTimeoutSeconds.toLong()), serializationMigrator = serializationMigrator ) @Bean @ConditionalOnBean(name = ["previousQueueJedisPool"]) fun redisQueueShovel( queue: AbstractRedisQueue, @Qualifier("previousQueue") previousQueueImpl: RedisQueue, registry: Registry, discoveryActivator: Activator ) = QueueShovel( queue = queue, previousQueue = previousQueueImpl, registry = registry, activator = discoveryActivator ) @Bean @ConditionalOnBean(name = ["previousClusterQueue"]) fun priorRedisClusterQueueShovel( queue: AbstractRedisQueue, @Qualifier("previousClusterQueue") previousQueueImpl: AbstractRedisQueue, registry: Registry, discoveryActivator: Activator ) = QueueShovel( queue = queue, previousQueue = previousQueueImpl, registry = registry, activator = discoveryActivator ) }
orca-queue-redis/src/main/kotlin/com/netflix/spinnaker/config/RedisQueueShovelConfiguration.kt
3613941280
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ @file:Suppress("JAVA_MODULE_DOES_NOT_DEPEND_ON_MODULE") package com.almasb.fxgl.physics.box2d.dynamics.joints import com.almasb.fxgl.core.math.Vec2 import com.almasb.fxgl.physics.box2d.dynamics.SolverData import com.almasb.fxgl.physics.box2d.dynamics.World import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test /** * * @author Almas Baimagambetov ([email protected]) */ class RevoluteJointTest { @Test fun `Solve position constraints`() { val def = RevoluteJointDef() val world = World(Vec2()) // TODO: val joint = RevoluteJoint(world.pool, def) // TODO: val data = SolverData() //joint.solvePositionConstraints(data) } }
fxgl-entity/src/test/kotlin/com/almasb/fxgl/physics/box2d/dynamics/joints/RevoluteJointTest.kt
1645116012
package br.com.wakim.eslpodclient.ui.podcastlist.view import android.os.Bundle import android.support.design.widget.AppBarLayout import android.support.design.widget.CoordinatorLayout import android.support.design.widget.FloatingActionButton import android.support.design.widget.Snackbar import android.support.v4.app.Fragment import android.view.Menu import android.view.MenuItem import br.com.wakim.eslpodclient.R import br.com.wakim.eslpodclient.android.widget.LoadingFloatingActionButton import br.com.wakim.eslpodclient.dagger.PodcastPlayerComponent import br.com.wakim.eslpodclient.dagger.module.PodcastPlayerModule import br.com.wakim.eslpodclient.ui.podcastlist.downloaded.view.DownloadedListFragment import br.com.wakim.eslpodclient.ui.podcastlist.favorited.view.FavoritedListFragment import br.com.wakim.eslpodclient.ui.podcastplayer.view.ListPlayerView import br.com.wakim.eslpodclient.ui.settings.view.SettingsActivity import br.com.wakim.eslpodclient.ui.view.BaseActivity import br.com.wakim.eslpodclient.util.extensions.snack import br.com.wakim.eslpodclient.util.extensions.startActivity import butterknife.BindView import it.sephiroth.android.library.bottomnavigation.BottomBehavior import it.sephiroth.android.library.bottomnavigation.BottomNavigation open class PodcastListActivity : BaseActivity() { companion object { const val MINIMUM_THRESHOLD = 5 const val FRAGMENT_TAG = "FRAGMENT" } private var podcastPlayerComponent: PodcastPlayerComponent? = null @BindView(R.id.coordinator_layout) lateinit var coordinatorLayout: CoordinatorLayout @BindView(R.id.appbar) lateinit var appBarLayout: AppBarLayout @BindView(R.id.player_view) lateinit var playerView: ListPlayerView @BindView(R.id.fab_play) lateinit var playFab: FloatingActionButton @BindView(R.id.fab_pause) lateinit var pauseFab: FloatingActionButton @BindView(R.id.fab_loading) lateinit var loadingFab: LoadingFloatingActionButton @BindView(R.id.bottom_navigation) lateinit var bottomBar: BottomNavigation var podcastListFragment: PodcastListFragment? = null var downloadedListFragment: DownloadedListFragment? = null var favoritedListFragment: FavoritedListFragment? = null var currentFragment: PodcastListFragment? = null var savedState = arrayOfNulls<Fragment.SavedState>(3) var lastSelectedPosition = 0 var lastOffset: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { setTheme(R.style.AppTheme) createActivityComponent() super.onCreate(savedInstanceState) setContentView(R.layout.activity_podcastlist) createPlayerComponent() restoreFragmentStates(savedInstanceState) configureAppBarLayout() configureBottomBar() addFragmentIfNeeded() playerView.setControls(playFab, pauseFab, loadingFab) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) val fragmentManager = supportFragmentManager podcastListFragment?.let { if (it.isAdded) { fragmentManager.putFragment(outState, "PODCAST_LIST", it) } } favoritedListFragment?.let { if (it.isAdded) { fragmentManager.putFragment(outState, "FAVORITED_LIST", it) } } downloadedListFragment?.let { if (it.isAdded) { fragmentManager.putFragment(outState, "DOWNLOADED_LIST", it) } } } fun configureAppBarLayout() { appBarLayout.addOnOffsetChangedListener { appBarLayout, offset -> currentFragment?.let { if (offset == 0) { it.setSwipeRefreshEnabled(true) } else if (lastOffset == 0 && it.isSwipeRefreshEnabled()) { it.setSwipeRefreshEnabled(false) } } lastOffset = offset } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.podcast_list_menu, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item?.itemId == R.id.menu_settings) { startActivity<SettingsActivity>() return true } return super.onOptionsItemSelected(item) } fun restoreFragmentStates(savedInstanceState: Bundle?) { savedInstanceState?.let { val fragmentManager = supportFragmentManager podcastListFragment = fragmentManager.getFragment(it, "PODCAST_LIST") as? PodcastListFragment favoritedListFragment = fragmentManager.getFragment(it, "FAVORITED_LIST") as? FavoritedListFragment downloadedListFragment = fragmentManager.getFragment(it, "DOWNLOADED_LIST") as? DownloadedListFragment } } fun configureBottomBar() { bottomBar.setOnMenuItemClickListener(object: BottomNavigation.OnMenuItemSelectionListener { override fun onMenuItemSelect(id: Int, position: Int) { when (position) { 0 -> replaceListFragment(PodcastListFragment(), lastSelectedPosition, position) 1 -> replaceFavoritedFragment(FavoritedListFragment(), lastSelectedPosition, position) 2 -> replaceDownloadedFragment(DownloadedListFragment(), lastSelectedPosition, position) } lastSelectedPosition = position } override fun onMenuItemReselect(p0: Int, p1: Int) { } }) } fun addFragmentIfNeeded() { currentFragment = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG) as PodcastListFragment? if (currentFragment == null) { podcastListFragment = PodcastListFragment() currentFragment = podcastListFragment supportFragmentManager .beginTransaction() .add(R.id.container, podcastListFragment, FRAGMENT_TAG) .commit() } } fun replaceListFragment(fragment: PodcastListFragment, previousPosition: Int, position: Int) { podcastListFragment = fragment replaceFragment(fragment, previousPosition, position) } fun replaceFavoritedFragment(fragment: FavoritedListFragment, previousPosition: Int, position: Int) { favoritedListFragment = favoritedListFragment replaceFragment(fragment, previousPosition, position) } fun replaceDownloadedFragment(fragment: DownloadedListFragment, previousPosition: Int, position: Int) { downloadedListFragment = fragment replaceFragment(fragment, previousPosition, position) } fun replaceFragment(fragment: PodcastListFragment, previousPosition: Int, position: Int) { val fragmentManager = supportFragmentManager val previousFragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG) val state = savedState[position] savedState[previousPosition] = fragmentManager.saveFragmentInstanceState(previousFragment) state?.let { fragment.setInitialSavedState(state) } currentFragment = fragment fragmentManager .beginTransaction() .replace(R.id.container, fragment, FRAGMENT_TAG) .commit() } override fun getSystemService(name: String?): Any? { if (name == PodcastPlayerComponent::class.java.simpleName) { return podcastPlayerComponent } return super.getSystemService(name) } fun createPlayerComponent() { podcastPlayerComponent = activityComponent + PodcastPlayerModule(playerView) } override fun onBackPressed() { with (playerView) { if (isExpanded()) { collapse() return } if (isVisible()) { hide() return } } disposePlayerIfNeeded() super.onBackPressed() } override fun finish() { disposePlayerIfNeeded() super.finish() } open fun disposePlayerIfNeeded() { if (!playerView.isPlaying()) { playerView.explicitlyStop() } } override fun showMessage(messageResId: Int): Snackbar = snack(coordinatorLayout, messageResId) }
app/src/main/java/br/com/wakim/eslpodclient/ui/podcastlist/view/PodcastListActivity.kt
1352928086
package me.camdenorrb.opencast.commands.sub import me.camdenorrb.opencast.OpenCast import me.camdenorrb.opencast.commands.SubCmd import me.camdenorrb.opencast.extensions.format import org.bukkit.ChatColor.* import org.bukkit.command.CommandSender /** * Created by camdenorrb on 12/27/16. */ class AddCmd(val openCast: OpenCast) : SubCmd("add", 1, "$RED/Bc Add <Message>") { override fun execute(sender: CommandSender, args: MutableList<String>): Boolean { val message = args.joinToString(" ") openCast.castHandler.messages.messageList.add(message) sender.sendMessage("$AQUA\"$LIGHT_PURPLE${message.format()}$AQUA\" was added to the list!") return true } }
src/me/camdenorrb/opencast/commands/sub/AddCmd.kt
2435477541
package com.fsck.k9.mail import com.google.common.truth.Truth.assertThat import java.util.Random import org.junit.Test import org.mockito.kotlin.mock class BoundaryGeneratorTest { @Test fun `generateBoundary() with all zeros`() { val random = createRandom(0) val boundaryGenerator = BoundaryGenerator(random) val result = boundaryGenerator.generateBoundary() assertThat(result).isEqualTo("----000000000000000000000000000000") } @Test fun generateBoundary() { val random = createRandom( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 35 ) val boundaryGenerator = BoundaryGenerator(random) val result = boundaryGenerator.generateBoundary() assertThat(result).isEqualTo("----0123456789ABCDEFGHIJKLMNOPQRSZ") } private fun createRandom(vararg values: Int): Random { return mock { var ongoingStubbing = on { nextInt(36) } for (value in values) { ongoingStubbing = ongoingStubbing.thenReturn(value) } } } }
mail/common/src/test/java/com/fsck/k9/mail/BoundaryGeneratorTest.kt
2317068103
package com.hotpodata.twistris.data import android.graphics.Color import android.os.Bundle import android.text.TextUtils import com.hotpodata.blocklib.Grid import com.hotpodata.blocklib.GridHelper import com.hotpodata.twistris.utils.TetrisFactory import org.json.JSONArray import org.json.JSONObject import timber.log.Timber import java.util.* /** * Created by jdrotos on 1/3/16. */ class TwistrisGame() { val VERT_W = 8 val VERT_H = 16 val HORI_W = 12 val HORI_H = 8 val MAX_LEVEL = 10 val LEVEL_STEP = 6 var currentRowsDestroyed = 0 var currentScore = 0 var currentLevel = 1 var twistCount = 0 var gameIsOver = false var boardVert: Grid var boardHoriz: Grid var activePiece: Grid get() = horizPieces[horizPieces.size - 1].first set(piece: Grid) { horizPieces[horizPieces.size - 1] = Pair(piece, horizPieces[horizPieces.size - 1].second) } var activeXOffset: Int get() = horizPieces[horizPieces.size - 1].second.first set(offset: Int) { horizPieces[horizPieces.size - 1] = Pair(horizPieces[horizPieces.size - 1].first, Pair(offset, horizPieces[horizPieces.size - 1].second.second)) } var activeYOffset: Int get() = horizPieces[horizPieces.size - 1].second.second set(offset: Int) { horizPieces[horizPieces.size - 1] = Pair(horizPieces[horizPieces.size - 1].first, Pair(horizPieces[horizPieces.size - 1].second.first, offset)) } var upcomingPiece: Grid = TetrisFactory.randomPiece() var horizPieces = ArrayList<Pair<Grid, Pair<Int, Int>>>() init { boardVert = Grid(VERT_W, VERT_H) boardHoriz = Grid(HORI_W, HORI_H) actionNextPiece() } constructor(source: TwistrisGame) : this() { currentRowsDestroyed = source.currentRowsDestroyed currentScore = source.currentScore currentLevel = source.currentLevel boardVert = GridHelper.copyGrid(source.boardVert) boardHoriz = GridHelper.copyGrid(source.boardHoriz) upcomingPiece = GridHelper.copyGrid(source.upcomingPiece) horizPieces.clear() for (item in source.horizPieces) { horizPieces.add(Pair(GridHelper.copyGrid(item.first), Pair(item.second.first, item.second.second))) } } fun peekMoveActiveUp(): Boolean { return GridHelper.gridInBounds(boardHoriz, activePiece, activeXOffset, activeYOffset - 1) && !GridHelper.gridsCollide(boardHoriz, activePiece, activeXOffset, activeYOffset - 1) } fun actionMoveActiveUp(): Boolean { if (peekMoveActiveUp()) { activeYOffset-- return true } return false } fun peekMoveActiveDown(): Boolean { return GridHelper.gridInBounds(boardHoriz, activePiece, activeXOffset, activeYOffset + 1) && !GridHelper.gridsCollide(boardHoriz, activePiece, activeXOffset, activeYOffset + 1) } fun actionMoveActiveDown(): Boolean { if (peekMoveActiveDown()) { activeYOffset++ return true } return false } fun peekMoveActiveLeft(): Boolean { return GridHelper.gridInBounds(boardHoriz, activePiece, activeXOffset - 1, activeYOffset) && !GridHelper.gridsCollide(boardHoriz, activePiece, activeXOffset - 1, activeYOffset); } fun actionMoveActiveLeft(): Boolean { if (peekMoveActiveLeft()) { activeXOffset-- return true } return false } fun actionMoveActiveAllTheWayLeft(): Boolean { var ret = false while (actionMoveActiveLeft()) { currentScore += 10 ret = true } return ret } fun actionRotate(left: Boolean): Boolean { var rot = activePiece.rotate(left) var xOff = activeXOffset var yOff = activeYOffset //Now we make sure the coordinates are ok with the board (since rotations next to the edge are ok) while (xOff + rot.width > boardHoriz.width) { xOff-- } while (yOff + rot.height > boardHoriz.height) { yOff-- } //If we've got no collisions we're in great shape if (!GridHelper.gridsCollide(boardHoriz, rot, xOff, yOff)) { activeXOffset = xOff activeYOffset = yOff activePiece = rot return true } else { return false } } fun actionRotateActiveLeft(): Boolean { return actionRotate(true) } fun actionRotateActiveRight(): Boolean { return actionRotate(false) } fun actionTwistBoard() { //The working board is twice as tall as the display board, so pieces can be added over the bounds var workingBoard = Grid(boardVert.width, boardVert.height * 2) GridHelper.addGrid(workingBoard, GridHelper.copyGrid(boardVert), 0, boardVert.height); Timber.d("1 workingBoard:" + workingBoard.getPrintString(" - ", " * ")) //Move all of the pieces down for (pieceAndCoords in horizPieces.reversed()) { var coords = pieceAndCoords.second if (coords != null) { var rotated = pieceAndCoords.first.rotate(false) var startX = boardHoriz.height - coords.second - rotated.width var endY = 0 while (GridHelper.gridInBounds(workingBoard, rotated, startX, endY + 1) && !GridHelper.gridsCollide(workingBoard, rotated, startX, endY + 1)) { endY++ } GridHelper.addGrid(workingBoard, rotated, startX, endY) } } //Figure out the shift values var shifts = ArrayList<Int>() var shiftVal = 0 for (i in workingBoard.height - 1 downTo 0) { if (workingBoard.rowFull(i)) { shifts.add(0, -1) shiftVal++ } else { shifts.add(0, shiftVal) } } //Shift working board for realz if (shiftVal > 0) { for (i in shifts.size - 1 downTo 0) { if (shifts[i] > 0) { for (j in 0..workingBoard.width - 1) { workingBoard.put(j, i + shifts[i], workingBoard.at(j, i)) } } } } horizPieces.clear() boardHoriz.clear() currentScore += (50 * shiftVal * shiftVal) currentRowsDestroyed += shiftVal currentLevel = currentRowsDestroyed / LEVEL_STEP + 1 gameIsOver = !workingBoard.rowEmpty(boardVert.height - 1) twistCount++ boardVert = GridHelper.copyGridPortion(workingBoard, 0, boardVert.height, boardVert.width, workingBoard.height) } private fun randomWidePiece(): Grid { var newPiece = TetrisFactory.randomPiece() if (newPiece.height > newPiece.width) { newPiece = newPiece.rotate(false) } return newPiece } fun actionNextPiece() { //Commit the active piece to the board if (horizPieces.size > 0) { GridHelper.addGrid(boardHoriz, activePiece, activeXOffset, activeYOffset) } if (upcomingPiece == null) { upcomingPiece = randomWidePiece() } var piece = upcomingPiece var x = boardHoriz.width - piece.width var y = (boardHoriz.height / 2f - piece.height / 2f).toInt() horizPieces.add(Pair(piece, Pair(x, y))) upcomingPiece = randomWidePiece() } fun gameNeedsTwist(): Boolean { return !peekMoveActiveLeft() && horizPieces.size >= currentLevel } fun gameNeedsNextPiece(): Boolean { return horizPieces.size == 0 || !peekMoveActiveLeft() } /** * SERIALIZER */ object Serializer { val JSON_KEY_ROWS_DESTROYED = "rowsDestroyed" val JSON_KEY_SCORE = "score" val JSON_KEY_LEVEL = "level" val JSON_KEY_TWISTS = "twists" val JSON_KEY_GAMEOVER = "gameover" val JSON_KEY_VERTBOARD = "vertBoard" val JSON_KEY_HORIZBOARD = "horizBoard" val JSON_KEY_XOFF = "xOffset" val JSON_KEY_YOFF = "yOffset" val JSON_KEY_UPCOMING = "upcoming" val JSON_KEY_HORIZ_PIECES = "horizPieces" val JSON_KEY_HORIZ_PIECE_GRID = "horizPieceGrid" val JSON_KEY_HORIZ_PIECE_X = "horizPieceX" val JSON_KEY_HORIZ_PIECE_Y = "horizPieceY" fun gameToJson(game: TwistrisGame): JSONObject { var chainjson = JSONObject() chainjson.put(JSON_KEY_ROWS_DESTROYED, game.currentRowsDestroyed) chainjson.put(JSON_KEY_SCORE, game.currentScore) chainjson.put(JSON_KEY_LEVEL, game.currentLevel) chainjson.put(JSON_KEY_TWISTS, game.twistCount) chainjson.put(JSON_KEY_GAMEOVER, game.gameIsOver) chainjson.put(JSON_KEY_VERTBOARD, gridToJson(game.boardVert)) chainjson.put(JSON_KEY_HORIZBOARD, gridToJson(game.boardHoriz)) chainjson.put(JSON_KEY_XOFF, game.activeXOffset) chainjson.put(JSON_KEY_YOFF, game.activeYOffset) chainjson.put(JSON_KEY_UPCOMING, gridToJson(game.upcomingPiece)) var jsonArrHoriz = JSONArray() for (p in game.horizPieces) { var horiP = JSONObject() horiP.put(JSON_KEY_HORIZ_PIECE_GRID, gridToJson(p.first)) horiP.put(JSON_KEY_HORIZ_PIECE_X, p.second.first) horiP.put(JSON_KEY_HORIZ_PIECE_Y, p.second.second) jsonArrHoriz.put(horiP) } chainjson.put(JSON_KEY_HORIZ_PIECES, jsonArrHoriz) return chainjson } fun gameFromJson(gameJsonStr: String): TwistrisGame? { try { if (!TextUtils.isEmpty(gameJsonStr)) { var game = TwistrisGame() var gamejson = JSONObject(gameJsonStr) game.currentRowsDestroyed =gamejson.getInt(JSON_KEY_ROWS_DESTROYED) game.currentScore = gamejson.getInt(JSON_KEY_SCORE) game.currentLevel = gamejson.getInt(JSON_KEY_LEVEL) game.twistCount = gamejson.getInt(JSON_KEY_TWISTS) game.gameIsOver = gamejson.getBoolean(JSON_KEY_GAMEOVER) game.boardVert = gridFromJson(gamejson.getJSONObject(JSON_KEY_VERTBOARD)) game.boardHoriz = gridFromJson(gamejson.getJSONObject(JSON_KEY_HORIZBOARD)) game.activeXOffset = gamejson.getInt(JSON_KEY_XOFF) game.activeYOffset = gamejson.getInt(JSON_KEY_YOFF) game.upcomingPiece = gridFromJson(gamejson.getJSONObject(JSON_KEY_UPCOMING)) game.horizPieces.clear() var horizPiecesJsonArr = gamejson.getJSONArray(JSON_KEY_HORIZ_PIECES) for(i in 0..(horizPiecesJsonArr.length() - 1)){ var obj = horizPiecesJsonArr.getJSONObject(i) var grid = gridFromJson(obj.getJSONObject(JSON_KEY_HORIZ_PIECE_GRID)) var x = obj.getInt(JSON_KEY_HORIZ_PIECE_X) var y = obj.getInt(JSON_KEY_HORIZ_PIECE_Y) game.horizPieces.add(Pair(grid,Pair(x,y))) } return game } } catch(ex: Exception) { Timber.e(ex, "gameFromJson Fail") } return null } val JSONKEY_WIDTH = "WIDTH" val JSONKEY_HEIGHT = "HEIGHT" val JSONKEY_VALUES = "VALS" val JSON_EMPTY_COLOR = Color.TRANSPARENT fun gridToJson(grid: Grid): JSONObject { var json = JSONObject() json.put(JSONKEY_WIDTH, grid.width) json.put(JSONKEY_HEIGHT, grid.height) var vals = JSONArray() for (i in 0..grid.width - 1) { for (j in 0..grid.height - 1) { vals.put((grid.at(i, j) as Int?) ?: JSON_EMPTY_COLOR) } } json.put(JSONKEY_VALUES, vals) return json } fun gridFromJson(json: JSONObject): Grid { val w = json.getInt(JSONKEY_WIDTH) val h = json.getInt(JSONKEY_HEIGHT) var vals = json.getJSONArray(JSONKEY_VALUES) var grid = Grid(w, h) var valsInd = 0 for (i in 0..grid.width - 1) { for (j in 0..grid.height - 1) { grid.slots[i][j] = if (vals[valsInd] == JSON_EMPTY_COLOR) null else vals[valsInd] valsInd++ } } return grid } val BUNDLE_KEY_GAME = "BUNDLE_KEY_GAME" fun gameToBundle(game: TwistrisGame, bundle: Bundle = Bundle()): Bundle { bundle.putString(BUNDLE_KEY_GAME, TwistrisGame.Serializer.gameToJson(game).toString()) return bundle } fun gameFromBundle(bundle: Bundle?): TwistrisGame? { return bundle?.getString(BUNDLE_KEY_GAME)?.let { TwistrisGame.Serializer.gameFromJson(it) } } } }
app/src/main/java/com/hotpodata/twistris/data/TwistrisGame.kt
459921118
package com.github.kittinunf.reactiveandroid.widget import android.widget.SeekBar import com.github.kittinunf.reactiveandroid.ExtensionFieldDelegate import com.github.kittinunf.reactiveandroid.subscription.AndroidMainThreadSubscription import io.reactivex.Observable //================================================================================ // Events //================================================================================ data class SeekBarProgressChangeListener(val seekBar: SeekBar?, val progress: Int, val fromUser: Boolean) fun SeekBar.rx_progressChanged(): Observable<SeekBarProgressChangeListener> { return Observable.create { subscriber -> _seekBarChange.onProgressChanged { seekBar, progress, fromUser -> subscriber.onNext(SeekBarProgressChangeListener(seekBar, progress, fromUser)) } subscriber.setDisposable(AndroidMainThreadSubscription { setOnSeekBarChangeListener(null) }) } } fun SeekBar.rx_startTrackingTouch(): Observable<SeekBar> { return Observable.create { subscriber -> _seekBarChange.onStartTrackingTouch { if (it != null) subscriber.onNext(it) } subscriber.setDisposable(AndroidMainThreadSubscription { setOnSeekBarChangeListener(null) }) } } fun SeekBar.rx_stopTrackingTouch(): Observable<SeekBar> { return Observable.create { subscriber -> _seekBarChange.onStopTrackingTouch { if (it != null) subscriber.onNext(it) } subscriber.setDisposable(AndroidMainThreadSubscription { setOnSeekBarChangeListener(null) }) } } private val SeekBar._seekBarChange: _SeekBar_OnSeekBarChangeListener by ExtensionFieldDelegate({ _SeekBar_OnSeekBarChangeListener() }, { setOnSeekBarChangeListener(it) }) internal class _SeekBar_OnSeekBarChangeListener : SeekBar.OnSeekBarChangeListener { var onProgressChanged: ((SeekBar?, Int, Boolean) -> Unit)? = null var onStartTrackingTouch: ((SeekBar?) -> Unit)? = null var onStopTrackingTouch: ((SeekBar?) -> Unit)? = null fun onProgressChanged(listener: (SeekBar?, Int, Boolean) -> Unit) { onProgressChanged = listener } override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { onProgressChanged?.invoke(seekBar, progress, fromUser) } fun onStartTrackingTouch(listener: (SeekBar?) -> Unit) { onStartTrackingTouch = listener } override fun onStartTrackingTouch(seekBar: SeekBar?) { onStartTrackingTouch?.invoke(seekBar) } fun onStopTrackingTouch(listener: (SeekBar?) -> Unit) { onStopTrackingTouch = listener } override fun onStopTrackingTouch(seekBar: SeekBar?) { onStopTrackingTouch?.invoke(seekBar) } }
reactiveandroid-ui/src/main/kotlin/com/github/kittinunf/reactiveandroid/widget/SeekBarEvent.kt
2887613859
package com.zj.example.kotlin.shengshiyuan.helloworld /** * * CreateTime: 18/3/5 13:56 * @author 郑炯 */ /** * 对象表达式: (object expression) * Java当中匿名内部类在很多场景下都得到了大量使用 * Kotlin的对象表达式就是为了解决匿名内部类的一些缺陷而产生的. */ /** * 1.匿名内部类是没有名字的类 * 2.匿名内部类一定是继承了某个父类,或是实现了某个接口(java), kotlin可以不实现接口或继承父类 * 3.Java运行时会将该匿名内部类当做它所实现的接口或是所继承的父类来看待. */ /* 对象表达式的格式: object [:若干个父类型,中间用逗号分隔]{ } 中括号中的可以省略, 省略后就是没有继承任何类和任何接口的一个内部类 */ interface MyInterface { fun println(i: Int) } abstract class MyAbstractClass { abstract val age: Int abstract fun printMyAbstractClassInfo() } fun main(args: Array<String>) { /** * 对象表达式最终返回的其实是一个匿名内部类 */ var myObject = object : MyInterface { override fun println(i: Int) { println("i的值是$i") } //可以定义其他方法 fun test() { println("test") } } myObject.println(100) myObject.test() println("-------------------") /** * 没有实现接口的对象表达式, 相当于是一个没有继承任何子类和实现任何接口的匿名内部类 */ var myObject2 = object { init { println("init") } var myProperty = "p1" fun myMethod() = "myMethod()" } println(myObject2.myProperty) println(myObject2.myMethod()) println("-------------------") /** * 和java不同的是: * java的匿名内部类只能实现一个接口或者继承一个类, * kotlin中的对象表达式就可以实现多个接口或者1个父类+多个接口. */ var myObject3 = object : MyInterface, MyAbstractClass() { override fun println(i: Int) { println("i的值是$i") } override val age: Int get() = 30 override fun printMyAbstractClassInfo() { println("myAbstractClassInfo") } } myObject3.println(99) println(myObject3.age) myObject3.printMyAbstractClassInfo() }
src/main/kotlin/com/zj/example/kotlin/shengshiyuan/helloworld/29.HelloKotlin-对象表达式object.kt
331898196
package coil.intercept import coil.EventListener import coil.request.ImageRequest import coil.request.ImageResult import coil.request.NullRequestData import coil.size.Size internal class RealInterceptorChain( val initialRequest: ImageRequest, val interceptors: List<Interceptor>, val index: Int, override val request: ImageRequest, override val size: Size, val eventListener: EventListener, val isPlaceholderCached: Boolean, ) : Interceptor.Chain { override fun withSize(size: Size) = copy(size = size) override suspend fun proceed(request: ImageRequest): ImageResult { if (index > 0) checkRequest(request, interceptors[index - 1]) val interceptor = interceptors[index] val next = copy(index = index + 1, request = request) val result = interceptor.intercept(next) checkRequest(result.request, interceptor) return result } private fun checkRequest(request: ImageRequest, interceptor: Interceptor) { check(request.context === initialRequest.context) { "Interceptor '$interceptor' cannot modify the request's context." } check(request.data !== NullRequestData) { "Interceptor '$interceptor' cannot set the request's data to null." } check(request.target === initialRequest.target) { "Interceptor '$interceptor' cannot modify the request's target." } check(request.lifecycle === initialRequest.lifecycle) { "Interceptor '$interceptor' cannot modify the request's lifecycle." } check(request.sizeResolver === initialRequest.sizeResolver) { "Interceptor '$interceptor' cannot modify the request's size resolver. " + "Use `Interceptor.Chain.withSize` instead." } } private fun copy( index: Int = this.index, request: ImageRequest = this.request, size: Size = this.size, ) = RealInterceptorChain(initialRequest, interceptors, index, request, size, eventListener, isPlaceholderCached) }
coil-base/src/main/java/coil/intercept/RealInterceptorChain.kt
617558769
package org.luxons.sevenwonders.engine.effects import org.junit.experimental.theories.DataPoints import org.junit.experimental.theories.Theories import org.junit.experimental.theories.Theory import org.junit.runner.RunWith import org.luxons.sevenwonders.engine.SimplePlayer import org.luxons.sevenwonders.engine.resources.resourcesOf import org.luxons.sevenwonders.engine.test.fixedProduction import org.luxons.sevenwonders.engine.test.testBoard import org.luxons.sevenwonders.engine.test.testTable import org.luxons.sevenwonders.model.resources.ResourceType import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @RunWith(Theories::class) class ProductionIncreaseTest { @Theory fun apply_boardContainsAddedResourceType( initialType: ResourceType, addedType: ResourceType, extraType: ResourceType, ) { val board = testBoard(initialType) val effect = ProductionIncrease(fixedProduction(addedType), false) effect.applyTo(board) val resources = resourcesOf(initialType, addedType) assertTrue(board.production.contains(resources)) assertFalse(board.publicProduction.contains(resources)) val moreResources = resourcesOf(initialType, addedType, extraType) assertFalse(board.production.contains(moreResources)) assertFalse(board.publicProduction.contains(moreResources)) } @Theory fun apply_boardContainsAddedResourceType_sellable( initialType: ResourceType, addedType: ResourceType, extraType: ResourceType, ) { val board = testBoard(initialType) val effect = ProductionIncrease(fixedProduction(addedType), true) effect.applyTo(board) val resources = resourcesOf(initialType, addedType) assertTrue(board.production.contains(resources)) assertTrue(board.publicProduction.contains(resources)) val moreResources = resourcesOf(initialType, addedType, extraType) assertFalse(board.production.contains(moreResources)) assertFalse(board.publicProduction.contains(moreResources)) } @Theory fun computePoints_isAlwaysZero(addedType: ResourceType) { val effect = ProductionIncrease(fixedProduction(addedType), false) val player = SimplePlayer(0, testTable(5)) assertEquals(0, effect.computePoints(player)) } companion object { @JvmStatic @DataPoints fun resourceTypes(): Array<ResourceType> = ResourceType.values() } }
sw-engine/src/test/kotlin/org/luxons/sevenwonders/engine/effects/ProductionIncreaseTest.kt
3165449657
package navigator.example.simple import android.app.Activity import android.os.Bundle import navigator.Navigator import navigator.example.simple.R class SimpleActivity : Activity() { private val navigator: Navigator by lazy { findViewById<Navigator>(R.id.navigator) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_simple) } override fun onBackPressed() { if (navigator.canPop()) { navigator.pop() return } super.onBackPressed() } }
samples/simple/src/main/kotlin/navigator/example/simple/SimpleActivity.kt
2452712586
@file:JvmName("RxSearchView") @file:JvmMultifileClass package com.jakewharton.rxbinding4.appcompat import androidx.annotation.CheckResult import androidx.appcompat.widget.SearchView import com.jakewharton.rxbinding4.InitialValueObservable import com.jakewharton.rxbinding4.internal.checkMainThread import io.reactivex.rxjava3.core.Observer import io.reactivex.rxjava3.android.MainThreadDisposable /** * Create an observable of character sequences for query text changes on `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Note:* A value will be emitted immediately on subscribe. */ @CheckResult fun SearchView.queryTextChanges(): InitialValueObservable<CharSequence> { return SearchViewQueryTextChangesObservable(this) } private class SearchViewQueryTextChangesObservable( private val view: SearchView ) : InitialValueObservable<CharSequence>() { override fun subscribeListener(observer: Observer<in CharSequence>) { if (!checkMainThread(observer)) { return } val listener = Listener(view, observer) observer.onSubscribe(listener) view.setOnQueryTextListener(listener) } override val initialValue get() = view.query private class Listener( private val searchView: SearchView, private val observer: Observer<in CharSequence> ) : MainThreadDisposable(), SearchView.OnQueryTextListener { override fun onQueryTextChange(s: String): Boolean { if (!isDisposed) { observer.onNext(s) return true } return false } override fun onQueryTextSubmit(query: String): Boolean { return false } override fun onDispose() { searchView.setOnQueryTextListener(null) } } }
rxbinding-appcompat/src/main/java/com/jakewharton/rxbinding4/appcompat/SearchViewQueryTextChangesObservable.kt
4059813497
package de.maibornwolff.codecharta.importer.gitlogparser.parser import de.maibornwolff.codecharta.importer.gitlogparser.input.VersionControlledFile class VersionControlledFilesInGitProject(private val vcFList: MutableMap<String, VersionControlledFile>, private val filesInGitLog: List<String>) { // TODO salts should not be part of filenames, change logic error private fun removeSaltFromFilenames() { vcFList.values .forEach { it.filename = it.filename.substringBefore("_\\0_") } } private fun findDuplicates(): MutableMap<String, Set<String>> { val occurrencesPerFilename = vcFList.values.groupingBy { it.filename }.eachCount() val duplicateFilenames = occurrencesPerFilename.filterValues { it > 1 } val trackingNamesPerFilename = mutableMapOf<String, Set<String>>() duplicateFilenames.keys.forEach { element -> trackingNamesPerFilename[element] = vcFList.keys.filter { vcFList[it]?.filename == element }.toSet() } return trackingNamesPerFilename } // We always keep deleted files until the end, because they might be re-added in a merge commit // This might result in multiple files with the same filename being stored in VCF // the following function tries to find the correct version to keep for later visualization, by accounting for flags and time of addition private fun removeDuplicates(trackingNamesPerFilename: MutableMap<String, Set<String>>) { trackingNamesPerFilename.keys.forEach { elem -> var chooseElement = "" trackingNamesPerFilename[elem]?.forEach { if (!vcFList[it]?.isDeleted()!!) { chooseElement = it } } if (chooseElement == "") { chooseElement = trackingNamesPerFilename[elem]?.last().toString() } trackingNamesPerFilename[elem]?.forEach { if (it != chooseElement) vcFList.remove(it) } } } fun getListOfVCFilesMatchingGitProject(): Set<VersionControlledFile> { removeSaltFromFilenames() val trackingNamesPerFilename = findDuplicates() removeDuplicates(trackingNamesPerFilename) return vcFList.values .filter { filesInGitLog.contains(it.filename) }.toSet() } }
analysis/import/GitLogParser/src/main/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/parser/VersionControlledFilesInGitProject.kt
267594151
/* * Created by Arcturus Mengsk * 2021. */ package com.anothermovieapp.repository import androidx.room.ColumnInfo import androidx.room.Entity import org.json.JSONObject @Entity(primaryKeys = ["reviewId"], tableName = "reviews") data class EntityDBMovieReview( @ColumnInfo(name = "id") var movieId: String, @ColumnInfo(name = "reviewId") var reviewId: String, @ColumnInfo(name = "author") var author: String, @ColumnInfo(name = "content") var content: String ) { companion object { const val JSON_ID = "id" const val JSON_PAGE = "page" const val JSON_ARRAY_RESULTS = "results" const val JSON_REVIEW_ID = "id" const val JSON_AUTHOR = "author" const val JSON_CONTENT = "content" const val JSON_TOTAL_PAGES = "total_pages" fun fromJSON(obj: JSONObject, movieId: String): EntityDBMovieReview { return EntityDBMovieReview( movieId, obj.optString(JSON_REVIEW_ID), obj.optString(JSON_AUTHOR), obj.optString(JSON_CONTENT) ) } } }
app/src/main/java/com/anothermovieapp/repository/EntityDBMovieReview.kt
4206720011
package org.havenapp.main.database.async import android.os.AsyncTask import org.havenapp.main.HavenApp import org.havenapp.main.model.EventTrigger /** * Created by Arka Prava Basu <[email protected]> on 8/9/18. */ class EventTriggerDeleteAsync(private val callback: DeleteCallback) : AsyncTask<EventTrigger, Unit, Unit>() { override fun doInBackground(vararg params: EventTrigger) { HavenApp.getDataBaseInstance().getEventTriggerDAO().delete(params.get(0)) // todo delete file here? } override fun onPostExecute(result: Unit?) { callback.onEventTriggerDeleted() } interface DeleteCallback { fun onEventTriggerDeleted() } }
src/main/java/org/havenapp/main/database/async/EventTriggerDeleteAsync.kt
1862765840
package com.androidvip.hebf.services import android.content.Context import android.content.Intent import android.content.IntentFilter import androidx.work.* import com.androidvip.hebf.receivers.UnlockReceiver import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.util.concurrent.TimeUnit class LockScreenWork(context: Context, params: WorkerParameters): CoroutineWorker(context, params) { override suspend fun doWork(): Result = withContext(Dispatchers.IO) { unregisterReceiver(applicationContext) return@withContext registerUnlockReceiver(applicationContext) } companion object { private const val WORK_TAG = "LOCK_SCREEN_WORK_REQUEST" var receiver: UnlockReceiver? = null fun registerUnlockReceiver(context: Context): Result { return runCatching { receiver = UnlockReceiver() IntentFilter(Intent.ACTION_SCREEN_OFF).apply { addAction(Intent.ACTION_SCREEN_ON) context.applicationContext.registerReceiver(receiver, this) } Result.success() }.getOrDefault(Result.failure()) } fun unregisterReceiver(context: Context) { try { if (receiver != null) { context.applicationContext.unregisterReceiver(receiver) } } catch (e: Exception) { e.printStackTrace() } finally { receiver = null } } fun scheduleJobPeriodic(context: Context?) { if (context == null) return val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.NOT_REQUIRED) .setRequiresCharging(false) .build() val request = PeriodicWorkRequest.Builder( LockScreenWork::class.java, PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, TimeUnit.MILLISECONDS, PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS, TimeUnit.MILLISECONDS ).setConstraints(constraints).build() val workManager = WorkManager.getInstance(context.applicationContext) workManager.enqueueUniquePeriodicWork( WORK_TAG, ExistingPeriodicWorkPolicy.KEEP, request ) } fun cancelJob(context: Context) { WorkManager.getInstance(context.applicationContext).cancelAllWorkByTag(WORK_TAG) unregisterReceiver(context) } } }
app/src/main/java/com/androidvip/hebf/services/LockScreenWork.kt
1795376818
package com.latitude.seventimer.util import android.util.Log object L { const val logSwitch = true const val logLevel = 1 private val version = "" private val LOG_MAXLENGTH = 2000 @JvmStatic fun e(tag: String, msg: String) { if (logLevel <= Log.ERROR || logSwitch) { Log.e(version + tag, msg) } } fun e(tag: String, format: String, vararg args: Any) { e(tag, formatMessage(format, *args)) } @JvmStatic fun d(tag: String, msg: String) { if (logLevel <= Log.DEBUG || logSwitch) { Log.d(version + tag, msg) } } @JvmStatic fun d(tag: String, format: String, vararg args: Any) { d(tag, formatMessage(format, *args)) } @JvmStatic fun w(tag: String, msg: String) { if (logLevel <= Log.WARN || logSwitch) { Log.w(version + tag, msg) } } @JvmStatic fun w(tag: String, format: String, vararg args: Any) { w(tag, formatMessage(format, *args)) } @JvmStatic fun i(tag: String, msg: String) { if (logLevel <= Log.INFO || logSwitch) { Log.i(version + tag, msg) } } @JvmStatic fun i(tag: String, format: String, vararg args: Any) { i(tag, formatMessage(format, *args)) } @JvmStatic fun v(tag: String, msg: String) { if (logLevel <= Log.VERBOSE || logSwitch) { Log.v(version + tag, msg) } } @JvmStatic fun v(tag: String, format: String, vararg args: Any) { v(tag, formatMessage(format, *args)) } @JvmStatic fun LongString(tag: String, msg: String) { if (logLevel <= Log.VERBOSE || logSwitch) { val strLength = msg.length var start = 0 var end = LOG_MAXLENGTH for (i in 0..99) { if (strLength > end) { L.e(tag, i.toString() + ": " + msg.substring(start, end)) start = end end = end + LOG_MAXLENGTH } else { L.e(tag, i.toString() + ": " + msg.substring(start, strLength)) break } } } } fun formatMessage(message: String, vararg args: Any): String { return String.format(message, *args) } }
app/src/main/java/com/latitude/seventimer/util/L.kt
2925977925
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) } } } }
app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryNavigationView.kt
2648370198
/* * 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) }
emoji/src/androidMain/kotlin/com/vanniktech/emoji/EmojiLayoutFactory.kt
2037726012
package io.kotest.property.arbitrary import io.kotest.property.Shrinker import kotlin.math.abs import kotlin.random.nextLong fun Arb.Companion.long(min: Long = Long.MIN_VALUE, max: Long = Long.MAX_VALUE) = long(min..max) fun Arb.Companion.long(range: LongRange = Long.MIN_VALUE..Long.MAX_VALUE): Arb<Long> { val edgecases = listOf(0, Long.MAX_VALUE, Long.MIN_VALUE) return arb(LongShrinker, edgecases) { it.random.nextLong(range) } } object LongShrinker : Shrinker<Long> { override fun shrink(value: Long): List<Long> = when (value) { 0L -> emptyList() 1L, -1L -> listOf(0L) else -> { val a = listOf(0, 1, -1, abs(value), value / 3, value / 2, value * 2 / 3) val b = (1..5).map { value - it }.reversed().filter { it > 0 } (a + b).distinct() .filterNot { it == value } } } }
kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/longs.kt
130630811
package org.paradise.ipaq.services.trace import org.apache.commons.lang3.StringUtils import org.paradise.ipaq.Constants import org.slf4j.LoggerFactory import org.springframework.cloud.sleuth.Span import org.springframework.cloud.sleuth.SpanTextMap import org.springframework.cloud.sleuth.instrument.web.ZipkinHttpSpanExtractor import org.springframework.cloud.sleuth.util.TextMapUtil import java.util.regex.Pattern /** * Created by terrence on 28/7/17. */ class CustomHttpSpanExtractor(skipPattern: Pattern) : ZipkinHttpSpanExtractor(skipPattern) { override fun joinTrace(carrier: SpanTextMap): Span { val map = TextMapUtil.asMap(carrier) val country = map[Constants.COUNTRY] LOG.debug("Extracting trace data with country [{}]", country) // Enable SPAN explorable carrier.put(Span.SPAN_FLAGS, "1") val span = super.joinTrace(carrier) if (StringUtils.isNotEmpty(country)) { span.setBaggageItem(Constants.COUNTRY, country) } return span } companion object { private val LOG = LoggerFactory.getLogger(CustomHttpSpanExtractor::class.java) } }
src/main/kotlin/org/paradise/ipaq/services/trace/CustomHttpSpanExtractor.kt
2383031016
/* * 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 } }
jvb/src/test/kotlin/org/jitsi/videobridge/cc/allocation/BitrateControllerTest.kt
1701323845
package com.github.telegram.domain /** * This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc. * * @property type Type of the entity. * Can be mention (@username), hashtag, bot_command, url, email, bold (bold text), italic (italic text), * code (monowidth string), pre (monowidth block), text_link (for clickable text URLs), * text_mention (for users without usernames). * @property offset Offset in UTF-16 code units to the start of the entity. * @property length Length of the entity in UTF-16 code units. * @property url For “text_link” only, url that will be opened after user taps on the text. * @property user For “text_mention” only, the mentioned user. */ data class MessageEntity( val type: String, val offset: Int, val length: Int, val url: String?, val user: User?)
telegram-bot-api/src/main/kotlin/com/github/telegram/domain/MessageEntity.kt
100434595
/* * 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() }
projects/ui/src/main/kotlin/callbacks-api.kt
2434996486
package de.ph1b.audiobook.misc.conductor import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import android.view.ViewGroup import com.bluelinelabs.conductor.Controller import com.bluelinelabs.conductor.ControllerChangeHandler /** * Like [com.bluelinelabs.conductor.ChangeHandlerFrameLayout], but as a CoordinatorLayout */ class ChangeHandlerCoordinatorLayout : androidx.coordinatorlayout.widget.CoordinatorLayout, ControllerChangeHandler.ControllerChangeListener { private var inProgressTransactionCount: Int = 0 constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) override fun onInterceptTouchEvent(ev: MotionEvent): Boolean = inProgressTransactionCount > 0 || super.onInterceptTouchEvent(ev) override fun onChangeStarted( to: Controller?, from: Controller?, isPush: Boolean, container: ViewGroup, handler: ControllerChangeHandler ) { inProgressTransactionCount++ } override fun onChangeCompleted( to: Controller?, from: Controller?, isPush: Boolean, container: ViewGroup, handler: ControllerChangeHandler ) { inProgressTransactionCount-- } }
app/src/main/kotlin/de/ph1b/audiobook/misc/conductor/ChangeHandlerCoordinatorLayout.kt
3299618489
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 } } } }
wukong/src/main/java/com/senorsen/wukong/network/SocketClient.kt
1783618574
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() } } }
sample-screen-color/src/main/java/screenswitchersample/color/ColorPresenter.kt
887199613
package net.dinkla.raytracer.math import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* internal class RayTest { private val origin = Point3D(1.0, 1.0, 1.0) private val direction = Vector3D.UP private val ray = Ray(origin, direction) @Test fun `construct from ray`() { val ray2 = Ray(ray) assertEquals(origin, ray2.origin) assertEquals(direction, ray2.direction) } @Test fun linear() { assertEquals(origin + (direction * 0.5), ray.linear(0.5)) } }
src/test/kotlin/net/dinkla/raytracer/math/RayTest.kt
1432119713
package com.supercilex.robotscouter.core.ui.views import android.content.Context import android.util.AttributeSet import android.widget.ProgressBar import androidx.core.view.isVisible import com.supercilex.robotscouter.core.ui.ContentLoader import com.supercilex.robotscouter.core.ui.ContentLoaderHelper /** * ContentLoadingProgressBar implements a ProgressBar that waits a minimum time to be dismissed * before showing. Once visible, the progress bar will be visible for a minimum amount of time to * avoid "flashes" in the UI when an event could take a largely variable time to complete * (from none, to a user perceivable amount). */ class ContentLoadingProgressBar : ProgressBar, ContentLoader { override val helper = ContentLoaderHelper(this) { isVisible = it } constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) override fun onAttachedToWindow() { super.onAttachedToWindow() helper.onAttachedToWindow() } override fun onDetachedFromWindow() { super.onDetachedFromWindow() helper.onDetachedFromWindow() } }
library/core-ui/src/main/java/com/supercilex/robotscouter/core/ui/views/ContentLoadingProgressBar.kt
1936011051
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
Sieve_Of_Eratosthenes/Sieve_Of_Eratosthenes.kt
901694569
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 } }
fluxc/src/main/java/org/wordpress/android/fluxc/store/EncryptedLogStore.kt
297707951
/** * DO NOT EDIT THIS FILE. * * This source code was autogenerated from source code within the `app/src/gms` directory * and is not intended for modifications. If any edits should be made, please do so in the * corresponding file under the `app/src/gms` directory. */ // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.example.kotlindemos import android.os.Bundle import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import com.google.android.libraries.maps.StreetViewPanoramaOptions import com.google.android.libraries.maps.StreetViewPanoramaView import com.google.android.libraries.maps.model.LatLng /** * This shows how to create a simple activity with streetview */ class StreetViewPanoramaViewDemoActivity : AppCompatActivity() { private lateinit var streetViewPanoramaView: StreetViewPanoramaView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val options = StreetViewPanoramaOptions() savedInstanceState ?: options.position(SYDNEY) streetViewPanoramaView = StreetViewPanoramaView(this, options) addContentView( streetViewPanoramaView, ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) ) // *** IMPORTANT *** // StreetViewPanoramaView requires that the Bundle you pass contain _ONLY_ // StreetViewPanoramaView SDK objects or sub-Bundles. streetViewPanoramaView.onCreate(savedInstanceState?.getBundle(STREETVIEW_BUNDLE_KEY)) } override fun onResume() { streetViewPanoramaView.onResume() super.onResume() } override fun onPause() { streetViewPanoramaView.onPause() super.onPause() } override fun onDestroy() { streetViewPanoramaView.onDestroy() super.onDestroy() } public override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) var streetViewBundle = outState.getBundle(STREETVIEW_BUNDLE_KEY) if (streetViewBundle == null) { streetViewBundle = Bundle() outState.putBundle( STREETVIEW_BUNDLE_KEY, streetViewBundle ) } streetViewPanoramaView.onSaveInstanceState(streetViewBundle) } companion object { // George St, Sydney private val SYDNEY = LatLng(-33.87365, 151.20689) private const val STREETVIEW_BUNDLE_KEY = "StreetViewBundleKey" } }
ApiDemos/kotlin/app/src/v3/java/com/example/kotlindemos/StreetViewPanoramaViewDemoActivity.kt
3915078978
package org.jetbrains.dokka.gradle import org.gradle.api.Project import org.gradle.api.provider.Property import org.gradle.api.tasks.* import org.jetbrains.dokka.DokkaConfigurationBuilder import org.jetbrains.dokka.SourceLinkDefinitionImpl import java.io.File import java.net.URL class GradleSourceLinkBuilder( @Transient @get:Internal internal val project: Project ) : DokkaConfigurationBuilder<SourceLinkDefinitionImpl> { @InputDirectory @PathSensitive(PathSensitivity.RELATIVE) val localDirectory: Property<File?> = project.objects.safeProperty() @Input val remoteUrl: Property<URL?> = project.objects.safeProperty() @Optional @Input val remoteLineSuffix: Property<String> = project.objects.safeProperty<String>() .safeConvention("#L") override fun build(): SourceLinkDefinitionImpl { return SourceLinkDefinitionImpl( localDirectory = localDirectory.getSafe()?.canonicalPath ?: project.projectDir.canonicalPath, remoteUrl = checkNotNull(remoteUrl.getSafe()) { "missing remoteUrl on source link" }, remoteLineSuffix = remoteLineSuffix.getSafe() ) } }
runners/gradle-plugin/src/main/kotlin/org/jetbrains/dokka/gradle/GradleSourceLinkBuilder.kt
3567521637
package com.yumodev.glide3 import android.os.Bundle import android.support.design.widget.Snackbar import android.support.design.widget.NavigationView import android.support.v4.view.GravityCompat import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import android.view.View import com.yumo.demo.config.Config import com.yumo.demo.view.YmTestClassFragment import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.app_bar_main.* class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } val toggle = ActionBarDrawerToggle( this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) drawer_layout.addDrawerListener(toggle) toggle.syncState() nav_view.setNavigationItemSelectedListener(this) showTestPackageHomePage() } override fun onBackPressed() { if (drawer_layout.isDrawerOpen(GravityCompat.START)) { drawer_layout.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. when (item.itemId) { R.id.action_settings -> return true else -> return super.onOptionsItemSelected(item) } } override fun onNavigationItemSelected(item: MenuItem): Boolean { // Handle navigation view item clicks here. when (item.itemId) { R.id.nav_camera -> { // Handle the camera action } R.id.nav_gallery -> { } R.id.nav_slideshow -> { } R.id.nav_manage -> { } R.id.nav_share -> { } R.id.nav_send -> { } } drawer_layout.closeDrawer(GravityCompat.START) return true } private fun showTestPackageHomePage() { // YmTestPackageFragment fragment = new YmTestPackageFragment(); // getSupportFragmentManager().beginTransaction().replace(R.id.test_fragment_id, fragment, "package").commit(); val bundle = Bundle() bundle.putString("packageName", packageName) bundle.putInt(Config.ARGUMENT_TOOLBAR_VISIBLE, View.GONE) val classFragment = YmTestClassFragment() classFragment.arguments = bundle val ft = supportFragmentManager.beginTransaction() ft.addToBackStack(null) ft.replace(com.yumo.demo.R.id.test_fragment_id, classFragment).commit() } }
glide3/src/main/java/com/yumodev/glide3/MainActivity.kt
2965779350
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)) }
src/main/kotlin/com/minecraft/moonlake/launcher/controller/MuiControllerUtils.kt
784536907
package baltamon.mx.pokedexmvp.ability import baltamon.mx.pokedexmvp.models.Ability import baltamon.mx.pokedexmvp.presenters.Presenter import baltamon.mx.pokedexmvp.providers.AbilityProvider import baltamon.mx.pokedexmvp.providers.AbilityProviderInterface /** * Created by Baltazar Rodriguez on 04/07/2017. */ class AbilityPresenter(val view: AbilityView, val abilityName: String): Presenter, AbilityProviderInterface { val provider = AbilityProvider(this) var ability: Ability? = null override fun onCreate() { provider.loadAbility(abilityName) } override fun onSuccess(ability: Ability) { this.ability = ability view.onAbilityInformation(ability) } override fun onFailure(fail: String) { view.onFailure(fail) } }
app/src/main/java/baltamon/mx/pokedexmvp/ability/AbilityPresenter.kt
1100782624
/* * 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*/] } """) }
src/test/kotlin/org/rust/lang/core/completion/RsStdlibCompletionTest.kt
2918423716
package me.camdenorrb.kportals.commands.sub import me.camdenorrb.kportals.KPortals import me.camdenorrb.kportals.messages.Messages.TYPE_DOES_NOT_EXIST import org.bukkit.ChatColor.DARK_GREEN import org.bukkit.ChatColor.LIGHT_PURPLE import org.bukkit.command.CommandSender /** * Created by camdenorrb on 3/20/17. */ class RemovePortalCmd : SubCmd("-remove", "/Portal -remove <Name>", "kportals.remove") { override fun execute(sender: CommandSender, plugin: KPortals, args: List<String>): Boolean { if (args.isEmpty()) return false if (plugin.portals.removeIf { it.name.equals(args[0], true) }.not()) return { TYPE_DOES_NOT_EXIST.send(sender); true }() sender.sendMessage("${DARK_GREEN}Successful removed $LIGHT_PURPLE${args[0]} ${DARK_GREEN}from existing portals.") return true } }
src/main/kotlin/me/camdenorrb/kportals/commands/sub/RemovePortalCmd.kt
252549184
/* * 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> }
requery-kotlin/src/main/kotlin/io/requery/kotlin/PropertyExtensions.kt
1475193242
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.digitalwellbeingexperiments.toolkit.notificationgenerator fun Any.TAG() = this.javaClass.simpleName fun <T> List<T>.randomItem(): T { return this[(this.size * Math.random()).toInt()] }
notifications/notification-generator/app/src/main/java/com/digitalwellbeingexperiments/toolkit/notificationgenerator/Extensions.kt
1818234750
/** * 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) } }
src/main/kotlin/DiameterOfBinaryTree.kt
35865155
package com.balanza.android.harrypotter.domain.model.house /** * Created by balanza on 17/02/17. */ abstract class House { abstract val background : Int abstract val name : String abstract val detailBackground : Int abstract val primaryColor : Int abstract val calculatePoints : (Int) -> Int }
app/src/main/java/com/balanza/android/harrypotter/domain/model/house/House.kt
2175235295
package io.github.binaryfoo.tlv public class TlvParseException(public val resultsSoFar: List<BerTlv>, message: String, cause: Exception) : RuntimeException(message, cause)
src/main/java/io/github/binaryfoo/tlv/TlvParseException.kt
2774225387
/*************************************************************************************** * * * Copyright (c) 2018 Mike Hardy <[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.ichi2.anki.tests import android.Manifest import android.annotation.SuppressLint import android.content.SharedPreferences import androidx.annotation.StringRes import androidx.core.content.edit import androidx.test.annotation.UiThreadTest import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.rule.GrantPermissionRule import com.ichi2.anki.AnkiDroidApp import com.ichi2.anki.CrashReportService import com.ichi2.anki.CrashReportService.FEEDBACK_REPORT_ALWAYS import com.ichi2.anki.CrashReportService.FEEDBACK_REPORT_ASK import com.ichi2.anki.R import org.acra.ACRA import org.acra.builder.ReportBuilder import org.acra.config.ACRAConfigurationException import org.acra.config.LimitingReportAdministrator import org.acra.config.ToastConfiguration import org.acra.data.CrashReportDataFactory import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.junit.Assert.* import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import timber.log.Timber @RunWith(AndroidJUnit4::class) @SuppressLint("DirectSystemCurrentTimeMillisUsage") class ACRATest : InstrumentedTest() { @get:Rule var runtimePermissionRule: GrantPermissionRule = GrantPermissionRule.grant(Manifest.permission.WRITE_EXTERNAL_STORAGE) private var mApp: AnkiDroidApp? = null private val mDebugLogcatArguments = arrayOf("-t", "300", "-v", "long", "ACRA:S") // private String[] prodLogcatArguments = { "-t", "100", "-v", "time", "ActivityManager:I", "SQLiteLog:W", AnkiDroidApp.TAG + ":D", "*:S" }; @Before @UiThreadTest fun setUp() { mApp = testContext.applicationContext as AnkiDroidApp // Note: attachBaseContext can't be called twice as we're using the same instance between all tests. mApp!!.onCreate() } @Test @Throws(Exception::class) fun testDebugConfiguration() { // Debug mode overrides all saved state so no setup needed CrashReportService.setDebugACRAConfig(sharedPrefs) assertArrayEquals( "Debug logcat arguments not set correctly", CrashReportService.acraCoreConfigBuilder.build().logcatArguments.toTypedArray(), mDebugLogcatArguments ) verifyDebugACRAPreferences() } private fun verifyDebugACRAPreferences() { assertTrue( "ACRA was not disabled correctly", sharedPrefs .getBoolean(ACRA.PREF_DISABLE_ACRA, true) ) assertEquals( "ACRA feedback was not turned off correctly", CrashReportService.FEEDBACK_REPORT_NEVER, sharedPrefs .getString(CrashReportService.FEEDBACK_REPORT_KEY, "undefined") ) } @Test @Throws(Exception::class) fun testProductionConfigurationUserDisabled() { // set up as if the user had prefs saved to disable completely setReportConfig(CrashReportService.FEEDBACK_REPORT_NEVER) // ACRA initializes production logcat via annotation and we can't mock Build.DEBUG // That means we are restricted from verifying production logcat args and this is the debug case again CrashReportService.setProductionACRAConfig(sharedPrefs) verifyDebugACRAPreferences() } @Test @Throws(Exception::class) fun testProductionConfigurationUserAsk() { // set up as if the user had prefs saved to ask setReportConfig(FEEDBACK_REPORT_ASK) // If the user is set to ask, then it's production, with interaction mode dialog CrashReportService.setProductionACRAConfig(sharedPrefs) verifyACRANotDisabled() assertToastMessage(R.string.feedback_for_manual_toast_text) assertToastIsEnabled() assertDialogEnabledStatus("Dialog should be enabled", true) } @Test @Throws(Exception::class) fun testCrashReportLimit() { // To test ACRA switch on reporting, plant a production tree, and trigger a report Timber.plant(AnkiDroidApp.ProductionCrashReportingTree()) // set up as if the user had prefs saved to full auto setReportConfig(FEEDBACK_REPORT_ALWAYS) // If the user is set to always, then it's production, with interaction mode toast // will be useful with ACRA 5.2.0 CrashReportService.setProductionACRAConfig(sharedPrefs) // The same class/method combo is only sent once, so we face a new method each time (should test that system later) val crash = Exception("testCrashReportSend at " + System.currentTimeMillis()) val trace = arrayOf( StackTraceElement( "Class", "Method" + System.currentTimeMillis().toInt(), "File", System.currentTimeMillis().toInt() ) ) crash.stackTrace = trace // one send should work val crashData = CrashReportDataFactory( testContext, CrashReportService.acraCoreConfigBuilder.build() ).createCrashData(ReportBuilder().exception(crash)) assertTrue( LimitingReportAdministrator().shouldSendReport( testContext, CrashReportService.acraCoreConfigBuilder.build(), crashData ) ) // A second send should not work assertFalse( LimitingReportAdministrator().shouldSendReport( testContext, CrashReportService.acraCoreConfigBuilder.build(), crashData ) ) // Now let's clear data CrashReportService.deleteACRALimiterData(testContext) // A third send should work again assertTrue( LimitingReportAdministrator().shouldSendReport( testContext, CrashReportService.acraCoreConfigBuilder.build(), crashData ) ) } @Test @Throws(Exception::class) fun testProductionConfigurationUserAlways() { // set up as if the user had prefs saved to full auto setReportConfig(FEEDBACK_REPORT_ALWAYS) // If the user is set to always, then it's production, with interaction mode toast CrashReportService.setProductionACRAConfig(sharedPrefs) verifyACRANotDisabled() assertToastMessage(R.string.feedback_auto_toast_text) assertToastIsEnabled() assertDialogEnabledStatus("Dialog should not be enabled", false) } @Test @Throws(Exception::class) fun testDialogEnabledWhenMovingFromAlwaysToAsk() { // Raised in #6891 - we ned to ensure that the dialog is re-enabled after this transition. setReportConfig(FEEDBACK_REPORT_ALWAYS) // If the user is set to ask, then it's production, with interaction mode dialog CrashReportService.setProductionACRAConfig(sharedPrefs) verifyACRANotDisabled() assertDialogEnabledStatus("dialog should be disabled when status is ALWAYS", false) assertToastMessage(R.string.feedback_auto_toast_text) setAcraReportingMode(FEEDBACK_REPORT_ASK) assertDialogEnabledStatus("dialog should be re-enabled after changed to ASK", true) assertToastMessage(R.string.feedback_for_manual_toast_text) } @Test @Throws(Exception::class) fun testToastTextWhenMovingFromAskToAlways() { // Raised in #6891 - we ned to ensure that the text is fixed after this transition. setReportConfig(FEEDBACK_REPORT_ASK) // If the user is set to ask, then it's production, with interaction mode dialog CrashReportService.setProductionACRAConfig(sharedPrefs) verifyACRANotDisabled() assertToastMessage(R.string.feedback_for_manual_toast_text) setAcraReportingMode(FEEDBACK_REPORT_ALWAYS) assertToastMessage(R.string.feedback_auto_toast_text) } private fun setAcraReportingMode(feedbackReportAlways: String) { CrashReportService.setAcraReportingMode(feedbackReportAlways) } @Throws(ACRAConfigurationException::class) private fun assertDialogEnabledStatus(message: String, isEnabled: Boolean) { val config = CrashReportService.acraCoreConfigBuilder.build() for (configuration in config.pluginConfigurations) { // Make sure the dialog is set to pop up if (configuration.javaClass.toString().contains("Dialog")) { assertThat(message, configuration.enabled(), equalTo(isEnabled)) } } } @Throws(ACRAConfigurationException::class) private fun assertToastIsEnabled() { val config = CrashReportService.acraCoreConfigBuilder.build() for (configuration in config.pluginConfigurations) { if (configuration.javaClass.toString().contains("Toast")) { assertThat("Toast should be enabled", configuration.enabled(), equalTo(true)) } } } @Throws(ACRAConfigurationException::class) private fun assertToastMessage(@StringRes res: Int) { val config = CrashReportService.acraCoreConfigBuilder.build() for (configuration in config.pluginConfigurations) { if (configuration.javaClass.toString().contains("Toast")) { assertEquals( mApp!!.resources.getString(res), (configuration as ToastConfiguration).text ) assertTrue("Toast should be enabled", configuration.enabled()) } } } private fun verifyACRANotDisabled() { assertFalse( "ACRA was not enabled correctly", sharedPrefs.getBoolean(ACRA.PREF_DISABLE_ACRA, false) ) } private fun setReportConfig(feedbackReportAsk: String) { sharedPrefs.edit { putString(CrashReportService.FEEDBACK_REPORT_KEY, feedbackReportAsk) } } private val sharedPrefs: SharedPreferences get() = AnkiDroidApp.getSharedPrefs(testContext) }
AnkiDroid/src/androidTest/java/com/ichi2/anki/tests/ACRATest.kt
861898201
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 )
src/main/kotlin/mixit/user/handler/dto/UserDto.kt
4268898335
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) } }
dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/content/shared/ContentAdapter.kt
2389605416
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 } }
dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/shared/base/BaseViewModel.kt
2255541289
package dagger.poc.android.injection import dagger.Module import dagger.android.ContributesAndroidInjector import dagger.poc.android.presentation.MainActivity import dagger.poc.android.presentation.SomeFragment /** * Created by Thiago on 6/14/2017. */ @Module internal abstract class AndroidBindingModule { @ContributesAndroidInjector @ActivityScope internal abstract fun someFragment(): SomeFragment @ContributesAndroidInjector @ActivityScope internal abstract fun mainActivity(): MainActivity }
DaggerPoc/app/src/main/java/dagger/poc/android/injection/AndroidBindingModule.kt
194354464
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" """ } }
.teamcity/_self/projects/WPComPlugins.kt
3419392653
package com.mooveit.library.providers.definition interface AddressProvider : Provider { fun city(): String fun streetAddress(): String fun buildingNumber(): String fun zipCode(): String fun state(): String fun stateAbbreviation(): String }
library/src/main/java/com/mooveit/library/providers/definition/AddressProvider.kt
311212707
package kotlinx.serialization.protobuf.schema import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.serializer import java.io.File import java.nio.charset.StandardCharsets import kotlin.reflect.KClass private const val RESOURCES_ROOT_PATH = "formats/protobuf/jvmTest/resources" // Regenerate all proto file for tests. private fun main() { regenerateAllProtoFiles() } private fun regenerateAllProtoFiles() { generateProtoFile( GenerationTest.OptionsClass::class, mapOf("java_package" to "api.proto", "java_outer_classname" to "Outer") ) commonClasses.forEach { generateProtoFile(it) } generateCommonProtoFile(commonClasses) } private fun generateProtoFile(clazz: KClass<*>, options: Map<String, String> = emptyMap() ) { generateSchemaFile("${clazz.simpleName}.proto", listOf(clazz.serializer().descriptor), options) } private fun generateCommonProtoFile(classes: List<KClass<*>>) { val descriptors = classes.map { it.serializer().descriptor }.toList() generateSchemaFile(COMMON_SCHEMA_FILE_NAME, descriptors) } private fun generateSchemaFile( fileName: String, descriptors: List<SerialDescriptor>, options: Map<String, String> = emptyMap() ) { val filePath = "$RESOURCES_ROOT_PATH/$fileName" val file = File(filePath) val schema = ProtoBufSchemaGenerator.generateSchemaText(descriptors, TARGET_PACKAGE, options) file.writeText(schema, StandardCharsets.UTF_8) }
formats/protobuf/jvmTest/src/kotlinx/serialization/protobuf/schema/RegenerateSchemas.kt
2337187645
/* * 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() }
formats/json/nativeMain/src/kotlinx/serialization/json/JsonSchemaCache.kt
2455942033
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), ) } } }, ) }
app/src/main/kotlin/me/echeung/moemoekyun/ui/common/Toolbar.kt
3328507162
package com.github.tommykw.tv.activity import android.app.Activity import android.os.Bundle import com.github.tommykw.tv.R class DetailsActivity : BaseActivity() { public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_details) } companion object { val SHARED_ELEMENT_NAME = "hero" val MOVIE = "Movie" } }
app/src/main/kotlin/com/github/tommykw/tv/activity/DetailsActivity.kt
3069235104
// 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" } }
src/main/kotlin/org/wfanet/measurement/duchy/deploy/common/server/ComputationsServer.kt
1465979953
// Copyright 2022 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.reporting.deploy.postgres import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.measurement.common.db.r2dbc.postgres.testing.EmbeddedPostgresDatabaseProvider import org.wfanet.measurement.common.identity.IdGenerator import org.wfanet.measurement.reporting.deploy.postgres.testing.Schemata.REPORTING_CHANGELOG_PATH import org.wfanet.measurement.reporting.service.internal.testing.ReportingSetsServiceTest @RunWith(JUnit4::class) class PostgresReportingSetsServiceTest : ReportingSetsServiceTest<PostgresReportingSetsService>() { override fun newService( idGenerator: IdGenerator, ): PostgresReportingSetsService { return PostgresReportingSetsService( idGenerator, EmbeddedPostgresDatabaseProvider(REPORTING_CHANGELOG_PATH).createNewDatabase() ) } }
src/test/kotlin/org/wfanet/measurement/reporting/deploy/postgres/PostgresReportingSetsServiceTest.kt
2208369512
// 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()) } } }
bbootimg/src/main/kotlin/bootimg/v2/BootHeaderV2.kt
3196919950
/* * 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() } }
debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/timeranges/WeekRangeCollection.kt
2642079821
package com.andreapivetta.blu.ui.settings import android.content.Context import android.content.Intent import android.os.Bundle import com.andreapivetta.blu.R import com.andreapivetta.blu.ui.custom.ThemedActivity import kotlinx.android.synthetic.main.activity_settings.* class SettingsActivity : ThemedActivity() { companion object { fun launch(context: Context) { context.startActivity(Intent(context, SettingsActivity::class.java)) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) toolbar.setNavigationOnClickListener { finish() } if (savedInstanceState == null) fragmentManager.beginTransaction() .add(R.id.container_frameLayout, SettingsFragment()).commit() } }
app/src/main/java/com/andreapivetta/blu/ui/settings/SettingsActivity.kt
1284077989
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) } }
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/fluidburner/FluidBurnerCategory.kt
1292760336
/* * 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 }
platform/projectModel-api/src/com/intellij/util/jdom.kt
3171652634
/* * 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) } } } } ) }
sample/src/main/java/com/google/modernstorage/sample/mediastore/AddMediaScreen.kt
3877367478
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() } }
app/src/main/kotlin/za/org/grassroot2/view/fragment/MeFragment.kt
2954912099
package swak.body.writer.provider.type import swak.body.writer.provider.request.BodyWriterChooser import swak.body.writer.provider.request.BodyWriterChoosers import java.util.* class BodyWriterChooserProviders( private val parent: BodyWriterChooserProviders? ) : BodyWriterChooserProvider { private val localChooserProviders: MutableList<BodyWriterChooserProvider> = ArrayList() fun add(provider: BodyWriterChooserProvider) { localChooserProviders.add(provider) } val allChooserProviders: List<BodyWriterChooserProvider> get() = if (parent != null) localChooserProviders + parent.allChooserProviders else localChooserProviders override fun <B> forClass(target: Class<B>): BodyWriterChooser<B> { val choosers = allChooserProviders.mapNotNull { it.forClass(target) } return if (choosers.isEmpty()) throw NoWriterFoundForType(target) else BodyWriterChoosers(choosers) } }
core/src/main/kotlin/swak/body/writer/provider/type/BodyWriterChooserProviders.kt
1697721832
/* * Copyright (C) 2019 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp.android.test import android.os.Build import androidx.test.platform.app.InstrumentationRegistry import com.google.android.gms.common.GooglePlayServicesNotAvailableException import com.google.android.gms.security.ProviderInstaller import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import mockwebserver3.MockResponse import mockwebserver3.MockWebServer import mockwebserver3.junit5.internal.MockWebServerExtension import okhttp3.Cache import okhttp3.Call import okhttp3.CertificatePinner import okhttp3.Connection import okhttp3.EventListener import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.OkHttpClient import okhttp3.OkHttpClientTestRule import okhttp3.Protocol import okhttp3.RecordingEventListener import okhttp3.Request import okhttp3.TlsVersion import okhttp3.dnsoverhttps.DnsOverHttps import okhttp3.internal.asFactory import okhttp3.internal.concurrent.TaskRunner import okhttp3.internal.http2.Http2 import okhttp3.internal.platform.Android10Platform import okhttp3.internal.platform.AndroidPlatform import okhttp3.internal.platform.Platform import okhttp3.logging.LoggingEventListener import okhttp3.testing.PlatformRule import okhttp3.tls.HandshakeCertificates import okhttp3.tls.internal.TlsUtil.localhost import okio.ByteString.Companion.toByteString import org.bouncycastle.jce.provider.BouncyCastleProvider import org.bouncycastle.jsse.provider.BouncyCastleJsseProvider import org.conscrypt.Conscrypt import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Assertions.fail import org.junit.jupiter.api.Assumptions.assumeTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.api.extension.RegisterExtension import org.opentest4j.TestAbortedException import java.io.IOException import java.net.InetAddress import java.net.UnknownHostException import java.security.KeyStore import java.security.SecureRandom import java.security.Security import java.security.cert.Certificate import java.security.cert.CertificateException import java.security.cert.X509Certificate import java.util.concurrent.atomic.AtomicInteger import java.util.logging.Handler import java.util.logging.Level import java.util.logging.LogRecord import java.util.logging.Logger import javax.net.ssl.HostnameVerifier import javax.net.ssl.SSLPeerUnverifiedException import javax.net.ssl.SSLSocket import javax.net.ssl.TrustManagerFactory import javax.net.ssl.X509TrustManager /** * Run with "./gradlew :android-test:connectedCheck" and make sure ANDROID_SDK_ROOT is set. */ @ExtendWith(MockWebServerExtension::class) @Tag("Slow") class OkHttpTest(val server: MockWebServer) { @Suppress("RedundantVisibilityModifier") @JvmField @RegisterExtension public val platform = PlatformRule() @Suppress("RedundantVisibilityModifier") @JvmField @RegisterExtension public val clientTestRule = OkHttpClientTestRule().apply { logger = Logger.getLogger(OkHttpTest::class.java.name) } private var client: OkHttpClient = clientTestRule.newClient() private val moshi = Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() private val handshakeCertificates = localhost() @Test fun testPlatform() { assertTrue(Platform.isAndroid) if (Build.VERSION.SDK_INT >= 29) { assertTrue(Platform.get() is Android10Platform) } else { assertTrue(Platform.get() is AndroidPlatform) } } @Test fun testRequest() { assumeNetwork() val request = Request.Builder().url("https://api.twitter.com/robots.txt").build() val clientCertificates = HandshakeCertificates.Builder() .addPlatformTrustedCertificates() .apply { if (Build.VERSION.SDK_INT >= 24) { addInsecureHost(server.hostName) } } .build() client = client.newBuilder() .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager) .build() val response = client.newCall(request).execute() response.use { assertEquals(200, response.code) } if (Build.VERSION.SDK_INT >= 24) { localhostInsecureRequest(); } } @Test fun testRequestWithSniRequirement() { assumeNetwork() val request = Request.Builder().url("https://docs.fabric.io/android/changelog.html").build() val response = client.newCall(request).execute() response.use { assertEquals(200, response.code) } } @Test fun testConscryptRequest() { assumeNetwork() try { Security.insertProviderAt(Conscrypt.newProviderBuilder().build(), 1) val request = Request.Builder().url("https://facebook.com/robots.txt").build() var socketClass: String? = null val clientCertificates = HandshakeCertificates.Builder() .addPlatformTrustedCertificates() .addInsecureHost(server.hostName) .build() // Need fresh client to reset sslSocketFactoryOrNull client = OkHttpClient.Builder() .eventListenerFactory(clientTestRule.wrap(object : EventListener() { override fun connectionAcquired(call: Call, connection: Connection) { socketClass = connection.socket().javaClass.name } })) .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager) .build() val response = client.newCall(request).execute() response.use { assertEquals(Protocol.HTTP_2, response.protocol) assertEquals(200, response.code) // see https://github.com/google/conscrypt/blob/b9463b2f74df42d85c73715a5f19e005dfb7b802/android/src/main/java/org/conscrypt/Platform.java#L613 when { Build.VERSION.SDK_INT >= 24 -> { // Conscrypt 2.5+ defaults to SSLEngine-based SSLSocket assertEquals("org.conscrypt.Java8EngineSocket", socketClass) } Build.VERSION.SDK_INT < 22 -> { assertEquals("org.conscrypt.KitKatPlatformOpenSSLSocketImplAdapter", socketClass) } else -> { assertEquals("org.conscrypt.ConscryptFileDescriptorSocket", socketClass) } } assertEquals(TlsVersion.TLS_1_3, response.handshake?.tlsVersion) } localhostInsecureRequest(); } finally { Security.removeProvider("Conscrypt") client.close() } } @Test fun testRequestUsesPlayProvider() { assumeNetwork() try { try { ProviderInstaller.installIfNeeded(InstrumentationRegistry.getInstrumentation().targetContext) } catch (gpsnae: GooglePlayServicesNotAvailableException) { throw TestAbortedException("Google Play Services not available", gpsnae) } val clientCertificates = HandshakeCertificates.Builder() .addPlatformTrustedCertificates() .addInsecureHost(server.hostName) .build() val request = Request.Builder().url("https://facebook.com/robots.txt").build() var socketClass: String? = null // Need fresh client to reset sslSocketFactoryOrNull client = OkHttpClient.Builder() .eventListenerFactory(clientTestRule.wrap(object : EventListener() { override fun connectionAcquired(call: Call, connection: Connection) { socketClass = connection.socket().javaClass.name } })) .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager) .build() val response = client.newCall(request).execute() response.use { assertEquals(Protocol.HTTP_2, response.protocol) assertEquals(200, response.code) assertEquals("com.google.android.gms.org.conscrypt.Java8FileDescriptorSocket", socketClass) assertEquals(TlsVersion.TLS_1_2, response.handshake?.tlsVersion) } localhostInsecureRequest(); } finally { Security.removeProvider("GmsCore_OpenSSL") client.close() } } private fun localhostInsecureRequest() { server.useHttps(handshakeCertificates.sslSocketFactory(), false) server.enqueue(MockResponse().setResponseCode(200)) val request = Request.Builder().url(server.url("/")).build() client.newCall(request).execute().use { assertEquals(200, it.code) assertEquals(listOf<Certificate>(), it.handshake?.peerCertificates) } } @Test fun testRequestUsesAndroidConscrypt() { assumeNetwork() val request = Request.Builder().url("https://facebook.com/robots.txt").build() var socketClass: String? = null val clientCertificates = HandshakeCertificates.Builder() .addPlatformTrustedCertificates().apply { if (Build.VERSION.SDK_INT >= 24) { addInsecureHost(server.hostName) } } .build() client = client.newBuilder() .eventListenerFactory(clientTestRule.wrap(object : EventListener() { override fun connectionAcquired(call: Call, connection: Connection) { socketClass = connection.socket().javaClass.name } })) .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager) .build() val response = client.newCall(request).execute() response.use { assertEquals(Protocol.HTTP_2, response.protocol) if (Build.VERSION.SDK_INT >= 29) { assertEquals(TlsVersion.TLS_1_3, response.handshake?.tlsVersion) } else { assertEquals(TlsVersion.TLS_1_2, response.handshake?.tlsVersion) } assertEquals(200, response.code) assertTrue(socketClass?.startsWith("com.android.org.conscrypt.") == true) } if (Build.VERSION.SDK_INT >= 24) { localhostInsecureRequest(); } } @Test fun testHttpRequestNotBlockedOnLegacyAndroid() { assumeTrue(Build.VERSION.SDK_INT < 23) val request = Request.Builder().url("http://squareup.com/robots.txt").build() val response = client.newCall(request).execute() response.use { assertEquals(200, response.code) } } @Test @Disabled("cleartext required for additional okhttp wide tests") fun testHttpRequestBlocked() { assumeTrue(Build.VERSION.SDK_INT >= 23) val request = Request.Builder().url("http://squareup.com/robots.txt").build() try { client.newCall(request).execute() fail<Any>("expected cleartext blocking") } catch (_: java.net.UnknownServiceException) { } } data class HowsMySslResults( val unknown_cipher_suite_supported: Boolean, val beast_vuln: Boolean, val session_ticket_supported: Boolean, val tls_compression_supported: Boolean, val ephemeral_keys_supported: Boolean, val rating: String, val tls_version: String, val able_to_detect_n_minus_one_splitting: Boolean, val insecure_cipher_suites: Map<String, List<String>>, val given_cipher_suites: List<String>? ) @Test @Disabled fun testSSLFeatures() { assumeNetwork() val request = Request.Builder().url("https://www.howsmyssl.com/a/check").build() val response = client.newCall(request).execute() val results = response.use { moshi.adapter(HowsMySslResults::class.java).fromJson(response.body!!.string())!! } Platform.get().log("results $results", Platform.WARN) assertTrue(results.session_ticket_supported) assertEquals("Probably Okay", results.rating) // TODO map to expected versions automatically, test ignored for now. Run manually. assertEquals("TLS 1.3", results.tls_version) assertEquals(0, results.insecure_cipher_suites.size) assertEquals(TlsVersion.TLS_1_3, response.handshake?.tlsVersion) assertEquals(Protocol.HTTP_2, response.protocol) } @Test fun testMockWebserverRequest() { enableTls() server.enqueue(MockResponse().setBody("abc")) val request = Request.Builder().url(server.url("/")).build() val response = client.newCall(request).execute() response.use { assertEquals(200, response.code) assertEquals(Protocol.HTTP_2, response.protocol) val tlsVersion = response.handshake?.tlsVersion assertTrue(tlsVersion == TlsVersion.TLS_1_2 || tlsVersion == TlsVersion.TLS_1_3) assertEquals("CN=localhost", (response.handshake!!.peerCertificates.first() as X509Certificate).subjectDN.name) } } @Test fun testCertificatePinningFailure() { enableTls() val certificatePinner = CertificatePinner.Builder() .add(server.hostName, "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") .build() client = client.newBuilder().certificatePinner(certificatePinner).build() server.enqueue(MockResponse().setBody("abc")) val request = Request.Builder().url(server.url("/")).build() try { client.newCall(request).execute() fail<Any>("") } catch (_: SSLPeerUnverifiedException) { } } @Test fun testCertificatePinningSuccess() { enableTls() val certificatePinner = CertificatePinner.Builder() .add(server.hostName, CertificatePinner.pin(handshakeCertificates.trustManager.acceptedIssuers[0])) .build() client = client.newBuilder().certificatePinner(certificatePinner).build() server.enqueue(MockResponse().setBody("abc")) val request = Request.Builder().url(server.url("/")).build() val response = client.newCall(request).execute() response.use { assertEquals(200, response.code) } } @Test fun testEventListener() { val eventListener = RecordingEventListener() enableTls() client = client.newBuilder().eventListenerFactory(clientTestRule.wrap(eventListener)).build() server.enqueue(MockResponse().setBody("abc1")) server.enqueue(MockResponse().setBody("abc2")) val request = Request.Builder().url(server.url("/")).build() client.newCall(request).execute().use { response -> assertEquals(200, response.code) } assertEquals(listOf("CallStart", "ProxySelectStart", "ProxySelectEnd", "DnsStart", "DnsEnd", "ConnectStart", "SecureConnectStart", "SecureConnectEnd", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"), eventListener.recordedEventTypes()) eventListener.clearAllEvents() client.newCall(request).execute().use { response -> assertEquals(200, response.code) } assertEquals(listOf("CallStart", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"), eventListener.recordedEventTypes()) } @Test fun testSessionReuse() { val sessionIds = mutableListOf<String>() enableTls() client = client.newBuilder().eventListenerFactory(clientTestRule.wrap(object : EventListener() { override fun connectionAcquired(call: Call, connection: Connection) { val sslSocket = connection.socket() as SSLSocket sessionIds.add(sslSocket.session.id.toByteString().hex()) } })).build() server.enqueue(MockResponse().setBody("abc1")) server.enqueue(MockResponse().setBody("abc2")) val request = Request.Builder().url(server.url("/")).build() client.newCall(request).execute().use { response -> assertEquals(200, response.code) } client.connectionPool.evictAll() assertEquals(0, client.connectionPool.connectionCount()) client.newCall(request).execute().use { response -> assertEquals(200, response.code) } assertEquals(2, sessionIds.size) assertEquals(sessionIds[0], sessionIds[1]) } @Test fun testDnsOverHttps() { assumeNetwork() client = client.newBuilder() .eventListenerFactory(clientTestRule.wrap(LoggingEventListener.Factory())) .build() val dohDns = buildCloudflareIp(client) val dohEnabledClient = client.newBuilder().eventListenerFactory(EventListener.NONE.asFactory()).dns(dohDns).build() dohEnabledClient.get("https://www.twitter.com/robots.txt") dohEnabledClient.get("https://www.facebook.com/robots.txt") } @Test fun testCustomTrustManager() { assumeNetwork() val trustManager = object : X509TrustManager { override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {} override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {} override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf() } val sslContext = Platform.get().newSSLContext().apply { init(null, arrayOf(trustManager), null) } val sslSocketFactory = sslContext.socketFactory val hostnameVerifier = HostnameVerifier { _, _ -> true } client = client.newBuilder() .sslSocketFactory(sslSocketFactory, trustManager) .hostnameVerifier(hostnameVerifier) .build() client.get("https://www.facebook.com/robots.txt") } @Test fun testCustomTrustManagerWithAndroidCheck() { assumeNetwork() var withHostCalled = false var withoutHostCalled = false val trustManager = object : X509TrustManager { override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {} override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) { withoutHostCalled = true } @Suppress("unused", "UNUSED_PARAMETER") // called by Android via reflection in X509TrustManagerExtensions fun checkServerTrusted(chain: Array<out X509Certificate>, authType: String, hostname: String): List<X509Certificate> { withHostCalled = true return chain.toList() } override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf() } val sslContext = Platform.get().newSSLContext().apply { init(null, arrayOf(trustManager), null) } val sslSocketFactory = sslContext.socketFactory val hostnameVerifier = HostnameVerifier { _, _ -> true } client = client.newBuilder() .sslSocketFactory(sslSocketFactory, trustManager) .hostnameVerifier(hostnameVerifier) .build() client.get("https://www.facebook.com/robots.txt") if (Build.VERSION.SDK_INT < 24) { assertFalse(withHostCalled) assertTrue(withoutHostCalled) } else { assertTrue(withHostCalled) assertFalse(withoutHostCalled) } } @Test fun testUnderscoreRequest() { assumeNetwork() val request = Request.Builder().url("https://example_underscore_123.s3.amazonaws.com/").build() try { client.newCall(request).execute().close() // Hopefully this passes } catch (ioe: IOException) { // https://github.com/square/okhttp/issues/5840 when (ioe.cause) { is IllegalArgumentException -> { assertEquals("Android internal error", ioe.message) } is CertificateException -> { assertTrue(ioe.cause?.cause is IllegalArgumentException) assertEquals(true, ioe.cause?.cause?.message?.startsWith("Invalid input to toASCII")) } else -> throw ioe } } } @Test @Disabled("breaks conscrypt test") fun testBouncyCastleRequest() { assumeNetwork() try { Security.insertProviderAt(BouncyCastleProvider(), 1) Security.insertProviderAt(BouncyCastleJsseProvider(), 2) var socketClass: String? = null val trustManager = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply { init(null as KeyStore?) }.trustManagers.first() as X509TrustManager val sslContext = Platform.get().newSSLContext().apply { // TODO remove most of this code after https://github.com/bcgit/bc-java/issues/686 init(null, arrayOf(trustManager), SecureRandom()) } client = client.newBuilder() .sslSocketFactory(sslContext.socketFactory, trustManager) .eventListenerFactory(clientTestRule.wrap(object : EventListener() { override fun connectionAcquired(call: Call, connection: Connection) { socketClass = connection.socket().javaClass.name } })) .build() val request = Request.Builder().url("https://facebook.com/robots.txt").build() val response = client.newCall(request).execute() response.use { assertEquals(Protocol.HTTP_2, response.protocol) assertEquals(200, response.code) assertEquals("org.bouncycastle.jsse.provider.ProvSSLSocketWrap", socketClass) assertEquals(TlsVersion.TLS_1_2, response.handshake?.tlsVersion) } } finally { Security.removeProvider("BCJSSE") Security.removeProvider("BC") } } @Test @Disabled("TODO: currently logging okhttp3.internal.concurrent.TaskRunner, okhttp3.internal.http2.Http2") fun testLoggingLevels() { enableTls() val testHandler = object : Handler() { val calls = mutableMapOf<String, AtomicInteger>() override fun publish(record: LogRecord) { calls.getOrPut(record.loggerName) { AtomicInteger(0) } .incrementAndGet() } override fun flush() { } override fun close() { } }.apply { level = Level.FINEST } Logger.getLogger("") .addHandler(testHandler) Logger.getLogger("okhttp3") .addHandler(testHandler) Logger.getLogger(Http2::class.java.name) .addHandler(testHandler) Logger.getLogger(TaskRunner::class.java.name) .addHandler(testHandler) Logger.getLogger(OkHttpClient::class.java.name) .addHandler(testHandler) server.enqueue(MockResponse().setBody("abc")) val request = Request.Builder() .url(server.url("/")) .build() val response = client.newCall(request) .execute() response.use { assertEquals(200, response.code) assertEquals(Protocol.HTTP_2, response.protocol) } // Only logs to the test logger above // Will fail if "adb shell setprop log.tag.okhttp.Http2 DEBUG" is called assertEquals(setOf(OkHttpTest::class.java.name), testHandler.calls.keys) } fun testCachedRequest() { enableTls() server.enqueue(MockResponse().setBody("abc").addHeader("cache-control: public, max-age=3")) server.enqueue(MockResponse().setBody("abc")) val ctxt = InstrumentationRegistry.getInstrumentation().targetContext.applicationContext val cacheSize = 1L * 1024 * 1024 // 1MB val cache = Cache(ctxt.cacheDir.resolve("testCache"), cacheSize) try { client = client.newBuilder() .cache(cache) .build() val request = Request.Builder() .url(server.url("/")) .build() client.newCall(request) .execute() .use { assertEquals(200, it.code) assertNull(it.cacheResponse) assertNotNull(it.networkResponse) assertEquals(3, it.cacheControl.maxAgeSeconds) assertTrue(it.cacheControl.isPublic) } client.newCall(request) .execute() .use { assertEquals(200, it.code) assertNotNull(it.cacheResponse) assertNull(it.networkResponse) } assertEquals(1, cache.hitCount()) assertEquals(1, cache.networkCount()) assertEquals(2, cache.requestCount()) } finally { cache.delete() } } private fun OkHttpClient.get(url: String) { val request = Request.Builder().url(url).build() val response = this.newCall(request).execute() response.use { assertEquals(200, response.code) } } fun buildCloudflareIp(bootstrapClient: OkHttpClient): DnsOverHttps { return DnsOverHttps.Builder().client(bootstrapClient) .url("https://1.1.1.1/dns-query".toHttpUrl()) .build() } private fun enableTls() { client = client.newBuilder() .sslSocketFactory( handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager) .build() server.useHttps(handshakeCertificates.sslSocketFactory(), false) } private fun assumeNetwork() { try { InetAddress.getByName("www.google.com") } catch (uhe: UnknownHostException) { throw TestAbortedException(uhe.message, uhe) } } fun OkHttpClient.close() { dispatcher.executorService.shutdown() connectionPool.evictAll() } }
android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt
1711151353
package ademar.goodreads.ui.common.holder import androidx.annotation.IdRes import androidx.annotation.LayoutRes import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlin.reflect.KProperty abstract class BaseHolder<T>(parent: ViewGroup?, @LayoutRes layout: Int) : RecyclerView.ViewHolder(LayoutInflater.from(parent?.context).inflate(layout, parent, false)) { abstract fun bind(item: T) class BindView<V : View>(@IdRes val id: Int) { @Suppress("UNCHECKED_CAST") operator fun getValue(thisRef: BaseHolder<*>, property: KProperty<*>): V { return thisRef.itemView.findViewById(id) as V } operator fun setValue(thisRef: BaseHolder<*>, property: KProperty<*>, value: V) { } } }
app/src/main/java/ademar/goodreads/ui/common/holder/BaseHolder.kt
1539238071
/******************************************************************************* * 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])) } }
application/vlc-android/test/org/videolan/vlc/repository/ExternalSubRepositoryTest.kt
770108197
package net.milosvasic.pussycat.android.application import net.milosvasic.pussycat.application.APPLICATION_TYPE class ApplicationTestNoParams : ApplicationTestAbstract() { init { params = arrayOf<String>() expectedType = APPLICATION_TYPE.GUI } }
Android/src/test/kotlin/net/milosvasic/pussycat/android/application/ApplicationTestNoParams.kt
2749144646
/* * 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.")) } }
src/chrislo27/discordbot/cmd/impl/ServerLockdownCommand.kt
2483697014
/* * 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 } }
buildSrc/src/main/kotlin/io/spine/internal/dependency/LicenseReport.kt
2825143059
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 } }
deprecated/MVI/MVI101/MVI_Client/app/src/main/java/ca/six/mvi/biz/home/HomeModel.kt
459035014
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) } }
Android/dokit-mc/src/main/java/com/didichuxing/doraemonkit/kit/mc/oldui/host/HostDoKitView.kt
811307548
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) } }
src/main/kotlin/com/github/pgutkowski/kgraphql/schema/dsl/PropertyDSL.kt
910253929
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) }
src/main/kotlin/com/klask/urlfor.kt
3207721040
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) } } } }
detekt-gradle-plugin/src/main/kotlin/io/gitlab/arturbosch/detekt/report/XmlReportMerger.kt
1425531586
/* * 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 } } }
app/src/main/java/com/ofalvai/bpinfo/notifications/NotificationMaker.kt
2977715890
package net.nemerosa.ontrack.extension.elastic.metrics import net.nemerosa.ontrack.it.AbstractDSLTestSupport import net.nemerosa.ontrack.json.asJson import net.nemerosa.ontrack.json.parse import net.nemerosa.ontrack.model.structure.RunInfoInput import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.TestPropertySource import kotlin.test.assertEquals import kotlin.test.assertNull @TestPropertySource( properties = [ "ontrack.extension.elastic.metrics.enabled=true", "ontrack.extension.elastic.metrics.index.immediate=true", "management.metrics.export.elastic.enabled=false", ] ) class ElasticMetricsRunInfoListenerIT : AbstractDSLTestSupport() { @Autowired private lateinit var elasticMetricsClient: ElasticMetricsClient @Test fun `Export of run info for a build`() { project { branch { build { runInfoService.setRunInfo( this, RunInfoInput( runTime = 50, ) ) // Checks the metric has been exported into ES val results = elasticMetricsClient.rawSearch( token = project.name ) // Expecting only one result assertEquals(1, results.items.size, "One metric registered") val result = results.items.first() val source = result.source.asJson() val ecs = source.parse<ECSEntry>() assertEquals( mapOf("value" to 50.0), ecs.ontrack ) assertEquals( mapOf( "project" to project.name, "branch" to branch.name, ), ecs.labels ) assertNull(ecs.tags) assertEquals( ECSEvent( kind = ECSEventKind.metric, category = "ontrack_run_build_time_seconds", ), ecs.event ) } } } } @Test fun `Export of run info for a validation`() { project { branch { val vs = validationStamp() build { validate(vs).apply { runInfoService.setRunInfo( this, RunInfoInput( runTime = 50, ) ) // Checks the metric has been exported into ES val results = elasticMetricsClient.rawSearch( token = this.validationStamp.name, ) // Expecting only one result assertEquals(1, results.items.size, "One metric registered") val result = results.items.first() val source = result.source.asJson() val ecs = source.parse<ECSEntry>() assertEquals( mapOf("value" to 50.0), ecs.ontrack ) assertEquals( mapOf( "project" to project.name, "branch" to branch.name, "validationStamp" to validationStamp.name, "status" to "PASSED", ), ecs.labels ) assertNull(ecs.tags) assertEquals( ECSEvent( kind = ECSEventKind.metric, category = "ontrack_run_validation_run_time_seconds", ), ecs.event ) } } } } } }
ontrack-extension-elastic/src/test/java/net/nemerosa/ontrack/extension/elastic/metrics/ElasticMetricsRunInfoListenerIT.kt
1685589794
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.common.dao import com.mycollab.common.domain.criteria.CommentSearchCriteria import com.mycollab.db.persistence.ISearchableDAO /** * @author MyCollab Ltd. * @since 1.0 */ interface CommentMapperExt : ISearchableDAO<CommentSearchCriteria>
mycollab-services/src/main/java/com/mycollab/common/dao/CommentMapperExt.kt
3943554361
package net.nemerosa.ontrack.extension.git.support import net.nemerosa.ontrack.extension.git.AbstractGitTestJUnit4Support import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull class GitCommitPropertyCommitLinkIT : AbstractGitTestJUnit4Support() { @Test(expected = NoGitCommitPropertyException::class) fun `Commit from build without property`() { withRepo { repo -> project { gitProject(repo) branch { gitBranch { commitAsProperty() } val link = gitService.getBranchConfiguration(this)!!.buildCommitLink!! build("1") { link.getCommitFromBuild(this) } } } } } @Test fun `Commit from build with property`() { createRepo { commits(1) } and { repo, commits -> project { gitProject(repo) branch { gitBranch { commitAsProperty() } val link = gitService.getBranchConfiguration(this)!!.buildCommitLink!! build("1") { gitCommitProperty(commits[1]!!) val commit = link.getCommitFromBuild(this) assertEquals( commits[1], commit ) } } } } } @Test fun `Issue search on one branch`() { createRepo { commits(10) } and { repo, commits -> project { gitProject(repo) branch { gitBranch { commitAsProperty() } mapOf("1.0" to 3, "1.1" to 6).forEach { name, commitIndex -> build(name) { gitCommitProperty(commits.getValue(commitIndex)) } } } // Gets commit info val commitInfo = asUserWithView(this).call { gitService.getCommitProjectInfo(id, commits.getValue(4)) } assertNotNull(commitInfo) { assertEquals( commits[4], it.uiCommit.commit.id ) assertEquals( "Commit 4", it.uiCommit.annotatedMessage ) } } } } }
ontrack-extension-git/src/test/java/net/nemerosa/ontrack/extension/git/support/GitCommitPropertyCommitLinkIT.kt
1005767398
package com.chimbori.crux.articles import com.chimbori.crux.common.fromFile import okhttp3.HttpUrl.Companion.toHttpUrl import org.junit.Assert.assertEquals import org.junit.Test class ArticleExtractorTest { @Test fun testRetainSpaceInsideTags() { val As = "aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa" val Bs = "bbb bbb bbb bbb bbb bbb bbb bbb bbb bbb bbb bbb bbb bbb bbb bbb bbb bbb bbb bbb bbb bbb" val Cs = "ccc ccc ccc ccc ccc ccc ccc ccc ccc ccc ccc ccc ccc ccc ccc ccc ccc ccc ccc ccc ccc ccc" var article = ArticleExtractor(EXAMPLE_URL, "<html><body><div> $As <p> $Bs</p>$Cs </div></body></html>") .extractContent().article assertEquals(3, article.document?.childNodeSize()) assertEquals(As, article.document?.childNode(0)?.outerHtml()?.trim { it <= ' ' }) assertEquals("<p>$Bs</p>", article.document?.childNode(1)?.outerHtml()?.trim { it <= ' ' }) assertEquals(Cs, article.document?.childNode(2)?.outerHtml()?.trim { it <= ' ' }) article = ArticleExtractor(EXAMPLE_URL, "<html><body><div> $As <p>$Bs </p>$Cs</div></body></html>") .extractContent().article assertEquals(3, article.document?.childNodeSize()) assertEquals(As, article.document?.childNode(0)?.outerHtml()?.trim { it <= ' ' }) assertEquals("<p>$Bs</p>", article.document?.childNode(1)?.outerHtml()?.trim { it <= ' ' }) assertEquals(Cs, article.document?.childNode(2)?.outerHtml()?.trim { it <= ' ' }) article = ArticleExtractor(EXAMPLE_URL, "<html><body><div> $As <p> $Bs </p>$Cs</div></body></html>") .extractContent().article assertEquals(3, article.document?.childNodeSize()) assertEquals(As, article.document?.childNode(0)?.outerHtml()?.trim { it <= ' ' }) assertEquals("<p>$Bs</p>", article.document?.childNode(1)?.outerHtml()?.trim { it <= ' ' }) assertEquals(Cs, article.document?.childNode(2)?.outerHtml()?.trim { it <= ' ' }) } @Test fun testThatHiddenTextIsNotExtracted() { ArticleExtractor( EXAMPLE_URL, """<div style="margin: 5px; display:none; padding: 5px;"> |Hidden Text |</div> |<div style="margin: 5px; display:block; padding: 5px;"> |Visible Text that has to be longer than X characters so it’s not stripped out for being too short. |</div> |<div>Default Text</div> |""".trimMargin() ).extractContent().article.run { assertEquals( "Visible Text that has to be longer than X characters so it’s not stripped out for being too short.", document?.text() ) } } @Test fun testThatLongerTextIsPreferred() { ArticleExtractor( EXAMPLE_URL, """<div style="margin: 5px; display:none; padding: 5px;"> |Hidden Text |</div> |<div style="margin: 5px; display:block; padding: 5px;"> |Visible Text that’s still longer than our minimum text size limits |</div> |<div> |Default Text but longer that’s still longer than our minimum text size limits |</div> |""".trimMargin() ).extractContent().article.run { assertEquals("Default Text but longer that’s still longer than our minimum text size limits", document?.text()) } } @Test fun testThatShortTextIsDiscarded() { ArticleExtractor( EXAMPLE_URL, """<div> |Default Text but longer that’s still longer than our minimum text size limits |<div>short text</div> |</div>""".trimMargin() ).extractContent().article.run { assertEquals("Default Text but longer that’s still longer than our minimum text size limits", document?.text()) } } @Test fun testThatImportantShortTextIsRetained() { ArticleExtractor( EXAMPLE_URL, """<div> |Default Text but longer that’s still longer than our minimum text size limits |<div crux-keep>short text</div> |</div>""".trimMargin() ).extractContent().article.run { assertEquals( "Default Text but longer that’s still longer than our minimum text size limits short text", document?.text() ) } } @Test fun testReadingTimeEstimates() { fromFile( "https://www.washingtonpost.com/lifestyle/style/the-nearly-forgotten-story-of-the-black-women-who-helped-land-a-man-on-the-moon/2016/09/12/95f2d356-7504-11e6-8149-b8d05321db62_story.html".toHttpUrl(), "washingtonpost.html" ).run { assertEquals(8, estimatedReadingTimeMinutes) } fromFile("https://en.wikipedia.org/wiki/Galileo_Galilei".toHttpUrl(), "wikipedia_galileo.html").run { assertEquals(53, estimatedReadingTimeMinutes) } } companion object { private val EXAMPLE_URL = "http://example.com/".toHttpUrl() } }
src/test/kotlin/com/chimbori/crux/articles/ArticleExtractorTest.kt
1395245717
package org.rust.lang.core.completion class RsDeriveCompletionProviderTest : RsCompletionTestBase() { fun testCompleteOnStruct() = checkSingleCompletion("PartialEq", """ #[derive(PartialE/*caret*/)] struct Test { foo: u8 } """) fun testCompleteOnEnum() = checkSingleCompletion("PartialEq", """ #[derive(PartialE/*caret*/)] enum Test { Something } """) fun testDoesntCompleteOnFn() = checkNoCompletion(""" #[foo(PartialE/*caret*/)] fn foo() { } """) fun testDoesntCompleteOnMod() = checkNoCompletion(""" #[foo(PartialE/*caret*/)] mod foo { } """) fun testDoesntCompleteNonDeriveAttr() = checkNoCompletion(""" #[foo(PartialE/*caret*/)] enum Test { Something } """) fun testDoesntCompleteInnerAttr() = checkNoCompletion(""" mod bar { #![derive(PartialE/*caret*/)] } """) fun testDoesntCompleteAlreadyDerived() = checkNoCompletion(""" #[derive(PartialEq, PartialE/*caret*/)] enum Test { Something } """) }
src/test/kotlin/org/rust/lang/core/completion/RsDeriveCompletionProviderTest.kt
3394692792
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
frontend/src/hu/nevermind/common/JQueryExt.kt
2490788508
/* * Copyright (c) 2021 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.xml.builder import net.mm2d.xml.node.XmlTextNode class XmlTextNodeBuilder( value: String ) : XmlNodeBuilder { private val valueBuilder = StringBuilder(value) override var parent: XmlElementBuilder? = null val value: String get() = valueBuilder.toString() fun appendText(text: String) { valueBuilder.append(text) } override fun build(removeIgnorableWhitespace: Boolean): XmlTextNode = XmlTextNode(value) }
xml/src/main/java/net/mm2d/xml/builder/XmlTextNodeBuilder.kt
1347455968
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.lang.psi.mixins.impl import com.demonwav.mcdev.nbt.lang.psi.mixins.NbttDoubleMixin import com.demonwav.mcdev.nbt.tags.TagDouble import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import org.apache.commons.lang3.StringUtils abstract class NbttDoubleImplMixin(node: ASTNode) : ASTWrapperPsiElement(node), NbttDoubleMixin { override fun getDoubleTag(): TagDouble { return TagDouble(StringUtils.replaceChars(text.trim(), "dD", null).toDouble()) } }
src/main/kotlin/nbt/lang/psi/mixins/impl/NbttDoubleImplMixin.kt
2480137251
package io.mockk.proxy.common.transformation import io.mockk.proxy.MockKAgentLogger import java.lang.instrument.UnmodifiableClassException abstract class RetransformInlineInstrumentation( protected val log: MockKAgentLogger, private val specMap: ClassTransformationSpecMap ) : InlineInstrumentation { protected abstract fun retransform(classesToTransform: Collection<Class<*>>) override fun execute(request: TransformationRequest): () -> Unit { var cancellation: (() -> Unit)? = null try { specMap.applyTransformation(request) { cancellation = { doCancel(request) } retransform(it.classes) } } catch (ex: java.lang.Exception) { log.warn(ex, "Failed to transform classes ${request.classes}") cancellation?.invoke() return {} } return cancellation ?: {} } private fun doCancel(request: TransformationRequest) { try { specMap.applyTransformation( request.reverse() ) { val classes = it.classes if (classes.isNotEmpty()) { log.trace("Retransforming back ${it.classes}") retransform(classes) } } } catch (ex: UnmodifiableClassException) { log.warn(ex, "Failed to revert class transformation ${request.classes}") } } }
modules/mockk-agent-api/src/jvmMain/kotlin/io/mockk/proxy/common/transformation/RetransformInlineInstrumentation.kt
588191335
package com.hedvig.botService.serviceIntegration.underwriter import feign.RequestInterceptor import feign.RequestTemplate import org.springframework.stereotype.Component import org.springframework.web.context.request.RequestContextHolder import org.springframework.web.context.request.ServletRequestAttributes @Component class UserAgentHeaderInterceptor : RequestInterceptor { private val userAgentHeader = "User-Agent" override fun apply(template: RequestTemplate?) { val requestAttributes = RequestContextHolder.getRequestAttributes() as ServletRequestAttributes? ?: return val request = requestAttributes.request val language = request.getHeader(userAgentHeader) ?: return template?.header(userAgentHeader, language) } }
src/main/java/com/hedvig/botService/serviceIntegration/underwriter/UseragenHeaderInterceptor.kt
3201227899
/* * 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 } } }
src/main/kotlin/de/jfachwert/pruefung/Mod97Verfahren.kt
3454991106
/** * 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() }
korge-dragonbones/src/commonMain/kotlin/com/dragonbones/parser/ObjectDataParser.kt
265678194
package app.cash.sqldelight.integration import app.cash.sqldelight.db.SqlDriver import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver.Companion.IN_MEMORY import java.util.concurrent.Executors import java.util.concurrent.Future import java.util.concurrent.TimeUnit actual fun createSqlDatabase(): SqlDriver { return JdbcSqliteDriver(IN_MEMORY).apply { QueryWrapper.Schema.create(this) } } actual class MPWorker actual constructor() { private val executor = Executors.newSingleThreadExecutor() actual fun <T> runBackground(backJob: () -> T): MPFuture<T> { return MPFuture(executor.submit(backJob) as Future<T>) } actual fun requestTermination() { executor.shutdown() executor.awaitTermination(30, TimeUnit.SECONDS) } } actual class MPFuture<T>(private val future: Future<T>) { actual fun consume(): T = future.get() }
sqldelight-gradle-plugin/src/test/integration-multiplatform/src/androidMain/kotlin/app/cash/sqldelight/integration/Android.kt
372323121
package app.cash.sqldelight.dialects.postgresql.grammar.mixins import app.cash.sqldelight.dialects.postgresql.grammar.psi.PostgreSqlTypeName import com.alecstrong.sql.psi.core.psi.SqlColumnDef import com.alecstrong.sql.psi.core.psi.impl.SqlColumnDefImpl import com.intellij.lang.ASTNode internal class ColumnDefMixin(node: ASTNode) : SqlColumnDefImpl(node), SqlColumnDef { override fun hasDefaultValue(): Boolean { return isSerial() || super.hasDefaultValue() } } private fun SqlColumnDef.isSerial(): Boolean { val typeName = columnType.typeName as PostgreSqlTypeName return typeName.smallSerialDataType != null || typeName.serialDataType != null || typeName.bigSerialDataType != null }
dialects/postgresql/src/main/kotlin/app/cash/sqldelight/dialects/postgresql/grammar/mixins/ColumnDefMixin.kt
3691696512
package com.uchuhimo.typeclass object ImplementShowWithOverload { fun <A> log(a: A, s: Show<A>) { println(s.show(a)) } fun log(a: String) { log(a, object : Show<String> { override fun show(f: String): String = f }) } }
lang/src/main/kotlin/com/uchuhimo/typeclass/ImplementShowWithOverload.kt
2397130756