content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/********************************************************** {{{1 ***********
* Copyright © 2015 … 2016 "Martin Krischik" «[email protected]»
***************************************************************************
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/
********************************************************** }}}1 **********/
package com.krischik.fit_import
/**
* <p>
* </p>
*
* <pre>
* Datum ;Zeit ;Dauer ;Watt;Puls;u/min;kcal;km;°
* 02.02.2014;18:42;00:40:00 ;88 ;118 ;48 ;294 ;6 ;-;
* 03.02.2014;18:29;00:40:00 ;88 ;94 ;61 ;294 ;6 ;-;
* </pre>
* @author "Martin Krischik" «[email protected]»
* @version 1.0
* @since 1.0
*/
data class Ketfit(
val start: java.util.Date,
val end: java.util.Date,
val watt: Int,
val puls: Int,
val uMin: Int,
val kCal: Int,
val km: Int,
val ω: Int)
{
/**
* <p>Kettler measures km and GoogleFit uses m</p>
*/
public val meter: Float
get() = km.toFloat() * 1000.0f
/**
* <p>Steps per minute. One cycle is two steps.</p>
*/
public val stepMin: Float
get() = uMin * 2.0f
/*
* <p>Google fit stores the steps for cross trainer.
* First we calculate the total revolutions from the average revolution per minute and the
* the time of session. * We consider one revolution to be one step.
*/
public val steps: Int
get() = (stepMin * durationInMinutes).toInt ()
/**
* <p>Training duration ins minutes</p>
*/
public val durationInMinutes: Float
get () = durationInSeconds / 60.0f
/**
* <p>Training duration ins seconds</p>
*/
public val durationInSeconds: Float
get () = (end.time - start.time).toFloat() / 1000.0f
}
// vim: set nowrap tabstop=8 shiftwidth=4 softtabstop=4 expandtab :
// vim: set textwidth=0 filetype=kotlin foldmethod=marker spell spelllang=en_gb :
| JavaLib/src/main/kotlin/com.krischik/fit_import/Ketfit.kt | 3592954004 |
package com.aidanvii.toolbox.adapterviews.recyclerpager
import android.view.ViewGroup
/**
* Represents the item held internally by the [android.support.v4.view.ViewPager]
*/
internal class PageItem<ViewHolder : RecyclerPagerAdapter.ViewHolder>(
val viewType: Int,
var adapterPosition: Int
) {
lateinit var viewHolderWrapper: ViewHolderWrapper<ViewHolder>
var viewTransaction: ViewTransaction? = null
fun runPendingTransaction(container: ViewGroup) {
viewTransaction?.run(container, this)
viewTransaction = null
}
} | adapterviews-recyclerpager/src/main/java/com/aidanvii/toolbox/adapterviews/recyclerpager/PageItem.kt | 4109078245 |
/****************************************************************************************
* Copyright (c) 2020 Arthur Milchior <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.libanki.template
import androidx.annotation.VisibleForTesting
import com.ichi2.libanki.template.TemplateError.NoClosingBrackets
import java.util.NoSuchElementException
import kotlin.Throws
/**
* This class encodes template.rs's file creating template.
* Due to the way iterator work in java, it's easier for the class to keep track of the template
*/
class Tokenizer internal constructor(template: String) : Iterator<Tokenizer.Token> {
/**
* The remaining of the string to read.
*/
private var mTemplate: String
/**
* Become true if lexing failed. That is, the string start with {{, but no }} is found.
*/
private var mFailed = false
/**
* Whether we consider <% and %> as handlebar
*/
private val mLegacy: Boolean
override fun hasNext(): Boolean {
return mTemplate.length > 0 && !mFailed
}
/**
* The kind of data we can find in a template and may want to consider for card generation
*/
enum class TokenKind {
/**
* Some text, assumed not to contains {{*}}
*/
TEXT,
/**
* {{Field name}}
*/
REPLACEMENT,
/**
* {{#Field name}}
*/
OPEN_CONDITIONAL,
/**
* {{^Field name}}
*/
OPEN_NEGATED,
/**
* {{/Field name}}
*/
CLOSE_CONDITIONAL
}
/**
* This is equivalent to upstream's template.rs's Token type.
*
*/
@VisibleForTesting
class Token(
val kind: TokenKind,
/**
* If mKind is Text, then this contains the text.
* Otherwise, it contains the content between "{{" and "}}", without the curly braces.
*/
val text: String
) {
override fun toString(): String {
return kind.toString() + "(\"" + text + "\")"
}
override fun equals(other: Any?): Boolean {
if (other !is Token) {
return false
}
val t = other
return kind == t.kind && text == t.text
}
@VisibleForTesting
fun new_to_legacy(): Token {
return Token(
kind,
new_to_legacy(
text
)
)
}
}
/**
* This is similar to template.rs's type IResult<&str, Token>.
* That is, it contains a token that was parsed, and the remaining of the string that must be read.
*/
@VisibleForTesting
internal class IResult(
val token: Token,
/**
* The part of the string that must still be read.
*/
/*
This is a substring of the template. Java deal efficiently with substring by encoding it as original string,
start index and length, so there is no loss in efficiency in using string instead of position.
*/
val remaining: String
) {
override fun toString(): String {
return "($token, \"$remaining\")"
}
override fun equals(other: Any?): Boolean {
if (other !is IResult) {
return false
}
val r = other
return token == r.token && remaining == r.remaining
}
@VisibleForTesting
fun new_to_legacy(): IResult {
return IResult(token.new_to_legacy(), new_to_legacy(remaining))
}
}
/**
* @return The next token.
* @throws TemplateError.NoClosingBrackets with no message if the template is entirely lexed, and with the remaining string otherwise.
*/
@Throws(NoClosingBrackets::class)
override fun next(): Token {
if (mTemplate.length == 0) {
throw NoSuchElementException()
}
val ir = next_token(mTemplate, mLegacy)
if (ir == null) {
// Missing closing }}
mFailed = true
throw NoClosingBrackets(mTemplate)
}
mTemplate = ir.remaining
return ir.token
}
companion object {
/**
* If this text appears at the top of a template (not considering whitespaces and other \s symbols), then the
* template accept legacy handlebars. That is <% foo %> is interpreted similarly as {{ foo }}.
* This is used for compatibility with legacy version of anki.
*
* Same as rslib/src/template's ALT_HANDLEBAR_DIRECTIVE upstream */
@VisibleForTesting
val ALT_HANDLEBAR_DIRECTIVE = "{{=<% %>=}}"
@VisibleForTesting
fun new_to_legacy(template_part: String): String {
return template_part.replace("{{", "<%").replace("}}", "%>")
}
/**
* @param template The part of the template that must still be lexed
* @param legacy whether <% is accepted as a handlebar
* @return The longest prefix without handlebar, or null if it's empty.
*/
@VisibleForTesting
internal fun text_token(template: String, legacy: Boolean): IResult? {
val first_legacy_handlebar = if (legacy) template.indexOf("<%") else -1
val first_new_handlebar = template.indexOf("{{")
val text_size: Int
text_size = if (first_new_handlebar == -1) {
if (first_legacy_handlebar == -1) {
template.length
} else {
first_legacy_handlebar
}
} else {
if (first_legacy_handlebar == -1 || first_new_handlebar < first_legacy_handlebar) {
first_new_handlebar
} else {
first_legacy_handlebar
}
}
return if (text_size == 0) {
null
} else IResult(
Token(
TokenKind.TEXT,
template.substring(0, text_size)
),
template.substring(text_size)
)
}
/**
* classify handle based on leading character
* @param handle The content between {{ and }}
*/
internal fun classify_handle(handle: String): Token {
var start_pos = 0
while (start_pos < handle.length && handle[start_pos] == '{') {
start_pos++
}
val start = handle.substring(start_pos).trim { it <= ' ' }
return if (start.length < 2) {
Token(
TokenKind.REPLACEMENT,
start
)
} else when (start[0]) {
'#' -> Token(
TokenKind.OPEN_CONDITIONAL,
start.substring(1).trim { it <= ' ' }
)
'/' -> Token(
TokenKind.CLOSE_CONDITIONAL,
start.substring(1).trim { it <= ' ' }
)
'^' -> Token(
TokenKind.OPEN_NEGATED,
start.substring(1).trim { it <= ' ' }
)
else -> Token(
TokenKind.REPLACEMENT,
start
)
}
}
/**
* @param template a part of a template to lex
* @param legacy Whether to also consider handlebar starting with <%
* @return The content of handlebar at start of template
*/
@VisibleForTesting
internal fun handlebar_token(template: String, legacy: Boolean): IResult? {
val new_handlebar_token = new_handlebar_token(template)
if (new_handlebar_token != null) {
return new_handlebar_token
}
return if (legacy) {
legacy_handlebar_token(template)
} else null
}
/**
* @param template a part of a template to lex
* @return The content of handlebar at start of template
*/
@VisibleForTesting
internal fun new_handlebar_token(template: String): IResult? {
return handlebar_token(template, "{{", "}}")
}
private fun handlebar_token(template: String, prefix: String, suffix: String): IResult? {
if (!template.startsWith(prefix)) {
return null
}
val end = template.indexOf(suffix)
if (end == -1) {
return null
}
val content = template.substring(prefix.length, end)
val handlebar = classify_handle(content)
return IResult(handlebar, template.substring(end + suffix.length))
}
/**
* @param template a part of a template to lex
* @return The content of handlebar at start of template
*/
@VisibleForTesting
internal fun legacy_handlebar_token(template: String): IResult? {
return handlebar_token(template, "<%", "%>")
}
/**
* @param template The remaining of template to lex
* @param legacy Whether to accept <% as handlebar
* @return The next token, or null at end of string
*/
internal fun next_token(template: String, legacy: Boolean): IResult? {
val t = handlebar_token(template, legacy)
return t ?: text_token(template, legacy)
}
}
/**
* @param template A question or answer template.
*/
init {
@Suppress("NAME_SHADOWING")
var template = template
val trimmed = template.trim { it <= ' ' }
mLegacy = trimmed.startsWith(ALT_HANDLEBAR_DIRECTIVE)
if (mLegacy) {
template = trimmed.substring(ALT_HANDLEBAR_DIRECTIVE.length)
}
mTemplate = template
}
}
| AnkiDroid/src/main/java/com/ichi2/libanki/template/Tokenizer.kt | 2322071212 |
package com.aidanvii.toolbox
typealias Action = () -> Unit
typealias Consumer<T> = (T) -> Unit
typealias Provider<T> = () -> T
typealias ExtensionAction<T> = T.() -> Unit
typealias ExtensionConsumer<T, I> = T.(I) -> Unit
val consumerStub: Consumer<Any> = {}
val actionStub: Action = {} | common/src/main/java/com/aidanvii/toolbox/TypeAliases.kt | 4194645475 |
package com.infinum.dbinspector.domain.settings.control.converters
import com.infinum.dbinspector.data.Data
import com.infinum.dbinspector.data.models.local.proto.input.SettingsTask
import com.infinum.dbinspector.data.models.local.proto.output.SettingsEntity
import com.infinum.dbinspector.domain.Converters
import com.infinum.dbinspector.domain.shared.converters.BlobPreviewConverter
import com.infinum.dbinspector.domain.shared.converters.TruncateModeConverter
import com.infinum.dbinspector.domain.shared.models.BlobPreviewMode
import com.infinum.dbinspector.domain.shared.models.TruncateMode
import com.infinum.dbinspector.domain.shared.models.parameters.SettingsParameters
import com.infinum.dbinspector.shared.BaseTest
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.koin.core.module.Module
import org.koin.dsl.module
import org.koin.test.get
@DisplayName("SettingsConverter tests")
internal class SettingsConverterTest : BaseTest() {
override fun modules(): List<Module> = listOf(
module {
factory<Converters.TruncateMode> { mockk<TruncateModeConverter>() }
factory<Converters.BlobPreview> { mockk<BlobPreviewConverter>() }
}
)
@Test
fun `Invoke is not implemented and should throw AbstractMethodError`() {
val given = mockk<SettingsParameters>()
val converter = SettingsConverter(get(), get())
assertThrows<NotImplementedError> {
blockingTest {
converter.invoke(given)
}
}
}
@Test
fun `Get converts to default data task values`() =
test {
val given = mockk<SettingsParameters.Get>()
val expected = SettingsTask()
val truncateModeConverter: Converters.TruncateMode = get()
val blobPreviewConverter: Converters.BlobPreview = get()
val converter = SettingsConverter(truncateModeConverter, blobPreviewConverter)
coEvery { truncateModeConverter.invoke(any()) } returns mockk()
coEvery { blobPreviewConverter.invoke(any()) } returns mockk()
val actual = converter get given
coVerify(exactly = 0) { truncateModeConverter.invoke(any()) }
coVerify(exactly = 0) { blobPreviewConverter.invoke(any()) }
assertEquals(expected, actual)
}
@Test
fun `Lines limit enabled converts to data task with value true`() =
test {
val given = mockk<SettingsParameters.LinesLimit> {
every { isEnabled } returns true
}
val expected = SettingsTask(linesLimited = true)
val truncateModeConverter: Converters.TruncateMode = get()
val blobPreviewConverter: Converters.BlobPreview = get()
val converter = SettingsConverter(truncateModeConverter, blobPreviewConverter)
coEvery { truncateModeConverter.invoke(any()) } returns mockk()
coEvery { blobPreviewConverter.invoke(any()) } returns mockk()
val actual = converter linesLimit given
coVerify(exactly = 0) { truncateModeConverter.invoke(any()) }
coVerify(exactly = 0) { blobPreviewConverter.invoke(any()) }
assertEquals(expected, actual)
}
@Test
fun `Lines limit disabled converts to data task with value false`() =
test {
val given = mockk<SettingsParameters.LinesLimit> {
every { isEnabled } returns false
}
val expected = SettingsTask(linesLimited = false)
val truncateModeConverter: Converters.TruncateMode = get()
val blobPreviewConverter: Converters.BlobPreview = get()
val converter = SettingsConverter(truncateModeConverter, blobPreviewConverter)
coEvery { truncateModeConverter.invoke(any()) } returns mockk()
coEvery { blobPreviewConverter.invoke(any()) } returns mockk()
val actual = converter linesLimit given
coVerify(exactly = 0) { truncateModeConverter.invoke(any()) }
coVerify(exactly = 0) { blobPreviewConverter.invoke(any()) }
assertEquals(expected, actual)
}
@Test
fun `Lines count more than zero converts to data task with same value`() =
test {
val given = mockk<SettingsParameters.LinesCount> {
every { count } returns 3
}
val expected = SettingsTask(linesCount = 3)
val truncateModeConverter: Converters.TruncateMode = get()
val blobPreviewConverter: Converters.BlobPreview = get()
val converter = SettingsConverter(truncateModeConverter, blobPreviewConverter)
coEvery { truncateModeConverter.invoke(any()) } returns mockk()
coEvery { blobPreviewConverter.invoke(any()) } returns mockk()
val actual = converter linesCount given
coVerify(exactly = 0) { truncateModeConverter.invoke(any()) }
coVerify(exactly = 0) { blobPreviewConverter.invoke(any()) }
assertEquals(expected, actual)
}
@Test
fun `Lines count set to zero converts to data task with maximum value`() =
test {
val given = mockk<SettingsParameters.LinesCount> {
every { count } returns 0
}
val expected = SettingsTask(linesCount = Data.Constants.Settings.LINES_LIMIT_MAXIMUM)
val truncateModeConverter: Converters.TruncateMode = get()
val blobPreviewConverter: Converters.BlobPreview = get()
val converter = SettingsConverter(truncateModeConverter, blobPreviewConverter)
coEvery { truncateModeConverter.invoke(any()) } returns mockk()
coEvery { blobPreviewConverter.invoke(any()) } returns mockk()
val actual = converter linesCount given
coVerify(exactly = 0) { truncateModeConverter.invoke(any()) }
coVerify(exactly = 0) { blobPreviewConverter.invoke(any()) }
assertEquals(expected, actual)
}
@Test
fun `Truncate mode START converts to data task with same value`() =
test {
val given = mockk<SettingsParameters.Truncate> {
every { mode } returns TruncateMode.START
}
val expected = SettingsTask(truncateMode = SettingsEntity.TruncateMode.START)
val truncateModeConverter: Converters.TruncateMode = get()
val blobPreviewConverter: Converters.BlobPreview = get()
val converter = SettingsConverter(truncateModeConverter, blobPreviewConverter)
coEvery { truncateModeConverter.invoke(any()) } returns SettingsEntity.TruncateMode.START
coEvery { blobPreviewConverter.invoke(any()) } returns mockk()
val actual = converter truncateMode given
coVerify(exactly = 1) { truncateModeConverter.invoke(any()) }
coVerify(exactly = 0) { blobPreviewConverter.invoke(any()) }
assertEquals(expected, actual)
}
@Test
fun `Truncate mode MIDDLE converts to data task with same value`() =
test {
val given = mockk<SettingsParameters.Truncate> {
every { mode } returns TruncateMode.MIDDLE
}
val expected = SettingsTask(truncateMode = SettingsEntity.TruncateMode.MIDDLE)
val truncateModeConverter: Converters.TruncateMode = get()
val blobPreviewConverter: Converters.BlobPreview = get()
val converter = SettingsConverter(truncateModeConverter, blobPreviewConverter)
coEvery { truncateModeConverter.invoke(any()) } returns SettingsEntity.TruncateMode.MIDDLE
coEvery { blobPreviewConverter.invoke(any()) } returns mockk()
val actual = converter truncateMode given
coVerify(exactly = 1) { truncateModeConverter.invoke(any()) }
coVerify(exactly = 0) { blobPreviewConverter.invoke(any()) }
assertEquals(expected, actual)
}
@Test
fun `Truncate mode END converts to data task with same value`() =
test {
val given = mockk<SettingsParameters.Truncate> {
every { mode } returns TruncateMode.END
}
val expected = SettingsTask(truncateMode = SettingsEntity.TruncateMode.END)
val truncateModeConverter: Converters.TruncateMode = get()
val blobPreviewConverter: Converters.BlobPreview = get()
val converter = SettingsConverter(truncateModeConverter, blobPreviewConverter)
coEvery { truncateModeConverter.invoke(any()) } returns SettingsEntity.TruncateMode.END
coEvery { blobPreviewConverter.invoke(any()) } returns mockk()
val actual = converter truncateMode given
coVerify(exactly = 1) { truncateModeConverter.invoke(any()) }
coVerify(exactly = 0) { blobPreviewConverter.invoke(any()) }
assertEquals(expected, actual)
}
@Test
fun `Blob preview mode UNSUPPORTED converts to data task with UNRECOGNIZED value`() =
test {
val given = mockk<SettingsParameters.BlobPreview> {
every { mode } returns BlobPreviewMode.UNSUPPORTED
}
val expected = SettingsTask(blobPreviewMode = SettingsEntity.BlobPreviewMode.UNRECOGNIZED)
val truncateModeConverter: Converters.TruncateMode = get()
val blobPreviewConverter: Converters.BlobPreview = get()
val converter = SettingsConverter(truncateModeConverter, blobPreviewConverter)
coEvery { truncateModeConverter.invoke(any()) } returns mockk()
coEvery { blobPreviewConverter.invoke(any()) } returns SettingsEntity.BlobPreviewMode.UNRECOGNIZED
val actual = converter blobPreviewMode given
coVerify(exactly = 0) { truncateModeConverter.invoke(any()) }
coVerify(exactly = 1) { blobPreviewConverter.invoke(any()) }
assertEquals(expected, actual)
}
@Test
fun `Blob preview mode PLACEHOLDER converts to data task with same value`() =
test {
val given = mockk<SettingsParameters.BlobPreview> {
every { mode } returns BlobPreviewMode.PLACEHOLDER
}
val expected = SettingsTask(blobPreviewMode = SettingsEntity.BlobPreviewMode.PLACEHOLDER)
val truncateModeConverter: Converters.TruncateMode = get()
val blobPreviewConverter: Converters.BlobPreview = get()
val converter = SettingsConverter(truncateModeConverter, blobPreviewConverter)
coEvery { truncateModeConverter.invoke(any()) } returns mockk()
coEvery { blobPreviewConverter.invoke(any()) } returns SettingsEntity.BlobPreviewMode.PLACEHOLDER
val actual = converter blobPreviewMode given
coVerify(exactly = 0) { truncateModeConverter.invoke(any()) }
coVerify(exactly = 1) { blobPreviewConverter.invoke(any()) }
assertEquals(expected, actual)
}
@Test
fun `Blob preview mode UT8 converts to data task with same value`() =
test {
val given = mockk<SettingsParameters.BlobPreview> {
every { mode } returns BlobPreviewMode.UTF_8
}
val expected = SettingsTask(blobPreviewMode = SettingsEntity.BlobPreviewMode.UTF8)
val truncateModeConverter: Converters.TruncateMode = get()
val blobPreviewConverter: Converters.BlobPreview = get()
val converter = SettingsConverter(truncateModeConverter, blobPreviewConverter)
coEvery { truncateModeConverter.invoke(any()) } returns mockk()
coEvery { blobPreviewConverter.invoke(any()) } returns SettingsEntity.BlobPreviewMode.UTF8
val actual = converter blobPreviewMode given
coVerify(exactly = 0) { truncateModeConverter.invoke(any()) }
coVerify(exactly = 1) { blobPreviewConverter.invoke(any()) }
assertEquals(expected, actual)
}
@Test
fun `Blob preview mode HEX converts to data task with same value`() =
test {
val given = mockk<SettingsParameters.BlobPreview> {
every { mode } returns BlobPreviewMode.HEX
}
val expected = SettingsTask(blobPreviewMode = SettingsEntity.BlobPreviewMode.HEX)
val truncateModeConverter: Converters.TruncateMode = get()
val blobPreviewConverter: Converters.BlobPreview = get()
val converter = SettingsConverter(truncateModeConverter, blobPreviewConverter)
coEvery { truncateModeConverter.invoke(any()) } returns mockk()
coEvery { blobPreviewConverter.invoke(any()) } returns SettingsEntity.BlobPreviewMode.HEX
val actual = converter blobPreviewMode given
coVerify(exactly = 0) { truncateModeConverter.invoke(any()) }
coVerify(exactly = 1) { blobPreviewConverter.invoke(any()) }
assertEquals(expected, actual)
}
@Test
fun `Blob preview mode BASE_64 converts to data task with same value`() =
test {
val given = mockk<SettingsParameters.BlobPreview> {
every { mode } returns BlobPreviewMode.BASE_64
}
val expected = SettingsTask(blobPreviewMode = SettingsEntity.BlobPreviewMode.BASE64)
val truncateModeConverter: Converters.TruncateMode = get()
val blobPreviewConverter: Converters.BlobPreview = get()
val converter = SettingsConverter(truncateModeConverter, blobPreviewConverter)
coEvery { truncateModeConverter.invoke(any()) } returns mockk()
coEvery { blobPreviewConverter.invoke(any()) } returns SettingsEntity.BlobPreviewMode.BASE64
val actual = converter blobPreviewMode given
coVerify(exactly = 0) { truncateModeConverter.invoke(any()) }
coVerify(exactly = 1) { blobPreviewConverter.invoke(any()) }
assertEquals(expected, actual)
}
@Test
fun `Empty ignored table name converts to data task with empty value`() =
test {
val given = mockk<SettingsParameters.IgnoredTableName> {
every { name } returns ""
}
val expected = SettingsTask(ignoredTableName = "")
val truncateModeConverter: Converters.TruncateMode = get()
val blobPreviewConverter: Converters.BlobPreview = get()
val converter = SettingsConverter(truncateModeConverter, blobPreviewConverter)
coEvery { truncateModeConverter.invoke(any()) } returns mockk()
coEvery { blobPreviewConverter.invoke(any()) } returns mockk()
val actual = converter ignoredTableName given
coVerify(exactly = 0) { truncateModeConverter.invoke(any()) }
coVerify(exactly = 0) { blobPreviewConverter.invoke(any()) }
assertEquals(expected, actual)
}
@Test
fun `Ignored table name converts to data task with same value`() =
test {
val given = mockk<SettingsParameters.IgnoredTableName> {
every { name } returns "android_metadata"
}
val expected = SettingsTask(ignoredTableName = "android_metadata")
val truncateModeConverter: Converters.TruncateMode = get()
val blobPreviewConverter: Converters.BlobPreview = get()
val converter = SettingsConverter(truncateModeConverter, blobPreviewConverter)
coEvery { truncateModeConverter.invoke(any()) } returns mockk()
coEvery { blobPreviewConverter.invoke(any()) } returns mockk()
val actual = converter ignoredTableName given
coVerify(exactly = 0) { truncateModeConverter.invoke(any()) }
coVerify(exactly = 0) { blobPreviewConverter.invoke(any()) }
assertEquals(expected, actual)
}
}
| dbinspector/src/test/kotlin/com/infinum/dbinspector/domain/settings/control/converters/SettingsConverterTest.kt | 3932316983 |
package com.moviereel.data.repositories.movierepo.remote
import com.moviereel.data.api.ApiRetrofitService
import com.moviereel.data.api.model.movie.MovieNowPlayingResponse
import com.moviereel.data.api.model.movie.MoviePopularResponse
import com.moviereel.data.db.entities.movie.*
import com.moviereel.data.repositories.movierepo.MovieDataSource
import io.reactivex.Flowable
import javax.inject.Inject
import javax.inject.Singleton
/**
* @author lusinabrian on 08/08/17.
* @Notes Remote data source for movies
*/
@Singleton
class MoviesRemoteDataSource
@Inject
constructor(val mApiRetrofitService: ApiRetrofitService) : MovieDataSource {
/**
* performs a call to get Now Playing Movies
* Will return a response that will contain a list of all the Movies that are currently now playing
* @return [MovieNowPlayingResponse] response to return from the api call
*/
override fun getMoviesNowPlaying(remote: Boolean?, page: Int, language: String): Flowable<List<MovieNowPlayingEntity>> {
val data = mApiRetrofitService.getMoviesNowPlaying(language, page)
return data.flatMap({ Flowable.just(it.results) })
}
/**
* API call to get the latest movies being shown*/
override fun doGetMoviesLatest(remote: Boolean, language: String): Flowable<MovieLatestEntity> {
return mApiRetrofitService.doGetMoviesLatest(language)
}
/**
* Does an api call to get a list of popular movies
* @return A list of [MoviePopularResponse] we get from the api call
*/
override fun doGetMoviesPopular(remote: Boolean, page: Int, language: String):
Flowable<List<MoviePopularEntity>> {
val popularMovieData = mApiRetrofitService.doGetMoviesPopular(page, language)
return popularMovieData.flatMap { Flowable.just(it.results) }
}
override fun doGetMoviesTopRated(remote: Boolean, page: Int, language: String, region: String): Flowable<List<MovieTopRatedEntity>> {
val topRatedMovieData = mApiRetrofitService.doGetMoviesTopRated(page, language, region)
return topRatedMovieData.flatMap { Flowable.just(it.results) }
}
override fun doGetMoviesUpcoming(remote: Boolean, page: Int, language: String, region: String): Flowable<List<MovieUpcomingEntity>> {
val upcomingMovieData = mApiRetrofitService.doGetMoviesUpcoming(page, language, region)
return upcomingMovieData.flatMap { Flowable.just(it.results) }
}
} | app/src/main/kotlin/com/moviereel/data/repositories/movierepo/remote/MoviesRemoteDataSource.kt | 1397528840 |
package com.fracturedskies.task
import com.fracturedskies.api.*
import com.fracturedskies.api.task.BehaviorStatus
import com.fracturedskies.api.task.BehaviorStatus.*
import com.fracturedskies.engine.Id
import com.fracturedskies.engine.api.Update
import javax.enterprise.event.*
import javax.inject.*
@Singleton
class TaskExecutionSystem {
@Inject
lateinit var world: World
@Inject
lateinit var events: Event<Any>
private val behavior = mutableMapOf<Id, Iterator<BehaviorStatus>>()
fun onColonistSelectedTask(@Observes message: ColonistTaskSelected) {
val colonist = world.colonists[message.colonistId]!!
if (message.taskId == null) {
behavior.remove(message.colonistId)
} else {
val selectedTask = world.tasks[message.taskId]!!
behavior[colonist.id] = selectedTask.details.behavior.execute(world, colonist).iterator()
}
}
fun onUpdate(@Observes update: Update) {
behavior.entries.map { (colonistId, behavior) ->
if (behavior.hasNext()) {
val taskId = world.colonists[colonistId]!!.assignedTask
val status = behavior.next()
when (status) {
SUCCESS -> {
if (taskId != null) {
world.completeTask(colonistId, taskId, update.cause)
}
}
FAILURE -> {
if (taskId != null) {
world.rejectTask(colonistId, taskId, update.cause)
}
}
RUNNING -> {
}
}
}
}
}
}
| src/main/kotlin/com/fracturedskies/task/TaskExecutionSystem.kt | 1218205387 |
/*
* Copyright (c) 2018.
*
* 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 nl.adaptivity.xml
import nl.adaptivity.io.Writable
import nl.adaptivity.xmlutil.IterableNamespaceContext
import nl.adaptivity.xmlutil.Namespace
import nl.adaptivity.xmlutil.XmlWriter
import nl.adaptivity.xmlutil.util.CompactFragment
import nl.adaptivity.xmlutil.util.ICompactFragment
import nl.adaptivity.xmlutil.util.XMLFragmentStreamReader
import java.io.IOException
import java.io.Writer
/**
* Created by pdvrieze on 27/11/15.
*/
actual class WritableCompactFragment private actual constructor(
private val data: ICompactFragment,
dummy: Boolean
) : ICompactFragment, Writable {
override val isEmpty: Boolean
get() = data.isEmpty
override val namespaces: IterableNamespaceContext
get() = data.namespaces
override val content: CharArray
get() = data.content
override val contentString: String
get() = data.contentString
actual constructor(namespaces: Iterable<Namespace>, content: CharArray) : this(
CompactFragment(namespaces, content),
false
)
actual constructor(string: String) : this(CompactFragment(string), false) {}
actual constructor(orig: ICompactFragment) : this(CompactFragment(orig.namespaces, orig.contentString), false) {}
override fun getXmlReader() = XMLFragmentStreamReader.from(this)
@Throws(IOException::class)
override fun writeTo(destination: Writer) {
destination.write(content)
}
override fun serialize(out: XmlWriter) {
data.serialize(out)
}
}
| PE-common/src/javaMain/kotlin/nl/adaptivity/xml/WritableCompactFragment.kt | 2379266559 |
package de.westnordost.streetcomplete.quests.bus_stop_shelter
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.quests.AbstractQuestAnswerFragment
import de.westnordost.streetcomplete.quests.AnswerItem
import de.westnordost.streetcomplete.quests.bus_stop_shelter.BusStopShelterAnswer.*
class AddBusStopShelterForm : AbstractQuestAnswerFragment<BusStopShelterAnswer>() {
override val buttonPanelAnswers = listOf(
AnswerItem(R.string.quest_generic_hasFeature_no) { applyAnswer(NO_SHELTER) },
AnswerItem(R.string.quest_generic_hasFeature_yes) { applyAnswer(SHELTER) }
)
override val otherAnswers = listOf(
AnswerItem(R.string.quest_busStopShelter_covered) { applyAnswer(COVERED) }
)
}
| app/src/main/java/de/westnordost/streetcomplete/quests/bus_stop_shelter/AddBusStopShelterForm.kt | 3886870556 |
/*
* Copyright (c) 2019 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.optimizedforchromeos
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
| start/src/test/java/com/google/sample/optimizedforchromeos/ExampleUnitTest.kt | 4280257609 |
package com.henorek.discharge
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Pointcut
@Aspect class HandlerAspect {
@Pointcut("execution(@com.henorek.discharge.HandleException * *(..))")
private fun methodAnnotatedWithHandleException() {}
@Around("methodAnnotatedWithHandleException()")
@Throws(Throwable::class)
fun proceedToHandler(joinPoint: ProceedingJoinPoint) {
try {
joinPoint.proceed()
} catch (exception: Exception) {
val exceptionClass = exception.javaClass
if (Discharge.isSolvable(exceptionClass)) {
Discharge.takeSolution(exceptionClass).solve()
} else throw RuntimeException(exception)
}
}
}
| library/src/main/java/com/henorek/discharge/HandlerAspect.kt | 4091122117 |
package org.wordpress.android.fluxc.store.stats.time
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.stats.LimitMode.Top
import org.wordpress.android.fluxc.model.stats.time.TimeStatsMapper
import org.wordpress.android.fluxc.network.rest.wpcom.stats.time.ClicksRestClient
import org.wordpress.android.fluxc.network.utils.StatsGranularity
import org.wordpress.android.fluxc.persistence.TimeStatsSqlUtils.ClicksSqlUtils
import org.wordpress.android.fluxc.store.StatsStore.OnStatsFetched
import org.wordpress.android.fluxc.store.StatsStore.StatsError
import org.wordpress.android.fluxc.store.StatsStore.StatsErrorType.INVALID_RESPONSE
import org.wordpress.android.fluxc.tools.CoroutineEngine
import org.wordpress.android.util.AppLog.T.STATS
import java.util.Date
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ClicksStore
@Inject constructor(
private val restClient: ClicksRestClient,
private val sqlUtils: ClicksSqlUtils,
private val timeStatsMapper: TimeStatsMapper,
private val coroutineEngine: CoroutineEngine
) {
suspend fun fetchClicks(
site: SiteModel,
granularity: StatsGranularity,
limitMode: Top,
date: Date,
forced: Boolean = false
) = coroutineEngine.withDefaultContext(STATS, this, "fetchClicks") {
if (!forced && sqlUtils.hasFreshRequest(site, granularity, date, limitMode.limit)) {
return@withDefaultContext OnStatsFetched(getClicks(site, granularity, limitMode, date), cached = true)
}
val payload = restClient.fetchClicks(site, granularity, date, limitMode.limit + 1, forced)
return@withDefaultContext when {
payload.isError -> OnStatsFetched(payload.error)
payload.response != null -> {
sqlUtils.insert(site, payload.response, granularity, date, limitMode.limit)
OnStatsFetched(timeStatsMapper.map(payload.response, limitMode))
}
else -> OnStatsFetched(StatsError(INVALID_RESPONSE))
}
}
fun getClicks(site: SiteModel, period: StatsGranularity, limitMode: Top, date: Date) =
coroutineEngine.run(STATS, this, "getClicks") {
sqlUtils.select(site, period, date)?.let { timeStatsMapper.map(it, limitMode) }
}
}
| fluxc/src/main/java/org/wordpress/android/fluxc/store/stats/time/ClicksStore.kt | 3306056195 |
/*
* 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.data
import org.lanternpowered.api.util.optional.orNull
import org.spongepowered.api.data.DataHolder
import org.spongepowered.api.data.Key
import org.spongepowered.api.data.value.Value
import kotlin.reflect.KProperty
internal open class OptionalKeyElementProperty<V : Value<E>, E : Any, H : DataHolder>(val key: Key<V>) : DataHolderProperty<H, E?> {
override fun getValue(thisRef: H, property: KProperty<*>) = thisRef[this.key].orNull()
}
| src/main/kotlin/org/lanternpowered/server/data/OptionalKeyElementProperty.kt | 942412569 |
/*
* 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.network.vanilla.packet.handler.login
import com.google.gson.Gson
import com.google.gson.JsonObject
import org.lanternpowered.api.cause.causeOf
import org.lanternpowered.api.event.EventManager
import org.lanternpowered.api.text.translatableTextOf
import org.lanternpowered.server.event.LanternEventFactory
import org.lanternpowered.server.network.NetworkContext
import org.lanternpowered.server.network.NetworkSession
import org.lanternpowered.server.network.WrappedServerSideConnection
import org.lanternpowered.server.network.packet.PacketHandler
import org.lanternpowered.server.network.pipeline.PacketEncryptionHandler
import org.lanternpowered.server.network.vanilla.packet.type.login.LoginEncryptionResponsePacket
import org.lanternpowered.server.network.vanilla.packet.type.login.LoginFinishPacket
import org.lanternpowered.server.profile.LanternGameProfile
import org.lanternpowered.server.profile.LanternProfileProperty
import org.lanternpowered.server.util.EncryptionHelper
import org.lanternpowered.server.util.InetAddressHelper
import org.lanternpowered.server.util.UUIDHelper
import org.lanternpowered.server.util.future.thenAsync
import org.lanternpowered.server.util.gson.fromJson
import java.io.UnsupportedEncodingException
import java.net.URLEncoder
import java.util.concurrent.CompletableFuture
import javax.crypto.spec.SecretKeySpec
object LoginEncryptionResponseHandler : PacketHandler<LoginEncryptionResponsePacket> {
private const val authBaseUrl = "https://sessionserver.mojang.com/session/minecraft/hasJoined"
private val gson = Gson()
override fun handle(ctx: NetworkContext, packet: LoginEncryptionResponsePacket) {
val session = ctx.session
val keyPair = session.server.keyPair
val authData: LoginAuthData? = ctx.channel.attr(LoginStartHandler.AUTH_DATA).getAndSet(null)
checkNotNull(authData) { "No login auth data." }
val decryptedVerifyToken = EncryptionHelper.decryptRsa(keyPair, packet.verifyToken)
check(!(decryptedVerifyToken contentEquals authData.verifyToken)) { "Invalid verify token." }
val decryptedSharedSecret = EncryptionHelper.decryptRsa(keyPair, packet.sharedSecret)
val serverId = EncryptionHelper.generateServerId(decryptedSharedSecret, keyPair.public)
val preventProxiesIp = this.preventProxiesIp(ctx.session)
val secretKey = SecretKeySpec(decryptedSharedSecret, "AES")
val connection = WrappedServerSideConnection(ctx.session)
this.requestAuth(ctx, authData.username, serverId, preventProxiesIp)
.thenAsync(session.server.syncExecutor) { profile ->
val cause = causeOf(session, profile)
val originalMessage = translatableTextOf("multiplayer.disconnect.not_allowed_to_join")
val event = LanternEventFactory.createServerSideConnectionEventAuth(
cause, originalMessage, originalMessage, connection, false)
EventManager.post(event)
if (event.isCancelled) {
session.close(event.message)
null
} else profile
}
.thenAsync(ctx.channel.eventLoop()) { profile ->
if (profile == null)
return@thenAsync
ctx.channel.pipeline().replace(NetworkSession.ENCRYPTION, NetworkSession.ENCRYPTION,
PacketEncryptionHandler(secretKey))
session.packetReceived(LoginFinishPacket(profile))
}
}
private fun preventProxiesIp(session: NetworkSession): String? {
if (!session.server.config.server.preventProxyConnections)
return null
val address = session.address.address
// Ignore local addresses, they will always fail
if (InetAddressHelper.isLocalAddress(address))
return null
return try {
URLEncoder.encode(address.hostAddress, Charsets.UTF_8)
} catch (e: UnsupportedEncodingException) {
throw IllegalStateException("Failed to encode the ip address to prevent proxies.", e)
}
}
private fun requestAuth(
context: NetworkContext, username: String, serverId: String, preventProxiesIp: String?
): CompletableFuture<LanternGameProfile> {
var url = "$authBaseUrl?username=$username&serverId=$serverId"
if (preventProxiesIp != null)
url += "?ip=$preventProxiesIp"
return context.server.httpClient.get(url, context.channel.eventLoop()).thenApply { response ->
if (response.body.isEmpty())
throw IllegalStateException("Invalid username or session id.")
val json = try {
gson.fromJson<JsonObject>(response.body)
} catch (e: Exception) {
throw IllegalStateException("Username $username failed to authenticate.")
}
val name = json["name"].asString
val id = json["id"].asString
val uniqueId = UUIDHelper.parseFlatStringOrNull(id) ?: error("Received an invalid uuid: $id")
val properties = LanternProfileProperty.createPropertiesMapFromJson(
json.getAsJsonArray("properties"))
LanternGameProfile(uniqueId, name, properties)
}
}
}
| src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/handler/login/LoginEncryptionResponseHandler.kt | 2585784966 |
/*
* 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>.
*/
/*
* Copyright (c) 2011-2014 Glowstone - Tad Hardesty
* Copyright (c) 2010-2011 Lightstone - Graham Edgecombe
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.lanternpowered.server.network.pipeline
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.ByteToMessageCodec
import io.netty.handler.codec.DecoderException
import org.lanternpowered.server.network.buffer.LanternByteBuffer
class PacketFramingHandler : ByteToMessageCodec<ByteBuf>() {
override fun encode(ctx: ChannelHandlerContext, buf: ByteBuf, output: ByteBuf) {
LanternByteBuffer.writeVarInt(output, buf.readableBytes())
output.writeBytes(buf)
}
override fun decode(ctx: ChannelHandlerContext, buf: ByteBuf, output: MutableList<Any>) {
while (true) {
val length = readableMessage(buf)
if (length == -1)
break
output.add(buf.readRetainedSlice(length))
}
}
/**
* Reads the length and checks if the message can be read in one call.
*
* @param buf The byte buffer
* @return The message length, or -1 if it's not possible to read a message
*/
private fun readableMessage(buf: ByteBuf): Int {
val index = buf.readerIndex()
var bits = 0
var length = 0
var b: Byte
do {
// The variable integer is not complete, try again next time
if (buf.readableBytes() < 1) {
buf.readerIndex(index)
return -1
}
b = buf.readByte()
length = length or (b.toInt() and 0x7F shl bits)
bits += 7
if (bits > 35)
throw DecoderException("Variable length is too long!")
} while (b.toInt() and 0x80 != 0)
if (length < 0)
throw DecoderException("Message length cannot be negative: $length")
// Not all the message bytes are available yet, try again later
if (buf.readableBytes() < length) {
buf.readerIndex(index)
return -1
}
return length
}
}
| src/main/kotlin/org/lanternpowered/server/network/pipeline/PacketFramingHandler.kt | 3738978435 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.service.pagination
import org.lanternpowered.api.Lantern
import org.lanternpowered.api.audience.Audience
import org.lanternpowered.api.entity.player.Player
import org.lanternpowered.api.text.Text
import org.lanternpowered.api.text.format.NamedTextColor
import org.lanternpowered.api.util.optional.asOptional
import org.lanternpowered.api.util.optional.orNull
import org.lanternpowered.server.util.reference.asProvider
import org.spongepowered.api.command.exception.CommandException
import org.spongepowered.api.service.pagination.PaginationList
import java.lang.ref.WeakReference
import java.util.Optional
internal class LanternPaginationList(
private val service: LanternPaginationService,
private val contents: Iterable<Text>,
private val title: Text?,
private val header: Text?,
private val footer: Text?,
private val paginationSpacer: Text,
private val linesPerPage: Int
) : PaginationList {
override fun getContents(): Iterable<Text> = this.contents
override fun getTitle(): Optional<Text> = this.title.asOptional()
override fun getHeader(): Optional<Text> = this.header.asOptional()
override fun getFooter(): Optional<Text> = this.footer.asOptional()
override fun getPadding(): Text = this.paginationSpacer
override fun getLinesPerPage(): Int = this.linesPerPage
override fun sendTo(receiver: Audience, page: Int) {
val calculator = PaginationCalculator(this.linesPerPage)
val counts = this.contents
.map { input -> input to calculator.getLines(input) }
var title: Text? = this.title
if (title != null)
title = calculator.center(title, this.paginationSpacer)
val source: () -> Audience? = if (receiver is Player) {
val uniqueId = receiver.uniqueId
{ Lantern.server.getPlayer(uniqueId).orNull() }
} else {
WeakReference(receiver).asProvider()
}
val pagination = if (this.contents is List<*>) {
ListPagination(source, calculator, counts, title,
this.header, this.footer, this.paginationSpacer)
} else {
IterablePagination(source, calculator, counts, title,
this.header, this.footer, this.paginationSpacer)
}
this.service.getPaginationState(receiver, true)!!.put(pagination)
try {
pagination.specificPage(page)
} catch (e: CommandException) {
val text = e.text
if (text != null)
receiver.sendMessage(text.color(NamedTextColor.RED))
}
}
}
| src/main/kotlin/org/lanternpowered/server/service/pagination/LanternPaginationList.kt | 2606977794 |
/*
* Copyright (C) 2018 Tobias Raatiniemi
*
* 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, version 2 of the License.
*
* 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 me.raatiniemi.worker.domain.util
import me.raatiniemi.worker.domain.model.HoursMinutes
import java.util.*
/**
* Format a time interval into hours with fraction, i.e. 1.5 for one hour and 30 minutes.
*/
class FractionIntervalFormat : DateIntervalFormat, HoursMinutesFormat {
override fun format(milliseconds: Long): String {
val hoursMinutes = CalculateTime.calculateHoursMinutes(milliseconds)
return apply(hoursMinutes)
}
override fun apply(hoursMinutes: HoursMinutes): String {
return String.format(
Locale.forLanguageTag("en_US"),
FRACTION_FORMAT,
calculateHoursWithFraction(hoursMinutes)
)
}
companion object {
private const val FRACTION_FORMAT = "%.2f"
private const val MINUTES_IN_HOUR = 60f
private fun calculateHoursWithFraction(hoursMinutes: HoursMinutes): Float {
return hoursMinutes.hours + calculateFraction(hoursMinutes.minutes)
}
private fun calculateFraction(minutes: Long): Float {
return minutes.toFloat() / MINUTES_IN_HOUR
}
}
}
| core/src/main/java/me/raatiniemi/worker/domain/util/FractionIntervalFormat.kt | 1562303179 |
// Copyright 2020 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.integration.common
import java.time.Duration
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestRule
import org.wfanet.measurement.api.v2alpha.AccountsGrpcKt.AccountsCoroutineStub as PublicAccountsCoroutineStub
import org.wfanet.measurement.api.v2alpha.ApiKeysGrpcKt.ApiKeysCoroutineStub as PublicApiKeysCoroutineStub
import org.wfanet.measurement.api.v2alpha.CertificatesGrpcKt.CertificatesCoroutineStub as PublicCertificatesCoroutineStub
import org.wfanet.measurement.api.v2alpha.DataProvidersGrpcKt.DataProvidersCoroutineStub as PublicDataProvidersCoroutineStub
import org.wfanet.measurement.api.v2alpha.EventGroup
import org.wfanet.measurement.api.v2alpha.EventGroupsGrpcKt.EventGroupsCoroutineStub as PublicEventGroupsCoroutineStub
import org.wfanet.measurement.api.v2alpha.MeasurementConsumersGrpcKt.MeasurementConsumersCoroutineStub as PublicMeasurementConsumersCoroutineStub
import org.wfanet.measurement.api.v2alpha.MeasurementsGrpcKt.MeasurementsCoroutineStub as PublicMeasurementsCoroutineStub
import org.wfanet.measurement.api.v2alpha.RequisitionsGrpcKt.RequisitionsCoroutineStub as PublicRequisitionsCoroutineStub
import org.wfanet.measurement.api.v2alpha.differentialPrivacyParams
import org.wfanet.measurement.common.identity.DuchyInfo
import org.wfanet.measurement.common.testing.ProviderRule
import org.wfanet.measurement.common.testing.chainRulesSequentially
import org.wfanet.measurement.kingdom.deploy.common.DuchyIds
import org.wfanet.measurement.kingdom.deploy.common.Llv2ProtocolConfig
import org.wfanet.measurement.kingdom.deploy.common.service.DataServices
import org.wfanet.measurement.loadtest.frontend.FrontendSimulator
import org.wfanet.measurement.loadtest.frontend.MeasurementConsumerData
import org.wfanet.measurement.loadtest.resourcesetup.DuchyCert
import org.wfanet.measurement.loadtest.resourcesetup.EntityContent
import org.wfanet.measurement.loadtest.resourcesetup.ResourceSetup
import org.wfanet.measurement.loadtest.storage.SketchStore
import org.wfanet.measurement.storage.StorageClient
private val OUTPUT_DP_PARAMS = differentialPrivacyParams {
epsilon = 1.0
delta = 1.0
}
private const val REDIRECT_URI = "https://localhost:2048"
private val RESULT_POLLING_DELAY = Duration.ofSeconds(10)
private const val ALLOW_MPC_PROTOCOLS_FOR_SINGLE_DATA_PROVIDER = true
/**
* Test that everything is wired up properly.
*
* This is abstract so that different implementations of dependencies can all run the same tests
* easily.
*/
abstract class InProcessLifeOfAMeasurementIntegrationTest {
abstract val kingdomDataServicesRule: ProviderRule<DataServices>
/** Provides a function from Duchy to the dependencies needed to start the Duchy to the test. */
abstract val duchyDependenciesRule: ProviderRule<(String) -> InProcessDuchy.DuchyDependencies>
abstract val storageClient: StorageClient
private val kingdomDataServices: DataServices
get() = kingdomDataServicesRule.value
private val kingdom: InProcessKingdom =
InProcessKingdom(
dataServicesProvider = { kingdomDataServices },
verboseGrpcLogging = false,
REDIRECT_URI,
ALLOW_MPC_PROTOCOLS_FOR_SINGLE_DATA_PROVIDER
)
private val duchies: List<InProcessDuchy> by lazy {
ALL_DUCHY_NAMES.map {
InProcessDuchy(
externalDuchyId = it,
kingdomSystemApiChannel = kingdom.systemApiChannel,
duchyDependenciesProvider = { duchyDependenciesRule.value(it) },
verboseGrpcLogging = false,
)
}
}
private val edpSimulators: List<InProcessEdpSimulator> by lazy {
edpDisplayNameToResourceNameMap.map { (displayName, resourceName) ->
InProcessEdpSimulator(
displayName = displayName,
resourceName = resourceName,
mcResourceName = mcResourceName,
storageClient = storageClient,
kingdomPublicApiChannel = kingdom.publicApiChannel,
duchyPublicApiChannel = duchies[1].publicApiChannel,
eventTemplateNames = EVENT_TEMPLATES_TO_FILTERS_MAP.keys.toList(),
)
}
}
@get:Rule
val ruleChain: TestRule by lazy {
chainRulesSequentially(
kingdomDataServicesRule,
kingdom,
duchyDependenciesRule,
*duchies.toTypedArray()
)
}
private val publicMeasurementsClient by lazy {
PublicMeasurementsCoroutineStub(kingdom.publicApiChannel)
}
private val publicMeasurementConsumersClient by lazy {
PublicMeasurementConsumersCoroutineStub(kingdom.publicApiChannel)
}
private val publicCertificatesClient by lazy {
PublicCertificatesCoroutineStub(kingdom.publicApiChannel)
}
private val publicEventGroupsClient by lazy {
PublicEventGroupsCoroutineStub(kingdom.publicApiChannel)
}
private val publicDataProvidersClient by lazy {
PublicDataProvidersCoroutineStub(kingdom.publicApiChannel)
}
private val publicRequisitionsClient by lazy {
PublicRequisitionsCoroutineStub(kingdom.publicApiChannel)
}
private val publicAccountsClient by lazy { PublicAccountsCoroutineStub(kingdom.publicApiChannel) }
private val publicApiKeysClient by lazy { PublicApiKeysCoroutineStub(kingdom.publicApiChannel) }
private lateinit var mcResourceName: String
private lateinit var apiAuthenticationKey: String
private lateinit var edpDisplayNameToResourceNameMap: Map<String, String>
private lateinit var duchyCertMap: Map<String, String>
private lateinit var frontendSimulator: FrontendSimulator
private lateinit var eventGroups: List<EventGroup>
private suspend fun createAllResources() {
val resourceSetup =
ResourceSetup(
internalAccountsClient = kingdom.internalAccountsClient,
internalDataProvidersClient = kingdom.internalDataProvidersClient,
accountsClient = publicAccountsClient,
apiKeysClient = publicApiKeysClient,
internalCertificatesClient = kingdom.internalCertificatesClient,
measurementConsumersClient = publicMeasurementConsumersClient,
runId = "12345"
)
// Create the MC.
val (measurementConsumer, apiKey) =
resourceSetup.createMeasurementConsumer(
MC_ENTITY_CONTENT,
resourceSetup.createAccountWithRetries()
)
mcResourceName = measurementConsumer.name
apiAuthenticationKey = apiKey
// Create all EDPs
edpDisplayNameToResourceNameMap =
ALL_EDP_DISPLAY_NAMES.associateWith {
val edp = createEntityContent(it)
resourceSetup.createInternalDataProvider(edp)
}
// Create all duchy certificates.
duchyCertMap =
ALL_DUCHY_NAMES.associateWith {
resourceSetup
.createDuchyCertificate(DuchyCert(it, loadTestCertDerFile("${it}_cs_cert.der")))
.name
}
frontendSimulator =
FrontendSimulator(
MeasurementConsumerData(
mcResourceName,
MC_ENTITY_CONTENT.signingKey,
loadEncryptionPrivateKey("${MC_DISPLAY_NAME}_enc_private.tink"),
apiAuthenticationKey
),
OUTPUT_DP_PARAMS,
publicDataProvidersClient,
publicEventGroupsClient,
publicMeasurementsClient,
publicRequisitionsClient,
publicMeasurementConsumersClient,
publicCertificatesClient,
SketchStore(storageClient),
RESULT_POLLING_DELAY,
EVENT_TEMPLATES_TO_FILTERS_MAP,
)
}
@Before
fun startDaemons() = runBlocking {
// Create all resources
createAllResources()
eventGroups = edpSimulators.map { it.createEventGroup() }
// Start daemons. Mills and EDP simulators can only be started after resources have been
// created.
duchies.forEach {
it.startHerald()
it.startLiquidLegionsV2mill(duchyCertMap)
}
edpSimulators.forEach { it.start() }
}
@After fun stopEdpSimulators() = runBlocking { edpSimulators.forEach { it.stop() } }
@After
fun stopDuchyDaemons() = runBlocking {
for (duchy in duchies) {
duchy.stopHerald()
duchy.stopLiquidLegionsV2Mill()
}
}
@Test
fun `create a RF measurement and check the result is equal to the expected result`() =
runBlocking {
// Use frontend simulator to create a reach and frequency measurement and verify its result.
frontendSimulator.executeReachAndFrequency("1234")
}
@Test
fun `create a direct RF measurement and check the result is equal to the expected result`() =
runBlocking {
// Use frontend simulator to create a direct reach and frequency measurement and verify its
// result.
frontendSimulator.executeDirectReachAndFrequency("1234")
}
@Test
fun `create a reach-only measurement and check the result is equal to the expected result`() =
runBlocking {
// Use frontend simulator to create a reach and frequency measurement and verify its result.
frontendSimulator.executeReachOnly("1234")
}
@Test
fun `create an impression measurement and check the result is equal to the expected result`() =
runBlocking {
// Use frontend simulator to create an impression measurement and verify its result.
frontendSimulator.executeImpression("1234")
}
@Test
fun `create a duration measurement and check the result is equal to the expected result`() =
runBlocking {
// Use frontend simulator to create a duration measurement and verify its result.
frontendSimulator.executeDuration("1234")
}
@Test
fun `create a RF measurement of invalid params and check the result contains error info`() =
runBlocking {
// Use frontend simulator to create an invalid reach and frequency measurement and verify
// its error info.
frontendSimulator.executeInvalidReachAndFrequency("1234")
}
companion object {
private val MC_ENTITY_CONTENT: EntityContent = createEntityContent(MC_DISPLAY_NAME)
@BeforeClass
@JvmStatic
fun initConfig() {
DuchyIds.setForTest(ALL_DUCHY_NAMES)
Llv2ProtocolConfig.setForTest(
LLV2_PROTOCOL_CONFIG_CONFIG.protocolConfig,
LLV2_PROTOCOL_CONFIG_CONFIG.duchyProtocolConfig
)
DuchyInfo.setForTest(ALL_DUCHY_NAMES.toSet())
}
}
}
| src/main/kotlin/org/wfanet/measurement/integration/common/InProcessLifeOfAMeasurementIntegrationTest.kt | 2746631250 |
package com.mercadopago.android.px.internal.features.payment_result.remedies
import android.os.Parcel
import android.os.Parcelable
import com.mercadopago.android.px.internal.features.payment_result.remedies.view.RetryPaymentFragment
import com.mercadopago.android.px.internal.features.payment_result.remedies.view.HighRiskRemedy
import com.mercadopago.android.px.internal.viewmodel.PaymentResultType
internal data class RemediesModel(val title: String, val retryPayment: RetryPaymentFragment.Model?,
val highRisk: HighRiskRemedy.Model?, val trackingData: Map<String, String>?) : Parcelable {
constructor(parcel: Parcel) : this(parcel.readString()!!,
parcel.readParcelable(RetryPaymentFragment.Model::class.java.classLoader),
parcel.readParcelable(HighRiskRemedy.Model::class.java.classLoader),
HashMap()) {
parcel.readMap(trackingData, String::class.java.classLoader)
}
fun hasRemedies() = retryPayment != null || highRisk != null
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(title)
parcel.writeParcelable(retryPayment, flags)
parcel.writeParcelable(highRisk, flags)
parcel.writeMap(trackingData)
}
override fun describeContents() = 0
companion object {
@JvmField val DECORATOR = PaymentResultType.PENDING
@JvmField val CREATOR = object : Parcelable.Creator<RemediesModel> {
override fun createFromParcel(parcel: Parcel) = RemediesModel(parcel)
override fun newArray(size: Int) = arrayOfNulls<RemediesModel?>(size)
}
}
} | px-checkout/src/main/java/com/mercadopago/android/px/internal/features/payment_result/remedies/RemediesModel.kt | 4012306682 |
/*
* Copyright 2016 Burke Choi All rights reserved.
* http://www.sarangnamu.net
*
* 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("NOTHING_TO_INLINE", "unused")
package net.sarangnamu.common
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.RelativeLayout
/**
* Created by <a href="mailto:[email protected]">Burke Choi</a> on 2017. 9. 28.. <p/>
*/
// LinearLayout
inline fun LinearLayout.lp(w: Int, h: Int) {
layoutParams = LinearLayout.LayoutParams(w, h)
}
inline fun LinearLayout.lpmm() {
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
}
inline fun LinearLayout.lpwm() {
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)
}
inline fun LinearLayout.lpmw() {
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
}
inline fun LinearLayout.lpww() {
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
}
// RelativeLayout
inline fun RelativeLayout.lp(w: Int, h: Int) {
layoutParams = RelativeLayout.LayoutParams(w, h)
}
inline fun RelativeLayout.lpmm() {
layoutParams = RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)
}
inline fun RelativeLayout.lpwm() {
layoutParams = RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT)
}
inline fun RelativeLayout.lpmw() {
layoutParams = RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
}
inline fun RelativeLayout.lpww() {
layoutParams = RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
}
// FrameLayout
inline fun FrameLayout.lp(w: Int, h: Int) {
layoutParams = FrameLayout.LayoutParams(w, h)
}
inline fun FrameLayout.lpmm() {
layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
}
inline fun FrameLayout.lpwm() {
layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT)
}
inline fun FrameLayout.lpmw() {
layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)
}
inline fun FrameLayout.lpww() {
layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT)
}
// ViewGroup
inline fun ViewGroup.lp(w: Int, h: Int) {
layoutParams = ViewGroup.LayoutParams(w, h)
}
inline fun ViewGroup.lpmm() {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
inline fun ViewGroup.lpwm() {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
inline fun ViewGroup.lpmw() {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
inline fun ViewGroup.lpww() {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
// Window
inline fun Window.lp(w: Int, h: Int) {
val lp = attributes
lp.width = w
lp.height = h
attributes = lp
}
inline fun Window.lpmm() {
attributes = WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT)
}
inline fun Window.lpwm() {
attributes = WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.MATCH_PARENT)
}
inline fun Window.lpmw() {
attributes = WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT)
}
inline fun Window.lpww() {
attributes = WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT)
} | library/src/main/java/net/sarangnamu/common/BkLayoutParams.kt | 260185734 |
package org.kwicket.wicket.extensions.markup.html.form
import org.apache.wicket.behavior.Behavior
import org.apache.wicket.extensions.markup.html.form.DateTextField
import org.apache.wicket.model.IModel
import org.kwicket.component.init
import org.kwicket.model.toDateModel
import java.time.LocalDate
/**
* [DateTextField] with named parameters and a [LocalDate] model.
*
* @param id Wicket component id
* @param model backing model for the component
* @param pattern the date pattern to use for parsing and rendering dates from and to strings
* @param outputMarkupId whether to output an id in the markup for the component
* @param outputMarkupPlaceholderTag whether to output a placeholder tag for the component if it is not initially
* visible
* @param visible whether the component is visible
* @param enabled whether the component is enabled
* @param escapeModelStrings whether the value of the model should have HTML tags escaped
* @param renderBodyOnly whether the tag containing the component should not be rendered
* @param behaviors list of [Behavior]s to add to the component
*/
open class KDateTextField(
id: String,
model: IModel<LocalDate?>,
pattern: String,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
escapeModelStrings: Boolean? = null,
renderBodyOnly: Boolean? = null,
behaviors: List<Behavior>? = null
) : DateTextField(id, toDateModel(model), pattern) {
init {
init(
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
escapeModelStrings = escapeModelStrings,
renderBodyOnly = renderBodyOnly,
behaviors = behaviors
)
}
} | kwicket-wicket-extensions/src/main/kotlin/org/kwicket/wicket/extensions/markup/html/form/KDateTextField.kt | 1753790569 |
package org.kwicket.sample
import de.agilecoders.wicket.core.markup.html.themes.bootstrap.BootstrapTheme
import de.agilecoders.wicket.core.settings.SingleThemeProvider
import org.apache.wicket.Application
import org.apache.wicket.Component
import org.apache.wicket.RuntimeConfigurationType
import org.apache.wicket.ajax.AjaxRequestTarget
import org.apache.wicket.event.Broadcast
import org.apache.wicket.model.IModel
import org.apache.wicket.protocol.http.WebApplication
import org.apache.wicket.util.time.Duration
import org.kwicket.agilecoders.enableBootstrap
import org.kwicket.agilecoders.wicket.core.ajax.markup.html.bootstrap.common.KNotificationMessage
import org.kwicket.component.target
import org.kwicket.model.model
import org.kwicket.wicket.core.protocol.http.KWebApplication
import org.kwicket.wicket.core.protocol.http.KWicketFilter
import org.kwicket.wicket.spring.enableSpringIoC
import org.kwicket.wicketstuff.annotation.enableMountAnnotations
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.context.annotation.Bean
import java.util.*
@SpringBootApplication
class SampleApplication {
@Value("\${wicket.config}")
private lateinit var wicketConfig: RuntimeConfigurationType
@Bean
fun getWicketApp() = SampleWebApplication(configurationType = wicketConfig)
@Bean
fun getWicketFilter(app: WebApplication) = KWicketFilter(webApp = app, filterPath = "/")
@Bean
fun getCustomers() = mutableListOf(
Customer(
id = UUID.randomUUID(),
firstName = "Alice",
lastName = "Anderson",
address = Address(city = "Ann Arbor", country = Country.US)
),
Customer(
id = UUID.randomUUID(),
firstName = "Bob",
lastName = "Bo",
address = Address(city = "Beijing", country = Country.China)
)
)
}
class SampleWebApplication(configurationType: RuntimeConfigurationType) :
KWebApplication(configurationType = configurationType) {
override fun getHomePage() = ManageCustomersPage::class.java
override fun init() {
super.init()
enableMountAnnotations(scanPackages = listOf("org.kwicket.sample"))
enableBootstrap(themeProvider = SingleThemeProvider(BootstrapTheme()))
enableSpringIoC()
//componentOnConfigureListeners.add(AsyncModelLoaderOnConfigureListener())
}
}
fun main(args: Array<String>) {
SpringApplication.run(SampleApplication::class.java)
}
private val notificationDuration: Duration = Duration.seconds(4)
fun Component.success(msg: IModel<String>, target: AjaxRequestTarget? = null, vararg refresh: Component) {
this.feedback(feedback = {
success(
KNotificationMessage(
message = msg,
header = "Success!".model(),
hideAfter = notificationDuration
)
)
}, target = target, refresh = *refresh)
}
fun Component.info(msg: IModel<String>, target: AjaxRequestTarget? = null, vararg refresh: Component) {
this.feedback(feedback = {
info(
KNotificationMessage(
message = msg,
hideAfter = notificationDuration
)
)
}, target = target, refresh = *refresh)
}
private fun Component.feedback(feedback: () -> Unit, target: AjaxRequestTarget? = null, vararg refresh: Component) {
feedback()
val t = target(target)
if (refresh.isNotEmpty()) t.add(*refresh)
send(this, Broadcast.BUBBLE, HasFeedbackEvent(t))
} | kwicket-sample/src/main/kotlin/org/kwicket/sample/SampleApplication.kt | 3666838183 |
package com.pr0gramm.app.ui.intro.slides
import com.pr0gramm.app.feed.FeedFilter
import com.pr0gramm.app.orm.bookmarkOf
import com.pr0gramm.app.services.BookmarkService
/**
*/
internal class BookmarkActionItem(private val bookmarkService: BookmarkService, title: String,
private val filter: FeedFilter) : ActionItem(title) {
override fun enabled(): Boolean {
return bookmarkService.byTitle(title) != null
}
override fun activate() {
deactivate()
bookmarkService.save(bookmarkOf(title, filter))
}
override fun deactivate() {
// delete any existing bookmarks
bookmarkService.byTitle(title)?.let { bookmarkService.delete(it) }
bookmarkService.byFilter(filter)?.let { bookmarkService.delete(it) }
}
}
| app/src/main/java/com/pr0gramm/app/ui/intro/slides/BookmarkActionItem.kt | 164245107 |
package me.ykrank.s1next.view.fragment
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import android.view.View
import com.github.ykrank.androidtools.util.MathUtil
import com.github.ykrank.androidtools.widget.RxBus
import io.reactivex.Single
import me.ykrank.s1next.App
import me.ykrank.s1next.R
import me.ykrank.s1next.data.api.model.PmGroup
import me.ykrank.s1next.data.api.model.collection.PmGroups
import me.ykrank.s1next.data.api.model.wrapper.BaseDataWrapper
import me.ykrank.s1next.view.adapter.BaseRecyclerViewAdapter
import me.ykrank.s1next.view.adapter.PmGroupsRecyclerViewAdapter
import me.ykrank.s1next.view.event.NoticeRefreshEvent
import java.util.*
import javax.inject.Inject
class PmGroupsFragment : BaseLoadMoreRecycleViewFragment<BaseDataWrapper<PmGroups>>() {
private lateinit var mRecyclerAdapter: PmGroupsRecyclerViewAdapter
@Inject
internal lateinit var mRxBus: RxBus
override val recyclerViewAdapter: BaseRecyclerViewAdapter
get() = mRecyclerAdapter
override val isCardViewContainer: Boolean
get() = true
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
App.appComponent.inject(this)
super.onViewCreated(view, savedInstanceState)
leavePageMsg("PmGroupsFragment")
activity?.setTitle(R.string.pms)
val recyclerView = recyclerView
recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
mRecyclerAdapter = PmGroupsRecyclerViewAdapter(activity)
recyclerView.adapter = mRecyclerAdapter
}
override fun getPageSourceObservable(pageNum: Int): Single<BaseDataWrapper<PmGroups>> {
return mS1Service.getPmGroups(pageNum)
}
override fun onNext(data: BaseDataWrapper<PmGroups>) {
super.onNext(data)
val pmGroups = data.data
if (pmGroups.pmGroupList != null) {
mRecyclerAdapter.diffNewDataSet(pmGroups.pmGroupList!!, false)
// update total page
setTotalPages(MathUtil.divide(pmGroups.total, pmGroups.pmPerPage))
}
if (pageNum == 1) {
mRxBus.post(NoticeRefreshEvent::class.java, NoticeRefreshEvent(data.data.hasNew(), null))
}
}
override fun appendNewData(oldData: BaseDataWrapper<PmGroups>?, newData: BaseDataWrapper<PmGroups>): BaseDataWrapper<PmGroups> {
if (oldData != null) {
val oldPmGroups = oldData.data.pmGroupList
var newPmGroups: MutableList<PmGroup>? = newData.data.pmGroupList
if (newPmGroups == null) {
newPmGroups = ArrayList()
newData.data.pmGroupList = newPmGroups
}
if (oldPmGroups != null) {
newPmGroups.addAll(0, oldPmGroups)
}
}
return newData
}
companion object {
val TAG = PmGroupsFragment::class.java.name
fun newInstance(): PmGroupsFragment {
return PmGroupsFragment()
}
}
}
| app/src/main/java/me/ykrank/s1next/view/fragment/PmGroupsFragment.kt | 2671052081 |
package com.matchr
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.matchr", appContext.packageName)
}
}
| app/src/androidTest/java/com/matchr/ExampleInstrumentedTest.kt | 748694190 |
/*
* 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.jetbrains.python.breadcrumbs
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.impl.source.tree.LeafElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.xml.breadcrumbs.BreadcrumbsInfoProvider
import com.jetbrains.python.PyTokenTypes
import com.jetbrains.python.PythonLanguage
import com.jetbrains.python.psi.*
class PyBreadcrumbsInfoProvider : BreadcrumbsInfoProvider() {
companion object {
private val LANGUAGES = arrayOf(PythonLanguage.getInstance())
private val HELPERS = listOf<Helper<*>>(
LambdaHelper,
SimpleHelper(PyTryPart::class.java, "try"),
ExceptHelper,
SimpleHelper(PyFinallyPart::class.java, "finally"),
SimpleHelper(PyElsePart::class.java, "else"),
IfHelper,
ForHelper,
WhileHelper,
WithHelper,
ClassHelper,
FunctionHelper,
KeyValueHelper
)
}
override fun getLanguages() = LANGUAGES
override fun acceptElement(e: PsiElement) = getHelper(e) != null
override fun getParent(e: PsiElement): PsiElement? {
val default = e.parent
val currentOffset = currentOffset(e) ?: return default
if (!isElementToMoveBackward(e, currentOffset)) return default
val nonWhiteSpace = moveBackward(e, currentOffset) ?: return default
val psiFile = e.containingFile ?: return default
val document = PsiDocumentManager.getInstance(e.project).getDocument(psiFile) ?: return default
val sameLine = document.getLineNumber(nonWhiteSpace.textOffset) == document.getLineNumber(currentOffset)
return if (sameLine) nonWhiteSpace.parent else default
}
override fun getElementInfo(e: PsiElement) = getHelper(e)!!.elementInfo(e as PyElement)
override fun getElementTooltip(e: PsiElement) = getHelper(e)!!.elementTooltip(e as PyElement)
private fun getHelper(e: PsiElement): Helper<in PyElement>? {
if (e !is PyElement) return null
@Suppress("UNCHECKED_CAST")
return HELPERS.firstOrNull { it.type.isInstance(e) && (it as Helper<in PyElement>).accepts(e) } as Helper<in PyElement>?
}
private fun currentOffset(e: PsiElement): Int? {
val virtualFile = e.containingFile?.virtualFile ?: return null
val selectedEditor = FileEditorManager.getInstance(e.project).getSelectedEditor(virtualFile) as? TextEditor ?: return null
return selectedEditor.editor.caretModel.offset
}
private fun isElementToMoveBackward(e: PsiElement, currentOffset: Int): Boolean {
if (e is PsiWhiteSpace) return true
if (e !is LeafElement || e.startOffset < currentOffset) return false
val elementType = e.elementType
return elementType == PyTokenTypes.COMMA || elementType in PyTokenTypes.CLOSE_BRACES
}
private fun moveBackward(e: PsiElement, currentOffset: Int): PsiElement? {
var result = PsiTreeUtil.prevLeaf(e)
while (result != null && isElementToMoveBackward(result, currentOffset)) {
result = PsiTreeUtil.prevLeaf(result)
}
return result
}
private abstract class Helper<T : PyElement>(val type: Class<T>) {
abstract fun accepts(e: T): Boolean
abstract fun elementInfo(e: T): String
abstract fun elementTooltip(e: T): String
}
private abstract class AbstractHelper<T : PyElement>(type: Class<T>) : Helper<T>(type) {
override fun accepts(e: T): Boolean = true
override fun elementInfo(e: T): String = getTruncatedPresentation(e, 16)
override fun elementTooltip(e: T): String = getTruncatedPresentation(e, 96)
abstract fun getPresentation(e: T): String
private fun getTruncatedPresentation(e: T, maxLength: Int) = StringUtil.shortenTextWithEllipsis(getPresentation(e), maxLength, 0, true)
}
private class SimpleHelper<T : PyElement>(type: Class<T>, val representation: String) : AbstractHelper<T>(type) {
override fun getPresentation(e: T) = representation
}
private object LambdaHelper : AbstractHelper<PyLambdaExpression>(PyLambdaExpression::class.java) {
override fun getPresentation(e: PyLambdaExpression) = "lambda ${e.parameterList.getPresentableText(false)}"
}
private object ExceptHelper : AbstractHelper<PyExceptPart>(PyExceptPart::class.java) {
override fun getPresentation(e: PyExceptPart): String {
val exceptClass = e.exceptClass ?: return "except"
val target = e.target ?: return "except ${exceptClass.text}"
return "except ${exceptClass.text} as ${target.text}"
}
}
private object IfHelper : AbstractHelper<PyIfPart>(PyIfPart::class.java) {
override fun getPresentation(e: PyIfPart): String {
val prefix = if (e.isElif) "elif" else "if"
val condition = e.condition ?: return prefix
return "$prefix ${condition.text}"
}
}
private object ForHelper : AbstractHelper<PyForPart>(PyForPart::class.java) {
override fun getPresentation(e: PyForPart): String {
val parent = e.parent
val prefix = if (parent is PyForStatement && parent.isAsync) "async for" else "for"
val target = e.target ?: return prefix
val source = e.source ?: return prefix
return "$prefix ${target.text} in ${source.text}"
}
}
private object WhileHelper : AbstractHelper<PyWhilePart>(PyWhilePart::class.java) {
override fun getPresentation(e: PyWhilePart): String {
val condition = e.condition ?: return "while"
return "while ${condition.text}"
}
}
private object WithHelper : AbstractHelper<PyWithStatement>(PyWithStatement::class.java) {
override fun getPresentation(e: PyWithStatement): String {
val getItemPresentation = fun(item: PyWithItem): String? {
val expression = item.expression ?: return null
val target = item.target ?: return expression.text
return "${expression.text} as ${target.text}"
}
val prefix = if (e.isAsync) "async with " else "with "
return e.withItems
.orEmpty()
.asSequence()
.map(getItemPresentation)
.filterNotNull()
.joinToString(prefix = prefix)
}
}
private object ClassHelper : AbstractHelper<PyClass>(PyClass::class.java) {
override fun getPresentation(e: PyClass) = e.name ?: "class"
}
private object FunctionHelper : AbstractHelper<PyFunction>(PyFunction::class.java) {
override fun getPresentation(e: PyFunction): String {
val prefix = if (e.isAsync) "async " else ""
val name = e.name ?: return "function"
return "$prefix$name()"
}
}
private object KeyValueHelper : AbstractHelper<PyKeyValueExpression>(PyKeyValueExpression::class.java) {
override fun getPresentation(e: PyKeyValueExpression): String = e.key.text ?: "key"
}
}
| python/src/com/jetbrains/python/breadcrumbs/PyBreadcrumbsInfoProvider.kt | 114800357 |
package com.simplecity.amp_library.ui.dialog
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v4.app.FragmentManager
import android.support.v4.content.ContextCompat
import android.view.LayoutInflater
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.CheckBox
import android.widget.ProgressBar
import com.afollestad.aesthetic.Aesthetic
import com.afollestad.materialdialogs.MaterialDialog
import com.simplecity.amp_library.R
import com.simplecity.amp_library.utils.SettingsManager
import com.simplecity.amp_library.utils.ViewUtils
import dagger.android.support.AndroidSupportInjection
import javax.inject.Inject
class ChangelogDialog : DialogFragment() {
@Inject lateinit var settingsManager: SettingsManager
override fun onAttach(context: Context?) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
@SuppressLint("InflateParams")
val customView = LayoutInflater.from(context).inflate(R.layout.dialog_changelog, null)
val webView = customView.findViewById<WebView>(R.id.webView)
webView.setBackgroundColor(ContextCompat.getColor(context!!, android.R.color.transparent))
val checkBox = customView.findViewById<CheckBox>(R.id.checkbox)
checkBox.isChecked = settingsManager.showChangelogOnLaunch
checkBox.setOnCheckedChangeListener { buttonView, isChecked -> settingsManager.showChangelogOnLaunch = isChecked }
val progressBar = customView.findViewById<ProgressBar>(R.id.progress)
webView.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
ViewUtils.fadeOut(progressBar) { ViewUtils.fadeIn(webView, null) }
}
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
if (intent.resolveActivity(context!!.packageManager) != null) {
context?.startActivity(intent)
return true
}
return false
}
}
Aesthetic.get(context)
.isDark
.take(1)
.subscribe { isDark -> webView.loadUrl(if (isDark) "file:///android_asset/web/info_dark.html" else "file:///android_asset/web/info.html") }
return MaterialDialog.Builder(context!!)
.title(R.string.pref_title_changelog)
.customView(customView, false)
.negativeText(R.string.close)
.build()
}
fun show(fragmentManager: FragmentManager) {
show(fragmentManager, TAG)
}
companion object {
private const val TAG = "ChangelogDialog"
fun newInstance() = ChangelogDialog()
}
} | app/src/main/java/com/simplecity/amp_library/ui/dialog/ChangelogDialog.kt | 2106920436 |
package de.thm.arsnova.service.httpgateway.service
import de.thm.arsnova.service.httpgateway.config.HttpGatewayProperties
import de.thm.arsnova.service.httpgateway.model.Room
import org.slf4j.LoggerFactory
import org.springframework.core.ParameterizedTypeReference
import org.springframework.stereotype.Service
import org.springframework.web.reactive.function.client.WebClient
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import java.util.Optional
@Service
class RoomService(
private val webClient: WebClient,
private val httpGatewayProperties: HttpGatewayProperties
) {
private val logger = LoggerFactory.getLogger(javaClass)
fun get(roomId: String): Mono<Room> {
val url = "${httpGatewayProperties.httpClient.core}/room/$roomId"
logger.trace("Querying core for room with url: {}", url)
return webClient.get().uri(url)
.retrieve().bodyToMono(Room::class.java).cache()
.checkpoint("Request failed in ${this::class.simpleName}::get(roomId).")
.onErrorResume { exception ->
logger.debug("Error on getting room with id: {}", roomId, exception)
Mono.empty()
}
}
fun get(roomIds: List<String>): Flux<Optional<Room>> {
val path = "${httpGatewayProperties.httpClient.core}/room/"
val url = "$path?ids=${roomIds.joinToString(",")}&skipMissing=false"
logger.trace("Querying core for room with url: {}", url)
val typeRef: ParameterizedTypeReference<List<Room?>> = object : ParameterizedTypeReference<List<Room?>>() {}
return webClient.get().uri(url)
.retrieve().bodyToMono(typeRef).cache()
.checkpoint("Request failed in ${this::class.simpleName}::get(roomIds).")
.flatMapMany { roomList: List<Room?> ->
Flux.fromIterable(
roomList.map { entry ->
if (entry != null) {
Optional.of(Room(entry.id, entry.shortId, entry.name))
} else {
Optional.empty()
}
}
)
}
}
fun getByShortId(shortId: String): Mono<Room> {
val path = "${httpGatewayProperties.httpClient.core}/room/"
val url = "$path~$shortId"
logger.trace("Querying core for room by shortId with url: {}", url)
return webClient
.get()
.uri(url)
.retrieve()
.bodyToMono(Room::class.java)
.checkpoint("Request failed in ${this::class.simpleName}::${::getByShortId.name}.")
}
}
| gateway/src/main/kotlin/de/thm/arsnova/service/httpgateway/service/RoomService.kt | 508233023 |
package com.bravelocation.yeltzlandnew.tweet
import com.google.gson.annotations.SerializedName
import java.util.*
class QuotedTweet : DisplayTweet {
@SerializedName("id_str")
var id: String? = null
@SerializedName("full_text")
override var fullText: String? = null
@SerializedName("user")
override var user: User? = null
@SerializedName("created_at")
override var createdDate: Date? = null
@SerializedName("entities")
override var entities: Entities? = null
@SerializedName("extended_entities")
override var extendedEntities: ExtendedEntities? = null
@SerializedName("quoted_status")
var quotedTweet: QuotedTweet? = null
override val isRetweet: Boolean
get() = false
override fun quote(): QuotedTweet? {
return quotedTweet
}
override fun userTwitterUrl(): String {
return "https://twitter.com/" + user?.screenName
}
override fun bodyTwitterUrl(): String {
return "https://twitter.com/" + user?.screenName + "/status/" + id
}
} | app/src/main/java/com/bravelocation/yeltzlandnew/tweet/QuotedTweet.kt | 872109229 |
package org.wow.learning
import java.io.File
import org.wow.logger.GameTurn
import org.slf4j.LoggerFactory
import reactor.core.composable.spec.Promises
import reactor.core.composable.spec.Streams
import org.wow.logger.LogsParser
import reactor.core.Environment
import reactor.function.Consumer
import java.util.concurrent.TimeUnit
public class FileBasedLearner<T>(
val env: reactor.core.Environment,
val files: List<File>,
val parser: LogsParser,
val vectorizer: (List<GameTurn>) -> List<T>,
val timeoutMin: Long = 1000) {
private val logger = LoggerFactory.getLogger(javaClass<FileBasedLearner<T>>())!!
fun <B, K : Learner<T, B>> learn(data: K): K {
val doneDefer = Promises.defer<K>()!!.env(env)!!.get()!!
val completePromise = doneDefer.compose()
val complete = Consumer<K> { doneDefer.accept(it) }
val deferred = Streams.defer<File>()!!.env(env)!!.dispatcher(Environment.RING_BUFFER)!!.get();
deferred!!.compose()!!
.map { file ->
logger.debug("Parsing: " + file)
parser.parse(file!!) }!!
.map { game ->
vectorizer(game!!)}!!
.batch(files.size)!!
.reduce ({ (current) ->
current!!.getT1()!!.forEach { current.getT2()!!.learn(it) }; current.getT2()
}, data)!!
.consume(complete)!!
.`when`(javaClass<Exception>(), { ex ->
logger.error(ex.toString())})
files.forEach{ deferred.accept(it) }
return completePromise!!.await(timeoutMin, TimeUnit.MINUTES)!!
}
}
| src/main/kotlin/org/wow/learning/FileBasedLearner.kt | 882558671 |
package org.apollo.game.plugin.testing.junit.params
import org.apollo.cache.def.ItemDefinition
import org.apollo.cache.def.NpcDefinition
import org.apollo.cache.def.ObjectDefinition
import org.junit.jupiter.params.provider.ArgumentsSource
/**
* `@ItemDefinitionSource` is an [ArgumentsSource] for [ItemDefinition]s.
*
* @param sourceNames The names of the properties or functions annotated with `@ItemDefinitions` to use as sources of
* [ItemDefinition]s for the test with this annotation. Every property/function must return
* `Collection<ItemDefinition>`. If no [sourceNames] are provided, every property and function annotated with
* `@ItemDefinitions` (in this class's companion object) will be used.
*
* @see org.junit.jupiter.params.provider.ArgumentsSource
* @see org.junit.jupiter.params.ParameterizedTest
*/
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@ArgumentsSource(ItemDefinitionsProvider::class)
annotation class ItemDefinitionSource(vararg val sourceNames: String)
/**
* `@NpcDefinitionSource` is an [ArgumentsSource] for [NpcDefinition]s.
*
* @param sourceNames The names of the properties or functions annotated with `@NpcDefinitions` to use as sources of
* [NpcDefinition]s for the test with this annotation. Every property/function must return
* `Collection<NpcDefinition>`. If no [sourceNames] are provided, every property and function annotated with
* `@NpcDefinitions` (in this class's companion object) will be used.
*
* @see org.junit.jupiter.params.provider.ArgumentsSource
* @see org.junit.jupiter.params.ParameterizedTest
*/
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@ArgumentsSource(NpcDefinitionsProvider::class)
annotation class NpcDefinitionSource(vararg val sourceNames: String)
/**
* `@ObjectDefinitionSource` is an [ArgumentsSource] for [ObjectDefinition]s.
*
* @param sourceNames The names of the properties or functions annotated with `@ObjectDefinitions` to use as sources of
* [ObjectDefinition]s for the test with this annotation. Every property/function must return
* `Collection<ObjectDefinition>`. If no [sourceNames] are provided, every property and function annotated with
* `@ObjectDefinitions` (in this class's companion object) will be used.
*
* @see org.junit.jupiter.params.provider.ArgumentsSource
* @see org.junit.jupiter.params.ParameterizedTest
*/
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@ArgumentsSource(ObjectDefinitionsProvider::class)
annotation class ObjectDefinitionSource(vararg val sourceNames: String)
| game/plugin-testing/src/main/kotlin/org/apollo/game/plugin/testing/junit/params/DefinitionSource.kt | 2462456029 |
package com.jawnnypoo.geotune.util
import android.animation.Animator
import android.annotation.TargetApi
import android.view.View
import android.view.ViewAnimationUtils
import android.view.animation.AccelerateInterpolator
/**
* Animation stuff
*/
object AnimUtils {
private val mAccelerateInterpolator = AccelerateInterpolator()
@TargetApi(21)
fun circleReveal(v: View, centerX: Int, centerY: Int,
startRadius: Float, endRadius: Float, duration: Int): Animator {
val anim = ViewAnimationUtils.createCircularReveal(v, centerX, centerY, startRadius, endRadius)
anim.duration = duration.toLong()
anim.interpolator = mAccelerateInterpolator
anim.start()
return anim
}
}
| app/src/main/java/com/jawnnypoo/geotune/util/AnimUtils.kt | 3229780547 |
package io.gitlab.arturbosch.detekt.test
import io.gitlab.arturbosch.detekt.api.Finding
import io.gitlab.arturbosch.detekt.api.SourceLocation
import io.gitlab.arturbosch.detekt.api.TextLocation
import org.assertj.core.api.AbstractAssert
import org.assertj.core.api.AbstractListAssert
import org.assertj.core.util.CheckReturnValue
import java.util.Objects
@CheckReturnValue
fun assertThat(findings: List<Finding>) = FindingsAssert(findings)
@CheckReturnValue
fun assertThat(finding: Finding) = FindingAssert(finding)
fun List<Finding>.assert() = FindingsAssert(this)
class FindingsAssert(actual: List<Finding>) :
AbstractListAssert<FindingsAssert, List<Finding>,
Finding, FindingAssert>(actual, FindingsAssert::class.java) {
override fun newAbstractIterableAssert(iterable: MutableIterable<Finding>): FindingsAssert {
throw UnsupportedOperationException("not implemented")
}
override fun toAssert(value: Finding?, description: String?): FindingAssert =
FindingAssert(value).`as`(description)
fun hasSourceLocations(vararg expected: SourceLocation) = apply {
val actualSources = actual.asSequence()
.map { it.location.source }
.sortedWith(compareBy({ it.line }, { it.column }))
val expectedSources = expected.asSequence()
.sortedWith(compareBy({ it.line }, { it.column }))
if (!Objects.deepEquals(actualSources.toList(), expectedSources.toList())) {
failWithMessage(
"Expected source locations to be ${expectedSources.toList()} but was ${actualSources.toList()}"
)
}
}
fun hasSourceLocation(line: Int, column: Int) = apply {
hasSourceLocations(SourceLocation(line, column))
}
fun hasTextLocations(vararg expected: Pair<Int, Int>) = apply {
val actualSources = actual.asSequence()
.map { it.location.text }
.sortedWith(compareBy({ it.start }, { it.end }))
val expectedSources = expected.asSequence()
.map { (start, end) -> TextLocation(start, end) }
.sortedWith(compareBy({ it.start }, { it.end }))
if (!Objects.deepEquals(actualSources.toList(), expectedSources.toList())) {
failWithMessage(
"Expected text locations to be ${expectedSources.toList()} but was ${actualSources.toList()}"
)
}
}
fun hasTextLocations(vararg expected: String): FindingsAssert {
val finding = actual.firstOrNull()
if (finding == null) {
if (expected.isEmpty()) {
return this
} else {
failWithMessage("Expected ${expected.size} findings but was 0")
}
}
val code = requireNotNull(finding?.entity?.ktElement?.run { containingKtFile.text }) {
"Finding expected to provide a KtElement."
}
val textLocations = expected.map { snippet ->
val index = code.indexOf(snippet)
if (index < 0) {
failWithMessage("The snippet \"$snippet\" doesn't exist in the code")
} else {
if (code.indexOf(snippet, index + 1) >= 0) {
failWithMessage("The snippet \"$snippet\" appears multiple times in the code")
}
}
index to index + snippet.length
}.toTypedArray()
return hasTextLocations(*textLocations)
}
}
class FindingAssert(val actual: Finding?) : AbstractAssert<FindingAssert, Finding>(actual, FindingAssert::class.java) {
fun hasMessage(expectedMessage: String) = apply {
if (expectedMessage.isNotBlank() && actual.message.isBlank()) {
failWithMessage("Expected message <$expectedMessage> but finding has no message")
}
if (!actual.message.trim().equals(expectedMessage.trim(), ignoreCase = true)) {
failWithMessage("Expected message <$expectedMessage> but actual message was <${actual.message}>")
}
}
}
| detekt-test/src/main/kotlin/io/gitlab/arturbosch/detekt/test/FindingsAssertions.kt | 3064364246 |
/*
* 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 io.plaidapp.core.dagger
import android.content.Context
import android.content.SharedPreferences
import dagger.Module
import dagger.Provides
import io.plaidapp.core.dagger.scope.FeatureScope
/**
* Provide [SharedPreferences] to this app's components.
*/
@Module
open class SharedPreferencesModule(val context: Context, val name: String) {
@Provides
@FeatureScope
fun provideSharedPreferences(): SharedPreferences {
return context.applicationContext.getSharedPreferences(name, Context.MODE_PRIVATE)
}
}
| core/src/main/java/io/plaidapp/core/dagger/SharedPreferencesModule.kt | 516771194 |
/*
* Nextcloud Android client application
*
* @author Álvaro Brey
* Copyright (C) 2022 Álvaro Brey
* Copyright (C) 2022 Nextcloud GmbH
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.nextcloud.client.media
import android.content.Context
import android.content.DialogInterface
import android.view.View
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.PlaybackException
import com.google.android.exoplayer2.Player
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.owncloud.android.R
import com.owncloud.android.lib.common.utils.Log_OC
class ExoplayerListener(private val context: Context, private val playerView: View, private val exoPlayer: ExoPlayer) :
Player.Listener {
override fun onPlaybackStateChanged(playbackState: Int) {
super.onPlaybackStateChanged(playbackState)
if (playbackState == Player.STATE_ENDED) {
onCompletion()
}
}
override fun onIsPlayingChanged(isPlaying: Boolean) {
super.onIsPlayingChanged(isPlaying)
Log_OC.d(TAG, "Exoplayer keep screen on: $isPlaying")
playerView.keepScreenOn = isPlaying
}
private fun onCompletion() {
exoPlayer.let {
it.seekToDefaultPosition()
it.pause()
}
}
override fun onPlayerError(error: PlaybackException) {
super.onPlayerError(error)
Log_OC.e(TAG, "Exoplayer error", error)
val message = ErrorFormat.toString(context, error)
MaterialAlertDialogBuilder(context)
.setMessage(message)
.setPositiveButton(R.string.common_ok) { _: DialogInterface?, _: Int ->
onCompletion()
}
.setCancelable(false)
.show()
}
companion object {
private const val TAG = "ExoplayerListener"
}
}
| app/src/main/java/com/nextcloud/client/media/ExoplayerListener.kt | 2191248473 |
package treehou.se.habit.ui.control.cells.config
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.trello.rxlifecycle2.components.support.RxFragment
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import io.realm.Realm
import kotlinx.android.synthetic.main.inc_dec_controller_action.*
import se.treehou.ng.ohcommunicator.connector.models.OHItem
import treehou.se.habit.R
import treehou.se.habit.core.db.model.ItemDB
import treehou.se.habit.core.db.model.ServerDB
import treehou.se.habit.core.db.model.controller.CellDB
import treehou.se.habit.core.db.model.controller.IncDecCellDB
import treehou.se.habit.ui.util.IconPickerActivity
import treehou.se.habit.util.ConnectionFactory
import treehou.se.habit.util.Constants
import treehou.se.habit.util.Util
import treehou.se.habit.util.logging.Logger
import java.util.*
import javax.inject.Inject
class CellIncDecConfigFragment : RxFragment() {
@Inject lateinit var connectionFactory: ConnectionFactory
@Inject lateinit var logger: Logger
lateinit var realm: Realm
private var itemAdapter: ArrayAdapter<OHItem>? = null
private val items = ArrayList<OHItem>()
private var incDecCell: IncDecCellDB? = null
private var cell: CellDB? = null
private var item: OHItem? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Util.getApplicationComponent(this).inject(this)
realm = Realm.getDefaultInstance()
if (arguments != null) {
val id = arguments!!.getLong(ARG_CELL_ID)
cell = CellDB.load(realm, id)
incDecCell = cell!!.getCellIncDec()
if (incDecCell == null) {
realm.executeTransaction { realm ->
incDecCell = IncDecCellDB()
incDecCell = realm.copyToRealm(incDecCell!!)
cell!!.setCellIncDec(incDecCell!!)
realm.copyToRealmOrUpdate(cell!!)
}
}
val itemDB = incDecCell!!.item
if (itemDB != null) {
item = itemDB.toGeneric()
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.inc_dec_controller_action, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
maxText.setText("" + incDecCell!!.max)
minText.setText("" + incDecCell!!.min)
valueText.setText("" + incDecCell!!.value)
itemsSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
realm.beginTransaction()
val item = items[position]
if (item != null) {
val itemDB = ItemDB.createOrLoadFromGeneric(realm, item)
incDecCell!!.item = itemDB
}
realm.commitTransaction()
}
override fun onNothingSelected(parent: AdapterView<*>) {}
}
itemAdapter = ArrayAdapter(activity!!, android.R.layout.simple_spinner_dropdown_item, items)
itemsSpinner.adapter = itemAdapter
val servers = realm.where(ServerDB::class.java).findAll()
items.clear()
val item = item
if (item != null) {
items.add(item)
itemAdapter!!.add(item)
itemAdapter!!.notifyDataSetChanged()
}
if (incDecCell!!.item != null) {
items.add(incDecCell!!.item!!.toGeneric())
}
for (serverDB in servers) {
val server = serverDB.toGeneric()
val serverHandler = connectionFactory.createServerHandler(server, context)
serverHandler.requestItemsRx()
.map<List<OHItem>>({ this.filterItems(it) })
.compose(bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ newItems ->
this.items.addAll(newItems)
itemAdapter!!.notifyDataSetChanged()
}, { logger.e(TAG, "Failed to load items", it) })
}
updateIconImage()
setIconButton.setOnClickListener {
val intent = Intent(activity, IconPickerActivity::class.java)
startActivityForResult(intent, REQUEST_ICON)
}
}
private fun updateIconImage() {
setIconButton.setImageDrawable(Util.getIconDrawable(activity, incDecCell!!.icon))
}
private fun filterItems(items: MutableList<OHItem>): List<OHItem> {
val tempItems = ArrayList<OHItem>()
for (item in items) {
if (Constants.SUPPORT_INC_DEC.contains(item.type)) {
tempItems.add(item)
}
}
items.clear()
items.addAll(tempItems)
return items
}
override fun onPause() {
super.onPause()
realm.beginTransaction()
try {
incDecCell!!.max = Integer.parseInt(maxText.text.toString())
} catch (e: NumberFormatException) {
incDecCell!!.max = 100
}
try {
incDecCell!!.min = Integer.parseInt(minText.text.toString())
} catch (e: NumberFormatException) {
incDecCell!!.min = 0
}
try {
incDecCell!!.value = Integer.parseInt(valueText.text.toString())
} catch (e: NumberFormatException) {
incDecCell!!.value = 1
}
realm.commitTransaction()
}
override fun onDestroy() {
super.onDestroy()
realm.close()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_ICON &&
resultCode == Activity.RESULT_OK &&
data!!.hasExtra(IconPickerActivity.RESULT_ICON)) {
val iconName = data.getStringExtra(IconPickerActivity.RESULT_ICON)
realm.beginTransaction()
incDecCell!!.icon = if (iconName == "") null else iconName
realm.commitTransaction()
updateIconImage()
}
}
companion object {
private val TAG = "CellIncDecConfigFragment"
private val ARG_CELL_ID = "ARG_CELL_ID"
private val REQUEST_ICON = 183
fun newInstance(cell: CellDB): CellIncDecConfigFragment {
val fragment = CellIncDecConfigFragment()
val args = Bundle()
args.putLong(ARG_CELL_ID, cell.id)
fragment.arguments = args
return fragment
}
}
}// Required empty public constructor
| mobile/src/main/java/treehou/se/habit/ui/control/cells/config/CellIncDecConfigFragment.kt | 1146115253 |
package com.xiaojinzi.component2
import android.content.Context
import com.xiaojinzi.base.ModuleConfig
import com.xiaojinzi.component.anno.ParameterAnno
import com.xiaojinzi.component.anno.router.*
import com.xiaojinzi.component.support.Action
import io.reactivex.Completable
// @RouterApiAnno
@HostAnno(ModuleConfig.App.NAME)
interface AppApiKotlin {
@UserInfoAnno("xiaojinzi")
@PathAnno(ModuleConfig.App.TEST_ROUTER)
fun goToTestRouter(@AfterActionAnno afterAction: Action)
@PathAnno(ModuleConfig.App.TEST_QUALITY)
fun goToTestQuality(): Completable
@HostAnno(ModuleConfig.Help.NAME)
@PathAnno(ModuleConfig.Help.TEST_WEB_ROUTER)
fun goToTestWebRouter(context: Context)
@PathAnno(ModuleConfig.Help.TEST_WEB_ROUTER)
fun test(
context: Context,
@ParameterAnno("name") name: String,
@ParameterAnno("age") age: Int? = 0
)
} | Demo/Module2/src/main/java/com/xiaojinzi/component2/AppApiKotlin.kt | 236448995 |
/*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2020 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC 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 BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.di
import android.content.Context
import dagger.BindsInstance
import dagger.Component
import edu.berkeley.boinc.attach.ProjectAttachService
import edu.berkeley.boinc.client.Monitor
import edu.berkeley.boinc.mutex.MutexModule
import javax.inject.Singleton
@Singleton
@Component(modules = [MutexModule::class])
interface AppComponent {
@Component.Factory
interface Factory {
fun create(@BindsInstance context: Context): AppComponent
}
fun inject(monitor: Monitor)
fun inject(projectAttachService: ProjectAttachService)
}
| android/BOINC/app/src/main/java/edu/berkeley/boinc/di/AppComponent.kt | 2650801831 |
package org.softpark.stateful4k.extensions
import org.softpark.stateful4k.StateMachine
import org.softpark.stateful4k.config.IConfigurator
import org.softpark.stateful4k.config.events.IEventConfigurator
import org.softpark.stateful4k.config.states.IStateConfigurator
import kotlin.reflect.KClass
internal fun Class<*>.inheritsFrom(baseClass: Class<*>): Boolean {
return baseClass.isAssignableFrom(this)
}
internal fun Class<*>.distanceFrom(baseClass: Class<*>): Int? {
if (!this.inheritsFrom(baseClass)) return null
fun min(x: Int?, y: Int?): Int? =
if (x == null) y else if (y == null) x else Math.min(x, y)
fun distance(thisClass: Class<*>?, total: Int): Int? {
if (thisClass == null) return null
if (thisClass == baseClass) return total
if (thisClass == Any::class.java) return null
val interfaces = if (baseClass.isInterface) thisClass.interfaces else emptyArray<Class<*>>()
return interfaces.plus(thisClass.superclass).map { distance(it, total + 1) }.reduce { x, y -> min(x, y) }
}
return distance(this, 0)
}
internal fun <T> T?.nullify(value: T): T? =
if (this == null || this.equals(value)) null else this
fun <C, S : Any, E, AS : S> IConfigurator<C, S, E>.state(
stateType: KClass<AS>): IStateConfigurator<C, S, E, AS> =
this.state(stateType.java)
fun <C, S : Any, E : Any, AS : S, AE : E> IConfigurator<C, S, E>.event(
stateType: KClass<AS>, eventType: KClass<AE>): IEventConfigurator<C, S, E, AS, AE> =
this.event(stateType.java, eventType.java)
fun <C, S : Any, E : Any, AS : S, AE : E> IStateConfigurator<C, S, E, AS>.event(
eventType: KClass<AE>): IEventConfigurator<C, S, E, AS, AE> =
this.event(eventType.java)
fun <C, S : Any, E : Any> IConfigurator<C, S, E>.createExecutor(context: C, state: S) =
StateMachine.createExecutor(this, context, state) | src/main/java/org/softpark/stateful4k/extensions/Extensions.kt | 2967815084 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.bukkit.data
enum class LoadOrder {
STARTUP,
POSTWORLD
}
| src/main/kotlin/platform/bukkit/data/LoadOrder.kt | 136461000 |
package com.paulyerger.nbrb.listener
/**
* Created by Pavel on 03.08.2015.
*/
public class RatesInfo(
val lastUpdateVal: String,
val currentDateVal: String,
val previousDateVal: String,
val prevEurVal: Float,
val prevUsdVal: Float,
val prevRubVal: Float,
val curEurVal: Float,
val curUsdVal: Float,
val curRubVal: Float,
val difEurVal: Float,
val difUsdVal: Float,
val difRubVal: Float
) {
} | src/main/java/com/paulyerger/nbrb/listener/RatesInfo.kt | 224207108 |
package com.esotericsoftware.spine.internal
| korge-spine/src/commonMain/kotlin/com/esotericsoftware/spine/internal/internal.kt | 1120668874 |
package com.soywiz.korge.baseview
import com.soywiz.klock.*
import com.soywiz.korge.component.*
import com.soywiz.korge.internal.*
import com.soywiz.korge.view.*
open class BaseView {
@KorgeInternal
@PublishedApi
internal var _components: Components? = null
@KorgeInternal
@PublishedApi
internal val componentsSure: Components
get() {
if (_components == null) _components = Components()
return _components!!
}
/** Creates a typed [T] component (using the [gen] factory function) if the [View] doesn't have any of that kind, or returns a component of that type if already attached */
//Deprecated("")
//inline fun <reified T : Component> ComponentContainer.getOrCreateComponent(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : Component> getOrCreateComponentOther(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : MouseComponent> getOrCreateComponentMouse(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : KeyComponent> getOrCreateComponentKey(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : GamepadComponent> getOrCreateComponentGamepad(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : TouchComponent> getOrCreateComponentTouch(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : EventComponent> getOrCreateComponentEvent(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : UpdateComponentWithViews> getOrCreateComponentUpdateWithViews(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : UpdateComponent> getOrCreateComponentUpdate(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : ResizeComponent> getOrCreateComponentResize(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : UpdateComponent> getComponentUpdate(): T? = componentsSure.getComponentUpdate<T>()
/** Removes a specific [c] component from the view */
fun removeComponent(c: Component) {
_components?.remove(c)
}
fun removeComponent(c: MouseComponent) {
_components?.remove(c)
}
fun removeComponent(c: KeyComponent) {
_components?.remove(c)
}
fun removeComponent(c: GamepadComponent) {
_components?.remove(c)
}
fun removeComponent(c: TouchComponent) {
_components?.remove(c)
}
fun removeComponent(c: EventComponent) {
_components?.remove(c)
}
fun removeComponent(c: UpdateComponentWithViews) {
_components?.remove(c)
}
fun removeComponent(c: UpdateComponent) {
_components?.remove(c)
}
fun removeComponent(c: ResizeComponent) {
_components?.remove(c)
}
//fun removeComponents(c: KClass<out Component>) { components?.removeAll { it.javaClass.isSubtypeOf(c) } }
///** Removes a set of components of the type [c] from the view */
//@eprecated("")
//fun removeComponents(c: KClass<out Component>) { _components?.removeAll(c) }
/** Removes all the components attached to this view */
fun removeAllComponents(): Unit {
_components?.removeAll()
}
/** Adds a component to this view */
fun addComponent(c: Component): Component = componentsSure.add(c)
fun addComponent(c: MouseComponent) = componentsSure.add(c)
fun addComponent(c: KeyComponent) = componentsSure.add(c)
fun addComponent(c: GamepadComponent) = componentsSure.add(c)
fun addComponent(c: TouchComponent) = componentsSure.add(c)
fun addComponent(c: EventComponent) = componentsSure.add(c)
fun addComponent(c: UpdateComponentWithViews) = componentsSure.add(c)
fun addComponent(c: UpdateComponent) = componentsSure.add(c)
fun addComponent(c: ResizeComponent) = componentsSure.add(c)
/** Registers a [block] that will be executed once in the next frame that this [View] is displayed with the [Views] singleton */
fun deferWithViews(block: (views: Views) -> Unit) {
addComponent(DeferWithViewsUpdateComponentWithViews(this@BaseView, block))
}
internal class DeferWithViewsUpdateComponentWithViews(override val view: BaseView, val block: (views: Views) -> Unit) :
UpdateComponentWithViews {
override fun update(views: Views, dt: TimeSpan) {
block(views)
detach()
}
}
// region Properties
private val _props = linkedMapOf<String, Any?>()
/** Immutable map of custom String properties attached to this view. Should use [hasProp], [getProp] and [addProp] methods to control this */
val props: Map<String, Any?> get() = _props
/** Checks if this view has the [key] property */
fun hasProp(key: String) = key in _props
/** Gets the [key] property of this view as a [String] or [default] when not found */
fun getPropString(key: String, default: String = "") = _props[key]?.toString() ?: default
/** Gets the [key] property of this view as an [Double] or [default] when not found */
fun getPropDouble(key: String, default: Double = 0.0): Double {
val value = _props[key]
if (value is Number) return value.toDouble()
if (value is String) return value.toDoubleOrNull() ?: default
return default
}
/** Gets the [key] property of this view as an [Int] or [default] when not found */
fun getPropInt(key: String, default: Int = 0) = getPropDouble(key, default.toDouble()).toInt()
/** Adds or replaces the property [key] with the [value] */
fun addProp(key: String, value: Any?) {
_props[key] = value
//val componentGen = views.propsTriggers[key]
//if (componentGen != null) {
// componentGen(this, key, value)
//}
}
/** Adds a list of [values] properties at once */
fun addProps(values: Map<String, Any?>) {
for (pair in values) addProp(pair.key, pair.value)
}
// endregion
}
| korge/src/commonMain/kotlin/com/soywiz/korge/baseview/BaseView.kt | 2350980524 |
package com.esorokin.lantector.model.network.api.handler
import io.reactivex.Observable
import io.reactivex.Scheduler
import retrofit2.Call
import retrofit2.CallAdapter
import java.lang.reflect.Type
internal class ObservableCallAdapter<BaseResponse>(
private val networkScheduler: Scheduler,
private val responseType: Type,
private val networkErrorAdapter: NetworkErrorAdapter,
private val httpResponseHandler: HttpResponseAdapter<BaseResponse>) : CallAdapter<BaseResponse, Observable<BaseResponse>> {
override fun responseType(): Type {
return responseType
}
override fun adapt(call: Call<BaseResponse>): Observable<BaseResponse> {
return CallExecuteObservable(call)
.subscribeOn(networkScheduler)
.onErrorResumeNext { throwable: Throwable -> Observable.error(networkErrorAdapter.adaptNetworkError(throwable)) }
.map(httpResponseHandler::adaptHttpResponse)
}
}
| app/src/main/java/com/esorokin/lantector/model/network/api/handler/ObservableCallAdapter.kt | 3677027940 |
package com.karumi.ui.view
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.test.espresso.intent.rule.IntentsTestRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.platform.app.InstrumentationRegistry
import com.github.salomonbrys.kodein.Kodein
import com.karumi.asApp
import org.junit.Before
import org.junit.Rule
import org.junit.runner.RunWith
import com.karumi.shot.ScreenshotTest
import org.mockito.MockitoAnnotations
@LargeTest
@RunWith(AndroidJUnit4::class)
abstract class AcceptanceTest<T : Activity>(clazz: Class<T>) : ScreenshotTest {
@Rule
@JvmField
val testRule: IntentsTestRule<T> = IntentsTestRule(clazz, true, false)
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
val app = InstrumentationRegistry.getInstrumentation().targetContext.asApp()
app.resetInjection()
app.overrideModule = testDependencies
}
fun startActivity(args: Bundle = Bundle()): T {
val intent = Intent()
intent.putExtras(args)
return testRule.launchActivity(intent)
}
abstract val testDependencies: Kodein.Module
} | shot-consumer/app/src/androidTest/java/com/karumi/ui/view/AcceptanceTest.kt | 2114628829 |
package com.esorokin.lantector.model.network.exception
import com.esorokin.lantector.model.network.data.ApiStatusCode
open class ApiException(val apiStatusCode: ApiStatusCode) : AppException(apiStatusCode.appErrorType)
| app/src/main/java/com/esorokin/lantector/model/network/exception/ApiException.kt | 2117389068 |
/*
* Copyright (c) 2017-2020 by Oliver Boehm
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* (c)reated 10.07.2017 by oboehm ([email protected])
*/
package de.jfachwert.rechnung
import de.jfachwert.KSimpleValidator
import de.jfachwert.Text
import de.jfachwert.pruefung.LengthValidator
import de.jfachwert.pruefung.NullValidator
import java.util.*
/**
* Auf Rechnunungen (und auch im geschaeftlichen Schriftverkehr) gibt es
* oftmals eine Referenznummer, die durch diese Klasse repraesentiert wird.
*
* @author oboehm
* @since 0.3 (10.07.2017)
*/
open class Referenznummer
/**
* Dieser Konstruktor ist hauptsaechlich fuer abgeleitete Klassen gedacht,
* damit diese den [KSimpleValidator] ueberschreiben koennen.
* Man kann es auch verwenden, um einen eigenen [KSimpleValidator]
* einsetzen zu koennen.
*
* @param nummer z.B. "000002835042"
* @param pruefung Pruefverfahren
*/
@JvmOverloads constructor(nummer: String, pruefung: KSimpleValidator<String> = LengthValidator.NOT_EMPTY_VALIDATOR) : Text(nummer, pruefung) {
companion object {
private val WEAK_CACHE = WeakHashMap<String, Referenznummer>()
/** Null-Konstante fuer Initialisierungen. */
@JvmField
val NULL = Referenznummer("", NullValidator())
/**
* Erzeugt eine Referenznummer.
*
* @param nummer z.B. "000002835042"
* @return Referenznummer
*/
@JvmStatic
fun of(nummer: String): Referenznummer {
return WEAK_CACHE.computeIfAbsent(nummer) { n: String -> Referenznummer(n) }
}
}
} | src/main/kotlin/de/jfachwert/rechnung/Referenznummer.kt | 3742838468 |
/**
* Created by [email protected]
*/
import BTree.BTree
import BinaryTree.BinarySearchTree
import RBTree.RedBlackTree
import org.junit.jupiter.api.Test
import java.util.*
internal class EqualTreeTest {
@Test
fun BinTreeRandom() {
val BinTree = BinarySearchTree<Int, Int>()
var number:Int = 100
while (number < 10000001) {
var start = System.currentTimeMillis()
for (i in 1..number) {
val key = Random().nextInt(number-1) + 1
BinTree.insert(key, key)
}
var finish = System.currentTimeMillis()
var timeConsumedMillis:Float = (finish - start).toFloat()/1000
println("InsertBinTreeRandom(${number}):"+timeConsumedMillis)
start = System.currentTimeMillis()
for (i in 1..number) {
val key = Random().nextInt(number-1) + 1
BinTree.search(key)
}
finish = System.currentTimeMillis()
timeConsumedMillis = (finish - start).toFloat()/1000
println("SearchBinTreeRandom(${number}):"+timeConsumedMillis)
number *= 10
println()
}
}
@Test
fun BinTreeQueue() {
val BinTree = BinarySearchTree<Int, Int>()
var number:Int = 100
while (number < 10000001) {
var start = System.currentTimeMillis()
for (key in 1..number) BinTree.insert(key, key)
var finish = System.currentTimeMillis()
var timeConsumedMillis:Float = (finish - start).toFloat()/1000
println("InsertBinTreeQueue(${number}):"+timeConsumedMillis)
start = System.currentTimeMillis()
for (key in 1..number) {
BinTree.search(key)
}
finish = System.currentTimeMillis()
timeConsumedMillis = (finish - start).toFloat()/1000
println("SearchBinTreeQueue(${number}):"+timeConsumedMillis)
number *= 10
println()
}
}
@Test
fun RBTreeRandom() {
val RBTree = RedBlackTree<Int, Int>()
var number:Int = 100
while (number < 10000001) {
var start = System.currentTimeMillis()
for (i in 1..number) {
val key = Random().nextInt(number-1) + 1
RBTree.insert(key, key)
}
var finish = System.currentTimeMillis()
var timeConsumedMillis:Float = (finish - start).toFloat()/1000
println("InsertRBTreeRandom(${number}):"+timeConsumedMillis)
start = System.currentTimeMillis()
for (i in 1..number) {
val key = Random().nextInt(number-1) + 1
RBTree.search(key)
}
finish = System.currentTimeMillis()
timeConsumedMillis = (finish - start).toFloat()/1000
println("SearchRBTreeRandom(${number}):"+timeConsumedMillis)
number *= 10
println()
}
}
@Test
fun RBTreeQueue() {
val RBTree = RedBlackTree<Int, Int>()
var number:Int = 100
while (number < 10000001) {
var start = System.currentTimeMillis()
for (key in 1..number) RBTree.insert(key, key)
var finish = System.currentTimeMillis()
var timeConsumedMillis:Float = (finish - start).toFloat()/1000
println("InsertRBTreeQueue(${number}):"+timeConsumedMillis)
start = System.currentTimeMillis()
for (key in 1..number) {
RBTree.search(key)
}
finish = System.currentTimeMillis()
timeConsumedMillis = (finish - start).toFloat()/1000
println("SearchRBTreeQueue(${number}):"+timeConsumedMillis)
number *= 10
println()
}
}
@Test
fun BTreeRandom() {
val BTree = BTree<Int>(100)
var number:Int = 100
while (number < 10000001) {
var start = System.currentTimeMillis()
for (i in 1..number) {
val key = Random().nextInt(number-1) + 1
BTree.insert(key)
}
var finish = System.currentTimeMillis()
var timeConsumedMillis:Float = (finish - start).toFloat()/1000
println("InsertBTreeRandom(${number}):"+timeConsumedMillis)
start = System.currentTimeMillis()
for (i in 1..number) {
val key = Random().nextInt(number-1) + 1
BTree.search(key)
}
finish = System.currentTimeMillis()
timeConsumedMillis = (finish - start).toFloat()/1000
println("SearchBTreeRandom(${number}):"+timeConsumedMillis)
number *= 10
println()
}
}
@Test
fun BTreeQueue() {
val BTree = BTree<Int>(100)
var number:Int = 100
while (number < 10000001) {
var start = System.currentTimeMillis()
for (key in 1..number) BTree.insert(key)
var finish = System.currentTimeMillis()
var timeConsumedMillis:Float = (finish - start).toFloat()/1000
println("InsertBTreeQueue(${number}):"+timeConsumedMillis)
start = System.currentTimeMillis()
for (key in 1..number) {
BTree.search(key)
}
finish = System.currentTimeMillis()
timeConsumedMillis = (finish - start).toFloat()/1000
println("SearchBTreeQueue(${number}):"+timeConsumedMillis)
number *= 10
println()
}
}
} | tests/RBTree/equalTree.kt | 1874280062 |
/*
* Copyright 2019 Patches Klinefelter
*
* 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.isupatches.wisefysample.internal.models
internal enum class NetworkType(val intVal: Int) {
OPEN(0),
WEP(1),
WPA2(2);
companion object {
fun of(intVal: Int): NetworkType {
return when (intVal) {
OPEN.intVal -> OPEN
WEP.intVal -> WEP
WPA2.intVal -> WPA2
else -> throw IllegalArgumentException("Invalid NetworkType, intVal: $intVal")
}
}
}
}
| wisefysample/src/main/java/com/isupatches/wisefysample/internal/models/NetworkType.kt | 967070183 |
package com.isupatches.wisefy
import com.isupatches.wisefy.callbacks.GetNearbyAccessPointsCallbacks
import com.isupatches.wisefy.constants.MISSING_PARAMETER
import com.isupatches.wisefy.internal.base.BaseInstrumentationTest
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.Mockito.mock
import org.mockito.Mockito.timeout
import org.mockito.Mockito.verify
/**
* Tests the ability to retrieve a list of nearby access points for a device.
*
* @author Patches
* @since 3.0
*/
internal class GetNearbyAccessPointsTests : BaseInstrumentationTest() {
@Test
fun sync_failure_prechecks_filterDuplicates_false() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_failure()
assertEquals(null, wisefy.getNearbyAccessPoints(false))
}
@Test
fun sync_failure_prechecks_filterDuplicates_true() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_failure()
assertEquals(null, wisefy.getNearbyAccessPoints(true))
}
@Test
fun sync_failure_filterDuplicates_false() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
mockWiseFySearchUtil.nearbyAccessPoints_null(false)
val nearbyAccessPoints = wisefy.getNearbyAccessPoints(false)
assertEquals(null, nearbyAccessPoints)
}
@Test
fun sync_failure_filterDuplicates_true() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
mockWiseFySearchUtil.nearbyAccessPoints_null(true)
val nearbyAccessPoints = wisefy.getNearbyAccessPoints(true)
assertEquals(null, nearbyAccessPoints)
}
@Test
fun sync_success_filterDuplicates_false() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
val accessPoints = mockWiseFySearchUtil.nearbyAccessPoints_success(false)
val nearbyAccessPoints = wisefy.getNearbyAccessPoints(false)
assertEquals(accessPoints, nearbyAccessPoints)
}
@Test
fun sync_success_filterDuplicates_true() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
val accessPoints = mockWiseFySearchUtil.nearbyAccessPoints_success(true)
val nearbyAccessPoints = wisefy.getNearbyAccessPoints(true)
assertEquals(accessPoints, nearbyAccessPoints)
}
@Test
fun async_failure_prechecks_filterDuplicates_false() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_failure()
val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java)
wisefy.getNearbyAccessPoints(false, mockCallbacks)
verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).wisefyFailure(MISSING_PARAMETER)
}
@Test
fun async_failure_prechecks_filterDuplicates_false_nullCallback() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_failure()
nullCallbackUtil.callGetNearbyAccessPoints(false)
}
@Test
fun async_failure_prechecks_filterDuplicates_true() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_failure()
val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java)
wisefy.getNearbyAccessPoints(true, mockCallbacks)
verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).wisefyFailure(MISSING_PARAMETER)
}
@Test
fun async_failure_prechecks_filterDuplicates_true_nullCallback() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_failure()
nullCallbackUtil.callGetNearbyAccessPoints(true)
}
@Test
fun async_failure_filterDuplicates_false() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
mockWiseFySearchUtil.nearbyAccessPoints_null(false)
val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java)
wisefy.getNearbyAccessPoints(false, mockCallbacks)
verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).noAccessPointsFound()
}
@Test
fun async_failure_filterDuplicates_false_nullCallback() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
mockWiseFySearchUtil.nearbyAccessPoints_success(true)
nullCallbackUtil.callGetNearbyAccessPoints(false)
}
@Test
fun async_failure_filterDuplicates_true() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
mockWiseFySearchUtil.nearbyAccessPoints_null(true)
val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java)
wisefy.getNearbyAccessPoints(true, mockCallbacks)
verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).noAccessPointsFound()
}
@Test
fun async_failure_filterDuplicates_true_nullCallback() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
mockWiseFySearchUtil.nearbyAccessPoints_null(true)
nullCallbackUtil.callGetNearbyAccessPoints(true)
}
@Test
fun async_success_filterDuplicates_false() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
val accessPoints = mockWiseFySearchUtil.nearbyAccessPoints_success(false)
val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java)
wisefy.getNearbyAccessPoints(false, mockCallbacks)
verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).retrievedNearbyAccessPoints(accessPoints)
}
@Test
fun async_success_filterDuplicates_false_nullCallback() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
mockWiseFySearchUtil.nearbyAccessPoints_success(true)
nullCallbackUtil.callGetNearbyAccessPoints(false)
}
@Test
fun async_success_filterDuplicates_true() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
val accessPoints = mockWiseFySearchUtil.nearbyAccessPoints_success(true)
val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java)
wisefy.getNearbyAccessPoints(true, mockCallbacks)
verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).retrievedNearbyAccessPoints(accessPoints)
}
@Test
fun async_success_filterDuplicates_true_nullCallback() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
mockWiseFySearchUtil.nearbyAccessPoints_success(true)
nullCallbackUtil.callGetNearbyAccessPoints(true)
}
}
| wisefy/src/androidTest/java/com/isupatches/wisefy/GetNearbyAccessPointsTests.kt | 2738043688 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.history.integration
import com.intellij.history.core.changes.ChangeSet
import com.intellij.history.core.changes.ChangeVisitor
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.ui.Messages
import com.intellij.util.ExceptionUtil
class ValidateHistoryAction : AnAction() {
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = ApplicationManager.getApplication().isInternal
}
override fun actionPerformed(e: AnActionEvent) {
object : Task.Modal(e.project, "Checking local history storage", true) {
override fun run(indicator: ProgressIndicator) {
val t = System.currentTimeMillis()
try {
LocalHistoryImpl.getInstanceImpl().facade?.accept(object : ChangeVisitor() {
private var count = 0
override fun end(c: ChangeSet) {
indicator.checkCanceled()
if (++count % 10 == 0) {
indicator.text = "${count} records checked"
}
}
override fun finished() {
val message = "Local history storage seems to be OK (checked ${count} records in ${System.currentTimeMillis() - t} ms)"
ApplicationManager.getApplication().invokeLater { Messages.showInfoMessage(e.project, message, "Local History Validation") }
}
})
}
catch(ex: ProcessCanceledException) { throw ex }
catch(ex: Exception) {
Messages.showErrorDialog(e.project, ExceptionUtil.getThrowableText(ex), "Local History Validation Error")
}
}
}.queue()
}
} | platform/lvcs-impl/src/com/intellij/history/integration/ValidateHistoryAction.kt | 1898009711 |
package com.chilangolabs.mdb
import android.hardware.fingerprint.FingerprintManager
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.chilangolabs.mdb.utils.logd
import com.chilangolabs.mdb.utils.loge
import com.chilangolabs.mdb.utils.logw
import com.dev21.fingerprintassistant.FingerprintAuthListener
import com.dev21.fingerprintassistant.FingerprintHelper
import com.dev21.fingerprintassistant.FingerprintResultsHandler
import com.dev21.fingerprintassistant.ResponseCode
import kotlinx.android.synthetic.main.activity_confirm_transfer.*
import org.jetbrains.anko.intentFor
import org.jetbrains.anko.singleTop
import org.jetbrains.anko.toast
class ConfirmTransferActivity : AppCompatActivity(), FingerprintAuthListener {
private val fingerPrintHelper: FingerprintHelper? by lazy {
FingerprintHelper(this, "FingerPrintMDB")
}
private val fingerprintresulthandler: FingerprintResultsHandler? by lazy {
FingerprintResultsHandler(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_confirm_transfer)
val a = fingerprintresulthandler
btnConfirmTransfer.setOnClickListener {
startActivity(intentFor<CardsActivity>().singleTop())
}
}
override fun onResume() {
super.onResume()
val responseCode = fingerPrintHelper?.checkAndEnableFingerPrintService()
when (responseCode) {
ResponseCode.FINGERPRINT_SERVICE_INITIALISATION_SUCCESS -> {
// toast("Fingerprint sensor service initialisation success")
fingerprintresulthandler?.setFingerprintAuthListener(this)
fingerprintresulthandler?.startListening(fingerPrintHelper?.fingerprintManager, fingerPrintHelper?.cryptoObject)
}
ResponseCode.OS_NOT_SUPPORTED -> toast("OS doesn't support fingerprint api")
ResponseCode.FINGER_PRINT_SENSOR_UNAVAILABLE -> toast("Fingerprint sensor not found")
ResponseCode.ENABLE_FINGER_PRINT_SENSOR_ACCESS -> toast("Provide access to use fingerprint sensor")
ResponseCode.NO_FINGER_PRINTS_ARE_ENROLLED -> toast("No fingerprints found")
ResponseCode.FINGERPRINT_SERVICE_INITIALISATION_FAILED -> toast("Fingerprint service initialisation failed")
ResponseCode.DEVICE_NOT_KEY_GUARD_SECURED -> toast("Device is not key guard protected")
}
fingerprintresulthandler?.let {
if (it.isAlreadyListening) {
it.startListening(fingerPrintHelper?.fingerprintManager, fingerPrintHelper?.cryptoObject)
}
}
}
override fun onStop() {
super.onStop()
fingerprintresulthandler?.stopListening()
}
override fun onAuthentication(helpOrErrorCode: Int,
infoString: CharSequence?,
authenticationResult: FingerprintManager.AuthenticationResult?,
authCode: Int) {
when (authCode) {
ResponseCode.AUTH_ERROR -> {
loge("AUTH Error")
logd("$infoString")
txtConfirmTransfer.text = "Error al leer tu huella, intena de nuevo"
imgFingerPrint.setImageResource(R.drawable.ic_finger_print_red)
}
ResponseCode.AUTH_FAILED -> {
loge("AUTH Failed")
logd("$infoString")
txtConfirmTransfer.text = "Error al leer tu huella, intena de nuevo"
imgFingerPrint.setImageResource(R.drawable.ic_finger_print_red)
}
ResponseCode.AUTH_HELP -> {
logw("AUTH HELP")
logd("$infoString")
txtConfirmTransfer.text = "Error al leer tu huella, intena de nuevo"
imgFingerPrint.setImageResource(R.drawable.ic_finger_print_red)
}
ResponseCode.AUTH_SUCCESS -> {
logd("AUTH Success")
logd("$infoString")
txtConfirmTransfer.text = "Huella confirmada"
imgFingerPrint.setImageResource(R.drawable.ic_finger_print_green)
}
}
}
}
| app/src/main/java/com/chilangolabs/mdb/ConfirmTransferActivity.kt | 2571578441 |
@file:JvmName("SimpleSettingsSample")
package com.github.konfko.core.sample
import com.github.konfko.core.derived.subSettings
import com.github.konfko.core.source.SettingsMaker
/**
* @author markopi
*/
fun main(args: Array<String>) {
val settings = SettingsMaker().make {
classpath("com/github/konfko/core/dataSources.properties")
}
// read a single setting
val firstUrl: String = settings["dataSource.first.url"]
// partial views
val firstDataSource = settings.subSettings("dataSource.first")
val secondDataSource = settings.subSettings("dataSource").subSettings("second")
val secondUrl: String = secondDataSource["url"]
println("First url: $firstUrl, second url: $secondUrl")
// optional Int settings
val firstConnectionTimeout: Int? = firstDataSource.find("connectionTimeout")
val secondConnectionTimeout: Int? = secondDataSource.find("connectionTimeout")
println("First timeout: $firstConnectionTimeout, second timeout: $secondConnectionTimeout")
println("All data sources: ${settings.subSettings("dataSource").topLevelKeys}")
}
| konfko-core/src/test/kotlin/com/github/konfko/core/sample/SimpleSettingsSample.kt | 954567518 |
package com.telenav.osv.data.collector.datatype.datatypes
import com.telenav.osv.data.collector.datatype.util.LibraryUtil
/**
* Class which retrieves the relative ambient air humidity as a percentage
*/
class HumidityObject(humidity: Float, statusCode: Int) : BaseObject<Float?>(humidity, statusCode, LibraryUtil.HUMIDITY) {
constructor(statusCode: Int) : this(Float.MIN_VALUE, statusCode) {}
/**
* Returns the relative ambient humidity in percent (%).
*/
val humidity: Float
get() = actualValue!!
init {
dataSource = LibraryUtil.PHONE_SOURCE
}
} | app/src/main/java/com/telenav/osv/data/collector/datatype/datatypes/HumidityObject.kt | 111740464 |
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util.media
import android.content.Context
import android.content.SharedPreferences
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.Target
import org.mariotaku.kpreferences.get
import de.vanita5.twittnuker.constant.mediaPreloadKey
import de.vanita5.twittnuker.constant.mediaPreloadOnWifiOnlyKey
import de.vanita5.twittnuker.extension.loadProfileImage
import de.vanita5.twittnuker.model.ParcelableActivity
import de.vanita5.twittnuker.model.ParcelableMedia
import de.vanita5.twittnuker.model.ParcelableStatus
import de.vanita5.twittnuker.extension.model.activityStatus
class MediaPreloader(val context: Context) {
var isNetworkMetered: Boolean = true
private var preloadEnabled: Boolean = true
private var preloadOnWifiOnly: Boolean = true
private val shouldPreload: Boolean get() = preloadEnabled && (!preloadOnWifiOnly || !isNetworkMetered)
fun preloadStatus(status: ParcelableStatus) {
if (!shouldPreload) return
preLoadProfileImage(status)
preloadMedia(status.media)
preloadMedia(status.quoted_media)
}
fun preloadActivity(activity: ParcelableActivity) {
if (!shouldPreload) return
activity.activityStatus?.let { preloadStatus(it) }
}
fun reloadOptions(preferences: SharedPreferences) {
preloadEnabled = preferences[mediaPreloadKey]
preloadOnWifiOnly = preferences[mediaPreloadOnWifiOnlyKey]
}
private fun preloadMedia(media: Array<ParcelableMedia>?) {
media?.forEach { item ->
val url = item.preview_url ?: run {
if (item.type != ParcelableMedia.Type.IMAGE) return@run null
return@run item.media_url
} ?: return@forEach
preloadPreviewImage(url)
}
}
private fun preLoadProfileImage(status: ParcelableStatus) {
Glide.with(context).loadProfileImage(context, status, 0).into(Target.SIZE_ORIGINAL,
Target.SIZE_ORIGINAL)
}
private fun preloadPreviewImage(url: String?) {
Glide.with(context).load(url).into(Target.SIZE_ORIGINAL,
Target.SIZE_ORIGINAL)
}
} | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/media/MediaPreloader.kt | 2393531897 |
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.fragment.iface
interface IFloatingActionButtonFragment {
fun getActionInfo(tag: String): ActionInfo?
fun onActionClick(tag: String) : Boolean
data class ActionInfo(val icon: Int, val title: String)
} | twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/iface/IFloatingActionButtonFragment.kt | 801743723 |
/*
* Copyright (C) 2019 Wiktor Nizio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.events.main.viewmodel
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
data class DefaultHotData<T>(
override val liveData: LiveData<T>,
override val owner: LifecycleOwner,
): HotData<T>
| events/src/main/kotlin/pl/org/seva/events/main/viewmodel/DefaultHotData.kt | 4223921107 |
package com.stripe.android.paymentsheet.screenshot
import androidx.compose.material.Surface
import androidx.compose.ui.test.junit4.createComposeRule
import com.karumi.shot.ScreenshotTest
import com.stripe.android.paymentsheet.ui.GooglePayDividerUi
import com.stripe.android.ui.core.PaymentsTheme
import com.stripe.android.ui.core.PaymentsThemeDefaults
import org.junit.Rule
import org.junit.Test
class GooglePayDividerScreenshot : ScreenshotTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun googlePayDividerUiLight() {
val colors = PaymentsThemeDefaults.colorsLight
composeTestRule.setContent {
PaymentsTheme(
colors = PaymentsThemeDefaults.colorsLight
) {
Surface(color = colors.materialColors.surface) {
GooglePayDividerUi()
}
}
}
compareScreenshot(composeTestRule)
}
@Test
fun googlePayDividerUiDark() {
val colors = PaymentsThemeDefaults.colorsDark
composeTestRule.setContent {
PaymentsTheme(
colors = PaymentsThemeDefaults.colorsDark
) {
Surface(color = colors.materialColors.surface) {
GooglePayDividerUi()
}
}
}
compareScreenshot(composeTestRule)
}
@Test
fun googlePayDividerUiBorders() {
composeTestRule.setContent {
PaymentsTheme(
shapes = PaymentsThemeDefaults.shapes.copy(borderStrokeWidth = 5.0f)
) {
Surface {
GooglePayDividerUi()
}
}
}
compareScreenshot(composeTestRule)
}
@Test
fun googlePayDividerUiBigFont() {
composeTestRule.setContent {
PaymentsTheme(
typography = PaymentsThemeDefaults.typography.copy(fontSizeMultiplier = 1.3f)
) {
Surface {
GooglePayDividerUi()
}
}
}
compareScreenshot(composeTestRule)
}
}
| paymentsheet/src/androidTest/java/com/stripe/android/paymentsheet/screenshot/GooglePayDividerScreenshot.kt | 469064679 |
package com.xenoage.zong.core.music.beam
import com.xenoage.utils.collections.checkIndex
import com.xenoage.utils.math.Fraction
import com.xenoage.utils.throwEx
import com.xenoage.zong.core.music.Voice
import com.xenoage.zong.core.music.WaypointPosition
import com.xenoage.zong.core.music.WaypointPosition.*
import com.xenoage.zong.core.music.beam.Beam.VerticalSpan.Other
import com.xenoage.zong.core.music.chord.Chord
import com.xenoage.zong.core.music.util.flagsCount
import com.xenoage.zong.core.position.MP
import com.xenoage.zong.core.position.MP.Companion.unknown
import com.xenoage.zong.core.position.MPElement
import kotlin.math.max
import kotlin.math.min
/**
* Class for a beam that connects two or more chords.
*
* A beam can be placed within a single staff (the common case) or
* cross two staves (e.g. in a piano score). When crossing two staves,
* the beam belongs to the staff of the first chord.
*/
class Beam(
/** The waypoints in this beam */
val waypoints: List<BeamWaypoint>
) : MPElement {
init { check() }
//cache
private var _verticalSpan: VerticalSpan? = null
private var _upperStaffIndex = -1
private var _lowerStaffIndex = -1
val start: BeamWaypoint
get() = waypoints.first()
val stop: BeamWaypoint
get() = waypoints.last()
/** The maximum number of beam lines used in the this beam */
val maxLinesCount: Int
get() {
val minDuration = waypoints.asSequence().map{ it.chord.displayedDuration }.min() ?: throw IllegalStateException()
return minDuration.flagsCount
}
/**
* The parent of the beam is defined as the voice of the start of the beam.
*/
override val parent: Voice?
get() = waypoints.first().chord.parent
/**
* The [MP] of the beam is the same as the [MP] of the first chord in the beam.
*/
override val mp: MP?
get() = waypoints.first().chord.mp
/** Spread of this beam within a system. */
enum class VerticalSpan {
/** Beam within a single staff. */
SingleStaff,
/** Beam crossing two adjacent staves. */
CrossStaff,
/** Other span (not supported). */
Other
}
/** Gets the waypoint at the given index. */
operator fun get(waypointIndex: Int): BeamWaypoint =
waypoints[waypointIndex]
/**
* Checks the correctness of the beam:
* The beam must have at least one line
* It must have at least 2 chords, must exist in a single measure column
* and the chords must be sorted by beat.
*/
private fun check() {
check(maxLinesCount > 0, { "A beam must have at least one line" })
check(waypoints.size >=2, { "At least two chords are needed to create a beam!" })
//check single column and beat order
var lastBeat: Fraction? = null
var wasLastChordGrace = false
val startMeasure = mp?.measure
if (startMeasure != unknown) {
for (wp in waypoints) {
val chordMP = wp.chord.mp ?: continue //if unknown MP, this waypoint can not be checked
val (_, wpMeasure, _, beat) = chordMP
//check, if all chords are in the same measure column
if (wpMeasure != startMeasure)
throw IllegalArgumentException("A beam may only span over one measure column")
//check, if chords are sorted by beat.
//for grace notes, the same beat is ok.
if (lastBeat != null && beat != null) {
val compare = beat.compareTo(lastBeat)
if (false == wasLastChordGrace && compare <= 0 || wasLastChordGrace && compare < 0)
throw IllegalArgumentException("Beamed chords must be sorted by beat")
}
lastBeat = beat
wasLastChordGrace = wp.chord.isGrace
}
}
}
/** The number of chords in this beam. */
val size: Int = waypoints.size
/** Gets the position of the given waypoint. */
fun getWaypointPosition(wp: BeamWaypoint): WaypointPosition =
getWaypointPosition(wp.chord)
/** Gets the position of the given chord. */
fun getWaypointPosition(chord: Chord): WaypointPosition {
return when (getWaypointIndex(chord)) {
0 -> Start
waypoints.size - 1 -> Stop
else -> Continue
}
}
/** Gets the index of the given chord within the beam. */
fun getWaypointIndex(chord: Chord): Int =
waypoints.indexOfFirst { it.chord === chord }.checkIndex { "Given chord is not part of this beam." }
/** The vertical spanning of this beam. */
val verticalSpan: VerticalSpan
get() {
if (_verticalSpan == null)
computeSpan()
return _verticalSpan!!
}
/** The index of the topmost staff this beam belongs to. */
val getUpperStaffIndex: Int
get() {
if (_upperStaffIndex == -1)
computeSpan()
return _upperStaffIndex
}
/** The index of the bottommost staff this beam belongs to. */
val getLowerStaffIndex: Int
get() {
if (_lowerStaffIndex == -1)
computeSpan()
return _lowerStaffIndex
}
/** Replaces the given old chord with the given new one. */
fun replaceChord(oldChord: Chord, newChord: Chord) {
for (i in waypoints.indices) {
if (waypoints[i].chord === oldChord) {
oldChord.beam = null
waypoints[i].chord = newChord
newChord.beam = this
computeSpan()
return
}
}
throwEx("Given chord is not part of this beam")
}
/**
* Returns true, if a beam lines subdivision ends at the chord
* with the given index.
*/
fun isEndOfSubdivision(chordIndex: Int): Boolean =
waypoints[chordIndex].subdivision
/** Gets the chord with the given index. */
fun getChord(chordIndex: Int): Chord =
waypoints[chordIndex].chord
/** Computes the vertical span of this beam. */
private fun computeSpan() {
var minStaffIndex = Int.MAX_VALUE
var maxStaffIndex = Int.MIN_VALUE
//check if the beam spans over a single staff or two adjacent staves or more
for (waypoint in waypoints) {
val chord = waypoint.chord
val mpChord = chord.mp
if (mpChord == null || mpChord.staff == unknown) { //unknown MP? then we can not compute this beam
_verticalSpan = Other
_upperStaffIndex = unknown
_lowerStaffIndex = unknown
return
}
minStaffIndex = min(minStaffIndex, mpChord.staff)
maxStaffIndex = max(maxStaffIndex, mpChord.staff)
}
var verticalSpan = Other
if (maxStaffIndex == minStaffIndex)
verticalSpan = VerticalSpan.SingleStaff
else if (maxStaffIndex - minStaffIndex == 1)
verticalSpan = VerticalSpan.CrossStaff
_verticalSpan = verticalSpan
_upperStaffIndex = minStaffIndex
_lowerStaffIndex = maxStaffIndex
}
companion object {
operator fun invoke(chords: List<Chord>) =
Beam(chords.map { BeamWaypoint(it) })
}
}
| core/src/com/xenoage/zong/core/music/beam/Beam.kt | 3198308481 |
package de.randombyte.lottery
import com.google.inject.Inject
import de.randombyte.kosp.PlayerExecutedCommand
import de.randombyte.kosp.config.ConfigManager
import de.randombyte.kosp.extensions.getUser
import de.randombyte.kosp.extensions.gray
import de.randombyte.kosp.extensions.toText
import de.randombyte.kosp.getServiceOrFail
import de.randombyte.lottery.commands.AddPotCommand
import de.randombyte.lottery.commands.BuyTicketCommand
import de.randombyte.lottery.commands.InfoCommand
import ninja.leaping.configurate.commented.CommentedConfigurationNode
import ninja.leaping.configurate.loader.ConfigurationLoader
import org.bstats.sponge.Metrics
import org.slf4j.Logger
import org.spongepowered.api.Sponge
import org.spongepowered.api.command.CommandResult
import org.spongepowered.api.command.args.CommandContext
import org.spongepowered.api.command.args.GenericArguments.integer
import org.spongepowered.api.command.args.GenericArguments.optional
import org.spongepowered.api.command.spec.CommandSpec
import org.spongepowered.api.config.DefaultConfig
import org.spongepowered.api.entity.living.player.Player
import org.spongepowered.api.event.Listener
import org.spongepowered.api.event.cause.Cause
import org.spongepowered.api.event.cause.EventContext
import org.spongepowered.api.event.game.GameReloadEvent
import org.spongepowered.api.event.game.state.GameInitializationEvent
import org.spongepowered.api.plugin.Plugin
import org.spongepowered.api.plugin.PluginContainer
import org.spongepowered.api.scheduler.Task
import org.spongepowered.api.service.economy.Currency
import org.spongepowered.api.service.economy.EconomyService
import org.spongepowered.api.text.Text
import java.math.BigDecimal
import java.time.Duration
import java.time.Instant
import java.util.*
import java.util.concurrent.TimeUnit
@Plugin(id = Lottery.ID, name = Lottery.NAME, version = Lottery.VERSION, authors = [(Lottery.AUTHOR)])
class Lottery @Inject constructor(
val logger: Logger,
@DefaultConfig(sharedRoot = true) configLoader: ConfigurationLoader<CommentedConfigurationNode>,
pluginContainer: PluginContainer,
private val bstats: Metrics
) {
companion object {
const val ID = "lottery"
const val NAME = "Lottery"
const val VERSION = "2.0.2"
const val AUTHOR = "RandomByte"
const val ROOT_PERMISSION = ID
}
val configManager = ConfigManager(
configLoader = configLoader,
clazz = Config::class.java,
simpleTextSerialization = true,
simpleTextTemplateSerialization = true,
simpleDurationSerialization = true)
val PLUGIN_CAUSE: Cause = Cause.builder().append(pluginContainer).build(EventContext.empty())
// Set on startup in setDurationUntilDraw()
lateinit var nextDraw: Instant
@Listener
fun onInit(event: GameInitializationEvent) {
configManager.generate()
Sponge.getCommandManager().register(this, CommandSpec.builder()
.child(CommandSpec.builder()
.permission("$ROOT_PERMISSION.ticket.buy")
.executor(BuyTicketCommand(configManager, PLUGIN_CAUSE))
.arguments(optional(integer("ticketAmount".toText())))
.build(), "buy")
.child(CommandSpec.builder()
.permission("$ROOT_PERMISSION.addpot")
.executor(AddPotCommand(configManager, PLUGIN_CAUSE))
.arguments(integer("amount".toText()))
.build(), "addpot")
.child(CommandSpec.builder()
.permission("$ROOT_PERMISSION.draw")
.executor(object : PlayerExecutedCommand() {
override fun executedByPlayer(player: Player, args: CommandContext): CommandResult {
draw(configManager.get())
return CommandResult.success()
}
})
.build(), "draw")
.child(CommandSpec.builder()
.executor(InfoCommand(configManager, durationUntilDraw = { getDurationUntilDraw() }))
.build(), "info")
.build(), "lottery", "lot")
val config = configManager.get()
// Manually set the duration because the draw task in resetTasks() may be executed too late
setDurationUntilDraw(config)
resetTasks(config)
logger.info("$NAME loaded: $VERSION")
}
@Listener
fun onReload(event: GameReloadEvent) {
configManager.generate()
resetTasks(configManager.get())
logger.info("Lottery reloaded!")
}
fun draw(config: Config) {
val ticketBuyers = config.internalData.boughtTickets.map { Collections.nCopies(it.value, it.key) }.flatten()
if (ticketBuyers.isEmpty()) {
broadcast("No tickets were bought, the draw is postponed!".gray())
return
}
Collections.shuffle(ticketBuyers) // Here comes the randomness
val winner = ticketBuyers.first()
playerWon(config, winner)
val drawEvent = DrawEvent(winner, config.calculatePot(), PLUGIN_CAUSE)
Sponge.getEventManager().post(drawEvent)
resetPot(config)
}
fun playerWon(config: Config, uuid: UUID) {
val playerName = uuid.getUser()?.name ?: "unknown"
val pot = config.calculatePot()
val defaultCurrency = getDefaultCurrency()
val message = config.messages.drawMessageBroadcast.apply(mapOf(
"winnerName" to playerName,
"pot" to pot,
"currencySymbol" to defaultCurrency.symbol,
"currencyName" to defaultCurrency.pluralDisplayName
)).build()
broadcast(message)
val economyService = getEconomyServiceOrFail()
economyService.getOrCreateAccount(uuid).get().deposit(economyService.defaultCurrency, BigDecimal(pot), PLUGIN_CAUSE)
}
fun resetPot(config: Config) {
val newInternalData = config.internalData.copy(pot = 0, boughtTickets = emptyMap())
val newConfig = config.copy(internalData = newInternalData)
configManager.save(newConfig)
}
fun getDurationUntilDraw(): Duration = Duration.between(Instant.now(), nextDraw)
fun setDurationUntilDraw(config : Config) {
nextDraw = Instant.ofEpochSecond(Instant.now().epochSecond + config.drawInterval.seconds)
}
fun resetTasks(config: Config) {
Sponge.getScheduler().getScheduledTasks(this).forEach { it.cancel() }
// Don't make the tasks async because it may happen that the broadcast and draw task are
// executed simultaneously. Irritating messages could be produced.
Task.builder()
.interval(config.drawInterval.seconds, TimeUnit.SECONDS)
.execute { ->
val currentConfig = configManager.get()
draw(currentConfig)
setDurationUntilDraw(currentConfig)
}.submit(this)
Task.builder()
.delay(5, TimeUnit.SECONDS) // First start: let economy plugin load
.interval(config.broadcasts.timedBroadcastInterval.seconds, TimeUnit.SECONDS)
.execute { ->
val currentConfig = configManager.get()
val currency = getDefaultCurrency()
val broadcastText = currentConfig.messages.broadcast.apply(mapOf(
"currencySymbol" to currency.symbol,
"currencyName" to currency.name,
"pot" to currentConfig.calculatePot()
)).build()
broadcast(broadcastText)
}.submit(this)
}
}
fun getEconomyServiceOrFail() = getServiceOrFail(EconomyService::class, "No economy plugin loaded!")
fun getDefaultCurrency(): Currency = getEconomyServiceOrFail().defaultCurrency
fun broadcast(text: Text) = Sponge.getServer().broadcastChannel.send(text) | src/main/kotlin/de/randombyte/lottery/Lottery.kt | 3812136884 |
package <%= appPackage %>.viewmodel
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider.Factory
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
@Singleton
class ViewModelFactory @Inject
constructor(private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>) : Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
var creator: Provider<out ViewModel>? = creators[modelClass]
if (creator == null) {
for ((key, value) in creators) {
if (modelClass.isAssignableFrom(key)) {
creator = value
break
}
}
}
if (creator == null) {
throw IllegalArgumentException("unknown model class " + modelClass)
}
try {
return creator.get() as T
} catch (e: Exception) {
throw RuntimeException(e)
}
}
} | generator-ssb/generators/templates/template-normal/app/src/main/kotlin/com/grayherring/temp/viewmodel/ViewModelFactory.kt | 287135329 |
/*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tealcube.minecraft.bukkit.mythicdrops.events
import com.tealcube.minecraft.bukkit.mythicdrops.api.events.MythicDropsCancellableEvent
import org.bukkit.entity.LivingEntity
import org.bukkit.event.HandlerList
import org.bukkit.inventory.ItemStack
class EntityEquipEvent(var itemStack: ItemStack, val livingEntity: LivingEntity) : MythicDropsCancellableEvent() {
companion object {
@JvmStatic
val handlerList = HandlerList()
}
override fun getHandlers(): HandlerList = handlerList
}
| src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/events/EntityEquipEvent.kt | 162858876 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.toolchain.tools
import com.intellij.execution.process.ProcessListener
import com.intellij.execution.process.ProcessOutput
import com.intellij.notification.NotificationType
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.rust.cargo.project.settings.toolchain
import org.rust.cargo.runconfig.wasmpack.WasmPackBuildTaskProvider.Companion.WASM_TARGET
import org.rust.cargo.toolchain.RsToolchainBase
import org.rust.cargo.util.DownloadResult
import org.rust.ide.actions.InstallComponentAction
import org.rust.ide.actions.InstallTargetAction
import org.rust.ide.notifications.showBalloon
import org.rust.openapiext.*
import org.rust.stdext.RsResult
import org.rust.stdext.capitalized
import org.rust.stdext.unwrapOrThrow
import java.nio.file.Path
private val LOG: Logger = logger<Rustup>()
val RsToolchainBase.isRustupAvailable: Boolean get() = hasExecutable(Rustup.NAME)
fun RsToolchainBase.rustup(cargoProjectDirectory: Path): Rustup? {
if (!isRustupAvailable) return null
return Rustup(this, cargoProjectDirectory)
}
class Rustup(toolchain: RsToolchainBase, private val projectDirectory: Path) : RsTool(NAME, toolchain) {
data class Component(val name: String, val isInstalled: Boolean) {
companion object {
fun from(line: String): Component {
val name = line.substringBefore(' ')
val isInstalled = line.substringAfter(' ') in listOf("(installed)", "(default)")
return Component(name, isInstalled)
}
}
}
data class Target(val name: String, val isInstalled: Boolean) {
companion object {
fun from(line: String): Target {
val name = line.substringBefore(' ')
val isInstalled = line.substringAfter(' ') in listOf("(installed)", "(default)")
return Target(name, isInstalled)
}
}
}
private fun listComponents(): List<Component> =
createBaseCommandLine(
"component", "list",
workingDirectory = projectDirectory
).execute(toolchain.executionTimeoutInMilliseconds)?.stdoutLines?.map { Component.from(it) }.orEmpty()
private fun listTargets(): List<Target> =
createBaseCommandLine(
"target", "list",
workingDirectory = projectDirectory
).execute(toolchain.executionTimeoutInMilliseconds)?.stdoutLines?.map { Target.from(it) }.orEmpty()
fun downloadStdlib(owner: Disposable? = null, listener: ProcessListener? = null): DownloadResult<VirtualFile> {
// Sometimes we have stdlib but don't have write access to install it (for example, github workflow)
if (needInstallComponent("rust-src")) {
val commandLine = createBaseCommandLine(
"component", "add", "rust-src",
workingDirectory = projectDirectory
)
val downloadProcessOutput = if (owner == null) {
commandLine.execute(null)
} else {
commandLine.execute(owner, listener = listener).ignoreExitCode().unwrapOrThrow()
}
if (downloadProcessOutput?.isSuccess != true) {
val message = "rustup failed: `${downloadProcessOutput?.stderr ?: ""}`"
LOG.warn(message)
return DownloadResult.Err(message)
}
}
val sources = toolchain.rustc().getStdlibFromSysroot(projectDirectory)
?: return DownloadResult.Err("Failed to find stdlib in sysroot")
LOG.info("stdlib path: ${sources.path}")
fullyRefreshDirectory(sources)
return DownloadResult.Ok(sources)
}
fun downloadComponent(owner: Disposable, componentName: String): DownloadResult<Unit> =
createBaseCommandLine(
"component", "add", componentName,
workingDirectory = projectDirectory
).execute(owner).convertResult()
fun downloadTarget(owner: Disposable, targetName: String): DownloadResult<Unit> =
createBaseCommandLine(
"target", "add", targetName,
workingDirectory = projectDirectory
).execute(owner).convertResult()
fun activeToolchainName(): String? {
val output = createBaseCommandLine("show", "active-toolchain", workingDirectory = projectDirectory)
.execute(toolchain.executionTimeoutInMilliseconds) ?: return null
if (!output.isSuccess) return null
// Expected outputs:
// 1.48.0-x86_64-apple-darwin (default)
// stable-x86_64-apple-darwin (overridden by '/path/to/rust-toolchain.toml')
// nightly-x86_64-apple-darwin (directory override for '/path/to/override/dir')
return output.stdout.substringBefore("(").trim()
}
private fun RsProcessResult<ProcessOutput>.convertResult() =
when (this) {
is RsResult.Ok -> DownloadResult.Ok(Unit)
is RsResult.Err -> {
val message = "rustup failed: `${err.message}`"
LOG.warn(message)
DownloadResult.Err(message)
}
}
private fun needInstallComponent(componentName: String): Boolean {
val isInstalled = listComponents()
.find { (name, _) -> name.startsWith(componentName) }
?.isInstalled
?: return false
return !isInstalled
}
private fun needInstallTarget(targetName: String): Boolean {
val isInstalled = listTargets()
.find { it.name == targetName }
?.isInstalled
?: return false
return !isInstalled
}
companion object {
const val NAME: String = "rustup"
fun checkNeedInstallClippy(project: Project, cargoProjectDirectory: Path): Boolean =
checkNeedInstallComponent(project, cargoProjectDirectory, "clippy")
fun checkNeedInstallRustfmt(project: Project, cargoProjectDirectory: Path): Boolean =
checkNeedInstallComponent(project, cargoProjectDirectory, "rustfmt")
fun checkNeedInstallWasmTarget(project: Project, cargoProjectDirectory: Path): Boolean =
checkNeedInstallTarget(project, cargoProjectDirectory, WASM_TARGET)
// We don't want to install the component if:
// 1. It is already installed
// 2. We don't have Rustup
// 3. Rustup doesn't have this component
private fun checkNeedInstallComponent(
project: Project,
cargoProjectDirectory: Path,
componentName: String
): Boolean {
val rustup = project.toolchain?.rustup(cargoProjectDirectory) ?: return false
val needInstall = rustup.needInstallComponent(componentName)
if (needInstall) {
project.showBalloon(
"${componentName.capitalized()} is not installed",
NotificationType.ERROR,
InstallComponentAction(cargoProjectDirectory, componentName)
)
}
return needInstall
}
fun checkNeedInstallTarget(
project: Project,
cargoProjectDirectory: Path,
targetName: String
): Boolean {
val rustup = project.toolchain?.rustup(cargoProjectDirectory) ?: return false
val needInstall = rustup.needInstallTarget(targetName)
if (needInstall) {
project.showBalloon(
"$targetName target is not installed",
NotificationType.ERROR,
InstallTargetAction(cargoProjectDirectory, targetName)
)
}
return needInstall
}
}
}
| src/main/kotlin/org/rust/cargo/toolchain/tools/Rustup.kt | 2802611111 |
package edu.csh.chase.kgeojson.coordinatereferencesystem
import edu.csh.chase.kjson.json
import java.net.URI
data public class LinkedCoordinateReferenceSystem(val href: URI, val linkType: String?) : CoordinateReferenceSystem(CoordinateReferenceSystemType.Link) {
override fun jsonSerialize(): String {
return json(
"type" to "link",
"properties" to json(
"href" to href.toString()
).putNotNull("type", linkType)
).toString()
}
} | src/main/kotlin/edu/csh/chase/kgeojson/coordinatereferencesystem/LinkedCoordinateReferenceSystem.kt | 3441559483 |
import kotlin.reflect.KClass
/**
* This annotation indicates what exceptions should be declared by a function when compiled to a JVM method.
*
* Example:
*
* ```
* Throws(IOException::class)
* fun readFile(name: String): String {...}
* ```
*/
class Throws
/**
* Check output of
* ``` brainfuck
* ++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.
* ```
*/
class ItDoesSomeObfuscatedThing | core/testdata/format/codeBlock.kt | 1234519889 |
package com.habitrpg.android.habitica.models.user
import com.habitrpg.android.habitica.models.BaseObject
interface OwnedObject : BaseObject {
var userID: String?
var key: String?
}
| Habitica/src/main/java/com/habitrpg/android/habitica/models/user/OwnedObject.kt | 2885912984 |
package org.tsdes.advanced.security.distributedsession.auth.db
import org.springframework.data.repository.CrudRepository
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
/**
* Created by arcuri82 on 08-Nov-17.
*/
@Service
@Transactional
class UserService(
private val userCrud: UserRepository,
private val passwordEncoder: PasswordEncoder
){
fun createUser(username: String, password: String, roles: Set<String> = setOf()) : Boolean{
try {
val hash = passwordEncoder.encode(password)
if (userCrud.existsById(username)) {
return false
}
val user = UserEntity(username, hash, roles.map{"ROLE_$it"}.toSet())
userCrud.save(user)
return true
} catch (e: Exception){
return false
}
}
}
interface UserRepository : CrudRepository<UserEntity, String>
| advanced/security/distributed-session/ds-auth/src/main/kotlin/org/tsdes/advanced/security/distributedsession/auth/db/UserService.kt | 2395398554 |
/*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE", "unused")
package org.jetbrains.anko
import android.app.AlertDialog
import android.app.Fragment
import android.app.ProgressDialog
import android.content.Context
import android.content.DialogInterface
inline fun AnkoContext<*>.alert(
message: String,
title: String? = null,
noinline init: (AlertBuilder<DialogInterface>.() -> Unit)? = null
) = ctx.alert(message, title, init)
inline fun Fragment.alert(
message: String,
title: String? = null,
noinline init: (AlertBuilder<DialogInterface>.() -> Unit)? = null
) = activity.alert(message, title, init)
fun Context.alert(
message: String,
title: String? = null,
init: (AlertBuilder<DialogInterface>.() -> Unit)? = null
): AlertBuilder<AlertDialog> {
return AndroidAlertBuilder(this).apply {
if (title != null) {
this.title = title
}
this.message = message
if (init != null) init()
}
}
inline fun AnkoContext<*>.alert(
message: Int,
title: Int? = null,
noinline init: (AlertBuilder<DialogInterface>.() -> Unit)? = null
) = ctx.alert(message, title, init)
inline fun Fragment.alert(
message: Int,
title: Int? = null,
noinline init: (AlertBuilder<DialogInterface>.() -> Unit)? = null
) = activity.alert(message, title, init)
fun Context.alert(
messageResource: Int,
titleResource: Int? = null,
init: (AlertBuilder<DialogInterface>.() -> Unit)? = null
): AlertBuilder<DialogInterface> {
return AndroidAlertBuilder(this).apply {
if (titleResource != null) {
this.titleResource = titleResource
}
this.messageResource = messageResource
if (init != null) init()
}
}
inline fun AnkoContext<*>.alert(noinline init: AlertBuilder<DialogInterface>.() -> Unit) = ctx.alert(init)
inline fun Fragment.alert(noinline init: AlertBuilder<DialogInterface>.() -> Unit) = activity.alert(init)
fun Context.alert(init: AlertBuilder<DialogInterface>.() -> Unit): AlertBuilder<DialogInterface> {
return AndroidAlertBuilder(this).apply { init() }
}
inline fun AnkoContext<*>.progressDialog(
message: Int? = null,
title: Int? = null,
noinline init: (ProgressDialog.() -> Unit)? = null
) = ctx.progressDialog(message, title, init)
inline fun Fragment.progressDialog(
message: Int? = null,
title: Int? = null,
noinline init: (ProgressDialog.() -> Unit)? = null
) = activity.progressDialog(message, title, init)
fun Context.progressDialog(
message: Int? = null,
title: Int? = null,
init: (ProgressDialog.() -> Unit)? = null
) = progressDialog(false, message?.let { getString(it) }, title?.let { getString(it) }, init)
inline fun AnkoContext<*>.indeterminateProgressDialog(
message: Int? = null,
title: Int? = null,
noinline init: (ProgressDialog.() -> Unit)? = null
) = ctx.indeterminateProgressDialog(message, title, init)
inline fun Fragment.indeterminateProgressDialog(
message: Int? = null,
title: Int? = null,
noinline init: (ProgressDialog.() -> Unit)? = null
) = activity.progressDialog(message, title, init)
fun Context.indeterminateProgressDialog(
message: Int? = null,
title: Int? = null,
init: (ProgressDialog.() -> Unit)? = null
) = progressDialog(true, message?.let { getString(it) }, title?.let { getString(it) }, init)
inline fun AnkoContext<*>.progressDialog(
message: String? = null,
title: String? = null,
noinline init: (ProgressDialog.() -> Unit)? = null
) = ctx.progressDialog(message, title, init)
inline fun Fragment.progressDialog(
message: String? = null,
title: String? = null,
noinline init: (ProgressDialog.() -> Unit)? = null
) = activity.progressDialog(message, title, init)
fun Context.progressDialog(
message: String? = null,
title: String? = null,
init: (ProgressDialog.() -> Unit)? = null
) = progressDialog(false, message, title, init)
inline fun AnkoContext<*>.indeterminateProgressDialog(
message: String? = null,
title: String? = null,
noinline init: (ProgressDialog.() -> Unit)? = null
) = ctx.indeterminateProgressDialog(message, title, init)
inline fun Fragment.indeterminateProgressDialog(
message: String? = null,
title: String? = null,
noinline init: (ProgressDialog.() -> Unit)? = null
) = activity.indeterminateProgressDialog(message, title, init)
fun Context.indeterminateProgressDialog(
message: String? = null,
title: String? = null,
init: (ProgressDialog.() -> Unit)? = null
) = progressDialog(true, message, title, init)
private fun Context.progressDialog(
indeterminate: Boolean,
message: String? = null,
title: String? = null,
init: (ProgressDialog.() -> Unit)? = null
) = ProgressDialog(this).apply {
isIndeterminate = indeterminate
if (!indeterminate) setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
if (message != null) setMessage(message)
if (title != null) setTitle(title)
if (init != null) init()
show()
} | anko/library/static/commons/src/dialogs/AndroidDialogs.kt | 2182447144 |
@file:JvmName("RxExtensions")
package org.signal.core.util.concurrent
import android.annotation.SuppressLint
import io.reactivex.rxjava3.core.Single
import java.lang.RuntimeException
/**
* Throw an [InterruptedException] if a [Single.blockingGet] call is interrupted. This can
* happen when being called by code already within an Rx chain that is disposed.
*
* [Single.blockingGet] is considered harmful and should not be used.
*/
@SuppressLint("UnsafeBlockingGet")
@Throws(InterruptedException::class)
fun <T : Any> Single<T>.safeBlockingGet(): T {
try {
return blockingGet()
} catch (e: RuntimeException) {
val cause = e.cause
if (cause is InterruptedException) {
throw cause
} else {
throw e
}
}
}
| core-util/src/main/java/org/signal/core/util/concurrent/RxExtensions.kt | 904655111 |
package com.baeldung.range
import org.junit.Test
import kotlin.test.assertEquals
class RangeTest {
@Test
fun testRange() {
assertEquals(listOf(1,2,3), (1.rangeTo(3).toList()))
}
@Test
fun testDownTo(){
assertEquals(listOf(3,2,1), (3.downTo(1).toList()))
}
@Test
fun testUntil(){
assertEquals(listOf(1,2), (1.until(3).toList()))
}
} | projects/tutorials-master/tutorials-master/core-kotlin-2/src/test/kotlin/com/baeldung/range/RangeTest.kt | 427817820 |
package com.tomclaw.drawa.stock.di
import android.content.Context
import android.os.Bundle
import com.tomclaw.drawa.core.Journal
import com.tomclaw.drawa.stock.RecordConverter
import com.tomclaw.drawa.stock.RecordConverterImpl
import com.tomclaw.drawa.stock.StockInteractor
import com.tomclaw.drawa.stock.StockInteractorImpl
import com.tomclaw.drawa.stock.StockItem
import com.tomclaw.drawa.stock.StockPresenter
import com.tomclaw.drawa.stock.StockPresenterImpl
import com.tomclaw.drawa.util.DataProvider
import com.tomclaw.drawa.util.PerActivity
import com.tomclaw.drawa.util.SchedulersFactory
import dagger.Module
import dagger.Provides
import java.io.File
@Module
class StockModule(private val context: Context,
private val presenterState: Bundle?) {
@Provides
@PerActivity
fun provideStockPresenter(interactor: StockInteractor,
dataProvider: DataProvider<StockItem>,
recordConverter: RecordConverter,
schedulers: SchedulersFactory): StockPresenter {
return StockPresenterImpl(interactor, dataProvider, recordConverter, schedulers, presenterState)
}
@Provides
@PerActivity
fun provideStockInteractor(journal: Journal,
schedulers: SchedulersFactory): StockInteractor {
return StockInteractorImpl(journal, schedulers)
}
@Provides
@PerActivity
fun provideStockItemDataProvider(): DataProvider<StockItem> {
return DataProvider()
}
@Provides
@PerActivity
fun provideRecordConverter(filesDir: File): RecordConverter {
return RecordConverterImpl(filesDir)
}
} | app/src/main/java/com/tomclaw/drawa/stock/di/StockModule.kt | 3982764490 |
/*
* Copyright (C) 2015 yvolk (Yuri Volkov), http://yurivolkov.com
*
* 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.andstatus.app.actor
import android.view.ContextMenu
import android.view.ContextMenu.ContextMenuInfo
import android.view.MenuItem
import android.view.View
import org.andstatus.app.R
import org.andstatus.app.activity.ActivityViewItem
import org.andstatus.app.note.NoteEditorContainer
import org.andstatus.app.origin.Origin
import org.andstatus.app.timeline.ContextMenuHeader
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.StringUtil
import org.andstatus.app.view.MyContextMenu
open class ActorContextMenu(val menuContainer: NoteEditorContainer, menuGroup: Int) : MyContextMenu(menuContainer.getActivity(), menuGroup) {
override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenuInfo?) {
val method = "onCreateContextMenu"
saveContextOfSelectedItem(v)
if (getViewItem().isEmpty) {
return
}
val actor = getViewItem().actor
if (!getMyContext().accounts.succeededForSameUser(actor).contains(getSelectedActingAccount())) {
setSelectedActingAccount(
getMyContext().accounts.firstOtherSucceededForSameUser(actor, getActingAccount())
)
}
var order = 0
try {
ContextMenuHeader(getActivity(), menu)
.setTitle(actor.toActorTitle())
.setSubtitle(getActingAccount().getAccountName())
val shortName = actor.getUsername()
if (actor.groupType == GroupType.LIST_MEMBERS) {
ActorContextMenuItem.LIST_MEMBERS.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.list_members, shortName))
} else if (actor.groupType.isGroupLike) {
ActorContextMenuItem.GROUP_NOTES.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.group_notes, shortName))
} else if (actor.isIdentified()) {
ActorContextMenuItem.NOTES_BY_ACTOR.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.menu_item_user_messages, shortName))
if (actor.origin.originType.hasListsOfUser) {
ActorContextMenuItem.LISTS.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.lists_of_user, shortName))
}
ActorContextMenuItem.FRIENDS.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.friends_of, shortName))
ActorContextMenuItem.FOLLOWERS.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.followers_of, shortName))
if (getActingAccount().actor.notSameUser(actor)) {
if (getActingAccount().isFollowing(actor)) {
ActorContextMenuItem.STOP_FOLLOWING.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.menu_item_stop_following_user, shortName))
} else {
ActorContextMenuItem.FOLLOW.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.menu_item_follow_user, shortName))
}
if (menuContainer.getNoteEditor()?.isVisible() == false) {
ActorContextMenuItem.POST_TO.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.post_to, shortName))
}
}
when (getMyContext().accounts.succeededForSameUser(actor).size) {
0, 1 -> {
}
2 -> ActorContextMenuItem.ACT_AS_FIRST_OTHER_ACCOUNT.addTo(menu, menuGroup, order++,
StringUtil.format(
getActivity(), R.string.menu_item_act_as_user,
getMyContext().accounts
.firstOtherSucceededForSameUser(actor, getActingAccount())
.getShortestUniqueAccountName()))
else -> ActorContextMenuItem.ACT_AS.addTo(menu, menuGroup, order++, R.string.menu_item_act_as)
}
}
if (actor.canGetActor()) {
ActorContextMenuItem.GET_ACTOR.addTo(menu, menuGroup, order++, R.string.get_user)
}
} catch (e: Exception) {
MyLog.i(this, method, e)
}
}
fun onContextItemSelected(item: MenuItem): Boolean {
val ma = getActingAccount()
return if (ma.isValid) {
val contextMenuItem: ActorContextMenuItem = ActorContextMenuItem.fromId(item.getItemId())
MyLog.v(this) {
("onContextItemSelected: " + contextMenuItem + "; account="
+ ma.getAccountName() + "; actor=" + getViewItem().actor.uniqueName)
}
contextMenuItem.execute(this)
} else {
false
}
}
fun getViewItem(): ActorViewItem {
if (mViewItem.isEmpty) {
return ActorViewItem.EMPTY
}
return if (mViewItem is ActivityViewItem) {
getViewItem(mViewItem as ActivityViewItem)
} else mViewItem as ActorViewItem
}
protected open fun getViewItem(activityViewItem: ActivityViewItem): ActorViewItem {
return activityViewItem.getObjActorItem()
}
fun getOrigin(): Origin {
return getViewItem().actor.origin
}
}
| app/src/main/kotlin/org/andstatus/app/actor/ActorContextMenu.kt | 1618939975 |
/*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.debugger.remote
import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.openapi.application.ApplicationManager
import com.tang.intellij.lua.debugger.LogConsoleType
import com.tang.intellij.lua.debugger.remote.commands.DebugCommand
import com.tang.intellij.lua.debugger.remote.commands.DefaultCommand
import java.io.IOException
import java.io.OutputStreamWriter
import java.net.SocketException
import java.nio.ByteBuffer
import java.nio.channels.SocketChannel
import java.nio.charset.Charset
import java.util.*
import java.util.regex.Pattern
class MobClient(private val socketChannel: SocketChannel, private val listener: MobServerListener) {
private var isStopped: Boolean = false
private val commands = LinkedList<DebugCommand>()
private var currentCommandWaitForResp: DebugCommand? = null
private var streamWriter: OutputStreamWriter? = null
private val socket = socketChannel.socket()
private val receiveBufferSize = 1024 * 1024
init {
socket.receiveBufferSize = receiveBufferSize
ApplicationManager.getApplication().executeOnPooledThread {
doReceive()
}
ApplicationManager.getApplication().executeOnPooledThread {
doSend()
}
}
private fun doSend() {
try {
streamWriter = OutputStreamWriter(socket.getOutputStream(), Charset.forName("UTF-8"))
while (socket.isConnected) {
if (isStopped) break
var command: DebugCommand
while (commands.size > 0 && currentCommandWaitForResp == null) {
if (currentCommandWaitForResp == null) {
command = commands.poll()
command.debugProcess = listener.process
command.write(this)
streamWriter!!.write("\n")
streamWriter!!.flush()
if (command.getRequireRespLines() > 0)
currentCommandWaitForResp = command
}
}
Thread.sleep(5)
}
} catch (e: SocketException) {
//e.message?.let { listener.error(it) }
} catch (e: Exception) {
e.message?.let { listener.error(it) }
} finally {
onClosed()
}
}
private fun doReceive() {
try {
var readSize: Int
val bf = ByteBuffer.allocate(receiveBufferSize)
while (!isStopped) {
readSize = socketChannel.read(bf)
if (readSize > 0) {
var begin = 0
for (i in 1..readSize + 1) {
if (bf[i - 1].toInt() == '\n'.toInt()) {
onResp(String(bf.array(), begin, i))
begin = i
}
}
if (begin < readSize) {
onResp(String(bf.array(), begin, readSize))
}
bf.clear()
}
}
} catch (e: IOException) {
onSocketClosed()
} catch (e: Exception) {
e.message?.let { listener.error(it) }
}
}
private fun onResp(data: String) {
val cmd = currentCommandWaitForResp
if (cmd != null) {
val eat = cmd.handle(data)
if (eat > 0) {
if (cmd.isFinished())
currentCommandWaitForResp = null
return
}
}
val pattern = Pattern.compile("(\\d+) (\\w+)( (.+))?")
val matcher = pattern.matcher(data)
if (matcher.find()) {
val code = Integer.parseInt(matcher.group(1))
//String status = matcher.group(2);
val context = matcher.group(4)
listener.handleResp(this, code, context)
}
}
private fun onSocketClosed() {
listener.onDisconnect(this)
}
@Throws(IOException::class)
fun write(data: String) {
streamWriter!!.write(data)
//println("send:" + data)
}
fun stop() {
try {
streamWriter?.write("done\n")
} catch (ignored: IOException) {
}
currentCommandWaitForResp = null
try {
socket.close()
} catch (ignored: Exception) {
}
onClosed()
isStopped = true
}
private fun onClosed() {
if (!isStopped) {
isStopped = true
listener.println("Disconnected.", LogConsoleType.NORMAL, ConsoleViewContentType.SYSTEM_OUTPUT)
}
}
fun sendAddBreakpoint(file: String, line: Int) {
addCommand("SETB $file $line")
}
fun sendRemoveBreakpoint(file: String, line: Int) {
addCommand("DELB $file $line")
}
fun addCommand(command: String, rl: Int = 1) {
addCommand(DefaultCommand(command, rl))
}
fun addCommand(command: DebugCommand) {
commands.add(command)
}
} | src/main/java/com/tang/intellij/lua/debugger/remote/MobClient.kt | 3926442917 |
package de.plapadoo.orgparser
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
/**
* Created by philipp on 8/7/16.
*/
class DocumentParserTest {
@Test
fun `document with all elements combined`() {
val document = "* headline\n" +
"SCHEDULED: <2016-08-16 Tue 15:32 ++3h> DEADLINE: [2016-08-16 Tue 15:32 ++4h]\n" +
":PROPERTIES:\n" +
":LAST_REPEAT: [2016-08-17 Wed 22:26]\n" +
":WITHOUT_VALUE:\n" +
":WITH_PLUS+:\n" +
":END:\n" +
":SOMEBLOCK:\n" +
"somecontents\n" +
":END:\n" +
"#+BEGIN: name params\n" +
"contents\n" +
"#+END:\n" +
"paragraph\n" +
"[fn:haha] a wild footnote appears\n" +
"\n" +
"------\n" +
"- a list item\n" +
" a) [ ]a list item\n" +
" 1. tag :: a list item\n" +
"\n" +
"#+BEGIN_QUOTE\n" +
"lol\n" +
"#+END_QUOTE\n" +
""
val doc = documentParser().parse(document)
assertThat(toOrg(doc)).isEqualTo(document)
}
@Test
fun `document with table`() {
val document = "* headline\n" +
"|---+-----|\n" +
"| a | b c |\n" +
"|---+-----|\n" +
"done\n"
val doc = documentParser().parse(document)
assertThat(toOrg(doc)).isEqualTo(document)
}
} | src/test/java/de/plapadoo/orgparser/DocumentParserTest.kt | 2499218932 |
package com.commonsense.android.kotlin.base.extensions.collections
import com.commonsense.android.kotlin.test.*
import org.junit.jupiter.api.*
/**
* Created by Kasper Tvede on 21-05-2018.
* Purpose:
*/
internal class PrimitiveExtensionsKtTest {
@Test
fun onTrue() {
false.onTrue { failTest("should not call on false") }.assert(false, "value should be returned")
var counter = 0
true.onTrue { counter += 1 }.assert(true, "value should be returned")
counter.assert(1, "should have executed the onTrue content")
}
@Test
fun onFalse() {
true.onFalse { failTest("should not call on false") }.assert(true, "value should be returned")
var counter = 0
false.onFalse { counter += 1 }.assert(false, "value should be returned")
counter.assert(1, "should have executed the onFalse content")
}
@Test
fun ifTrue() {
false.ifTrue { failTest("should not call on false") }.assert(false, "value should be returned")
var counter = 0
true.ifTrue { counter += 1 }.assert(true, "value should be returned")
counter.assert(1, "should have executed the onTrue content")
}
@Test
fun ifFalse() {
true.ifFalse { failTest("should not call on false") }.assert(true, "value should be returned")
var counter = 0
false.ifFalse { counter += 1 }.assert(false, "value should be returned")
counter.assert(1, "should have executed the onFalse content")
}
@Test
fun map() {
false.map(1, -1).assert(-1)
true.map("a", "b").assert("a")
}
@Test
fun mapLazy() {
true.mapLazy({
42
}, {
failTest("should have lazy evaluation")
20
}).assert(42)
false.mapLazy({
failTest("should have lazy evaluation")
20
}, {
42
}).assert(42)
}
@Test
fun ifNull() {
val optString: String? = ""
optString.ifNull { failTest("should not be called on non null") }
var counter = 0
val optInt: Int? = null
optInt.ifNull { counter += 1 }
counter.assert(1, "should have executed branch.")
}
@Test
fun ifNotNull() {
val optString: String? = ""
var counter = 0
optString.ifNotNull { counter += 1 }
counter.assert(1, "should have executed branch.")
val optInt: Int? = null
optInt.ifNotNull { failTest("should not be called on null") }
}
@Test
fun getLength() {
val range = 0 until 20
range.length.assert(20)
val weirdRange = 20 until 21
weirdRange.length.assert(1)
val wrongRange = 20 until 20
wrongRange.length.assert(0)
}
@Test
fun getLargest() {
val range = 0 until 20
range.largest.assert(19, "largest element is 20 - 1 = 19(due to until )")
val weirdRange = 20 until 21
weirdRange.largest.assert(20)
val wrongRange = 20 until 20
wrongRange.largest.assert(20)
}
} | base/src/test/kotlin/com/commonsense/android/kotlin/base/extensions/collections/PrimitiveExtensionsKtTest.kt | 998812555 |
// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.panelmatch.common.crypto
import com.google.protobuf.ByteString
import java.io.Serializable
data class AsymmetricKeyPair(
val serializedPublicKey: ByteString,
val serializedPrivateKey: ByteString,
) : Serializable
| src/main/kotlin/org/wfanet/panelmatch/common/crypto/AsymmetricKeyPair.kt | 1622981518 |
package org.jetbrains.haskell.parser
import com.intellij.psi.tree.IElementType
import org.jetbrains.grammar.HaskellLexerTokens
import java.util.Arrays
import java.util.HashSet
import java.util.ArrayList
import org.jetbrains.haskell.parser.lexer.HaskellLexer
import com.intellij.psi.TokenType
import org.jetbrains.haskell.parser.token.NEW_LINE
import org.jetbrains.haskell.parser.token.END_OF_LINE_COMMENT
import org.jetbrains.haskell.parser.token.BLOCK_COMMENT
import java.io.PrintStream
import com.intellij.lang.PsiBuilder
import com.intellij.lang.WhitespaceSkippedCallback
import org.jetbrains.grammar.dumb.NonTerminalTree
import org.jetbrains.grammar.dumb.TerminalTree
import org.jetbrains.haskell.parser.token.PRAGMA
import org.jetbrains.haskell.parser.token.COMMENTS
val INDENT_TOKENS = HashSet<IElementType>(Arrays.asList(
HaskellLexerTokens.DO,
HaskellLexerTokens.OF,
HaskellLexerTokens.LET,
HaskellLexerTokens.WHERE))
class IntStack(val indent: Int,
val parent: IntStack?)
public fun getCachedTokens(lexer: HaskellLexer, stream: PrintStream?): CachedTokens {
val tokens = ArrayList<IElementType>()
val starts = ArrayList<Int>()
val indents = ArrayList<Int>()
val lineStarts = ArrayList<Boolean>()
var currentIndent = 0
var isLineStart = true
stream?.println("-------------------")
while (lexer.getTokenType() != null) {
val tokenType = lexer.getTokenType()
if (!COMMENTS.contains(tokenType) && tokenType != TokenType.WHITE_SPACE) {
if (tokenType == NEW_LINE) {
currentIndent = 0
isLineStart = true
stream?.println()
} else {
tokens.add(tokenType)
starts.add(lexer.getTokenStart())
indents.add(currentIndent)
lineStarts.add(isLineStart)
isLineStart = false
stream?.print("${tokenType} ")
}
}
if (tokenType != NEW_LINE) {
for (ch in lexer.getTokenText()) {
if (ch == '\t') {
currentIndent += 8;
} else {
currentIndent += 1;
}
}
}
lexer.advance();
}
stream?.println("-------------------")
return CachedTokens(tokens, starts, indents, lineStarts)
}
public fun getCachedTokens(builder: PsiBuilder): CachedTokens {
val tokens = ArrayList<IElementType>()
val starts = ArrayList<Int>()
val indents = ArrayList<Int>()
val lineStarts = ArrayList<Boolean>()
var currentIndent = 0
var isLineStart = true
builder.setWhitespaceSkippedCallback(object : WhitespaceSkippedCallback {
override fun onSkip(type: IElementType?, start: Int, end: Int) {
if (type == NEW_LINE) {
currentIndent = 0
isLineStart = true
} else {
val charSequence = builder.getOriginalText()
for (i in start..(end-1)) {
if (charSequence.charAt(i) == '\t') {
currentIndent += 8;
} else {
currentIndent += 1;
}
}
}
}
})
while (builder.getTokenType() != null) {
tokens.add(builder.getTokenType())
starts.add(builder.getCurrentOffset())
indents.add(currentIndent)
lineStarts.add(isLineStart)
isLineStart = false
currentIndent += builder.getTokenText()!!.length()
builder.advanceLexer()
}
return CachedTokens(tokens, starts, indents, lineStarts)
}
public fun newLexerState(tokens: CachedTokens): LexerState {
if (tokens.tokens.firstOrNull() == HaskellLexerTokens.MODULE) {
return LexerState(tokens, 0, 0, null, null)
} else {
return LexerState(tokens, 0, 0, null, IntStack(0, null))
}
}
public class CachedTokens(val tokens: List<IElementType>,
val starts: List<Int>,
val indents: ArrayList<Int>,
val lineStart: ArrayList<Boolean>) {
}
public class LexerState(val tokens: CachedTokens,
val position: Int,
val readedLexemNumber: Int,
val currentToken: HaskellTokenType?,
val indentStack: IntStack?) {
fun match(token: HaskellTokenType): Boolean {
if (currentToken != null) {
return currentToken == token
}
if (position < tokens.tokens.size() && tokens.tokens[position] == token) {
return true
}
return false
}
fun next(): LexerState {
if (currentToken != null) {
if (currentToken == HaskellLexerTokens.VCCURLY && indentStack != null) {
return checkIndent(position)
}
return LexerState(tokens, position, readedLexemNumber + 1, null, indentStack)
}
if (position == tokens.tokens.size()) {
return last()
}
if (tokens.tokens[position] == HaskellLexerTokens.OCURLY) {
return LexerState(tokens,
position + 1,
readedLexemNumber + 1,
null,
IntStack(-1, indentStack))
}
val nextPosition = position + 1
if (nextPosition == tokens.tokens.size()) {
return last()
}
if (INDENT_TOKENS.contains(tokens.tokens[position]) &&
tokens.tokens[nextPosition] != HaskellLexerTokens.OCURLY) {
val indent = tokens.indents[nextPosition]
return LexerState(tokens,
nextPosition,
readedLexemNumber + 1,
HaskellLexerTokens.VOCURLY,
IntStack(indent, indentStack))
}
return checkIndent(nextPosition)
}
private fun last(): LexerState {
if (indentStack != null) {
return LexerState(tokens,
tokens.tokens.size(),
readedLexemNumber + 1,
HaskellLexerTokens.VCCURLY,
indentStack.parent)
} else {
return LexerState(tokens, tokens.tokens.size(), readedLexemNumber, null, null)
}
}
private fun checkIndent(position: Int): LexerState {
if (position == tokens.tokens.size()) {
return last()
}
if (tokens.lineStart[position]) {
val indent = tokens.indents[position]
if (indentStack != null) {
if (indentStack.indent == indent) {
return LexerState(tokens, position, readedLexemNumber + 1, HaskellLexerTokens.SEMI, indentStack)
} else if (indentStack.indent < indent) {
return checkCurly(position)
} else {
return LexerState(tokens, position, readedLexemNumber + 1, HaskellLexerTokens.VCCURLY, indentStack.parent)
}
} else {
//if (0 == indent) {
// return LexerState(tokens, position, lexemNumber + 1, HaskellLexerTokens.SEMI, indentStack)
//} else {
// return checkCurly(position)
//}
}
}
return checkCurly(position)
}
private fun checkCurly(nextPosition: Int): LexerState {
if (tokens.tokens[nextPosition] == HaskellLexerTokens.CCURLY) {
if (indentStack!!.indent > -1) {
return LexerState(tokens, nextPosition - 1, readedLexemNumber + 1, HaskellLexerTokens.VCCURLY, indentStack.parent)
}
return LexerState(tokens, nextPosition, readedLexemNumber + 1, null, indentStack.parent)
}
return LexerState(tokens, nextPosition, readedLexemNumber + 1, null, indentStack)
}
fun dropIndent() = LexerState(
tokens,
position,
readedLexemNumber + 1,
HaskellLexerTokens.VCCURLY,
indentStack?.parent)
fun getToken(): IElementType? {
if (currentToken != null) {
return currentToken
}
if (position < tokens.tokens.size()) {
return tokens.tokens[position];
}
return null;
}
fun eof(): Boolean {
return currentToken == null && position == tokens.tokens.size();
}
} | plugin/src/org/jetbrains/haskell/parser/LexerState.kt | 745008242 |
package com.pinchotsoft.spiffy.mapping
import com.pinchotsoft.spiffy.ReflectionHelper
import com.pinchotsoft.spiffy.isPrimitive
import java.lang.reflect.Constructor
import java.sql.ResultSet
class ResultContext(rs: ResultSet, clazz: Class<*>) {
private val columns: List<String>
private val calculatedColumnAvailability = HashMap<String, Boolean>()
private var _constructor: Constructor<*>? = null
private var _isDataClass = false
val isPrimitiveType: Boolean
val isDataClass: Boolean
get() = _isDataClass
val constructor: Constructor<*>?
get() = _constructor
init {
val metadata = rs.metaData
columns = (1..metadata.columnCount).map { metadata.getColumnName(it) }
isPrimitiveType = isPrimitive(clazz)
if (!isPrimitiveType) {
val cons = ReflectionHelper.getClassConstructor(clazz, true)
if (cons != null) {
_constructor = cons
} else {
_constructor = ReflectionHelper.getClassConstructor(clazz, false)!!
_isDataClass = true
}
}
}
fun hasColumn(columnName: String): Boolean {
if (!calculatedColumnAvailability.containsKey(columnName))
calculatedColumnAvailability.put(columnName, columns.any { it.equals(columnName, true) })
return calculatedColumnAvailability[columnName]!!
}
} | src/main/kotlin/com/pinchotsoft/spiffy/mapping/ResultContext.kt | 3128022982 |
package xyz.gnarbot.gnar.commands.music
import xyz.gnarbot.gnar.commands.*
import xyz.gnarbot.gnar.commands.template.CommandTemplate
import xyz.gnarbot.gnar.commands.template.annotations.Description
import xyz.gnarbot.gnar.utils.Utils
import java.time.Duration
@Command(
aliases = ["jump", "seek"],
usage = "(to|forward|backward) (time)",
description = "Set the time marker of the music playback."
)
@BotInfo(
id = 65,
category = Category.MUSIC,
scope = Scope.VOICE
)
class JumpCommand : CommandTemplate() {
@Description("Set the time marker of the player.")
fun to(context: Context, duration: Duration) {
val manager = context.bot.players.getExisting(context.guild)!!
manager.player.playingTrack.position = duration.toMillis().coerceIn(0, manager.player.playingTrack.duration)
context.send().info("The position of the track has been set to ${Utils.getTimestamp(manager.player.playingTrack.position)}.").queue()
}
@Description("Move the time marker forward.")
fun forward(context: Context, duration: Duration) {
val manager = context.bot.players.getExisting(context.guild)!!
manager.player.playingTrack.position = (manager.player.playingTrack.position + duration.toMillis())
.coerceIn(0, manager.player.playingTrack.duration)
context.send().info("The position of the track has been set to ${Utils.getTimestamp(manager.player.playingTrack.position)}.").queue()
}
@Description("Move the time marker backward.")
fun backward(context: Context, duration: Duration) {
val manager = context.bot.players.getExisting(context.guild)!!
manager.player.playingTrack.position = (manager.player.playingTrack.position - duration.toMillis())
.coerceIn(0, manager.player.playingTrack.duration)
context.send().embed("Jump Backward") {
desc { "The position of the track has been set to ${Utils.getTimestamp(manager.player.playingTrack.position)}." }
}.action().queue()
}
override fun execute(context: Context, label: String, args: Array<out String>) {
val manager = context.bot.players.getExisting(context.guild)
if (manager == null) {
context.send().error("There's no music player in this guild.\n$PLAY_MESSAGE").queue()
return
}
val botChannel = context.selfMember.voiceState?.channel
if (botChannel == null) {
context.send().error("The bot is not currently in a channel.\n$PLAY_MESSAGE").queue()
return
}
if (context.voiceChannel != botChannel) {
context.send().error("You're not in the same channel as the context.bot.").queue()
return
}
if (manager.player.playingTrack == null) {
context.send().error("The player is not playing anything.").queue()
return
}
if (!manager.player.playingTrack.isSeekable) {
context.send().error("You can't change the time marker on this track.").queue()
return
}
super.execute(context, label, args)
}
}
| src/main/kotlin/xyz/gnarbot/gnar/commands/music/JumpCommand.kt | 4023298072 |
/**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plsqlopen.checks
import org.junit.jupiter.api.Test
import org.sonar.plsqlopen.checks.verifier.PlSqlCheckVerifier
class VariableInitializationWithFunctionCallCheckTest : BaseCheckTest() {
@Test
fun test() {
PlSqlCheckVerifier.verify(getPath("variable_initialization_with_function_call.sql"), VariableInitializationWithFunctionCallCheck())
}
}
| zpa-checks/src/test/kotlin/org/sonar/plsqlopen/checks/VariableInitializationWithFunctionCallCheckTest.kt | 1735947908 |
package org.xdty.callerinfo.di
import dagger.Component
import org.xdty.callerinfo.di.modules.AppModule
import org.xdty.callerinfo.di.modules.PhoneStatusModule
import org.xdty.callerinfo.receiver.IncomingCall.PhoneStateListener
import javax.inject.Singleton
@Singleton
@Component(modules = [PhoneStatusModule::class, AppModule::class])
interface PhoneStatusComponent {
fun inject(phoneStateListener: PhoneStateListener)
} | app/src/main/java/org/xdty/callerinfo/di/PhoneStatusComponent.kt | 2195251506 |
package com.empowerops.getoptk
import junit.framework.AssertionFailedError
import org.assertj.core.api.Assertions.*
import org.junit.Test
import java.lang.UnsupportedOperationException
class ErrorExamples {
@Test fun `when two cli classes have args that map to the same name should get configuration error`(){
//setup & act
val ex = assertThrows<ConfigurationException> {
emptyArray<String>().parsedAs("prog") { DuplicateInferredNamesArgBundle() }
}
//assert
assertThat(ex.messages.single().message).isEqualTo(
"the options 'val excess: String by getValueOpt()' and 'val extra: String by getValueOpt()' have the same short name 'e'."
)
}
class DuplicateInferredNamesArgBundle : CLI(){
val extra: String by getValueOpt<String>()
val excess: String by getValueOpt()
}
@Test fun `when using the wrong type to destructure should generate unconsumed tokens warnings`(){
//setup & act
val ex = assertThrows<ParseFailedException>{
arrayOf("--eh", "hello_world", "1.0").parsedAs("prog") { ConfusedTypeArgBundle() }
}
//assert
assertThat(ex.message).isEqualTo(
"""Failed to parse value for val eh: A by getValueOpt()
|prog --eh hello_world 1.0
|at: ~~~
|java.lang.NumberFormatException: For input string: "1.0"
""".trimMargin()
)
assertThat(ex.cause).isInstanceOf(NumberFormatException::class.java)
}
data class A(val name: String, val x: Int)
data class B(val name: String, val x: Double)
class ConfusedTypeArgBundle: CLI(){
val eh: A by getOpt()
}
@Test fun `when attempting to use the wrong option name should generate nice error messages`(){
//setup
val args = arrayOf("--name", "bob")
//act
val ex = assertThrows<ParseFailedException> { args.parsedAs("prog") { ValueOfAbleCLI() } }
//assert
assertThat(ex.message).isEqualTo(
"""unknown option 'name', expected 'parsable', 'help'
|prog --name bob
|at: ~~~~
""".trimMargin()
)
}
class ValueOfAbleCLI : CLI(){
val parsable: ValueOfAble by getValueOpt()
}
data class ValueOfAble(val name: String) {
companion object {
fun valueOf(str: String) = ValueOfAble(str + "_thingy")
}
}
@Test fun `when custom converter throws should recover and display proper error message`(){
//setup
val args = arrayOf("--problem", "sam")
//act
val ex = assertThrows<ParseFailedException> { args.parsedAs("prog") { BadConvertingCLI() }}
//assert
assertThat(ex.message).isEqualTo(
"""Failed to parse value for val problem: String by getValueOpt()
|prog --problem sam
|at: ~~~
|java.lang.UnsupportedOperationException: no sam's allowed!
""".trimMargin()
)
assertThat(ex.cause).isInstanceOf(UnsupportedOperationException::class.java)
}
class BadConvertingCLI: CLI(){
val problem: String by getValueOpt {
converter = { when(it){
"sam" -> throw UnsupportedOperationException("no sam's allowed!")
"bob" -> "bobbo"
else -> TODO()
}}
}
}
}
| src/test/kotlin/com/empowerops/getoptk/ErrorExamples.kt | 2946878830 |
package pl.shockah.godwit.geom.polygon
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import pl.shockah.godwit.LazyDirty
import pl.shockah.godwit.ObservableList
import pl.shockah.godwit.geom.*
class ClosedPolygon(
points: List<Vec2>
) : Polygon(points), Shape.Filled {
var triangulator: Triangulator = BasicTriangulator()
private val dirtyTriangles = LazyDirty {
triangulator.triangulate(points) ?: throw IllegalStateException("Cannot triangulate polygon.")
}
val triangles: List<Triangle> by dirtyTriangles
override val lines: List<Line>
get() {
val result = mutableListOf<Line>()
for (i in 0 until points.size) {
result += Line(points[i], points[(i + 1) % points.size])
}
return result
}
constructor(vararg points: Vec2) : this(points.toList())
init {
super.points.listeners += object : ObservableList.ChangeListener<MutableVec2> {
override fun onAddedToList(element: MutableVec2) {
dirtyTriangles.invalidate()
}
override fun onRemovedFromList(element: MutableVec2) {
dirtyTriangles.invalidate()
}
}
}
companion object {
init {
Shape.registerCollisionHandler { a: ClosedPolygon, b: ClosedPolygon ->
for (aTriangle in a.triangles) {
for (bTriangle in b.triangles) {
if (aTriangle collides bTriangle)
return@registerCollisionHandler true
}
}
return@registerCollisionHandler false
}
Shape.registerCollisionHandler { polygon: ClosedPolygon, triangle: Triangle ->
for (polygonTriangle in polygon.triangles) {
if (triangle collides polygonTriangle)
return@registerCollisionHandler true
}
return@registerCollisionHandler false
}
Shape.registerCollisionHandler { polygon: ClosedPolygon, line: Line ->
for (polygonTriangle in polygon.triangles) {
if (line collides polygonTriangle)
return@registerCollisionHandler true
}
return@registerCollisionHandler false
}
}
}
override fun copy(): ClosedPolygon {
return ClosedPolygon(points).apply {
triangulator = [email protected]
}
}
override fun contains(point: Vec2): Boolean {
for (triangle in triangles) {
if (point in triangle)
return true
}
return false
}
override fun ease(other: Polygon, f: Float): ClosedPolygon {
if (other !is ClosedPolygon)
throw IllegalArgumentException()
if (points.size != other.points.size)
throw IllegalArgumentException()
return ClosedPolygon(points.mapIndexed { index, point -> point.ease(other.points[index], f) })
}
private fun draw(shapes: ShapeRenderer) {
val vertices = FloatArray(points.size * 2)
for (i in 0 until points.size) {
vertices[i * 2] = points[i].x
vertices[i * 2 + 1] = points[i].y
}
shapes.polygon(vertices)
}
override fun drawFilled(shapes: ShapeRenderer) {
draw(shapes)
}
override fun drawOutline(shapes: ShapeRenderer) {
draw(shapes)
}
} | core/src/pl/shockah/godwit/geom/polygon/ClosedPolygon.kt | 1863020317 |
package com.intfocus.template.dashboard.kpi.bean
import java.io.Serializable
/**
* Created by liuruilin on 2017/6/21.
*/
class KpiGroupItemData : Serializable {
var high_light: KpiGroupItemHighLight? = null
var chart_data: List<*>? = null
}
| app/src/main/java/com/intfocus/template/dashboard/kpi/bean/KpiGroupItemData.kt | 1698707232 |
package de.westnordost.streetcomplete.data.osm.upload
import de.westnordost.osmapi.map.data.Element
import de.westnordost.osmapi.map.data.LatLon
import de.westnordost.streetcomplete.data.osm.osmquest.OsmElementQuestType
interface UploadableInChangeset {
val source: String
val osmElementQuestType: OsmElementQuestType<*>
val elementType: Element.Type
val elementId: Long
val position: LatLon
}
| app/src/main/java/de/westnordost/streetcomplete/data/osm/upload/UploadableInChangeset.kt | 1978941884 |
package de.westnordost.streetcomplete.quests.building_underground
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.SimpleOverpassQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddIsBuildingUnderground(o: OverpassMapDataDao) : SimpleOverpassQuestType<Boolean>(o) {
override val tagFilters = "ways, relations with building and !location and layer~-[0-9]+"
override val commitMessage = "Determine whatever building is fully underground"
override val icon = R.drawable.ic_quest_building_underground
override fun getTitle(tags: Map<String, String>): Int {
val hasName = tags.containsKey("name")
return if (hasName)
R.string.quest_building_underground_name_title
else
R.string.quest_building_underground_title
}
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("location", if (answer) "underground" else "surface")
}
}
| app/src/main/java/de/westnordost/streetcomplete/quests/building_underground/AddIsBuildingUnderground.kt | 2781396950 |
package com.fieldbook.tracker.database.dao
import android.content.ContentValues
import com.fieldbook.tracker.database.*
import com.fieldbook.tracker.database.models.ObservationUnitModel
import java.util.HashMap
import com.fieldbook.tracker.database.Migrator.Study
import com.fieldbook.tracker.database.Migrator.ObservationUnit
class ObservationUnitDao {
companion object {
fun checkUnique(values: HashMap<String, String>): Boolean? = withDatabase { db ->
var result = true
db.query(ObservationUnit.tableName,
select = arrayOf("observation_unit_db_id")).toTable().forEach {
if (it["observation_unit_db_id"] in values.keys) {
result = false
}
}
result
} ?: false
fun getAll(): Array<ObservationUnitModel> = withDatabase { db ->
arrayOf(*db.query(ObservationUnit.tableName)
.toTable()
.map { ObservationUnitModel(it) }
.toTypedArray())
} ?: emptyArray()
fun getAll(eid: Int): Array<ObservationUnitModel> = withDatabase { db ->
arrayOf(*db.query(ObservationUnit.tableName,
where = "${Study.FK} = ?",
whereArgs = arrayOf(eid.toString())).toTable()
.map { ObservationUnitModel(it) }
.toTypedArray())
} ?: emptyArray()
/**
* Updates a given observation unit row with a geo coordinates string.
*/
fun updateObservationUnit(unit: ObservationUnitModel, geoCoordinates: String) = withDatabase { db ->
db.update(ObservationUnit.tableName,
ContentValues().apply {
put("geo_coordinates", geoCoordinates)
},
"${ObservationUnit.PK} = ?", arrayOf(unit.internal_id_observation_unit.toString()))
}
}
} | app/src/main/java/com/fieldbook/tracker/database/dao/ObservationUnitDao.kt | 58955276 |
/*
* Copyright (C) 2020-2022 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.saxon.tests.lang
import com.intellij.lang.LanguageASTFactory
import com.intellij.openapi.extensions.PluginId
import com.intellij.psi.PsiElement
import org.hamcrest.CoreMatchers.`is`
import org.junit.jupiter.api.*
import uk.co.reecedunn.intellij.plugin.core.extensions.registerServiceInstance
import uk.co.reecedunn.intellij.plugin.core.tests.assertion.assertThat
import uk.co.reecedunn.intellij.plugin.core.tests.parser.ParsingTestCase
import uk.co.reecedunn.intellij.plugin.saxon.lang.*
import uk.co.reecedunn.intellij.plugin.xpath.parser.XPathASTFactory
import uk.co.reecedunn.intellij.plugin.xpath.parser.XPathParserDefinition
import uk.co.reecedunn.intellij.plugin.xpm.lang.configuration.XpmLanguageConfiguration
import uk.co.reecedunn.intellij.plugin.xpm.lang.diagnostics.XpmDiagnostics
import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidation
import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidator
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryModule
import uk.co.reecedunn.intellij.plugin.xquery.lang.XQuery
import uk.co.reecedunn.intellij.plugin.xquery.parser.XQueryASTFactory
import uk.co.reecedunn.intellij.plugin.xquery.parser.XQueryParserDefinition
import uk.co.reecedunn.intellij.plugin.xquery.project.settings.XQueryProjectSettings
import xqt.platform.intellij.xpath.XPath
@Suppress("ClassName")
@DisplayName("XQuery IntelliJ Plugin - Syntax Validation - Saxon")
class SaxonSyntaxValidatorTest :
ParsingTestCase<XQueryModule>("xqy", XQueryParserDefinition(), XPathParserDefinition()),
XpmDiagnostics {
override val pluginId: PluginId = PluginId.getId("SaxonSyntaxValidatorTest")
// region ParsingTestCase
override fun registerServicesAndExtensions() {
super.registerServicesAndExtensions()
project.registerServiceInstance(XQueryProjectSettings::class.java, XQueryProjectSettings())
addExplicitExtension(LanguageASTFactory.INSTANCE, XPath, XPathASTFactory())
addExplicitExtension(LanguageASTFactory.INSTANCE, XQuery, XQueryASTFactory())
XpmSyntaxValidator.register(this, SaxonSyntaxValidator)
}
// endregion
// region XpmDiagnostics
val report: StringBuffer = StringBuffer()
@BeforeEach
fun reset() {
report.delete(0, report.length)
}
override fun error(element: PsiElement, code: String, description: String) {
if (report.isNotEmpty()) {
report.append('\n')
}
report.append("E $code(${element.textOffset}:${element.textOffset + element.textLength}): $description")
}
override fun warning(element: PsiElement, code: String, description: String) {
if (report.isNotEmpty()) {
report.append('\n')
}
report.append("W $code(${element.textOffset}:${element.textOffset + element.textLength}): $description")
}
val validator: XpmSyntaxValidation = XpmSyntaxValidation()
// endregion
@Suppress("PrivatePropertyName")
private val SAXON_HE_9_8 = XpmLanguageConfiguration(XQuery.VERSION_1_0, SaxonVersion(SaxonHE, 9, 8, ""))
@Suppress("PrivatePropertyName")
private val SAXON_HE_9_9 = XpmLanguageConfiguration(XQuery.VERSION_1_0, SaxonVersion(SaxonHE, 9, 9, ""))
@Suppress("PrivatePropertyName")
private val SAXON_HE_10_0 = XpmLanguageConfiguration(XQuery.VERSION_1_0, SaxonVersion(SaxonHE, 10, 0, ""))
@Suppress("PrivatePropertyName")
private val SAXON_PE_9_7 = XpmLanguageConfiguration(XQuery.VERSION_1_0, SaxonPE.VERSION_9_7)
@Suppress("PrivatePropertyName")
private val SAXON_PE_9_8 = XpmLanguageConfiguration(XQuery.VERSION_1_0, SaxonPE.VERSION_9_8)
@Suppress("PrivatePropertyName")
private val SAXON_PE_9_9 = XpmLanguageConfiguration(XQuery.VERSION_1_0, SaxonPE.VERSION_9_9)
@Suppress("PrivatePropertyName")
private val SAXON_PE_10_0 = XpmLanguageConfiguration(XQuery.VERSION_1_0, SaxonPE.VERSION_10_0)
@Suppress("PrivatePropertyName")
private val SAXON_EE_9_7 = XpmLanguageConfiguration(XQuery.VERSION_1_0, SaxonEE.VERSION_9_7)
@Suppress("PrivatePropertyName")
private val SAXON_EE_9_8 = XpmLanguageConfiguration(XQuery.VERSION_1_0, SaxonEE.VERSION_9_8)
@Suppress("PrivatePropertyName")
private val SAXON_EE_9_9 = XpmLanguageConfiguration(XQuery.VERSION_1_0, SaxonEE.VERSION_9_9)
@Suppress("PrivatePropertyName")
private val SAXON_EE_10_0 = XpmLanguageConfiguration(XQuery.VERSION_1_0, SaxonEE.VERSION_10_0)
@Nested
@DisplayName("XQuery IntelliJ Plugin EBNF (11) OrExpr")
internal inner class AndExpr {
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>("1 and 2, 3 andAlso 4")[0]
validator.configuration = SAXON_HE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(11:18): Saxon Home Edition 9.9 does not support Saxon Professional Edition 9.9, or Saxon Enterprise Edition 9.9 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE >= 9.9")
fun supportedPE() {
val file = parse<XQueryModule>("1 and 2, 3 andAlso 4")[0]
validator.configuration = SAXON_PE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 9.9")
fun notSupportedPE() {
val file = parse<XQueryModule>("1 and 2, 3 andAlso 4")[0]
validator.configuration = SAXON_PE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(11:18): Saxon Professional Edition 9.8 does not support Saxon Professional Edition 9.9, or Saxon Enterprise Edition 9.9 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE >= 9.9")
fun supportedEE() {
val file = parse<XQueryModule>("1 and 2, 3 andAlso 4")[0]
validator.configuration = SAXON_EE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 9.9")
fun notSupportedEE() {
val file = parse<XQueryModule>("1 and 2, 3 andAlso 4")[0]
validator.configuration = SAXON_EE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(11:18): Saxon Enterprise Edition 9.8 does not support Saxon Professional Edition 9.9, or Saxon Enterprise Edition 9.9 constructs.
""".trimIndent()
)
)
}
}
@Nested
@DisplayName("XQuery IntelliJ Plugin EBNF (19) ItemTypeDecl")
internal inner class ItemTypeDecl {
@Test
@DisplayName("XQuery 4.0 ED syntax")
fun xquery40() {
val file = parse<XQueryModule>("declare item-type a:test = xs:string;")[0]
validator.configuration = SAXON_HE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>("declare type a:test = xs:string;")[0]
validator.configuration = SAXON_HE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(8:12): Saxon Home Edition 9.8 does not support Saxon Professional Edition 9.8, or Saxon Enterprise Edition 9.8 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE >= 9.8")
fun supportedPE() {
val file = parse<XQueryModule>("declare type a:test = xs:string;")[0]
validator.configuration = SAXON_PE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 9.8")
fun notSupportedPE() {
val file = parse<XQueryModule>("declare type a:test = xs:string;")[0]
validator.configuration = SAXON_PE_9_7
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(8:12): Saxon Professional Edition 9.7 does not support Saxon Professional Edition 9.8, or Saxon Enterprise Edition 9.8 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE >= 9.8")
fun supportedEE() {
val file = parse<XQueryModule>("declare type a:test = xs:string;")[0]
validator.configuration = SAXON_EE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 9.8")
fun notSupportedEE() {
val file = parse<XQueryModule>("declare type a:test = xs:string;")[0]
validator.configuration = SAXON_EE_9_7
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(8:12): Saxon Enterprise Edition 9.7 does not support Saxon Professional Edition 9.8, or Saxon Enterprise Edition 9.8 constructs.
""".trimIndent()
)
)
}
}
@Nested
@DisplayName("XQuery 4.0 ED EBNF (233) LocalUnionType")
internal inner class LocalUnionType {
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>("1 instance of union(xs:integer, xs:double)")[0]
validator.configuration = SAXON_HE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(14:19): Saxon Home Edition 9.8 does not support Saxon Professional Edition 9.8, or Saxon Enterprise Edition 9.8 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE >= 9.8")
fun supportedPE() {
val file = parse<XQueryModule>("1 instance of union(xs:integer, xs:double)")[0]
validator.configuration = SAXON_PE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 9.8")
fun notSupportedPE() {
val file = parse<XQueryModule>("1 instance of union(xs:integer, xs:double)")[0]
validator.configuration = SAXON_PE_9_7
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(14:19): Saxon Professional Edition 9.7 does not support Saxon Professional Edition 9.8, or Saxon Enterprise Edition 9.8 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE >= 9.8")
fun supportedEE() {
val file = parse<XQueryModule>("1 instance of union(xs:integer, xs:double)")[0]
validator.configuration = SAXON_EE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 9.8")
fun notSupportedEE() {
val file = parse<XQueryModule>("1 instance of union(xs:integer, xs:double)")[0]
validator.configuration = SAXON_EE_9_7
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(14:19): Saxon Enterprise Edition 9.7 does not support Saxon Professional Edition 9.8, or Saxon Enterprise Edition 9.8 constructs.
""".trimIndent()
)
)
}
}
@Nested
@DisplayName("XQuery IntelliJ Plugin EBNF (23) RecordTest")
internal inner class RecordTest {
@Test
@DisplayName("XQuery 4.0 ED record test")
fun xquery40() {
val file = parse<XQueryModule>("1 instance of record(a as xs:string, b as .., \"c\"? as xs:int, *)")[0]
validator.configuration = SAXON_HE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Nested
@DisplayName("tuple type")
internal inner class TupleType {
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>("1 instance of tuple(a: xs:string, b: xs:string)")[0]
validator.configuration = SAXON_HE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(14:19): Saxon Home Edition 9.8 does not support Saxon Professional Edition 9.8, or Saxon Enterprise Edition 9.8 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE >= 9.8")
fun supportedPE() {
val file = parse<XQueryModule>("1 instance of tuple(a: xs:string, b: xs:string)")[0]
validator.configuration = SAXON_PE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 9.8")
fun notSupportedPE() {
val file = parse<XQueryModule>("1 instance of tuple(a: xs:string, b: xs:string)")[0]
validator.configuration = SAXON_PE_9_7
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(14:19): Saxon Professional Edition 9.7 does not support Saxon Professional Edition 9.8, or Saxon Enterprise Edition 9.8 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE >= 9.8")
fun supportedEE() {
val file = parse<XQueryModule>("1 instance of tuple(a: xs:string, b: xs:string)")[0]
validator.configuration = SAXON_EE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 9.8")
fun notSupportedEE() {
val file = parse<XQueryModule>("1 instance of tuple(a: xs:string, b: xs:string)")[0]
validator.configuration = SAXON_EE_9_7
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(14:19): Saxon Enterprise Edition 9.7 does not support Saxon Professional Edition 9.8, or Saxon Enterprise Edition 9.8 constructs.
""".trimIndent()
)
)
}
}
@Nested
@DisplayName("extensible tuple type")
internal inner class ExtensibleTupleType {
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>("1 instance of tuple(a, *)")[0]
validator.configuration = SAXON_HE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(23:24): Saxon Home Edition 9.9 does not support Saxon Professional Edition 9.9, or Saxon Enterprise Edition 9.9 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE >= 9.9")
fun supportedPE() {
val file = parse<XQueryModule>("1 instance of tuple(a, *)")[0]
validator.configuration = SAXON_PE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 9.9")
fun notSupportedPE() {
val file = parse<XQueryModule>("1 instance of tuple(a, *)")[0]
validator.configuration = SAXON_PE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(23:24): Saxon Professional Edition 9.8 does not support Saxon Professional Edition 9.9, or Saxon Enterprise Edition 9.9 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE >= 9.9")
fun supportedEE() {
val file = parse<XQueryModule>("1 instance of tuple(a, *)")[0]
validator.configuration = SAXON_EE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 9.9")
fun notSupportedEE() {
val file = parse<XQueryModule>("1 instance of tuple(a, *)")[0]
validator.configuration = SAXON_EE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(23:24): Saxon Enterprise Edition 9.8 does not support Saxon Professional Edition 9.9, or Saxon Enterprise Edition 9.9 constructs.
""".trimIndent()
)
)
}
}
}
@Nested
@DisplayName("XQuery IntelliJ Plugin EBNF (24) FieldDeclaration")
internal inner class FieldDeclaration {
@Nested
@DisplayName("optional tuple field")
internal inner class Optional {
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>("1 instance of tuple(a?: xs:string, b? : xs:string)")[0]
validator.configuration = SAXON_HE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(14:19): Saxon Home Edition 9.9 does not support Saxon Professional Edition 9.8, or Saxon Enterprise Edition 9.8 constructs.
E XPST0003(21:23): Saxon Home Edition 9.9 does not support Saxon Professional Edition 9.9, or Saxon Enterprise Edition 9.9 constructs.
E XPST0003(36:37): Saxon Home Edition 9.9 does not support Saxon Professional Edition 9.9, or Saxon Enterprise Edition 9.9 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE >= 9.9")
fun supportedPE() {
val file = parse<XQueryModule>("1 instance of tuple(a?: xs:string, b? : xs:string)")[0]
validator.configuration = SAXON_PE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 9.9")
fun notSupportedPE() {
val file = parse<XQueryModule>("1 instance of tuple(a?: xs:string, b? : xs:string)")[0]
validator.configuration = SAXON_PE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(21:23): Saxon Professional Edition 9.8 does not support Saxon Professional Edition 9.9, or Saxon Enterprise Edition 9.9 constructs.
E XPST0003(36:37): Saxon Professional Edition 9.8 does not support Saxon Professional Edition 9.9, or Saxon Enterprise Edition 9.9 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE >= 9.9")
fun supportedEE() {
val file = parse<XQueryModule>("1 instance of tuple(a?: xs:string, b? : xs:string)")[0]
validator.configuration = SAXON_EE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 9.9")
fun notSupportedEE() {
val file = parse<XQueryModule>("1 instance of tuple(a?: xs:string, b? : xs:string)")[0]
validator.configuration = SAXON_EE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(21:23): Saxon Enterprise Edition 9.8 does not support Saxon Professional Edition 9.9, or Saxon Enterprise Edition 9.9 constructs.
E XPST0003(36:37): Saxon Enterprise Edition 9.8 does not support Saxon Professional Edition 9.9, or Saxon Enterprise Edition 9.9 constructs.
""".trimIndent()
)
)
}
}
@Nested
@DisplayName("as SequenceType")
internal inner class AsSequenceType {
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>("1 instance of tuple(a as xs:string, b? as xs:string)")[0]
validator.configuration = SAXON_HE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(14:19): Saxon Home Edition 9.9 does not support Saxon Professional Edition 9.8, or Saxon Enterprise Edition 9.8 constructs.
E XPST0003(22:24): Saxon Home Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
E XPST0003(37:38): Saxon Home Edition 9.9 does not support Saxon Professional Edition 9.9, or Saxon Enterprise Edition 9.9 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE >= 10.0")
fun supportedPE() {
val file = parse<XQueryModule>("1 instance of tuple(a as xs:string, b? as xs:string)")[0]
validator.configuration = SAXON_PE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 10.0")
fun notSupportedPE() {
val file = parse<XQueryModule>("1 instance of tuple(a as xs:string, b? as xs:string)")[0]
validator.configuration = SAXON_PE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(22:24): Saxon Professional Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE >= 10.0")
fun supportedEE() {
val file = parse<XQueryModule>("1 instance of tuple(a as xs:string, b? as xs:string)")[0]
validator.configuration = SAXON_EE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 10.0")
fun notSupportedEE() {
val file = parse<XQueryModule>("1 instance of tuple(a as xs:string, b? as xs:string)")[0]
validator.configuration = SAXON_EE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(22:24): Saxon Enterprise Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
}
}
@Nested
@DisplayName("XQuery IntelliJ Plugin EBNF (79) OrExpr")
internal inner class OrExpr {
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>("1 or 2, 3 orElse 4")[0]
validator.configuration = SAXON_HE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(10:16): Saxon Home Edition 9.9 does not support Saxon Professional Edition 9.9, or Saxon Enterprise Edition 9.9 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE >= 9.9")
fun supportedPE() {
val file = parse<XQueryModule>("1 or 2, 3 orElse 4")[0]
validator.configuration = SAXON_PE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 9.9")
fun notSupportedPE() {
val file = parse<XQueryModule>("1 or 2, 3 orElse 4")[0]
validator.configuration = SAXON_PE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(10:16): Saxon Professional Edition 9.8 does not support Saxon Professional Edition 9.9, or Saxon Enterprise Edition 9.9 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE >= 9.9")
fun supportedEE() {
val file = parse<XQueryModule>("1 or 2, 3 orElse 4")[0]
validator.configuration = SAXON_EE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 9.9")
fun notSupportedEE() {
val file = parse<XQueryModule>("1 or 2, 3 orElse 4")[0]
validator.configuration = SAXON_EE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(10:16): Saxon Enterprise Edition 9.8 does not support Saxon Professional Edition 9.9, or Saxon Enterprise Edition 9.9 constructs.
""".trimIndent()
)
)
}
}
@Nested
@DisplayName("XQuery IntelliJ Plugin EBNF (81) ContextItemFunctionExpr")
internal inner class ContextItemFunctionExpr {
@Nested
@DisplayName("dot syntax")
internal inner class DotSyntax {
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>(".{1} , . {2}")[0]
validator.configuration = SAXON_HE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(0:2): Saxon Home Edition 10.0 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
E XPST0003(7:8): Saxon Home Edition 10.0 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE >= 10.0")
fun supportedPE() {
val file = parse<XQueryModule>(".{1} , . {2}")[0]
validator.configuration = SAXON_PE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 10.0")
fun notSupportedPE() {
val file = parse<XQueryModule>(".{1} , . {2}")[0]
validator.configuration = SAXON_PE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(0:2): Saxon Professional Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
E XPST0003(7:8): Saxon Professional Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE >= 10.0")
fun supportedEE() {
val file = parse<XQueryModule>(".{1} , . {2}")[0]
validator.configuration = SAXON_EE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 10.0")
fun notSupportedEE() {
val file = parse<XQueryModule>(".{1} , . {2}")[0]
validator.configuration = SAXON_EE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(0:2): Saxon Enterprise Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
E XPST0003(7:8): Saxon Enterprise Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
}
@Nested
@DisplayName("fn syntax")
internal inner class FnSyntax {
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>("fn{1}")[0]
validator.configuration = SAXON_HE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(0:2): Saxon Home Edition 9.9 does not support Saxon Professional Edition 9.9-9.9, or Saxon Enterprise Edition 9.9-9.9 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE == 9.9")
fun supportedPE() {
val file = parse<XQueryModule>("fn{1}")[0]
validator.configuration = SAXON_PE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 9.9")
fun ltSupportedPE() {
val file = parse<XQueryModule>("fn{1}")[0]
validator.configuration = SAXON_PE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(0:2): Saxon Professional Edition 9.8 does not support Saxon Professional Edition 9.9-9.9, or Saxon Enterprise Edition 9.9-9.9 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE > 9.9")
fun gtSupportedPE() {
val file = parse<XQueryModule>("fn{1}")[0]
validator.configuration = SAXON_PE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(0:2): Saxon Professional Edition 10.0 does not support Saxon Professional Edition 9.9-9.9, or Saxon Enterprise Edition 9.9-9.9 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE == 9.9")
fun supportedEE() {
val file = parse<XQueryModule>("fn{1}")[0]
validator.configuration = SAXON_EE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 9.9")
fun ltSupportedEE() {
val file = parse<XQueryModule>("fn{1}")[0]
validator.configuration = SAXON_EE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(0:2): Saxon Enterprise Edition 9.8 does not support Saxon Professional Edition 9.9-9.9, or Saxon Enterprise Edition 9.9-9.9 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE > 9.9")
fun gtSupportedEE() {
val file = parse<XQueryModule>("fn{1}")[0]
validator.configuration = SAXON_EE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(0:2): Saxon Enterprise Edition 10.0 does not support Saxon Professional Edition 9.9-9.9, or Saxon Enterprise Edition 9.9-9.9 constructs.
""".trimIndent()
)
)
}
}
}
@Nested
@DisplayName("XQuery 4.0 ED EBNF (215) ElementTest ; XQuery 4.0 ED EBNF (128) NameTest")
internal inner class ElementTest {
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>(
"""
1 instance of element(), (: XPath/XQuery :)
2 instance of element(ns:test), (: XPath/XQuery :)
3 instance of element(test:*) (: Saxon :)
""".trimIndent()
)[0]
validator.configuration = SAXON_HE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(117:123): Saxon Home Edition 10.0 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 wildcard local or prefix part in 'ElementTest' constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE >= 10.0")
fun supportedPE() {
val file = parse<XQueryModule>(
"""
1 instance of element(), (: XPath/XQuery :)
2 instance of element(ns:test), (: XPath/XQuery :)
3 instance of element(test:*) (: Saxon :)
""".trimIndent()
)[0]
validator.configuration = SAXON_PE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 10.0")
fun notSupportedPE() {
val file = parse<XQueryModule>(
"""
1 instance of element(), (: XPath/XQuery :)
2 instance of element(ns:test), (: XPath/XQuery :)
3 instance of element(test:*) (: Saxon :)
""".trimIndent()
)[0]
validator.configuration = SAXON_PE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(117:123): Saxon Professional Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 wildcard local or prefix part in 'ElementTest' constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE >= 10.0")
fun supportedEE() {
val file = parse<XQueryModule>(
"""
1 instance of element(), (: XPath/XQuery :)
2 instance of element(ns:test), (: XPath/XQuery :)
3 instance of element(test:*) (: Saxon :)
""".trimIndent()
)[0]
validator.configuration = SAXON_EE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 10.0")
fun notSupportedEE() {
val file = parse<XQueryModule>(
"""
1 instance of element(), (: XPath/XQuery :)
2 instance of element(ns:test), (: XPath/XQuery :)
3 instance of element(test:*) (: Saxon :)
""".trimIndent()
)[0]
validator.configuration = SAXON_EE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(117:123): Saxon Enterprise Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 wildcard local or prefix part in 'ElementTest' constructs.
""".trimIndent()
)
)
}
}
@Nested
@DisplayName("XQuery 4.0 ED EBNF (212) AttributeTest ; XQuery 4.0 ED EBNF (128) NameTest")
internal inner class AttributeTest {
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>(
"""
1 instance of attribute(), (: XPath/XQuery :)
2 instance of attribute(ns:test), (: XPath/XQuery :)
3 instance of attribute(test:*) (: Saxon :)
""".trimIndent()
)[0]
validator.configuration = SAXON_HE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(123:129): Saxon Home Edition 10.0 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 wildcard local or prefix part in 'AttributeTest' constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE >= 10.0")
fun supportedPE() {
val file = parse<XQueryModule>(
"""
1 instance of attribute(), (: XPath/XQuery :)
2 instance of attribute(ns:test), (: XPath/XQuery :)
3 instance of attribute(test:*) (: Saxon :)
""".trimIndent()
)[0]
validator.configuration = SAXON_PE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 10.0")
fun notSupportedPE() {
val file = parse<XQueryModule>(
"""
1 instance of attribute(), (: XPath/XQuery :)
2 instance of attribute(ns:test), (: XPath/XQuery :)
3 instance of attribute(test:*) (: Saxon :)
""".trimIndent()
)[0]
validator.configuration = SAXON_PE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(123:129): Saxon Professional Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 wildcard local or prefix part in 'AttributeTest' constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE >= 10.0")
fun supportedEE() {
val file = parse<XQueryModule>(
"""
1 instance of attribute(), (: XPath/XQuery :)
2 instance of attribute(ns:test), (: XPath/XQuery :)
3 instance of attribute(test:*) (: Saxon :)
""".trimIndent()
)[0]
validator.configuration = SAXON_EE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 10.0")
fun notSupportedEE() {
val file = parse<XQueryModule>(
"""
1 instance of attribute(), (: XPath/XQuery :)
2 instance of attribute(ns:test), (: XPath/XQuery :)
3 instance of attribute(test:*) (: Saxon :)
""".trimIndent()
)[0]
validator.configuration = SAXON_EE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(123:129): Saxon Enterprise Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 wildcard local or prefix part in 'AttributeTest' constructs.
""".trimIndent()
)
)
}
}
@Nested
@DisplayName("XQuery 4.0 ED EBNF (53) ForMemberBinding")
internal inner class ForMemberBinding {
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>("for member \$x in \$y return \$x")[0]
validator.configuration = SAXON_HE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(4:10): Saxon Home Edition 10.0 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE >= 10.0")
fun supportedPE() {
val file = parse<XQueryModule>("for member \$x in \$y return \$x")[0]
validator.configuration = SAXON_PE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 10.0")
fun notSupportedPE() {
val file = parse<XQueryModule>("for member \$x in \$y return \$x")[0]
validator.configuration = SAXON_PE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(4:10): Saxon Professional Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE >= 10.0")
fun supportedEE() {
val file = parse<XQueryModule>("for member \$x in \$y return \$x")[0]
validator.configuration = SAXON_EE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 10.0")
fun notSupportedEE() {
val file = parse<XQueryModule>("for member \$x in \$y return \$x")[0]
validator.configuration = SAXON_EE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(4:10): Saxon Enterprise Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
}
@Nested
@DisplayName("XQuery 4.0 ED EBNF (96) OtherwiseExpr")
internal inner class OtherwiseExpr {
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>("1 otherwise 2")[0]
validator.configuration = SAXON_HE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(2:11): Saxon Home Edition 10.0 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE >= 10.0")
fun supportedPE() {
val file = parse<XQueryModule>("1 otherwise 2")[0]
validator.configuration = SAXON_PE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 10.0")
fun notSupportedPE() {
val file = parse<XQueryModule>("1 otherwise 2")[0]
validator.configuration = SAXON_PE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(2:11): Saxon Professional Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE >= 10.0")
fun supportedEE() {
val file = parse<XQueryModule>("1 otherwise 2")[0]
validator.configuration = SAXON_EE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 10.0")
fun notSupportedEE() {
val file = parse<XQueryModule>("1 otherwise 2")[0]
validator.configuration = SAXON_EE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(2:11): Saxon Enterprise Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
}
@Nested
@DisplayName("XQuery IntelliJ Plugin EBNF (116) TypeAlias")
internal inner class TypeAlias {
@Nested
@DisplayName("tilde syntax")
internal inner class TildeSyntax {
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>("1 instance of ~a:type-name")[0]
validator.configuration = SAXON_HE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(14:15): Saxon Home Edition 9.8 does not support Saxon Professional Edition 9.8-9.9, or Saxon Enterprise Edition 9.8-9.9 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE >= 9.8")
fun supportedPE() {
val file = parse<XQueryModule>("1 instance of ~a:type-name")[0]
validator.configuration = SAXON_PE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 9.8")
fun notSupportedPE() {
val file = parse<XQueryModule>("1 instance of ~a:type-name")[0]
validator.configuration = SAXON_PE_9_7
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(14:15): Saxon Professional Edition 9.7 does not support Saxon Professional Edition 9.8-9.9, or Saxon Enterprise Edition 9.8-9.9 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE >= 9.8")
fun supportedEE() {
val file = parse<XQueryModule>("1 instance of ~a:type-name")[0]
validator.configuration = SAXON_EE_9_8
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 9.8")
fun notSupportedEE() {
val file = parse<XQueryModule>("1 instance of ~a:type-name")[0]
validator.configuration = SAXON_EE_9_7
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(14:15): Saxon Enterprise Edition 9.7 does not support Saxon Professional Edition 9.8-9.9, or Saxon Enterprise Edition 9.8-9.9 constructs.
""".trimIndent()
)
)
}
}
@Nested
@DisplayName("type alias")
internal inner class TypeAlias {
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>("1 instance of type(a:type-name)")[0]
validator.configuration = SAXON_HE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(14:18): Saxon Home Edition 10.0 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE >= 10.0")
fun supportedPE() {
val file = parse<XQueryModule>("1 instance of type(a:type-name)")[0]
validator.configuration = SAXON_PE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 10.0")
fun notSupportedPE() {
val file = parse<XQueryModule>("1 instance of type(a:type-name)")[0]
validator.configuration = SAXON_PE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(14:18): Saxon Professional Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE >= 10.0")
fun supportedEE() {
val file = parse<XQueryModule>("1 instance of type(a:type-name)")[0]
validator.configuration = SAXON_EE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 10.0")
fun notSupportedEE() {
val file = parse<XQueryModule>("1 instance of type(a:type-name)")[0]
validator.configuration = SAXON_EE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(14:18): Saxon Enterprise Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
}
}
@Nested
@DisplayName("XQuery IntelliJ Plugin EBNF (117) LambdaFunctionExpr")
internal inner class LambdaFunctionExpr {
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>("_{1} , _ {2}")[0]
validator.configuration = SAXON_HE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(0:2): Saxon Home Edition 10.0 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
E XPST0003(7:8): Saxon Home Edition 10.0 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE >= 10.0")
fun supportedPE() {
val file = parse<XQueryModule>("_{1} , _ {2}")[0]
validator.configuration = SAXON_PE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 10.0")
fun notSupportedPE() {
val file = parse<XQueryModule>("_{1} , _ {2}")[0]
validator.configuration = SAXON_PE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(0:2): Saxon Professional Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
E XPST0003(7:8): Saxon Professional Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE >= 10.0")
fun supportedEE() {
val file = parse<XQueryModule>("_{1} , _ {2}")[0]
validator.configuration = SAXON_EE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 10.0")
fun notSupportedEE() {
val file = parse<XQueryModule>("_{1} , _ {2}")[0]
validator.configuration = SAXON_EE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(0:2): Saxon Enterprise Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
E XPST0003(7:8): Saxon Enterprise Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
}
@Nested
@DisplayName("XQuery IntelliJ Plugin EBNF (118) ParamRef")
internal inner class ParamRef {
@Test
@DisplayName("Saxon HE")
fun notSupportedHE() {
val file = parse<XQueryModule>("\$1234")[0]
validator.configuration = SAXON_HE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(1:5): Saxon Home Edition 10.0 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon PE >= 10.0")
fun supportedPE() {
val file = parse<XQueryModule>("\$1234")[0]
validator.configuration = SAXON_PE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon PE < 10.0")
fun notSupportedPE() {
val file = parse<XQueryModule>("\$1234")[0]
validator.configuration = SAXON_PE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(1:5): Saxon Professional Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
@Test
@DisplayName("Saxon EE >= 10.0")
fun supportedEE() {
val file = parse<XQueryModule>("\$1234")[0]
validator.configuration = SAXON_EE_10_0
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(report.toString(), `is`(""))
}
@Test
@DisplayName("Saxon EE < 10.0")
fun notSupportedEE() {
val file = parse<XQueryModule>("\$1234")[0]
validator.configuration = SAXON_EE_9_9
validator.validate(file, this@SaxonSyntaxValidatorTest)
assertThat(
report.toString(), `is`(
"""
E XPST0003(1:5): Saxon Enterprise Edition 9.9 does not support Saxon Professional Edition 10.0, or Saxon Enterprise Edition 10.0 constructs.
""".trimIndent()
)
)
}
}
}
| src/plugin-saxon/test/uk/co/reecedunn/intellij/plugin/saxon/tests/lang/SaxonSyntaxValidatorTests.kt | 989916623 |
import kotlin.test.*
import kotlin.comparisons.*
fun box() {
val values = generateSequence(3) { n -> if (n > 0) n - 1 else null }
val expected = listOf(3, 2, 1, 0)
assertEquals(expected, values.toList())
assertEquals(expected, values.toList(), "Iterating sequence second time yields the same result")
}
| backend.native/tests/external/stdlib/collections/SequenceTest/sequenceFromFunctionWithInitialValue.kt | 3235424796 |
package org.stepik.android.view.injection.code_preference
import dagger.Binds
import dagger.Module
import dagger.Provides
import org.stepik.android.cache.base.database.AppDatabase
import org.stepik.android.cache.code_preference.CodePreferenceCacheDataSourceImpl
import org.stepik.android.cache.code_preference.dao.CodePreferenceDao
import org.stepik.android.data.code_preference.repository.CodePreferenceRepositoryImpl
import org.stepik.android.data.code_preference.source.CodePreferenceCacheDataSource
import org.stepik.android.domain.code_preference.repository.CodePreferenceRepository
@Module
abstract class CodePreferenceDataModule {
@Binds
internal abstract fun bindCodePreferenceRepository(
codePreferenceRepositoryImpl: CodePreferenceRepositoryImpl
): CodePreferenceRepository
@Binds
internal abstract fun bindCodePreferenceCacheDataSource(
codePreferenceCacheDataSourceImpl: CodePreferenceCacheDataSourceImpl
): CodePreferenceCacheDataSource
@Module
companion object {
@Provides
@JvmStatic
fun provideCodePreferenceDao(appDatabase: AppDatabase): CodePreferenceDao =
appDatabase.codePreferenceDao()
}
} | app/src/main/java/org/stepik/android/view/injection/code_preference/CodePreferenceDataModule.kt | 2188463323 |
/* Copyright 2021 Braden Farmer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalComposeUiApi::class)
package com.farmerbb.notepad.ui.content
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInteropFilter
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.farmerbb.notepad.R
import com.farmerbb.notepad.ui.components.RtlTextWrapper
import com.farmerbb.notepad.ui.previews.ViewNotePreview
import com.halilibo.richtext.markdown.Markdown
import com.halilibo.richtext.ui.RichText
import com.halilibo.richtext.ui.RichTextThemeIntegration
import com.linkifytext.LinkifyText
@Composable
fun ViewNoteContent(
text: String,
baseTextStyle: TextStyle = TextStyle(),
markdown: Boolean = false,
rtlLayout: Boolean = false,
isPrinting: Boolean = false,
showDoubleTapMessage: Boolean = false,
doubleTapMessageShown: () -> Unit = {},
onDoubleTap: () -> Unit = {}
) {
val textStyle = if (isPrinting) {
baseTextStyle.copy(color = Color.Black)
} else baseTextStyle
var doubleTapTime by remember { mutableStateOf(0L) }
Column(
modifier = Modifier
.fillMaxSize()
.pointerInteropFilter {
val now = System.currentTimeMillis()
when {
doubleTapTime > now -> onDoubleTap()
showDoubleTapMessage -> doubleTapMessageShown()
}
doubleTapTime = now + 300
false
}
) {
Box(
modifier = if (isPrinting) Modifier else Modifier
.verticalScroll(state = rememberScrollState())
) {
val modifier = Modifier
.padding(
horizontal = 16.dp,
vertical = 12.dp
)
.fillMaxWidth()
RtlTextWrapper(text, rtlLayout) {
SelectionContainer {
if (markdown) {
val localTextStyle = compositionLocalOf {
textStyle.copy(color = Color.Unspecified)
}
val localContentColor = compositionLocalOf {
textStyle.color
}
RichTextThemeIntegration(
textStyle = { localTextStyle.current },
contentColor = { localContentColor.current },
ProvideTextStyle = { textStyle, content ->
CompositionLocalProvider(
localTextStyle provides textStyle,
content = content
)
},
ProvideContentColor = { color, content ->
CompositionLocalProvider(
localContentColor provides color,
content = content
)
}
) {
RichText(modifier = modifier) {
Markdown(
// Replace markdown images with links
text.replace(Regex("!\\[([^\\[]+)](\\(.*\\))")) {
it.value.replaceFirst("![", "[")
}
)
}
}
} else {
LinkifyText(
text = text,
style = textStyle,
linkColor = colorResource(id = R.color.primary),
modifier = modifier
)
}
}
}
}
}
}
@Preview
@Composable
fun ViewNoteContentPreview() = ViewNotePreview() | app/src/main/java/com/farmerbb/notepad/ui/content/ViewNoteContent.kt | 1764988870 |
package nl.sugcube.dirtyarrows.command
import nl.sugcube.dirtyarrows.Broadcast
import nl.sugcube.dirtyarrows.DirtyArrows
import nl.sugcube.dirtyarrows.util.sendFormattedMessage
import org.bukkit.command.CommandSender
/**
* @author SugarCaney
*/
open class CommandList : SubCommand<DirtyArrows>(
name = "list",
usage = "/da list",
argumentCount = 0,
description = "Lists all registered protection regions."
) {
init {
addPermissions("dirtyarrows.admin")
}
override fun executeImpl(plugin: DirtyArrows, sender: CommandSender, vararg arguments: String) {
val regions = plugin.regionManager.allNames
val chat = regions.joinToString("&e, ") { "&a$it" }
sender.sendFormattedMessage(Broadcast.REGIONS_LIST.format(regions.size, chat))
}
override fun assertSender(sender: CommandSender) = true
} | src/main/kotlin/nl/sugcube/dirtyarrows/command/CommandList.kt | 2045053812 |
package messengerbot
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
open class MessengerBotApplication
fun main(args: Array<String>) {
SpringApplication.run(MessengerBotApplication::class.java, *args)
}
| src/main/kotlin/messengerbot/MessengerBotApplication.kt | 521756315 |
/*
* MapFragment.kt
* Implements the MapFragment fragment
* A MapFragment displays a map using osmdroid as well as the controls to start / stop a recording
*
* This file is part of
* TRACKBOOK - Movement Recorder for Android
*
* Copyright (c) 2016-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*
* Trackbook uses osmdroid - OpenStreetMap-Tools for Android
* https://github.com/osmdroid/osmdroid
*/
package org.y20k.trackbook
import YesNoDialog
import android.Manifest
import android.content.*
import android.content.pm.PackageManager
import android.location.Location
import android.os.*
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.y20k.trackbook.core.Track
import org.y20k.trackbook.core.TracklistElement
import org.y20k.trackbook.helpers.*
import org.y20k.trackbook.ui.MapFragmentLayoutHolder
/*
* MapFragment class
*/
class MapFragment : Fragment(), YesNoDialog.YesNoDialogListener, MapOverlayHelper.MarkerListener {
/* Define log tag */
private val TAG: String = LogHelper.makeLogTag(MapFragment::class.java)
/* Main class variables */
private var bound: Boolean = false
private val handler: Handler = Handler(Looper.getMainLooper())
private var trackingState: Int = Keys.STATE_TRACKING_NOT
private var gpsProviderActive: Boolean = false
private var networkProviderActive: Boolean = false
private var track: Track = Track()
private lateinit var currentBestLocation: Location
private lateinit var layout: MapFragmentLayoutHolder
private lateinit var trackerService: TrackerService
/* Overrides onCreate from Fragment */
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// TODO make only MapFragment's status bar transparent - see: https://gist.github.com/Dvik/a3de88d39da9d1d6d175025a56c5e797#file-viewextension-kt and https://proandroiddev.com/android-full-screen-ui-with-transparent-status-bar-ef52f3adde63
// get current best location
currentBestLocation = LocationHelper.getLastKnownLocation(activity as Context)
// get saved tracking state
trackingState = PreferencesHelper.loadTrackingState()
}
/* Overrides onStop from Fragment */
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
// initialize layout
val statusBarHeight: Int = UiHelper.getStatusBarHeight(activity as Context)
layout = MapFragmentLayoutHolder(activity as Context, this as MapOverlayHelper.MarkerListener, inflater, container, statusBarHeight, currentBestLocation, trackingState)
// set up buttons
layout.currentLocationButton.setOnClickListener {
layout.centerMap(currentBestLocation, animated = true)
}
layout.mainButton.setOnClickListener {
handleTrackingManagementMenu()
}
layout.saveButton.setOnClickListener {
saveTrack()
}
layout.clearButton.setOnClickListener {
if (track.wayPoints.isNotEmpty()) {
YesNoDialog(this as YesNoDialog.YesNoDialogListener).show(context = activity as Context, type = Keys.DIALOG_DELETE_CURRENT_RECORDING, message = R.string.dialog_delete_current_recording_message, yesButton = R.string.dialog_delete_current_recording_button_discard)
} else {
trackerService.clearTrack()
}
}
return layout.rootView
}
/* Overrides onStart from Fragment */
override fun onStart() {
super.onStart()
// request location permission if denied
if (ContextCompat.checkSelfPermission(activity as Context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) {
requestLocationPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
}
// bind to TrackerService
activity?.bindService(Intent(activity, TrackerService::class.java), connection, Context.BIND_AUTO_CREATE)
}
/* Overrides onResume from Fragment */
override fun onResume() {
super.onResume()
// if (bound) {
// trackerService.addGpsLocationListener()
// trackerService.addNetworkLocationListener()
// }
}
/* Overrides onPause from Fragment */
override fun onPause() {
super.onPause()
layout.saveState(currentBestLocation)
if (bound && trackingState != Keys.STATE_TRACKING_ACTIVE) {
trackerService.removeGpsLocationListener()
trackerService.removeNetworkLocationListener()
}
}
/* Overrides onStop from Fragment */
override fun onStop() {
super.onStop()
// unbind from TrackerService
activity?.unbindService(connection)
handleServiceUnbind()
}
/* Register the permission launcher for requesting location */
private val requestLocationPermissionLauncher = registerForActivityResult(RequestPermission()) { isGranted: Boolean ->
if (isGranted) {
// permission was granted - re-bind service
activity?.unbindService(connection)
activity?.bindService(Intent(activity, TrackerService::class.java), connection, Context.BIND_AUTO_CREATE)
LogHelper.i(TAG, "Request result: Location permission has been granted.")
} else {
// permission denied - unbind service
activity?.unbindService(connection)
}
layout.toggleLocationErrorBar(gpsProviderActive, networkProviderActive)
}
/* Register the permission launcher for starting the tracking service */
private val startTrackingPermissionLauncher = registerForActivityResult(RequestPermission()) { isGranted: Boolean ->
logPermissionRequestResult(isGranted)
// start service via intent so that it keeps running after unbind
startTrackerService()
trackerService.startTracking()
}
/* Register the permission launcher for resuming the tracking service */
private val resumeTrackingPermissionLauncher = registerForActivityResult(RequestPermission()) { isGranted: Boolean ->
logPermissionRequestResult(isGranted)
// start service via intent so that it keeps running after unbind
startTrackerService()
trackerService.resumeTracking()
}
/* Logs the request result of the Activity Recognition permission launcher */
private fun logPermissionRequestResult(isGranted: Boolean) {
if (isGranted) {
LogHelper.i(TAG, "Request result: Activity Recognition permission has been granted.")
} else {
LogHelper.i(TAG, "Request result: Activity Recognition permission has NOT been granted.")
}
}
/* Overrides onYesNoDialog from YesNoDialogListener */
override fun onYesNoDialog(type: Int, dialogResult: Boolean, payload: Int, payloadString: String) {
super.onYesNoDialog(type, dialogResult, payload, payloadString)
when (type) {
Keys.DIALOG_EMPTY_RECORDING -> {
when (dialogResult) {
// user tapped resume
true -> {
trackerService.resumeTracking()
}
}
}
Keys.DIALOG_DELETE_CURRENT_RECORDING -> {
when (dialogResult) {
true -> {
trackerService.clearTrack()
}
}
}
}
}
/* Overrides onMarkerTapped from MarkerListener */
override fun onMarkerTapped(latitude: Double, longitude: Double) {
super.onMarkerTapped(latitude, longitude)
if (bound) {
track = TrackHelper.toggleStarred(activity as Context, track, latitude, longitude)
layout.overlayCurrentTrack(track, trackingState)
trackerService.track = track
}
}
/* Start recording waypoints */
private fun startTracking() {
// request activity recognition permission on Android Q+ if denied
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && ContextCompat.checkSelfPermission(activity as Context, Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_DENIED) {
startTrackingPermissionLauncher.launch(Manifest.permission.ACTIVITY_RECOGNITION)
} else {
// start service via intent so that it keeps running after unbind
startTrackerService()
trackerService.startTracking()
}
}
/* Resume recording waypoints */
private fun resumeTracking() {
// request activity recognition permission on Android Q+ if denied
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && ContextCompat.checkSelfPermission(activity as Context, Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_DENIED) {
resumeTrackingPermissionLauncher.launch(Manifest.permission.ACTIVITY_RECOGNITION)
} else {
// start service via intent so that it keeps running after unbind
startTrackerService()
trackerService.resumeTracking()
}
}
/* Start tracker service */
private fun startTrackerService() {
val intent = Intent(activity, TrackerService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// ... start service in foreground to prevent it being killed on Oreo
activity?.startForegroundService(intent)
} else {
activity?.startService(intent)
}
}
/* Handles state when service is being unbound */
private fun handleServiceUnbind() {
bound = false
// unregister listener for changes in shared preferences
PreferencesHelper.unregisterPreferenceChangeListener(sharedPreferenceChangeListener)
// stop receiving location updates
handler.removeCallbacks(periodicLocationRequestRunnable)
}
/* Starts / pauses tracking and toggles the recording sub menu_bottom_navigation */
private fun handleTrackingManagementMenu() {
when (trackingState) {
Keys.STATE_TRACKING_PAUSED -> resumeTracking()
Keys.STATE_TRACKING_ACTIVE -> trackerService.stopTracking()
Keys.STATE_TRACKING_NOT -> startTracking()
}
}
/* Saves track - shows dialog, if recording is still empty */
private fun saveTrack() {
if (track.wayPoints.isEmpty()) {
YesNoDialog(this as YesNoDialog.YesNoDialogListener).show(context = activity as Context, type = Keys.DIALOG_EMPTY_RECORDING, message = R.string.dialog_error_empty_recording_message, yesButton = R.string.dialog_error_empty_recording_button_resume)
} else {
CoroutineScope(IO).launch {
// step 1: create and store filenames for json and gpx files
track.trackUriString = FileHelper.getTrackFileUri(activity as Context, track).toString()
track.gpxUriString = FileHelper.getGpxFileUri(activity as Context, track).toString()
// step 2: save track
FileHelper.saveTrackSuspended(track, saveGpxToo = true)
// step 3: save tracklist - suspended
FileHelper.addTrackAndSaveTracklistSuspended(activity as Context, track)
// step 3: clear track
trackerService.clearTrack()
// step 4: open track in TrackFragement
withContext(Main) {
openTrack(track.toTracklistElement(activity as Context))
}
}
}
}
/* Opens a track in TrackFragment */
private fun openTrack(tracklistElement: TracklistElement) {
val bundle: Bundle = Bundle()
bundle.putString(Keys.ARG_TRACK_TITLE, tracklistElement.name)
bundle.putString(Keys.ARG_TRACK_FILE_URI, tracklistElement.trackUriString)
bundle.putString(Keys.ARG_GPX_FILE_URI, tracklistElement.gpxUriString)
bundle.putLong(Keys.ARG_TRACK_ID, TrackHelper.getTrackId(tracklistElement))
findNavController().navigate(R.id.action_map_fragment_to_track_fragment, bundle)
}
/*
* Defines the listener for changes in shared preferences
*/
private val sharedPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
when (key) {
Keys.PREF_TRACKING_STATE -> {
if (activity != null) {
trackingState = PreferencesHelper.loadTrackingState()
layout.updateMainButton(trackingState)
}
}
}
}
/*
* End of declaration
*/
/*
* Defines callbacks for service binding, passed to bindService()
*/
private val connection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
bound = true
// get reference to tracker service
val binder = service as TrackerService.LocalBinder
trackerService = binder.service
// get state of tracking and update button if necessary
trackingState = trackerService.trackingState
layout.updateMainButton(trackingState)
// register listener for changes in shared preferences
PreferencesHelper.registerPreferenceChangeListener(sharedPreferenceChangeListener)
// start listening for location updates
handler.removeCallbacks(periodicLocationRequestRunnable)
handler.postDelayed(periodicLocationRequestRunnable, 0)
}
override fun onServiceDisconnected(arg0: ComponentName) {
// service has crashed, or was killed by the system
handleServiceUnbind()
}
}
/*
* End of declaration
*/
/*
* Runnable: Periodically requests location
*/
private val periodicLocationRequestRunnable: Runnable = object : Runnable {
override fun run() {
// pull current state from service
currentBestLocation = trackerService.currentBestLocation
track = trackerService.track
gpsProviderActive = trackerService.gpsProviderActive
networkProviderActive = trackerService.networkProviderActive
trackingState = trackerService.trackingState
// update location and track
layout.markCurrentPosition(currentBestLocation, trackingState)
layout.overlayCurrentTrack(track, trackingState)
layout.updateLiveStatics(length = track.length, duration = track.duration, trackingState = trackingState)
// center map, if it had not been dragged/zoomed before
if (!layout.userInteraction) { layout.centerMap(currentBestLocation, true)}
// show error snackbar if necessary
layout.toggleLocationErrorBar(gpsProviderActive, networkProviderActive)
// use the handler to start runnable again after specified delay
handler.postDelayed(this, Keys.REQUEST_CURRENT_LOCATION_INTERVAL)
}
}
/*
* End of declaration
*/
}
| app/src/main/java/org/y20k/trackbook/MapFragment.kt | 4219084342 |
package eu.kanade.core.prefs
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import eu.kanade.tachiyomi.core.preference.Preference
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
class PreferenceMutableState<T>(
private val preference: Preference<T>,
scope: CoroutineScope,
) : MutableState<T> {
private val state = mutableStateOf(preference.get())
init {
preference.changes()
.onEach { state.value = it }
.launchIn(scope)
}
override var value: T
get() = state.value
set(value) {
preference.set(value)
}
override fun component1(): T {
return state.value
}
override fun component2(): (T) -> Unit {
return { preference.set(it) }
}
}
| app/src/main/java/eu/kanade/core/prefs/PreferenceMutableState.kt | 1402580598 |
package com.lopezjuri.uc_accesss.models
/**
* Created by patriciolopez on 19-01-16.
*/
data class WebPage(
val id: String?,
val name: String,
val description: String?,
val URL: String,
val imageURL: String?,
var selected: Boolean = false
)
| app/src/main/java/com/lopezjuri/uc_accesss/models/WebPage.kt | 3721769988 |
package venus.simulator.diffs
import venus.simulator.Diff
import venus.simulator.SimulatorState
class RegisterDiff(val id: Int, val v: Int) : Diff {
override operator fun invoke(state: SimulatorState) = state.setReg(id, v)
} | src/main/kotlin/venus/simulator/diffs/RegisterDiff.kt | 1903872057 |
package net.dean.jraw.models
import com.squareup.moshi.Json
/** A list of sorting methods that can be used when examining comments */
enum class CommentSort {
/** What reddit thinks is best. Factors in score, age, and a few other variables. */
@Json(name = "confidence") CONFIDENCE,
/** Comments with the highest score are shown first. */
@Json(name = "top") TOP,
/** Newest comments are shown first */
@Json(name = "new") NEW,
/** The most controversial comments are shown first (usually this means the comments with the most downvotes) */
@Json(name = "controversial") CONTROVERSIAL,
/** Comments appear in the order they were created */
@Json(name = "old") OLD,
/** Self explanatory */
@Json(name = "random") RANDOM,
/**
* A special sorting made for Q&A-style (questions and answers) posts. Also known as AMA's (ask me anything). Puts
* comments where the submission author replied first, then sorts by [CONFIDENCE].
*/
@Json(name = "qa") QA,
/** As of the time of writing (15 Dec 2017), this sort is in beta. When disabled by reddit, functions like [NEW]. */
@Json(name = "live") LIVE
}
| lib/src/main/kotlin/net/dean/jraw/models/CommentSort.kt | 718695639 |
package com.auth0.android.authentication
import com.auth0.android.request.internal.OidcUtils
/**
* Builder for Auth0 Authentication API parameters
* You can build your parameters like this
* ```
* val parameters = ParameterBuilder.newBuilder()
* .setClientId("{CLIENT_ID}")
* .setConnection("{CONNECTION}")
* .set("{PARAMETER_NAME}", "{PARAMETER_VALUE}")
* .asDictionary()
* ```
*
* @see ParameterBuilder.newBuilder
* @see ParameterBuilder.newAuthenticationBuilder
*/
public class ParameterBuilder private constructor(parameters: Map<String, String>) {
private val parameters: MutableMap<String, String> = parameters.toMutableMap()
/**
* Sets the 'client_id' parameter
*
* @param clientId the application's client id
* @return itself
*/
public fun setClientId(clientId: String): ParameterBuilder {
return set(CLIENT_ID_KEY, clientId)
}
/**
* Sets the 'grant_type' parameter
*
* @param grantType grant type
* @return itself
*/
public fun setGrantType(grantType: String): ParameterBuilder {
return set(GRANT_TYPE_KEY, grantType)
}
/**
* Sets the 'connection' parameter
*
* @param connection name of the connection
* @return itself
*/
public fun setConnection(connection: String): ParameterBuilder {
return set(CONNECTION_KEY, connection)
}
/**
* Sets the 'realm' parameter. A realm identifies the host against which the authentication will be made, and usually helps to know which username and password to use.
*
* @param realm name of the realm
* @return itself
*/
public fun setRealm(realm: String): ParameterBuilder {
return set(REALM_KEY, realm)
}
/**
* Sets the 'scope' parameter.
*
* @param scope a scope value
* @return itself
*/
public fun setScope(scope: String): ParameterBuilder {
return set(SCOPE_KEY, OidcUtils.includeRequiredScope(scope))
}
/**
* Sets the 'audience' parameter.
*
* @param audience an audience value
* @return itself
*/
public fun setAudience(audience: String): ParameterBuilder {
return set(AUDIENCE_KEY, audience)
}
/**
* Sets the 'refresh_token' parameter
*
* @param refreshToken a access token
* @return itself
*/
public fun setRefreshToken(refreshToken: String): ParameterBuilder {
return set(REFRESH_TOKEN_KEY, refreshToken)
}
/**
* Sets the 'send' parameter
*
* @param passwordlessType the type of passwordless login
* @return itself
*/
public fun setSend(passwordlessType: PasswordlessType): ParameterBuilder {
return set(SEND_KEY, passwordlessType.value)
}
/**
* Sets a parameter
*
* @param key parameter name
* @param value parameter value. A null value will remove the key if present.
* @return itself
*/
public operator fun set(key: String, value: String?): ParameterBuilder {
if (value == null) {
parameters.remove(key)
} else {
parameters[key] = value
}
return this
}
/**
* Adds all parameter from a map
*
* @param parameters map with parameters to add. Null values will be skipped.
* @return itself
*/
public fun addAll(parameters: Map<String, String?>): ParameterBuilder {
parameters.filterValues { it != null }.map { this.parameters.put(it.key, it.value!!) }
return this
}
/**
* Clears all existing parameters
*
* @return itself
*/
public fun clearAll(): ParameterBuilder {
parameters.clear()
return this
}
/**
* Create a [Map] with all the parameters
*
* @return all parameters added previously as a [Map]
*/
public fun asDictionary(): Map<String, String> {
return parameters.toMap()
}
public companion object {
public const val GRANT_TYPE_REFRESH_TOKEN: String = "refresh_token"
public const val GRANT_TYPE_PASSWORD: String = "password"
public const val GRANT_TYPE_PASSWORD_REALM: String =
"http://auth0.com/oauth/grant-type/password-realm"
public const val GRANT_TYPE_AUTHORIZATION_CODE: String = "authorization_code"
public const val GRANT_TYPE_MFA_OTP: String = "http://auth0.com/oauth/grant-type/mfa-otp"
public const val GRANT_TYPE_MFA_OOB: String = "http://auth0.com/oauth/grant-type/mfa-oob"
public const val GRANT_TYPE_MFA_RECOVERY_CODE: String =
"http://auth0.com/oauth/grant-type/mfa-recovery-code"
public const val GRANT_TYPE_PASSWORDLESS_OTP: String =
"http://auth0.com/oauth/grant-type/passwordless/otp"
public const val GRANT_TYPE_TOKEN_EXCHANGE: String =
"urn:ietf:params:oauth:grant-type:token-exchange"
public const val SCOPE_OPENID: String = "openid"
public const val SCOPE_OFFLINE_ACCESS: String = "openid offline_access"
public const val SCOPE_KEY: String = "scope"
public const val REFRESH_TOKEN_KEY: String = "refresh_token"
public const val CONNECTION_KEY: String = "connection"
public const val REALM_KEY: String = "realm"
public const val SEND_KEY: String = "send"
public const val CLIENT_ID_KEY: String = "client_id"
public const val GRANT_TYPE_KEY: String = "grant_type"
public const val AUDIENCE_KEY: String = "audience"
/**
* Creates a new instance of the builder using default values for login request, e.g. 'openid profile email' for scope.
*
* @return a new builder
*/
@JvmStatic
public fun newAuthenticationBuilder(): ParameterBuilder {
return newBuilder()
.setScope(OidcUtils.DEFAULT_SCOPE)
}
/**
* Creates a new instance of the builder.
*
* @param parameters an optional map of initial parameters
* @return a new builder
*/
@JvmStatic
@JvmOverloads
public fun newBuilder(parameters: Map<String, String> = mutableMapOf()): ParameterBuilder {
return ParameterBuilder(parameters)
}
}
} | auth0/src/main/java/com/auth0/android/authentication/ParameterBuilder.kt | 67074456 |
/*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire.gradle
import org.gradle.api.Action
import org.gradle.api.Project
import org.gradle.api.artifacts.MinimalExternalModuleDependency
import org.gradle.api.file.SourceDirectorySet
import org.gradle.api.internal.catalog.DelegatingProjectDependency
import org.gradle.api.provider.Provider
import org.gradle.api.provider.ProviderConvertible
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.util.PatternFilterable
open class WireExtension(project: Project) {
private val objectFactory = project.objects
internal val sourcePaths = mutableSetOf<String>()
internal val protoPaths = mutableSetOf<String>()
internal val sourceTrees = mutableSetOf<SourceDirectorySet>()
internal val protoTrees = mutableSetOf<SourceDirectorySet>()
internal val sourceJars = mutableSetOf<ProtoRootSet>()
internal val protoJars = mutableSetOf<ProtoRootSet>()
internal val roots = mutableSetOf<String>()
internal val prunes = mutableSetOf<String>()
internal val moves = mutableListOf<Move>()
internal var onlyVersion: String? = null
internal var sinceVersion: String? = null
internal var untilVersion: String? = null
internal var permitPackageCycles: Boolean = false
@Input
@Optional
fun roots() = roots.toSet()
/**
* See [com.squareup.wire.schema.WireRun.treeShakingRoots]
*/
fun root(vararg roots: String) {
this.roots.addAll(roots)
}
@Input
@Optional
fun prunes() = prunes.toSet()
/**
* See [com.squareup.wire.schema.WireRun.treeShakingRubbish]
*/
fun prune(vararg prunes: String) {
this.prunes.addAll(prunes)
}
@Input
@Optional
fun sinceVersion() = sinceVersion
/**
* See [com.squareup.wire.schema.WireRun.sinceVersion]
*/
fun sinceVersion(sinceVersion: String) {
this.sinceVersion = sinceVersion
}
@Input
@Optional
fun untilVersion() = untilVersion
/**
* See [com.squareup.wire.schema.WireRun.untilVersion]
*/
fun untilVersion(untilVersion: String) {
this.untilVersion = untilVersion
}
@Input
@Optional
fun onlyVersion() = onlyVersion
/**
* See [com.squareup.wire.schema.WireRun.onlyVersion].
*/
fun onlyVersion(onlyVersion: String) {
this.onlyVersion = onlyVersion
}
@Input
fun permitPackageCycles() = permitPackageCycles
/**
* See [com.squareup.wire.schema.WireRun.permitPackageCycles]
*/
fun permitPackageCycles(permitPackageCycles: Boolean) {
this.permitPackageCycles = permitPackageCycles
}
/**
* A user-provided file listing [roots] and [prunes]
*/
@get:Input
@get:Optional
var rules: String? = null
/** Specified what types to output where. Maps to [com.squareup.wire.schema.Target] */
@get:Input
val outputs = mutableListOf<WireOutput>()
/**
* True to emit `.proto` files into the output resources. Use this when your `.jar` file can be
* used as a library for other proto or Wire projects.
*
* Note that only the `.proto` files used in the library will be included, and these files will
* have tree-shaking applied.
*/
@get:Input
@get:Optional
var protoLibrary = false
@InputFiles
@Optional
fun getSourcePaths() = sourcePaths.toSet()
@InputFiles
@Optional
fun getSourceTrees() = sourceTrees.toSet()
@InputFiles
@Optional
fun getSourceJars() = sourceJars.toSet()
/**
* Source paths for local jars and directories, as well as remote binary dependencies
*/
// TODO(Benoit) Delete this because it seems unused? I think the DSL only pass down ProtoRootSet.
fun sourcePath(vararg sourcePaths: String) {
this.sourcePaths.addAll(sourcePaths)
}
/**
* Source paths for local file trees, backed by a [org.gradle.api.file.SourceDirectorySet]
* Must provide at least a [org.gradle.api.file.SourceDirectorySet.srcDir]
*/
fun sourcePath(action: Action<ProtoRootSet>) {
populateRootSets(action, sourceTrees, sourceJars, "source-tree")
}
@InputFiles
@Optional
fun getProtoPaths(): Set<String> {
return protoPaths
}
@InputFiles
@Optional
fun getProtoTrees(): Set<SourceDirectorySet> {
return protoTrees
}
@InputFiles
@Optional
fun getProtoJars(): Set<ProtoRootSet> {
return protoJars
}
/**
* Proto paths for local jars and directories, as well as remote binary dependencies
*/
fun protoPath(vararg protoPaths: String) {
this.protoPaths.addAll(protoPaths)
}
/**
* Proto paths for local file trees, backed by a [org.gradle.api.file.SourceDirectorySet]
* Must provide at least a [org.gradle.api.file.SourceDirectorySet.srcDir]
*/
fun protoPath(action: Action<ProtoRootSet>) {
populateRootSets(action, protoTrees, protoJars, "proto-tree")
}
private fun populateRootSets(
action: Action<ProtoRootSet>,
sourceTrees: MutableSet<SourceDirectorySet>,
sourceJars: MutableSet<ProtoRootSet>,
name: String
) {
val protoRootSet = objectFactory.newInstance(ProtoRootSet::class.java)
action.execute(protoRootSet)
protoRootSet.validate()
val hasSrcDirs = protoRootSet.srcDirs.isNotEmpty()
val hasSrcJar = protoRootSet.srcJar != null
val hasSrcJarAsExternalModuleDependency = protoRootSet.srcJarAsExternalModuleDependency != null
val hasSrcProjectDependency = protoRootSet.srcProjectDependency != null
val hasSrcProject = protoRootSet.srcProject != null
if (hasSrcDirs) {
// map to SourceDirectorySet which does the work for us!
val protoTree = objectFactory
.sourceDirectorySet(name, "Wire proto sources for $name.")
.srcDirs(protoRootSet.srcDirs)
protoRootSet.filters
.ifEmpty { listOf(Include("**/*.proto")) }
.forEach { it.act(protoTree.filter) }
sourceTrees.add(protoTree)
}
if (hasSrcJar || hasSrcJarAsExternalModuleDependency || hasSrcProject || hasSrcProjectDependency) {
sourceJars.add(protoRootSet)
}
}
fun java(action: Action<JavaOutput>) {
val javaOutput = objectFactory.newInstance(JavaOutput::class.java)
action.execute(javaOutput)
outputs += javaOutput
}
fun kotlin(action: Action<KotlinOutput>) {
val kotlinOutput = objectFactory.newInstance(KotlinOutput::class.java)
action.execute(kotlinOutput)
outputs += kotlinOutput
}
fun proto(action: Action<ProtoOutput>) {
val protoOutput = objectFactory.newInstance(ProtoOutput::class.java)
action.execute(protoOutput)
outputs += protoOutput
}
fun custom(action: Action<CustomOutput>) {
val customOutput = objectFactory.newInstance(CustomOutput::class.java)
action.execute(customOutput)
outputs += customOutput
}
fun move(action: Action<Move>) {
val move = objectFactory.newInstance(Move::class.java)
action.execute(move)
moves += move
}
// TODO(Benoit) See how we can make this class better, it's a mess and doesn't scale nicely.
open class ProtoRootSet {
val srcDirs = mutableListOf<String>()
var srcJar: String? = null
var srcProject: String? = null
var srcProjectDependency: DelegatingProjectDependency? = null
var srcJarAsExternalModuleDependency: Provider<MinimalExternalModuleDependency>? = null
val includes = mutableListOf<String>()
val excludes = mutableListOf<String>()
internal val filters: Collection<Filter>
get() = includes.map(::Include) + excludes.map(::Exclude)
fun srcDir(dir: String) {
srcDirs += dir
}
fun srcDirs(vararg dirs: String) {
srcDirs += dirs
}
fun srcJar(jar: String) {
srcJar = jar
}
fun srcJar(provider: Provider<MinimalExternalModuleDependency>) {
srcJarAsExternalModuleDependency = provider
}
fun srcJar(convertible: ProviderConvertible<MinimalExternalModuleDependency>) {
srcJar(convertible.asProvider())
}
fun srcProject(projectPath: String) {
srcProject = projectPath
}
fun srcProject(project: DelegatingProjectDependency) {
srcProjectDependency = project
}
fun include(vararg includePaths: String) {
includes += includePaths
}
fun exclude(vararg excludePaths: String) {
excludes += excludePaths
}
}
internal sealed class Filter(val glob: String) {
abstract fun act(filter: PatternFilterable)
}
internal class Exclude(glob: String) : Filter(glob) {
override fun act(filter: PatternFilterable) {
filter.exclude(glob)
}
}
internal class Include(glob: String) : Filter(glob) {
override fun act(filter: PatternFilterable) {
filter.include(glob)
}
}
}
private fun WireExtension.ProtoRootSet.validate() {
val sources = listOf(
srcDirs.isNotEmpty(),
srcJar != null,
srcJarAsExternalModuleDependency != null,
srcProjectDependency != null,
srcProject != null,
)
check(sources.count { it } <= 1) {
"Only one source can be set among srcDirs, srcJar, and srcProject within one sourcePath or protoPath closure."
}
}
| wire-library/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireExtension.kt | 3650522064 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.