content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Copyright (C) 2018 Dario Scoppelletti, <http://www.scoppelletti.it/>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("JoinDeclarationAndAssignment", "RedundantVisibilityModifier")
package it.scoppelletti.spaceship.widget
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import it.scoppelletti.spaceship.R
import it.scoppelletti.spaceship.toMessage
import kotlinx.parcelize.Parcelize
/**
* Default implementation of the `ExceptionItem` interface.
*
* @since 1.0.0
*
* @property className Name of the exception class.
* @property message Message.
*/
@Parcelize
public data class DefaultExceptionItem(
public val className: String,
public val message: String,
override val adapter: ExceptionAdapter<*>
) : ExceptionItem
/**
* Default implementation of the `ExceptionAdapter` interface.
*
* @since 1.0.0
*/
@Parcelize
public class DefaultExceptionAdapter : ExceptionAdapter<DefaultExceptionItem> {
override fun getView(ex: DefaultExceptionItem, parent: ViewGroup): View {
val itemView: View
val inflater: LayoutInflater
var textView: TextView
inflater = LayoutInflater.from(parent.context)
itemView = inflater.inflate(R.layout.it_scoppelletti_exception, parent,
false)
textView = itemView.findViewById(R.id.txtClass)
textView.text = ex.className
textView = itemView.findViewById(R.id.txtMessage)
textView.text = ex.message
return itemView
}
}
/**
* Default implementation of the `ExceptionMapper` interface.
*
* @since 1.0.0
*/
public class DefaultExceptionMapperHandler : ExceptionMapperHandler<Throwable> {
override fun map(ex: Throwable) : ExceptionItem =
DefaultExceptionItem(ex.javaClass.name,
ex.toMessage(), DefaultExceptionAdapter())
}
| lib/src/main/kotlin/it/scoppelletti/spaceship/widget/DefaultExceptionItem.kt | 1344282284 |
package com.quran.labs.androidquran.util
import android.content.Context
import android.content.Intent
import androidx.annotation.VisibleForTesting
import com.quran.data.core.QuranInfo
import com.quran.data.model.SuraAyah
import com.quran.data.model.audio.Qari
import com.quran.labs.androidquran.common.audio.model.QariItem
import com.quran.labs.androidquran.common.audio.util.QariUtil
import com.quran.labs.androidquran.service.AudioService
import java.io.File
import java.util.Locale
import javax.inject.Inject
import timber.log.Timber
class AudioUtils @Inject constructor(
private val quranInfo: QuranInfo,
private val quranFileUtils: QuranFileUtils,
private val qariUtil: QariUtil
) {
private val totalPages = quranInfo.numberOfPages
internal object LookAheadAmount {
const val PAGE = 1
const val SURA = 2
const val JUZ = 3
// make sure to update these when a lookup type is added
const val MIN = 1
const val MAX = 3
}
/**
* Get a list of QariItem representing the qaris to show
*
* This removes gapped qaris that have a gapless alternative if
* no files are downloaded for that qari.
*
* This list sorts gapless qaris before gapped qaris, with each
* set being alphabetically sorted.
*/
fun getQariList(context: Context): List<QariItem> {
return qariUtil.getQariList(context)
.filter {
it.isGapless || (it.hasGaplessAlternative && !haveAnyFiles(it.path))
}
.sortedWith { lhs, rhs ->
if (lhs.isGapless != rhs.isGapless) {
if (lhs.isGapless) -1 else 1
} else {
lhs.name.compareTo(rhs.name)
}
}
}
private fun haveAnyFiles(path: String): Boolean {
val basePath = quranFileUtils.audioFileDirectory()
val file = File(basePath, path)
return file.isDirectory && file.list()?.isNotEmpty() ?: false
}
fun getQariUrl(qari: Qari): String {
return qari.url + if (qari.isGapless) {
"%03d$AUDIO_EXTENSION"
} else {
"%03d%03d$AUDIO_EXTENSION"
}
}
fun getQariUrl(item: QariItem): String {
return item.url + if (item.isGapless) {
"%03d$AUDIO_EXTENSION"
} else {
"%03d%03d$AUDIO_EXTENSION"
}
}
fun getLocalQariUrl(item: QariItem): String? {
val rootDirectory = quranFileUtils.audioFileDirectory()
return if (rootDirectory == null) null else rootDirectory + item.path
}
fun getLocalQariUri(item: QariItem): String? {
val rootDirectory = quranFileUtils.audioFileDirectory()
return if (rootDirectory == null) null else
rootDirectory + item.path + File.separator + if (item.isGapless) {
"%03d$AUDIO_EXTENSION"
} else {
"%d" + File.separator + "%d" + AUDIO_EXTENSION
}
}
fun getQariDatabasePathIfGapless(item: QariItem): String? {
var databaseName = item.databaseName
if (databaseName != null) {
val path = getLocalQariUrl(item)
if (path != null) {
databaseName = path + File.separator + databaseName + DB_EXTENSION
}
}
return databaseName
}
fun getLastAyahToPlay(
startAyah: SuraAyah,
currentPage: Int,
mode: Int,
isDualPageVisible: Boolean
): SuraAyah? {
val page =
if (isDualPageVisible &&
mode == LookAheadAmount.PAGE &&
currentPage % 2 == 1
) {
// if we download page by page and we are currently in tablet mode
// and playing from the right page, get the left page as well.
currentPage + 1
} else {
currentPage
}
var pageLastSura = 114
var pageLastAyah = 6
// page < 0 - intentional, because nextPageAyah looks up the ayah on the next page
if (page > totalPages || page < 0) {
return null
}
if (mode == LookAheadAmount.SURA) {
val sura = startAyah.sura
val lastAyah = quranInfo.getNumberOfAyahs(sura)
if (lastAyah == -1) {
return null
}
return SuraAyah(sura, lastAyah)
} else if (mode == LookAheadAmount.JUZ) {
val juz = quranInfo.getJuzFromPage(page)
if (juz == 30) {
return SuraAyah(114, 6)
} else if (juz in 1..29) {
val endJuz = quranInfo.getQuarterByIndex(juz * 8)
if (pageLastSura > endJuz.sura) {
// ex between jathiya and a7qaf
return getQuarterForNextJuz(juz)
} else if (pageLastSura == endJuz.sura && pageLastAyah > endJuz.ayah) {
// ex surat al anfal
return getQuarterForNextJuz(juz)
}
return SuraAyah(endJuz.sura, endJuz.ayah)
}
} else {
val range = quranInfo.getVerseRangeForPage(page)
pageLastSura = range.endingSura
pageLastAyah = range.endingAyah
}
// page mode (fallback also from errors above)
return SuraAyah(pageLastSura, pageLastAyah)
}
private fun getQuarterForNextJuz(currentJuz: Int): SuraAyah {
return if (currentJuz < 29) {
val juz = quranInfo.getQuarterByIndex((currentJuz + 1) * 8)
SuraAyah(juz.sura, juz.ayah)
} else {
// if we're currently at the 29th juz', just return the end of the 30th.
SuraAyah(114, 6)
}
}
fun shouldDownloadBasmallah(
baseDirectory: String,
start: SuraAyah,
end: SuraAyah,
isGapless: Boolean
): Boolean {
if (isGapless) {
return false
}
if (baseDirectory.isNotEmpty()) {
var f = File(baseDirectory)
if (f.exists()) {
val filename = 1.toString() + File.separator + 1 + AUDIO_EXTENSION
f = File(baseDirectory + File.separator + filename)
if (f.exists()) {
Timber.d("already have basmalla...")
return false
}
} else {
f.mkdirs()
}
}
return doesRequireBasmallah(start, end)
}
@VisibleForTesting
fun doesRequireBasmallah(minAyah: SuraAyah, maxAyah: SuraAyah): Boolean {
Timber.d("seeing if need basmalla...")
for (i in minAyah.sura..maxAyah.sura) {
val firstAyah: Int = if (i == minAyah.sura) {
minAyah.ayah
} else {
1
}
if (firstAyah == 1 && i != 1 && i != 9) {
return true
}
}
return false
}
fun haveAllFiles(
baseUrl: String,
path: String,
start: SuraAyah,
end: SuraAyah,
isGapless: Boolean
): Boolean {
if (path.isEmpty()) {
return false
}
var f = File(path)
if (!f.exists()) {
f.mkdirs()
return false
}
val startSura = start.sura
val startAyah = start.ayah
val endSura = end.sura
val endAyah = end.ayah
if (endSura < startSura || endSura == startSura && endAyah < startAyah) {
throw IllegalStateException(
"End isn't larger than the start: $startSura:$startAyah to $endSura:$endAyah"
)
}
for (i in startSura..endSura) {
val lastAyah = if (i == endSura) {
endAyah
} else {
quranInfo.getNumberOfAyahs(i)
}
val firstAyah = if (i == startSura) {
startAyah
} else {
1
}
if (isGapless) {
if (i == endSura && endAyah == 0) {
continue
}
val fileName = String.format(Locale.US, baseUrl, i)
Timber.d("gapless, checking if we have %s", fileName)
f = File(fileName)
if (!f.exists()) {
return false
}
continue
}
Timber.d("not gapless, checking each ayah...")
for (j in firstAyah..lastAyah) {
val filename = i.toString() + File.separator + j + AUDIO_EXTENSION
f = File(path + File.separator + filename)
if (!f.exists()) {
return false
}
}
}
return true
}
fun getAudioIntent(context: Context, action: String): Intent {
return Intent(context, AudioService::class.java).apply {
setAction(action)
}
}
companion object {
const val ZIP_EXTENSION = ".zip"
const val AUDIO_EXTENSION = ".mp3"
private const val DB_EXTENSION = ".db"
}
}
| app/src/main/java/com/quran/labs/androidquran/util/AudioUtils.kt | 3501923249 |
package com.quran.page.common.data.coordinates
import android.graphics.RectF
import com.quran.data.model.AyahGlyph
data class GlyphCoords(
val glyph: AyahGlyph,
val line: Int,
val bounds: RectF
)
| common/pages/src/main/java/com/quran/page/common/data/coordinates/GlyphCoords.kt | 3698466627 |
/*
* Copyright 2019 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.clouddriver.saga.models
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.google.common.annotations.VisibleForTesting
import com.netflix.spinnaker.clouddriver.saga.SagaCommand
import com.netflix.spinnaker.clouddriver.saga.SagaCommandCompleted
import com.netflix.spinnaker.clouddriver.saga.SagaCompleted
import com.netflix.spinnaker.clouddriver.saga.SagaEvent
import com.netflix.spinnaker.clouddriver.saga.SagaLogAppended
import com.netflix.spinnaker.clouddriver.saga.SagaRollbackStarted
import com.netflix.spinnaker.clouddriver.saga.exceptions.SagaStateIntegrationException
import com.netflix.spinnaker.clouddriver.saga.exceptions.SagaSystemException
import com.netflix.spinnaker.kork.annotations.Beta
import org.slf4j.LoggerFactory
/**
* The primary domain model of the Saga framework.
*
* @param name The name of the Saga type. This should be shared across all same-type Sagas (e.g. aws deploys)
* @param id The Saga instance ID
* @param sequence An internal counter used for tracking a Saga's position in an event log
*/
@Beta
class Saga(
val name: String,
val id: String,
private var sequence: Long = 0
) {
constructor(name: String, id: String) : this(name, id, 0)
private val log by lazy { LoggerFactory.getLogger(javaClass) }
private val events: MutableList<SagaEvent> = mutableListOf()
private val pendingEvents: MutableList<SagaEvent> = mutableListOf()
internal fun complete(success: Boolean = true) {
addEvent(SagaCompleted(success))
}
fun isComplete(): Boolean = events.filterIsInstance<SagaCompleted>().isNotEmpty()
fun isCompensating(): Boolean = events.filterIsInstance<SagaRollbackStarted>().isNotEmpty()
fun getVersion(): Long {
return events.map { it.getMetadata().originatingVersion }.max()?.let { it + 1 } ?: 0
}
fun addEvent(event: SagaEvent) {
this.pendingEvents.add(event)
}
@Suppress("UNCHECKED_CAST")
fun <T : SagaEvent> getEvent(clazz: Class<T>): T {
return events.reversed()
.filter { clazz.isAssignableFrom(it.javaClass) }
.let {
when (it.size) {
0 -> throw SagaStateIntegrationException.typeNotFound(clazz, this)
1 -> it.first() as T
else -> throw SagaStateIntegrationException.tooManyResults(clazz, this)
}
}
}
@Suppress("UNCHECKED_CAST")
fun <T : SagaEvent> getEvent(clazz: Class<T>, reducer: (List<T>) -> T): T {
return events.reversed()
.filter { clazz.isAssignableFrom(it.javaClass) }
.let {
when (it.size) {
0 -> throw SagaStateIntegrationException.typeNotFound(clazz, this)
1 -> it.first()
else -> reducer(it as List<T>)
} as T
}
}
internal fun completed(command: Class<SagaCommand>): Boolean {
return getEvents().filterIsInstance<SagaCommandCompleted>().any { it.matches(command) }
}
internal fun getNextCommand(requiredCommand: Class<SagaCommand>): SagaCommand? {
return getEvents()
.filterIsInstance<SagaCommand>()
.filterNot { completed(it.javaClass) }
.firstOrNull { requiredCommand.isAssignableFrom(it.javaClass) }
}
internal fun hasUnappliedCommands(): Boolean {
return getEvents().plus(pendingEvents)
.filterIsInstance<SagaCommand>()
.filterNot { completed(it.javaClass) }
.any()
}
@VisibleForTesting
fun addEventForTest(event: SagaEvent) {
this.events.add(event)
}
internal fun hydrateEvents(events: List<SagaEvent>) {
if (this.events.isEmpty()) {
this.events.addAll(events)
}
}
fun getSequence(): Long = sequence
internal fun setSequence(appliedEventVersion: Long) {
if (sequence > appliedEventVersion) {
throw SagaSystemException("Attempted to set Saga sequence to an event version in the past " +
"(current: $sequence, applying: $appliedEventVersion)")
}
sequence = appliedEventVersion
}
@JsonIgnoreProperties("saga")
fun getEvents(): List<SagaEvent> {
return events.toList()
}
@JsonIgnore
@VisibleForTesting
fun getPendingEvents(flush: Boolean = true): List<SagaEvent> {
val pending = mutableListOf<SagaEvent>()
pending.addAll(pendingEvents)
if (flush) {
pendingEvents.clear()
}
return pending.toList()
}
fun log(message: String) {
addEvent(SagaLogAppended(
SagaLogAppended.Message(message, null),
null
))
}
fun log(message: String, vararg replacements: Any?) {
log(String.format(message, *replacements))
}
fun getLogs(): List<String> {
return events.filterIsInstance<SagaLogAppended>().mapNotNull { it.message.user }
}
}
| clouddriver-saga/src/main/kotlin/com/netflix/spinnaker/clouddriver/saga/models/Saga.kt | 4142381859 |
package org.evomaster.core.search.impact.impactinfocollection
import org.evomaster.core.search.gene.Gene
/**
* this can be used to represent a mutated gene in detail, including
* @property current gene after mutation
* @property previous gene before mutation
* @property action refers to an action which contains the gene
* @property position indicates where the gene located in a view of an individual, e.g., index of action
* @property actionLocalId indicates the local id of the action
* @property isDynamicAction indicates whether the action belongs to [Individual.seeDynamicMainActions]
*/
class MutatedGeneWithContext (
val current : Gene,
val action : String = NO_ACTION,
val position : Int? = null,
val actionLocalId : String = NO_ACTION,
val isDynamicAction: Boolean = false,
val previous : Gene?,
val numOfMutatedGene: Int = 1
){
companion object{
const val NO_ACTION = "NONE"
}
fun mainPosition(current: Gene, previous: Gene?, numOfMutatedGene: Int) : MutatedGeneWithContext{
return MutatedGeneWithContext(current = current, previous = previous,action = this.action, position = this.position, actionLocalId = actionLocalId, isDynamicAction = isDynamicAction, numOfMutatedGene = numOfMutatedGene)
}
} | core/src/main/kotlin/org/evomaster/core/search/impact/impactinfocollection/MutatedGeneWithContext.kt | 3209720379 |
package com.piticlistudio.playednext.data.repository.datasource.room.platform
import com.nhaarman.mockito_kotlin.*
import com.piticlistudio.playednext.data.entity.mapper.datasources.platform.RoomPlatformMapper
import com.piticlistudio.playednext.domain.model.Platform
import com.piticlistudio.playednext.test.factory.PlatformFactory.Factory.makePlatform
import com.piticlistudio.playednext.test.factory.PlatformFactory.Factory.makeRoomPlatform
import io.reactivex.Flowable
import io.reactivex.Single
import io.reactivex.observers.TestObserver
import io.reactivex.subscribers.TestSubscriber
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
internal class RoomGamePlatformRepositoryImplTest {
@Nested
@DisplayName("Given a RoomGamePlatformRepositoryImpl instance")
inner class Instance {
private lateinit var repository: RoomGamePlatformRepositoryImpl
private val dao: RoomGamePlatformService = mock()
private val mapper: RoomPlatformMapper = mock()
@BeforeEach
internal fun setUp() {
reset(dao, mapper)
repository = RoomGamePlatformRepositoryImpl(dao, mapper)
}
@Nested
@DisplayName("When we call load")
inner class LoadCalled {
private var observer: TestSubscriber<Platform>? = null
private val source = makeRoomPlatform()
private val result = makePlatform()
@BeforeEach
internal fun setUp() {
whenever(dao.find(10)).thenReturn(Flowable.just(source))
whenever(mapper.mapFromDataLayer(source)).thenReturn(result)
observer = repository.load(10).test()
}
@Test
@DisplayName("Then should request dao service")
fun shouldRequestRepository() {
verify(dao).find(10)
}
@Test
@DisplayName("Then should map response")
fun shouldMap() {
verify(mapper).mapFromDataLayer(source)
}
@Test
@DisplayName("Then should emit without errors")
fun withoutErrors() {
assertNotNull(observer)
observer?.apply {
assertNoErrors()
assertComplete()
assertValueCount(1)
assertValue(result)
}
}
}
@Nested
@DisplayName("When we call loadForGame")
inner class LoadForGameCalled {
private var observer: TestSubscriber<List<Platform>>? = null
private val source = makeRoomPlatform()
private val result = makePlatform()
@BeforeEach
internal fun setUp() {
whenever(dao.findForGame(10)).thenReturn(Flowable.just(listOf(source)))
whenever(mapper.mapFromDataLayer(source)).thenReturn(result)
observer = repository.loadForGame(10).test()
}
@Test
@DisplayName("Then should request dao service")
fun shouldRequestRepository() {
verify(dao).findForGame(10)
}
@Test
@DisplayName("Then should map response")
fun shouldMap() {
verify(mapper).mapFromDataLayer(source)
}
@Test
@DisplayName("Then should emit without errors")
fun withoutErrors() {
assertNotNull(observer)
observer?.apply {
assertNoErrors()
assertComplete()
assertValueCount(1)
assertValue { it.size == 1 && it.contains(result) }
}
}
}
@Nested
@DisplayName("When we call saveForGame")
inner class SaveForGameCalled {
private var observer: TestObserver<Void>? = null
private val source = makePlatform()
private val result = makeRoomPlatform()
@BeforeEach
internal fun setUp() {
whenever(mapper.mapIntoDataLayerModel(source)).thenReturn(result)
whenever(dao.insert(result)).thenReturn(10)
whenever(dao.insertGamePlatform(any())).thenReturn(10)
observer = repository.saveForGame(10, source).test()
}
@Test
@DisplayName("Then should save company")
fun shouldSaveCompany() {
verify(dao).insert(result)
}
@Test
@DisplayName("Then should save relation")
fun shouldRequestDao() {
verify(dao).insertGamePlatform(com.nhaarman.mockito_kotlin.check {
assertEquals(it.platformId, source.id)
assertEquals(it.gameId, 10)
})
}
@Test
@DisplayName("Then should emit without errors")
fun withoutErrors() {
assertNotNull(observer)
observer?.apply {
assertNoErrors()
assertComplete()
assertNoValues()
}
}
@Nested
@DisplayName("And Room fails to save platform")
inner class RoomFail {
@BeforeEach
internal fun setUp() {
reset(dao, mapper)
whenever(dao.insert(result)).thenReturn(-1)
observer = repository.saveForGame(10, source).test()
}
@Test
@DisplayName("Then should emit error")
fun emitsError() {
assertNotNull(observer)
observer?.apply {
assertNoValues()
assertError(PlatformSaveException::class.java)
assertNotComplete()
}
}
@Test
@DisplayName("Then should not save RoomGameGenre")
fun shouldNotSaveGameDeveloper() {
verify(dao, never()).insertGamePlatform(any())
}
}
@Nested
@DisplayName("And Room fails to save gamePlatform")
inner class RoomPlatformFail {
@BeforeEach
internal fun setUp() {
reset(dao)
whenever(dao.insert(result)).thenReturn(10)
whenever(dao.insertGamePlatform(any())).thenReturn(-1)
observer = repository.saveForGame(10, source).test()
}
@Test
@DisplayName("Then should emit error")
fun emitsError() {
assertNotNull(observer)
observer?.apply {
assertNoValues()
assertError(GamePlatformSaveException::class.java)
assertNotComplete()
}
}
@Test
@DisplayName("Then should have saved platform")
fun shouldHaveSavedCompany() {
verify(dao).insert(result)
}
}
}
}
} | app/src/test/java/com/piticlistudio/playednext/data/repository/datasource/room/platform/RoomGamePlatformRepositoryImplTest.kt | 1105578169 |
package org.evomaster.e2etests.spring.rest.postgres
import org.evomaster.client.java.controller.EmbeddedSutController
import org.evomaster.e2etests.utils.RestTestBase
/**
* Created by arcuri82 on 21-Jun-19.
*/
open class SpringRestPostgresTestBase : RestTestBase() {
companion object {
@JvmStatic
fun initKlass(controller: EmbeddedSutController) {
RestTestBase.initClass(controller)
}
}
} | e2e-tests/spring-rest-postgres/src/test/kotlin/org/evomaster/e2etests/spring/rest/postgres/SpringRestPostgresTestBase.kt | 2645473914 |
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.marsphotos.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
private val DarkColorPalette = darkColors(
primary = Purple200,
primaryVariant = Purple700,
secondary = Teal200
)
private val LightColorPalette = lightColors(
primary = Purple500,
primaryVariant = Purple700,
secondary = Teal200
)
@Composable
fun MarsPhotosTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
}
| app/src/main/java/com/example/marsphotos/ui/theme/Theme.kt | 3151168787 |
package com.kaltura.playkit.plugins.playback
import com.kaltura.playkit.PKRequestParams
import com.kaltura.playkit.PlayKitManager
import com.kaltura.playkit.Utils
class PlaybackUtils {
companion object {
@JvmStatic
fun getPKRequestParams(requestParams: PKRequestParams,
playSessionId: String?, applicationName: String?,
httpHeaders: Map<String?, String?>?): PKRequestParams {
val url = requestParams.url
url?.let {
it.path?.let { path ->
if (path.contains("/playManifest/")) {
var alt = url.buildUpon()
.appendQueryParameter("clientTag", PlayKitManager.CLIENT_TAG)
.appendQueryParameter("playSessionId", playSessionId).build()
if (!applicationName.isNullOrEmpty()) {
alt = alt.buildUpon().appendQueryParameter("referrer", Utils.toBase64(applicationName.toByteArray())).build()
}
val lastPathSegment = requestParams.url.lastPathSegment
if (!lastPathSegment.isNullOrEmpty() && lastPathSegment.endsWith(".wvm")) {
// in old android device it will not play wvc if url is not ended in wvm
alt = alt.buildUpon().appendQueryParameter("name", lastPathSegment).build()
}
setCustomHeaders(requestParams, httpHeaders)
return PKRequestParams(alt, requestParams.headers)
}
}
}
setCustomHeaders(requestParams, httpHeaders)
return requestParams
}
private fun setCustomHeaders(requestParams: PKRequestParams, httpHeaders: Map<String?, String?>?) {
httpHeaders?.let { header ->
if (header.isNotEmpty()) {
header.forEach { (key, value) ->
key?.let { requestKey ->
value?.let { requestValue ->
requestParams.headers[requestKey] = requestValue
}
}
}
}
}
}
}
}
| playkit/src/main/java/com/kaltura/playkit/plugins/playback/PlaybackUtils.kt | 893601778 |
package io.thecontext.podcaster.output
import org.commonmark.parser.Parser
interface HtmlRenderer {
fun render(markdown: String): String
class Impl : HtmlRenderer {
private val markdownParser by lazy { Parser.builder().build() }
private val markdownRenderer by lazy { org.commonmark.renderer.html.HtmlRenderer.builder().build() }
override fun render(markdown: String) = markdownRenderer.render(markdownParser.parse(markdown))
}
} | src/main/kotlin/io/thecontext/podcaster/output/HtmlRenderer.kt | 3014469236 |
package com.google.firebase.quickstart.database.kotlin.listfragments
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.Query
class RecentPostsFragment : PostListFragment() {
override fun getQuery(databaseReference: DatabaseReference): Query {
// [START recent_posts_query]
// Last 100 posts, these are automatically the 100 most recent
// due to sorting by push() keys.
return databaseReference.child("posts")
.limitToFirst(100)
// [END recent_posts_query]
}
}
| database/app/src/main/java/com/google/firebase/quickstart/database/kotlin/listfragments/RecentPostsFragment.kt | 1719653598 |
package ii_collections
fun example8() {
val numbers = listOf(1, 3, -4, 2, -11)
// The details (how multi-assignment works) will be explained later in the 'Conventions' task
val (positive, negative) = numbers.partition { it > 0 }
positive == listOf(1, 3, 2)
negative == listOf(-4, -11)
}
fun Shop.getCustomersWithMoreUndeliveredOrdersThanDelivered(): Set<Customer> {
// Return customers who have more undelivered orders than delivered
return customers.filter {
val (deliveredCustomer, undeliveredCustomer) = it.orders.partition { it.isDelivered }
undeliveredCustomer.size > deliveredCustomer.size
}.toSet()
}
| src/ii_collections/_21_Partition_.kt | 4183990585 |
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.codegen.processor.testdata.annotatedtypes
import com.google.android.libraries.pcc.chronicle.annotation.ChronicleConnection
import com.google.android.libraries.pcc.chronicle.storage.datacache.DataCacheReader
import com.google.android.libraries.pcc.chronicle.storage.datacache.DataCacheWriter
@ChronicleConnection(dataClass = ExampleKotlinType::class, generateConnectionProvider = true)
interface ExampleKotlinTypeReaderWithDataCache : DataCacheReader<ExampleKotlinType>
@ChronicleConnection(dataClass = ExampleKotlinType::class, generateConnectionProvider = true)
interface ExampleKotlinTypeWriterWithDataCache : DataCacheWriter<ExampleKotlinType>
| javatests/com/google/android/libraries/pcc/chronicle/codegen/processor/testdata/annotatedtypes/ExampleKotlinTypeReaderAndWriter.kt | 3572360112 |
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.api.remote.client
import android.app.Application
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.IBinder
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.google.android.libraries.pcc.chronicle.api.remote.IRemote
import com.google.android.libraries.pcc.chronicle.api.remote.IResponseCallback
import com.google.android.libraries.pcc.chronicle.api.remote.RemoteRequest
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import java.time.Duration
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class DefaultChronicleServiceConnectorTest {
private lateinit var testContext: Context
private lateinit var application: ConnectorTestApplication
private lateinit var connectionScope: CoroutineScope
private lateinit var serviceComponentName: ComponentName
@Before
fun setUp() {
application = ApplicationProvider.getApplicationContext()
testContext = InstrumentationRegistry.getInstrumentation().context
connectionScope = CoroutineScope(Executors.newSingleThreadExecutor().asCoroutineDispatcher())
serviceComponentName = ComponentName(application, ConnectorTestService::class.java)
}
@After
fun tearDown() {
application.callsToOnBind = 0
application.callsToOnUnbind = 0
application.latch = null
application.returnNullBinder = false
application.unbound = null
connectionScope.cancel()
}
@Test
fun connectionState_subscribe_connects() = runBlocking {
val connector =
DefaultChronicleServiceConnector(
context = testContext,
connectionScope = connectionScope,
serviceComponentName = serviceComponentName,
timeout = Duration.ofSeconds(5)
)
val states = connector.connectionState.take(3).toList()
assertThat(states[0]).isEqualTo(ChronicleServiceConnector.State.Disconnected)
assertThat(states[1]).isEqualTo(ChronicleServiceConnector.State.Connecting)
assertThat(states[2]).isInstanceOf(ChronicleServiceConnector.State.Connected::class.java)
}
@Test
fun connectionState_subscribe_retriesUntilBind(): Unit = runBlocking {
val connector =
DefaultChronicleServiceConnector(
context = testContext,
connectionScope = connectionScope,
serviceComponentName = serviceComponentName,
timeout = Duration.ofSeconds(5)
)
launch {
application.returnNullBinder = true
delay(2000)
application.returnNullBinder = false
}
val states =
connector.connectionState
.takeWhile { it !is ChronicleServiceConnector.State.Connected }
.toList()
assertWithMessage("Should be an even number of Disconnected, Connecting states with retries.")
.that(states.size % 2).isEqualTo(0)
states.forEachIndexed { index, state ->
if (index % 2 == 0) assertThat(state).isEqualTo(ChronicleServiceConnector.State.Disconnected)
else assertThat(state).isEqualTo(ChronicleServiceConnector.State.Connecting)
}
}
@Test
fun connectionState_subscribe_timeoutRetries(): Unit = runBlocking {
val connector =
DefaultChronicleServiceConnector(
context = testContext,
connectionScope = connectionScope,
serviceComponentName = serviceComponentName,
timeout = Duration.ofSeconds(5)
)
application.latch = CountDownLatch(1)
val states = async(start = CoroutineStart.UNDISPATCHED) {
connector.connectionState
.takeWhile { it !is ChronicleServiceConnector.State.Connected }
.toList()
}
application.latch?.countDown()
assertWithMessage("Should be an even number of Disconnected, Connecting states with retries.")
.that(states.await().size % 2).isEqualTo(0)
states.await().forEachIndexed { index, state ->
if (index % 2 == 0) assertThat(state).isEqualTo(ChronicleServiceConnector.State.Disconnected)
else assertThat(state).isEqualTo(ChronicleServiceConnector.State.Connecting)
}
}
@Test
fun connectionScope_cancelled_unbinds(): Unit = runBlocking {
val connector =
DefaultChronicleServiceConnector(
context = testContext,
connectionScope = connectionScope,
serviceComponentName = serviceComponentName,
timeout = Duration.ofSeconds(1)
)
application.unbound = CompletableDeferred()
connector.connectionState.first { it is ChronicleServiceConnector.State.Connected }
as ChronicleServiceConnector.State.Connected
connectionScope.cancel()
application.unbound?.await()
assertThat(application.callsToOnUnbind).isEqualTo(1)
}
@Test
fun connectionState_maximumFailures_givesUp(): Unit = runBlocking {
val connector =
DefaultChronicleServiceConnector(
context = testContext,
connectionScope = connectionScope,
serviceComponentName = serviceComponentName,
timeout = Duration.ofSeconds(0),
maximumFailures = 3
)
application.returnNullBinder = true
val e = connector.connectionState.first { it is ChronicleServiceConnector.State.Unavailable }
as ChronicleServiceConnector.State.Unavailable
assertThat(e.cause).hasMessageThat().contains("failed 3 times in a row")
}
}
class ConnectorTestApplication : Application() {
var returnNullBinder: Boolean = false
var callsToOnBind: Int = 0
var callsToOnUnbind: Int = 0
var latch: CountDownLatch? = null
var unbound: CompletableDeferred<Unit>? = null
}
class ConnectorTestService : Service() {
override fun onBind(intent: Intent?): IBinder? {
val appContext = applicationContext as ConnectorTestApplication
appContext.callsToOnBind++
appContext.latch?.await()
if (appContext.returnNullBinder) return null
return object : IRemote.Stub() {
override fun serve(request: RemoteRequest, callback: IResponseCallback) {
callback.onComplete()
}
}
}
override fun onUnbind(intent: Intent?): Boolean {
val appContext = applicationContext as ConnectorTestApplication
appContext.callsToOnUnbind++
appContext.unbound?.complete(Unit)
return super.onUnbind(intent)
}
}
| javatests/com/google/android/libraries/pcc/chronicle/api/remote/client/DefaultChronicleServiceConnectorTest.kt | 1641006535 |
package com.jayrave.falkon.sqlBuilders.common
internal const val ARG_PLACEHOLDER = "?" | falkon-sql-builder-common/src/main/kotlin/com/jayrave/falkon/sqlBuilders/common/Constants.kt | 1535991394 |
@file:Suppress(
names = "NOTHING_TO_INLINE"
)
package com.jakewharton.rxbinding2.widget
import android.widget.SeekBar
import com.jakewharton.rxbinding2.InitialValueObservable
import kotlin.Int
import kotlin.Suppress
/**
* Create an observable of progress value 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.
*/
inline fun SeekBar.changes(): InitialValueObservable<Int> = RxSeekBar.changes(this)
/**
* Create an observable of progress value changes on `view` that were made only from the
* user.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Note:* A value will be emitted immediately on subscribe.
*/
inline fun SeekBar.userChanges(): InitialValueObservable<Int> = RxSeekBar.userChanges(this)
/**
* Create an observable of progress value changes on `view` that were made only from the
* system.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Note:* A value will be emitted immediately on subscribe.
*/
inline fun SeekBar.systemChanges(): InitialValueObservable<Int> = RxSeekBar.systemChanges(this)
/**
* Create an observable of progress change events for `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.
*/
inline fun SeekBar.changeEvents(): InitialValueObservable<SeekBarChangeEvent> = RxSeekBar.changeEvents(this)
| rxbinding-kotlin/src/main/kotlin/com/jakewharton/rxbinding2/widget/RxSeekBar.kt | 1587186424 |
package com.example.dummyapp2
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("com.example.dummyapp2", appContext.packageName)
}
}
| DummyApp2/app/src/androidTest/java/com/example/dummyapp2/ExampleInstrumentedTest.kt | 1662025784 |
package org.openapitools.client.infrastructure
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson
class ByteArrayAdapter {
@ToJson
fun toJson(data: ByteArray): String = String(data)
@FromJson
fun fromJson(data: String): ByteArray = data.toByteArray()
}
| ems-gateway-rest-sdk/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt | 1867683999 |
package com.arcao.geocaching4locus.base.util.backup
import android.app.backup.BackupAgentHelper
import android.app.backup.SharedPreferencesBackupHelper
import android.content.Context
class PreferencesBackupAgent : BackupAgentHelper() {
override fun onCreate() {
val helper = SharedPreferencesBackupHelper(this, getDefaultSharedPreferencesName(this))
addHelper(PREFS_BACKUP_KEY, helper)
}
companion object {
// A key to uniquely identify the set of backup data
private const val PREFS_BACKUP_KEY = "PREFERENCES"
private fun getDefaultSharedPreferencesName(context: Context): String =
"${context.packageName}_preferences"
}
} | app/src/main/java/com/arcao/geocaching4locus/base/util/backup/PreferencesBackupAgent.kt | 444900362 |
package com.arcao.geocaching4locus.error.exception
class LocusMapRuntimeException(cause: Throwable) : RuntimeException(cause) {
companion object {
private const val serialVersionUID = -4019163571054565979L
}
}
| app/src/main/java/com/arcao/geocaching4locus/error/exception/LocusMapRuntimeException.kt | 895023122 |
/*
* Copyright 2020 Ren Binden
*
* 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.rpkit.moderation.bukkit.event.warning
interface RPKWarningCreateEvent : RPKWarningEvent | bukkit/rpk-moderation-lib-bukkit/src/main/kotlin/com/rpkit/moderation/bukkit/event/warning/RPKWarningCreateEvent.kt | 2051613899 |
package com.arcao.geocaching4locus.data.api.util
import java.util.Locale
/**
* Helper functions to convert string reference code to numeric reference id and vice versa.
*/
object ReferenceCode {
private const val BASE_31_CHARS = "0123456789ABCDEFGHJKMNPQRTVWXYZ"
// = (16 * 31 * 31 * 31) - (16 * 16 * 16 * 16)
private const val REFERENCE_CODE_BASE31_MAGIC_NUMBER: Long = 411120
const val GEOCACHE_PREFIX = "GC"
private const val REFERENCE_CODE_BASE16_MAX: Long = 0xFFFF
private const val BASE_31 = 31
private const val BASE_16 = 16
/**
* Convert a base 31 number containing chars 0123456789ABCDEFGHJKMNPQRTVWXYZ
* to numeric value.
*
* @param input base 31 number
* @return numeric value
* @throws IllegalArgumentException If input contains illegal chars
*/
fun base31Decode(input: String): Long {
var result: Long = 0
for (ch in input.toCharArray()) {
result *= BASE_31
val index = BASE_31_CHARS.indexOf(ch, ignoreCase = true)
if (index == -1) {
throw IllegalArgumentException("Only chars $BASE_31_CHARS are supported.")
}
result += index.toLong()
}
return result
}
/**
* Convert a numeric value to base 31 number using chars
* 0123456789ABCDEFGHJKMNPQRTVWXYZ.
*
* @param input numeric value
* @return base 31 number
*/
fun base31Encode(input: Long): String {
var temp = input
val sb = StringBuilder()
while (temp != 0L) {
sb.append(BASE_31_CHARS[(temp % BASE_31).toInt()])
temp /= BASE_31
}
return sb.reverse().toString()
}
/**
* Convert reference code `ppXXX` to numeric reference id.
*
* The algorithm respects following rules used for reference code:
*
* * `pp0 - ppFFFF` - value after `pp` prefix is a hexadecimal number
* * `ppG000 - ...` = value after `pp` is a base 31 number minus magic constant
* `411120 = (16 * 31 * 31 * 31 - 16 * 16 * 16 * 16)`
*
* @param referenceCode cache code including GC prefix
* @return reference id
* @throws IllegalArgumentException reference code contains invalid characters
*/
fun toId(referenceCode: String): Long {
val referenceCodeNorm = referenceCode.uppercase(Locale.US)
if (referenceCodeNorm.length < 3) {
throw IllegalArgumentException("Reference code is too short.")
}
// remove prefix
val code = referenceCodeNorm.substring(2)
// 0 - FFFF = base16; G000 - ... = base 31
return if (code.length <= 4 && code[0] < 'G') {
try {
code.toLong(BASE_16)
} catch (e: NumberFormatException) {
throw IllegalArgumentException("Only chars $BASE_31_CHARS are supported.")
}
} else {
base31Decode(code) - REFERENCE_CODE_BASE31_MAGIC_NUMBER
}
}
/**
* Convert a numeric id to reference code `ppXXX`. The algorithm respects
* rules for generating reference code.
*
* @param prefix the reference code prefix `pp`
* @param id reference id
* @return reference code including prefix
* @see .toId
*/
fun toReferenceCode(prefix: String = GEOCACHE_PREFIX, id: Long): String {
val sb = StringBuilder()
// append GC prefix
sb.append(prefix)
if (id <= REFERENCE_CODE_BASE16_MAX) { // 0 - FFFF
sb.append(id.toString(BASE_16).uppercase(Locale.US))
} else { // G000 - ...
sb.append(base31Encode(id + REFERENCE_CODE_BASE31_MAGIC_NUMBER))
}
return sb.toString()
}
/**
* Returns true if the reference code is valid. The algorithm respects
* rules for reference code.
*
* @param referenceCode reference code
* @return true if reference code is valid, otherwise false
* @see .toId
*/
fun isReferenceCodeValid(referenceCode: String, prefix: String? = null): Boolean {
try {
if (prefix != null && !referenceCode.startsWith(prefix, ignoreCase = true))
return false
return toId(referenceCode) >= 0
} catch (e: IllegalArgumentException) {
return false
}
}
}
| geocaching-api/src/main/java/com/arcao/geocaching4locus/data/api/util/ReferenceCode.kt | 362909966 |
package coil.transform
import android.content.ContentResolver.SCHEME_FILE
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.graphics.Path.Direction
import android.graphics.PorterDuff.Mode.SRC
import android.graphics.PorterDuffXfermode
import android.graphics.RectF
import android.graphics.drawable.Animatable
import android.os.Build.VERSION.SDK_INT
import androidx.core.graphics.drawable.toBitmap
import androidx.test.core.app.ApplicationProvider
import coil.ImageLoader
import coil.decode.GifDecoder
import coil.decode.ImageDecoderDecoder
import coil.request.CachePolicy
import coil.request.ImageRequest
import coil.request.SuccessResult
import coil.request.animatedTransformation
import coil.util.assertIsSimilarTo
import coil.util.decodeBitmapAsset
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class AnimatedAndNormalTransformationTest {
private lateinit var context: Context
private lateinit var imageLoader: ImageLoader
private lateinit var imageRequestBuilder: ImageRequest.Builder
@Before
fun before() {
context = ApplicationProvider.getApplicationContext()
imageLoader = ImageLoader.Builder(context)
.crossfade(false)
.components {
if (SDK_INT >= 28) {
add(ImageDecoderDecoder.Factory())
} else {
add(GifDecoder.Factory())
}
}
.memoryCachePolicy(CachePolicy.DISABLED)
.diskCachePolicy(CachePolicy.DISABLED)
.build()
imageRequestBuilder = ImageRequest.Builder(context)
.bitmapConfig(Bitmap.Config.ARGB_8888)
.transformations(CircleCropTransformation())
.animatedTransformation(AnimatedCircleTransformation())
.allowConversionToBitmap(false)
}
@Test
fun animatedGifStillAnimated() = runTest {
val imageRequest = imageRequestBuilder
.data("$SCHEME_FILE:///android_asset/animated.gif")
.build()
val actual = imageLoader.execute(imageRequest)
assertTrue(actual is SuccessResult)
// Make sure this is still an animated result (has not been flattened to
// apply CircleCropTransformation).
assertTrue(actual.drawable is Animatable)
}
@Test
fun staticImageStillTransformed() = runTest {
val expected = context.decodeBitmapAsset("normal_small_circle.png")
val imageRequest = imageRequestBuilder
.data("$SCHEME_FILE:///android_asset/normal_small.jpg")
.build()
val actual = imageLoader.execute(imageRequest)
assertTrue(actual is SuccessResult)
// Make sure this is not an animated result.
assertFalse(actual.drawable is Animatable)
actual.drawable.toBitmap().assertIsSimilarTo(expected)
}
class AnimatedCircleTransformation : AnimatedTransformation {
override fun transform(canvas: Canvas): PixelOpacity {
val path = Path()
path.fillType = Path.FillType.INVERSE_EVEN_ODD
val width = canvas.width
val height = canvas.height
val radius = width / 2f
val rect = RectF(0f, 0f, width.toFloat(), height.toFloat())
path.addRoundRect(rect, radius, radius, Direction.CW)
val paint = Paint()
paint.isAntiAlias = true
paint.color = Color.TRANSPARENT
paint.xfermode = PorterDuffXfermode(SRC)
canvas.drawPath(path, paint)
return PixelOpacity.TRANSLUCENT
}
}
}
| coil-gif/src/androidTest/java/coil/transform/AnimatedAndNormalTransformationTest.kt | 1718198499 |
package com.wayfair.userlistanko.injection
import android.app.Application
import com.wayfair.userlistanko.MainApp
import com.wayfair.userlistanko.injection.builder.ActivityBuilder
import com.wayfair.userlistanko.injection.module.AppModule
import com.wayfair.userlistanko.injection.module.NetModule
import dagger.BindsInstance
import dagger.Component
import dagger.android.AndroidInjectionModule
@Component(modules = [
AndroidInjectionModule::class,
AppModule::class,
NetModule::class,
ActivityBuilder::class
])
interface AppComponent {
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: Application): Builder
fun build(): AppComponent
}
fun inject(app: MainApp)
} | android/anko_blogpost/UserlistAnko/app/src/main/java/com/wayfair/userlistanko/injection/AppComponent.kt | 1632806635 |
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.kotlin.emojify
import com.google.cloud.storage.Bucket
import com.google.cloud.storage.Storage
import com.google.cloud.vision.v1.Likelihood
import com.google.cloud.vision.v1.FaceAnnotation
import com.google.cloud.vision.v1.AnnotateImageRequest
import com.google.cloud.vision.v1.ImageAnnotatorClient
import com.google.cloud.vision.v1.ImageSource
import com.google.cloud.vision.v1.Image
import com.google.cloud.vision.v1.Feature
import com.google.cloud.vision.v1.Feature.Type
import org.springframework.http.HttpStatus
import org.springframework.beans.factory.annotation.Value
import org.springframework.core.io.ClassPathResource
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.awt.Polygon
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.nio.channels.Channels
import javax.imageio.ImageIO
import java.util.logging.Logger
enum class Emoji {
JOY, ANGER, SURPRISE, SORROW, NONE
}
val errorMessage = mapOf(
100 to "Other",
101 to "Slashes are intentionally forbidden in objectName.",
102 to "storage.bucket.name is missing in application.properties.",
103 to "Blob specified doesn't exist in bucket.",
104 to "blob ContentType is null.",
105 to "Size of responsesList is not 1.",
106 to "objectName is null.",
107 to "We couldn't detect faces in your image."
)
// Returns best emoji based on detected emotions likelihoods
fun bestEmoji(annotation: FaceAnnotation): Emoji {
val emotionsLikelihood = listOf(Likelihood.VERY_LIKELY, Likelihood.LIKELY, Likelihood.POSSIBLE)
val emotions = mapOf(
Emoji.JOY to annotation.joyLikelihood,
Emoji.ANGER to annotation.angerLikelihood,
Emoji.SURPRISE to annotation.surpriseLikelihood,
Emoji.SORROW to annotation.sorrowLikelihood
)
for (likelihood in emotionsLikelihood) { // In this order: VERY_LIKELY, LIKELY, POSSIBLE
for (emotion in emotions) { // In this order: JOY, ANGER, SURPRISE, SORROW (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map-of.html)
if (emotion.value == likelihood) return emotion.key // Returns emotion corresponding to likelihood
}
}
return Emoji.NONE
}
data class EmojifyResponse(
val objectPath: String? = null,
val emojifiedUrl: String? = null,
val statusCode: HttpStatus = HttpStatus.OK,
val errorCode: Int? = null,
val errorMessage: String? = null
)
@RestController
class EmojifyController(@Value("\${storage.bucket.name}") val bucketName: String, val storage: Storage, val vision: ImageAnnotatorClient) {
companion object {
val log: Logger = Logger.getLogger(EmojifyController::class.java.name)
}
val emojiBufferedImage = mapOf(
Emoji.JOY to retrieveEmoji("joy.png"),
Emoji.ANGER to retrieveEmoji("anger.png"),
Emoji.SURPRISE to retrieveEmoji("surprise.png"),
Emoji.SORROW to retrieveEmoji("sorrow.png"),
Emoji.NONE to retrieveEmoji("none.png")
)
private final fun retrieveEmoji(name: String): BufferedImage {
return ImageIO.read(ClassPathResource("emojis/$name").inputStream)
}
fun streamFromGCS(blobName: String): BufferedImage {
val strm: InputStream = Channels.newInputStream(storage.reader(bucketName, blobName))
return ImageIO.read(strm)
}
fun errorResponse(statusCode: HttpStatus, errorCode: Int = 100, msg: String? = null): EmojifyResponse {
val err = msg ?: errorMessage[errorCode]
log.severe(err)
return EmojifyResponse(statusCode = statusCode, errorCode = errorCode, errorMessage = err)
}
@GetMapping("/emojify")
fun emojify(@RequestParam(value = "objectName") objectName: String): EmojifyResponse {
if (objectName.isEmpty()) return errorResponse(HttpStatus.BAD_REQUEST, 106)
if (objectName.contains('/')) return errorResponse(HttpStatus.BAD_REQUEST, 101)
val bucket = storage.get(bucketName) ?: return errorResponse(HttpStatus.INTERNAL_SERVER_ERROR, 102)
val publicUrl: String =
"https://storage.googleapis.com/$bucketName/emojified/emojified-$objectName" // api response
val blob = bucket.get(objectName) ?: return errorResponse(HttpStatus.BAD_REQUEST, 103)
val imgType = blob.contentType?.substringAfter('/') ?: return errorResponse(HttpStatus.BAD_REQUEST, 104)
// Setting up image annotation request
val source = ImageSource.newBuilder().setGcsImageUri("gs://$bucketName/$objectName").build()
val img = Image.newBuilder().setSource(source).build()
val feat = Feature.newBuilder().setMaxResults(100).setType(Type.FACE_DETECTION).build()
val request = AnnotateImageRequest.newBuilder()
.addFeatures(feat)
.setImage(img)
.build()
// Calls vision api on above image annotation requests
val response = vision.batchAnnotateImages(listOf(request))
if (response.responsesList.size != 1) return errorResponse(HttpStatus.INTERNAL_SERVER_ERROR, 105)
val resp = response.responsesList[0]
if (resp.hasError()) return errorResponse(HttpStatus.INTERNAL_SERVER_ERROR, 100, resp.error.message)
// Writing source image to InputStream
val imgBuff = streamFromGCS(objectName)
val gfx = imgBuff.createGraphics()
if (resp.faceAnnotationsList.size == 0) return errorResponse(HttpStatus.BAD_REQUEST, 107)
for (annotation in resp.faceAnnotationsList) {
val imgEmoji = emojiBufferedImage[bestEmoji(annotation)]
val poly = Polygon()
for (vertex in annotation.fdBoundingPoly.verticesList) {
poly.addPoint(vertex.x, vertex.y)
}
val height = poly.ypoints[2] - poly.ypoints[0]
val width = poly.xpoints[1] - poly.xpoints[0]
// Draws emoji on detected face
gfx.drawImage(imgEmoji, poly.xpoints[0], poly.ypoints[1], height, width, null)
}
// Writing emojified image to OutputStream
val outputStream = ByteArrayOutputStream()
ImageIO.write(imgBuff, imgType, outputStream)
// Uploading emojified image to GCS and making it public
bucket.create(
"emojified/emojified-$objectName",
outputStream.toByteArray(),
Bucket.BlobTargetOption.predefinedAcl(Storage.PredefinedAcl.PUBLIC_READ)
)
// Everything went well!
return EmojifyResponse(
objectPath = "emojified/emojified-$objectName",
emojifiedUrl = publicUrl
)
}
} | getting-started/android-with-appengine/backend/src/main/kotlin/com/google/cloud/kotlin/emojify/EmojifyController.kt | 1373002489 |
package app.opass.ccip.ui
import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.*
import android.webkit.PermissionRequest
import android.webkit.WebSettings
import android.widget.FrameLayout
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import app.opass.ccip.R
import app.opass.ccip.network.webclient.OfficialWebViewClient
import app.opass.ccip.network.webclient.WebChromeViewClient
import app.opass.ccip.util.CryptoUtil
import app.opass.ccip.util.PreferenceUtil
import kotlinx.android.synthetic.main.fragment_web.*
class PuzzleFragment : Fragment() {
companion object {
private const val URL_NO_NETWORK = "file:///android_asset/no_network.html"
private const val EXTRA_URL = "EXTRA_URL"
fun newInstance(url: String): PuzzleFragment = PuzzleFragment().apply {
arguments = Bundle().apply { putString(EXTRA_URL, url) }
}
}
private lateinit var mActivity: MainActivity
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
mActivity = requireActivity() as MainActivity
return inflater.inflate(R.layout.fragment_web, container, false)
}
@SuppressLint("SetJavaScriptEnabled")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<FrameLayout>(R.id.webview_wrapper)
.setOnApplyWindowInsetsListener { v, insets ->
v.updatePadding(bottom = insets.systemWindowInsetBottom)
insets
}
webView.webViewClient = OfficialWebViewClient()
webView.webChromeClient = WebChromeViewClient(progressBar, fun (request) {
if (!request!!.resources.contains(PermissionRequest.RESOURCE_VIDEO_CAPTURE)) request.deny()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Android M Permission check
if (mActivity.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.CAMERA), 2)
request.deny()
} else {
request.grant(request.resources)
}
} else {
request.grant(request.resources)
}
})
if (PreferenceUtil.getToken(mActivity) != null) {
webView.loadUrl(
requireArguments().getString(EXTRA_URL)!!
.replace(
"{public_token}",
CryptoUtil.toPublicToken(PreferenceUtil.getToken(mActivity)) ?: ""
)
)
} else {
webView.loadUrl("data:text/html, <div>Please login</div>")
}
val settings = webView.settings
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
if (Build.VERSION.SDK_INT >= 21) {
settings.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (permissions.contains(Manifest.permission.CAMERA) && grantResults.contains(PackageManager.PERMISSION_GRANTED)) {
webView.reload()
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
mActivity.menuInflater.inflate(R.menu.puzzle, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.share -> {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_SUBJECT, resources.getText(R.string.puzzle_share_subject))
intent.putExtra(Intent.EXTRA_TEXT, webView.url)
mActivity.startActivity(Intent.createChooser(intent, resources.getText(R.string.share)))
}
}
return true
}
}
| app/src/main/java/app/opass/ccip/ui/PuzzleFragment.kt | 3650652034 |
package utils
@JsName("moment")
external class Moment(unix: Number) {
companion object {
fun locale(locale: String)
fun unix(unix: Number): Moment
}
fun fromNow(): String
fun calendar(): String
fun add(number: Number, span: String)
} | web/spicy-morenitta/src/main/kotlin/utils/momentjs.kt | 679635729 |
package de.maibornwolff.codecharta.importer.gitlogparser.input.metrics
import de.maibornwolff.codecharta.importer.gitlogparser.input.Modification
class NumberOfOccurencesInCommits : Metric {
private var numberOfOccurrencesInCommits: Long = 0
override fun description(): String {
return "Number Of Commits: Number of times this file occured in a commit."
}
override fun metricName(): String {
return "number_of_commits"
}
override fun registerModification(modification: Modification) {
numberOfOccurrencesInCommits++
}
override fun value(): Number {
return numberOfOccurrencesInCommits
}
}
| analysis/import/GitLogParser/src/main/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/input/metrics/NumberOfOccurencesInCommits.kt | 2633394767 |
package net.perfectdreams.loritta.morenitta.website.routes.api.v1
import net.perfectdreams.loritta.morenitta.dao.ServerConfig
import net.perfectdreams.loritta.morenitta.utils.GuildLorittaUser
import net.perfectdreams.loritta.morenitta.utils.LorittaPermission
import net.perfectdreams.loritta.morenitta.utils.LorittaUser
import net.perfectdreams.loritta.morenitta.utils.extensions.await
import net.perfectdreams.loritta.morenitta.website.LoriWebCode
import net.perfectdreams.loritta.morenitta.website.WebsiteAPIException
import io.ktor.server.application.*
import io.ktor.http.*
import io.ktor.server.request.*
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.Guild
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.utils.DiscordUtils
import net.perfectdreams.loritta.morenitta.website.session.LorittaJsonWebSession
import net.perfectdreams.loritta.morenitta.website.utils.WebsiteUtils
import net.perfectdreams.loritta.morenitta.website.utils.extensions.hostFromHeader
import net.perfectdreams.loritta.morenitta.website.utils.extensions.redirect
import net.perfectdreams.loritta.morenitta.website.utils.extensions.urlQueryString
import net.perfectdreams.temmiediscordauth.TemmieDiscordAuth
abstract class RequiresAPIGuildAuthRoute(loritta: LorittaBot, originalDashboardPath: String) : RequiresAPIDiscordLoginRoute(loritta, "/api/v1/guilds/{guildId}$originalDashboardPath") {
abstract suspend fun onGuildAuthenticatedRequest(call: ApplicationCall, discordAuth: TemmieDiscordAuth, userIdentification: LorittaJsonWebSession.UserIdentification, guild: Guild, serverConfig: ServerConfig)
override suspend fun onAuthenticatedRequest(call: ApplicationCall, discordAuth: TemmieDiscordAuth, userIdentification: LorittaJsonWebSession.UserIdentification) {
val guildId = call.parameters["guildId"] ?: return
val shardId = DiscordUtils.getShardIdFromGuildId(loritta, guildId.toLong())
val loriShardId = DiscordUtils.getLorittaClusterIdForShardId(loritta, shardId)
if (loriShardId != loritta.clusterId) {
val theNewUrl = DiscordUtils.getUrlForLorittaClusterId(loritta, loriShardId)
redirect("$theNewUrl${call.request.path()}${call.request.urlQueryString}", false)
}
val jdaGuild = loritta.lorittaShards.getGuildById(guildId)
?: throw WebsiteAPIException(
HttpStatusCode.BadRequest,
WebsiteUtils.createErrorPayload(
loritta,
LoriWebCode.UNKNOWN_GUILD,
"Guild $guildId doesn't exist or it isn't loaded yet"
)
)
val serverConfig = loritta.getOrCreateServerConfig(guildId.toLong()) // get server config for guild
val id = userIdentification.id
val member = jdaGuild.retrieveMemberById(id).await()
var canAccessDashboardViaPermission = false
if (member != null) {
val lorittaUser = GuildLorittaUser(loritta, member, LorittaUser.loadMemberLorittaPermissions(loritta, serverConfig, member), loritta.getOrCreateLorittaProfile(id.toLong()))
canAccessDashboardViaPermission = lorittaUser.hasPermission(LorittaPermission.ALLOW_ACCESS_TO_DASHBOARD)
}
val canBypass = loritta.isOwner(userIdentification.id) || canAccessDashboardViaPermission
if (!canBypass && !(member?.hasPermission(Permission.ADMINISTRATOR) == true || member?.hasPermission(Permission.MANAGE_SERVER) == true || jdaGuild.ownerId == userIdentification.id)) {
throw WebsiteAPIException(
HttpStatusCode.Forbidden,
WebsiteUtils.createErrorPayload(
loritta,
LoriWebCode.FORBIDDEN,
"User ${member?.user?.id} doesn't have permission to edit ${guildId}'s config"
)
)
}
return onGuildAuthenticatedRequest(call, discordAuth, userIdentification, jdaGuild, serverConfig)
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/routes/api/v1/RequiresAPIGuildAuthRoute.kt | 176735088 |
/*
* Copyright 2012 APPNEXUS 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 appnexus.com.appnexussdktestapp.functional.mar
import android.content.Intent
import android.content.res.Resources
import androidx.test.espresso.Espresso
import androidx.test.espresso.IdlingPolicies
import androidx.test.espresso.IdlingRegistry
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.intent.rule.IntentsTestRule
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.runner.AndroidJUnit4
import appnexus.com.appnexussdktestapp.BannerScaleLoadAndDisplayActivity
import appnexus.com.appnexussdktestapp.MARScaleLoadAndDisplayActivity
import appnexus.com.appnexussdktestapp.R
import com.appnexus.opensdk.XandrAd
import com.appnexus.opensdk.utils.Clog
import com.microsoft.appcenter.espresso.Factory
import kotlinx.android.synthetic.main.activity_mar_load.*
import org.junit.*
import org.junit.runner.RunWith
import java.util.concurrent.TimeUnit
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class MARScaleMemoryTest {
val Int.dp: Int
get() = (this / Resources.getSystem().displayMetrics.density).toInt()
val Int.px: Int
get() = (this * Resources.getSystem().displayMetrics.density).toInt()
@get:Rule
var reportHelper = Factory.getReportHelper()
@Rule
@JvmField
var mActivityTestRule = IntentsTestRule(MARScaleLoadAndDisplayActivity::class.java, false, false)
lateinit var marActivity: MARScaleLoadAndDisplayActivity
@Before
fun setup() {
XandrAd.init(123, null, false, null)
IdlingPolicies.setMasterPolicyTimeout(1, TimeUnit.MINUTES)
IdlingPolicies.setIdlingResourceTimeout(1, TimeUnit.MINUTES)
}
@After
fun destroy() {
IdlingRegistry.getInstance().unregister(marActivity.idlingResource)
reportHelper.label("Stopping App")
}
/*
* Test for the Invalid Renderer Url for Banner Native Ad (NativeAssemblyRenderer)
* */
@Test
fun marScaleForNumberOfCountMARs() {
var intent = Intent()
var count = 64
intent.putExtra(BannerScaleLoadAndDisplayActivity.COUNT, count)
mActivityTestRule.launchActivity(intent)
marActivity = mActivityTestRule.activity
IdlingRegistry.getInstance().register(marActivity.idlingResource)
Thread.sleep(2000)
Espresso.onView(ViewMatchers.withId(R.id.recyclerListAdView))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Clog.e("COUNT: ", marActivity.recyclerListAdView.adapter!!.itemCount.toString())
(0 until count-1 step 3).forEach { i-> marActivity.recyclerListAdView.smoothScrollToPosition(i)
Thread.sleep(1000)}
(count-1 until 0 step 3).forEach { i-> marActivity.recyclerListAdView.smoothScrollToPosition(i)
Thread.sleep(1000)}
Espresso.onView(ViewMatchers.withId(R.id.recyclerListAdView))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
}
}
| tests/AppNexusSDKTestApp/app/src/androidTest/java/appnexus/com/appnexussdktestapp/functional/mar/MARScaleMemoryTest.kt | 2660082392 |
package at.cpickl.gadsu.appointment
import at.cpickl.gadsu.persistence.Persistable
import at.cpickl.gadsu.service.HasId
import com.google.common.collect.ComparisonChain
import com.google.common.collect.Ordering
import org.joda.time.DateTime
data class Appointment(
override val id: String?,
val clientId: String,
// title, as shown as summary in gcal
val created: DateTime,
val start: DateTime,
val end: DateTime,
val note: String,
val gcalId: String?,
val gcalUrl: String?
) : Comparable<Appointment>, HasId, Persistable {
companion object {
fun insertPrototype(clientId: String, start: DateTime): Appointment {
return Appointment(null, clientId, DateTime.now(), start, start.plusMinutes(90), "", null, null)
}
}
val idComparator: (Appointment) -> Boolean
get() = { that -> this.id == that.id }
override val yetPersisted: Boolean get() = id != null
override fun compareTo(other: Appointment): Int {
return ComparisonChain.start()
.compare(this.start, other.start)
.compare(this.end, other.end)
.compare(this.clientId, other.clientId)
.compare(this.id, other.id, Ordering.natural<String>().nullsFirst())
.result()
}
}
| src/main/kotlin/at/cpickl/gadsu/appointment/model.kt | 2990203062 |
package library.service.business.books.domain.events
import library.service.business.books.domain.BookRecord
import library.service.business.books.domain.types.BookId
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.DynamicTest.dynamicTest
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestFactory
import utils.Books
import utils.classification.UnitTest
import java.time.OffsetDateTime
import java.util.*
@UnitTest
internal class BookEventsTest {
val uuid = UUID.randomUUID()!!
val timestamp = OffsetDateTime.now()!!
val bookRecord = BookRecord(BookId.generate(), Books.THE_MARTIAN)
val allBookEventTypes = listOf(
BookAdded(uuid, timestamp, bookRecord),
BookUpdated(uuid, timestamp, bookRecord),
BookRemoved(uuid, timestamp, bookRecord),
BookBorrowed(uuid, timestamp, bookRecord),
BookReturned(uuid, timestamp, bookRecord)
)
@Test fun `all event types are unique`() {
val types = allBookEventTypes.map { it.type }
val distinctTypes = types.distinct()
assertThat(types).isEqualTo(distinctTypes)
}
@TestFactory fun `all event types follow naming pattern`() = allBookEventTypes.map {
dynamicTest(it.javaClass.simpleName) {
assertThat(it.type).matches("[a-z]+(-[a-z]+)*")
}
}
@TestFactory fun `all event ids are formatted as strings`() = allBookEventTypes.map {
dynamicTest(it.javaClass.simpleName) {
assertThat(it.id).isEqualTo(uuid.toString())
}
}
@TestFactory fun `all event book ids are formatted as strings`() = allBookEventTypes.map {
dynamicTest(it.javaClass.simpleName) {
assertThat(it.bookId).isEqualTo(bookRecord.id.toString())
}
}
@TestFactory fun `all event timestamps are formatted as strings`() = allBookEventTypes.map {
dynamicTest(it.javaClass.simpleName) {
assertThat(it.timestamp).isEqualTo(timestamp.toString())
}
}
@TestFactory fun `all event book isbn are formatted as strings`() = allBookEventTypes.map {
dynamicTest(it.javaClass.simpleName) {
assertThat(it.isbn).isEqualTo(bookRecord.book.isbn.toString())
}
}
@TestFactory fun `all event book titles are formatted as strings`() = allBookEventTypes.map {
dynamicTest(it.javaClass.simpleName) {
assertThat(it.title).isEqualTo(bookRecord.book.title.toString())
}
}
} | library-service/src/test/kotlin/library/service/business/books/domain/events/BookEventsTest.kt | 610955841 |
/**
* Copyright 2016 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 org.openrewrite.java.tree
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.openrewrite.java.JavaParser
open class BlockTest : JavaParser() {
@Test
fun methodBlock() {
val a = parse("""
public class A {
public void foo() {
System.out.println("foo");
}
}
""")
assertEquals(1, a.classes[0].methods[0].body!!.statements.size)
}
@Test
fun format() {
val a = parse("""
public class A {
public void foo() { }
}
""")
assertEquals("{ }", a.classes[0].methods[0].body!!.printTrimmed())
}
@Test
fun staticInitBlock() {
val a = parse("""
public class A {
static {}
}
""")
assertEquals("static {}", a.classes[0].body.statements[0].printTrimmed())
}
} | rewrite-java/src/test/kotlin/org/openrewrite/java/tree/BlockTest.kt | 3108479447 |
package uk.co.appsbystudio.geoshare.authentication.signup
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import kotlinx.android.synthetic.main.fragment_signup.*
import uk.co.appsbystudio.geoshare.R
import uk.co.appsbystudio.geoshare.authentication.AuthActivity
import uk.co.appsbystudio.geoshare.authentication.AuthView
class SignupFragment : Fragment(), SignupView {
private var fragmentCallback: AuthView? = null
private var presenter: SignupPresenter? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_signup, container, false)
presenter = SignupPresenterImpl(this, SignupInteractorImpl())
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
progress_button_signup.setOnClickListener {
presenter?.validate(edit_name_signup.text.toString(), edit_email_signup.text.toString(), edit_password_signup.text.toString(), checkbox_terms_signup.isChecked)
}
text_terms_link_signup.setOnClickListener {
presenter?.onTermsClick()
}
button_back_signup.setOnClickListener {
fragmentCallback?.onBack()
}
}
override fun onAttach(context: Context?) {
super.onAttach(context)
try {
fragmentCallback = context as AuthActivity
} catch (e: ClassCastException) {
throw ClassCastException(activity.toString() + "must implement AuthView")
}
}
override fun setNameError() {
edit_name_signup.error = resources.getString(R.string.error_field_required)
edit_name_signup.requestFocus()
}
override fun setEmailError() {
edit_email_signup.error = resources.getString(R.string.error_field_required)
edit_email_signup.requestFocus()
}
override fun setPasswordError() {
edit_password_signup.error = resources.getString(R.string.error_field_required)
edit_password_signup.requestFocus()
}
override fun setTermsError() {
checkbox_terms_signup.error = resources.getString(R.string.error_field_required)
}
override fun showTerms() {
//TODO: Create a dialog to show the terms
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://geoshare.appsbystudio.co.uk/terms")))
}
override fun showProgress() {
progress_button_signup.startAnimation()
}
override fun hideProgress() {
progress_button_signup.revertAnimation()
}
override fun updateUI() {
fragmentCallback?.onSuccess()
}
override fun showError(error: String) {
Toast.makeText(this.context, error, Toast.LENGTH_SHORT).show()
}
}
| mobile/src/main/java/uk/co/appsbystudio/geoshare/authentication/signup/SignupFragment.kt | 2676703412 |
package com.joom.smuggler.compiler
internal interface ContentGenerator {
fun generate(environment: GenerationEnvironment): Collection<GeneratedContent>
}
| smuggler-compiler/src/main/java/com/joom/smuggler/compiler/ContentGenerator.kt | 1725825125 |
package com.lasthopesoftware.bluewater.client.playback.engine.GivenAPlayingPlaybackEngine
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.library.access.ILibraryStorage
import com.lasthopesoftware.bluewater.client.browsing.library.access.ISpecificLibraryProvider
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library
import com.lasthopesoftware.bluewater.client.playback.engine.PlaybackEngine.Companion.createEngine
import com.lasthopesoftware.bluewater.client.playback.engine.bootstrap.PlaylistPlaybackBootstrapper
import com.lasthopesoftware.bluewater.client.playback.engine.preparation.PreparedPlaybackQueueResourceManagement
import com.lasthopesoftware.bluewater.client.playback.file.preparation.FakeDeferredPlayableFilePreparationSourceProvider
import com.lasthopesoftware.bluewater.client.playback.file.preparation.queues.CompletingFileQueueProvider
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.storage.NowPlayingRepository
import com.lasthopesoftware.bluewater.client.playback.volume.PlaylistVolumeManager
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions
import org.joda.time.Duration
import org.junit.Test
import java.util.*
class WhenNotObservingPlayback {
companion object {
private val library = Library(_id = 1, _nowPlayingId = 5)
private val playbackEngine by lazy {
val fakePlaybackPreparerProvider = FakeDeferredPlayableFilePreparationSourceProvider()
val libraryProvider = mockk<ISpecificLibraryProvider>()
every { libraryProvider.library } returns Promise(library)
val libraryStorage = mockk<ILibraryStorage>()
every { libraryStorage.saveLibrary(any()) } returns Promise(library)
val playbackEngine = createEngine(
PreparedPlaybackQueueResourceManagement(
fakePlaybackPreparerProvider
) { 1 }, listOf(CompletingFileQueueProvider()),
NowPlayingRepository(libraryProvider, libraryStorage),
PlaylistPlaybackBootstrapper(PlaylistVolumeManager(1.0f))
).toFuture().get()
playbackEngine
?.startPlaylist(
Arrays.asList(
ServiceFile(1),
ServiceFile(2),
ServiceFile(3),
ServiceFile(4),
ServiceFile(5)
), 0, Duration.ZERO
)
val resolveablePlaybackHandler =
fakePlaybackPreparerProvider.deferredResolution.resolve()
fakePlaybackPreparerProvider.deferredResolution.resolve()
resolveablePlaybackHandler.resolve()
playbackEngine
}
}
@Test
fun thenTheSavedTrackPositionIsOne() {
Assertions.assertThat(library.nowPlayingId).isEqualTo(1)
}
@Test
fun thenTheManagerIsPlaying() {
Assertions.assertThat(playbackEngine?.isPlaying).isTrue
}
}
| projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/engine/GivenAPlayingPlaybackEngine/WhenNotObservingPlayback.kt | 2428787697 |
package com.lasthopesoftware.bluewater.client.playback.file.exoplayer.GivenAPlayingFile.AndThePlayerIdles.AndTheFilePositionIsAtTheEnd
import com.annimon.stream.Stream
import com.google.android.exoplayer2.Player
import com.lasthopesoftware.any
import com.lasthopesoftware.bluewater.client.playback.exoplayer.PromisingExoPlayer
import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.ExoPlayerPlaybackHandler
import com.lasthopesoftware.bluewater.shared.promises.extensions.FuturePromise
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import org.assertj.core.api.AssertionsForClassTypes
import org.junit.BeforeClass
import org.junit.Test
import org.mockito.Mockito
import java.util.*
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
class WhenThePlayerWillNotPlayWhenReady {
companion object {
private val eventListeners: MutableCollection<Player.EventListener> = ArrayList()
private var isComplete = false
@JvmStatic
@BeforeClass
@Throws(InterruptedException::class, TimeoutException::class, ExecutionException::class)
fun before() {
val mockExoPlayer = Mockito.mock(PromisingExoPlayer::class.java)
Mockito.`when`(mockExoPlayer.getPlayWhenReady()).thenReturn(true.toPromise())
Mockito.`when`(mockExoPlayer.setPlayWhenReady(true)).thenReturn(mockExoPlayer.toPromise())
Mockito.`when`(mockExoPlayer.getCurrentPosition()).thenReturn(100L.toPromise())
Mockito.`when`(mockExoPlayer.getDuration()).thenReturn(100L.toPromise())
Mockito.doAnswer { invocation ->
eventListeners.add(invocation.getArgument(0))
mockExoPlayer.toPromise()
}.`when`(mockExoPlayer).addListener(any())
val exoPlayerPlaybackHandler = ExoPlayerPlaybackHandler(mockExoPlayer)
val playbackPromise = exoPlayerPlaybackHandler.promisePlayback()
.eventually { obj -> obj.promisePlayedFile() }
.then { isComplete = true }
Stream.of(eventListeners).forEach { e -> e.onPlayerStateChanged(false, Player.STATE_IDLE) }
FuturePromise(playbackPromise)[1, TimeUnit.SECONDS]
}
}
@Test
fun thenPlaybackCompletes() {
AssertionsForClassTypes.assertThat(isComplete).isTrue
}
}
| projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/file/exoplayer/GivenAPlayingFile/AndThePlayerIdles/AndTheFilePositionIsAtTheEnd/WhenThePlayerWillNotPlayWhenReady.kt | 1567285354 |
package org.paradise.ipaq.services
import org.paradise.ipaq.Constants
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import org.thymeleaf.context.Context
import org.thymeleaf.spring4.SpringTemplateEngine
/**
* Created by terrence on 26/7/17.
*/
@Service
class MailService(val springTemplateEngine: SpringTemplateEngine) {
@Value("\${app.template.plaintext.file.email}")
private val emailTemplate: String? = null
fun sendMail(): Boolean {
val context = Context()
context.setVariable(Constants.CUSTOMER_NAME_VARIABLE, "John Smith")
springTemplateEngine.process(emailTemplate, context)
return true
}
} | src/main/kotlin/org/paradise/ipaq/services/MailService.kt | 501081390 |
/*
* Sone - ImageInsertStartedEvent.kt - Copyright © 2013–2020 David Roden
*
* 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 net.pterodactylus.sone.core.event
import net.pterodactylus.sone.data.*
/**
* Event that signals that an [Image] is not being inserted.
*/
class ImageInsertStartedEvent(image: Image) : ImageEvent(image)
| src/main/kotlin/net/pterodactylus/sone/core/event/ImageInsertStartedEvent.kt | 4095454700 |
package com.cout970.magneticraft.systems.tilemodules
import com.cout970.magneticraft.api.heat.IHeatNode
import com.cout970.magneticraft.misc.*
import com.cout970.magneticraft.misc.inventory.Inventory
import com.cout970.magneticraft.misc.inventory.get
import com.cout970.magneticraft.misc.inventory.isNotEmpty
import com.cout970.magneticraft.misc.inventory.withSize
import com.cout970.magneticraft.misc.network.IntSyncVariable
import com.cout970.magneticraft.misc.network.SyncVariable
import com.cout970.magneticraft.misc.vector.*
import com.cout970.magneticraft.misc.world.isClient
import com.cout970.magneticraft.systems.blocks.*
import com.cout970.magneticraft.systems.config.Config
import com.cout970.magneticraft.systems.gui.DATA_ID_BURNING_TIME
import com.cout970.magneticraft.systems.gui.DATA_ID_MAX_BURNING_TIME
import com.cout970.magneticraft.systems.integration.ItemHolder
import com.cout970.magneticraft.systems.tileentities.IModule
import com.cout970.magneticraft.systems.tileentities.IModuleContainer
import net.minecraft.init.Blocks
import net.minecraft.init.Items
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.tileentity.TileEntityFurnace
import net.minecraft.util.EnumParticleTypes
/**
* Created by cout970 on 2017/07/13.
*/
class ModuleCombustionChamber(
val node: IHeatNode,
val inventory: Inventory,
override val name: String = "module_combustion_chamber"
) : IModule, IOnActivated {
override lateinit var container: IModuleContainer
var burningTime = 0
var maxBurningTime = 0
var doorOpen = false
companion object {
@JvmStatic
val MAX_HEAT = 600.fromCelsiusToKelvin()
}
override fun onActivated(args: OnActivatedArgs): Boolean {
val block = container.blockState.block
val boxes = (block as? BlockBase)
?.aabb
?.invoke(BoundingBoxArgs(container.blockState, world, pos))
?: emptyList()
val index = boxes.indexOfFirst { it.isHitBy(args.hit) }
if (index != 2) {
return if (Config.allowCombustionChamberGui) {
CommonMethods.openGui(args)
} else {
false
}
} else {
if (doorOpen && isValidFuel(args.heldItem)) {
val space = 64 - inventory[0].count
val toMove = Math.min(args.heldItem.count, space)
if (toMove > 0) {
val notMoved = inventory.insertItem(0, args.heldItem.withSize(toMove), false)
args.heldItem.shrink(toMove - notMoved.count)
}
} else {
doorOpen = !doorOpen
container.sendUpdateToNearPlayers()
}
return true
}
}
fun spawnParticles() {
if (doorOpen && inventory[0].isNotEmpty) {
repeat(2) {
val rand = world.rand
val offset = (vec3Of(rand.nextFloat(), 0, rand.nextFloat()) * 2 - vec3Of(1, 0, 1)) * 0.25
val pos = pos.toVec3d() + vec3Of(0.5, 0.2, 0.5) + offset
val randDir = vec3Of(rand.nextFloat(), rand.nextFloat(), rand.nextFloat())
val randDirAllDirections = randDir * vec3Of(2, 1, 2) - vec3Of(1, 0, 1)
val dir = randDirAllDirections * 0.001 + (-offset + vec3Of(0, 1, 0)) * 0.025
world.spawnParticle(EnumParticleTypes.FLAME, pos.x, pos.y, pos.z, dir.x, dir.y, dir.z)
}
}
}
override fun update() {
if (world.isClient) {
spawnParticles()
return
}
if (maxBurningTime > 0) {
if (burningTime > maxBurningTime) {
maxBurningTime = 0
burningTime = 0
} else {
if (node.temperature < MAX_HEAT) {
val speed = ((if (doorOpen) 0.5f else 1f) * Config.combustionChamberMaxSpeed.toFloat()).toInt()
burningTime += speed
node.applyHeat(Config.fuelToJoules * speed)
}
}
}
if (maxBurningTime <= 0) {
val consumed = consumeFuel()
if (!consumed && node.temperature > STANDARD_AMBIENT_TEMPERATURE) {
node.applyHeat(Config.heatDissipationSpeed)
}
}
}
fun consumeFuel(): Boolean {
maxBurningTime = 0
val stack = inventory[0]
if (stack.isEmpty || !isValidFuel(stack)) return false
val time = TileEntityFurnace.getItemBurnTime(stack)
if (time > 0) {
stack.shrink(1)
maxBurningTime = (time * Config.combustionChamberFuelMultiplier).toInt()
}
return true
}
fun isValidFuel(stack: ItemStack): Boolean {
if (stack.isEmpty) return false
if (!Config.combustionChamberOnlyCoal) {
return TileEntityFurnace.getItemBurnTime(stack) > 0
}
// vanilla
if (stack.item == Items.COAL) return true
if (stack.item == Item.getItemFromBlock(Blocks.COAL_BLOCK)) return true
// other mods
ItemHolder.coalCoke?.let { if (it.isItemEqual(stack)) return true }
ItemHolder.coalCokeBlock?.let { if (it.isItemEqual(stack)) return true }
return false
}
override fun serializeNBT(): NBTTagCompound = newNbt {
add("burningTime", burningTime)
add("maxBurningTime", maxBurningTime)
add("doorOpen", doorOpen)
}
override fun deserializeNBT(nbt: NBTTagCompound) {
burningTime = nbt.getInteger("burningTime")
maxBurningTime = nbt.getInteger("maxBurningTime")
doorOpen = nbt.getBoolean("doorOpen")
}
override fun getGuiSyncVariables(): List<SyncVariable> {
return listOf(
IntSyncVariable(DATA_ID_BURNING_TIME, { burningTime }, { burningTime = it }),
IntSyncVariable(DATA_ID_MAX_BURNING_TIME, { maxBurningTime }, { maxBurningTime = it })
)
}
} | src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/ModuleCombustionChamber.kt | 2883020541 |
package com.baulsupp.okurl.completion
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class UrlListTest {
@Test
fun testReplacements() {
val l = UrlList(UrlList.Match.EXACT,
listOf("https://a.com/{location}", "https://a.com/here"))
assertEquals(listOf("https://a.com/A", "https://a.com/B", "https://a.com/{location}",
"https://a.com/here"), l.replace("location", listOf("A", "B"), true).getUrls(""))
}
@Test
fun testReplacementsEmpty() {
val l = UrlList(UrlList.Match.EXACT,
listOf("https://a.com/{location}", "https://a.com/here"))
assertEquals(listOf("https://a.com/{location}", "https://a.com/here"),
l.replace("location", listOf(), true).getUrls(""))
}
}
| src/test/kotlin/com/baulsupp/okurl/completion/UrlListTest.kt | 496083973 |
package org.jlleitschuh.gradle.ktlint
import org.gradle.api.Plugin
import org.gradle.api.Project
/**
* Adds tasks associated with configuring IntelliJ IDEA.
*/
open class KtlintIdeaPlugin : Plugin<Project> {
override fun apply(target: Project) {
val extension = target.plugins.apply(KtlintBasePlugin::class.java).extension
if (target == target.rootProject) {
/*
* Only add these tasks if we are applying to the root project.
*/
addApplyToIdeaTasks(target, extension)
}
}
private fun addApplyToIdeaTasks(rootProject: Project, extension: KtlintExtension) {
val ktLintConfig = createKtlintConfiguration(rootProject, extension)
rootProject.registerTask<KtlintApplyToIdeaTask>(APPLY_TO_IDEA_TASK_NAME) {
group = HELP_GROUP
description = "Generates IDEA built-in formatter rules and apply them to the project." +
"It will overwrite existing ones."
classpath.setFrom(ktLintConfig)
android.set(extension.android)
globally.set(rootProject.provider { false })
ktlintVersion.set(extension.version)
}
rootProject.registerTask<KtlintApplyToIdeaTask>(APPLY_TO_IDEA_GLOBALLY_TASK_NAME) {
group = HELP_GROUP
description = "Generates IDEA built-in formatter rules and apply them globally " +
"(in IDEA user settings folder). It will overwrite existing ones."
classpath.setFrom(ktLintConfig)
android.set(extension.android)
globally.set(rootProject.provider { true })
ktlintVersion.set(extension.version)
}
}
}
| plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintIdeaPlugin.kt | 3056350535 |
package com.jetbrains.rider.plugins.unity.run.attach
import com.intellij.execution.process.ProcessInfo
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder
import com.intellij.xdebugger.attach.*
import com.jetbrains.rd.platform.util.idea.getOrCreateUserData
import com.jetbrains.rider.plugins.unity.run.UnityProcessInfo
import com.jetbrains.rider.plugins.unity.run.UnityRunUtil
class UnityLocalAttachProcessDebuggerProvider : XAttachDebuggerProvider {
companion object {
val PROCESS_INFO_KEY: Key<MutableMap<Int, UnityProcessInfo>> = Key("UnityProcess::Info")
}
override fun getAvailableDebuggers(project: Project, host: XAttachHost, process: ProcessInfo, userData: UserDataHolder): MutableList<XAttachDebugger> {
if (UnityRunUtil.isUnityEditorProcess(process)) {
// Fetch the project + role names while we're not on the EDT, and cache so we can use it in the presenter
val unityProcessInfo = UnityRunUtil.getUnityProcessInfo(process, project)?.apply {
val map = userData.getOrCreateUserData(PROCESS_INFO_KEY) { mutableMapOf() }
map[process.pid] = this
}
return mutableListOf(UnityLocalAttachDebugger(unityProcessInfo))
}
return mutableListOf()
}
override fun isAttachHostApplicable(host: XAttachHost) = host is LocalAttachHost
override fun getPresentationGroup(): XAttachPresentationGroup<ProcessInfo> = UnityLocalAttachProcessPresentationGroup
} | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/run/attach/UnityLocalAttachProcessDebuggerProvider.kt | 2753577588 |
package reactivecircus.flowbinding.swiperefreshlayout
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.test.filters.LargeTest
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import reactivecircus.blueprint.testing.action.swipeDownOnView
import reactivecircus.flowbinding.swiperefreshlayout.fixtures.SwipeRefreshLayoutFragment
import reactivecircus.flowbinding.swiperefreshlayout.test.R
import reactivecircus.flowbinding.testing.FlowRecorder
import reactivecircus.flowbinding.testing.launchTest
import reactivecircus.flowbinding.testing.recordWith
@LargeTest
class SwipeRefreshLayoutRefreshFlowTest {
@Test
fun swipeRefreshLayoutRefreshes() {
launchTest<SwipeRefreshLayoutFragment> {
val recorder = FlowRecorder<Unit>(testScope)
val swipeRefreshLayout = getViewById<SwipeRefreshLayout>(R.id.swipeRefreshLayout)
swipeRefreshLayout.refreshes().recordWith(recorder)
recorder.assertNoMoreValues()
swipeDownOnView(R.id.swipeRefreshLayout)
assertThat(recorder.takeValue())
.isEqualTo(Unit)
cancelTestScope()
recorder.clearValues()
swipeDownOnView(R.id.swipeRefreshLayout)
recorder.assertNoMoreValues()
}
}
}
| flowbinding-swiperefreshlayout/src/androidTest/java/reactivecircus/flowbinding/swiperefreshlayout/SwipeRefreshLayoutRefreshFlowTest.kt | 1360014510 |
package org.fdroid.download
import mu.KotlinLogging
import org.fdroid.fdroid.ProgressListener
import org.fdroid.fdroid.isMatching
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.security.MessageDigest
public abstract class Downloader constructor(
@JvmField
protected val outputFile: File,
) {
public companion object {
private val log = KotlinLogging.logger {}
}
protected var fileSize: Long? = null
/**
* If not null, this is the expected sha256 hash of the [outputFile] after download.
*/
protected var sha256: String? = null
/**
* If you ask for the cacheTag before calling download(), you will get the
* same one you passed in (if any). If you call it after download(), you
* will get the new cacheTag from the server, or null if there was none.
*
* If this cacheTag matches that returned by the server, then no download will
* take place, and a status code of 304 will be returned by download().
*/
@Deprecated("Used only for v1 repos")
public var cacheTag: String? = null
@Volatile
private var cancelled = false
@Volatile
private var progressListener: ProgressListener? = null
/**
* Call this to start the download.
* Never call this more than once. Create a new [Downloader], if you need to download again!
*
* @totalSize must be set to what the index tells us the size will be
* @sha256 must be set to the sha256 hash from the index and only be null for `entry.jar`.
*/
@Throws(IOException::class, InterruptedException::class)
public abstract fun download(totalSize: Long, sha256: String? = null)
/**
* Call this to start the download.
* Never call this more than once. Create a new [Downloader], if you need to download again!
*/
@Deprecated("Use only for v1 repos")
@Throws(IOException::class, InterruptedException::class)
public abstract fun download()
@Throws(IOException::class, NotFoundException::class)
protected abstract fun getInputStream(resumable: Boolean): InputStream
protected open suspend fun getBytes(resumable: Boolean, receiver: BytesReceiver) {
throw NotImplementedError()
}
/**
* Returns the size of the file to be downloaded in bytes.
* Note this is -1 when the size is unknown.
* Used only for progress reporting.
*/
protected abstract fun totalDownloadSize(): Long
/**
* After calling [download], this returns true if a new file was downloaded and
* false if the file on the server has not changed and thus was not downloaded.
*/
@Deprecated("Only for v1 repos")
public abstract fun hasChanged(): Boolean
public abstract fun close()
public fun setListener(listener: ProgressListener) {
progressListener = listener
}
@Throws(IOException::class, InterruptedException::class)
protected fun downloadFromStream(isResume: Boolean) {
log.debug { "Downloading from stream" }
try {
FileOutputStream(outputFile, isResume).use { outputStream ->
getInputStream(isResume).use { input ->
// Getting the input stream is slow(ish) for HTTP downloads, so we'll check if
// we were interrupted before proceeding to the download.
throwExceptionIfInterrupted()
copyInputToOutputStream(input, outputStream)
}
}
// Even if we have completely downloaded the file, we should probably respect
// the wishes of the user who wanted to cancel us.
throwExceptionIfInterrupted()
} finally {
close()
}
}
@Suppress("BlockingMethodInNonBlockingContext")
@Throws(InterruptedException::class, IOException::class, NoResumeException::class)
protected suspend fun downloadFromBytesReceiver(isResume: Boolean) {
try {
val messageDigest: MessageDigest? = if (sha256 == null) null else {
MessageDigest.getInstance("SHA-256")
}
FileOutputStream(outputFile, isResume).use { outputStream ->
var bytesCopied = outputFile.length()
var lastTimeReported = 0L
val bytesTotal = totalDownloadSize()
getBytes(isResume) { bytes, numTotalBytes ->
// Getting the input stream is slow(ish) for HTTP downloads, so we'll check if
// we were interrupted before proceeding to the download.
throwExceptionIfInterrupted()
outputStream.write(bytes)
messageDigest?.update(bytes)
bytesCopied += bytes.size
val total = if (bytesTotal == -1L) numTotalBytes ?: -1L else bytesTotal
lastTimeReported = reportProgress(lastTimeReported, bytesCopied, total)
}
// check if expected sha256 hash matches
sha256?.let { expectedHash ->
if (!messageDigest.isMatching(expectedHash)) {
throw IOException("Hash not matching")
}
}
// force progress reporting at the end
reportProgress(0L, bytesCopied, bytesTotal)
}
// Even if we have completely downloaded the file, we should probably respect
// the wishes of the user who wanted to cancel us.
throwExceptionIfInterrupted()
} finally {
close()
}
}
/**
* This copies the downloaded data from the [InputStream] to the [OutputStream],
* keeping track of the number of bytes that have flown through for the [progressListener].
*
* Attention: The caller is responsible for closing the streams.
*/
@Throws(IOException::class, InterruptedException::class)
private fun copyInputToOutputStream(input: InputStream, output: OutputStream) {
val messageDigest: MessageDigest? = if (sha256 == null) null else {
MessageDigest.getInstance("SHA-256")
}
try {
var bytesCopied = outputFile.length()
var lastTimeReported = 0L
val bytesTotal = totalDownloadSize()
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var numBytes = input.read(buffer)
while (numBytes >= 0) {
throwExceptionIfInterrupted()
output.write(buffer, 0, numBytes)
messageDigest?.update(buffer, 0, numBytes)
bytesCopied += numBytes
lastTimeReported = reportProgress(lastTimeReported, bytesCopied, bytesTotal)
numBytes = input.read(buffer)
}
// check if expected sha256 hash matches
sha256?.let { expectedHash ->
if (!messageDigest.isMatching(expectedHash)) {
throw IOException("Hash not matching")
}
}
// force progress reporting at the end
reportProgress(0L, bytesCopied, bytesTotal)
} finally {
output.flush()
progressListener = null
}
}
private fun reportProgress(lastTimeReported: Long, bytesRead: Long, bytesTotal: Long): Long {
val now = System.currentTimeMillis()
return if (now - lastTimeReported > 100) {
log.debug { "onProgress: $bytesRead/$bytesTotal" }
progressListener?.onProgress(bytesRead, bytesTotal)
now
} else {
lastTimeReported
}
}
/**
* Cancel a running download, triggering an [InterruptedException]
*/
public fun cancelDownload() {
cancelled = true
}
/**
* After every network operation that could take a while, we will check if an
* interrupt occurred during that blocking operation. The goal is to ensure we
* don't move onto another slow, network operation if we have cancelled the
* download.
*
* @throws InterruptedException
*/
@Throws(InterruptedException::class)
private fun throwExceptionIfInterrupted() {
if (cancelled) {
log.info { "Received interrupt, cancelling download" }
Thread.currentThread().interrupt()
throw InterruptedException()
}
}
}
public fun interface BytesReceiver {
public suspend fun receive(bytes: ByteArray, numTotalBytes: Long?)
}
| libs/download/src/androidMain/kotlin/org/fdroid/download/Downloader.kt | 1617240023 |
package reactivecircus.flowbinding.material
import android.annotation.SuppressLint
import androidx.annotation.CheckResult
import com.google.android.material.slider.RangeSlider
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import reactivecircus.flowbinding.common.checkMainThread
/**
* Create a [Flow] of touch events on the [RangeSlider] instance.
*
* Note: Created flow keeps a strong reference to the [RangeSlider] instance
* until the coroutine that launched the flow collector is cancelled.
*
* Example of usage:
*
* ```
* rangeSlider.touchEvents()
* .onEach { event ->
* // handle event
* }
* .launchIn(uiScope)
* ```
*/
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
public fun RangeSlider.touchEvents(): Flow<RangeSliderTouchEvent> = callbackFlow {
checkMainThread()
val listener = object : RangeSlider.OnSliderTouchListener {
@SuppressLint("RestrictedApi")
override fun onStartTrackingTouch(rangeSlider: RangeSlider) {
trySend(RangeSliderTouchEvent.StartTracking(rangeSlider))
}
@SuppressLint("RestrictedApi")
override fun onStopTrackingTouch(rangeSlider: RangeSlider) {
trySend(RangeSliderTouchEvent.StopTracking(rangeSlider))
}
}
addOnSliderTouchListener(listener)
awaitClose { removeOnSliderTouchListener(listener) }
}.conflate()
public sealed class RangeSliderTouchEvent {
public abstract val rangeSlider: RangeSlider
public data class StartTracking(override val rangeSlider: RangeSlider) : RangeSliderTouchEvent()
public data class StopTracking(override val rangeSlider: RangeSlider) : RangeSliderTouchEvent()
}
| flowbinding-material/src/main/java/reactivecircus/flowbinding/material/RangeSliderTouchEventFlow.kt | 423273404 |
/*
* 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.
*/
package example.ui
import nl.komponents.kovenant.task
import nl.komponents.kovenant.ui.successUi
fun main(args: Array<String>) {
task {
1 + 1
} successUi {
//bla bla
}
}
| projects/ui/src/test/kotlin/example/ui.kt | 752517360 |
package com.fastaccess.ui.modules.repos.extras.license
import android.os.Bundle
import android.support.annotation.StringRes
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import com.evernote.android.state.State
import com.fastaccess.R
import com.fastaccess.helper.BundleConstant
import com.fastaccess.helper.Bundler
import com.fastaccess.ui.base.BaseMvpBottomSheetDialogFragment
import com.fastaccess.ui.widgets.StateLayout
import com.prettifier.pretty.PrettifyWebView
/**
* Created by Kosh on 30 Jun 2017, 12:38 PM
*/
class RepoLicenseBottomSheet : BaseMvpBottomSheetDialogFragment<RepoLicenseMvp.View, RepoLicensePresenter>(), RepoLicenseMvp.View,
PrettifyWebView.OnContentChangedListener {
@State var content: String? = null
val stateLayout: StateLayout by lazy { view!!.findViewById<StateLayout>(R.id.stateLayout) }
val loader: ProgressBar by lazy { view!!.findViewById<ProgressBar>(R.id.readmeLoader) }
val webView: PrettifyWebView by lazy { view!!.findViewById<PrettifyWebView>(R.id.webView) }
val licenseName: TextView by lazy { view!!.findViewById<TextView>(R.id.licenseName) }
override fun providePresenter(): RepoLicensePresenter = RepoLicensePresenter()
override fun onLicenseLoaded(license: String) {
this.content = license
if (!license.isNullOrBlank()) {
loader.isIndeterminate = false
val licenseText = license.replace("<pre>", "<pre style='overflow: hidden;word-wrap:break-word;word-break:break-all;" +
"white-space:pre-line;'>")
webView.setGithubContent("<div class='markdown-body'>$licenseText</div>", null)
} else {
hideProgress()
}
}
override fun fragmentLayout(): Int = R.layout.license_viewer_layout
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val login = arguments.getString(BundleConstant.EXTRA)
val repo = arguments.getString(BundleConstant.ID)
val licenseTitle = arguments.getString(BundleConstant.EXTRA_TWO)
licenseName.text = licenseTitle
if (content.isNullOrBlank() && !presenter.isApiCalled) {
presenter.onLoadLicense(login, repo)
} else {
content?.let { onLicenseLoaded(it) }
}
webView.setOnContentChangedListener(this)
}
override fun onContentChanged(progress: Int) {
loader.let {
it.progress = progress
if (progress == 100) {
it.visibility = View.GONE
hideProgress()
}
}
}
override fun showProgress(@StringRes resId: Int) {
loader.visibility = View.VISIBLE
loader.isIndeterminate = true
stateLayout.showProgress()
}
override fun hideProgress() {
loader.visibility = View.GONE
stateLayout.hideProgress()
}
override fun showErrorMessage(msgRes: String) {
hideProgress()
super.showErrorMessage(msgRes)
}
override fun showMessage(titleRes: Int, msgRes: Int) {
hideProgress()
super.showMessage(titleRes, msgRes)
}
override fun showMessage(titleRes: String, msgRes: String) {
hideProgress()
super.showMessage(titleRes, msgRes)
}
override fun onScrollChanged(reachedTop: Boolean, scroll: Int) {}
companion object {
fun newInstance(login: String, repo: String, license: String): RepoLicenseBottomSheet {
val view = RepoLicenseBottomSheet()
view.arguments = Bundler.start()
.put(BundleConstant.ID, repo)
.put(BundleConstant.EXTRA, login)
.put(BundleConstant.EXTRA_TWO, license)
.end()
return view
}
}
} | app/src/main/java/com/fastaccess/ui/modules/repos/extras/license/RepoLicenseBottomSheet.kt | 417179928 |
import kotlin.browser.window
abstract class Task
{
class Wait(var time: Double) : Task()
class Move(val location: Location, val placeItem: Item?) : Task()
{
override fun toString() =
if (placeItem == null) "Take item from $location"
else "Place ${placeItem.name} on $location"
}
}
abstract class LevelState
{
class AwaitVisitor(val character: Character, var progress: Double): LevelState()
class ManageItems(val character: Character, val tasks: ArrayList<Task>): LevelState()
class AwaitFailure(var progress: Double): LevelState()
class CheckPause(val character: Character, val messages: List<String>, var progress: Double) : LevelState()
}
val allItems = listOf(
Item(Point(50, 35), "Wallet"),
Item(Point(50, 40), "Flashlight"),
Item(Point(50, 60), "Kettle"),
Item(Point(50, 50), "Clock"),
Item(Point(50, 45), "Book"),
Item(Point(50, 35), "Pencil"),
Item(Point(50, 60), "Ball"),
Item(Point(50, 50), "Hat"),
Item(Point(50, 80), "Panda"))
val colors = listOf(
0xFFFFFF,
0x0000FF,
0xFF00FF,
0xFFFF00,
0x00FFFF,
0xAAAAAA,
0x8844AA,
0xAA8844,
0x44AA88)
class Level(val container: PIXI.Container, val stageSize: Point,
val charactersCount: Int = 3,
val itemsPerCharacter: Int = 1,
val dialogTexture: PIXI.BaseTexture)
{
val size = Point(560, 240)
val spawnPoint = Point(size.x / 2, 80)
val topLeft = Point(50, 80)
val bottomRight = Point(510, 200)
val locations = arrayListOf<Location>()
val characterSize = Point(60, 30)
val player = Character(characterSize)
val inventory = Array<Item?>(allItems.size) {null}
val npcs = arrayListOf<Character>()
val schedule: Schedule
var currentState: LevelState
var activeLocation: Location? = null
var moveDirection = Direction.None
val roomRoot = PIXI.Container()
val inventoryRoot = PIXI.Container()
val inventoryGraphics = PIXI.Graphics()
val graphics = PIXI.Graphics()
val locationSprites = arrayListOf<PIXI.Sprite>()
val itemSprites = arrayListOf<PIXI.Sprite>()
val inventorySprites = arrayListOf<PIXI.Sprite>()
//val inventoryHighlights = Array(allItems.size) {0.0}
val highlightSprite: PIXI.Sprite
val playerSprite: PIXI.Sprite
val npcSprite: PIXI.Sprite
var npcSpriteFirst: Boolean = true
val previewSprite: PIXI.Sprite
val playerAnimation: CharacterAnimation
val npcAnimation: CharacterAnimation
val help: PIXI.Text
var levelCompleted: Boolean? = null
init
{
val shuffledItems = ArrayList(allItems)
permute(shuffledItems)
for (i in 0..charactersCount - 1)
{
val items = shuffledItems.drop(itemsPerCharacter * i).take(itemsPerCharacter)
val character = Character(characterSize)
character.items.addAll(items)
npcs.add(character)
}
val locationsCount = 4
val spacing = size.x / (locationsCount + 1)
for (i in 0..locationsCount - 1)
{
val location = Location(Point(75, 75))
location.position =
Point((i + 1) * spacing - location.width / 2,
size.y - location.height)
locations.add(location)
}
schedule = Schedule(npcs, locations, rounds = 6)
currentState = LevelState.AwaitVisitor(schedule.nextCharacter, 0.5)
val inventoryPart = stageSize.y / 5
val background = PIXI.Sprite(LevelResources.roomTexture)
background.width = size.x
background.position = PIXI.Point(0, 8)
roomRoot.addChild(background)
roomRoot.addChild(graphics)
roomRoot.position = PIXI.Point((stageSize.x - size.x) / 2, inventoryPart)
playerSprite = PIXI.Sprite(LevelResources.characterTextures[1])
npcSprite = PIXI.Sprite(LevelResources.characterTextures[1])
npcSprite.visible = false
player.position = spawnPoint
playerAnimation = CharacterAnimation(playerSprite)
npcAnimation = CharacterAnimation(npcSprite)
roomRoot.addChild(playerSprite)
roomRoot.addChild(npcSprite)
for (location in locations)
{
val sprite = PIXI.Sprite(LevelResources.tableTexture)
sprite.width = location.width
sprite.height = location.height
sprite.position = PIXI.Point(location.x, location.y - 10)
locationSprites.add(sprite)
roomRoot.addChild(sprite)
}
highlightSprite = PIXI.Sprite(LevelResources.tableTexture)
highlightSprite.visible = false
highlightSprite.width = 75
highlightSprite.height = 75
highlightSprite.blendMode = PIXI.BLEND_MODES.SCREEN
roomRoot.addChild(highlightSprite)
for (i in allItems.indices)
{
val sprite = PIXI.Sprite(LevelResources.itemTextures[i])
roomRoot.addChild(sprite)
itemSprites.add(sprite)
sprite.visible = false
}
previewSprite = PIXI.Sprite(LevelResources.characterTextures[
(npcs.indexOf(schedule.nextCharacter) + 1) * 3 + 1])
previewSprite.position = PIXI.Point(0, size.y + 20)
previewSprite.scale = PIXI.Point(0.5, 0.5)
roomRoot.addChild(previewSprite)
inventoryGraphics.lineStyle(3, 0xAA7700)
val shift = size.x.toDouble() / (allItems.size) + 1
for ((i, item) in allItems.withIndex())
{
val sprite = PIXI.Sprite(LevelResources.itemTextures[i])
sprite.width = 60
sprite.height = 60
//sprite._tint = 0x444444
sprite.visible = false
sprite.position = PIXI.Point((i + 1) * shift - sprite.width.toDouble() / 2, 6)
inventoryRoot.addChild(sprite)
inventorySprites.add(sprite)
inventoryGraphics.drawRect(
sprite.position.x.toInt() - 2, sprite.position.y.toInt() + 4,
sprite.width.toInt() + 4, sprite.height.toInt() + 4)
}
inventoryRoot.addChild(inventoryGraphics)
val helpText = "<Arrows>, <WASD>: Move\n<Enter>, <Space>: Skip to the next visitor\n<1-9>: Take/place item\n<Esc>: Pause"
help = PIXI.Text(helpText, TextStyle(
fill = "blanchedAlmond",
wordWrap = false,
font = "14pt"))
help.position = PIXI.Point(80, size.y + 10)
roomRoot.addChild(help)
container.addChild(inventoryRoot)
container.addChild(roomRoot)
}
fun update()
{
if (moveDirection != Direction.None)
{
playerAnimation.start()
move(moveDirection.shift)
}
else
{
playerAnimation.stop()
}
playerAnimation.update(player.position, moveDirection)
graphics.clear()
graphics.lineStyle(4, 0x00FF00)
/*graphics.lineStyle(4, 0xFF0000)
graphics.drawRect(0, 0, size.x, size.y)
graphics.lineStyle(2, 0x00FF00)
for (it in locations)
{
if (it == activeLocation) graphics.lineStyle(2, 0xFFFF00)
else graphics.lineStyle(2, 0x00FF00)
graphics.draw(it)
val item = it.item
if (item != null)
{
graphics.lineStyle(2, colors[allItems.indexOf(item)])
graphics.drawRect(it.x, it.y, item.width, item.height)
}
}
graphics.lineStyle(2, 0x00FF00)
graphics.draw(player)*/
val state = currentState
when (state)
{
is LevelState.AwaitVisitor ->
{
activeLocation =
if (player.position.y > bottomRight.y - 30)
locations.minBy { Math.abs((it.midX - player.x).toDouble()) }
else
null
graphics.beginFill(0x0000FF)
graphics.drawRect(0, size.y, state.progress * 50, 10)
graphics.endFill()
state.progress -= 0.001
if (state.progress <= 0.0)
{
activeLocation = null
state.character.position = spawnPoint
npcSprite.visible = true
npcAnimation.animationIndex = npcs.indexOf(state.character) + 1
npcAnimation.stop()
npcAnimation.update(state.character.position, Direction.Left)
val messages = schedule.checkState()
currentState = LevelState.CheckPause(
state.character, messages, if (messages.isNotEmpty()) 1.0 else 0.5)
}
}
is LevelState.CheckPause ->
{
state.progress -= 0.02
if (state.progress <= 0)
{
if (state.messages.isNotEmpty())
{
initFailure(state.messages)
}
else
{
val tasks = createTasks(state.character)
currentState = LevelState.ManageItems(state.character, tasks)
npcAnimation.start()
npcAnimation.update(state.character.position, Direction.Left)
}
}
}
is LevelState.ManageItems ->
{
val character = state.character
//graphics.draw(character)
if (state.tasks.isEmpty())
{
schedule.rememberState()
if (schedule.completed)
{
levelCompleted = true
}
else
{
currentState = LevelState.AwaitVisitor(schedule.nextCharacter, 1.0)
activeLocation = null
npcSprite.visible = false
npcAnimation.stop()
previewSprite.texture =
LevelResources.characterTextures[
(npcs.indexOf(schedule.nextCharacter) + 1) * 3 + 1]
}
}
else
{
val task = state.tasks.first()
if (task is Task.Wait)
{
val dy = if (character.y > topLeft.y + 10) - 2 else 0
val dx = when
{
(topLeft.x + bottomRight.x) / 2 > character.x + 4 -> 3
(topLeft.x + bottomRight.x) / 2 < character.x - 4 -> -3
else -> 0
}
if (dx != 0 || dy != 0)
{
character.position += Point(dx, dy)
npcAnimation.update(
character.position,
when
{
dx > 0 -> Direction.Right
dx < 0 -> Direction.Left
else -> Direction.Up
})
}
else
{
npcAnimation.stop()
task.time -= 0.1
if (task.time <= 0.0)
{
state.tasks.removeAt(0)
npcAnimation.start()
}
}
}
else if (task is Task.Move)
{
val dx = Math.abs((task.location.midX - character.x).toDouble()).toInt()
if (character.y > bottomRight.y - 20 &&
dx < task.location.width / 4)
{
val item = task.location.item
if (item != null)
{
updateItemSprite(item, null)
character.items.add(item)
task.location.item = null
}
else if (task.placeItem != null)
{
updateItemSprite(task.placeItem, task.location)
character.items.remove(task.placeItem)
task.location.item = task.placeItem
}
state.tasks.removeAt(0)
}
else
{
val shift = Point(
when
{
task.location.midX > character.x + 4 -> 3
task.location.midX < character.x - 4 -> -3
else -> 0
},
if (character.y < bottomRight.y) 2 else 0)
character.position += shift
npcAnimation.update(
character.position,
if (shift.x > 0) Direction.Right else Direction.Left)
}
}
}
}
is LevelState.AwaitFailure ->
{
state.progress -= 0.005
if (state.progress <= 0.0)
{
levelCompleted = false
}
}
}
val location = activeLocation
if (location != null)
{
highlightSprite.position = PIXI.Point(location.x, location.y - 10)
highlightSprite.visible = true
}
else
{
highlightSprite.visible = false
}
if (npcSpriteFirst)
{
if (npcSprite.position.y.toInt() < playerSprite.position.y.toInt())
{
roomRoot.swapChildren(playerSprite, npcSprite)
npcSpriteFirst = false
}
}
else
{
if (npcSprite.position.y.toInt() > playerSprite.position.y.toInt())
{
roomRoot.swapChildren(playerSprite, npcSprite)
npcSpriteFirst = true
}
}
}
fun PIXI.Graphics.draw(item: GameItem)
{
drawRect(item.x, item.y, item.width, item.height)
}
fun initFailure(messages: List<String>)
{
val text = PIXI.Text(messages.take(3).joinToString("\n"), TextStyle(
fill = "blanchedAlmond",
font = "14pt bold",
align = "center"))
val width = text.width.toInt() + Dialog.side * 2 + Dialog.tileSize * 2
val height = text.height.toInt() + Dialog.side * 2 + Dialog.tileSize
val dialog = Dialog(
roomRoot,
PIXI.Rectangle((size.x - width) / 2, 0, width, height),
dialogTexture)
text.position = PIXI.Point(
(dialog.clientWidth - text.width.toInt()) / 2,
(dialog.clientHeight - text.height.toInt()) / 2)
dialog.add(text)
currentState = LevelState.AwaitFailure(1.0)
}
fun updateItemSprite(item: Item, location: Location?)
{
val sprite = itemSprites[allItems.indexOf(item)]
if (location == null)
{
sprite.visible = false
}
else
{
sprite.position = PIXI.Point(
location.position.x + (location.width - item.width) / 2,
location.position.y - item.height / 4 - 15)
val scale = item.width / sprite.texture.frame.width.toDouble()
sprite.scale = PIXI.Point(scale, scale)
sprite.visible = true
}
}
fun move(shift: Point)
{
val state = currentState
val scaleShift = shift * 4
var newPosition = player.position + scaleShift
if (state is LevelState.ManageItems)
{
newPosition = state.character.block(player, scaleShift) ?: newPosition
}
player.position = newPosition.clamp(topLeft, bottomRight)
}
fun createTasks(character: Character): ArrayList<Task>
{
val heldItems = character.items
val placedItems = locations.mapNotNull{ it.item }
val maxActions = heldItems.size + placedItems.size
val actions = Math.min(2, (Math.random() * (maxActions - 1)).toInt() + 1)
val _takeActions = (Math.random() * actions).toInt()
val _placeActions = Math.min(actions - _takeActions, heldItems.size)
val takeActions = Math.min(placedItems.size, Math.max(_takeActions, actions - _placeActions))
val placeActions = Math.min(heldItems.size, Math.max(_placeActions, actions - takeActions))
val tasks = arrayListOf<Task>()
for (i in 0..takeActions - 1)
{
val item = placedItems[i]
val location = locations.first{ it.item == item }
tasks.add(Task.Move(location, null))
}
val placeLocations = ArrayList(locations)
permute(placeLocations)
for ((i, location) in placeLocations.take(placeActions).withIndex())
{
val item = heldItems[i]
tasks.add(Task.Move(location, item))
}
tasks.add(Task.Wait(0.5))
return tasks
}
fun GameItem.block(other: GameItem, shift: Point): Point?
{
val intersects =
other.x + shift.x in x - other.width..endX &&
other.y + shift.y in y - other.height..endY
return if (intersects)
{
val xClamp = when
{
x in other.endX..other.endX + shift.x -> x - other.width - 1
endX in other.x + shift.x..other.x -> endX + 1
else -> other.x + shift.x
}
val yClamp = when
{
y in other.endY..other.endY + shift.y -> y - other.height - 1
endY in other.y + shift.y..other.y -> endY + 1
else -> other.y + shift.y
}
Point(xClamp, yClamp)
}
else
{
null
}
}
fun action(inventoryIndex: Int)
{
val location = activeLocation
if (location != null)
{
val item = location.item
val replaceItem = inventory[inventoryIndex]
if (item != null)
{
updateItemSprite(item, null)
location.item = null
inventory[inventoryIndex] = item
}
if (replaceItem != null)
{
updateItemSprite(replaceItem, location)
location.item = replaceItem
if (item == null)
{
inventory[inventoryIndex] = null
}
}
}
val shift = size.x.toDouble() / (allItems.size) + 1
inventorySprites.forEach { it.visible = false }
for ((i, item) in allItems.withIndex())
{
val index = inventory.indexOf(item)
if (index >= 0)
{
val sprite = inventorySprites[i]
sprite.position = PIXI.Point((index + 1) * shift - sprite.width.toDouble() / 2, 10)
sprite.visible = true
}
}
}
fun hurry()
{
val state = currentState
if (state is LevelState.AwaitVisitor)
{
state.progress = 0.0
}
else if (state is LevelState.AwaitFailure)
{
state.progress = 0.08
}
}
companion object
{
val activateDistance = 20
}
}
object LevelResources
{
val roomTexture = PIXI.Texture.fromImage("images/room.png", false)
val tableTexture = PIXI.Texture.fromImage("images/table.png", false)
val itemsBase = PIXI.BaseTexture.fromImage("images/items.png", false)
val itemTextures = itemsBase.slice(100, 100, 100)
val charactersBase = PIXI.BaseTexture.fromImage("images/characters.png", false)
val characterTextures = charactersBase.slice(PIXI.Point(100, 162), 3, 4)
}
class CharacterAnimation(val sprite: PIXI.Sprite, var animationIndex: Int = 0)
{
var progress = 0.0
var isRunning = false
val scale = 0.65
var orientation = 1.0
fun start()
{
isRunning = true
}
fun stop()
{
isRunning = false
sprite.texture = LevelResources.characterTextures[animationIndex * 3 + 1]
}
fun update(position: Point, direction: Direction)
{
if (isRunning)
{
progress += 0.1
if (progress >= 4.0)
{
progress = 0.0
}
val frame = Math.floor(progress)
val texture = animationIndex * 3 + frame - 2 * frame.div(3)
sprite.texture = LevelResources.characterTextures[texture]
when (direction)
{
Direction.Right -> orientation = -1.0
Direction.Left -> orientation = 1.0
Direction.Up -> orientation = if (position.x < 280) 1.0 else -1.0
Direction.Down -> orientation = if (position.x < 280) -1.0 else 1.0
}
}
val dy = 200 - position.y
val perspective = 1.0 - dy / 270.0
val dx = (280 - position.x) * perspective
val x = 280 - dx
val scale = scale * perspective
sprite.scale = PIXI.Point(scale * orientation, scale)
val y = position.y - sprite.height.toInt()
val w = sprite.width.toInt() / 2
sprite.position =
if (sprite.scale.x.toDouble() > 0) PIXI.Point(x - w, y)
else PIXI.Point(x + w, y)
}
}
class Schedule(val characters: List<Character>,
val locations: List<Location>,
val rounds: Int)
{
class Entry(val character: Character)
{
val expectedState = arrayListOf<Pair<Location, Item?>>()
}
val entries = arrayListOf<Entry>()
var nextEntry = 0
val nextCharacter: Character
get() = entries[nextEntry].character
val completed: Boolean; get() = nextEntry >= entries.size
init
{
for (round in 0..rounds - 1)
{
characters.forEach { entries.add(Entry(it)) }
permute(entries, round * characters.size, characters.size)
}
if (characters.size > 1)
{
for (round in 1..rounds - 1)
{
val borderIndex = round * characters.size
if (entries[borderIndex].character == entries[borderIndex - 1].character)
{
val swapIndex =
borderIndex + 1 + (Math.random() * (characters.size - 1)).toInt()
val t = entries[borderIndex]
entries[borderIndex] = entries[swapIndex]
entries[swapIndex] = t
}
}
}
for (character in characters)
{
val entry = entries.first{it.character == character}
for (location in locations)
{
entry.expectedState.add(Pair(location, null))
}
}
}
fun nextVisit(character: Character) =
(nextEntry + 1..entries.size - 1)
.firstOrNull{ entries[it].character == character }
?: - 1
fun rememberState()
{
val returnEntry = nextVisit(entries[nextEntry].character)
++nextEntry
if (returnEntry >= 0)
{
val entry = entries[returnEntry]
for (location in locations)
{
entry.expectedState.add(Pair(location, location.item))
}
}
}
fun checkState(): List<String>
{
val result = ArrayList<String>()
val entry = entries[nextEntry]
val expectedItems = entry.expectedState.mapNotNull{ it.second }
for ((location, item) in entry.expectedState)
{
val existingItem = location.item
if (existingItem == null)
{
if (item != null && !locations.any{it.item == item})
{
result.add("Where is my ${item.name}?!")
}
}
else if (!expectedItems.contains(existingItem))
{
result.add("What is this ${existingItem.name} doing here?!")
}
else if (existingItem != item)
{
result.add("Why has my ${existingItem.name} been moved?!")
}
}
return result
}
}
inline fun <reified T> permute(list: MutableList<T>,
start: Int = 0,
count: Int = list.size)
{
for (i in 0..count - 1)
{
val swapIndex = (Math.random() * (i + 1)).toInt()
if (swapIndex < i)
{
val t = list[start + swapIndex]
list[start + swapIndex] = list[start + i]
list[start + i] = t
}
}
}
open class GameItem(val size: Point)
{
var position = Point.zero
val x: Int; get() = position.x
val y: Int; get() = position.y
val width: Int; get() = size.x
val height: Int; get() = size.y
val midX: Int; get() = x + width / 2
val midY: Int; get() = y + height / 2
val endX: Int; get() = x + width
val endY: Int; get() = y + height
}
class Location(size: Point) : GameItem(size)
{
var item: Item? = null
}
class Character(size: Point) : GameItem(size)
{
val items = arrayListOf<Item>()
}
class Item(val size: Point, val name: String)
{
val width: Int; get() = size.x
val height: Int; get() = size.y
} | src/Level.kt | 2459470965 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
class RsExtraSemicolonInspectionTest : RsInspectionsTestBase(RsExtraSemicolonInspection()) {
fun `test not applicable without return type`() = checkByText("""
fn foo() { 92; }
""")
fun `test not applicable for let`() = checkByText("""
fn foo() -> i32 { let x = 92; }
""")
fun `test not applicable with explicit return`() = checkByText("""
fn foo() -> i32 { return 92; }
""")
fun `test not applicable with explicit unit type`() = checkByText("""
fn fun() -> () { 2 + 2; }
""")
fun `test not applicable with macro`() = checkByText("""
fn fun() -> i32 { panic!("diverge"); }
""")
fun `test not applicable with trailing fn`() = checkByText("""
fn foo() -> bool {
loop {}
fn f() {}
}
""")
fun `test not applicable with diverging if`() = checkByText("""
fn a() -> i32 {
if true { return 0; } else { return 6; };
}
""")
fun `test fix`() = checkFixByText("Remove semicolon", """
fn foo() -> i32 {
let x = 92;
<warning descr="Function returns () instead of i32">x;<caret></warning>
}
""", """
fn foo() -> i32 {
let x = 92;
x
}
""")
fun `test recurse into complex expressions`() = checkFixByText("Remove semicolon", """
fn foo() -> i32 {
let x = 92;
if true {
<warning descr="Function returns () instead of i32">x;<caret></warning>
} else {
x
}
}
""", """
fn foo() -> i32 {
let x = 92;
if true {
x<caret>
} else {
x
}
}
""")
}
| src/test/kotlin/org/rust/ide/inspections/RsExtraSemicolonInspectionTest.kt | 2337695639 |
package com.android.szparag.todoist
interface TodoistRecyclerAdapter<E : Any> {
fun updateData(updatedList: List<E>)
fun updateData(updatedListRanges: List<E>, fromIndex: Int, changedElementsCount: Int)
fun get(index: Int): E
fun get(): List<E>
} | app/src/main/java/com/android/szparag/todoist/TodoistRecyclerAdapter.kt | 3466162122 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.example.jetnews.ui
import android.os.Bundle
import androidx.annotation.MainThread
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.core.os.bundleOf
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import com.example.jetnews.ui.Screen.*
import com.example.jetnews.ui.ScreenName.*
import com.example.jetnews.utils.getMutableStateOf
/**
* Screen names (used for serialization)
*/
enum class ScreenName { HOME, INTERESTS, ARTICLE }
/**
* Class defining the screens we have in the app: home, article details and interests
*/
sealed class Screen(val id: ScreenName) {
object Home : Screen(HOME)
object Interests : Screen(INTERESTS)
data class Article(val postId: String) : Screen(ARTICLE)
}
/**
* Helpers for saving and loading a [Screen] object to a [Bundle].
*
* This allows us to persist navigation across process death, for example caused by a long video
* call.
*/
private const val SIS_SCREEN = "sis_screen"
private const val SIS_NAME = "screen_name"
private const val SIS_POST = "post"
/**
* Convert a screen to a bundle that can be stored in [SavedStateHandle]
*/
private fun Screen.toBundle(): Bundle {
return bundleOf(SIS_NAME to id.name).also {
// add extra keys for various types here
if (this is Article) {
it.putString(SIS_POST, postId)
}
}
}
/**
* Read a bundle stored by [Screen.toBundle] and return desired screen.
*
* @return the parsed [Screen]
* @throws IllegalArgumentException if the bundle could not be parsed
*/
private fun Bundle.toScreen(): Screen {
val screenName = ScreenName.valueOf(getStringOrThrow(SIS_NAME))
return when (screenName) {
HOME -> Home
INTERESTS -> Interests
ARTICLE -> {
val postId = getStringOrThrow(SIS_POST)
Article(postId)
}
}
}
/**
* Throw [IllegalArgumentException] if key is not in bundle.
*
* @see Bundle.getString
*/
private fun Bundle.getStringOrThrow(key: String) =
requireNotNull(getString(key)) { "Missing key '$key' in $this" }
/**
* This is expected to be replaced by the navigation component, but for now handle navigation
* manually.
*
* Instantiate this ViewModel at the scope that is fully-responsible for navigation, which in this
* application is [MainActivity].
*
* This app has simplified navigation; the back stack is always [Home] or [Home, dest] and more
* levels are not allowed. To use a similar pattern with a longer back stack, use a [StateList] to
* hold the back stack state.
*/
class NavigationViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() {
/**
* Hold the current screen in an observable, restored from savedStateHandle after process
* death.
*
* mutableStateOf is an observable similar to LiveData that's designed to be read by compose. It
* supports observability via property delegate syntax as shown here.
*/
var currentScreen: Screen by savedStateHandle.getMutableStateOf<Screen>(
key = SIS_SCREEN,
default = Home,
save = { it.toBundle() },
restore = { it.toScreen() }
)
private set // limit the writes to only inside this class.
/**
* Go back (always to [Home]).
*
* Returns true if this call caused user-visible navigation. Will always return false
* when [currentScreen] is [Home].
*/
@MainThread
fun onBack(): Boolean {
val wasHandled = currentScreen != Home
currentScreen = Home
return wasHandled
}
/**
* Navigate to requested [Screen].
*
* If the requested screen is not [Home], it will always create a back stack with one element:
* ([Home] -> [screen]). More back entries are not supported in this app.
*/
@MainThread
fun navigateTo(screen: Screen) {
currentScreen = screen
}
} | koin-projects/examples/androidx-compose-jetnews/src/main/java/com/example/jetnews/ui/Navigation.kt | 1207058341 |
/*
* 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.testGuiFramework.recorder
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.ui.SimpleToolWindowPanel
import com.intellij.openapi.util.Ref
import com.intellij.openapi.wm.WindowManager
import com.intellij.testGuiFramework.fixtures.SettingsTreeFixture
import com.intellij.testGuiFramework.generators.ComponentCodeGenerator
import com.intellij.testGuiFramework.generators.Generators
import com.intellij.testGuiFramework.recorder.ScriptGenerator.scriptBuffer
import com.intellij.testGuiFramework.recorder.components.GuiRecorderComponent
import com.intellij.testGuiFramework.recorder.ui.KeyUtil
import com.intellij.ui.KeyStrokeAdapter
import com.intellij.ui.treeStructure.SimpleTree
import com.intellij.util.ui.tree.TreeUtil
import java.awt.Component
import java.awt.Menu
import java.awt.MenuItem
import java.awt.Point
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import javax.swing.JComponent
import javax.swing.JList
import javax.swing.JTree
import javax.swing.KeyStroke.getKeyStrokeForEvent
import javax.swing.tree.TreeNode
import javax.swing.tree.TreePath
/**
* @author Sergey Karashevich
*/
object ScriptGenerator {
val scriptBuffer = StringBuilder("")
var openComboBox = false
fun getScriptBuffer() = scriptBuffer.toString()
fun clearScriptBuffer() = scriptBuffer.setLength(0)
private val generators: List<ComponentCodeGenerator<*>> = Generators.getGenerators()
object ScriptWrapper {
val TEST_METHOD_NAME = "testMe"
private fun classWrap(function: () -> (String)): String = "class CurrentTest: GuiTestCase() {\n${function.invoke()}\n}"
private fun funWrap(function: () -> String): String = "fun $TEST_METHOD_NAME(){\n${function.invoke()}\n}"
private fun importsWrap(vararg imports: String, function: () -> String): String {
val sb = StringBuilder()
imports.forEach { sb.append("$it\n") }
sb.append(function.invoke())
return sb.toString()
}
fun wrapScript(code: String): String =
importsWrap(
"import com.intellij.testGuiFramework.* ",
"import com.intellij.testGuiFramework.fixtures.*",
"import com.intellij.testGuiFramework.framework.*",
"import com.intellij.testGuiFramework.impl.*",
"import org.fest.swing.core.Robot",
"import java.awt.Component",
"import com.intellij.openapi.application.ApplicationManager",
"import org.fest.swing.fixture.*")
{
classWrap {
funWrap {
code
}
}
}
}
// fun actionPerformed(e: com.intellij.openapi.actionSystem.AnActionEvent?) {
// get action type for script: click, enter text, mark checkbox
// val component = e!!.getDataContext().getData("Component") as Component
// checkGlobalContext(component)
// clickCmp(component, e)
// }
fun processTyping(keyChar: Char) {
Typer.type(keyChar)
}
//(keyEvent.id == KeyEvent.KEY_PRESSED) for all events here
fun processKeyPressing(keyEvent: KeyEvent) {
//retrieve shortcut here
// val keyStroke = getKeyStrokeForEvent(keyEvent)
// val actionIds = KeymapManager.getInstance().activeKeymap.getActionIds(keyStroke)
// if (!actionIds.isEmpty()) {
// val firstActionId = actionIds[0]
// if (IgnoredActions.ignore(firstActionId)) return
// val keyStrokeStr = KeyStrokeAdapter.toString(keyStroke)
// if (IgnoredActions.ignore(keyStrokeStr)) return
// Writer.writeln(Templates.invokeActionComment(firstActionId))
// makeIndent()
// Writer.writeln(Templates.shortcut(keyStrokeStr))
// }
}
fun processKeyActionEvent(anAction: AnAction, anActionEvent: AnActionEvent) {
//retrieve shortcut here
val keyEvent = anActionEvent.inputEvent as KeyEvent
val keyStroke = getKeyStrokeForEvent(keyEvent)
val actionId = anActionEvent.actionManager.getId(anAction)
if (IgnoredActions.ignore(actionId)) return
val keyStrokeStr = KeyStrokeAdapter.toString(keyStroke)
if (IgnoredActions.ignore(keyStrokeStr)) return
ScriptGenerator.flushTyping()
addToScript(Templates.invokeActionComment(actionId))
addToScript(Templates.shortcut(keyStrokeStr))
}
// clickComponent methods
fun clickComponent(component: Component, convertedPoint: Point, me: MouseEvent) {
awareListsAndPopups(component) {
ContextChecker.checkContext(component, me, convertedPoint)
// checkGlobalContext(component, me, convertedPoint)
// checkLocalContext(component, me, convertedPoint)
}
val suitableGenerator = generators.filter { generator -> generator.accept(component) }.sortedByDescending(
ComponentCodeGenerator<*>::priority).firstOrNull() ?: return
val code = suitableGenerator.generateCode(component, me, convertedPoint)
addToScript(code)
}
//
fun awareListsAndPopups(cmp: Component, body: () -> Unit) {
cmp as JComponent
if (cmp is JList<*> && openComboBox) return //don't change context for comboBox list
if (isPopupList(cmp)) return //dont' change context for a popup menu
body()
}
fun clearContext() {
ContextChecker.clearContext()
}
fun processMainMenuActionEvent(anActionToBePerformed: AnAction, anActionEvent: AnActionEvent) {
val actionId: String? = ActionManager.getInstance().getId(anActionToBePerformed)
if (actionId == null) {
addToScript("//called action (${anActionToBePerformed.templatePresentation.text}) from main menu with null actionId"); return
}
addToScript(Templates.invokeMainMenuAction(actionId))
}
fun flushTyping() {
Typer.flushBuffer()
}
private fun isPopupList(cmp: Component) = cmp.javaClass.name.toLowerCase().contains("listpopup")
private fun isFrameworksTree(cmp: Component) = cmp.javaClass.name.toLowerCase().contains("AddSupportForFrameworksPanel".toLowerCase())
private fun Component.inToolWindow(): Boolean {
var pivotComponent = this
while (pivotComponent.parent != null) {
if (pivotComponent is SimpleToolWindowPanel) return true
else pivotComponent = pivotComponent.parent
}
return false
}
fun addToScript(code: String, withIndent: Boolean = true, indent: Int = 2) {
if (withIndent) {
val indentedString = (0..(indent * ContextChecker.getContextDepth() - 1)).map { i -> ' ' }.joinToString(separator = "")
ScriptGenerator.addToScriptDelegate("$indentedString$code")
}
else ScriptGenerator.addToScriptDelegate(code)
}
//use it for outer generators
private fun addToScriptDelegate(code: String?) {
if (code != null) Writer.writeln(code)
}
}
object Writer {
fun writeln(str: String) {
write(str + "\n")
}
fun write(str: String) {
writeToConsole(str)
if (GuiRecorderComponent.getFrame() != null && GuiRecorderComponent.getFrame()!!.isSyncToEditor())
writeToEditor(str)
else
writeToBuffer(str)
}
fun writeToConsole(str: String) {
print(str)
}
fun writeToBuffer(str: String) {
scriptBuffer.append(str)
}
fun writeToEditor(str: String) {
if (GuiRecorderComponent.getFrame() != null && GuiRecorderComponent.getFrame()!!.getEditor() != null) {
val editor = GuiRecorderComponent.getFrame()!!.getEditor()
val document = editor.document
// ApplicationManager.getApplication().runWriteAction { document.insertString(document.textLength, str) }
WriteCommandAction.runWriteCommandAction(null, { document.insertString(document.textLength, str) })
}
}
}
private object Typer {
val strBuffer = StringBuilder()
val rawBuffer = StringBuilder()
fun type(keyChar: Char) {
strBuffer.append(KeyUtil.patch(keyChar))
rawBuffer.append("${if (rawBuffer.length > 0) ", " else ""}\"${keyChar.toInt()}\"")
}
fun flushBuffer() {
if (strBuffer.length == 0) return
ScriptGenerator.addToScript("//typed:[${strBuffer.length},\"${strBuffer.toString()}\", raw=[${rawBuffer.toString()}]]")
ScriptGenerator.addToScript(Templates.typeText(strBuffer.toString()))
strBuffer.setLength(0)
rawBuffer.setLength(0)
}
}
//TEMPLATES
object IgnoredActions {
val ignoreActions = listOf("EditorBackSpace")
val ignoreShortcuts = listOf("space")
fun ignore(actionOrShortCut: String): Boolean = (ignoreActions.contains(actionOrShortCut) || ignoreShortcuts.contains(actionOrShortCut))
}
object Util {
// fun isActionFromMainMenu(anActionTobePerformed: AnAction, anActionEvent: AnActionEvent): Boolean {
// val menuBar = WindowManager.getInstance().findVisibleFrame().menuBar ?: return false
// }
fun getPathFromMainMenu(anActionTobePerformed: AnAction, anActionEvent: AnActionEvent): String? {
// WindowManager.getInstance().findVisibleFrame().menuBar.getMenu(0).label
val menuBar = WindowManager.getInstance().findVisibleFrame().menuBar ?: return null
//in fact it should be only one String in "map"
return (0..(menuBar.menuCount - 1)).mapNotNull {
traverseMenu(menuBar.getMenu(it), anActionTobePerformed.templatePresentation.text!!)
}.lastOrNull()
}
fun traverseMenu(menuItem: MenuItem, itemName: String): String? {
if (menuItem is Menu) {
if (menuItem.itemCount == 0) {
if (menuItem.label == itemName) return itemName
else return null
}
else {
(0..(menuItem.itemCount - 1))
.mapNotNull { traverseMenu(menuItem.getItem(it), itemName) }
.forEach { return "${menuItem.label};$it" }
return null
}
}
else {
if (menuItem.label == itemName) return itemName
else return null
}
}
fun convertSimpleTreeItemToPath(tree: SimpleTree, itemName: String): String {
val searchableNodeRef = Ref.create<TreeNode>()
val searchableNode: TreeNode?
TreeUtil.traverse(tree.getModel().getRoot() as TreeNode) { node ->
val valueFromNode = SettingsTreeFixture.getValueFromNode(tree, node)
if (valueFromNode != null && valueFromNode == itemName) {
assert(node is TreeNode)
searchableNodeRef.set(node as TreeNode)
}
true
}
searchableNode = searchableNodeRef.get()
val path = TreeUtil.getPathFromRoot(searchableNode!!)
return (0..path.pathCount - 1).map { path.getPathComponent(it).toString() }.filter(String::isNotEmpty).joinToString("/")
}
fun getJTreePath(cmp: JTree, path: TreePath): String {
var treePath = path
val result = StringBuilder()
val bcr = org.fest.swing.driver.BasicJTreeCellReader()
while (treePath.pathCount != 1 || (cmp.isRootVisible && treePath.pathCount == 1)) {
val valueAt = bcr.valueAt(cmp, treePath.lastPathComponent)
result.insert(0, "$valueAt${if (!result.isEmpty()) "/" else ""}")
if (treePath.pathCount == 1) break
else treePath = treePath.parentPath
}
return result.toString()
}
} | platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/ScriptGenerator.kt | 1774891343 |
/*
* Copyright 2019 Allan Wang
*
* 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.pitchedapps.frost.views
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.webkit.WebView
import android.widget.ListView
import androidx.core.widget.ListViewCompat
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnChildScrollUpCallback
import com.pitchedapps.frost.prefs.Prefs
import com.pitchedapps.frost.utils.L
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
/**
* Variant that forbids refreshing if child layout is not at the top Inspired by
* https://github.com/slapperwan/gh4a/blob/master/app/src/main/java/com/gh4a/widget/SwipeRefreshLayout.java
*/
@AndroidEntryPoint
class SwipeRefreshLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
SwipeRefreshLayout(context, attrs) {
@Inject lateinit var prefs: Prefs
private var preventRefresh: Boolean = false
private var downY: Float = -1f
private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
private var nestedCanChildScrollUp: OnChildScrollUpCallback? = null
/** Copy of [canChildScrollUp], with additional support if necessary */
private val canChildScrollUp = OnChildScrollUpCallback { parent, child ->
nestedCanChildScrollUp?.canChildScrollUp(parent, child)
?: when (child) {
is WebView -> child.canScrollVertically(-1).apply { L.d { "Webview can scroll up $this" } }
is ListView -> ListViewCompat.canScrollList(child, -1)
// Supports webviews as well
else -> child?.canScrollVertically(-1) ?: false
}
}
init {
setOnChildScrollUpCallback(canChildScrollUp)
}
override fun setOnChildScrollUpCallback(callback: OnChildScrollUpCallback?) {
this.nestedCanChildScrollUp = callback
}
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
if (!prefs.swipeToRefresh) {
return false
}
if (ev.action != MotionEvent.ACTION_DOWN && preventRefresh) {
return false
}
when (ev.action) {
MotionEvent.ACTION_DOWN -> {
downY = ev.y
preventRefresh = canChildScrollUp()
}
MotionEvent.ACTION_MOVE -> {
if (downY - ev.y > touchSlop) {
preventRefresh = true
return false
}
}
}
return super.onInterceptTouchEvent(ev)
}
override fun onStartNestedScroll(child: View, target: View, nestedScrollAxes: Int): Boolean {
return prefs.swipeToRefresh && super.onStartNestedScroll(child, target, nestedScrollAxes)
}
override fun onNestedScroll(
target: View,
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int
) {
if (preventRefresh) {
/*
* Ignoring offsetInWindow since
* 1. It doesn't seem to matter in the typical use case
* 2. It isn't being transferred to the underlying array used by the super class
*/
dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, null)
} else {
super.onNestedScroll(target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed)
}
}
}
| app/src/main/kotlin/com/pitchedapps/frost/views/SwipeRefreshLayout.kt | 3508639522 |
package kota
import android.app.FragmentTransaction
import android.app.FragmentTransaction.*
import android.support.annotation.AnimatorRes
import android.support.annotation.StyleRes
import kota.FragmentTransit.Companion.TRANSIT_TYPE_CONSTANT
import kota.FragmentTransit.Companion.TRANSIT_TYPE_CUSTOM
open class FragmentTransit @PublishedApi internal constructor(
private val type: Int,
private vararg val value: Int
) {
operator fun component1(): Int = type
operator fun component2(): IntArray = value
companion object {
const val TRANSIT_TYPE_CUSTOM: Int = 0
const val TRANSIT_TYPE_CONSTANT: Int = 1
const val TRANSIT_TYPE_STYLE: Int = 2
}
}
open class CustomTransit : FragmentTransit {
constructor(
@AnimatorRes enter: Int,
@AnimatorRes exit: Int
) : super(TRANSIT_TYPE_CUSTOM, enter, exit)
constructor(
@AnimatorRes enter: Int,
@AnimatorRes exit: Int,
@AnimatorRes popEnter: Int,
@AnimatorRes popExit: Int
) : super(TRANSIT_TYPE_CUSTOM, enter, exit, popEnter, popExit)
}
object NoTransit : FragmentTransit(TRANSIT_TYPE_CONSTANT, TRANSIT_NONE)
object OpenTransit : FragmentTransit(TRANSIT_TYPE_CONSTANT, TRANSIT_FRAGMENT_OPEN)
object CloseTransit : FragmentTransit(TRANSIT_TYPE_CONSTANT, TRANSIT_FRAGMENT_CLOSE)
open class FadeTransit : FragmentTransit(TRANSIT_TYPE_CONSTANT, TRANSIT_FRAGMENT_FADE) {
companion object : FadeTransit()
}
open class StyleTransit(@StyleRes styleRes: Int) : FragmentTransit(TRANSIT_TYPE_STYLE, styleRes)
@PublishedApi
@Suppress("NOTHING_TO_INLINE")
internal inline fun FragmentTransaction.setTransit(transit: FragmentTransit): FragmentTransaction = transit.let { (type, value) ->
return when (type) {
TRANSIT_TYPE_CUSTOM -> if (value.size == 2) setCustomAnimations(value[0], value[1]) else setCustomAnimations(value[0], value[1], value[2], value[3])
TRANSIT_TYPE_CONSTANT -> setTransition(value[0])
else -> setTransitionStyle(value[0])
}
} | kota/src/fragments/FragmentTransits.kt | 3728426402 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.runconfig
import com.intellij.execution.configurations.RunConfigurationModule
import com.intellij.openapi.project.Project
class RsRunConfigurationModule(project: Project) : RunConfigurationModule(project)
| src/main/kotlin/org/rust/cargo/runconfig/RsRunConfigurationModule.kt | 1406317664 |
package com.kazucocoa.droidtesthelperlib
import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.test.platform.app.InstrumentationRegistry
class HandleClearData {
companion object {
private val TAG = HandleClearData::class.java.simpleName
private const val clearDataExtra = "CLEAR_DATA"
fun hasExtraRegardingHandleClearData(intent: Intent): Boolean {
return intent.hasExtra(clearDataExtra)
}
fun clearData(intent: Intent) {
val targetePackage = intent.getStringExtra(clearDataExtra)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
InstrumentationRegistry.getInstrumentation().uiAutomation.executeShellCommand("pm clear $targetePackage")
} else {
Log.e(HandleClearData.TAG, "Failed to clear data because of API Level 21-")
}
}
}
}
| droidtesthelperlib/src/main/java/com/kazucocoa/droidtesthelperlib/HandleClearData.kt | 419078033 |
package io.gitlab.arturbosch.detekt.core.processors
import io.gitlab.arturbosch.detekt.core.path
import io.gitlab.arturbosch.detekt.test.compileForTest
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
/**
* @author Artur Bosch
*/
internal class LLOCVisitorTest {
@Test
fun defaultCaseHasOneClassAndAnnotationLine() {
val file = compileForTest(path.resolve("Default.kt"))
val lloc = with(file) {
accept(LLOCVisitor())
getUserData(LLOC_KEY)
}
assertThat(lloc).isEqualTo(2)
}
@Test
fun llocOfComplexClass() {
val file = compileForTest(path.resolve("ComplexClass.kt"))
val lloc = with(file) {
accept(LLOCVisitor())
getUserData(LLOC_KEY)
}
assertThat(lloc).isEqualTo(85)
}
}
| detekt-core/src/test/kotlin/io/gitlab/arturbosch/detekt/core/processors/LLOCVisitorTest.kt | 1224875319 |
package com.trydroid.coboard
import android.graphics.Point
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import com.google.firebase.database.*
import kotlinx.android.synthetic.main.activity_main.*
class CoBoardActivity : AppCompatActivity() {
private val mLinesReference: DatabaseReference by lazy {
FirebaseDatabase.getInstance().reference.child(CHILD_LINES)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_co_board, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?) =
when (item?.itemId) {
R.id.action_clear -> consumeMenuSelected { removeFirebaseChild() }
else -> super.onOptionsItemSelected(item)
}
override fun onStart() {
super.onStart()
mLinesReference.addChildEventListener(mLinesReferenceListener)
drawView.drawListener = { lineList ->
lineList?.let { sendToFirebase(lineList) }
}
}
override fun onStop() {
super.onStop()
mLinesReference.removeEventListener(mLinesReferenceListener)
drawView.drawListener = null
}
private fun sendToFirebase(lineList: List<Point>) {
mLinesReference.push().setValue(lineList)
}
private fun removeFirebaseChild() {
mLinesReference.removeValue()
}
private fun clearDrawView() {
drawView.clear()
}
private fun drawLine(lineList: List<Point>) {
drawView.drawLine(lineList)
}
private val mLinesReferenceListener = object : ChildEventListener {
override fun onChildAdded(dataSnapshot: DataSnapshot?, p1: String?) {
Log.e(TAG, "onChildAdded")
dataSnapshot?.children
?.map { children -> children.getValue<Point>(Point::class.java) }
?.let { lineList -> drawLine(lineList) }
}
override fun onChildRemoved(dataSnapshot: DataSnapshot?) {
Log.e(TAG, "onChildRemoved")
clearDrawView()
}
override fun onChildMoved(dataSnapshot: DataSnapshot?, p1: String?) {
}
override fun onChildChanged(dataSnapshot: DataSnapshot?, p1: String?) {
}
override fun onCancelled(databaseError: DatabaseError) {
}
}
inline fun consumeMenuSelected(func: () -> Unit): Boolean {
func()
return true
}
companion object {
private val TAG = CoBoardActivity::class.java.simpleName
private val CHILD_LINES = "lines"
}
}
| app/src/main/kotlin/com/trydroid/coboard/CoBoardActivity.kt | 4088140274 |
/* -*-mode:java; c-basic-offset:2; -*- */ /*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly([email protected]) and Mark Adler([email protected])
* and contributors of zlib.
*/
package com.jtransc.compression.jzlib
import com.jtransc.annotation.JTranscInvisible
import java.io.IOException
@JTranscInvisible
class ZStreamException : IOException {
constructor() : super() {}
constructor(s: String?) : super(s) {}
} | benchmark_kotlin_mpp/wip/jzlib/ZStreamException.kt | 4224507676 |
package com.feliperoriz.cadence.extensions
import com.feliperoriz.cadence.LibraryFragment
import com.feliperoriz.cadence.SearchFragment
import com.feliperoriz.cadence.SettingsFragment
/**
* Created by Felipe Roriz on 5/7/16.
*/
fun LibraryFragment.newInstance(): LibraryFragment {
return LibraryFragment()
}
fun SearchFragment.newInstance(): SearchFragment {
return SearchFragment()
}
fun SettingsFragment.newInstance(): SettingsFragment {
return SettingsFragment()
}
| mobile/src/main/kotlin/com/feliperoriz/cadence/extensions/MainExtensions.kt | 3162035891 |
package org.http4k.serverless.lambda.testing.setup.aws.apigateway
import org.http4k.core.Body
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.with
import org.http4k.serverless.lambda.testing.setup.aws.apigateway.ApiGatewayJackson.auto
import org.http4k.serverless.lambda.testing.setup.aws.apigatewayv2.ApiName
import org.http4k.serverless.lambda.testing.setup.aws.kClass
class CreateApi(val name: ApiName) : AwsApiGatewayAction<RestApiDetails>(kClass()) {
override fun toRequest() = Request(Method.POST, "/restapis")
.with(Body.auto<RestApi>().toLens() of RestApi(name.value))
private data class RestApi(val name: String)
}
| http4k-serverless/lambda/integration-test/src/test/kotlin/org/http4k/serverless/lambda/testing/setup/aws/apigateway/CreateApi.kt | 4248152733 |
package com.v2ray.ang.ui
import android.graphics.Color
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.v2ray.ang.R
import com.v2ray.ang.dto.AppInfo
import kotlinx.android.synthetic.main.item_recycler_bypass_list.view.*
import org.jetbrains.anko.image
import org.jetbrains.anko.layoutInflater
import org.jetbrains.anko.textColor
import java.util.*
class PerAppProxyAdapter(val activity: BaseActivity, val apps: List<AppInfo>, blacklist: MutableSet<String>?) :
RecyclerView.Adapter<PerAppProxyAdapter.BaseViewHolder>() {
companion object {
private const val VIEW_TYPE_HEADER = 0
private const val VIEW_TYPE_ITEM = 1
}
private var mActivity: BaseActivity = activity
val blacklist = if (blacklist == null) HashSet<String>() else HashSet<String>(blacklist)
override fun onBindViewHolder(holder: BaseViewHolder?, position: Int) {
if (holder is AppViewHolder) {
val appInfo = apps[position - 1]
holder.bind(appInfo)
}
}
override fun getItemCount() = apps.size + 1
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder? {
val ctx = parent.context
return when (viewType) {
VIEW_TYPE_HEADER -> {
val view = View(ctx)
view.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ctx.resources.getDimensionPixelSize(R.dimen.bypass_list_header_height) * 3)
BaseViewHolder(view)
}
VIEW_TYPE_ITEM -> AppViewHolder(ctx.layoutInflater
.inflate(R.layout.item_recycler_bypass_list, parent, false))
else -> null
}
}
override fun getItemViewType(position: Int)
= if (position == 0) VIEW_TYPE_HEADER else VIEW_TYPE_ITEM
open class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
inner class AppViewHolder(itemView: View) : BaseViewHolder(itemView),
View.OnClickListener {
private val inBlacklist: Boolean get() = blacklist.contains(appInfo.packageName)
private lateinit var appInfo: AppInfo
val icon = itemView.icon!!
val name = itemView.name!!
val checkBox = itemView.check_box!!
fun bind(appInfo: AppInfo) {
this.appInfo = appInfo
icon.image = appInfo.appIcon
// name.text = appInfo.appName
checkBox.isChecked = inBlacklist
// name.textColor = mActivity.resources.getColor(if (appInfo.isSystemApp)
// R.color.color_highlight_material else R.color.abc_secondary_text_material_light)
if (appInfo.isSystemApp) {
name.text = String.format("** %1s", appInfo.appName)
name.textColor = Color.RED
} else {
name.text = appInfo.appName
name.textColor = Color.DKGRAY
}
itemView.setOnClickListener(this)
}
override fun onClick(v: View?) {
if (inBlacklist) {
blacklist.remove(appInfo.packageName)
checkBox.isChecked = false
} else {
blacklist.add(appInfo.packageName)
checkBox.isChecked = true
}
}
}
} | V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/PerAppProxyAdapter.kt | 1662343889 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.svn.info
import org.jetbrains.idea.svn.api.*
import org.jetbrains.idea.svn.checkin.CommitInfo
import org.jetbrains.idea.svn.conflict.TreeConflictDescription
import org.jetbrains.idea.svn.lock.Lock
import java.io.File
private fun resolveConflictFile(file: File?, path: String?) = if (file != null && path != null) File(file.parentFile, path) else null
class Info(val file: File?,
val url: Url?,
val revision: Revision,
nodeKind: NodeKind,
val repositoryRootUrl: Url?,
val repositoryId: String?,
commitInfo: CommitInfo? = null,
val schedule: String? = null,
val depth: Depth? = null,
val copyFromUrl: Url? = null,
val copyFromRevision: Revision = Revision.UNDEFINED,
val lock: Lock? = null,
conflictOldFileName: String? = null,
conflictNewFileName: String? = null,
conflictWorkingFileName: String? = null,
val treeConflict: TreeConflictDescription? = null) : BaseNodeDescription(nodeKind) {
val commitInfo: CommitInfo = commitInfo ?: CommitInfo.EMPTY
val conflictOldFile = resolveConflictFile(file, conflictOldFileName)
val conflictNewFile = resolveConflictFile(file, conflictNewFileName)
val conflictWrkFile = resolveConflictFile(file, conflictWorkingFileName)
@Deprecated("Use nodeKind property", ReplaceWith("nodeKind"))
val kind
get() = nodeKind
@Deprecated("Use url property", ReplaceWith("url"))
fun getURL() = url
companion object {
const val SCHEDULE_ADD = "add"
}
} | plugins/svn4idea/src/org/jetbrains/idea/svn/info/Info.kt | 973382593 |
package com.muhron.kotlinq
import com.muhron.kotlinq.inner.Calculator
@JvmName("sumOfByte")
fun Sequence<Byte>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfShort")
fun Sequence<Short>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfInt")
fun Sequence<Int>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfLong")
fun Sequence<Long>.sum(): Long {
return Calculator.sum(this)
}
@JvmName("sumOfFloat")
fun Sequence<Float>.sum(): Float {
return Calculator.sum(this)
}
@JvmName("sumOfDouble")
fun Sequence<Double>.sum(): Double {
return Calculator.sum(this)
}
@JvmName("sumOfByte")
fun Iterable<Byte>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfShort")
fun Iterable<Short>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfInt")
fun Iterable<Int>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfLong")
fun Iterable<Long>.sum(): Long {
return Calculator.sum(this)
}
@JvmName("sumOfFloat")
fun Iterable<Float>.sum(): Float {
return Calculator.sum(this)
}
@JvmName("sumOfDouble")
fun Iterable<Double>.sum(): Double {
return Calculator.sum(this)
}
@JvmName("sumOfByte")
fun Array<Byte>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfShort")
fun Array<Short>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfInt")
fun Array<Int>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfLong")
fun Array<Long>.sum(): Long {
return Calculator.sum(this)
}
@JvmName("sumOfFloat")
fun Array<Float>.sum(): Float {
return Calculator.sum(this)
}
@JvmName("sumOfDouble")
fun Array<Double>.sum(): Double {
return Calculator.sum(this)
}
fun ByteArray.sum(): Int {
require(any()) { "empty." }
return Calculator.sum(this)
}
fun ShortArray.sum(): Int {
require(any()) { "empty." }
return Calculator.sum(this)
}
fun IntArray.sum(): Int {
require(any()) { "empty." }
return Calculator.sum(this)
}
fun LongArray.sum(): Long {
require(any()) { "empty." }
return Calculator.sum(this)
}
fun FloatArray.sum(): Float {
require(any()) { "empty." }
return Calculator.sum(this)
}
fun DoubleArray.sum(): Double {
require(any()) { "empty." }
return Calculator.sum(this)
}
@JvmName("sumOfByte")
fun <T> Sequence<T>.sum(selector: (T) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun <T> Sequence<T>.sum(selector: (T) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun <T> Sequence<T>.sum(selector: (T) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun <T> Sequence<T>.sum(selector: (T) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun <T> Sequence<T>.sum(selector: (T) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun <T> Sequence<T>.sum(selector: (T) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun <T> Iterable<T>.sum(selector: (T) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun <T> Iterable<T>.sum(selector: (T) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun <T> Iterable<T>.sum(selector: (T) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun <T> Iterable<T>.sum(selector: (T) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun <T> Iterable<T>.sum(selector: (T) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun <T> Iterable<T>.sum(selector: (T) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun <T> Array<T>.sum(selector: (T) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun <T> Array<T>.sum(selector: (T) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun <T> Array<T>.sum(selector: (T) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun <T> Array<T>.sum(selector: (T) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun <T> Array<T>.sum(selector: (T) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun <T> Array<T>.sum(selector: (T) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun ByteArray.sum(selector: (Byte) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun ByteArray.sum(selector: (Byte) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun ByteArray.sum(selector: (Byte) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun ByteArray.sum(selector: (Byte) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun ByteArray.sum(selector: (Byte) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun ByteArray.sum(selector: (Byte) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun ShortArray.sum(selector: (Short) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun ShortArray.sum(selector: (Short) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun ShortArray.sum(selector: (Short) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun ShortArray.sum(selector: (Short) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun ShortArray.sum(selector: (Short) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun ShortArray.sum(selector: (Short) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun IntArray.sum(selector: (Int) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun IntArray.sum(selector: (Int) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun IntArray.sum(selector: (Int) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun IntArray.sum(selector: (Int) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun IntArray.sum(selector: (Int) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun IntArray.sum(selector: (Int) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun LongArray.sum(selector: (Long) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun LongArray.sum(selector: (Long) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun LongArray.sum(selector: (Long) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun LongArray.sum(selector: (Long) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun LongArray.sum(selector: (Long) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun LongArray.sum(selector: (Long) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun FloatArray.sum(selector: (Float) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun FloatArray.sum(selector: (Float) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun FloatArray.sum(selector: (Float) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun FloatArray.sum(selector: (Float) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun FloatArray.sum(selector: (Float) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun FloatArray.sum(selector: (Float) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun DoubleArray.sum(selector: (Double) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun DoubleArray.sum(selector: (Double) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun DoubleArray.sum(selector: (Double) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun DoubleArray.sum(selector: (Double) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun DoubleArray.sum(selector: (Double) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun DoubleArray.sum(selector: (Double) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.sum(selector: (Map.Entry<TSourceK, TSourceV>) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.sum(selector: (Map.Entry<TSourceK, TSourceV>) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.sum(selector: (Map.Entry<TSourceK, TSourceV>) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.sum(selector: (Map.Entry<TSourceK, TSourceV>) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.sum(selector: (Map.Entry<TSourceK, TSourceV>) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.sum(selector: (Map.Entry<TSourceK, TSourceV>) -> Double): Double = map(selector).sum()
| src/main/kotlin/com/muhron/kotlinq/sum.kt | 4156579308 |
package com.headlessideas.http
data class StatusCode(val code: Int, val message: String) {
override fun toString(): String {
return "$code $message"
}
} | src/main/kotlin/com/headlessideas/http/StatusCode.kt | 2756966530 |
/*
* Copyright 2019 Johannes Donath <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* 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 tv.dotstart.beacon.ui.cell.model
import javafx.scene.image.Image
import tv.dotstart.beacon.ui.repository.model.Service
/**
* @author [Johannes Donath](mailto:[email protected])
*/
data class ServiceNode(
/**
* Identifies the service with which this node is directly associated.
*/
val service: Service,
/**
* Defines the icon which is to be displayed within this service node.
*/
override val icon: Image?,
/**
* Defines the title which is to be displayed within this service node.
*/
override val title: String) : ServiceListNode {
override val styleClass = "service"
}
| ui/src/main/kotlin/tv/dotstart/beacon/ui/cell/model/ServiceNode.kt | 2550051602 |
package com.dev.bins.note.utils
/**
* Created by bin on 11/25/15.
*/
object InitData {
fun initCategory() {
// val db = Connector.getDatabase()
// val category = Category()
// category.categoty = "默认"
// category.save()
//
// val category1 = Category()
// category1.categoty = "剪切板"
// category1.save()
//
// val category2 = Category()
// category2.categoty = "私人"
// category2.save()
}
}
| app/src/main/java/com/dev/bins/note/utils/InitData.kt | 1230380836 |
/*
* Copyright (c) 2021.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package net.devrieze.util
import io.github.pdvrieze.kotlinsql.ddl.Database
import io.github.pdvrieze.kotlinsql.monadic.DBReceiver
import net.devrieze.util.db.MonadicDBTransaction
interface DBTransactionFactory<out TR: MonadicDBTransaction<DB>, DB: Database>: TransactionFactory<TR> {
fun asTransaction(dbReceiver: DBReceiver<DB>): TR
}
| java-common/src/jvmMain/kotlin/net/devrieze/util/DBTransactionFactory.kt | 3644634872 |
package com.octaldata.domain.topics
import com.octaldata.domain.DeploymentId
import java.util.UUID
data class TopicView(
val id: TopicViewId,
val deploymentId: DeploymentId,
val name: TopicViewName,
val filter: String,
)
data class TopicViewId(val value: String) {
companion object {
fun generate(): TopicViewId = TopicViewId(UUID.randomUUID().toString())
}
}
data class TopicViewName(val value: String) | streamops-domain/src/main/kotlin/com/octaldata/domain/topics/view.kt | 10032104 |
package com.byagowi.persiancalendar
import com.byagowi.persiancalendar.utils.CalendarType
import com.byagowi.persiancalendar.utils.getDayOfWeekFromJdn
import com.byagowi.persiancalendar.utils.getMonthLength
import com.byagowi.persiancalendar.utils.isMoonInScorpio
import com.cepmuvakkit.times.view.QiblaCompassView
import io.github.persiancalendar.Equinox
import io.github.persiancalendar.calendar.CivilDate
import io.github.persiancalendar.calendar.IslamicDate
import io.github.persiancalendar.calendar.PersianDate
import io.github.persiancalendar.praytimes.CalculationMethod
import io.github.persiancalendar.praytimes.Clock
import io.github.persiancalendar.praytimes.Coordinate
import io.github.persiancalendar.praytimes.PrayTimesCalculator
import org.junit.Assert.*
import org.junit.Test
import java.util.*
class MainLogicTests {
@Test
fun islamic_converter_test() {
listOf(
listOf(2453767, 1427, 1, 1), listOf(2455658, 1432, 5, 2)
// listOf(2458579, 1440, 7, 29), listOf(2458580, 1440, 8, 1)
).forEach {
val reference = IslamicDate(it[1], it[2], it[3])
assertEquals(it[0].toLong(), reference.toJdn())
val converted = IslamicDate(it[0].toLong())
assertEquals(it[1], converted.year)
assertEquals(it[2], converted.month)
assertEquals(it[3], converted.dayOfMonth)
assertEquals(it[0].toLong(), converted.toJdn())
assertTrue(reference == IslamicDate(reference.toJdn()))
}
listOf(
listOf(2016, 10, 3, 1438, 1, 1),
listOf(2016, 11, 1, 1438, 2, 1),
listOf(2016, 12, 1, 1438, 3, 1),
listOf(2016, 12, 31, 1438, 4, 1),
listOf(2016, 10, 3, 1438, 1, 1),
listOf(2016, 11, 1, 1438, 2, 1),
listOf(2016, 12, 1, 1438, 3, 1),
listOf(2016, 12, 31, 1438, 4, 1),
listOf(2017, 1, 30, 1438, 5, 1),
listOf(2017, 2, 28, 1438, 6, 1),
listOf(2017, 3, 30, 1438, 7, 1),
listOf(2017, 4, 28, 1438, 8, 1),
listOf(2017, 5, 27, 1438, 9, 1),
listOf(2017, 6, 26, 1438, 10, 1),
listOf(2017, 7, 25, 1438, 11, 1),
listOf(2017, 8, 23, 1438, 12, 1),
listOf(2017, 9, 22, 1439, 1, 1),
listOf(2017, 10, 21, 1439, 2, 1),
listOf(2017, 11, 20, 1439, 3, 1),
listOf(2017, 12, 20, 1439, 4, 1),
listOf(2018, 1, 19, 1439, 5, 1),
listOf(2018, 2, 18, 1439, 6, 1),
listOf(2018, 3, 19, 1439, 7, 1),
listOf(2018, 4, 18, 1439, 8, 1),
listOf(2018, 5, 17, 1439, 9, 1),
listOf(2018, 6, 15, 1439, 10, 1),
listOf(2018, 7, 15, 1439, 11, 1),
listOf(2018, 8, 13, 1439, 12, 1),
listOf(2018, 9, 11, 1440, 1, 1),
listOf(2018, 10, 11, 1440, 2, 1),
listOf(2018, 11, 9, 1440, 3, 1),
listOf(2018, 12, 9, 1440, 4, 1),
listOf(2019, 1, 8, 1440, 5, 1),
listOf(2019, 2, 7, 1440, 6, 1)
// listOf(2040, 5, 12, 1462, 5, 1),
// listOf(2040, 6, 11, 1462, 6, 1),
// listOf(2040, 7, 10, 1462, 7, 1),
// listOf(2040, 8, 9, 1462, 8, 1),
// listOf(2040, 9, 7, 1462, 9, 1),
// listOf(2040, 10, 7, 1462, 10, 1),
// listOf(2040, 11, 6, 1462, 11, 1),
// listOf(2040, 12, 5, 1462, 12, 1),
// listOf(2041, 1, 4, 1463, 1, 1),
// listOf(2041, 2, 2, 1463, 2, 1),
// listOf(2041, 3, 4, 1463, 3, 1),
// listOf(2041, 4, 2, 1463, 4, 1),
// listOf(2041, 5, 1, 1463, 5, 1),
// listOf(2041, 5, 31, 1463, 6, 1),
// listOf(2041, 6, 29, 1463, 7, 1),
// listOf(2041, 7, 29, 1463, 8, 1),
// listOf(2041, 8, 28, 1463, 9, 1),
// listOf(2041, 9, 26, 1463, 10, 1),
// listOf(2041, 10, 26, 1463, 11, 1),
// listOf(2041, 11, 25, 1463, 12, 1),
// listOf(2041, 12, 24, 1464, 1, 1)
).forEach {
val jdn = CivilDate(it[0], it[1], it[2]).toJdn()
val islamicDate = IslamicDate(it[3], it[4], it[5])
assertEquals(jdn, islamicDate.toJdn())
assertTrue(islamicDate == IslamicDate(jdn))
}
IslamicDate.useUmmAlQura = true
listOf(
listOf(listOf(2015, 3, 14), listOf(1436, 5, 23)),
listOf(listOf(1999, 4, 1), listOf(1419, 12, 15)),
listOf(listOf(1989, 2, 25), listOf(1409, 7, 19))
).forEach {
val jdn = CivilDate(it[0][0], it[0][1], it[0][2]).toJdn()
val islamicDate = IslamicDate(it[1][0], it[1][1], it[1][2])
assertEquals(jdn, islamicDate.toJdn())
assertTrue(islamicDate == IslamicDate(jdn))
}
IslamicDate.useUmmAlQura = false
// int i = -1;
// long last = 0;
// for (int[][] test : tests2) {
// if (i % 12 == 0) {
// System.out.print(test[1][0]);
// System.out.print(", ");
// }
// long jdn = DateConverter.toJdn(test[0][0], test[0][1], test[0][2]);
// System.out.print(jdn - last);
// last = jdn;
// System.out.print(", ");
// if (i % 12 == 11)
// System.out.print("\n");
// ++i;
// }
}
@Test
fun practice_persian_converting_back_and_forth() {
assertEquals(PersianDate(1398, 1, 1).toJdn(), 2458564)
val startJdn = CivilDate(1750, 1, 1).toJdn()
val endJdn = CivilDate(2350, 1, 1).toJdn()
(startJdn..endJdn).forEach { assertEquals(it, PersianDate(it).toJdn()) }
}
@Test
fun practice_islamic_converting_back_and_forth() {
val startJdn = CivilDate(1750, 1, 1).toJdn()
val endJdn = CivilDate(2350, 1, 1).toJdn()
(startJdn..endJdn).forEach { assertEquals(it, IslamicDate(it).toJdn()) }
}
@Test
fun practice_ummalqara_converting_back_and_forth() {
IslamicDate.useUmmAlQura = true
val startJdn = CivilDate(1750, 1, 1).toJdn()
val endJdn = CivilDate(2350, 1, 1).toJdn()
(startJdn..endJdn).forEach { assertEquals(it, IslamicDate(it).toJdn()) }
IslamicDate.useUmmAlQura = false
}
@Test
fun practice_civil_converting_back_and_forth() {
val startJdn = CivilDate(1750, 1, 1).toJdn()
val endJdn = CivilDate(2350, 1, 1).toJdn()
(startJdn..endJdn).forEach { assertEquals(it, CivilDate(it).toJdn()) }
}
@Test
fun practice_moon_in_scorpio() {
val positiveJdn = listOf(
listOf(1397, 1, 14), listOf(1397, 1, 15), listOf(1397, 2, 10),
listOf(1397, 2, 11), listOf(1397, 2, 12), listOf(1397, 3, 6),
listOf(1397, 3, 7), listOf(1397, 3, 8), listOf(1397, 4, 2),
listOf(1397, 4, 3), listOf(1397, 4, 30), listOf(1397, 4, 31),
listOf(1397, 5, 26), listOf(1397, 5, 27), listOf(1397, 6, 22),
listOf(1397, 6, 23), listOf(1397, 7, 18), listOf(1397, 7, 19),
listOf(1397, 7, 20), listOf(1397, 8, 16), listOf(1397, 8, 17),
listOf(1397, 9, 12), listOf(1397, 9, 13), listOf(1397, 9, 14),
listOf(1397, 10, 10), listOf(1397, 10, 11), listOf(1397, 11, 8),
listOf(1397, 11, 9), listOf(1397, 12, 6), listOf(1397, 12, 7)
).map { PersianDate(it[0], it[1], it[2]).toJdn() }
val startOfYear = PersianDate(1397, 1, 1).toJdn()
(0..365).forEach {
val jdn = startOfYear + it
val persian = PersianDate(jdn)
val year = persian.year
val month = persian.month
val day = persian.dayOfMonth
assertEquals(
"%d %d %d".format(year, month, day),
jdn in positiveJdn,
isMoonInScorpio(persian, IslamicDate(jdn))
)
}
}
@Test
fun test_getMonthLength() {
assertEquals(31, getMonthLength(CalendarType.SHAMSI, 1397, 1))
assertEquals(31, getMonthLength(CalendarType.SHAMSI, 1397, 2))
assertEquals(31, getMonthLength(CalendarType.SHAMSI, 1397, 3))
assertEquals(31, getMonthLength(CalendarType.SHAMSI, 1397, 4))
assertEquals(31, getMonthLength(CalendarType.SHAMSI, 1397, 5))
assertEquals(31, getMonthLength(CalendarType.SHAMSI, 1397, 6))
assertEquals(30, getMonthLength(CalendarType.SHAMSI, 1397, 7))
assertEquals(30, getMonthLength(CalendarType.SHAMSI, 1397, 8))
assertEquals(30, getMonthLength(CalendarType.SHAMSI, 1397, 9))
assertEquals(30, getMonthLength(CalendarType.SHAMSI, 1397, 10))
assertEquals(30, getMonthLength(CalendarType.SHAMSI, 1397, 11))
assertEquals(29, getMonthLength(CalendarType.SHAMSI, 1397, 12))
}
private fun getDate(year: Int, month: Int, dayOfMonth: Int): Date =
Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply {
set(year, month - 1, dayOfMonth)
}.time
@Test
fun test_praytimes() {
// http://praytimes.org/code/v2/js/examples/monthly.htm
var prayTimes = PrayTimesCalculator.calculate(
CalculationMethod.MWL,
getDate(2018, 9, 5),
Coordinate(43.0, -80.0, 0.0),
-5.0, true
)
assertEquals(Clock(5, 9).toInt(), prayTimes.fajrClock.toInt())
assertEquals(Clock(6, 49).toInt(), prayTimes.sunriseClock.toInt())
assertEquals(Clock(13, 19).toInt(), prayTimes.dhuhrClock.toInt())
assertEquals(Clock(16, 57).toInt(), prayTimes.asrClock.toInt())
assertEquals(Clock(19, 48).toInt(), prayTimes.maghribClock.toInt())
assertEquals(Clock(21, 21).toInt(), prayTimes.ishaClock.toInt())
prayTimes = PrayTimesCalculator.calculate(
CalculationMethod.ISNA,
getDate(2018, 9, 5),
Coordinate(43.0, -80.0, 0.0),
-5.0, true
)
assertEquals(Clock(5, 27).toInt(), prayTimes.fajrClock.toInt())
assertEquals(Clock(6, 49).toInt(), prayTimes.sunriseClock.toInt())
assertEquals(Clock(13, 19).toInt(), prayTimes.dhuhrClock.toInt())
assertEquals(Clock(16, 57).toInt(), prayTimes.asrClock.toInt())
assertEquals(Clock(19, 48).toInt(), prayTimes.maghribClock.toInt())
assertEquals(Clock(21, 9).toInt(), prayTimes.ishaClock.toInt())
prayTimes = PrayTimesCalculator.calculate(
CalculationMethod.Egypt,
getDate(2018, 9, 5),
Coordinate(43.0, -80.0, 0.0),
-5.0, true
)
assertEquals(Clock(5, 0).toInt(), prayTimes.fajrClock.toInt())
assertEquals(Clock(6, 49).toInt(), prayTimes.sunriseClock.toInt())
assertEquals(Clock(13, 19).toInt(), prayTimes.dhuhrClock.toInt())
assertEquals(Clock(16, 57).toInt(), prayTimes.asrClock.toInt())
assertEquals(Clock(19, 48).toInt(), prayTimes.maghribClock.toInt())
assertEquals(Clock(21, 24).toInt(), prayTimes.ishaClock.toInt())
prayTimes = PrayTimesCalculator.calculate(
CalculationMethod.Makkah,
getDate(2018, 9, 5),
Coordinate(43.0, -80.0, 0.0),
-5.0, true
)
assertEquals(Clock(5, 6).toInt(), prayTimes.fajrClock.toInt())
assertEquals(Clock(6, 49).toInt(), prayTimes.sunriseClock.toInt())
assertEquals(Clock(13, 19).toInt(), prayTimes.dhuhrClock.toInt())
assertEquals(Clock(16, 57).toInt(), prayTimes.asrClock.toInt())
assertEquals(Clock(19, 48).toInt(), prayTimes.maghribClock.toInt())
assertEquals(Clock(21, 18).toInt(), prayTimes.ishaClock.toInt())
prayTimes = PrayTimesCalculator.calculate(
CalculationMethod.Karachi,
getDate(2018, 9, 5),
Coordinate(43.0, -80.0, 0.0),
-5.0, true
)
assertEquals(Clock(5, 9).toInt(), prayTimes.fajrClock.toInt())
assertEquals(Clock(6, 49).toInt(), prayTimes.sunriseClock.toInt())
assertEquals(Clock(13, 19).toInt(), prayTimes.dhuhrClock.toInt())
assertEquals(Clock(16, 57).toInt(), prayTimes.asrClock.toInt())
assertEquals(Clock(19, 48).toInt(), prayTimes.maghribClock.toInt())
assertEquals(Clock(21, 27).toInt(), prayTimes.ishaClock.toInt())
prayTimes = PrayTimesCalculator.calculate(
CalculationMethod.Jafari,
getDate(2018, 9, 5),
Coordinate(43.0, -80.0, 0.0),
-5.0, true
)
assertEquals(Clock(5, 21).toInt(), prayTimes.fajrClock.toInt())
assertEquals(Clock(6, 49).toInt(), prayTimes.sunriseClock.toInt())
assertEquals(Clock(13, 19).toInt(), prayTimes.dhuhrClock.toInt())
assertEquals(Clock(16, 57).toInt(), prayTimes.asrClock.toInt())
assertEquals(Clock(20, 5).toInt(), prayTimes.maghribClock.toInt())
assertEquals(Clock(21, 3).toInt(), prayTimes.ishaClock.toInt())
prayTimes = PrayTimesCalculator.calculate(
CalculationMethod.Tehran,
getDate(2018, 9, 5),
Coordinate(43.0, -80.0, 0.0),
-5.0, true
)
assertEquals(Clock(5, 11).toInt(), prayTimes.fajrClock.toInt())
assertEquals(Clock(6, 49).toInt(), prayTimes.sunriseClock.toInt())
assertEquals(Clock(13, 19).toInt(), prayTimes.dhuhrClock.toInt())
assertEquals(Clock(16, 57).toInt(), prayTimes.asrClock.toInt())
assertEquals(Clock(20, 8).toInt(), prayTimes.maghribClock.toInt())
assertEquals(Clock(21, 3).toInt(), prayTimes.ishaClock.toInt())
prayTimes = PrayTimesCalculator.calculate(
CalculationMethod.Tehran,
getDate(2019, 6, 9),
Coordinate(3.147778, 101.695278, 0.0),
8.0, false
)
assertEquals(Clock(5, 49).toInt(), prayTimes.fajrClock.toInt())
assertEquals(Clock(7, 3).toInt(), prayTimes.sunriseClock.toInt())
assertEquals(Clock(13, 12).toInt(), prayTimes.dhuhrClock.toInt())
assertEquals(Clock(16, 39).toInt(), prayTimes.asrClock.toInt())
assertEquals(Clock(19, 37).toInt(), prayTimes.maghribClock.toInt())
assertEquals(Clock(20, 19).toInt(), prayTimes.ishaClock.toInt())
}
@Test
fun test_isNearToDegree() {
assertTrue(QiblaCompassView.isNearToDegree(360f, 1f))
assertTrue(QiblaCompassView.isNearToDegree(1f, 360f))
assertTrue(QiblaCompassView.isNearToDegree(2f, 360f))
assertFalse(QiblaCompassView.isNearToDegree(3f, 360f))
assertTrue(QiblaCompassView.isNearToDegree(360f, 2f))
assertFalse(QiblaCompassView.isNearToDegree(360f, 3f))
assertTrue(QiblaCompassView.isNearToDegree(180f, 181f))
assertTrue(QiblaCompassView.isNearToDegree(180f, 182f))
assertFalse(QiblaCompassView.isNearToDegree(180f, 183f))
assertFalse(QiblaCompassView.isNearToDegree(180f, 184f))
assertTrue(QiblaCompassView.isNearToDegree(181f, 180f))
assertTrue(QiblaCompassView.isNearToDegree(182f, 180f))
assertFalse(QiblaCompassView.isNearToDegree(183f, 180f))
assertFalse(QiblaCompassView.isNearToDegree(184f, 180f))
}
@Test
fun test_it_different_date_object_equal() {
assertFalse(CivilDate(2000, 1, 1) == PersianDate(2000, 1, 1))
assertTrue(CivilDate(2000, 1, 1) == CivilDate(2000, 1, 1))
assertFalse(CivilDate(2000, 1, 1) == CivilDate(2000, 2, 1))
}
@Test
fun tests_imported_from_calendariale() {
val J0000 = 1721425L // Ours is different apparently
listOf(
// listOf(-214193, -1208, 5, 1),
// listOf(-61387, -790, 9, 14),
// listOf(25469, -552, 7, 2),
// listOf(49217, -487, 7, 9),
// listOf(171307, -153, 10, 18),
// listOf(210155, -46, 2, 30),
listOf(253427, 73, 8, 19),
listOf(369740, 392, 2, 5),
listOf(400085, 475, 3, 3),
listOf(434355, 569, 1, 3),
listOf(452605, 618, 12, 20),
listOf(470160, 667, 1, 14),
listOf(473837, 677, 2, 8),
listOf(507850, 770, 3, 22),
listOf(524156, 814, 11, 13),
listOf(544676, 871, 1, 21),
listOf(567118, 932, 6, 28),
listOf(569477, 938, 12, 14),
listOf(601716, 1027, 3, 21),
listOf(613424, 1059, 4, 10),
listOf(626596, 1095, 5, 2),
listOf(645554, 1147, 3, 30),
listOf(664224, 1198, 5, 10),
listOf(671401, 1218, 1, 7),
listOf(694799, 1282, 1, 29),
listOf(704424, 1308, 6, 3),
listOf(708842, 1320, 7, 7),
listOf(709409, 1322, 1, 29),
listOf(709580, 1322, 7, 14),
listOf(727274, 1370, 12, 27),
listOf(728714, 1374, 12, 6),
listOf(744313, 1417, 8, 19),
listOf(764652, 1473, 4, 28)
).forEach {
assertEquals(it[0] + J0000, PersianDate(it[1], it[2], it[3]).toJdn())
val from = PersianDate(it[0] + J0000)
assertEquals(from.year, it[1])
assertEquals(from.month, it[2])
assertEquals(from.dayOfMonth, it[3])
}
listOf(
// listOf(1507231, -586, 7, 24),
// listOf(1660037, -168, 12, 5),
// listOf(1746893, 70, 9, 24),
// listOf(1770641, 135, 10, 2),
// listOf(1892731, 470, 1, 8),
// listOf(1931579, 576, 5, 20),
// listOf(1974851, 694, 11, 10),
// listOf(2091164, 1013, 4, 25),
// listOf(2121509, 1096, 5, 24),
// listOf(2155779, 1190, 3, 23),
// listOf(2174029, 1240, 3, 10),
// listOf(2191584, 1288, 4, 2),
// listOf(2195261, 1298, 4, 27),
// listOf(2229274, 1391, 6, 12),
// listOf(2245580, 1436, 2, 3),
// listOf(2266100, 1492, 4, 9),
// listOf(2288542, 1553, 9, 19),
// listOf(2290901, 1560, 3, 5),
// listOf(2323140, 1648, 6, 10),
listOf(2334848, 1680, 6, 30),
listOf(2348020, 1716, 7, 24),
listOf(2366978, 1768, 6, 19),
listOf(2385648, 1819, 8, 2),
listOf(2392825, 1839, 3, 27),
listOf(2416223, 1903, 4, 19),
listOf(2425848, 1929, 8, 25),
listOf(2430266, 1941, 9, 29),
listOf(2430833, 1943, 4, 19),
listOf(2431004, 1943, 10, 7),
listOf(2448698, 1992, 3, 17),
listOf(2450138, 1996, 2, 25),
listOf(2465737, 2038, 11, 10),
listOf(2486076, 2094, 7, 18)
).forEach {
assertEquals(it[0] + 1L, CivilDate(it[1], it[2], it[3]).toJdn())
val from = CivilDate(it[0] + 1L)
assertEquals(from.year, it[1])
assertEquals(from.month, it[2])
assertEquals(from.dayOfMonth, it[3])
}
listOf(
// listOf(-214193, -1245, 12, 11),
// listOf(-61387, -813, 2, 25),
// listOf(25469, -568, 4, 2),
// listOf(49217, -501, 4, 7),
// listOf(171307, -157, 10, 18),
// listOf(210155, -47, 6, 3),
// listOf(253427, 75, 7, 13),
// listOf(369740, 403, 10, 5),
// listOf(400085, 489, 5, 22),
// listOf(434355, 586, 2, 7),
listOf(452605, 637, 8, 7),
// listOf(470160, 687, 2, 21),
// listOf(473837, 697, 7, 7),
// listOf(507850, 793, 6, 30),
// listOf(524156, 839, 7, 6),
// listOf(544676, 897, 6, 2),
// listOf(567118, 960, 9, 30),
// listOf(569477, 967, 5, 27),
// listOf(601716, 1058, 5, 18),
// listOf(613424, 1091, 6, 3),
// listOf(626596, 1128, 8, 4),
listOf(645554, 1182, 2, 4),
// listOf(664224, 1234, 10, 10),
// listOf(671401, 1255, 1, 11),
// listOf(694799, 1321, 1, 20),
listOf(704424, 1348, 3, 19),
// listOf(708842, 1360, 9, 7),
// listOf(709409, 1362, 4, 14),
// listOf(709580, 1362, 10, 7),
// listOf(727274, 1412, 9, 12),
// listOf(728714, 1416, 10, 5),
// listOf(744313, 1460, 10, 12),
listOf(764652, 1518, 3, 5)
).forEach {
assertEquals("${it[0]}", it[0] + J0000, IslamicDate(it[1], it[2], it[3]).toJdn())
val from = IslamicDate(it[0] + J0000)
assertEquals(from.year, it[1])
assertEquals(from.month, it[2])
assertEquals(from.dayOfMonth, it[3])
}
}
@Test
fun test_leap_years() {
// Doesn't match with https://calendar.ut.ac.ir/Fa/News/Data/Doc/KabiseShamsi1206-1498.pdf
val leapYears = listOf(
1210, 1214, 1218, 1222, 1226, 1230, 1234, 1238, 1243, 1247, 1251, 1255, 1259, 1263,
1267, 1271, 1276, 1280, 1284, 1288, 1292, 1296, 1300, 1304, 1309, 1313, 1317, 1321,
1325, 1329, 1333, 1337, 1342, 1346, 1350, 1354, 1358, 1362, 1366, 1370, 1375, 1379,
1383, 1387, 1391, 1395, 1399, 1403, 1408, 1412, 1416, 1420, 1424, 1428, 1432, 1436,
1441, 1445, 1449, 1453, 1457, 1461, 1465, 1469, 1474, 1478, 1482, 1486, 1490, 1494,
1498
)
(1206..1498).forEach {
assertEquals(
it.toString(), if (it in leapYears) 30 else 29,
getMonthLength(CalendarType.SHAMSI, it, 12)
)
}
}
@Test
fun test_equinox_time() {
val calendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Tehran"))
listOf(
// https://calendar.ut.ac.ir/Fa/News/Data/Doc/Calendar%201398-Full.pdf
listOf(2020, 3, 20, 7, 20/*should be 19*/, 43/* should be 37*/),
// https://calendar.ut.ac.ir/Fa/News/Data/Doc/Calendar%201398-Full.pdf
listOf(2019, 3, 21, 1, 28, 13/*should be 27*/),
// https://calendar.ut.ac.ir/Fa/News/Data/Doc/Calendar%201397-Full.pdf
listOf(2018, 3, 20, 19, 45, 53/*should be 28*/),
// https://calendar.ut.ac.ir/Fa/News/Data/Doc/Calendar%201396-Full.pdf
listOf(2017, 3, 20, 13, 59/*should be 58*/, 38/*should be 40*/),
// https://calendar.ut.ac.ir/Fa/News/Data/Doc/Calendar%201395-Full.pdf
listOf(2016, 3, 20, 8, 0, 55/*should be 12*/),
// http://vetmed.uk.ac.ir/documents/203998/204600/calendar-1394.pdf
listOf(2015, 3, 21, 2, 16/*should be 15*/, 0/*should be 11*/),
// https://raw.githubusercontent.com/ilius/starcal/master/plugins/iran-jalali-data.txt
listOf(2014, 3, 20, 20, 27, 41/*should be 7*/),
listOf(2013, 3, 20, 14, 32/*should be 31*/, 41/*should be 56*/),
listOf(2012, 3, 20, 8, 44, 19/*should be 27*/),
listOf(2011, 3, 21, 2, 51/*should be 50*/, 38/*should be 25*/),
listOf(2010, 3, 20, 21, 2, 49/*should be 13*/),
listOf(2009, 3, 20, 15, 14/*should be 13*/, 50/*should be 39*/),
listOf(2008, 3, 20, 9, 18, 17/*should be 19*/)
).forEach {
calendar.time = Equinox.northwardEquinox(it[0])
assertEquals(it[0].toString(), it[0], calendar[Calendar.YEAR])
assertEquals(it[0].toString(), it[1], calendar[Calendar.MONTH] + 1)
assertEquals(it[0].toString(), it[2], calendar[Calendar.DAY_OF_MONTH])
assertEquals(it[0].toString(), it[3], calendar[Calendar.HOUR_OF_DAY])
assertEquals(it[0].toString(), it[4], calendar[Calendar.MINUTE])
assertEquals(it[0].toString(), it[5], calendar[Calendar.SECOND])
}
// And not having random crashes
(-2000..10000).forEach { Equinox.northwardEquinox(it) }
}
@Test
fun test_day_of_week_from_jdn() {
assertEquals(0, getDayOfWeekFromJdn(PersianDate(1398, 9, 9).toJdn()))
assertEquals(1, getDayOfWeekFromJdn(PersianDate(1398, 9, 10).toJdn()))
assertEquals(2, getDayOfWeekFromJdn(PersianDate(1398, 9, 11).toJdn()))
assertEquals(3, getDayOfWeekFromJdn(PersianDate(1398, 9, 12).toJdn()))
assertEquals(4, getDayOfWeekFromJdn(PersianDate(1398, 9, 13).toJdn()))
assertEquals(5, getDayOfWeekFromJdn(PersianDate(1398, 9, 14).toJdn()))
assertEquals(6, getDayOfWeekFromJdn(PersianDate(1398, 9, 15).toJdn()))
assertEquals(0, getDayOfWeekFromJdn(PersianDate(1398, 9, 16).toJdn()))
assertEquals(1, getDayOfWeekFromJdn(PersianDate(1398, 9, 17).toJdn()))
assertEquals(2, getDayOfWeekFromJdn(PersianDate(1398, 9, 18).toJdn()))
assertEquals(3, getDayOfWeekFromJdn(PersianDate(1398, 9, 19).toJdn()))
assertEquals(4, getDayOfWeekFromJdn(PersianDate(1398, 9, 20).toJdn()))
assertEquals(5, getDayOfWeekFromJdn(PersianDate(1398, 9, 21).toJdn()))
assertEquals(6, getDayOfWeekFromJdn(PersianDate(1398, 9, 22).toJdn()))
}
}
| PersianCalendar/src/test/java/com/byagowi/persiancalendar/MainLogicTests.kt | 664608012 |
/*
* Copyright (c) 2021.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
@file:JvmName("ServletKt")
package uk.ac.bournemouth.darwin.html
import kotlinx.html.*
import kotlinx.html.stream.appendHTML
import uk.ac.bournemouth.darwin.sharedhtml.*
import java.net.URI
import java.security.Principal
import java.util.*
/** Should Javascript initialization be delayed to the footer of the page. */
private const val DELAY_JS = true
val RequestInfo.isNoChromeRequested: Boolean
get() = getHeader("X-Darwin")?.contains("nochrome") ?: false
/**
* Method that encapsulates the darwin web template.
*
* @param request The request to respond to
* @param windowTitle The title that should be in the head element
* @param pageTitle The title to display on page (if not the same as windowTitle)
* @param bodyContent The closure that creates the actual body content of the document.
*/
fun ResponseContext.darwinResponse(request: RequestInfo,
windowTitle: String = "Darwin",
pageTitle: String? = null,
includeLogin: Boolean = true,
context: ServiceContext = RequestServiceContext(request),
bodyContent: ContextTagConsumer<HtmlBlockTag>.() -> Unit) {
respondWriter { result ->
if (request.isNoChromeRequested) {
contentType("text/xml")
result.append("<?xml version=\"1.0\" ?>\n")
result.appendHTML().partialHTML {
title(windowTitle, pageTitle)
script(context.jsLocalRef("main.js"))
body {
withContext(context).bodyContent()
}
}
} else {
contentType("text/html")
result.append("<!DOCTYPE html>\n")
result.appendHTML().html {
head {
title(windowTitle)
styleLink(context.cssRef("darwin.css"))
meta(name = "viewport", content = "width=device-width, initial-scale=1.0")
if (!DELAY_JS) script(
type = ScriptType.textJavaScript,
src = context.jsGlobalRef("require.js")
) { this.attributes["data-main"] = context.jsLocalRef("main.js") }
}
body {
h1 {
id = "header"
a(href = "/") {
id = "logo"
+"Darwin"
}
span {
id = "title"
+(pageTitle ?: windowTitle)
}
}
darwinMenu(request)
div {
id = "login"
loginPanelContent(context, request.userPrincipal?.name)
}
div {
id = "content"
withContext(context).bodyContent()
}
if (includeLogin) {
// A mini form that we use to get username/password out of the account manager
form(action = "${context.accountMgrPath}login", method = FormMethod.post) {
id = "xloginform"; style = "display:none"
input(type = InputType.text, name = "username")
input(type = InputType.password, name = "password")
}
}
div {
id = "footer"
span { id = "divider" }
+"Darwin is a Bournemouth University Project"
}
if (DELAY_JS) script(
type = ScriptType.textJavaScript, src = context.jsGlobalRef(
"require.js"
)
) { this.attributes["data-main"] = context.jsLocalRef("main.js") }
// script(type= ScriptType.textJavaScript, src="/js/darwin.js")
}
}
}
}
}
fun ResponseContext.darwinError(req: RequestInfo,
message: String,
code: Int = 500,
status: String = "Server error",
cause: Exception? = null) {
setStatus(code)
darwinResponse(req, windowTitle = "$code $status") {
h2 { +status }
p {
style = "margin-top: 2em"
+message.trim().replace("\n", "<br />")
}
if (cause != null && System.getProperty("DEBUG")?.let { it != "false" } == true) {
p {
this.printCauseAsHtml(cause)
}
}
}
}
private fun HtmlBlockTag.printCauseAsHtml(cause: Throwable) {
b { +cause.javaClass.simpleName }
+": ${cause.message}"
div {
style = "margin-left: 1em"
ul {
for (elem in cause.stackTrace) {
li { +elem.toString() }
}
}
cause.cause?.let {
i { +"caused by " }
printCauseAsHtml(it)
}
for (suppressed in cause.suppressed) {
i { +"suppressing " }
printCauseAsHtml(suppressed)
}
}
}
class MenuItem(val label: String, val target: URI) {
constructor(label: String, target: String) : this(label, URI.create(target))
}
fun <T, C : TagConsumer<T>> C.darwinMenu(request: RequestInfo): T {
val user = request.userPrincipal
return div {
id = "menu"
var first = true
for (menuItem in getMenuItems(request, user)) {
if (!first) +"\n" else first = false
a(href = menuItem.target.toString(), classes = "menuitem") {
+menuItem.label
}
}
}
}
fun FlowContent.darwinMenu(request: RequestInfo) {
consumer.darwinMenu(request)
}
private fun getMenuItems(request: RequestInfo, user: Principal?): List<MenuItem> {
val menuItems: MutableList<MenuItem> = ArrayList()
// Pages with /#/... urls are virtual pages. They don't have valid other urls
if (user == null) {
menuItems += MenuItem("Welcome", "/")
} else {
menuItems += MenuItem("Home", "/")
if (request.isUserInRole("admin") || request.isUserInRole("appprogramming")) {
menuItems += MenuItem("Trac", user.name + "/trac/")
}
}
menuItems += MenuItem("About", "/#/about")
return menuItems
}
/**
* A class representing the idea of sending sufficient html to replace the content, but not the layout of the page.
*/
class PartialHTML(initialAttributes: Map<String, String>, override val consumer: TagConsumer<*>) :
HTMLTag("root", consumer, initialAttributes, null, false, false) {
fun title(block: TITLE.() -> Unit = {}): Unit = TITLE(emptyMap, consumer).visit(block)
fun title(windowTitle: String = "", pageTitle: String? = null): Unit =
TITLE(emptyMap, consumer).visit {
attributes["windowtitle"] = windowTitle
+(pageTitle ?: windowTitle)
}
fun script(src: String) {
SCRIPT(emptyMap, consumer).visit {
this.type = ScriptType.textJavaScript
this.src = src
}
}
fun body(block: XMLBody.() -> Unit = {}): Unit = XMLBody(emptyMap, consumer).visit(block)
}
class XMLBody(initialAttributes: Map<String, String>, override val consumer: TagConsumer<*>) : HTMLTag("body", consumer,
initialAttributes,
null, false,
false), HtmlBlockTag
fun <T, C : TagConsumer<T>> C.partialHTML(block: PartialHTML.() -> Unit = {}): T = PartialHTML(emptyMap,
this).visitAndFinalize(
this, block)
val RequestInfo.htmlAccepted: Boolean
get() {
return getHeader("Accept")?.let { it.contains("text/html") || it.contains("application/nochrome") } ?: false
}
fun ContextTagConsumer<HtmlBlockTag>.darwinDialog(title: String,
id: String? = null,
bodyContent: FlowContent.() -> Unit = {}) {
div(classes = "dialog centerContents") {
if (id != null) {
this.id = id
}
div(classes = "dialogOuter") {
h1(classes = "dlgTitle") { +title }
div(classes = "dialogInner centerContents") {
div(classes = "dlgContent") {
bodyContent()
}
}
}
}
}
class RequestServiceContext(private val request: RequestInfo) : ServiceContext {
override val accountMgrPath: String
get() = "/accountmgr/"
override val assetPath: String
get() = "/assets/"
override val cssPath: String
get() = "/css/"
override val jsGlobalPath: String
get() = "/js/"
override val jsLocalPath: String
get() = "${request.contextPath}/js/"
}
| darwin/src/jvmMain/kotlin/uk/ac/bournemouth/darwin/html/darwinPage.kt | 821297336 |
package gargoyle.ct.util.log.jul
import gargoyle.ct.util.log.Level
import gargoyle.ct.util.log.Logger
import java.text.MessageFormat
import java.util.logging.LogRecord
class JULLogger(name: String?) : Logger {
private val logger: java.util.logging.Logger
init {
logger = java.util.logging.Logger.getLogger(name)
}
override fun log(level: Level, exception: Throwable?, pattern: String, vararg arguments: Any) {
logger.log(LogRecord(getLevel(level), MessageFormat.format(pattern, *arguments)).also {
it.thrown = exception
})
}
private fun getLevel(level: Level): java.util.logging.Level =
when (level) {
Level.TRACE -> java.util.logging.Level.FINER
Level.DEBUG -> java.util.logging.Level.FINE
Level.INFO -> java.util.logging.Level.INFO
Level.WARNING -> java.util.logging.Level.WARNING
Level.ERROR -> java.util.logging.Level.SEVERE
}
override fun isLoggable(level: Level): Boolean = logger.isLoggable(getLevel(level))
}
| util/src/main/kotlin/gargoyle/ct/util/log/jul/JULLogger.kt | 2675838953 |
package org.wordpress.android.fluxc.network.rest.wpcom.activity
import com.android.volley.RequestQueue
import com.nhaarman.mockitokotlin2.KArgumentCaptor
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.anyOrNull
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.isNull
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.activity.ActivityTypeModel
import org.wordpress.android.fluxc.model.activity.RewindStatusModel.Reason
import org.wordpress.android.fluxc.model.activity.RewindStatusModel.State
import org.wordpress.android.fluxc.network.BaseRequest.BaseNetworkError
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.NETWORK_ERROR
import org.wordpress.android.fluxc.network.UserAgent
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequest.WPComGsonNetworkError
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response.Success
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.ActivitiesResponse
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.ActivitiesResponse.Page
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.ActivityTypesResponse
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.ActivityTypesResponse.ActivityType
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.ActivityTypesResponse.Groups
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.BackupDownloadResponse
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.BackupDownloadStatusResponse
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.DismissBackupDownloadResponse
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.RewindResponse
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.RewindStatusResponse
import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken
import org.wordpress.android.fluxc.store.ActivityLogStore.ActivityLogErrorType
import org.wordpress.android.fluxc.store.ActivityLogStore.ActivityTypesErrorType
import org.wordpress.android.fluxc.store.ActivityLogStore.BackupDownloadRequestTypes
import org.wordpress.android.fluxc.store.ActivityLogStore.BackupDownloadStatusErrorType
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchActivityLogPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchedActivityLogPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchedBackupDownloadStatePayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchedRewindStatePayload
import org.wordpress.android.fluxc.store.ActivityLogStore.RewindRequestTypes
import org.wordpress.android.fluxc.store.ActivityLogStore.RewindStatusErrorType
import org.wordpress.android.fluxc.test
import org.wordpress.android.fluxc.tools.FormattableContent
import org.wordpress.android.fluxc.utils.TimeZoneProvider
import java.util.Date
import java.util.TimeZone
private const val DATE_1_IN_MILLIS = 1578614400000L // 2020-01-10T00:00:00+00:00
private const val DATE_2_IN_MILLIS = 1578787200000L // 2020-01-12T00:00:00+00:00
@RunWith(MockitoJUnitRunner::class)
class ActivityLogRestClientTest {
@Mock private lateinit var dispatcher: Dispatcher
@Mock private lateinit var wpComGsonRequestBuilder: WPComGsonRequestBuilder
@Mock private lateinit var site: SiteModel
@Mock private lateinit var requestPayload: FetchActivityLogPayload
@Mock private lateinit var requestQueue: RequestQueue
@Mock private lateinit var accessToken: AccessToken
@Mock private lateinit var userAgent: UserAgent
@Mock private lateinit var timeZoneProvider: TimeZoneProvider
private lateinit var urlCaptor: KArgumentCaptor<String>
private lateinit var paramsCaptor: KArgumentCaptor<Map<String, String>>
private lateinit var activityRestClient: ActivityLogRestClient
private val siteId: Long = 12
private val number = 10
private val offset = 0
@Before
fun setUp() {
urlCaptor = argumentCaptor()
paramsCaptor = argumentCaptor()
activityRestClient = ActivityLogRestClient(
wpComGsonRequestBuilder,
timeZoneProvider,
dispatcher,
null,
requestQueue,
accessToken,
userAgent)
whenever(requestPayload.site).thenReturn(site)
whenever(timeZoneProvider.getDefaultTimeZone()).thenReturn(TimeZone.getTimeZone("GMT"))
}
@Test
fun fetchActivity_passesCorrectParamToBuildRequest() = test {
initFetchActivity()
val payload = FetchActivityLogPayload(
site,
false,
Date(DATE_1_IN_MILLIS),
Date(DATE_2_IN_MILLIS),
listOf("post", "attachment")
)
activityRestClient.fetchActivity(payload, number, offset)
assertEquals(urlCaptor.firstValue, "https://public-api.wordpress.com/wpcom/v2/sites/$siteId/activity/")
with(paramsCaptor.firstValue) {
assertEquals("1", this["page"])
assertEquals("$number", this["number"])
assertNotNull(this["after"])
assertNotNull(this["before"])
assertEquals("post", this["group[0]"])
assertEquals("attachment", this["group[1]"])
}
}
@Test
fun fetchActivity_passesOnlyNonEmptyParamsToBuildRequest() = test {
initFetchActivity()
val payload = FetchActivityLogPayload(
site,
false,
after = null,
before = null,
groups = listOf()
)
activityRestClient.fetchActivity(payload, number, offset)
assertEquals(urlCaptor.firstValue, "https://public-api.wordpress.com/wpcom/v2/sites/$siteId/activity/")
with(paramsCaptor.firstValue) {
assertEquals("1", this["page"])
assertEquals("$number", this["number"])
assertEquals(2, size)
}
}
@Test
fun fetchActivity_adjustsDateRangeBasedOnTimezoneGMT3() = test {
val timezoneOffset = 3
whenever(timeZoneProvider.getDefaultTimeZone()).thenReturn(TimeZone.getTimeZone("GMT+$timezoneOffset"))
initFetchActivity()
val payload = FetchActivityLogPayload(
site,
false,
// 2020-01-10T00:00:00+00:00
Date(DATE_1_IN_MILLIS),
// 2020-01-12T00:00:00+00:00
Date(DATE_2_IN_MILLIS)
)
activityRestClient.fetchActivity(payload, number, offset)
with(paramsCaptor.firstValue) {
assertEquals("2020-01-09T21:00:00+00:00", this["after"])
assertEquals("2020-01-11T21:00:00+00:00", this["before"])
}
}
@Test
fun fetchActivity_adjustsDateRangeBasedOnTimezoneGMTMinus7() = test {
val timezoneOffset = -7
whenever(timeZoneProvider.getDefaultTimeZone()).thenReturn(TimeZone.getTimeZone("GMT$timezoneOffset"))
initFetchActivity()
val payload = FetchActivityLogPayload(
site,
false,
// 2020-01-10T00:00:00+00:00
Date(DATE_1_IN_MILLIS),
// 2020-01-12T00:00:00+00:00
Date(DATE_2_IN_MILLIS)
)
activityRestClient.fetchActivity(payload, number, offset)
with(paramsCaptor.firstValue) {
assertEquals("2020-01-10T07:00:00+00:00", this["after"])
assertEquals("2020-01-12T07:00:00+00:00", this["before"])
}
}
@Test
fun fetchActivity_dispatchesResponseOnSuccess() = test {
val response = ActivitiesResponse(1, "response", ACTIVITY_RESPONSE_PAGE)
initFetchActivity(response)
val payload = activityRestClient.fetchActivity(requestPayload, number, offset)
with(payload) {
assertEquals([email protected], number)
assertEquals([email protected], offset)
assertEquals(totalItems, 1)
assertEquals([email protected], site)
assertEquals(activityLogModels.size, 1)
assertNull(error)
with(activityLogModels[0]) {
assertEquals(activityID, ACTIVITY_RESPONSE.activity_id)
assertEquals(gridicon, ACTIVITY_RESPONSE.gridicon)
assertEquals(name, ACTIVITY_RESPONSE.name)
assertEquals(published, ACTIVITY_RESPONSE.published)
assertEquals(rewindID, ACTIVITY_RESPONSE.rewind_id)
assertEquals(rewindable, ACTIVITY_RESPONSE.is_rewindable)
assertEquals(content, ACTIVITY_RESPONSE.content)
assertEquals(actor?.avatarURL, ACTIVITY_RESPONSE.actor?.icon?.url)
assertEquals(actor?.wpcomUserID, ACTIVITY_RESPONSE.actor?.wpcom_user_id)
}
}
}
@Test
fun fetchActivity_dispatchesErrorOnMissingActivityId() = test {
val failingPage = Page(listOf(ACTIVITY_RESPONSE.copy(activity_id = null)))
val activitiesResponse = ActivitiesResponse(1, "response", failingPage)
initFetchActivity(activitiesResponse)
val payload = activityRestClient.fetchActivity(requestPayload, number, offset)
assertEmittedActivityError(payload, ActivityLogErrorType.MISSING_ACTIVITY_ID)
}
@Test
fun fetchActivity_dispatchesErrorOnMissingSummary() = test {
val failingPage = Page(listOf(ACTIVITY_RESPONSE.copy(summary = null)))
val activitiesResponse = ActivitiesResponse(1, "response", failingPage)
initFetchActivity(activitiesResponse)
val payload = activityRestClient.fetchActivity(requestPayload, number, offset)
assertEmittedActivityError(payload, ActivityLogErrorType.MISSING_SUMMARY)
}
@Test
fun fetchActivity_dispatchesErrorOnMissingContentText() = test {
val emptyContent = FormattableContent(null)
val failingPage = Page(listOf(ACTIVITY_RESPONSE.copy(content = emptyContent)))
val activitiesResponse = ActivitiesResponse(1, "response", failingPage)
initFetchActivity(activitiesResponse)
val payload = activityRestClient.fetchActivity(requestPayload, number, offset)
assertEmittedActivityError(payload, ActivityLogErrorType.MISSING_CONTENT_TEXT)
}
@Test
fun fetchActivity_dispatchesErrorOnMissingPublishedDate() = test {
val failingPage = Page(listOf(ACTIVITY_RESPONSE.copy(published = null)))
val activitiesResponse = ActivitiesResponse(1, "response", failingPage)
initFetchActivity(activitiesResponse)
val payload = activityRestClient.fetchActivity(requestPayload, number, offset)
assertEmittedActivityError(payload, ActivityLogErrorType.MISSING_PUBLISHED_DATE)
}
@Test
fun fetchActivity_dispatchesErrorOnFailure() = test {
initFetchActivity(error = WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR)))
val payload = activityRestClient.fetchActivity(requestPayload, number, offset)
assertEmittedActivityError(payload, ActivityLogErrorType.GENERIC_ERROR)
}
@Test
fun fetchActivityRewind_dispatchesResponseOnSuccess() = test {
val state = State.ACTIVE
val rewindResponse = REWIND_STATUS_RESPONSE.copy(state = state.value)
initFetchRewindStatus(rewindResponse)
val payload = activityRestClient.fetchActivityRewind(site)
with(payload) {
assertEquals([email protected], site)
assertNull(error)
assertNotNull(rewindStatusModelResponse)
rewindStatusModelResponse?.apply {
assertEquals(reason, Reason.UNKNOWN)
assertEquals(state, state)
assertNotNull(rewind)
rewind?.apply {
assertEquals(status.value, REWIND_RESPONSE.status)
}
}
}
}
@Test
fun fetchActivityRewind_dispatchesGenericErrorOnFailure() = test {
initFetchRewindStatus(error = WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR)))
val payload = activityRestClient.fetchActivityRewind(site)
assertEmittedRewindStatusError(payload, RewindStatusErrorType.GENERIC_ERROR)
}
@Test
fun fetchActivityRewind_dispatchesErrorOnWrongState() = test {
initFetchRewindStatus(REWIND_STATUS_RESPONSE.copy(state = "wrong"))
val payload = activityRestClient.fetchActivityRewind(site)
assertEmittedRewindStatusError(payload, RewindStatusErrorType.INVALID_RESPONSE)
}
@Test
fun fetchActivityRewind_dispatchesErrorOnMissingRestoreId() = test {
initFetchRewindStatus(REWIND_STATUS_RESPONSE.copy(rewind = REWIND_RESPONSE.copy(rewind_id = null)))
val payload = activityRestClient.fetchActivityRewind(site)
assertEmittedRewindStatusError(payload, RewindStatusErrorType.MISSING_REWIND_ID)
}
@Test
fun fetchActivityRewind_dispatchesErrorOnWrongRestoreStatus() = test {
initFetchRewindStatus(REWIND_STATUS_RESPONSE.copy(rewind = REWIND_RESPONSE.copy(status = "wrong")))
val payload = activityRestClient.fetchActivityRewind(site)
assertEmittedRewindStatusError(payload, RewindStatusErrorType.INVALID_REWIND_STATE)
}
@Test
fun postRewindOperation() = test {
val restoreId = 10L
val response = RewindResponse(restoreId, true, null)
initPostRewind(response)
val payload = activityRestClient.rewind(site, "rewindId")
assertEquals(restoreId, payload.restoreId)
}
@Test
fun postRewindOperationError() = test {
initPostRewind(error = WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR)))
val payload = activityRestClient.rewind(site, "rewindId")
assertTrue(payload.isError)
}
@Test
fun postRewindApiError() = test {
val restoreId = 10L
initPostRewind(RewindResponse(restoreId, false, "error"))
val payload = activityRestClient.rewind(site, "rewindId")
assertTrue(payload.isError)
}
@Test
fun postRewindOperationWithTypes() = test {
val restoreId = 10L
val response = RewindResponse(restoreId, true, null)
val types = RewindRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
initPostRewindWithTypes(data = response, requestTypes = types)
val payload = activityRestClient.rewind(site, "rewindId", types)
assertEquals(restoreId, payload.restoreId)
}
@Test
fun postRewindOperationErrorWithTypes() = test {
val types = RewindRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
initPostRewindWithTypes(error = WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR)), requestTypes = types)
val payload = activityRestClient.rewind(site, "rewindId", types)
assertTrue(payload.isError)
}
@Test
fun postRewindApiErrorWithTypes() = test {
val restoreId = 10L
val types = RewindRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
initPostRewindWithTypes(data = RewindResponse(restoreId, false, "error"), requestTypes = types)
val payload = activityRestClient.rewind(site, "rewindId", types)
assertTrue(payload.isError)
}
@Test
fun postBackupDownloadOperation() = test {
val downloadId = 10L
val rewindId = "rewind_id"
val backupPoint = "backup_point"
val startedAt = "started_at"
val progress = 0
val response = BackupDownloadResponse(downloadId, rewindId, backupPoint, startedAt, progress)
val types = BackupDownloadRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
initPostBackupDownload(rewindId = rewindId, data = response, requestTypes = types)
val payload = activityRestClient.backupDownload(site, rewindId, types)
assertEquals(downloadId, payload.downloadId)
}
@Test
fun postBackupDownloadOperationError() = test {
val rewindId = "rewind_id"
val types = BackupDownloadRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
initPostBackupDownload(rewindId = rewindId, error =
WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR)), requestTypes = types)
val payload = activityRestClient.backupDownload(site, rewindId, types)
assertTrue(payload.isError)
}
@Test
fun fetchActivityDownload_dispatchesGenericErrorOnFailure() = test {
initFetchBackupDownloadStatus(
error = WPComGsonNetworkError(
BaseNetworkError(
NETWORK_ERROR
)
)
)
val payload = activityRestClient.fetchBackupDownloadState(site)
assertEmittedDownloadStatusError(payload, BackupDownloadStatusErrorType.GENERIC_ERROR)
}
@Test
fun fetchActivityBackupDownload_dispatchesResponseOnSuccess() = test {
val progress = 55
val downloadResponse = BACKUP_DOWNLOAD_STATUS_RESPONSE.copy(progress = progress)
initFetchBackupDownloadStatus(arrayOf(downloadResponse))
val payload = activityRestClient.fetchBackupDownloadState(site)
with(payload) {
assertEquals([email protected], site)
assertNull(error)
assertNotNull(backupDownloadStatusModelResponse)
backupDownloadStatusModelResponse?.apply {
assertEquals(downloadId, BACKUP_DOWNLOAD_STATUS_RESPONSE.downloadId)
assertEquals(rewindId, BACKUP_DOWNLOAD_STATUS_RESPONSE.rewindId)
assertEquals(backupPoint, BACKUP_DOWNLOAD_STATUS_RESPONSE.backupPoint)
assertEquals(startedAt, BACKUP_DOWNLOAD_STATUS_RESPONSE.startedAt)
assertEquals(downloadCount, BACKUP_DOWNLOAD_STATUS_RESPONSE.downloadCount)
assertEquals(validUntil, BACKUP_DOWNLOAD_STATUS_RESPONSE.validUntil)
assertEquals(url, BACKUP_DOWNLOAD_STATUS_RESPONSE.url)
assertEquals(progress, progress)
}
}
}
@Test
fun fetchEmptyActivityBackupDownload_dispatchesResponseOnSuccess() = test {
initFetchBackupDownloadStatus(arrayOf())
val payload = activityRestClient.fetchBackupDownloadState(site)
with(payload) {
assertEquals(site, [email protected])
assertNull(error)
assertNull(backupDownloadStatusModelResponse)
}
}
@Test
fun fetchActivityTypes_dispatchesSuccessResponseOnSuccess() = test {
initFetchActivityTypes()
val siteId = 90L
val payload = activityRestClient.fetchActivityTypes(siteId, null, null)
with(payload) {
assertEquals(siteId, remoteSiteId)
assertEquals(false, isError)
}
}
@Test
fun fetchActivityTypes_dispatchesGenericErrorOnFailure() = test {
initFetchActivityTypes(error = WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR)))
val siteId = 90L
val payload = activityRestClient.fetchActivityTypes(siteId, null, null)
with(payload) {
assertEquals(siteId, remoteSiteId)
assertEquals(true, isError)
assertEquals(error.type, ActivityTypesErrorType.GENERIC_ERROR)
}
}
@Test
fun fetchActivityTypes_mapsResponseModelsToDomainModels() = test {
val activityType = ActivityType("key1", "name1", 10)
initFetchActivityTypes(
data = ActivityTypesResponse(
groups = Groups(
activityTypes = listOf(activityType)
),
15
)
)
val siteId = site.siteId
val payload = activityRestClient.fetchActivityTypes(siteId, null, null)
assertEquals(
payload.activityTypeModels[0],
ActivityTypeModel(activityType.key!!, activityType.name!!, activityType.count!!)
)
}
@Test
fun fetchActivityTypes_passesCorrectParams() = test {
initFetchActivityTypes()
val siteId = site.siteId
val afterMillis = 234124242145
val beforeMillis = 234124242999
val after = Date(afterMillis)
val before = Date(beforeMillis)
activityRestClient.fetchActivityTypes(siteId, after, before)
with(paramsCaptor.firstValue) {
assertNotNull(this["after"])
assertNotNull(this["before"])
}
}
@Test
fun postDismissBackupDownloadOperation() = test {
val downloadId = 10L
val response = DismissBackupDownloadResponse(downloadId, true)
initPostDismissBackupDownload(data = response)
val payload = activityRestClient.dismissBackupDownload(site, downloadId)
assertEquals(downloadId, payload.downloadId)
}
@Test
fun postDismissBackupDownloadOperationError() = test {
val downloadId = 10L
initPostDismissBackupDownload(error = WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR)))
val payload = activityRestClient.dismissBackupDownload(site, downloadId)
assertTrue(payload.isError)
}
private suspend fun initFetchActivity(
data: ActivitiesResponse = mock(),
error: WPComGsonNetworkError? = null
): Response<ActivitiesResponse> {
val response = if (error != null) Response.Error<ActivitiesResponse>(error) else Success(data)
whenever(wpComGsonRequestBuilder.syncGetRequest(
eq(activityRestClient),
urlCaptor.capture(),
paramsCaptor.capture(),
eq(ActivitiesResponse::class.java),
eq(false),
any(),
eq(false))
).thenReturn(response)
whenever(site.siteId).thenReturn(siteId)
return response
}
private suspend fun initFetchRewindStatus(
data: RewindStatusResponse = mock(),
error: WPComGsonNetworkError? = null
):
Response<RewindStatusResponse> {
val response = if (error != null) Response.Error<RewindStatusResponse>(error) else Success(data)
whenever(wpComGsonRequestBuilder.syncGetRequest(
eq(activityRestClient),
urlCaptor.capture(),
paramsCaptor.capture(),
eq(RewindStatusResponse::class.java),
eq(false),
any(),
eq(false))).thenReturn(response)
whenever(site.siteId).thenReturn(siteId)
return response
}
private suspend fun initPostRewind(
data: RewindResponse = mock(),
error: WPComGsonNetworkError? = null
): Response<RewindResponse> {
val response = if (error != null) Response.Error<RewindResponse>(error) else Success(data)
whenever(wpComGsonRequestBuilder.syncPostRequest(
eq(activityRestClient),
urlCaptor.capture(),
eq(null),
eq(mapOf()),
eq(RewindResponse::class.java),
isNull()
)).thenReturn(response)
whenever(site.siteId).thenReturn(siteId)
return response
}
private suspend fun initPostRewindWithTypes(
data: RewindResponse = mock(),
error: WPComGsonNetworkError? = null,
requestTypes: RewindRequestTypes
): Response<RewindResponse> {
val response = if (error != null) Response.Error<RewindResponse>(error) else Success(data)
whenever(wpComGsonRequestBuilder.syncPostRequest(
eq(activityRestClient),
urlCaptor.capture(),
eq(null),
eq(mapOf("types" to requestTypes)),
eq(RewindResponse::class.java),
isNull()
)).thenReturn(response)
whenever(site.siteId).thenReturn(siteId)
return response
}
private suspend fun initPostBackupDownload(
data: BackupDownloadResponse = mock(),
error: WPComGsonNetworkError? = null,
requestTypes: BackupDownloadRequestTypes,
rewindId: String
): Response<BackupDownloadResponse> {
val response = if (error != null) Response.Error<BackupDownloadResponse>(error) else Success(data)
whenever(wpComGsonRequestBuilder.syncPostRequest(
eq(activityRestClient),
urlCaptor.capture(),
eq(null),
eq(mapOf("rewindId" to rewindId,
"types" to requestTypes)),
eq(BackupDownloadResponse::class.java),
isNull()
)).thenReturn(response)
whenever(site.siteId).thenReturn(siteId)
return response
}
private suspend fun initFetchBackupDownloadStatus(
data: Array<BackupDownloadStatusResponse>? = null,
error: WPComGsonNetworkError? = null
): Response<Array<BackupDownloadStatusResponse>> {
val defaultError = WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR))
val response = when {
error != null -> { Response.Error(error) }
data != null -> { Success(data) }
else -> { Response.Error(defaultError) }
}
whenever(wpComGsonRequestBuilder.syncGetRequest(
eq(activityRestClient),
urlCaptor.capture(),
paramsCaptor.capture(),
eq(Array<BackupDownloadStatusResponse>::class.java),
eq(false),
any(),
eq(false))).thenReturn(response)
whenever(site.siteId).thenReturn(siteId)
return response
}
private suspend fun initFetchActivityTypes(
data: ActivityTypesResponse = mock(),
error: WPComGsonNetworkError? = null
): Response<ActivityTypesResponse> {
val response = if (error != null) Response.Error<ActivityTypesResponse>(error) else Success(data)
whenever(wpComGsonRequestBuilder.syncGetRequest(
eq(activityRestClient),
urlCaptor.capture(),
paramsCaptor.capture(),
eq(ActivityTypesResponse::class.java),
eq(false),
any(),
eq(false))
).thenReturn(response)
return response
}
private suspend fun initPostDismissBackupDownload(
data: DismissBackupDownloadResponse = mock(),
error: WPComGsonNetworkError? = null
): Response<DismissBackupDownloadResponse> {
val response = if (error != null) Response.Error(error) else Success(data)
whenever(wpComGsonRequestBuilder.syncPostRequest(
eq(activityRestClient),
urlCaptor.capture(),
anyOrNull(),
eq(mapOf("dismissed" to true.toString())),
eq(DismissBackupDownloadResponse::class.java),
isNull()
)).thenReturn(response)
whenever(site.siteId).thenReturn(siteId)
return response
}
private fun assertEmittedActivityError(payload: FetchedActivityLogPayload, errorType: ActivityLogErrorType) {
with(payload) {
assertEquals([email protected], number)
assertEquals([email protected], offset)
assertEquals([email protected], site)
assertTrue(isError)
assertEquals(error.type, errorType)
}
}
private fun assertEmittedRewindStatusError(payload: FetchedRewindStatePayload, errorType: RewindStatusErrorType) {
with(payload) {
assertEquals([email protected], site)
assertTrue(isError)
assertEquals(errorType, error.type)
}
}
private fun assertEmittedDownloadStatusError(
payload: FetchedBackupDownloadStatePayload,
errorType: BackupDownloadStatusErrorType
) {
with(payload) {
assertEquals([email protected], site)
assertTrue(isError)
assertEquals(errorType, error.type)
}
}
}
| example/src/test/java/org/wordpress/android/fluxc/network/rest/wpcom/activity/ActivityLogRestClientTest.kt | 1426966152 |
package app.youkai.data.models
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
import com.github.jasminb.jsonapi.Links
import com.github.jasminb.jsonapi.annotations.Relationship
import com.github.jasminb.jsonapi.annotations.RelationshipLinks
import com.github.jasminb.jsonapi.annotations.Type
@Type("anime") @JsonIgnoreProperties(ignoreUnknown = true)
class Anime : BaseMedia(JsonType("anime")) {
companion object FieldNames {
val EPISODE_COUNT = "episodeCount"
val EPISODE_LENGTH = "episodeLength"
val SHOW_TYPE = "showType"
val YOUTUBE_VIDEO_ID = "youtubeVideoId"
val NSFW = "nsfw"
val EPISODES = "episodes"
val STREAMING_LINKS = "streamingLinks"
val PRODUCTIONS = "animeProductions"
val CHARACTERS = "animeCharacters"
val STAFF = "animeStaff"
}
var episodeCount: Int? = null
var episodeLength: Int? = null
var showType: String? = null
var youtubeVideoId: String? = null
@JsonProperty("nsfw")
var isNsfw: Boolean? = null
@Relationship("episodes")
var episodes: List<Episode>? = null
@RelationshipLinks("episodes")
var episodeLinks: Links? = null
@Relationship("streamingLinks")
var streamingLinks: List<StreamingLink>? = null
@RelationshipLinks("streamingLinks")
var streamingLinksLinks: Links? = null
@Relationship("animeProductions")
var productions: List<AnimeProduction>? = null
@RelationshipLinks("animeProductions")
var productionLinks: Links? = null
@Relationship("animeCharacters")
var animeCharacters: List<AnimeCharacter>? = null
@RelationshipLinks("animeCharacters")
var animeCharacterLinks: Links? = null
@Relationship("animeStaff")
var staff: List<AnimeStaff>? = null
@RelationshipLinks("animeStaff")
var staffLinks: Links? = null
} | app/src/main/kotlin/app/youkai/data/models/Anime.kt | 1845403265 |
package kotlinx.serialization.json.internal
/**
* Optimized version of StringBuilder that is specific to JSON-encoding.
*
* ## Implementation note
*
* In order to encode a single string, it should be processed symbol-per-symbol,
* in order to detect and escape unicode symbols.
*
* Doing naively, it drastically slows down strings processing due to factors:
* * Byte-by-byte copying that does not leverage optimized array copying
* * A lot of range and flags checks due to Java's compact strings
*
* The following technique is used:
* 1) Instead of storing intermediate result in `StringBuilder`, we store it in
* `CharArray` directly, skipping compact strings checks in `StringBuilder`
* 2) Instead of copying symbols one-by-one, we optimistically copy it in batch using
* optimized and intrinsified `string.toCharArray(destination)`.
* It copies the content by up-to 8 times faster.
* Then we iterate over the char-array and execute single check over
* each character that is easily unrolled and vectorized by the inliner.
* If escape character is found, we fallback to per-symbol processing.
*
* 3) We pool char arrays in order to save excess resizes, allocations
* and nulls-out of arrays.
*/
internal actual class JsonToStringWriter : JsonWriter {
private var array: CharArray = CharArrayPool.take()
private var size = 0
actual override fun writeLong(value: Long) {
// Can be hand-rolled, but requires a lot of code and corner-cases handling
write(value.toString())
}
actual override fun writeChar(char: Char) {
ensureAdditionalCapacity(1)
array[size++] = char
}
actual override fun write(text: String) {
val length = text.length
if (length == 0) return
ensureAdditionalCapacity(length)
text.toCharArray(array, size, 0, text.length)
size += length
}
actual override fun writeQuoted(text: String) {
ensureAdditionalCapacity(text.length + 2)
val arr = array
var sz = size
arr[sz++] = '"'
val length = text.length
text.toCharArray(arr, sz, 0, length)
for (i in sz until sz + length) {
val ch = arr[i].code
// Do we have unescaped symbols?
if (ch < ESCAPE_MARKERS.size && ESCAPE_MARKERS[ch] != 0.toByte()) {
// Go to slow path
return appendStringSlowPath(i - sz, i, text)
}
}
// Update the state
// Capacity is not ensured because we didn't hit the slow path and thus guessed it properly in the beginning
sz += length
arr[sz++] = '"'
size = sz
}
private fun appendStringSlowPath(firstEscapedChar: Int, currentSize: Int, string: String) {
var sz = currentSize
for (i in firstEscapedChar until string.length) {
/*
* We ar already on slow path and haven't guessed the capacity properly.
* Reserve +2 for backslash-escaped symbols on each iteration
*/
sz = ensureTotalCapacity(sz, 2)
val ch = string[i].code
// Do we have unescaped symbols?
if (ch < ESCAPE_MARKERS.size) {
/*
* Escape markers are populated for backslash-escaped symbols.
* E.g. ESCAPE_MARKERS['\b'] == 'b'.toByte()
* Everything else is populated with either zeros (no escapes)
* or ones (unicode escape)
*/
when (val marker = ESCAPE_MARKERS[ch]) {
0.toByte() -> {
array[sz++] = ch.toChar()
}
1.toByte() -> {
val escapedString = ESCAPE_STRINGS[ch]!!
sz = ensureTotalCapacity(sz, escapedString.length)
escapedString.toCharArray(array, sz, 0, escapedString.length)
sz += escapedString.length
size = sz // Update size so the next resize will take it into account
}
else -> {
array[sz] = '\\'
array[sz + 1] = marker.toInt().toChar()
sz += 2
size = sz // Update size so the next resize will take it into account
}
}
} else {
array[sz++] = ch.toChar()
}
}
sz = ensureTotalCapacity(sz, 1)
array[sz++] = '"'
size = sz
}
actual override fun release() {
CharArrayPool.release(array)
}
actual override fun toString(): String {
return String(array, 0, size)
}
private fun ensureAdditionalCapacity(expected: Int) {
ensureTotalCapacity(size, expected)
}
// Old size is passed and returned separately to avoid excessive [size] field read
private fun ensureTotalCapacity(oldSize: Int, additional: Int): Int {
val newSize = oldSize + additional
if (array.size <= newSize) {
array = array.copyOf(newSize.coerceAtLeast(oldSize * 2))
}
return oldSize
}
}
| formats/json/jvmMain/src/kotlinx/serialization/json/internal/JsonToStringWriter.kt | 1503551008 |
package com.aheidelbacher.algoventure.core.serialization
import com.aheidelbacher.algostorm.engine.serialization.JsonDriver
import com.aheidelbacher.algostorm.engine.serialization.SerializationDriver
object JsonSerializer : SerializationDriver by JsonDriver() {
override fun release() {}
}
| src/main/kotlin/com/aheidelbacher/algoventure/core/serialization/JsonSerializer.kt | 306438739 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.world.portal
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.world.portal.PortalType
import org.lanternpowered.server.catalog.DefaultCatalogType
abstract class LanternPortalType(key: NamespacedKey) : DefaultCatalogType(key), PortalType
| src/main/kotlin/org/lanternpowered/server/world/portal/LanternPortalType.kt | 3377176829 |
package com.mooveit.library.providers.definition
interface CardProvider : Provider {
fun name(): String
fun brand(): String
fun number(): String
fun type(): String
fun expirationDate(): String
}
| library/src/main/java/com/mooveit/library/providers/definition/CardProvider.kt | 1787004252 |
package com.bl_lia.kirakiratter.domain.entity.realm
import com.bl_lia.kirakiratter.domain.entity.Status
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import java.util.*
open class RealmStatus(
@PrimaryKey
open var id: Int = -1,
open var content: RealmContent? = null,
open var account: RealmAccount? = null,
open var reblog: RealmStatus? = null,
open var reblogged: Boolean = false,
open var favourited: Boolean = false,
open var mediaAttachments: RealmList<RealmMedia> = RealmList(),
open var sensitive: Boolean = false,
open var createdAt: Date? = null,
open var url: String? = null
): RealmObject() {
fun toStatus(): Status =
Status(
id = id,
content = content?.toContent(),
account = account?.toAccount(),
reblog = reblog?.toStatus(),
reblogged = reblogged,
favourited = favourited,
mediaAttachments = mediaAttachments.map { it.toMedia() },
sensitive = sensitive,
createdAt = createdAt,
url = url
)
} | app/src/main/kotlin/com/bl_lia/kirakiratter/domain/entity/realm/RealmStatus.kt | 2381342706 |
package net.gtaun.shoebill.streamer
/**
* @author Marvin Haschker
*/
@AllOpen
class NativeNotFoundException(native: String) : Throwable("Could not find native function $native.") | src/main/java/net/gtaun/shoebill/streamer/NativeNotFoundException.kt | 259240730 |
package arash.sp.runda.view.fragments
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import arash.sp.runda.R
import arash.sp.runda.presenters.MapPresenter
/**
* Created by khangaldi on 9/2/17.
*/
class MapFragment: Fragment(),FragmentIdentifier {
lateinit var mPresenter: MapPresenter
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val v = inflater?.inflate(R.layout.fragment_map, container, false)
mPresenter = MapPresenter(this, v?.findViewById(R.id.mapView), savedInstanceState, activity)
return v
}
override fun onResume() {
super.onResume()
mPresenter?.onViewStarted()
}
override fun onPause() {
super.onPause()
}
override fun onStop() {
super.onStop()
mPresenter?.onStop()
}
override fun decorateView() {
}
}
| app/src/main/java/arash/sp/runda/view/fragments/MapFragment.kt | 4011767648 |
package org.rliz.cfm.recorder.playback.api
import org.rliz.cfm.recorder.common.api.toHttpResponse
import org.rliz.cfm.recorder.common.api.toRes
import org.rliz.cfm.recorder.common.security.currentUser
import org.rliz.cfm.recorder.playback.boundary.PlaybackBoundary
import org.rliz.cfm.recorder.playback.data.Playback
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.data.web.SortDefault
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.util.UUID
import javax.validation.Valid
@RestController
@RequestMapping(path = ["/rec/v1/playbacks"])
class PlaybackApi {
@Autowired
lateinit var playbackBoundary: PlaybackBoundary
@RequestMapping(method = [RequestMethod.POST])
fun postPlayback(
@Valid @RequestBody body: PlaybackRes,
@RequestParam(name = "id-method", required = false) idMethod: String?
) =
playbackBoundary.createPlayback(
id = body.id,
artists = body.artists,
release = body.releaseTitle!!,
recording = body.recordingTitle!!,
timestamp = body.timestamp,
idMethod = idMethod,
length = body.trackLength,
playtime = body.playTime,
source = body.source
).toRes().toHttpResponse(HttpStatus.CREATED)
@RequestMapping(method = [RequestMethod.GET])
fun getPlaybacks(
@RequestParam("userId", required = false) userId: UUID?,
@RequestParam("broken", required = false, defaultValue = "false") unattached: Boolean,
@SortDefault(sort = ["timestamp"], direction = Sort.Direction.DESC) pageable: Pageable
) =
playbackBoundary.getPlaybacksForUser(userId ?: currentUser().uuid!!, unattached, pageable)
.toRes(Playback::toRes).toHttpResponse(HttpStatus.OK)
@RequestMapping(method = [RequestMethod.GET], path = ["/{playbackId}"])
fun getPlayback(@PathVariable("playbackId") playbackId: UUID) =
playbackBoundary.getPlayback(playbackId).toRes().toHttpResponse(HttpStatus.OK)
@RequestMapping(method = [RequestMethod.POST], path = ["/batch"])
fun postPlaybackBatch(@RequestBody batch: PlaybackBatchRes) =
playbackBoundary.batchCreatePlaybacks(batch.playbacks).toRes().toHttpResponse(HttpStatus.OK)
@RequestMapping(method = [RequestMethod.PUT], path = ["/now"])
fun putNowPlaying(
@RequestBody body: PlaybackRes,
@RequestParam(name = "id-method", required = false) idMethod: String?
) =
playbackBoundary.setNowPlaying(
artists = body.artists,
release = body.releaseTitle!!,
recording = body.recordingTitle!!,
timestamp = body.timestamp,
trackLength = body.trackLength,
idMethod = idMethod
).toRes().toHttpResponse(HttpStatus.OK)
@RequestMapping(method = [RequestMethod.GET], path = ["/now"])
fun getNowPlaying() = playbackBoundary.getNowPlaying().toRes().toHttpResponse(HttpStatus.OK)
@RequestMapping(method = [RequestMethod.DELETE])
fun deletePlaybacks(@RequestParam(required = true) withSource: String?) =
playbackBoundary.deletePlaybacks(withSource).toRes().toHttpResponse(HttpStatus.OK)
@RequestMapping(method = [RequestMethod.GET], path = ["/fixlog"])
fun getFixLog(pageable: Pageable) = playbackBoundary.getFixLog(currentUser(), pageable)
.toRes(Playback::toRes)
}
| server/recorder/src/main/kotlin/org/rliz/cfm/recorder/playback/api/PlaybackApi.kt | 2096368428 |
package voice.app.scanner
import androidx.documentfile.provider.DocumentFile
import voice.common.BookId
import voice.data.folders.FolderType
import voice.data.repo.BookContentRepo
import javax.inject.Inject
class MediaScanner
@Inject constructor(
private val contentRepo: BookContentRepo,
private val chapterParser: ChapterParser,
private val bookParser: BookParser,
) {
suspend fun scan(folders: Map<FolderType, List<DocumentFile>>) {
val files = folders.flatMap { (folderType, files) ->
when (folderType) {
FolderType.SingleFile, FolderType.SingleFolder -> {
files
}
FolderType.Root -> {
files.flatMap { file ->
file.listFiles().toList()
}
}
}
}
contentRepo.setAllInactiveExcept(files.map { BookId(it.uri) })
files.forEach { scan(it) }
}
private suspend fun scan(file: DocumentFile) {
val chapters = chapterParser.parse(file)
if (chapters.isEmpty()) return
val content = bookParser.parseAndStore(chapters, file)
val chapterIds = chapters.map { it.id }
val currentChapterGone = content.currentChapter !in chapterIds
val currentChapter = if (currentChapterGone) chapterIds.first() else content.currentChapter
val positionInChapter = if (currentChapterGone) 0 else content.positionInChapter
val updated = content.copy(
chapters = chapterIds,
currentChapter = currentChapter,
positionInChapter = positionInChapter,
isActive = true,
)
if (content != updated) {
validateIntegrity(updated, chapters)
contentRepo.put(updated)
}
}
}
| scanner/src/main/kotlin/voice/app/scanner/MediaScanner.kt | 1530784759 |
package io.gitlab.arturbosch.detekt.rules.bugs.util
import io.gitlab.arturbosch.detekt.rules.collectByType
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtThrowExpression
internal fun KtClassOrObject.isImplementingIterator(): Boolean {
val typeList = this.getSuperTypeList()?.entries
val name = typeList?.firstOrNull()?.typeAsUserType?.referencedName
return name == "Iterator"
}
internal fun KtClassOrObject.getMethod(name: String): KtNamedFunction? {
val functions = this.declarations.filterIsInstance(KtNamedFunction::class.java)
return functions.firstOrNull { it.name == name && it.valueParameters.isEmpty() }
}
internal fun KtNamedFunction.throwsNoSuchElementExceptionThrown(): Boolean {
return this.bodyExpression
?.collectByType<KtThrowExpression>()
?.any { isNoSuchElementExpression(it) } ?: false
}
private fun isNoSuchElementExpression(expression: KtThrowExpression): Boolean {
val calleeExpression = (expression.thrownExpression as? KtCallExpression)?.calleeExpression
return calleeExpression?.text == "NoSuchElementException"
}
| detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/util/IteratorExtension.kt | 1982476821 |
package io.aconite.server.errors
import io.aconite.*
import io.aconite.server.ServerRequestAcceptor
import org.slf4j.LoggerFactory
object LogErrorHandler : ServerRequestAcceptor.Factory<LogErrorHandler.Configuration> {
class Configuration {
var clazz: Class<*> = LogErrorHandler::class.java
}
override fun create(inner: ServerRequestAcceptor, configurator: Configuration.() -> Unit): ServerRequestAcceptor {
val config = Configuration().apply(configurator)
val logger = LoggerFactory.getLogger(config.clazz)
return ErrorHandler(inner) { ex ->
when (ex) {
is HttpException -> ex.toResponse()
else -> {
logger.error("Internal server error", ex)
Response (
code = 500,
body = BodyBuffer(Buffer.wrap("Internal server error"), "text/plain")
)
}
}
}
}
} | aconite-server/src/io/aconite/server/errors/LogErrorHandler.kt | 1756945574 |
package avalon.function
import avalon.group.Hitokoto
import org.junit.Test
class HitokotoTest {
@Test
fun test() {
println(Hitokoto.Hitokotor.get())
}
} | src/test/kotlin/avalon/function/HitokotoTest.kt | 4262139544 |
package org.metplus.cruncher.web.security.useCases
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.metplus.cruncher.web.security.services.LocalTokenService
import org.metplus.cruncher.web.security.services.TokenService
class UserTokenAuthenticationTest {
open class DefaultTokenAuthenticationTest {
protected lateinit var useCase: UserTokenAuthentication
protected lateinit var tokenService: TokenService
protected lateinit var tokens: Array<String?>
@BeforeEach
fun before() {
tokenService = LocalTokenService(30)
useCase = UserTokenAuthentication(tokenService)
tokens = arrayOfNulls(2)
tokens[0] = tokenService.generateToken("1.1.1.1")
tokens[1] = tokenService.generateToken("2.2.2.2")
}
}
class AuthenticationSuccessful : DefaultTokenAuthenticationTest() {
@Test
@Throws(Exception::class)
fun correctToken_shouldReturnTrue() {
val token = tokens[0]
assertThat(useCase.canLogin(token)).isTrue()
}
}
class AuthenticationFail : DefaultTokenAuthenticationTest() {
@Test
@Throws(Exception::class)
fun incorrectToken_shouldReturnFalse() {
val token = "3dc6cc5a-b4b7-41a0-b9cb-7906c0e2f40d"
assertThat(useCase.canLogin(token)).isFalse()
}
}
} | web/src/test/kotlin/org/metplus/cruncher/web/security/useCases/UserTokenAuthenticationTest.kt | 1541716384 |
/*
* Copyright (C) 2014-2020 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager 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.amaze.filemanager.crashreport
import android.content.Context
import com.amaze.filemanager.R
import org.acra.data.CrashReportData
import org.acra.sender.ReportSender
class AcraReportSender : ReportSender {
override fun send(context: Context, errorContent: CrashReportData) {
ErrorActivity.reportError(
context,
errorContent,
ErrorActivity.ErrorInfo.make(
ErrorActivity.ERROR_UI_ERROR,
"Application crash",
R.string.app_ui_crash
)
)
}
override fun requiresForeground(): Boolean {
return true
}
}
| app/src/main/java/com/amaze/filemanager/crashreport/AcraReportSender.kt | 970963765 |
package ca.six.archi.cfl.biz
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import ca.six.archi.cfl.ui.OnRvItemClickListener
import ca.six.archi.cfl.R
import ca.six.archi.cfl.core.App
import ca.six.archi.cfl.data.Plant
import ca.six.oneadapter.lib.OneDiffAdapter
import ca.six.oneadapter.lib.RvViewHolder
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private lateinit var adapter: OneDiffAdapter<Plant>
private lateinit var vm: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val diffCallback = object : DiffUtil.ItemCallback<Plant>() {
override fun areItemsTheSame(oldItem: Plant, newItem: Plant): Boolean = oldItem.plantId == newItem.plantId
override fun areContentsTheSame(oldItem: Plant, newItem: Plant): Boolean = oldItem == newItem
}
rv.layoutManager = GridLayoutManager(this, 2)
adapter = object : OneDiffAdapter<Plant>(diffCallback, R.layout.item_plants) {
override fun apply(vh: RvViewHolder, value: Plant, position: Int) {
val iv = vh.getView<ImageView>(R.id.ivPlant)
Glide.with(this@MainActivity).load(value.imageUrl).into(iv)
// Picasso.get().load(value.imageUrl).into(iv); //让界面超级卡, 故我改为Glide
vh.setText(R.id.tvPlant, value.name)
}
}
rv.addOnItemTouchListener(object : OnRvItemClickListener(rv) {
override fun onItemClick(vh: RecyclerView.ViewHolder) {
val position = vh.adapterPosition
val plant = vm.getPlant(position)
val intent = Intent(this@MainActivity, DetailActivity::class.java)
.putExtra("plant", plant)
startActivity(intent)
}
})
rv.adapter = adapter
vm = ViewModelProvider(this).get(MainViewModel::class.java)
vm.injector = App.injector
vm.dataLiveData.observe(this) { resp ->
adapter.refresh(resp)
}
vm.gridDisplayLiveData.observe(this) { isGrid ->
rv.layoutManager = GridLayoutManager(this, 2)
}
vm.listDisplayLiveData.observe(this) { isList ->
rv.layoutManager = LinearLayoutManager(this)
}
vm.fetchPlants()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menuDisplay -> {
vm.updateDisplay()
item.setIcon(vm.displayIcon)
true
}
R.id.menuFilter -> {
vm.filterData()
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
| deprecated/CoroutineFlowLiveData/app/src/main/java/ca/six/archi/cfl/biz/MainActivity.kt | 763466141 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.utils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.ObsoleteCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/**
* Creates a debounced ReceiveChannel.
*
* @param time the amount of time in units to debounce by
* @param channel the channel to debounce
* @return a throttled channel
*/
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
fun <T> CoroutineScope.debounce(time: Long, channel: ReceiveChannel<T>): ReceiveChannel<T> =
produce(coroutineContext, Channel.CONFLATED) {
var job: Job? = null
channel.consumeEach {
job?.cancel()
job = launch {
delay(time)
send(it)
}
}
job?.join()
}
| app/src/main/java/org/mozilla/focus/utils/Debounce.kt | 2360032824 |
package com.flexpoker.signup.command.aggregate
import com.flexpoker.exception.FlexPokerException
import com.flexpoker.signup.SignUpUser
import com.flexpoker.util.PasswordUtils.encode
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.util.UUID
class SignUpUserTest {
companion object {
private const val VALID_EMAIL_ADDRESS = "[email protected]"
private const val VALID_USERNAME = "unique"
private const val VALID_PASSWORD = "123456"
private val VALID_ENCRYPTED_PASSWORD = encode(VALID_PASSWORD)
private val VALID_AGGREGATE_ID = UUID.randomUUID()
private val VALID_SIGN_UP_CODE = UUID.randomUUID()
}
@Test
fun testConfirmSignedUpUserSucceedsEvent() {
val signUpUser = SignUpUser(
VALID_AGGREGATE_ID, VALID_SIGN_UP_CODE, VALID_EMAIL_ADDRESS,
VALID_USERNAME, VALID_ENCRYPTED_PASSWORD
)
signUpUser.confirmSignedUpUser(VALID_USERNAME, VALID_SIGN_UP_CODE)
assertTrue(signUpUser.isConfirmed)
}
@Test
fun testConfirmSignedUpUserFailsBadUsername() {
val signUpUser = SignUpUser(
VALID_AGGREGATE_ID, VALID_SIGN_UP_CODE, VALID_EMAIL_ADDRESS,
VALID_USERNAME, VALID_ENCRYPTED_PASSWORD
)
assertThrows(FlexPokerException::class.java) {
signUpUser.confirmSignedUpUser("notequalusername", VALID_SIGN_UP_CODE)
}
}
@Test
fun testConfirmSignedUpUserFailsBadSignUpCode() {
val signUpUser = SignUpUser(
VALID_AGGREGATE_ID, VALID_SIGN_UP_CODE, VALID_EMAIL_ADDRESS,
VALID_USERNAME, VALID_ENCRYPTED_PASSWORD
)
assertThrows(FlexPokerException::class.java) {
signUpUser.confirmSignedUpUser(VALID_USERNAME, UUID.randomUUID())
}
}
@Test
fun testConfirmSignedUpUserFailedWhenEventAlreadyApplied() {
val signUpUser = SignUpUser(
VALID_AGGREGATE_ID, VALID_SIGN_UP_CODE, VALID_EMAIL_ADDRESS,
VALID_USERNAME, VALID_ENCRYPTED_PASSWORD
)
signUpUser.confirmSignedUpUser(VALID_USERNAME, VALID_SIGN_UP_CODE)
assertThrows(IllegalStateException::class.java) {
signUpUser.confirmSignedUpUser(VALID_USERNAME, VALID_SIGN_UP_CODE)
}
}
} | src/test/kotlin/com/flexpoker/signup/command/aggregate/SignUpUserTest.kt | 3679621526 |
/*
* Copyright (C) 2017 Andrzej Ressel ([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 <https://www.gnu.org/licenses/>.
*/
package com.jereksel.libresubstratum.activities.main
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import android.databinding.ObservableBoolean
import android.databinding.ObservableList
import com.jereksel.libresubstratum.data.SingleLiveEvent
abstract class IMainViewViewModel: ViewModel() {
abstract fun getAppsObservable(): ObservableList<MainViewModel>
abstract fun getSwipeToRefreshObservable(): ObservableBoolean
abstract fun getDialogContent(): LiveData<String>
abstract fun getPermissions(): LiveData<List<String>>
//Mutable because Adapter is writing to it
abstract fun getAppToOpen(): MutableLiveData<String>
abstract fun reset()
abstract fun init()
abstract suspend fun tickChecks()
} | app/src/main/kotlin/com/jereksel/libresubstratum/activities/main/IMainViewViewModel.kt | 1910749464 |
package coconautti.ddl
import coconautti.sql.Value
abstract class Column(val name: String) {
private var primaryKey = false
private var autoIncrement = false
private var unique = false
private var nullable = false
private var default: Value? = null
fun primaryKey(): Column {
primaryKey = true
return this
}
fun autoIncrement(): Column {
autoIncrement = true
return this
}
fun unique(): Column {
unique = true
return this
}
fun nullable(): Column {
nullable = true
return this
}
fun default(value: Any?): Column {
default = Value(value)
return this
}
abstract fun type(): String
override fun toString(): String {
val sb = StringBuilder()
sb.append(name)
sb.append(type())
if (unique) {
sb.append(" UNIQUE")
}
if (autoIncrement) {
sb.append(" AUTO_INCREMENT")
}
if (primaryKey) {
sb.append(" PRIMARY KEY")
} else if (!nullable) {
sb.append(" NOT NULL")
}
default?.let {
sb.append(" DEFAULT ${default.toString()}")
}
return sb.toString()
}
}
class Varchar(name: String, private val length: Int) : Column(name) {
override fun type(): String = " VARCHAR($length)"
}
class Bigint(name: String) : Column(name) {
override fun type(): String = " BIGINT"
}
class Clob(name: String) : Column(name) {
override fun type(): String = " CLOB"
}
class Timestamp(name: String) : Column(name) {
override fun type(): String = " TIMESTAMP"
}
class Bool(name: String) : Column(name) {
override fun type(): String = " BOOLEAN"
}
| src/main/kotlin/coconautti/ddl/Column.kt | 883208136 |
package net.nemerosa.ontrack.common
/**
* Information about a document.
*
* @property type MIME type about the document
* @property size Size of the document
*/
class DocumentInfo(
val type: String,
val size: Long
) | ontrack-common/src/main/java/net/nemerosa/ontrack/common/DocumentInfo.kt | 46647373 |
package org.jetbrains.protocolReader
import gnu.trove.THashSet
import org.jetbrains.io.JsonReaderEx
import org.jetbrains.jsonProtocol.JsonField
import org.jetbrains.jsonProtocol.JsonOptionalField
import org.jetbrains.jsonProtocol.JsonSubtype
import org.jetbrains.jsonProtocol.StringIntPair
import java.lang.reflect.Method
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.lang.reflect.WildcardType
import java.util.ArrayList
import java.util.LinkedHashMap
fun InterfaceReader(protocolInterfaces: Array<Class<*>>): InterfaceReader {
val map = LinkedHashMap<Class<*>, TypeWriter<*>>(protocolInterfaces.size())
for (typeClass in protocolInterfaces) {
map.put(typeClass, null)
}
return InterfaceReader(map)
}
private val LONG_PARSER = PrimitiveValueReader("long", "-1")
private val INTEGER_PARSER = PrimitiveValueReader("int", "-1")
private val BOOLEAN_PARSER = PrimitiveValueReader("boolean")
private val FLOAT_PARSER = PrimitiveValueReader("float")
private val NUMBER_PARSER = PrimitiveValueReader("double")
private val STRING_PARSER = PrimitiveValueReader("String")
private val NULLABLE_STRING_PARSER = PrimitiveValueReader(className = "String", nullable = true)
private val RAW_STRING_PARSER = PrimitiveValueReader("String", null, true)
private val RAW_STRING_OR_MAP_PARSER = object : PrimitiveValueReader("Object", null, true) {
override fun writeReadCode(scope: ClassScope, subtyping: Boolean, out: TextOutput) {
out.append("readRawStringOrMap(")
addReaderParameter(subtyping, out)
out.append(')')
}
}
private val JSON_PARSER = RawValueReader()
private val STRING_INT_PAIR_PARSER = StringIntPairValueReader()
val VOID_PARSER: ValueReader = object : ValueReader() {
override fun appendFinishedValueTypeName(out: TextOutput) {
out.append("void")
}
override fun writeReadCode(scope: ClassScope, subtyping: Boolean, out: TextOutput) {
out.append("null")
}
}
fun createHandler(typeToTypeHandler: LinkedHashMap<Class<*>, TypeWriter<*>>, aClass: Class<*>): TypeWriter<*> {
val reader = InterfaceReader(typeToTypeHandler)
reader.processed.addAll(typeToTypeHandler.keySet())
reader.go(array(aClass))
return typeToTypeHandler.get(aClass)
}
class InterfaceReader(val typeToTypeHandler: LinkedHashMap<Class<*>, TypeWriter<*>>) {
val processed = THashSet<Class<*>>()
private val refs = ArrayList<TypeRef<*>>()
val subtypeCasters = ArrayList<SubtypeCaster>()
fun go(): LinkedHashMap<Class<*>, TypeWriter<*>> {
return go(typeToTypeHandler.keySet().copyToArray())
}
fun go(classes: Array<Class<*>>): LinkedHashMap<Class<*>, TypeWriter<*>> {
for (typeClass in classes) {
createIfNotExists(typeClass)
}
var hasUnresolved = true
while (hasUnresolved) {
hasUnresolved = false
// refs can be modified - new items can be added
for (i in 0..refs.size() - 1) {
val ref = refs.get(i)
ref.type = typeToTypeHandler.get(ref.typeClass)
if (ref.type == null) {
createIfNotExists(ref.typeClass)
hasUnresolved = true
ref.type = typeToTypeHandler.get(ref.typeClass)
if (ref.type == null) {
throw IllegalStateException()
}
}
}
}
for (subtypeCaster in subtypeCasters) {
subtypeCaster.getSubtypeHandler().subtypeAspect?.setSubtypeCaster(subtypeCaster)
}
return typeToTypeHandler
}
private fun createIfNotExists(typeClass: Class<*>) {
if (typeClass == javaClass<Map<Any, Any>>() || typeClass == javaClass<List<Any>>() || !typeClass.isInterface()) {
return
}
if (!processed.add(typeClass)) {
return
}
typeToTypeHandler.put(typeClass, null)
for (aClass in typeClass.getDeclaredClasses()) {
createIfNotExists(aClass)
}
if (!typeClass.isInterface()) {
throw JsonProtocolModelParseException("Json model type should be interface: " + typeClass.getName())
}
val fields = FieldProcessor(this, typeClass)
for (method in fields.methodHandlerMap.keySet()) {
val returnType = method.getReturnType()
if (returnType != typeClass) {
createIfNotExists(returnType)
}
}
val typeWriter = TypeWriter(typeClass, getSuperclassRef(typeClass), fields.volatileFields, fields.methodHandlerMap, fields.fieldLoaders, fields.lazyRead)
for (ref in refs) {
if (ref.typeClass == typeClass) {
assert(ref.type == null)
ref.type = typeWriter
break
}
}
typeToTypeHandler.put(typeClass, typeWriter)
}
fun getFieldTypeParser(type: Type, isSubtyping: Boolean, method: Method?): ValueReader {
if (type is Class<*>) {
if (type == java.lang.Long.TYPE) {
return LONG_PARSER
}
else if (type == Integer.TYPE) {
return INTEGER_PARSER
}
else if (type == java.lang.Boolean.TYPE) {
return BOOLEAN_PARSER
}
else if (type == java.lang.Float.TYPE) {
return FLOAT_PARSER
}
else if (type == javaClass<Number>() || type == java.lang.Double.TYPE) {
return NUMBER_PARSER
}
else if (type == Void.TYPE) {
return VOID_PARSER
}
else if (type == javaClass<String>()) {
if (method != null) {
val jsonField = method.getAnnotation<JsonField>(javaClass<JsonField>())
if (jsonField != null && jsonField.allowAnyPrimitiveValue()) {
return RAW_STRING_PARSER
}
else if ((jsonField != null && jsonField.optional()) || method.getAnnotation<JsonOptionalField>(javaClass<JsonOptionalField>()) != null) {
return NULLABLE_STRING_PARSER
}
}
return STRING_PARSER
}
else if (type == javaClass<Any>()) {
return RAW_STRING_OR_MAP_PARSER
}
else if (type == javaClass<JsonReaderEx>()) {
return JSON_PARSER
}
else if (type == javaClass<StringIntPair>()) {
return STRING_INT_PAIR_PARSER
}
else if (type.isArray()) {
return ArrayReader(getFieldTypeParser(type.getComponentType(), false, null), false)
}
else if (type.isEnum()) {
return EnumReader(type as Class<Enum<*>>)
}
val ref = getTypeRef(type)
if (ref != null) {
return ObjectValueReader(ref, isSubtyping, method?.getAnnotation<JsonField>(javaClass<JsonField>())?.primitiveValue())
}
throw UnsupportedOperationException("Method return type " + type + " (simple class) not supported")
}
else if (type is ParameterizedType) {
val isList = type.getRawType() == javaClass<List<Any>>()
if (isList || type.getRawType() == javaClass<Map<Any, Any>>()) {
var argumentType = type.getActualTypeArguments()[if (isList) 0 else 1]
if (argumentType is WildcardType) {
val wildcard = argumentType as WildcardType
if (wildcard.getLowerBounds().size() == 0 && wildcard.getUpperBounds().size() == 1) {
argumentType = wildcard.getUpperBounds()[0]
}
}
val componentParser = getFieldTypeParser(argumentType, false, method)
return if (isList) ArrayReader(componentParser, true) else MapReader(componentParser)
}
else {
throw UnsupportedOperationException("Method return type " + type + " (generic) not supported")
}
}
else {
throw UnsupportedOperationException("Method return type " + type + " not supported")
}
}
fun <T> getTypeRef(typeClass: Class<T>): TypeRef<T>? {
val result = TypeRef(typeClass)
refs.add(result)
return result
}
private fun getSuperclassRef(typeClass: Class<*>): TypeRef<*>? {
var result: TypeRef<*>? = null
for (interfaceGeneric in typeClass.getGenericInterfaces()) {
if (interfaceGeneric !is ParameterizedType) {
continue
}
if (interfaceGeneric.getRawType() != javaClass<JsonSubtype<Any>>()) {
continue
}
val param = interfaceGeneric.getActualTypeArguments()[0]
if (param !is Class<*>) {
throw JsonProtocolModelParseException("Unexpected type of superclass " + param)
}
if (result != null) {
throw JsonProtocolModelParseException("Already has superclass " + result!!.typeClass.getName())
}
result = getTypeRef(param)
if (result == null) {
throw JsonProtocolModelParseException("Unknown base class " + param.getName())
}
}
return result
}
} | platform/script-debugger/protocol/protocol-reader/src/InterfaceReader.kt | 1159818381 |
package info.jdavid.asynk.server.http.base
import info.jdavid.asynk.core.asyncWrite
import info.jdavid.asynk.http.Crypto
import info.jdavid.asynk.http.Headers
import info.jdavid.asynk.http.MediaType
import java.nio.ByteBuffer
import java.nio.channels.AsynchronousSocketChannel
open class DefaultHttpHandler(maxRequestSize: Int = 4096): SimpleHttpHandler(maxRequestSize) {
override suspend fun handle(acceptance: Acceptance, headers: Headers, body: ByteBuffer,
socket: AsynchronousSocketChannel,
context: Context) {
val str = StringBuilder()
str.append("${acceptance.method} ${acceptance.uri}\r\n\r\n")
str.append(headers.lines.joinToString("\r\n"))
str.append("\n\n")
val contentType = headers.value(Headers.CONTENT_TYPE) ?: "text/plain"
val isText =
contentType.startsWith("text/") ||
contentType.startsWith("application/") &&
(contentType.startsWith(MediaType.JAVASCRIPT) ||
contentType.startsWith(MediaType.JSON) ||
contentType.startsWith(MediaType.XHTML) ||
contentType.startsWith(MediaType.WEB_MANIFEST))
//val extra = if (isText) body.remaining() else Math.min(2048, body.remaining() * 2)
val extra = if (isText) body.remaining() else body.remaining() * 2
val bytes = str.toString().toByteArray(Charsets.ISO_8859_1)
socket.asyncWrite(
ByteBuffer.wrap(
"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: ${bytes.size + extra}\r\nConnection: close\r\n\r\n".
toByteArray(Charsets.US_ASCII)
),
true
)
socket.asyncWrite(ByteBuffer.wrap(bytes), true)
if (extra > 0) {
if (contentType.startsWith("text/") ||
contentType.startsWith("application/") &&
(contentType.startsWith(MediaType.JAVASCRIPT) ||
contentType.startsWith(MediaType.JSON) ||
contentType.startsWith(MediaType.XHTML) ||
contentType.startsWith(MediaType.WEB_MANIFEST))) {
socket.asyncWrite(body, true)
}
else {
// if (body.remaining() > 1024) {
// val limit = body.limit()
// body.limit(body.position() + 511)
// socket.asyncWrite(
// ByteBuffer.wrap(Crypto.hex(body).toByteArray(Charsets.US_ASCII)),
// true
// )
// socket.asyncWrite(
// ByteBuffer.wrap("....".toByteArray(Charsets.US_ASCII)),
// true
// )
// body.limit(limit)
// body.position(limit - 511)
// socket.asyncWrite(
// ByteBuffer.wrap(Crypto.hex(body).toByteArray(Charsets.US_ASCII)),
// true
// )
// }
// else {
socket.asyncWrite(ByteBuffer.wrap(Crypto.hex(body).toByteArray(Charsets.US_ASCII)), true)
// }
}
}
}
}
| src/test/kotlin/info/jdavid/asynk/server/http/base/DefaultHttpHandler.kt | 4063023924 |
package io.mockk.proxy.android.transformation
import android.os.Build
import com.android.dx.stock.ProxyBuilder
import com.android.dx.stock.ProxyBuilder.MethodSetEntry
import io.mockk.proxy.MockKAgentException
import io.mockk.proxy.MockKInvocationHandler
import io.mockk.proxy.common.ProxyInvocationHandler
import io.mockk.proxy.common.transformation.SubclassInstrumentation
import java.lang.reflect.Method
import java.lang.reflect.Modifier
internal class AndroidSubclassInstrumentation(
val inlineInstrumentationApplied: Boolean
) : SubclassInstrumentation {
@Suppress("UNCHECKED_CAST")
override fun <T> subclass(clazz: Class<T>, interfaces: Array<Class<*>>): Class<T> =
try {
ProxyBuilder.forClass(clazz)
.implementing(*interfaces)
.apply {
if (inlineInstrumentationApplied) {
onlyMethods(getMethodsToProxy(clazz, interfaces))
}
}
.apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// markTrusted();
}
}
.apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
withSharedClassLoader()
}
}
.buildProxyClass() as Class<T>
} catch (e: Exception) {
throw MockKAgentException("Failed to mock $clazz", e)
}
private fun <T> getMethodsToProxy(clazz: Class<T>, interfaces: Array<Class<*>>): Array<Method> {
val abstractMethods = mutableSetOf<MethodSetEntry>()
val nonAbstractMethods = mutableSetOf<MethodSetEntry>()
tailrec fun fillInAbstractAndNonAbstract(clazz: Class<*>) {
clazz.declaredMethods
.filter { Modifier.isAbstract(it.modifiers) }
.map { MethodSetEntry(it) }
.filterNotTo(abstractMethods) { it in nonAbstractMethods }
clazz.declaredMethods
.filterNot { Modifier.isAbstract(it.modifiers) }
.mapTo(nonAbstractMethods) { MethodSetEntry(it) }
fillInAbstractAndNonAbstract(clazz.superclass ?: return)
}
fillInAbstractAndNonAbstract(clazz)
fun Class<*>.allSuperInterfaces(): Set<Class<*>> {
val setOfInterfaces = this.interfaces.toSet()
return setOfInterfaces + setOfInterfaces.flatMap { it.allSuperInterfaces() }
}
(clazz.interfaces + interfaces)
.asSequence()
.flatMap { it.allSuperInterfaces().asSequence() }
.flatMap { it.methods.asSequence() }
.map { MethodSetEntry(it) }
.filterNot { it in nonAbstractMethods }
.mapTo(abstractMethods) { it }
return abstractMethods.map { it.originalMethod }.toTypedArray()
}
override fun setProxyHandler(proxy: Any, handler: MockKInvocationHandler) {
if (ProxyBuilder.isProxyClass(proxy::class.java)) {
ProxyBuilder.setInvocationHandler(proxy, ProxyInvocationHandler(handler))
}
}
} | modules/mockk-agent-android/src/main/kotlin/io/mockk/proxy/android/transformation/AndroidSubclassInstrumentation.kt | 2187330844 |
package io.mockk.impl.recording.states
import io.mockk.InternalPlatformDsl.toStr
import io.mockk.Invocation
import io.mockk.MockKGateway.VerificationParameters
import io.mockk.impl.log.Logger
import io.mockk.impl.recording.CommonCallRecorder
open class AnsweringState(recorder: CommonCallRecorder) : CallRecordingState(recorder) {
open val log = recorder.safeToString(Logger<AnsweringState>())
override fun call(invocation: Invocation): Any? {
val stub = recorder.stubRepo.stubFor(invocation.self)
stub.recordCall(invocation.copy(originalCall = { null }))
try {
val answer = stub.answer(invocation)
log.debug { "Answering ${answer.toStr()} on $invocation" }
return answer
} catch (ex: Exception) {
log.debug { "Throwing ${ex.toStr()} on $invocation" }
throw ex
}
}
override fun startStubbing() = recorder.factories.stubbingState(recorder)
override fun startVerification(params: VerificationParameters) = recorder.factories.verifyingState(recorder, params)
} | modules/mockk/src/commonMain/kotlin/io/mockk/impl/recording/states/AnsweringState.kt | 3447974252 |
package com.lunivore.montecarluni.engine
import com.lunivore.montecarluni.model.CycleTime
import com.lunivore.montecarluni.model.Record
import org.junit.Assert.assertEquals
import org.junit.Test
import java.time.Duration
import java.time.LocalDateTime
class CycleTimesCalculatorTest {
@Test
fun `should provide a list of the gaps between work items`() {
// Given a list of records
val dates = listOf(LocalDateTime.of(2017, 1, 2, 12, 0, 0),
LocalDateTime.of(2017, 1, 3, 16, 0, 0), // this one is out of order
LocalDateTime.of(2017, 1, 3, 14, 0, 0),
LocalDateTime.of(2017, 1, 7, 16, 0, 0))
val records = dates
.map { Record(it, null) }
// When we ask for the cycle times from the records
val result = CycleTimesCalculator().calculateCycleTimes(records)
// Then it should give us back a list of the gaps
val expectedResult = listOf(
CycleTime("", dates[0], null),
CycleTime("", dates[2], Duration.ofHours(26)),
CycleTime("", dates[1], Duration.ofHours(2)),
CycleTime("", dates[3], Duration.ofHours(96))
)
assertEquals(expectedResult, result)
}
}
| src/test/kotlin/com/lunivore/montecarluni/engine/CycleTimesCalculatorTest.kt | 2446703329 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.