content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package taiwan.no1.app.internal.di.components
import android.content.Context
import dagger.Component
import taiwan.no1.app.App
import taiwan.no1.app.domain.executor.PostExecutionThread
import taiwan.no1.app.domain.executor.ThreadExecutor
import taiwan.no1.app.domain.repository.IRepository
import taiwan.no1.app.internal.di.modules.AppModule
import taiwan.no1.app.internal.di.modules.NetModule
import javax.inject.Singleton
/**
* A component whose lifetime is the life of the application.
*
* @author Jieyi
* @since 12/6/16
*/
@Singleton
@Component(modules = arrayOf(AppModule::class, NetModule::class))
interface AppComponent {
object Initializer {
fun init(app: App): AppComponent = DaggerAppComponent.builder()
.appModule(AppModule(app))
.netModule(NetModule(app))
.build()
}
// Exposed to sub-graphs.
fun context(): Context
fun threadExecutor(): ThreadExecutor
fun postExecutionThread(): PostExecutionThread
fun repository(): IRepository
} | app/src/main/kotlin/taiwan/no1/app/internal/di/components/AppComponent.kt | 1738162034 |
package me.ykrank.s1next.widget.download
import com.liulishuo.okdownload.DownloadTask
import com.liulishuo.okdownload.core.cause.EndCause
import com.liulishuo.okdownload.core.listener.assist.Listener1Assist
import java.util.*
object ProgressManager {
private val mListeners = WeakHashMap<String, MutableList<ProgressListener>>()
fun addListener(url: String, listener: ProgressListener) {
var progressListeners: MutableList<ProgressListener>?
synchronized(ProgressManager::class.java) {
progressListeners = mListeners[url]
if (progressListeners == null) {
progressListeners = LinkedList()
mListeners[url] = progressListeners
}
}
progressListeners?.add(listener)
}
fun notifyProgress(task: DownloadTask, currentOffset: Long, totalLength: Long) {
val progressListeners = mListeners[task.url]
if (progressListeners != null) {
val array = progressListeners.toTypedArray()
for (i in array.indices) {
array[i].onProgress(task, currentOffset, totalLength)
}
}
}
fun notifyTaskEnd(task: DownloadTask, cause: EndCause, realCause: java.lang.Exception?, model: Listener1Assist.Listener1Model) {
val progressListeners = mListeners[task.url]
if (progressListeners != null) {
val array = progressListeners.toTypedArray()
for (i in array.indices) {
array[i].taskEnd(task, cause, realCause, model)
}
}
}
}
interface ProgressListener {
fun onProgress(task: DownloadTask, currentOffset: Long, totalLength: Long)
fun taskEnd(task: DownloadTask, cause: EndCause, realCause: java.lang.Exception?, model: Listener1Assist.Listener1Model)
} | app/src/main/java/me/ykrank/s1next/widget/download/ProgressManager.kt | 2408641949 |
package io.gitlab.arturbosch.detekt.core
import io.gitlab.arturbosch.detekt.api.SplitPattern
import io.gitlab.arturbosch.detekt.test.yamlConfig
import org.assertj.core.api.Assertions
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import java.nio.file.Path
import java.nio.file.Paths
/**
* @author Artur Bosch
*/
class TestPatternTest : Spek({
given("a bunch of paths") {
val pathContent = """
a/b/c/test/abcTest.kt,
a/b/c/test/adeTest.kt,
a/b/c/test/afgTest.kt,
a/b/c/d/ab.kt,
a/b/c/d/bb.kt,
a/b/c/d/cb.kt
"""
val paths = SplitPattern(pathContent).mapAll { Paths.get(it) }
fun splitSources(pattern: TestPattern, paths: List<Path>): Pair<List<Path>, List<Path>> =
paths.partition { pattern.matches(it.toString()) }
fun preparePattern() = createTestPattern(yamlConfig("patterns/test-pattern.yml"))
it("should split the given paths to main and test sources") {
val pattern = preparePattern()
val (testSources, mainSources) = splitSources(pattern, paths)
Assertions.assertThat(testSources).allMatch { it.toString().endsWith("Test.kt") }
Assertions.assertThat(mainSources).allMatch { it.toString().endsWith("b.kt") }
}
}
})
| detekt-core/src/test/kotlin/io/gitlab/arturbosch/detekt/core/TestPatternTest.kt | 465633555 |
package voice.bookOverview.views
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.GenericShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathOperation
import androidx.compose.ui.graphics.addOutline
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntRect
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupPositionProvider
@Composable
internal fun ExplanationTooltip(content: @Composable ColumnScope.() -> Unit) {
var triangleCenterX: Float? by remember { mutableStateOf(null) }
val popupPositionProvider = ExplanationTooltipPopupPositionProvider(LocalDensity.current) {
triangleCenterX = it.toFloat()
}
Popup(popupPositionProvider = popupPositionProvider) {
Card(
modifier = Modifier.widthIn(max = 240.dp),
elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
shape = explanationTooltipShape(triangleCenterX, LocalDensity.current),
) {
content()
}
}
}
private class ExplanationTooltipPopupPositionProvider(
private val density: Density,
private val onTriangleCenterX: (Int) -> Unit,
) : PopupPositionProvider {
override fun calculatePosition(
anchorBounds: IntRect,
windowSize: IntSize,
layoutDirection: LayoutDirection,
popupContentSize: IntSize,
): IntOffset {
val rightMargin = with(density) { 16.dp.toPx() }
var offset = IntOffset(anchorBounds.center.x - popupContentSize.width / 2, anchorBounds.bottom)
if ((offset.x + popupContentSize.width + rightMargin) > windowSize.width) {
offset -= IntOffset(rightMargin.toInt() + (offset.x + popupContentSize.width - windowSize.width), 0)
}
onTriangleCenterX(anchorBounds.center.x - offset.x)
return offset
}
}
private fun explanationTooltipShape(triangleCenterX: Float?, density: Density): GenericShape {
val triangleSize = with(density) {
28.dp.toPx()
}
return GenericShape { size, layoutDirection ->
addOutline(
RoundedCornerShape(12.0.dp)
.createOutline(size, layoutDirection, density),
)
if (triangleCenterX != null) {
val trianglePath = Path().apply {
moveTo(
x = triangleCenterX - triangleSize / 2F,
y = 0F,
)
lineTo(
x = triangleCenterX,
y = -triangleSize / 2F,
)
lineTo(
x = triangleCenterX + triangleSize / 2F,
y = 0F,
)
close()
}
op(this, trianglePath, PathOperation.Union)
}
}
}
| bookOverview/src/main/kotlin/voice/bookOverview/views/ExplanationTooltip.kt | 1254199402 |
package net.twisterrob.challenges.adventOfKotlin2018.week2.global
import net.twisterrob.challenges.adventOfKotlin2018.week2.Twinject
import net.twisterrob.challenges.adventOfKotlin2018.week2.reflect.register
import net.twisterrob.challenges.adventOfKotlin2018.week2.reflect.registerContract
val inject = (Twinject()) {
// reflective creation (same type)
register<CoffeeMaker>()
// reflective creation (super type)
registerContract<Pump, Thermosiphon>()
// custom creation
register<Heater> { EletrictHeater() }
}
fun main(args: Array<String>) {
val maker: CoffeeMaker = inject()
maker.brew()
}
interface Pump {
fun pump()
}
interface Heater {
fun heat()
}
class Thermosiphon(
private val heater: Heater = inject()
) : Pump {
override fun pump() {
heater.heat()
println("=> => pumping => =>")
}
}
class CoffeeMaker {
private val pump: Pump by inject
fun brew() {
pump.pump()
println(" [_]P coffee! [_]P")
}
}
class EletrictHeater : Heater {
override fun heat() {
println("~ ~ ~ heating ~ ~ ~")
}
}
| KotlinAdvent2018/week2/src/main/kotlin/net/twisterrob/challenges/adventOfKotlin2018/week2/global/CoffeeShop.kt | 2582805119 |
package com.jamieadkins.gwent.data
object Constants {
const val CARDS_API_BASE_URL = "https://gwent-9e62a.firebaseio.com/"
const val CACHE_KEY = BuildConfig.APPLICATION_ID
} | data/src/main/java/com/jamieadkins/gwent/data/Constants.kt | 417554445 |
package com.intellij.credentialStore
import com.intellij.util.io.jna.DisposableMemory
import com.sun.jna.Library
import com.sun.jna.Native
import com.sun.jna.Pointer
import com.sun.jna.Structure
private val LIBRARY by lazy { Native.loadLibrary("secret-1", SecretLibrary::class.java) as SecretLibrary }
private const val SECRET_SCHEMA_NONE = 0
private const val SECRET_SCHEMA_ATTRIBUTE_STRING = 0
// explicitly create pointer to be explicitly dispose it to avoid sensitive data in the memory
internal fun stringPointer(data: ByteArray, clearInput: Boolean = false): DisposableMemory {
val pointer = DisposableMemory(data.size + 1L)
pointer.write(0, data, 0, data.size)
pointer.setByte(data.size.toLong(), 0.toByte())
if (clearInput) {
data.fill(0)
}
return pointer
}
// we use default collection, it seems no way to use custom
internal class SecretCredentialStore(schemeName: String) : CredentialStore {
private val serviceAttributeNamePointer by lazy { stringPointer("service".toByteArray()) }
private val accountAttributeNamePointer by lazy { stringPointer("account".toByteArray()) }
private val scheme by lazy {
LIBRARY.secret_schema_new(schemeName, SECRET_SCHEMA_NONE,
serviceAttributeNamePointer, SECRET_SCHEMA_ATTRIBUTE_STRING,
accountAttributeNamePointer, SECRET_SCHEMA_ATTRIBUTE_STRING,
null)
}
override fun get(attributes: CredentialAttributes): Credentials? {
checkError("secret_password_lookup_sync") { errorRef ->
val serviceNamePointer = stringPointer(attributes.serviceName.toByteArray())
if (attributes.userName == null) {
LIBRARY.secret_password_lookup_sync(scheme, null, errorRef, serviceAttributeNamePointer, serviceNamePointer, null)?.let {
// Secret Service doesn't allow to get attributes, so, we store joined data
return splitData(it)
}
}
else {
LIBRARY.secret_password_lookup_sync(scheme, null, errorRef,
serviceAttributeNamePointer, serviceNamePointer,
accountAttributeNamePointer, stringPointer(attributes.userName!!.toByteArray()),
null)?.let {
return splitData(it)
}
}
}
return null
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
val serviceNamePointer = stringPointer(attributes.serviceName.toByteArray())
val accountName = attributes.userName ?: credentials?.userName
if (credentials.isEmpty()) {
checkError("secret_password_store_sync") { errorRef ->
if (accountName == null) {
LIBRARY.secret_password_clear_sync(scheme, null, errorRef,
serviceAttributeNamePointer, serviceNamePointer,
null)
}
else {
LIBRARY.secret_password_clear_sync(scheme, null, errorRef,
serviceAttributeNamePointer, serviceNamePointer,
accountAttributeNamePointer, stringPointer(accountName.toByteArray()),
null)
}
}
return
}
val passwordPointer = stringPointer(credentials!!.serialize(!attributes.isPasswordMemoryOnly), true)
checkError("secret_password_store_sync") { errorRef ->
try {
if (accountName == null) {
LIBRARY.secret_password_store_sync(scheme, null, serviceNamePointer, passwordPointer, null, errorRef,
serviceAttributeNamePointer, serviceNamePointer,
null)
}
else {
LIBRARY.secret_password_store_sync(scheme, null, serviceNamePointer, passwordPointer, null, errorRef,
serviceAttributeNamePointer, serviceNamePointer,
accountAttributeNamePointer, stringPointer(accountName.toByteArray()),
null)
}
}
finally {
passwordPointer.dispose()
}
}
}
}
private inline fun <T> checkError(method: String, task: (errorRef: Array<GErrorStruct?>) -> T): T {
val errorRef = arrayOf<GErrorStruct?>(null)
val result = task(errorRef)
val error = errorRef.get(0)
if (error != null && error.code !== 0) {
if (error.code == 32584 || error.code == 32618 || error.code == 32606 || error.code == 32642) {
LOG.warn("gnome-keyring not installed or kde doesn't support Secret Service API. $method error code ${error.code}, error message ${error.message}")
}
else {
LOG.error("$method error code ${error.code}, error message ${error.message}")
}
}
return result
}
// we use sync API to simplify - client will use postponed write
private interface SecretLibrary : Library {
fun secret_schema_new(name: String, flags: Int, vararg attributes: Any?): Pointer
fun secret_password_store_sync(scheme: Pointer, collection: Pointer?, label: Pointer, password: Pointer, cancellable: Pointer?, error: Array<GErrorStruct?>, vararg attributes: Pointer?)
fun secret_password_lookup_sync(scheme: Pointer, cancellable: Pointer?, error: Array<GErrorStruct?>, vararg attributes: Pointer?): String?
fun secret_password_clear_sync(scheme: Pointer, cancellable: Pointer?, error: Array<GErrorStruct?>, vararg attributes: Pointer?)
}
@Suppress("unused")
internal class GErrorStruct : Structure() {
@JvmField
var domain = 0
@JvmField
var code = 0
@JvmField
var message: String? = null
override fun getFieldOrder() = listOf("domain", "code", "message")
} | platform/credential-store/src/linuxSecretLibrary.kt | 1708692006 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.recorder.actions
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.testGuiFramework.recorder.GlobalActionRecorder
import com.intellij.testGuiFramework.recorder.ui.Notifier
/**
* @author Sergey Karashevich
*/
class StartPauseRecAction : ToggleAction(null, "Start/Stop GUI Script Recording", AllIcons.Ide.Macro.Recording_1) {
override fun isSelected(actionEvent: AnActionEvent?): Boolean = GlobalActionRecorder.isActive()
override fun setSelected(actionEvent: AnActionEvent?, toStart: Boolean) {
if (toStart) {
val presentation = if (actionEvent != null) actionEvent.presentation else templatePresentation
presentation.description = "Stop GUI Script Recording"
Notifier.updateStatus("Recording started")
GlobalActionRecorder.activate()
}
else {
val presentation = if (actionEvent != null) actionEvent.presentation else templatePresentation
presentation.description = "Start GUI Script Recording"
Notifier.updateStatus("Recording paused")
GlobalActionRecorder.deactivate()
}
}
} | platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/actions/StartPauseRecAction.kt | 2028049601 |
package io.aconite.client
import io.aconite.Request
import io.aconite.Response
import io.aconite.parser.ModuleParser
import kotlinx.coroutines.experimental.suspendCancellableCoroutine
import org.junit.Assert
import org.junit.Test
import kotlin.reflect.full.functions
class ModuleProxyTest {
@Test fun testCreatesModuleProxy() {
val client = AconiteClient(acceptor = TestHttpClient())
val proxy = client.moduleFactory.create(ModuleParser().parse(RootModuleApi::class))
Assert.assertNotNull(proxy)
}
@Test fun testCallProxyMethod() = asyncTest {
val client = AconiteClient(acceptor = TestHttpClient { _, r -> Response(body = r.body)})
val proxy = client.moduleFactory.create(ModuleParser().parse(RootModuleApi::class))
val fn = RootModuleApi::class.functions.first { it.name == "patch" }
val result = suspendCancellableCoroutine<Any?> { c ->
proxy.invoke(fn, "/test/url", Request(), arrayOf("foobar", c))
}
Assert.assertEquals("foobar", result)
}
@Test fun testCallProxyModule() = asyncTest {
val client = AconiteClient(acceptor = TestHttpClient())
val proxy = client.moduleFactory.create(ModuleParser().parse(RootModuleApi::class))
val fn = RootModuleApi::class.functions.first { it.name == "test" }
val result = suspendCancellableCoroutine<Any> { c ->
proxy.invoke(fn, "/test/url", Request(), arrayOf(c))
}
Assert.assertTrue(result is TestModuleApi)
}
} | aconite-client/tests/io/aconite/client/ModuleProxyTest.kt | 1727973083 |
package com.lasthopesoftware.bluewater.client.playback.exoplayer
import android.os.Looper
import com.google.android.exoplayer2.*
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.ShuffleOrder
import com.google.android.exoplayer2.trackselection.TrackSelector
import com.namehillsoftware.handoff.promises.Promise
interface PromisingExoPlayer {
fun getApplicationLooper(): Promise<Looper>
fun addListener(listener: Player.Listener): Promise<PromisingExoPlayer>
fun removeListener(listener: Player.Listener): Promise<PromisingExoPlayer>
fun setMediaItems(mediaItems: MutableList<MediaItem>): Promise<PromisingExoPlayer>
fun setMediaItems(mediaItems: MutableList<MediaItem>, resetPosition: Boolean): Promise<PromisingExoPlayer>
fun setMediaItems(mediaItems: MutableList<MediaItem>, startWindowIndex: Int, startPositionMs: Long): Promise<PromisingExoPlayer>
fun setMediaItem(mediaItem: MediaItem): Promise<PromisingExoPlayer>
fun setMediaItem(mediaItem: MediaItem, startPositionMs: Long): Promise<PromisingExoPlayer>
fun setMediaItem(mediaItem: MediaItem, resetPosition: Boolean): Promise<PromisingExoPlayer>
fun addMediaItem(mediaItem: MediaItem): Promise<PromisingExoPlayer>
fun addMediaItem(index: Int, mediaItem: MediaItem): Promise<PromisingExoPlayer>
fun addMediaItems(mediaItems: MutableList<MediaItem>): Promise<PromisingExoPlayer>
fun addMediaItems(index: Int, mediaItems: MutableList<MediaItem>): Promise<PromisingExoPlayer>
fun moveMediaItem(currentIndex: Int, newIndex: Int): Promise<PromisingExoPlayer>
fun moveMediaItems(fromIndex: Int, toIndex: Int, newIndex: Int): Promise<PromisingExoPlayer>
fun removeMediaItem(index: Int): Promise<PromisingExoPlayer>
fun removeMediaItems(fromIndex: Int, toIndex: Int): Promise<PromisingExoPlayer>
fun clearMediaItems(): Promise<PromisingExoPlayer>
fun prepare(): Promise<PromisingExoPlayer>
fun getPlaybackState(): Promise<Int>
fun getPlaybackSuppressionReason(): Promise<Int>
fun isPlaying(): Promise<Boolean>
fun getPlayerError(): Promise<ExoPlaybackException?>
fun play(): Promise<PromisingExoPlayer>
fun pause(): Promise<PromisingExoPlayer>
fun setPlayWhenReady(playWhenReady: Boolean): Promise<PromisingExoPlayer>
fun getPlayWhenReady(): Promise<Boolean>
fun setRepeatMode(repeatMode: Int): Promise<PromisingExoPlayer>
fun getRepeatMode(): Promise<Int>
fun setShuffleModeEnabled(shuffleModeEnabled: Boolean): Promise<PromisingExoPlayer>
fun getShuffleModeEnabled(): Promise<Boolean>
fun isLoading(): Promise<Boolean>
fun seekToDefaultPosition(): Promise<PromisingExoPlayer>
fun seekToDefaultPosition(windowIndex: Int): Promise<PromisingExoPlayer>
fun seekTo(positionMs: Long): Promise<PromisingExoPlayer>
fun seekTo(windowIndex: Int, positionMs: Long): Promise<PromisingExoPlayer>
fun hasPreviousMediaItem(): Promise<Boolean>
fun seekToPreviousMediaItem(): Promise<PromisingExoPlayer>
fun hasNextMediaItem(): Promise<Boolean>
fun seekToNextMediaItem(): Promise<PromisingExoPlayer>
fun setPlaybackParameters(playbackParameters: PlaybackParameters): Promise<PromisingExoPlayer>
fun getPlaybackParameters(): Promise<PlaybackParameters>
fun stop(): Promise<PromisingExoPlayer>
fun release(): Promise<PromisingExoPlayer>
fun getRendererCount(): Promise<Int>
fun getRendererType(index: Int): Promise<Int>
fun getTrackSelector(): Promise<TrackSelector?>
fun getCurrentTracksInfo(): Promise<TracksInfo?>
fun getCurrentManifest(): Promise<Any?>
fun getCurrentTimeline(): Promise<Timeline>
fun getCurrentPeriodIndex(): Promise<Int>
fun getCurrentMediaItemIndex(): Promise<Int>
fun getNextMediaItemIndex(): Promise<Int>
fun getPreviousMediaItemIndex(): Promise<Int>
fun getCurrentMediaItem(): Promise<MediaItem?>
fun getMediaItemCount(): Promise<Int>
fun getMediaItemAt(index: Int): Promise<MediaItem>
fun getDuration(): Promise<Long>
fun getCurrentPosition(): Promise<Long>
fun getBufferedPosition(): Promise<Long>
fun getBufferedPercentage(): Promise<Int>
fun getTotalBufferedDuration(): Promise<Long>
fun isCurrentMediaItemDynamic(): Promise<Boolean>
fun isCurrentMediaItemLive(): Promise<Boolean>
fun getCurrentLiveOffset(): Promise<Long>
fun isCurrentMediaItemSeekable(): Promise<Boolean>
fun isPlayingAd(): Promise<Boolean>
fun getCurrentAdGroupIndex(): Promise<Int>
fun getCurrentAdIndexInAdGroup(): Promise<Int>
fun getContentDuration(): Promise<Long>
fun getContentPosition(): Promise<Long>
fun getContentBufferedPosition(): Promise<Long>
fun getPlaybackLooper(): Promise<Looper>
fun setMediaSources(mediaSources: MutableList<MediaSource>): Promise<PromisingExoPlayer>
fun setMediaSources(mediaSources: MutableList<MediaSource>, resetPosition: Boolean): Promise<PromisingExoPlayer>
fun setMediaSources(mediaSources: MutableList<MediaSource>, startWindowIndex: Int, startPositionMs: Long): Promise<PromisingExoPlayer>
fun setMediaSource(mediaSource: MediaSource): Promise<PromisingExoPlayer>
fun setMediaSource(mediaSource: MediaSource, startPositionMs: Long): Promise<PromisingExoPlayer>
fun setMediaSource(mediaSource: MediaSource, resetPosition: Boolean): Promise<PromisingExoPlayer>
fun addMediaSource(mediaSource: MediaSource): Promise<PromisingExoPlayer>
fun addMediaSource(index: Int, mediaSource: MediaSource): Promise<PromisingExoPlayer>
fun addMediaSources(mediaSources: MutableList<MediaSource>): Promise<PromisingExoPlayer>
fun addMediaSources(index: Int, mediaSources: MutableList<MediaSource>): Promise<PromisingExoPlayer>
fun setShuffleOrder(shuffleOrder: ShuffleOrder): Promise<PromisingExoPlayer>
fun createMessage(target: PlayerMessage.Target): Promise<PlayerMessage>
fun setSeekParameters(seekParameters: SeekParameters?): Promise<PromisingExoPlayer>
fun getSeekParameters(): Promise<SeekParameters>
fun setForegroundMode(foregroundMode: Boolean): Promise<PromisingExoPlayer>
fun setPauseAtEndOfMediaItems(pauseAtEndOfMediaItems: Boolean): Promise<PromisingExoPlayer>
fun getPauseAtEndOfMediaItems(): Promise<Boolean>
fun experimentalSetOffloadSchedulingEnabled(offloadSchedulingEnabled: Boolean): Promise<PromisingExoPlayer>
}
| projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/playback/exoplayer/PromisingExoPlayer.kt | 3320073516 |
package xyz.b515.schedule.api
import okhttp3.*
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.*
import java.util.concurrent.TimeUnit
object ZfRetrofit {
private val server = "http://gdjwgl.bjut.edu.cn"
private val headers = Headers.Builder()
.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3014.0 Safari/537.36")
.add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
.add("Accept-Encoding", "gzip, deflate, sdch")
.add("Accept-Language", "zh-CN,en-US;q=0.8")
.build()
private val httpClient = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.addInterceptor { chain -> chain.proceed(chain.request().newBuilder().headers(headers).build()) }
.cookieJar(object : CookieJar {
private val cookieStore = HashMap<String, List<Cookie>>()
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
cookieStore.put(url.host(), cookies)
}
override fun loadForRequest(url: HttpUrl): List<Cookie> {
val cookies = cookieStore[url.host()]
return cookies ?: ArrayList()
}
})
.build()
val zfService: ZfService by lazy {
Retrofit.Builder()
.baseUrl(server)
.client(httpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create())
.build()
.create(ZfService::class.java)
}
}
| app/src/main/kotlin/xyz/b515/schedule/api/ZfRetrofit.kt | 715707583 |
package com.tumpaca.tp.util
import android.webkit.WebView
import com.tumpaca.tp.view.TPWebViewClient
/**
* UIの便利メソッド集
* Created by yabu on 2016/10/12.
*/
object UIUtil {
val TPWebViewClient = TPWebViewClient("style.css")
val DoNotHorizontalScrollWebViewClient = TPWebViewClient("doNotHorizontalScroll.css")
fun loadCss(webView: WebView): Unit {
webView.setWebViewClient(TPWebViewClient)
}
fun doNotHorizontalScroll(webView: WebView): Unit {
webView.setWebViewClient(DoNotHorizontalScrollWebViewClient)
}
} | app/src/main/kotlin/com/tumpaca/tp/util/UIUtil.kt | 2303666242 |
/*
Copyright 2016 Dániel Sólyom
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 ds.violin.v1.datasource.base
/**
* the SessionHandling has the session's [state]
*
* @param S type of the state
*/
interface SessionHandling<S> {
var state: S?
}
| ViolinDS/app/src/main/java/ds/violin/v1/datasource/base/Session.kt | 2889133121 |
/*
* Copyright (C) 2014 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 okhttp3.internal.ws
import java.io.Closeable
import java.io.IOException
import java.net.ProtocolException
import java.util.concurrent.TimeUnit
import okhttp3.internal.and
import okhttp3.internal.toHexString
import okhttp3.internal.ws.WebSocketProtocol.B0_FLAG_FIN
import okhttp3.internal.ws.WebSocketProtocol.B0_FLAG_RSV1
import okhttp3.internal.ws.WebSocketProtocol.B0_FLAG_RSV2
import okhttp3.internal.ws.WebSocketProtocol.B0_FLAG_RSV3
import okhttp3.internal.ws.WebSocketProtocol.B0_MASK_OPCODE
import okhttp3.internal.ws.WebSocketProtocol.B1_FLAG_MASK
import okhttp3.internal.ws.WebSocketProtocol.B1_MASK_LENGTH
import okhttp3.internal.ws.WebSocketProtocol.CLOSE_NO_STATUS_CODE
import okhttp3.internal.ws.WebSocketProtocol.OPCODE_BINARY
import okhttp3.internal.ws.WebSocketProtocol.OPCODE_CONTINUATION
import okhttp3.internal.ws.WebSocketProtocol.OPCODE_CONTROL_CLOSE
import okhttp3.internal.ws.WebSocketProtocol.OPCODE_CONTROL_PING
import okhttp3.internal.ws.WebSocketProtocol.OPCODE_CONTROL_PONG
import okhttp3.internal.ws.WebSocketProtocol.OPCODE_FLAG_CONTROL
import okhttp3.internal.ws.WebSocketProtocol.OPCODE_TEXT
import okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_BYTE_MAX
import okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_LONG
import okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_SHORT
import okhttp3.internal.ws.WebSocketProtocol.toggleMask
import okio.Buffer
import okio.BufferedSource
import okio.ByteString
/**
* An [RFC 6455][rfc_6455]-compatible WebSocket frame reader.
*
* This class is not thread safe.
*
* [rfc_6455]: http://tools.ietf.org/html/rfc6455
*/
class WebSocketReader(
private val isClient: Boolean,
val source: BufferedSource,
private val frameCallback: FrameCallback,
private val perMessageDeflate: Boolean,
private val noContextTakeover: Boolean
) : Closeable {
private var closed = false
// Stateful data about the current frame.
private var opcode = 0
private var frameLength = 0L
private var isFinalFrame = false
private var isControlFrame = false
private var readingCompressedMessage = false
private val controlFrameBuffer = Buffer()
private val messageFrameBuffer = Buffer()
/** Lazily initialized on first use. */
private var messageInflater: MessageInflater? = null
// Masks are only a concern for server writers.
private val maskKey: ByteArray? = if (isClient) null else ByteArray(4)
private val maskCursor: Buffer.UnsafeCursor? = if (isClient) null else Buffer.UnsafeCursor()
interface FrameCallback {
@Throws(IOException::class)
fun onReadMessage(text: String)
@Throws(IOException::class)
fun onReadMessage(bytes: ByteString)
fun onReadPing(payload: ByteString)
fun onReadPong(payload: ByteString)
fun onReadClose(code: Int, reason: String)
}
/**
* Process the next protocol frame.
*
* * If it is a control frame this will result in a single call to [FrameCallback].
* * If it is a message frame this will result in a single call to [FrameCallback.onReadMessage].
* If the message spans multiple frames, each interleaved control frame will result in a
* corresponding call to [FrameCallback].
*/
@Throws(IOException::class)
fun processNextFrame() {
readHeader()
if (isControlFrame) {
readControlFrame()
} else {
readMessageFrame()
}
}
@Throws(IOException::class, ProtocolException::class)
private fun readHeader() {
if (closed) throw IOException("closed")
// Disable the timeout to read the first byte of a new frame.
val b0: Int
val timeoutBefore = source.timeout().timeoutNanos()
source.timeout().clearTimeout()
try {
b0 = source.readByte() and 0xff
} finally {
source.timeout().timeout(timeoutBefore, TimeUnit.NANOSECONDS)
}
opcode = b0 and B0_MASK_OPCODE
isFinalFrame = b0 and B0_FLAG_FIN != 0
isControlFrame = b0 and OPCODE_FLAG_CONTROL != 0
// Control frames must be final frames (cannot contain continuations).
if (isControlFrame && !isFinalFrame) {
throw ProtocolException("Control frames must be final.")
}
val reservedFlag1 = b0 and B0_FLAG_RSV1 != 0
when (opcode) {
OPCODE_TEXT, OPCODE_BINARY -> {
readingCompressedMessage = if (reservedFlag1) {
if (!perMessageDeflate) throw ProtocolException("Unexpected rsv1 flag")
true
} else {
false
}
}
else -> {
if (reservedFlag1) throw ProtocolException("Unexpected rsv1 flag")
}
}
val reservedFlag2 = b0 and B0_FLAG_RSV2 != 0
if (reservedFlag2) throw ProtocolException("Unexpected rsv2 flag")
val reservedFlag3 = b0 and B0_FLAG_RSV3 != 0
if (reservedFlag3) throw ProtocolException("Unexpected rsv3 flag")
val b1 = source.readByte() and 0xff
val isMasked = b1 and B1_FLAG_MASK != 0
if (isMasked == isClient) {
// Masked payloads must be read on the server. Unmasked payloads must be read on the client.
throw ProtocolException(if (isClient) {
"Server-sent frames must not be masked."
} else {
"Client-sent frames must be masked."
})
}
// Get frame length, optionally reading from follow-up bytes if indicated by special values.
frameLength = (b1 and B1_MASK_LENGTH).toLong()
if (frameLength == PAYLOAD_SHORT.toLong()) {
frameLength = (source.readShort() and 0xffff).toLong() // Value is unsigned.
} else if (frameLength == PAYLOAD_LONG.toLong()) {
frameLength = source.readLong()
if (frameLength < 0L) {
throw ProtocolException(
"Frame length 0x${frameLength.toHexString()} > 0x7FFFFFFFFFFFFFFF")
}
}
if (isControlFrame && frameLength > PAYLOAD_BYTE_MAX) {
throw ProtocolException("Control frame must be less than ${PAYLOAD_BYTE_MAX}B.")
}
if (isMasked) {
// Read the masking key as bytes so that they can be used directly for unmasking.
source.readFully(maskKey!!)
}
}
@Throws(IOException::class)
private fun readControlFrame() {
if (frameLength > 0L) {
source.readFully(controlFrameBuffer, frameLength)
if (!isClient) {
controlFrameBuffer.readAndWriteUnsafe(maskCursor!!)
maskCursor.seek(0)
toggleMask(maskCursor, maskKey!!)
maskCursor.close()
}
}
when (opcode) {
OPCODE_CONTROL_PING -> {
frameCallback.onReadPing(controlFrameBuffer.readByteString())
}
OPCODE_CONTROL_PONG -> {
frameCallback.onReadPong(controlFrameBuffer.readByteString())
}
OPCODE_CONTROL_CLOSE -> {
var code = CLOSE_NO_STATUS_CODE
var reason = ""
val bufferSize = controlFrameBuffer.size
if (bufferSize == 1L) {
throw ProtocolException("Malformed close payload length of 1.")
} else if (bufferSize != 0L) {
code = controlFrameBuffer.readShort().toInt()
reason = controlFrameBuffer.readUtf8()
val codeExceptionMessage = WebSocketProtocol.closeCodeExceptionMessage(code)
if (codeExceptionMessage != null) throw ProtocolException(codeExceptionMessage)
}
frameCallback.onReadClose(code, reason)
closed = true
}
else -> {
throw ProtocolException("Unknown control opcode: " + opcode.toHexString())
}
}
}
@Throws(IOException::class)
private fun readMessageFrame() {
val opcode = this.opcode
if (opcode != OPCODE_TEXT && opcode != OPCODE_BINARY) {
throw ProtocolException("Unknown opcode: ${opcode.toHexString()}")
}
readMessage()
if (readingCompressedMessage) {
val messageInflater = this.messageInflater
?: MessageInflater(noContextTakeover).also { this.messageInflater = it }
messageInflater.inflate(messageFrameBuffer)
}
if (opcode == OPCODE_TEXT) {
frameCallback.onReadMessage(messageFrameBuffer.readUtf8())
} else {
frameCallback.onReadMessage(messageFrameBuffer.readByteString())
}
}
/** Read headers and process any control frames until we reach a non-control frame. */
@Throws(IOException::class)
private fun readUntilNonControlFrame() {
while (!closed) {
readHeader()
if (!isControlFrame) {
break
}
readControlFrame()
}
}
/**
* Reads a message body into across one or more frames. Control frames that occur between
* fragments will be processed. If the message payload is masked this will unmask as it's being
* processed.
*/
@Throws(IOException::class)
private fun readMessage() {
while (true) {
if (closed) throw IOException("closed")
if (frameLength > 0L) {
source.readFully(messageFrameBuffer, frameLength)
if (!isClient) {
messageFrameBuffer.readAndWriteUnsafe(maskCursor!!)
maskCursor.seek(messageFrameBuffer.size - frameLength)
toggleMask(maskCursor, maskKey!!)
maskCursor.close()
}
}
if (isFinalFrame) break // We are exhausted and have no continuations.
readUntilNonControlFrame()
if (opcode != OPCODE_CONTINUATION) {
throw ProtocolException("Expected continuation opcode. Got: ${opcode.toHexString()}")
}
}
}
@Throws(IOException::class)
override fun close() {
messageInflater?.close()
}
}
| okhttp/src/main/kotlin/okhttp3/internal/ws/WebSocketReader.kt | 270135556 |
@file:RestrictTo(RestrictTo.Scope.LIBRARY)
package com.didichuxing.doraemonkit.kit.network.utils
import androidx.annotation.RestrictTo
import com.didichuxing.doraemonkit.okhttp_api.OkHttpWrap
import okhttp3.Response
import okio.Buffer
import okio.GzipSource
import java.nio.charset.Charset
internal fun Response.encoding() =
this.header("content-encoding") ?: this.header("Content-Encoding")
internal fun Response.charset(): Charset {
this.encoding()
?.takeIf { Charset.isSupported(it) }
?.also {
return Charset.forName(it)
}
return OkHttpWrap.toResponseBody(this)?.contentType()?.charset() ?: Charset.defaultCharset()
}
internal fun Response.bodyContent(): String = OkHttpWrap.toResponseBody(this)
?.let { body ->
val source = body.source()
.apply {
request(Long.MAX_VALUE)
}
var buffer = source.buffer
val encoding = encoding()
if ("gzip".equals(encoding, true)) {
GzipSource(buffer.clone()).use { gzippedBody ->
buffer = Buffer().also { it.writeAll(gzippedBody) }
}
}
buffer
}
?.clone()
?.readString(charset())
?: ""
| Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/network/utils/OkHttpResponse.kt | 4254877811 |
package com.ternaryop.photoshelf.lifecycle
import androidx.lifecycle.Observer
/**
* Used as a wrapper for data that is exposed via a LiveData that represents an event.
*/
class EventObserver<T>(private val onEventUnhandledContent: (T) -> Unit) : Observer<Event<T>> {
override fun onChanged(event: Event<T>?) {
event?.getContentIfNotHandled()?.let(onEventUnhandledContent)
}
}
open class Event<out T>(private val content: T) {
var hasBeenHandled = false
private set // Allow external read but not write
/**
* Returns the content and prevents its use again.
*/
fun getContentIfNotHandled(): T? {
return if (hasBeenHandled) {
null
} else {
hasBeenHandled = true
content
}
}
/**
* Returns the content, even if it's already been handled.
*/
fun peekContent(): T = content
}
| core/src/main/java/com/ternaryop/photoshelf/lifecycle/Event.kt | 2966366790 |
/*
* Copyright 2022, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.internal.gradle.github.pages
import java.io.File
import java.nio.file.Path
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.FileCollection
import org.gradle.api.logging.Logger
import io.spine.internal.gradle.git.Repository
/**
* Performs the update of GitHub pages.
*/
fun Task.updateGhPages(project: Project) {
val plugin = project.plugins.getPlugin(UpdateGitHubPages::class.java)
with(plugin) {
SshKey(rootFolder).register()
}
val repository = Repository.forPublishingDocumentation()
val updateJavadoc = with(plugin) {
UpdateJavadoc(project, javadocOutputFolder, repository, logger)
}
val updateDokka = with(plugin) {
UpdateDokka(project, dokkaOutputFolder, repository, logger)
}
repository.use {
updateJavadoc.run()
updateDokka.run()
repository.push()
}
}
private abstract class UpdateDocumentation(
private val project: Project,
private val docsSourceFolder: Path,
private val repository: Repository,
private val logger: Logger
) {
/**
* The folder under the repository's root(`/`) for storing documentation.
*
* The value should not contain any leading or trailing file separators.
*
* The absolute path to the project's documentation is made by appending its
* name to the end, making `/docsDestinationFolder/project.name`.
*/
protected abstract val docsDestinationFolder: String
/**
* The name of the tool used to generate the documentation to update.
*
* This name will appear in logs as part of a message.
*/
protected abstract val toolName: String
private val mostRecentFolder by lazy {
File("${repository.location}/${docsDestinationFolder}/${project.name}")
}
fun run() {
val module = project.name
logger.debug("Update of the $toolName documentation for module `$module` started.")
val documentation = replaceMostRecentDocs()
copyIntoVersionDir(documentation)
val version = project.version
val updateMessage = "Update $toolName documentation for module `$module` as for " +
"version $version"
repository.commitAllChanges(updateMessage)
logger.debug("Update of the $toolName documentation for `$module` successfully finished.")
}
private fun replaceMostRecentDocs(): ConfigurableFileCollection {
val generatedDocs = project.files(docsSourceFolder)
logger.debug("Replacing the most recent $toolName documentation in ${mostRecentFolder}.")
copyDocs(generatedDocs, mostRecentFolder)
return generatedDocs
}
private fun copyDocs(source: FileCollection, destination: File) {
destination.mkdir()
project.copy {
from(source)
into(destination)
}
}
private fun copyIntoVersionDir(generatedDocs: ConfigurableFileCollection) {
val versionedDocDir = File("$mostRecentFolder/v/${project.version}")
logger.debug("Storing the new version of $toolName documentation in `${versionedDocDir}.")
copyDocs(generatedDocs, versionedDocDir)
}
}
private class UpdateJavadoc(
project: Project,
docsSourceFolder: Path,
repository: Repository,
logger: Logger
) : UpdateDocumentation(project, docsSourceFolder, repository, logger) {
override val docsDestinationFolder: String
get() = "reference"
override val toolName: String
get() = "Javadoc"
}
private class UpdateDokka(
project: Project,
docsSourceFolder: Path,
repository: Repository,
logger: Logger
) : UpdateDocumentation(project, docsSourceFolder, repository, logger) {
override val docsDestinationFolder: String
get() = "dokka-reference"
override val toolName: String
get() = "Dokka"
}
| buildSrc/src/main/kotlin/io/spine/internal/gradle/github/pages/Update.kt | 3681919698 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.learning.katas.windowing.addingtimestamp.withtimestamps
import org.apache.beam.learning.katas.windowing.addingtimestamp.withtimestamps.Task.applyTransform
import org.apache.beam.sdk.testing.PAssert
import org.apache.beam.sdk.testing.TestPipeline
import org.apache.beam.sdk.transforms.Create
import org.apache.beam.sdk.transforms.DoFn
import org.apache.beam.sdk.transforms.ParDo
import org.apache.beam.sdk.values.KV
import org.joda.time.DateTime
import org.joda.time.Instant
import org.junit.Rule
import org.junit.Test
import java.io.Serializable
class TaskTest : Serializable {
@get:Rule
@Transient
val testPipeline: TestPipeline = TestPipeline.create()
@Test
fun windowing_adding_timestamp_withtimestamps() {
val events = listOf(
Event("1", "book-order", DateTime.parse("2019-06-01T00:00:00+00:00")),
Event("2", "pencil-order", DateTime.parse("2019-06-02T00:00:00+00:00")),
Event("3", "paper-order", DateTime.parse("2019-06-03T00:00:00+00:00")),
Event("4", "pencil-order", DateTime.parse("2019-06-04T00:00:00+00:00")),
Event("5", "book-order", DateTime.parse("2019-06-05T00:00:00+00:00"))
)
val eventsPColl = testPipeline.apply(Create.of(events))
val results = applyTransform(eventsPColl)
val timestampedResults = results.apply(
"KV<Event, Instant>",
ParDo.of(object : DoFn<Event, KV<Event, Instant>>() {
@ProcessElement
fun processElement(context: ProcessContext, out: OutputReceiver<KV<Event, Instant>>) {
val event = context.element()
out.output(KV.of(event, context.timestamp()))
}
})
)
PAssert.that(results).containsInAnyOrder(events)
PAssert.that(timestampedResults).containsInAnyOrder(
KV.of(events[0], events[0].date.toInstant()),
KV.of(events[1], events[1].date.toInstant()),
KV.of(events[2], events[2].date.toInstant()),
KV.of(events[3], events[3].date.toInstant()),
KV.of(events[4], events[4].date.toInstant())
)
testPipeline.run().waitUntilFinish()
}
} | learning/katas/kotlin/Windowing/Adding Timestamp/WithTimestamps/test/org/apache/beam/learning/katas/windowing/addingtimestamp/withtimestamps/TaskTest.kt | 2116748423 |
/*
* Copyright @ 2020 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.videobridge.cc.allocation
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import org.json.simple.JSONObject
@JsonIgnoreProperties(ignoreUnknown = true)
data class VideoConstraints(
val maxHeight: Int,
val maxFrameRate: Double = -1.0
) {
override fun toString(): String = JSONObject().apply {
this["maxHeight"] = maxHeight
this["maxFrameRate"] = maxFrameRate
}.toJSONString()
companion object {
val NOTHING = VideoConstraints(0)
}
}
fun Map<String, VideoConstraints>.prettyPrint(): String =
entries.joinToString { "${it.key}->${it.value.maxHeight}" }
| jvb/src/main/kotlin/org/jitsi/videobridge/cc/allocation/VideoConstraints.kt | 1470542306 |
/*
* Copyright @ 2020-Present 8x8, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.videobridge.message
import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.exc.InvalidTypeIdException
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.collections.shouldContainExactly
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.shouldNotInclude
import io.kotest.matchers.types.shouldBeInstanceOf
import org.jitsi.videobridge.cc.allocation.VideoConstraints
import org.jitsi.videobridge.message.BridgeChannelMessage.Companion.parse
import org.jitsi.videobridge.util.VideoType
import org.json.simple.JSONArray
import org.json.simple.JSONObject
import org.json.simple.parser.JSONParser
@Suppress("BlockingMethodInNonBlockingContext")
class BridgeChannelMessageTest : ShouldSpec() {
init {
context("serializing") {
should("encode the type as colibriClass") {
// Any message will do, this one is just simple
val message = ClientHelloMessage()
val parsed = JSONParser().parse(message.toJson())
parsed.shouldBeInstanceOf<JSONObject>()
val parsedColibriClass = parsed["colibriClass"]
parsedColibriClass.shouldBeInstanceOf<String>()
parsedColibriClass shouldBe message.type
}
}
context("parsing and serializing a SelectedEndpointsChangedEvent message") {
val parsed = parse(SELECTED_ENDPOINTS_MESSAGE)
should("parse to the correct type") {
parsed.shouldBeInstanceOf<SelectedEndpointsMessage>()
}
should("parse the list of endpoints correctly") {
parsed as SelectedEndpointsMessage
parsed.selectedEndpoints shouldBe listOf("abcdabcd", "12341234")
}
should("serialize and de-serialize correctly") {
val selectedEndpoints = listOf("abcdabcd", "12341234")
val serialized = SelectedEndpointsMessage(selectedEndpoints).toJson()
val parsed2 = parse(serialized)
parsed2.shouldBeInstanceOf<SelectedEndpointsMessage>()
parsed2.selectedEndpoints shouldBe selectedEndpoints
}
}
context("parsing an invalid message") {
shouldThrow<JsonProcessingException> {
parse("{invalid json")
}
shouldThrow<JsonProcessingException> {
parse("")
}
shouldThrow<InvalidTypeIdException> {
parse("{}")
}
shouldThrow<InvalidTypeIdException> {
parse("""{"colibriClass": "invalid-colibri-class" }""")
}
context("when some of the message-specific fields are missing/invalid") {
shouldThrow<JsonProcessingException> {
parse("""{"colibriClass": "SelectedEndpointsChangedEvent" }""")
}
shouldThrow<JsonProcessingException> {
parse("""{"colibriClass": "SelectedEndpointsChangedEvent", "selectedEndpoints": 5 }""")
}
}
}
context("serializing and parsing EndpointMessage") {
val endpointsMessage = EndpointMessage("to_value")
endpointsMessage.otherFields["other_field1"] = "other_value1"
endpointsMessage.put("other_field2", 97)
val json = endpointsMessage.toJson()
// Make sure we don't mistakenly serialize the "broadcast" flag.
json shouldNotInclude "broadcast"
// Make sure we don't mistakenly serialize the "type".
json shouldNotInclude """
"type":
""".trimIndent()
val parsed = parse(json)
parsed.shouldBeInstanceOf<EndpointMessage>()
parsed.from shouldBe null
parsed.to shouldBe "to_value"
parsed.otherFields["other_field1"] shouldBe "other_value1"
parsed.otherFields["other_field2"] shouldBe 97
endpointsMessage.from = "new"
(parse(endpointsMessage.toJson()) as EndpointMessage).from shouldBe "new"
context("parsing") {
val parsed2 = parse(ENDPOINT_MESSAGE)
parsed2 as EndpointMessage
parsed2.from shouldBe null
parsed2.to shouldBe "to_value"
parsed2.otherFields["other_field1"] shouldBe "other_value1"
parsed2.otherFields["other_field2"] shouldBe 97
}
}
context("serializing and parsing DominantSpeakerMessage") {
val previousSpeakers = listOf("p1", "p2")
val original = DominantSpeakerMessage("d", previousSpeakers)
val parsed = parse(original.toJson())
parsed.shouldBeInstanceOf<DominantSpeakerMessage>()
parsed.dominantSpeakerEndpoint shouldBe "d"
parsed.previousSpeakers shouldBe listOf("p1", "p2")
}
context("serializing and parsing ServerHello") {
context("without a version") {
val parsed = parse(ServerHelloMessage().toJson())
parsed.shouldBeInstanceOf<ServerHelloMessage>()
parsed.version shouldBe null
}
context("with a version") {
val message = ServerHelloMessage("v")
val parsed = parse(message.toJson())
parsed.shouldBeInstanceOf<ServerHelloMessage>()
parsed.version shouldBe "v"
}
}
context("serializing and parsing ClientHello") {
val parsed = parse(ClientHelloMessage().toJson())
parsed.shouldBeInstanceOf<ClientHelloMessage>()
}
context("serializing and parsing EndpointConnectionStatusMessage") {
val parsed = parse(EndpointConnectionStatusMessage("abcdabcd", true).toJson())
parsed.shouldBeInstanceOf<EndpointConnectionStatusMessage>()
parsed.endpoint shouldBe "abcdabcd"
parsed.active shouldBe "true"
}
context("serializing and parsing ForwardedEndpointsMessage") {
val forwardedEndpoints = setOf("a", "b", "c")
val message = ForwardedEndpointsMessage(forwardedEndpoints)
val parsed = parse(message.toJson())
parsed.shouldBeInstanceOf<ForwardedEndpointsMessage>()
parsed.forwardedEndpoints shouldContainExactly forwardedEndpoints
// Make sure the forwardedEndpoints field is serialized as lastNEndpoints as the client (presumably) expects
val parsedJson = JSONParser().parse(message.toJson())
parsedJson.shouldBeInstanceOf<JSONObject>()
val parsedForwardedEndpoints = parsedJson["lastNEndpoints"]
parsedForwardedEndpoints.shouldBeInstanceOf<JSONArray>()
parsedForwardedEndpoints.toList() shouldContainExactly forwardedEndpoints
}
context("serializing and parsing VideoConstraints") {
val videoConstraints: VideoConstraints = jacksonObjectMapper().readValue(VIDEO_CONSTRAINTS)
videoConstraints.maxHeight shouldBe 1080
videoConstraints.maxFrameRate shouldBe 15.0
}
context("and SenderVideoConstraintsMessage") {
val senderVideoConstraintsMessage = SenderVideoConstraintsMessage(1080)
val parsed = parse(senderVideoConstraintsMessage.toJson())
parsed.shouldBeInstanceOf<SenderVideoConstraintsMessage>()
parsed.videoConstraints.idealHeight shouldBe 1080
}
context("serializing and parsing AddReceiver") {
val message = AddReceiverMessage("bridge1", "abcdabcd", VideoConstraints(360))
val parsed = parse(message.toJson())
parsed.shouldBeInstanceOf<AddReceiverMessage>()
parsed.bridgeId shouldBe "bridge1"
parsed.endpointId shouldBe "abcdabcd"
parsed.videoConstraints shouldBe VideoConstraints(360)
}
context("serializing and parsing RemoveReceiver") {
val message = RemoveReceiverMessage("bridge1", "abcdabcd")
val parsed = parse(message.toJson())
parsed.shouldBeInstanceOf<RemoveReceiverMessage>()
parsed.bridgeId shouldBe "bridge1"
parsed.endpointId shouldBe "abcdabcd"
}
context("serializing and parsing VideoType") {
val videoTypeMessage = VideoTypeMessage(VideoType.DESKTOP)
videoTypeMessage.videoType shouldBe VideoType.DESKTOP
parse(videoTypeMessage.toJson()).apply {
shouldBeInstanceOf<VideoTypeMessage>()
videoType shouldBe VideoType.DESKTOP
}
listOf("none", "NONE", "None", "nOnE").forEach {
val jsonString = """
{
"colibriClass" : "VideoTypeMessage",
"videoType" : "$it"
}
"""
parse(jsonString).apply {
shouldBeInstanceOf<VideoTypeMessage>()
videoType shouldBe VideoType.NONE
}
}
val jsonString = """
{
"colibriClass" : "VideoTypeMessage",
"videoType" : "desktop_high_fps"
}
"""
parse(jsonString).apply {
shouldBeInstanceOf<VideoTypeMessage>()
videoType shouldBe VideoType.DESKTOP_HIGH_FPS
}
}
context("Parsing ReceiverVideoConstraints") {
context("With all fields present") {
val parsed = parse(RECEIVER_VIDEO_CONSTRAINTS)
parsed.shouldBeInstanceOf<ReceiverVideoConstraintsMessage>()
parsed.lastN shouldBe 3
parsed.onStageEndpoints shouldBe listOf("onstage1", "onstage2")
parsed.selectedEndpoints shouldBe listOf("selected1", "selected2")
parsed.defaultConstraints shouldBe VideoConstraints(0)
val constraints = parsed.constraints
constraints.shouldNotBeNull()
constraints.size shouldBe 3
constraints["epOnStage"] shouldBe VideoConstraints(720)
constraints["epThumbnail1"] shouldBe VideoConstraints(180)
constraints["epThumbnail2"] shouldBe VideoConstraints(180, 30.0)
}
context("With fields missing") {
val parsed = parse(RECEIVER_VIDEO_CONSTRAINTS_EMPTY)
parsed.shouldBeInstanceOf<ReceiverVideoConstraintsMessage>()
parsed.lastN shouldBe null
parsed.onStageEndpoints shouldBe null
parsed.selectedEndpoints shouldBe null
parsed.defaultConstraints shouldBe null
parsed.constraints shouldBe null
}
}
xcontext("Serializing performance") {
val times = 1_000_000
val objectMapper = ObjectMapper()
fun toJsonJackson(m: DominantSpeakerMessage): String = objectMapper.writeValueAsString(m)
fun toJsonJsonSimple(m: DominantSpeakerMessage) = JSONObject().apply {
this["dominantSpeakerEndpoint"] = m.dominantSpeakerEndpoint
}.toJSONString()
fun toJsonStringConcat(m: DominantSpeakerMessage) =
"{\"colibriClass\":\"DominantSpeakerEndpointChangeEvent\",\"dominantSpeakerEndpoint\":\"" +
m.dominantSpeakerEndpoint + "\"}"
fun toJsonStringTemplate(m: DominantSpeakerMessage) =
"{\"colibriClass\":\"${DominantSpeakerMessage.TYPE}\"," +
"\"dominantSpeakerEndpoint\":\"${m.dominantSpeakerEndpoint}\"}"
fun toJsonRawStringTemplate(m: DominantSpeakerMessage) = """
{"colibriClass":"${DominantSpeakerMessage.TYPE}",
"dominantSpeakerEndpoint":"${m.dominantSpeakerEndpoint}"}
"""
fun runTest(f: (DominantSpeakerMessage) -> String): Long {
val start = System.currentTimeMillis()
for (i in 0..times) {
f(DominantSpeakerMessage(i.toString()))
}
val end = System.currentTimeMillis()
return end - start
}
System.err.println("Times=$times")
System.err.println("Jackson: ${runTest { toJsonJackson(it) }}")
System.err.println("Json-simple: ${runTest { toJsonJsonSimple(it) }}")
System.err.println("String concat: ${runTest { toJsonStringConcat(it) }}")
System.err.println("String template: ${runTest { toJsonStringTemplate(it) }}")
System.err.println("Raw string template: ${runTest { toJsonRawStringTemplate(it) }}")
System.err.println("Raw string template (trim): ${runTest { toJsonRawStringTemplate(it).trimMargin() }}")
}
}
companion object {
const val SELECTED_ENDPOINTS_MESSAGE = """
{
"colibriClass": "SelectedEndpointsChangedEvent",
"selectedEndpoints": [ "abcdabcd", "12341234" ]
}
"""
const val ENDPOINT_MESSAGE = """
{
"colibriClass": "EndpointMessage",
"to": "to_value",
"other_field1": "other_value1",
"other_field2": 97
}
"""
const val VIDEO_CONSTRAINTS = """
{
"maxHeight": 1080,
"maxFrameRate": 15.0
}
"""
const val RECEIVER_VIDEO_CONSTRAINTS_EMPTY = """
{
"colibriClass": "ReceiverVideoConstraints"
}
"""
const val RECEIVER_VIDEO_CONSTRAINTS = """
{
"colibriClass": "ReceiverVideoConstraints",
"lastN": 3,
"selectedEndpoints": [ "selected1", "selected2" ],
"onStageEndpoints": [ "onstage1", "onstage2" ],
"defaultConstraints": { "maxHeight": 0 },
"constraints": {
"epOnStage": { "maxHeight": 720 },
"epThumbnail1": { "maxHeight": 180 },
"epThumbnail2": { "maxHeight": 180, "maxFrameRate": 30 }
}
}
"""
}
}
| jvb/src/test/kotlin/org/jitsi/videobridge/message/BridgeChannelMessageTest.kt | 1334812604 |
/*
* Copyright 2015, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.testing.notes.notedetail
import android.app.Activity
import android.content.Intent
import android.support.test.espresso.Espresso
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.matcher.ViewMatchers.*
import android.support.test.filters.LargeTest
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import com.example.android.testing.notes.R
import com.example.android.testing.notes.data.FakeNotesServiceApiImpl
import com.example.android.testing.notes.data.Note
import org.hamcrest.Matchers.allOf
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* Tests for the notes screen, the main screen which contains a list of all notes.
*/
@RunWith(AndroidJUnit4::class)
@LargeTest
class NoteDetailScreenTest {
private val NOTE_TITLE = "ATSL"
private val NOTE_DESCRIPTION = "Rocks"
private val NOTE_IMAGE = "file:///android_asset/atsl-logo.png"
/**
* [Note] stub that is added to the fake service API layer.
*/
private val NOTE = Note(NOTE_TITLE, NOTE_DESCRIPTION, NOTE_IMAGE)
/**
* [ActivityTestRule] is a JUnit [@Rule][Rule] to launch your activity under test.
*
*
* Rules are interceptors which are executed for each test method and are important building
* blocks of Junit tests.
*
*
* Sometimes an [Activity] requires a custom start [Intent] to receive data
* from the source Activity. ActivityTestRule has a feature which let's you lazily start the
* Activity under test, so you can control the Intent that is used to start the target Activity.
*/
@Rule @JvmField
var mNoteDetailActivityTestRule = ActivityTestRule(NoteDetailActivity::class.java, true /* Initial touch mode */,
false /* Lazily launch activity */)
/**
* Setup your test fixture with a fake note id. The [NoteDetailActivity] is started with
* a particular note id, which is then loaded from the service API.
*
*
* Note that this test runs hermetically and is fully isolated using a fake implementation of
* the service API. This is a great way to make your tests more reliable and faster at the same
* time, since they are isolated from any outside dependencies.
*/
@Before
fun intentWithStubbedNoteId() {
// Add a note stub to the fake service api layer.
FakeNotesServiceApiImpl.addNotes(NOTE)
// Lazily start the Activity from the ActivityTestRule this time to inject the start Intent
val startIntent = Intent()
startIntent.putExtra(NoteDetailActivity.EXTRA_NOTE_ID, NOTE.id)
mNoteDetailActivityTestRule.launchActivity(startIntent)
registerIdlingResource()
}
@Test
fun noteDetails_DisplayedInUi() {
// Check that the note title, description and image are displayed
onView(withId(R.id.note_detail_title)).check(matches(withText(NOTE_TITLE)))
onView(withId(R.id.note_detail_description)).check(matches(withText(NOTE_DESCRIPTION)))
onView(withId(R.id.note_detail_image)).check(matches(allOf(
//hasDrawable(),
isDisplayed())))
}
/**
* Unregister your Idling Resource so it can be garbage collected and does not leak any memory.
*/
@After
fun unregisterIdlingResource() {
Espresso.unregisterIdlingResources(
mNoteDetailActivityTestRule.activity.countingIdlingResource)
}
/**
* Convenience method to register an IdlingResources with Espresso. IdlingResource resource is
* a great way to tell Espresso when your app is in an idle state. This helps Espresso to
* synchronize your test actions, which makes tests significantly more reliable.
*/
private fun registerIdlingResource() {
Espresso.registerIdlingResources(
mNoteDetailActivityTestRule.activity.countingIdlingResource)
}
} | app/src/androidTestMock/java/com/example/android/testing/notes/notedetail/NoteDetailScreenTest.kt | 2516641683 |
package com.cout970.computer.proxy
/**
* Created by cout970 on 19/05/2016.
*/
open class CommonProxy {
open fun preInit() {
}
open fun init() {
}
open fun postInit() {
}
} | src/main/kotlin/com/cout970/computer/proxy/CommonProxy.kt | 3789305794 |
/*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) 2016 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker 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.
*
* OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.ng.features.tracklist
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import nl.sogeti.android.gpstracker.ng.features.FeatureConfiguration
import nl.sogeti.android.gpstracker.ng.features.model.TrackSearch
import nl.sogeti.android.opengpstrack.ng.features.R
import javax.inject.Inject
class TrackListActivity : AppCompatActivity() {
@Inject
lateinit var trackSearch: TrackSearch
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tracklist)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
FeatureConfiguration.featureComponent.inject(this)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
if (intent?.action == Intent.ACTION_SEARCH) {
trackSearch.query.value = intent.getStringExtra(SearchManager.QUERY)
}
}
companion object {
fun start(context: Context) {
val intent = Intent(context, TrackListActivity::class.java)
context.startActivity(intent)
}
}
}
| studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/tracklist/TrackListActivity.kt | 425061360 |
package io.gitlab.arturbosch.detekt.sample.extensions
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.RuleSet
import io.gitlab.arturbosch.detekt.api.RuleSetProvider
import io.gitlab.arturbosch.detekt.sample.extensions.rules.TooManyFunctions
import io.gitlab.arturbosch.detekt.sample.extensions.rules.TooManyFunctionsTwo
class SampleProvider : RuleSetProvider {
override val ruleSetId: String = "sample"
override fun instance(config: Config): RuleSet = RuleSet(
ruleSetId,
listOf(
TooManyFunctions(config),
TooManyFunctionsTwo(config)
)
)
}
| detekt-sample-extensions/src/main/kotlin/io/gitlab/arturbosch/detekt/sample/extensions/SampleProvider.kt | 430935602 |
package com.soywiz.vitaorganizer
enum class DumperNames(val shortName: String, val longName: String, val file: String, val size: Long) {
VTLEAK("VT_Leak", "Vitamin Leaked Version", DumperModules.VITAMIN.file, 110535L),
VT1("VT1.0", "Vitamin 1.0 or 1.1", DumperModules.VITAMIN.file, 107851L),
VT2("VT2.0", "Vitamin 2.0", DumperModules.VITAMIN.file, 78682L),
MAI233("Mai.v233.0", "Mai.v233.0", DumperModules.MAI.file, 86442L),
HOMEBREW("HB", "Normal homebrew", "", -1L),
UNKNOWN("UNKNOWN", "Unknown Dumper Version", "", -1L)
}
enum class DumperModules(val file: String) {
VITAMIN("sce_module/steroid.suprx"),
MAI("mai_moe/mai.suprx")
}
class DumperNamesHelper {
fun findDumperBySize(size: Long): DumperNames {
for (dumper in DumperNames.values()) {
if (size == dumper.size)
return dumper
}
return DumperNames.UNKNOWN
}
fun findDumperByShortName(shortName: String): DumperNames {
for (dumper in DumperNames.values()) {
if (dumper.shortName.equals(shortName))
return dumper
}
return DumperNames.UNKNOWN
}
} | src/com/soywiz/vitaorganizer/DumperNames.kt | 1210687683 |
package net.nemerosa.ontrack.it
import net.nemerosa.ontrack.model.security.Account
import net.nemerosa.ontrack.model.security.AccountOntrackUser
class TestOntrackUser(account: Account) : AccountOntrackUser(account)
| ontrack-it-utils/src/main/java/net/nemerosa/ontrack/it/TestOntrackUser.kt | 3575908551 |
package net.nemerosa.ontrack.extension.casc.entities
interface CascEntityPropertyContext : SubCascEntityContext {
} | ontrack-extension-casc/src/main/java/net/nemerosa/ontrack/extension/casc/entities/CascEntityPropertyContext.kt | 4067627714 |
package net.nemerosa.ontrack.git.model.plot
abstract class AbstractGItem : GItem {
override val type: String
get() = javaClass.simpleName.substring(1).lowercase()
}
| ontrack-git/src/main/java/net/nemerosa/ontrack/git/model/plot/AbstractGItem.kt | 1329674348 |
package net.nemerosa.ontrack.extension.issues.support
import net.nemerosa.ontrack.extension.issues.IssueServiceExtensionService
import net.nemerosa.ontrack.extension.issues.model.ConfiguredIssueService
import net.nemerosa.ontrack.model.structure.Project
import org.springframework.stereotype.Service
@Service
class IssueServiceExtensionServiceImpl(
private val contributors: List<IssueServiceExtensionContributor>
) : IssueServiceExtensionService {
override fun getIssueServiceExtension(project: Project): ConfiguredIssueService? =
contributors.mapNotNull {
it.getIssueServiceExtension(project)
}.firstOrNull()
} | ontrack-extension-issues/src/main/java/net/nemerosa/ontrack/extension/issues/support/IssueServiceExtensionServiceImpl.kt | 3512735220 |
package net.nemerosa.ontrack.extension.plugin
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.extra
import org.gradle.kotlin.dsl.withType
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
/**
* Prefix for Ontrack extensions module names
*/
const val PREFIX = "ontrack-extension-"
/**
* Configuration of the Ontrack extension.
*
* @property project Linked project
*/
open class OntrackExtension(
private val project: Project
) {
/**
* ID of the extension (required)
*/
private var id: String? = null
/**
* DSL access
*/
fun id(value: String) {
id = value
}
/**
* Applies Kotlin dependencies
*/
fun kotlin() {
val kotlinVersion = project.extra["kotlinVersion"] as String
println("[ontrack] Applying Kotlin v${kotlinVersion} to ${project.name} plugin")
project.apply(plugin = "kotlin")
project.apply(plugin = "kotlin-spring")
project.tasks.withType<KotlinCompile> {
kotlinOptions {
jvmTarget = "11"
freeCompilerArgs = listOf("-Xjsr305=strict")
}
}
project.dependencies {
"compileOnly"("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}")
"compileOnly"("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}")
}
}
/**
* Dynamic computation of the ID if not specified
*/
fun id(): String {
return id ?: if (project.name.startsWith(PREFIX)) {
project.name.removePrefix(PREFIX)
} else {
throw GradleException("""
Project ${project.path} must declare the Ontrack extension id or have a name like `ontrack-extension-<id>`.
Use:
ontrack {
id "your-extension-id"
}
""".trimIndent())
}
}
/**
* Registers an ontrack core extension
*/
fun uses(extension: String) {
val version = project.extra["ontrackVersion"] as String
project.dependencies {
"compile"("net.nemerosa.ontrack:ontrack-extension-${extension}:${version}")
}
}
}
| ontrack-extension-plugin/src/main/kotlin/net/nemerosa/ontrack/extension/plugin/OntrackExtension.kt | 771481443 |
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package sample.html5canvas
import kotlinx.interop.wasm.dom.*
import kotlinx.wasm.jsinterop.*
fun main() {
val canvas = document.getElementById("myCanvas").asCanvas
val ctx = canvas.getContext("2d")
val rect = canvas.getBoundingClientRect()
val rectLeft = rect.left
val rectTop = rect.top
var mouseX: Int = 0
var mouseY: Int = 0
var draw: Boolean = false
document.setter("onmousemove") { arguments: ArrayList<JsValue> ->
val event = MouseEvent(arguments[0])
mouseX = event.getInt("clientX") - rectLeft
mouseY = event.getInt("clientY") - rectTop
if (mouseX < 0) mouseX = 0
if (mouseX > 639) mouseX = 639
if (mouseY < 0) mouseY = 0
if (mouseY > 479) mouseY = 479
}
document.setter("onmousedown") {
draw = true
}
document.setter("onmouseup") {
draw = false
}
setInterval(10) {
if (draw) {
ctx.strokeStyle = "#222222"
ctx.lineTo(mouseX, mouseY)
ctx.stroke()
} else {
ctx.moveTo(mouseX, mouseY)
ctx.stroke()
}
}
}
| samples/html5Canvas/src/html5CanvasMain/kotlin/main.kt | 1983133889 |
package tornadofx.tests
import javafx.beans.binding.BooleanExpression
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleDoubleProperty
import javafx.collections.FXCollections
import javafx.scene.control.Label
import javafx.stage.Stage
import org.junit.Assert
import org.junit.Test
import org.testfx.api.FxToolkit
import tornadofx.*
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.*
class BindingTest {
val primaryStage: Stage = FxToolkit.registerPrimaryStage()
@Test
fun testBindingFormat() {
val property = SimpleDoubleProperty(Math.PI)
val label = Label()
label.bind(property, format = DecimalFormat("#0.0", DecimalFormatSymbols.getInstance(Locale.ENGLISH)))
Assert.assertEquals("3.1", label.text)
}
@Test
fun observableListBinding() {
val elements = FXCollections.observableArrayList("Hello", "World")
val binding = stringBinding(elements, elements) { this.joinToString(" ")}
val uielement = Label().apply { bind(binding) }
Assert.assertEquals("Hello World", uielement.text)
elements.setAll("Hello", "Changed")
Assert.assertEquals("Hello Changed", uielement.text)
}
@Test
fun nestedBinding() {
val father = Person("Mr Father", 50)
val stepFather = Person("Mr Step Father", 40)
val child = Person("Firstborn Child", 18)
child.parent = father
val fatherName = child.parentProperty().select(Person::nameProperty)
Assert.assertEquals("Mr Father", fatherName.value)
fatherName.value = "Mister Father"
Assert.assertEquals("Mister Father", father.name)
child.parent = stepFather
Assert.assertEquals("Mr Step Father", fatherName.value)
}
@Test
fun booleanBinding() {
val mylist = FXCollections.observableArrayList<String>()
val complete = booleanBinding(mylist) { isNotEmpty() }
Assert.assertFalse(complete.value)
mylist.add("One")
Assert.assertTrue(complete.value)
}
@Test
fun booleanListBinding() {
val mylist = FXCollections.observableArrayList<BooleanExpression>()
val complete = booleanListBinding(mylist) { this }
Assert.assertFalse(complete.value)
mylist.add(SimpleBooleanProperty(true))
Assert.assertTrue(complete.value)
mylist.add(SimpleBooleanProperty(false))
Assert.assertFalse(complete.value)
}
} | src/test/kotlin/tornadofx/tests/BindingTest.kt | 1932123359 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.lang
import com.demonwav.mcdev.translations.lang.gen.LangLexer
import com.intellij.lexer.FlexAdapter
class LangLexerAdapter : FlexAdapter(LangLexer())
| src/main/kotlin/translations/lang/LangLexerAdapter.kt | 684491422 |
package com.google.firebase.quickstart.auth.kotlin
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import com.facebook.AccessToken
import com.facebook.CallbackManager
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.google.firebase.auth.FacebookAuthProvider
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.auth.R
import com.google.firebase.quickstart.auth.databinding.ActivityFacebookBinding
/**
* Demonstrate Firebase Authentication using a Facebook access token.
*/
class FacebookLoginActivity : BaseActivity(), View.OnClickListener {
// [START declare_auth]
private lateinit var auth: FirebaseAuth
// [END declare_auth]
private lateinit var binding: ActivityFacebookBinding
private lateinit var callbackManager: CallbackManager
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityFacebookBinding.inflate(layoutInflater)
setContentView(binding.root)
setProgressBar(binding.progressBar)
binding.buttonFacebookSignout.setOnClickListener(this)
// [START initialize_auth]
// Initialize Firebase Auth
auth = Firebase.auth
// [END initialize_auth]
// [START initialize_fblogin]
// Initialize Facebook Login button
callbackManager = CallbackManager.Factory.create()
binding.buttonFacebookLogin.setReadPermissions("email", "public_profile")
binding.buttonFacebookLogin.registerCallback(callbackManager, object : FacebookCallback<LoginResult> {
override fun onSuccess(loginResult: LoginResult) {
Log.d(TAG, "facebook:onSuccess:$loginResult")
handleFacebookAccessToken(loginResult.accessToken)
}
override fun onCancel() {
Log.d(TAG, "facebook:onCancel")
// [START_EXCLUDE]
updateUI(null)
// [END_EXCLUDE]
}
override fun onError(error: FacebookException) {
Log.d(TAG, "facebook:onError", error)
// [START_EXCLUDE]
updateUI(null)
// [END_EXCLUDE]
}
})
// [END initialize_fblogin]
}
// [START on_start_check_user]
public override fun onStart() {
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = auth.currentUser
updateUI(currentUser)
}
// [END on_start_check_user]
// [START on_activity_result]
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Pass the activity result back to the Facebook SDK
callbackManager.onActivityResult(requestCode, resultCode, data)
}
// [END on_activity_result]
// [START auth_with_facebook]
private fun handleFacebookAccessToken(token: AccessToken) {
Log.d(TAG, "handleFacebookAccessToken:$token")
// [START_EXCLUDE silent]
showProgressBar()
// [END_EXCLUDE]
val credential = FacebookAuthProvider.getCredential(token.token)
auth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success")
val user = auth.currentUser
updateUI(user)
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
Toast.makeText(baseContext, "Authentication failed.",
Toast.LENGTH_SHORT).show()
updateUI(null)
}
// [START_EXCLUDE]
hideProgressBar()
// [END_EXCLUDE]
}
}
// [END auth_with_facebook]
fun signOut() {
auth.signOut()
LoginManager.getInstance().logOut()
updateUI(null)
}
private fun updateUI(user: FirebaseUser?) {
hideProgressBar()
if (user != null) {
binding.status.text = getString(R.string.facebook_status_fmt, user.displayName)
binding.detail.text = getString(R.string.firebase_status_fmt, user.uid)
binding.buttonFacebookLogin.visibility = View.GONE
binding.buttonFacebookSignout.visibility = View.VISIBLE
} else {
binding.status.setText(R.string.signed_out)
binding.detail.text = null
binding.buttonFacebookLogin.visibility = View.VISIBLE
binding.buttonFacebookSignout.visibility = View.GONE
}
}
override fun onClick(v: View) {
if (v.id == R.id.buttonFacebookSignout) {
signOut()
}
}
companion object {
private const val TAG = "FacebookLogin"
}
}
| auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/FacebookLoginActivity.kt | 4031439681 |
/*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.repository.git.path.matcher.path
import svnserver.repository.git.path.NameMatcher
import svnserver.repository.git.path.PathMatcher
/**
* Complex full-feature pattern matcher.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class FileMaskMatcher constructor(private val matcher: NameMatcher) : PathMatcher {
override fun createChild(name: String, isDir: Boolean): PathMatcher? {
if (matcher.isMatch(name, isDir)) {
return AlwaysMatcher.INSTANCE
}
if (!isDir) {
return null
}
return this
}
override val isMatch: Boolean
get() {
return false
}
override val svnMaskGlobal: String?
get() {
return matcher.svnMask
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val that: FileMaskMatcher = other as FileMaskMatcher
return (matcher == that.matcher)
}
override fun hashCode(): Int {
return matcher.hashCode()
}
}
| src/main/kotlin/svnserver/repository/git/path/matcher/path/FileMaskMatcher.kt | 440605790 |
package imgui.internal.sections
//-----------------------------------------------------------------------------
// [SECTION] Docking support
//----------------------------------------------------------------------------- | core/src/main/kotlin/imgui/internal/sections/Docking support.kt | 4147200429 |
package com.soywiz.korge.ui.korui
import com.soywiz.korge.input.*
import com.soywiz.korge.view.*
import com.soywiz.korio.lang.*
import com.soywiz.korev.*
import com.soywiz.korge.ui.*
import com.soywiz.korui.light.*
import kotlin.reflect.*
//class KorgeLightComponentsFactory : LightComponentsFactory() {
// //override fun create(): LightComponents = KorgeLightComponents()
// override fun create(): LightComponents = TODO()
//}
class KorgeLightComponents(val uiFactory: UIFactory) : LightComponents() {
val views = uiFactory.views
override fun create(type: LightType, config: Any?): LightComponentInfo {
val handle = when (type) {
LightType.BUTTON -> uiFactory.button()
LightType.CONTAINER -> FixedSizeContainer()
LightType.FRAME -> FixedSizeContainer()
LightType.LABEL -> uiFactory.label("")
else -> FixedSizeContainer()
}
return LightComponentInfo(handle)
}
override fun setBounds(c: Any, x: Int, y: Int, width: Int, height: Int) {
val view = c as View
view.x = x.toDouble()
view.y = y.toDouble()
view.width = width.toDouble()
view.height = height.toDouble()
}
override fun <T> setProperty(c: Any, key: LightProperty<T>, value: T) {
val view = c as View
when (key) {
LightProperty.TEXT -> {
(view as? IText)?.text = value as String
}
}
}
override fun <T : Event> registerEventKind(c: Any, clazz: KClass<T>, ed: EventDispatcher): Closeable {
val view = c as View
val mouseEvent = MouseEvent()
when (clazz) {
MouseEvent::class -> {
return listOf(
view.mouse.onClick {
ed.dispatch(mouseEvent.apply {
this.type = MouseEvent.Type.CLICK
this.button = MouseButton.LEFT
this.x = 0
this.y = 0
})
}
).closeable()
}
}
return super.registerEventKind(c, clazz, ed)
}
override fun openURL(url: String) {
//browser.browse(URL(url))
}
override fun setParent(c: Any, parent: Any?) {
val view = c as View
val parentView = parent as? Container?
parentView?.addChild(view)
}
override fun repaint(c: Any) {
}
}
| @old/korge-ui/src/commonMain/kotlin/com/soywiz/korge/ui/korui/KorgeLightComponents.kt | 3554409807 |
package com.fufik.vsuschedule
import android.support.v7.widget.CardView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import java.util.ArrayList
class RecyclerAdapter(private val mParas: ArrayList<Para>) : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {
class ViewHolder(v:View):RecyclerView.ViewHolder(v) {
val mCard:CardView = v.findViewById(R.id.cv)
var mBeginTime:TextView = v.findViewById(R.id.item_begin_time)
var mEndTime:TextView = v.findViewById(R.id.item_end_time)
var mParaName:TextView = v.findViewById(R.id.item_para_name)
var mParaRoom:TextView = v.findViewById(R.id.item_para_room)
var mParaTeacher:TextView = v.findViewById(R.id.item_para_teacher)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerAdapter.ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.recycler_item, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.mBeginTime.text = mParas[position].beginTime
holder.mEndTime.text = mParas[position].endTime
holder.mParaName.text = mParas[position].name
holder.mParaRoom.text = mParas[position].room
holder.mParaTeacher.text = mParas[position].teacher
}
override fun getItemCount(): Int {
return mParas.size
}
}
| src/main/java/com/fufik/vsuschedule/RecyclerAdapter.kt | 3287583943 |
package permissions.dispatcher.test
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import org.junit.After
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Matchers.any
import org.mockito.Mockito
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
import permissions.dispatcher.PermissionRequest
@Suppress("IllegalIdentifier")
@RunWith(PowerMockRunner::class)
@PrepareForTest(ActivityCompat::class, ContextCompat::class)
class ActivityWithAllAnnotationsKtPermissionsDispatcherTest {
private lateinit var activity: ActivityWithAllAnnotationsKt
companion object {
private var requestCode = 0
private lateinit var requestPermissions: Array<String>
@BeforeClass
@JvmStatic
fun setUpForClass() {
requestCode = ActivityWithAllAnnotationsKt::showCameraWithPermissionCheck.packageLevelGetPropertyValueByName("REQUEST_SHOWCAMERA") as Int
requestPermissions = arrayOf("android.permission.CAMERA")
}
}
@Before
fun setUp() {
activity = Mockito.mock(ActivityWithAllAnnotationsKt::class.java)
PowerMockito.mockStatic(ActivityCompat::class.java)
PowerMockito.mockStatic(ContextCompat::class.java)
}
@After
fun tearDown() {
clearCustomSdkInt()
}
@Test
fun `already granted call the method`() {
mockCheckSelfPermission(true)
activity.showCameraWithPermissionCheck()
Mockito.verify(activity, Mockito.times(1)).showCamera()
}
@Test
fun `not granted does not call the method`() {
mockCheckSelfPermission(false)
mockShouldShowRequestPermissionRationaleActivity(true)
activity.showCameraWithPermissionCheck()
Mockito.verify(activity, Mockito.times(0)).showCamera()
}
@Test
fun `not granted permission and show rationale is true then call the rationale method`() {
mockCheckSelfPermission(false)
mockShouldShowRequestPermissionRationaleActivity(true)
activity.showCameraWithPermissionCheck()
Mockito.verify(activity, Mockito.times(1)).showRationaleForCamera(any(PermissionRequest::class.java))
}
@Test
fun `not granted permission and show rationale is false then does not call the rationale method`() {
mockCheckSelfPermission(false)
mockShouldShowRequestPermissionRationaleActivity(false)
activity.showCameraWithPermissionCheck()
Mockito.verify(activity, Mockito.times(0)).showRationaleForCamera(any(PermissionRequest::class.java))
}
@Test
fun `the method is called if verifyPermission is true`() {
activity.onRequestPermissionsResult(requestCode, intArrayOf(PackageManager.PERMISSION_GRANTED))
Mockito.verify(activity, Mockito.times(1)).showCamera()
}
@Test
fun `the method is not called if verifyPermission is false`() {
activity.onRequestPermissionsResult(requestCode, intArrayOf(PackageManager.PERMISSION_DENIED))
Mockito.verify(activity, Mockito.times(0)).showCamera()
}
@Test
fun `show never ask method is call if verifyPermission is false and shouldShowRequestPermissionRationale is false`() {
mockShouldShowRequestPermissionRationaleActivity(false)
activity.onRequestPermissionsResult(requestCode, intArrayOf(PackageManager.PERMISSION_DENIED))
Mockito.verify(activity, Mockito.times(1)).showNeverAskForCamera()
}
@Test
fun `show deny method is call if verifyPermission is false and shouldShowRequestPermissionRationale is true`() {
mockShouldShowRequestPermissionRationaleActivity(true)
activity.onRequestPermissionsResult(requestCode, intArrayOf(PackageManager.PERMISSION_DENIED))
Mockito.verify(activity, Mockito.times(1)).showDeniedForCamera()
}
@Test
fun `no the method call if request code is not related to the library`() {
activity.onRequestPermissionsResult(requestCode + 1000, intArrayOf())
Mockito.verify(activity, Mockito.times(0)).showCamera()
}
@Test
fun `no denied method call if request code is not related to the library`() {
activity.onRequestPermissionsResult(requestCode + 1000, intArrayOf())
Mockito.verify(activity, Mockito.times(0)).showDeniedForCamera()
}
@Test
fun `no never ask method call if request code is not related to the library`() {
activity.onRequestPermissionsResult(requestCode + 1000, intArrayOf())
Mockito.verify(activity, Mockito.times(0)).showNeverAskForCamera()
}
@Test
fun `blow M follows checkSelfPermissions result false`() {
overwriteCustomSdkInt(22)
mockCheckSelfPermission(false)
activity.showCameraWithPermissionCheck()
Mockito.verify(activity, Mockito.times(0)).showCamera()
}
@Test
fun `blow M follows checkSelfPermissions result true`() {
overwriteCustomSdkInt(22)
mockCheckSelfPermission(true)
activity.showCameraWithPermissionCheck()
Mockito.verify(activity, Mockito.times(1)).showCamera()
}
}
| test/src/test/java/permissions/dispatcher/test/ActivityWithAllAnnotationsKtPermissionsDispatcherTest.kt | 1715142142 |
package web
import com.google.gson.JsonSyntaxException
import events.Command
import loginRedirect
import main.config
import main.jdas
import org.jsoup.Jsoup
import utils.functionality.gson
import utils.functionality.log
val dapi = "https://discordapp.com/api"
data class Token(val access_token: String, val token_type: String, val expires_in: Int, val refresh_token: String, val scope: String)
data class IdentificationObject(val username: String, val verified: Boolean, val mfa_enabled: Boolean, val id: String, val avatar: String, val discriminator: String)
enum class Scope(val route: String) {
CONNECTIONS("/users/@me/connections"),
EMAIL("/users/@me"),
IDENTIFY("/users/@me"),
GUILDS("/users/@me/guilds"),
BOT_INFORMATION("/oauth2/applications/@me");
override fun toString(): String {
return route
}
}
fun identityObject(access_token: String): IdentificationObject? {
val obj = gson.fromJson(retrieveObject(access_token, Scope.IDENTIFY), IdentificationObject::class.java)
return if (obj.id == null) null /* This is possible due to issues with the kotlin compiler */
else obj
}
fun retrieveObject(access_token: String, scope: Scope): String {
return Jsoup.connect("$dapi$scope").ignoreContentType(true).ignoreHttpErrors(true)
.header("authorization", "Bearer $access_token")
.header("cache-control", "no-cache")
.get()
.text()
}
fun retrieveToken(code: String): Token? {
val response = Jsoup.connect("$dapi/oauth2/token").ignoreContentType(true).ignoreHttpErrors(true)
.header("content-type", "application/x-www-form-urlencoded")
.header("authorization", "Bearer $code")
.header("cache-control", "no-cache")
.data("client_id", jdas[0].selfUser.id)
.data("client_secret", config.getValue("client_secret"))
.data("grant_type", "authorization_code")
.data("redirect_uri", loginRedirect)
.data("code", code)
.post()
return try {
val data = gson.fromJson(response.text(), Token::class.java)
if (data.access_token == null) null // this is a possibility due to issues with the kotlin compiler
else data /* verified non null object */
} catch (e: JsonSyntaxException) {
e.printStackTrace()
null
}
}
data class CommandWrapper(val category: String, val description: String, val commands: List<Command>) | src/main/kotlin/web/WebUtils.kt | 1764007196 |
package com.tamsiree.rxkit
import android.app.ActivityManager
import android.app.ActivityManager.RunningAppProcessInfo
import android.app.AppOpsManager
import android.app.usage.UsageStats
import android.app.usage.UsageStatsManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.provider.Settings
import com.tamsiree.rxkit.RxDataTool.Companion.isNullString
import java.util.*
/**
* @author tamsiree
* @date 2016/12/21
*/
object RxProcessTool {
/**
* 获取前台线程包名
*
* 当不是查看当前App,且SDK大于21时,
* 需添加权限 `<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"/>`
*
* @return 前台应用包名
*/
@JvmStatic
fun getForegroundProcessName(context: Context): String? {
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val infos = manager.runningAppProcesses
if (infos != null && infos.size != 0) {
for (info in infos) {
if (info.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return info.processName
}
}
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
val packageManager = context.packageManager
val intent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)
val list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
println(list)
if (list.size > 0) { // 有"有权查看使用权限的应用"选项
try {
val info = packageManager.getApplicationInfo(context.packageName, 0)
val aom = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, info.uid, info.packageName) != AppOpsManager.MODE_ALLOWED) {
context.startActivity(intent)
}
if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, info.uid, info.packageName) != AppOpsManager.MODE_ALLOWED) {
TLog.d("getForegroundApp", "没有打开\"有权查看使用权限的应用\"选项")
return null
}
val usageStatsManager = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
val endTime = System.currentTimeMillis()
val beginTime = endTime - 86400000 * 7
val usageStatses = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, beginTime, endTime)
if (usageStatses == null || usageStatses.isEmpty()) return null
var recentStats: UsageStats? = null
for (usageStats in usageStatses) {
if (recentStats == null || usageStats.lastTimeUsed > recentStats.lastTimeUsed) {
recentStats = usageStats
}
}
return recentStats?.packageName
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
} else {
TLog.d("getForegroundApp", "无\"有权查看使用权限的应用\"选项")
}
}
return null
}
/**
* 获取后台服务进程
*
* 需添加权限 `<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>`
*
* @return 后台服务进程
*/
@JvmStatic
fun getAllBackgroundProcesses(context: Context): MutableCollection<String> {
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val infos = am.runningAppProcesses
val set: MutableCollection<String> = HashSet()
for (info in infos) {
Collections.addAll(set, *info.pkgList)
}
return set
}
/**
* 杀死后台服务进程
*
* 需添加权限 `<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>`
*
* @return 被暂时杀死的服务集合
*/
@JvmStatic
fun killAllBackgroundProcesses(context: Context): Set<String> {
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
var infos = am.runningAppProcesses
val set: MutableSet<String> = HashSet()
for (info in infos) {
for (pkg in info.pkgList) {
am.killBackgroundProcesses(pkg)
set.add(pkg)
}
}
infos = am.runningAppProcesses
for (info in infos) {
for (pkg in info.pkgList) {
set.remove(pkg)
}
}
return set
}
/**
* 杀死后台服务进程
*
* 需添加权限 `<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>`
*
* @param packageName 包名
* @return `true`: 杀死成功<br></br>`false`: 杀死失败
*/
@JvmStatic
fun killBackgroundProcesses(context: Context, packageName: String?): Boolean {
if (isNullString(packageName)) return false
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
var infos = am.runningAppProcesses
if (infos == null || infos.size == 0) return true
for (info in infos) {
if (Arrays.asList(*info.pkgList).contains(packageName)) {
am.killBackgroundProcesses(packageName)
}
}
infos = am.runningAppProcesses
if (infos == null || infos.size == 0) return true
for (info in infos) {
if (Arrays.asList(*info.pkgList).contains(packageName)) {
return false
}
}
return true
}
} | RxKit/src/main/java/com/tamsiree/rxkit/RxProcessTool.kt | 1181561272 |
package li.ruoshi.playground
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.ViewGroup
import android.widget.TextView
import java.util.*
/**
* Created by ruoshili on 7/13/2016.
*/
private const val TAG = "DemoAdapter"
class DemoAdapter() : RecyclerView.Adapter<DemoViewHolder>() {
private val items: MutableList<Int> = ArrayList()
override fun onBindViewHolder(holder: DemoViewHolder?, position: Int) {
if(holder == null) {
return
}
if(position < 0 || position >= items.size) {
return
}
Log.v(TAG, "onBindViewHolder pos: $position, value: ${items[position]}, holder id: ${holder.id}")
holder.update(items[position])
}
override fun onFailedToRecycleView(holder: DemoViewHolder?): Boolean {
Log.e(TAG, "onFailedToRecycleView")
return super.onFailedToRecycleView(holder)
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): DemoViewHolder {
val textView = TextView(parent!!.context!!)
val holder = DemoViewHolder(textView)
Log.v(TAG, "onCreateViewHolder, holder id: ${holder.id}")
return holder
}
override fun getItemCount(): Int {
return items.size
}
fun addItem(i : Int) {
items.add(i)
notifyItemInserted(items.size - 1)
}
fun removeItem(pos : Int) {
if(pos < 0 || pos >= items.size) {
return
}
items.removeAt(pos)
notifyItemRemoved(pos)
}
fun removeOddItems() {
while (true) {
val pos = items.indexOfFirst { it % 2 == 1 }
if(pos < 0) {
break
} else {
removeItem(pos)
}
}
}
} | app/src/main/kotlin/li/ruoshi/playground/DemoAdapter.kt | 3073162851 |
package com.tamsiree.rxui.view.loadingview.animation.interpolator
import android.graphics.Path
import android.graphics.PathMeasure
import android.view.animation.Interpolator
/**
* @author tamsiree
* A path interpolator implementation compatible with API 4+.
*/
internal class PathInterpolatorDonut(path: Path?) : Interpolator {
private val mX: FloatArray
private val mY: FloatArray
constructor(controlX: Float, controlY: Float) : this(createQuad(controlX, controlY))
constructor(controlX1: Float, controlY1: Float,
controlX2: Float, controlY2: Float) : this(createCubic(controlX1, controlY1, controlX2, controlY2))
override fun getInterpolation(t: Float): Float {
if (t <= 0.0f) {
return 0.0f
} else if (t >= 1.0f) {
return 1.0f
}
// Do a binary search for the correct x to interpolate between.
var startIndex = 0
var endIndex = mX.size - 1
while (endIndex - startIndex > 1) {
val midIndex = (startIndex + endIndex) / 2
if (t < mX[midIndex]) {
endIndex = midIndex
} else {
startIndex = midIndex
}
}
val xRange = mX[endIndex] - mX[startIndex]
if (xRange == 0f) {
return mY[startIndex]
}
val tInRange = t - mX[startIndex]
val fraction = tInRange / xRange
val startY = mY[startIndex]
val endY = mY[endIndex]
return startY + fraction * (endY - startY)
}
companion object {
/**
* Governs the accuracy of the approximation of the [Path].
*/
private const val PRECISION = 0.002f
private fun createQuad(controlX: Float, controlY: Float): Path {
val path = Path()
path.moveTo(0.0f, 0.0f)
path.quadTo(controlX, controlY, 1.0f, 1.0f)
return path
}
private fun createCubic(controlX1: Float, controlY1: Float,
controlX2: Float, controlY2: Float): Path {
val path = Path()
path.moveTo(0.0f, 0.0f)
path.cubicTo(controlX1, controlY1, controlX2, controlY2, 1.0f, 1.0f)
return path
}
}
init {
val pathMeasure = PathMeasure(path, false /* forceClosed */)
val pathLength = pathMeasure.length
val numPoints = (pathLength / PRECISION).toInt() + 1
mX = FloatArray(numPoints)
mY = FloatArray(numPoints)
val position = FloatArray(2)
for (i in 0 until numPoints) {
val distance = i * pathLength / (numPoints - 1)
pathMeasure.getPosTan(distance, position, null /* tangent */)
mX[i] = position[0]
mY[i] = position[1]
}
}
} | RxUI/src/main/java/com/tamsiree/rxui/view/loadingview/animation/interpolator/PathInterpolatorDonut.kt | 1343553467 |
package com.tamsiree.rxui.view.roundprogressbar
import android.content.Context
import android.graphics.Color
import android.os.Parcel
import android.os.Parcelable
import android.util.AttributeSet
import android.util.TypedValue
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import com.tamsiree.rxkit.RxImageTool.dp2px
import com.tamsiree.rxui.R
import com.tamsiree.rxui.view.roundprogressbar.common.RxBaseRoundProgress
/**
* @author tamsiree
*/
class RxTextRoundProgress : RxBaseRoundProgress, OnGlobalLayoutListener {
private var tvProgress: TextView? = null
private var colorTextProgress = 0
private var textProgressSize = 0
private var textProgressMargin = 0
private var textProgress: String? = null
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun initLayout(): Int {
return R.layout.layout_text_round_corner_progress_bar
}
override fun initStyleable(context: Context, attrs: AttributeSet?) {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.RxTextRoundProgress)
colorTextProgress = typedArray.getColor(R.styleable.RxTextRoundProgress_rcTextProgressColor, Color.WHITE)
textProgressSize = typedArray.getDimension(R.styleable.RxTextRoundProgress_rcTextProgressSize, dp2px(context, DEFAULT_TEXT_SIZE.toFloat()).toFloat()).toInt()
textProgressMargin = typedArray.getDimension(R.styleable.RxTextRoundProgress_rcTextProgressMargin, dp2px(context, DEFAULT_TEXT_MARGIN.toFloat()).toFloat()).toInt()
textProgress = typedArray.getString(R.styleable.RxTextRoundProgress_rcTextProgress)
typedArray.recycle()
}
override fun initView() {
tvProgress = findViewById(R.id.tv_progress)
tvProgress?.viewTreeObserver?.addOnGlobalLayoutListener(this)
}
override fun drawProgress(layoutProgress: LinearLayout?, max: Float, progress: Float, totalWidth: Float,
radius: Int, padding: Int, colorProgress: Int, isReverse: Boolean) {
val backgroundDrawable = createGradientDrawable(colorProgress)
val newRadius = radius - padding / 2
backgroundDrawable.cornerRadii = floatArrayOf(newRadius.toFloat(), newRadius.toFloat(), newRadius.toFloat(), newRadius.toFloat(), newRadius.toFloat(), newRadius.toFloat(), newRadius.toFloat(), newRadius.toFloat())
layoutProgress?.background = backgroundDrawable
val ratio = max / progress
val progressWidth = ((totalWidth - padding * 2) / ratio).toInt()
val progressParams = layoutProgress?.layoutParams
progressParams?.width = progressWidth
layoutProgress?.layoutParams = progressParams
}
override fun onViewDraw() {
drawTextProgress()
drawTextProgressSize()
drawTextProgressMargin()
drawTextProgressPosition()
drawTextProgressColor()
}
private fun drawTextProgress() {
tvProgress!!.text = textProgress
}
private fun drawTextProgressColor() {
tvProgress!!.setTextColor(colorTextProgress)
}
private fun drawTextProgressSize() {
tvProgress!!.setTextSize(TypedValue.COMPLEX_UNIT_PX, textProgressSize.toFloat())
}
private fun drawTextProgressMargin() {
val params = tvProgress!!.layoutParams as MarginLayoutParams
params.setMargins(textProgressMargin, 0, textProgressMargin, 0)
tvProgress!!.layoutParams = params
}
private fun drawTextProgressPosition() {
// tvProgress.setVisibility(View.INVISIBLE);
// tvProgress.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
// @SuppressWarnings("deprecation")
// @Override
// public void onGlobalLayout() {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
// tvProgress.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// else
// tvProgress.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// setTextProgressAlign();
// }
// });
clearTextProgressAlign()
// TODO Temporary
val textProgressWidth = tvProgress!!.measuredWidth + getTextProgressMargin() * 2
val ratio = getMax() / getProgress()
val progressWidth = ((layoutWidth - getPadding() * 2) / ratio).toInt()
if (textProgressWidth + textProgressMargin < progressWidth) {
alignTextProgressInsideProgress()
} else {
alignTextProgressOutsideProgress()
}
}
// private void setTextProgressAlign() {
// tvProgress.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
// @SuppressWarnings("deprecation")
// @Override
// public void onGlobalLayout() {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
// tvProgress.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// else
// tvProgress.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// tvProgress.setVisibility(View.VISIBLE);
// }
// });
// int textProgressWidth = tvProgress.getMeasuredWidth() + (getTextProgressMargin() * 2);
// float ratio = getMax() / getProgress();
// int progressWidth = (int) ((getLayoutWidth() - (getPadding() * 2)) / ratio);
// if (textProgressWidth + textProgressMargin < progressWidth) {
// alignTextProgressInsideProgress();
// } else {
// alignTextProgressOutsideProgress();
// }
// }
private fun clearTextProgressAlign() {
val params = tvProgress!!.layoutParams as RelativeLayout.LayoutParams
params.addRule(RelativeLayout.ALIGN_LEFT, 0)
params.addRule(RelativeLayout.ALIGN_RIGHT, 0)
params.addRule(RelativeLayout.LEFT_OF, 0)
params.addRule(RelativeLayout.RIGHT_OF, 0)
params.removeRule(RelativeLayout.START_OF)
params.removeRule(RelativeLayout.END_OF)
params.removeRule(RelativeLayout.ALIGN_START)
params.removeRule(RelativeLayout.ALIGN_END)
tvProgress!!.layoutParams = params
}
private fun alignTextProgressInsideProgress() {
val params = tvProgress!!.layoutParams as RelativeLayout.LayoutParams
if (getReverse()) {
params.addRule(RelativeLayout.ALIGN_LEFT, R.id.layout_progress)
params.addRule(RelativeLayout.ALIGN_START, R.id.layout_progress)
} else {
params.addRule(RelativeLayout.ALIGN_RIGHT, R.id.layout_progress)
params.addRule(RelativeLayout.ALIGN_END, R.id.layout_progress)
}
tvProgress!!.layoutParams = params
}
private fun alignTextProgressOutsideProgress() {
val params = tvProgress!!.layoutParams as RelativeLayout.LayoutParams
if (getReverse()) {
params.addRule(RelativeLayout.LEFT_OF, R.id.layout_progress)
params.addRule(RelativeLayout.START_OF, R.id.layout_progress)
} else {
params.addRule(RelativeLayout.RIGHT_OF, R.id.layout_progress)
params.addRule(RelativeLayout.END_OF, R.id.layout_progress)
}
tvProgress!!.layoutParams = params
}
var progressText: String?
get() = textProgress
set(text) {
textProgress = text
drawTextProgress()
drawTextProgressPosition()
}
override fun setProgress(progress: Float) {
super.setProgress(progress)
drawTextProgressPosition()
}
var textProgressColor: Int
get() = colorTextProgress
set(color) {
colorTextProgress = color
drawTextProgressColor()
}
fun getTextProgressSize(): Int {
return textProgressSize
}
fun setTextProgressSize(size: Int) {
textProgressSize = size
drawTextProgressSize()
drawTextProgressPosition()
}
fun getTextProgressMargin(): Int {
return textProgressMargin
}
fun setTextProgressMargin(margin: Int) {
textProgressMargin = margin
drawTextProgressMargin()
drawTextProgressPosition()
}
override fun onGlobalLayout() {
tvProgress!!.viewTreeObserver.removeOnGlobalLayoutListener(this)
drawTextProgressPosition()
}
override fun onSaveInstanceState(): Parcelable? {
val superState = super.onSaveInstanceState()
val ss = SavedState(superState)
ss.colorTextProgress = colorTextProgress
ss.textProgressSize = textProgressSize
ss.textProgressMargin = textProgressMargin
ss.textProgress = textProgress
return ss
}
override fun onRestoreInstanceState(state: Parcelable) {
if (state !is SavedState) {
super.onRestoreInstanceState(state)
return
}
val ss = state
super.onRestoreInstanceState(ss.superState)
colorTextProgress = ss.colorTextProgress
textProgressSize = ss.textProgressSize
textProgressMargin = ss.textProgressMargin
textProgress = ss.textProgress
}
private class SavedState : BaseSavedState {
var colorTextProgress = 0
var textProgressSize = 0
var textProgressMargin = 0
var textProgress: String? = null
internal constructor(superState: Parcelable?) : super(superState)
private constructor(`in`: Parcel) : super(`in`) {
colorTextProgress = `in`.readInt()
textProgressSize = `in`.readInt()
textProgressMargin = `in`.readInt()
textProgress = `in`.readString()
}
override fun writeToParcel(out: Parcel, flags: Int) {
super.writeToParcel(out, flags)
out.writeInt(colorTextProgress)
out.writeInt(textProgressSize)
out.writeInt(textProgressMargin)
out.writeString(textProgress)
}
companion object {
val CREATOR: Parcelable.Creator<SavedState> = object : Parcelable.Creator<SavedState> {
override fun createFromParcel(`in`: Parcel): SavedState? {
return SavedState(`in`)
}
override fun newArray(size: Int): Array<SavedState?> {
return arrayOfNulls(size)
}
}
}
}
companion object {
protected const val DEFAULT_TEXT_SIZE = 16
protected const val DEFAULT_TEXT_MARGIN = 10
}
} | RxUI/src/main/java/com/tamsiree/rxui/view/roundprogressbar/RxTextRoundProgress.kt | 3036939827 |
package rxjoin.internal.codegen.step
import rxjoin.internal.codegen.Model
interface ProcessStep {
fun process(model: Model)
}
| compiler/src/main/kotlin/rxjoin/internal/codegen/step/ProcessStep.kt | 696722644 |
package com.adityakamble49.ttl.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.adityakamble49.ttl.utils.didTimeStart
import com.adityakamble49.ttl.utils.setTimeUpAlarm
/**
*
* @author Akshay
* @since 12-03-2017.
* @version 1.0
*/
class RestartTimeBootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
if (didTimeStart(context)) {
// Restart countdown via Alarm
setTimeUpAlarm(context)
}
}
} | app/src/main/java/com/adityakamble49/ttl/receiver/RestartTimeBootReceiver.kt | 1909863434 |
package com.jovial.misc.bluetooth.im
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.inputmethod.InputMethodInfo
import android.content.Context.INPUT_METHOD_SERVICE
import android.support.v4.content.ContextCompat.getSystemService
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.Toast
class SettingsActivity : AppCompatActivity() {
private val ui by lazy {
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
val dismissButton : Button = findViewById(R.id.dismiss_button)
dismissButton.setOnClickListener( { finish() })
}
override fun onResume() {
super.onResume()
println("@@ SettingsActivity onResume")
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val enabled = imm.getEnabledInputMethodList()
for (service in enabled) {
println(" @@ ${service.serviceName} : $service")
}
Toast.makeText(this, "Jovial Accented Keyboard installed", Toast.LENGTH_LONG).show()
}
}
| abandoned_hacks/bluetooth_keyboard_input_method_android/app/src/main/java/com/jovial/misc/bluetooth/im/SettingsActivity.kt | 2923259760 |
package com.stripe.android.paymentsheet
import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import kotlinx.coroutines.FlowPreview
@OptIn(FlowPreview::class)
internal class PaymentSheetAddPaymentMethodFragment() : BaseAddPaymentMethodFragment() {
override val sheetViewModel by activityViewModels<PaymentSheetViewModel> {
PaymentSheetViewModel.Factory {
requireNotNull(requireArguments().getParcelable(PaymentSheetActivity.EXTRA_STARTER_ARGS))
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
sheetViewModel.showTopContainer.observe(viewLifecycleOwner) { visible ->
sheetViewModel.headerText.value = if (visible) {
null
} else {
getString(R.string.stripe_paymentsheet_add_payment_method_title)
}
}
}
}
| paymentsheet/src/main/java/com/stripe/android/paymentsheet/PaymentSheetAddPaymentMethodFragment.kt | 619439912 |
package abi44_0_0.expo.modules
import android.app.Application
import android.content.res.Configuration
import androidx.annotation.UiThread
import abi44_0_0.expo.modules.core.interfaces.ApplicationLifecycleListener
object ApplicationLifecycleDispatcher {
private var listeners: List<ApplicationLifecycleListener>? = null
@UiThread
private fun getCachedListeners(application: Application): List<ApplicationLifecycleListener> {
return listeners ?: ExpoModulesPackage.packageList
.flatMap { it.createApplicationLifecycleListeners(application) }
.also { listeners = it }
}
@JvmStatic
fun onApplicationCreate(application: Application) {
getCachedListeners(application).forEach { it.onCreate(application) }
}
@JvmStatic
fun onConfigurationChanged(application: Application, newConfig: Configuration) {
getCachedListeners(application).forEach { it.onConfigurationChanged(newConfig) }
}
}
| android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/ApplicationLifecycleDispatcher.kt | 2089270251 |
package com.the_roberto.kittengifs.kittens
import android.app.AlertDialog
import android.app.Dialog
import android.content.ActivityNotFoundException
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.util.Log
import com.the_roberto.kittengifs.App
import com.the_roberto.kittengifs.EventsTracker
import com.the_roberto.kittengifs.IntentStarter
import com.the_roberto.kittengifs.R
import com.the_roberto.kittengifs.model.Settings
import javax.inject.Inject
class RatingDialog : DialogFragment() {
private val TAG = "RatingFragment"
@Inject lateinit var settings: Settings
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
injectDependencies()
return AlertDialog.Builder(activity).setTitle(getString(R.string.dialog_rating_title)).setMessage(getString(R.string.dialog_rating_message))
.setPositiveButton(getString(R.string.dialog_rating_positive)) { dialog, which ->
neverAsk()
EventsTracker.trackRatingYes()
val appPackageName = "com.the_roberto.kittengifs"
try {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)))
} catch (e: ActivityNotFoundException) {
Log.wtf(TAG, e)
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)))
}
}.setNeutralButton(getString(R.string.dialog_rating_neutral)) { dialog, which ->
EventsTracker.trackRatingLater(/*cancel*/ false)
later()
}.setNegativeButton(getString(R.string.dialog_rating_negative)) { dialog, which ->
EventsTracker.trackRatingNah()
neverAsk()
}.create()
}
private fun injectDependencies() {
(activity.application as App).appComponent.inject(this)
}
override fun onCancel(dialog: DialogInterface?) {
super.onCancel(dialog)
EventsTracker.trackRatingLater(/*cancel*/ true)
later()
}
private fun later() {
settings.setKittensBeforeAskingToRate(settings.getKittensBeforeAskingToRate() * 4)
}
private fun neverAsk() {
settings.setKittensBeforeAskingToRate(Integer.MAX_VALUE)
}
}
| app/src/main/java/com/the_roberto/kittengifs/kittens/RatingDialog.kt | 1102459323 |
package de.reiss.bible2net.theword.architecture.di
import android.content.Context
import com.grapesnberries.curllogger.CurlLoggerInterceptor
import dagger.Module
import dagger.Provides
import de.reiss.bible2net.theword.architecture.UserAgentInterceptor
import de.reiss.bible2net.theword.util.appVersion
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
@Module(
includes = [
ContextModule::class
]
)
open class OkHttpModule {
@Provides
@ApplicationScope
open fun cacheFile(context: Context): File {
return File(context.cacheDir, "okhttp").apply {
mkdirs()
}
}
@Provides
@ApplicationScope
open fun cache(cacheFile: File): Cache =
Cache(cacheFile, (16 * 1024 * 1024).toLong())
@Provides
@ApplicationScope
open fun okHttpClient(context: Context, cache: Cache): OkHttpClient =
OkHttpClient.Builder()
.cache(cache)
.addInterceptor(CurlLoggerInterceptor("TheWord"))
.addNetworkInterceptor(UserAgentInterceptor("The Word", appVersion(context)))
.build()
}
| app/src/main/java/de/reiss/bible2net/theword/architecture/di/OkHttpModule.kt | 4182383119 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.samples
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import androidx.annotation.Sampled
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.rememberScrollableState
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.rememberNestedScrollInteropConnection
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.view.ViewCompat
import kotlin.math.roundToInt
@Sampled
@Composable
fun ComposeInCooperatingViewNestedScrollInteropSample() {
val nestedSrollInterop = rememberNestedScrollInteropConnection()
// Add the nested scroll connection to your top level @Composable element
// using the nestedScroll modifier.
LazyColumn(modifier = Modifier.nestedScroll(nestedSrollInterop)) {
items(20) { item ->
Box(
modifier = Modifier
.padding(16.dp)
.height(56.dp)
.fillMaxWidth()
.background(Color.Gray),
contentAlignment = Alignment.Center
) {
Text(item.toString())
}
}
}
}
@Sampled
@Composable
fun ViewInComposeNestedScrollInteropSample() {
Box(
Modifier
.fillMaxSize()
.scrollable(rememberScrollableState {
// view world deltas should be reflected in compose world
// components that participate in nested scrolling
it
}, Orientation.Vertical)
) {
AndroidView(
{ context ->
LayoutInflater.from(context)
.inflate(android.R.layout.activity_list_item, null)
.apply {
// Nested Scroll Interop will be Enabled when
// nested scroll is enabled for the root view
ViewCompat.setNestedScrollingEnabled(this, true)
}
}
)
}
}
private val ToolbarHeight = 48.dp
@Composable
fun CollapsingToolbarComposeViewComposeNestedScrollInteropSample() {
val toolbarHeightPx = with(LocalDensity.current) { ToolbarHeight.roundToPx().toFloat() }
val toolbarOffsetHeightPx = remember { mutableStateOf(0f) }
val nestedScrollConnection = remember {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
val delta = available.y
val newOffset = toolbarOffsetHeightPx.value + delta
toolbarOffsetHeightPx.value = newOffset.coerceIn(-toolbarHeightPx, 0f)
return Offset.Zero
}
}
}
// Compose Scrollable
Box(
Modifier
.fillMaxSize()
.nestedScroll(nestedScrollConnection)
) {
TopAppBar(
modifier = Modifier
.height(ToolbarHeight)
.offset { IntOffset(x = 0, y = toolbarOffsetHeightPx.value.roundToInt()) },
title = { Text("toolbar offset is ${toolbarOffsetHeightPx.value}") }
)
// Android View
AndroidView(
factory = { context -> AndroidViewWithCompose(context) },
modifier = Modifier.fillMaxWidth()
)
}
}
private fun AndroidViewWithCompose(context: Context): View {
return LayoutInflater.from(context)
.inflate(R.layout.three_fold_nested_scroll_interop, null).apply {
with(findViewById<ComposeView>(R.id.compose_view)) {
// Compose
setContent { LazyColumnWithNestedScrollInteropEnabled() }
}
}.also {
ViewCompat.setNestedScrollingEnabled(it, true)
}
}
@Composable
private fun LazyColumnWithNestedScrollInteropEnabled() {
LazyColumn(
modifier = Modifier.nestedScroll(
rememberNestedScrollInteropConnection()
),
contentPadding = PaddingValues(top = ToolbarHeight)
) {
item {
Text("This is a Lazy Column")
}
items(40) { item ->
Box(
modifier = Modifier
.padding(16.dp)
.height(56.dp)
.fillMaxWidth()
.background(Color.Gray),
contentAlignment = Alignment.Center
) {
Text(item.toString())
}
}
}
}
| compose/ui/ui/samples/src/main/java/androidx/compose/ui/samples/NestedScrollInteropSamples.kt | 763257070 |
package xcarpaccio
data class Result(val total: Double) {} | clients/kotlin/src/main/kotlin/xcarpaccio/Result.kt | 2652632843 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import org.intellij.lang.annotations.Language
import org.rust.ide.inspections.import.checkAutoImportWithMultipleChoice
class AddImportForPatternIntentionTest : RsIntentionTestBase(AddImportForPatternIntention::class) {
fun `test constant`() = doAvailableTest("""
mod inner {
pub const C: i32 = 0;
}
fn main() {
match 0 {
/*caret*/C => {}
_ => {}
}
}
""", """
use crate::inner::C;
mod inner {
pub const C: i32 = 0;
}
fn main() {
match 0 {
C => {}
_ => {}
}
}
""")
fun `test enum variant`() = doAvailableTest("""
enum E { A, B }
fn func(e: E) {
match e {
/*caret*/A => {}
B => {}
}
}
""", """
use crate::E::A;
enum E { A, B }
fn func(e: E) {
match e {
A => {}
B => {}
}
}
""")
fun `test complex pattern`() = doAvailableTest("""
mod inner {
pub const C: i32 = 0;
}
fn main() {
match (0, 0) {
(/*caret*/C, _) => {}
}
}
""", """
use crate::inner::C;
mod inner {
pub const C: i32 = 0;
}
fn main() {
match (0, 0) {
(C, _) => {}
}
}
""")
// Ideally we should filter variants by expected type
fun `test enum variant and constant`() = checkAutoImportVariantsByText("""
mod inner {
pub const C: i32 = 0;
}
enum E { C }
fn func(e: E) {
match e {
/*caret*/C => {}
_ => {}
}
}
""", listOf("crate::E::C", "crate::inner::C"))
fun `test unavailable for ref pattern`() = doUnavailableTest("""
mod inner {
pub const C: i32 = 0;
}
fn main() {
match 0 {
ref /*caret*/C => {}
_ => {}
}
}
""")
// Potentially intention can work in this case
fun `test unavailable for field binding`() = doUnavailableTest("""
mod inner {
pub const C: i32 = 0;
}
struct Foo { C: i32 }
fn func(foo: Foo) {
match foo {
Foo { /*caret*/C } => {}
}
}
""")
fun `test unavailable for let declaration`() = doUnavailableTest("""
mod inner {
pub const C: i32 = 0;
}
fn func(foo: Foo) {
let /*caret*/C = 1;
}
""")
fun `test unavailable for resolved path`() = doUnavailableTest("""
mod inner {
pub const C: i32 = 0;
}
pub const C: i32 = 0;
fn main() {
match 0 {
/*caret*/C => {}
_ => {}
}
}
""")
private fun checkAutoImportVariantsByText(
@Language("Rust") before: String,
expectedElements: List<String>
) = checkAutoImportWithMultipleChoice(expectedElements, choice = null) {
InlineFile(before.trimIndent()).withCaret()
launchAction()
myFixture.checkResult(replaceCaretMarker(before.trimIndent()))
}
}
| src/test/kotlin/org/rust/ide/intentions/AddImportForPatternIntentionTest.kt | 395052006 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import org.rust.lang.core.psi.*
fun RsTypeArgumentList.getGenericArguments(
includeLifetimes: Boolean = true,
includeTypes: Boolean = true,
includeConsts: Boolean = true,
includeAssocBindings: Boolean = true
): List<RsElement> {
val typeArguments = typeArguments
return stubChildrenOfType<RsElement>().filter {
when {
it is RsLifetime -> includeLifetimes
it is RsTypeReference && it in typeArguments -> includeTypes
it is RsExpr || it is RsTypeReference -> includeConsts
it is RsAssocTypeBinding -> includeAssocBindings
else -> false
}
}
}
val RsTypeArgumentList.lifetimeArguments: List<RsLifetime> get() = lifetimeList
val RsTypeArgumentList.typeArguments: List<RsTypeReference>
get() = typeReferenceList.filter { ref ->
val type = ref as? RsPathType
val element = type?.path?.reference?.resolve()
element !is RsConstant && element !is RsFunction && element !is RsConstParameter
}
val RsTypeArgumentList.constArguments: List<RsElement>
get() {
val typeArguments = typeArguments
return stubChildrenOfType<RsElement>().filter {
it is RsExpr || it is RsTypeReference && it !in typeArguments
}
}
| src/main/kotlin/org/rust/lang/core/psi/ext/RsTypeArgumentList.kt | 888067248 |
package com.habitrpg.android.habitica.ui.viewmodels
import android.os.Bundle
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.ChallengeRepository
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.extensions.Optional
import com.habitrpg.android.habitica.extensions.asOptional
import com.habitrpg.android.habitica.extensions.filterOptionalDoOnEmpty
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.helpers.NotificationsManager
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.members.Member
import com.habitrpg.android.habitica.models.notifications.NewChatMessageData
import com.habitrpg.android.habitica.models.social.Challenge
import com.habitrpg.android.habitica.models.social.ChatMessage
import com.habitrpg.android.habitica.models.social.Group
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.BackpressureStrategy
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.subjects.BehaviorSubject
import retrofit2.HttpException
import java.util.concurrent.TimeUnit
import javax.inject.Inject
enum class GroupViewType(internal val order: String) {
PARTY("party"),
GUILD("guild"),
TAVERN("tavern")
}
open class GroupViewModel(initializeComponent: Boolean) : BaseViewModel(initializeComponent) {
constructor() : this(true)
@Inject
lateinit var challengeRepository: ChallengeRepository
@Inject
lateinit var socialRepository: SocialRepository
@Inject
lateinit var notificationsManager: NotificationsManager
var groupViewType: GroupViewType? = null
private val group: MutableLiveData<Group?> by lazy {
MutableLiveData<Group?>()
}
private val leader: MutableLiveData<Member?> by lazy {
MutableLiveData<Member?>()
}
private val isMemberData: MutableLiveData<Boolean?> by lazy {
MutableLiveData<Boolean?>()
}
private val _chatMessages: MutableLiveData<List<ChatMessage>> by lazy {
MutableLiveData<List<ChatMessage>>(listOf())
}
val chatmessages: LiveData<List<ChatMessage>> by lazy {
_chatMessages
}
protected val groupIDSubject = BehaviorSubject.create<Optional<String>>()
val groupIDFlowable: Flowable<Optional<String>> = groupIDSubject.toFlowable(BackpressureStrategy.BUFFER)
var gotNewMessages: Boolean = false
init {
loadGroupFromLocal()
loadLeaderFromLocal()
loadMembershipFromLocal()
}
override fun inject(component: UserComponent) {
component.inject(this)
}
override fun onCleared() {
socialRepository.close()
super.onCleared()
}
fun setGroupID(groupID: String) {
if (groupID == groupIDSubject.value?.value) return
groupIDSubject.onNext(groupID.asOptional())
disposable.add(
notificationsManager.getNotifications().firstElement().map {
it.filter { notification ->
val data = notification.data as? NewChatMessageData
data?.group?.id == groupID
}
}
.filter { it.isNotEmpty() }
.flatMapPublisher { userRepository.readNotification(it.first().id) }
.subscribe(
{
},
RxErrorHandler.handleEmptyError()
)
)
}
val groupID: String?
get() = groupIDSubject.value?.value
val isMember: Boolean
get() = isMemberData.value ?: false
val leaderID: String?
get() = group.value?.leaderID
val isLeader: Boolean
get() = user.value?.id == leaderID
val isPublicGuild: Boolean
get() = group.value?.privacy == "public"
fun getGroupData(): LiveData<Group?> = group
fun getLeaderData(): LiveData<Member?> = leader
fun getIsMemberData(): LiveData<Boolean?> = isMemberData
private fun loadGroupFromLocal() {
disposable.add(
groupIDFlowable
.filterOptionalDoOnEmpty { group.value = null }
.flatMap { socialRepository.getGroup(it) }
.map { socialRepository.getUnmanagedCopy(it) }
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ group.value = it }, RxErrorHandler.handleEmptyError())
)
}
private fun loadLeaderFromLocal() {
disposable.add(
groupIDFlowable
.filterOptionalDoOnEmpty { leader.value = null }
.flatMap { socialRepository.getGroup(it) }
.distinctUntilChanged { group1, group2 -> group1.id == group2.id }
.flatMap { socialRepository.getMember(it.leaderID) }
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ leader.value = it }, RxErrorHandler.handleEmptyError())
)
}
private fun loadMembershipFromLocal() {
disposable.add(
groupIDFlowable
.filterOptionalDoOnEmpty { isMemberData.value = null }
.flatMap { socialRepository.getGroupMemberships() }
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
isMemberData.value = it.firstOrNull { membership -> membership.groupID == groupID } != null
},
RxErrorHandler.handleEmptyError()
)
)
}
fun retrieveGroup(function: (() -> Unit)?) {
if (groupID?.isNotEmpty() == true) {
disposable.add(
socialRepository.retrieveGroup(groupID ?: "")
.filter { groupViewType == GroupViewType.PARTY }
.flatMap { group1 ->
socialRepository.retrieveGroupMembers(group1.id, true)
}
.doOnComplete { function?.invoke() }
.subscribe({ }, {
if (it is HttpException && it.code() == 404) {
MainNavigationController.navigateBack()
}
RxErrorHandler.reportError(it)
})
)
}
}
fun inviteToGroup(inviteData: HashMap<String, Any>) {
disposable.add(
socialRepository.inviteToGroup(group.value?.id ?: "", inviteData)
.subscribe({ }, RxErrorHandler.handleEmptyError())
)
}
fun updateOrCreateGroup(bundle: Bundle?) {
if (group.value == null) {
socialRepository.createGroup(
bundle?.getString("name"),
bundle?.getString("description"),
bundle?.getString("leader"),
bundle?.getString("groupType"),
bundle?.getString("privacy"),
bundle?.getBoolean("leaderCreateChallenge")
)
} else {
disposable.add(
socialRepository.updateGroup(
group.value, bundle?.getString("name"),
bundle?.getString("description"),
bundle?.getString("leader"),
bundle?.getBoolean("leaderCreateChallenge")
)
.subscribe({ }, RxErrorHandler.handleEmptyError())
)
}
}
fun leaveGroup(groupChallenges: List<Challenge>, keepChallenges: Boolean = true, function: (() -> Unit)? = null) {
if (!keepChallenges) {
for (challenge in groupChallenges) {
challengeRepository.leaveChallenge(challenge, "remove-all").subscribe({}, RxErrorHandler.handleEmptyError())
}
}
disposable.add(
socialRepository.leaveGroup(this.group.value?.id ?: "", keepChallenges)
.flatMap { userRepository.retrieveUser(withTasks = false, forced = true) }
.subscribe(
{
function?.invoke()
},
RxErrorHandler.handleEmptyError()
)
)
}
fun joinGroup(id: String? = null, function: (() -> Unit)? = null) {
disposable.add(
socialRepository.joinGroup(id ?: groupID).subscribe(
{
function?.invoke()
},
RxErrorHandler.handleEmptyError()
)
)
}
fun rejectGroupInvite(id: String? = null) {
groupID?.let {
disposable.add(socialRepository.rejectGroupInvite(id ?: it).subscribe({ }, RxErrorHandler.handleEmptyError()))
}
}
fun markMessagesSeen() {
groupIDSubject.value?.value?.let {
if (groupViewType != GroupViewType.TAVERN && it.isNotEmpty() && gotNewMessages) {
socialRepository.markMessagesSeen(it)
}
}
}
fun likeMessage(message: ChatMessage) {
val index = _chatMessages.value?.indexOf(message)
if (index == null || index < 0) return
disposable.add(
socialRepository.likeMessage(message).subscribe(
{
val list = _chatMessages.value?.toMutableList()
list?.set(index, it)
_chatMessages.postValue(list)
}, RxErrorHandler.handleEmptyError()
)
)
}
fun deleteMessage(chatMessage: ChatMessage) {
val oldIndex = _chatMessages.value?.indexOf(chatMessage) ?: return
val list = _chatMessages.value?.toMutableList()
list?.remove(chatMessage)
_chatMessages.postValue(list)
disposable.add(
socialRepository.deleteMessage(chatMessage).subscribe({
}, {
list?.add(oldIndex, chatMessage)
_chatMessages.postValue(list)
RxErrorHandler.reportError(it)
})
)
}
fun postGroupChat(chatText: String, onComplete: () -> Unit, onError: () -> Unit) {
groupIDSubject.value?.value?.let { groupID ->
socialRepository.postGroupChat(groupID, chatText).subscribe(
{
val list = _chatMessages.value?.toMutableList()
list?.add(0, it.message)
_chatMessages.postValue(list)
onComplete()
},
{ error ->
RxErrorHandler.reportError(error)
onError()
}
)
}
}
fun retrieveGroupChat(onComplete: () -> Unit) {
val groupID = groupIDSubject.value?.value
if (groupID.isNullOrEmpty()) {
onComplete()
return
}
disposable.add(
socialRepository.retrieveGroupChat(groupID)
.delay(500, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
_chatMessages.postValue(it)
onComplete()
},
RxErrorHandler.handleEmptyError()
)
)
}
fun updateGroup(bundle: Bundle?) {
disposable.add(
socialRepository.updateGroup(
group.value,
bundle?.getString("name"),
bundle?.getString("description"),
bundle?.getString("leader"),
bundle?.getBoolean("leaderOnlyChallenges")
)
.subscribe({}, RxErrorHandler.handleEmptyError())
)
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewmodels/GroupViewModel.kt | 1926944825 |
/*
* 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.
*/
package org.jetbrains.android.anko.config
import org.jetbrains.android.anko.config.ArtifactType.*
import org.jetbrains.android.anko.utils.toCamelCase
enum class AnkoFile(applicableArtifactTypes: Set<ArtifactType>) : ConfigurationKey<Boolean> {
LAYOUTS(setOf(PLATFORM, SUPPORT_V4, TOOLKIT)),
LISTENERS(setOf(SIMPLE_LISTENERS)),
LISTENERS_WITH_COROUTINES(setOf(COROUTINE_LISTENERS)),
PROPERTIES(setOf(PLATFORM, SUPPORT_V4, TOOLKIT)),
SERVICES(setOf(PLATFORM, SUPPORT_V4, TOOLKIT)),
SQL_PARSER_HELPERS(setOf(SQLITE)),
VIEWS(setOf(PLATFORM, SUPPORT_V4, TOOLKIT));
val types: Set<ArtifactType> = applicableArtifactTypes.toSet()
override val defaultValue = true
val filename: String
get() = name.toCamelCase() + ".kt"
} | anko/library/generator/src/org/jetbrains/android/anko/config/AnkoFile.kt | 2266205472 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material3
import androidx.compose.animation.core.TweenSpec
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.tokens.NavigationDrawerTokens
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.canScroll
import androidx.compose.ui.input.consumeScrollContainerInfo
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.SemanticsActions
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.test.SemanticsMatcher
import androidx.compose.ui.test.assert
import androidx.compose.ui.test.assertLeftPositionInRootIsEqualTo
import androidx.compose.ui.test.assertTopPositionInRootIsEqualTo
import androidx.compose.ui.test.assertWidthIsEqualTo
import androidx.compose.ui.test.click
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onParent
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performSemanticsAction
import androidx.compose.ui.test.performTouchInput
import androidx.compose.ui.test.swipeLeft
import androidx.compose.ui.test.swipeRight
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.filters.MediumTest
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.runBlocking
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@MediumTest
@RunWith(AndroidJUnit4::class)
@OptIn(ExperimentalMaterial3Api::class)
class DismissibleNavigationDrawerTest {
@get:Rule
val rule = createComposeRule()
val NavigationDrawerWidth = NavigationDrawerTokens.ContainerWidth
@Test
fun dismissibleNavigationDrawer_testOffset_whenOpen() {
rule.setMaterialContent(lightColorScheme()) {
val drawerState = rememberDrawerState(DrawerValue.Open)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.testTag("content")
)
}
},
content = {}
)
}
rule.onNodeWithTag("content")
.assertLeftPositionInRootIsEqualTo(0.dp)
}
@Test
fun dismissibleNavigationDrawer_sheet_respectsContentPadding() {
rule.setMaterialContent(lightColorScheme()) {
val drawerState = rememberDrawerState(DrawerValue.Open)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet(windowInsets = WindowInsets(7.dp, 7.dp, 7.dp, 7.dp)) {
Box(
Modifier
.fillMaxSize()
.testTag("content")
)
}
},
content = {}
)
}
rule.onNodeWithTag("content")
.assertLeftPositionInRootIsEqualTo(7.dp)
.assertTopPositionInRootIsEqualTo(7.dp)
}
@Test
fun dismissibleNavigationDrawer_testOffset_whenClosed() {
rule.setMaterialContent(lightColorScheme()) {
val drawerState = rememberDrawerState(DrawerValue.Closed)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.testTag("content")
)
}
},
content = {}
)
}
rule.onNodeWithTag("content")
.assertLeftPositionInRootIsEqualTo(-NavigationDrawerWidth)
}
@Test
fun dismissibleNavigationDrawer_testWidth_whenOpen() {
rule.setMaterialContent(lightColorScheme()) {
val drawerState = rememberDrawerState(DrawerValue.Open)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.testTag("content")
)
}
},
content = {}
)
}
rule.onNodeWithTag("content")
.assertWidthIsEqualTo(NavigationDrawerWidth)
}
@Test
@SmallTest
fun dismissibleNavigationDrawer_hasPaneTitle() {
lateinit var navigationMenu: String
rule.setMaterialContent(lightColorScheme()) {
DismissibleNavigationDrawer(
drawerState = rememberDrawerState(DrawerValue.Open),
drawerContent = {
DismissibleDrawerSheet(Modifier.testTag("navigationDrawerTag")) {
Box(
Modifier
.fillMaxSize()
)
}
},
content = {}
)
navigationMenu = getString(Strings.NavigationMenu)
}
rule.onNodeWithTag("navigationDrawerTag", useUnmergedTree = true)
.onParent()
.assert(SemanticsMatcher.expectValue(SemanticsProperties.PaneTitle, navigationMenu))
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_openAndClose(): Unit = runBlocking(AutoTestFrameClock()) {
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(DrawerValue.Closed)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.testTag(DrawerTestTag)
)
}
},
content = {}
)
}
// Drawer should start in closed state
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(-NavigationDrawerWidth)
// When the drawer state is set to Opened
drawerState.open()
// Then the drawer should be opened
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(0.dp)
// When the drawer state is set to Closed
drawerState.close()
// Then the drawer should be closed
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(-NavigationDrawerWidth)
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_animateTo(): Unit = runBlocking(AutoTestFrameClock()) {
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(DrawerValue.Closed)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.testTag(DrawerTestTag)
)
}
},
content = {}
)
}
// Drawer should start in closed state
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(-NavigationDrawerWidth)
// When the drawer state is set to Opened
drawerState.animateTo(DrawerValue.Open, TweenSpec())
// Then the drawer should be opened
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(0.dp)
// When the drawer state is set to Closed
drawerState.animateTo(DrawerValue.Closed, TweenSpec())
// Then the drawer should be closed
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(-NavigationDrawerWidth)
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_snapTo(): Unit = runBlocking(AutoTestFrameClock()) {
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(DrawerValue.Closed)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.testTag(DrawerTestTag)
)
}
},
content = {}
)
}
// Drawer should start in closed state
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(-NavigationDrawerWidth)
// When the drawer state is set to Opened
drawerState.snapTo(DrawerValue.Open)
// Then the drawer should be opened
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(0.dp)
// When the drawer state is set to Closed
drawerState.snapTo(DrawerValue.Closed)
// Then the drawer should be closed
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(-NavigationDrawerWidth)
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_currentValue(): Unit = runBlocking(AutoTestFrameClock()) {
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(DrawerValue.Closed)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.testTag(DrawerTestTag)
)
}
},
content = {}
)
}
// Drawer should start in closed state
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Closed)
// When the drawer state is set to Opened
drawerState.snapTo(DrawerValue.Open)
// Then the drawer should be opened
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Open)
// When the drawer state is set to Closed
drawerState.snapTo(DrawerValue.Closed)
// Then the drawer should be closed
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Closed)
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_drawerContent_doesntPropagateClicksWhenOpen(): Unit =
runBlocking(
AutoTestFrameClock()
) {
var bodyClicks = 0
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(DrawerValue.Closed)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.testTag(DrawerTestTag)
)
}
},
content = {
Box(
Modifier
.fillMaxSize()
.clickable { bodyClicks += 1 })
}
)
}
// Click in the middle of the drawer
rule.onNodeWithTag(DrawerTestTag).performClick()
rule.runOnIdle {
assertThat(bodyClicks).isEqualTo(1)
}
drawerState.open()
// Click on the left-center pixel of the drawer
rule.onNodeWithTag(DrawerTestTag).performTouchInput {
click(centerLeft)
}
rule.runOnIdle {
assertThat(bodyClicks).isEqualTo(1)
}
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_openBySwipe() {
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(DrawerValue.Closed)
Box(Modifier.testTag(DrawerTestTag)) {
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.background(color = Color.Magenta)
)
}
},
content = {
Box(
Modifier
.fillMaxSize()
.background(color = Color.Red)
)
}
)
}
}
rule.onNodeWithTag(DrawerTestTag)
.performTouchInput { swipeRight() }
rule.runOnIdle {
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Open)
}
rule.onNodeWithTag(DrawerTestTag)
.performTouchInput { swipeLeft() }
rule.runOnIdle {
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Closed)
}
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_confirmStateChangeRespect() {
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(
DrawerValue.Open,
confirmStateChange = {
it != DrawerValue.Closed
}
)
Box(Modifier.testTag(DrawerTestTag)) {
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet(Modifier.testTag("content")) {
Box(
Modifier
.fillMaxSize()
.background(color = Color.Magenta)
)
}
},
content = {
Box(
Modifier
.fillMaxSize()
.background(color = Color.Red)
)
}
)
}
}
rule.onNodeWithTag(DrawerTestTag)
.performTouchInput { swipeLeft() }
// still open
rule.runOnIdle {
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Open)
}
rule.onNodeWithTag("content", useUnmergedTree = true)
.onParent()
.performSemanticsAction(SemanticsActions.Dismiss)
rule.runOnIdle {
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Open)
}
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_openBySwipe_rtl() {
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(DrawerValue.Closed)
// emulate click on the screen
CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
Box(Modifier.testTag(DrawerTestTag)) {
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.background(color = Color.Magenta)
)
}
},
content = {
Box(
Modifier
.fillMaxSize()
.background(color = Color.Red)
)
}
)
}
}
}
rule.onNodeWithTag(DrawerTestTag)
.performTouchInput { swipeLeft() }
rule.runOnIdle {
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Open)
}
rule.onNodeWithTag(DrawerTestTag)
.performTouchInput { swipeRight() }
rule.runOnIdle {
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Closed)
}
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_noDismissActionWhenClosed_hasDissmissActionWhenOpen(): Unit =
runBlocking(
AutoTestFrameClock()
) {
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(DrawerValue.Closed)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet(Modifier.testTag(DrawerTestTag)) {
Box(
Modifier
.fillMaxSize()
)
}
},
content = {}
)
}
// Drawer should start in closed state and have no dismiss action
rule.onNodeWithTag(DrawerTestTag, useUnmergedTree = true)
.onParent()
.assert(SemanticsMatcher.keyNotDefined(SemanticsActions.Dismiss))
// When the drawer state is set to Opened
drawerState.open()
// Then the drawer should be opened and have dismiss action
rule.onNodeWithTag(DrawerTestTag, useUnmergedTree = true)
.onParent()
.assert(SemanticsMatcher.keyIsDefined(SemanticsActions.Dismiss))
// When the drawer state is set to Closed using dismiss action
rule.onNodeWithTag(DrawerTestTag, useUnmergedTree = true)
.onParent()
.performSemanticsAction(SemanticsActions.Dismiss)
// Then the drawer should be closed and have no dismiss action
rule.onNodeWithTag(DrawerTestTag, useUnmergedTree = true)
.onParent()
.assert(SemanticsMatcher.keyNotDefined(SemanticsActions.Dismiss))
}
@Test
fun dismissibleNavigationDrawer_providesScrollableContainerInfo_enabled() {
var actualValue = { false }
rule.setMaterialContent(lightColorScheme()) {
DismissibleNavigationDrawer(
gesturesEnabled = true,
drawerContent = {},
content = {
Box(Modifier.consumeScrollContainerInfo {
actualValue = { it!!.canScroll() }
})
}
)
}
assertThat(actualValue()).isTrue()
}
@Test
fun dismissibleNavigationDrawer_providesScrollableContainerInfo_disabled() {
var actualValue = { false }
rule.setMaterialContent(lightColorScheme()) {
DismissibleNavigationDrawer(
gesturesEnabled = false,
drawerContent = {},
content = {
Box(Modifier.consumeScrollContainerInfo {
actualValue = { it!!.canScroll() }
})
}
)
}
assertThat(actualValue()).isFalse()
}
}
private val DrawerTestTag = "drawer" | compose/material3/material3/src/androidAndroidTest/kotlin/androidx/compose/material3/DismissibleNavigationDrawerTest.kt | 1895943661 |
/*
* 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.diff.merge
import com.intellij.diff.DiffContentFactoryImpl
import com.intellij.diff.DiffTestCase
import com.intellij.diff.contents.DocumentContent
import com.intellij.diff.merge.MergeTestBase.SidesState.*
import com.intellij.diff.merge.TextMergeViewer
import com.intellij.diff.merge.TextMergeViewer.MyThreesideViewer
import com.intellij.diff.util.DiffUtil
import com.intellij.diff.util.Side
import com.intellij.diff.util.TextDiffType
import com.intellij.diff.util.ThreeSide
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Couple
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.StringUtil
import com.intellij.testFramework.fixtures.IdeaProjectTestFixture
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory
import com.intellij.util.ui.UIUtil
abstract class MergeTestBase : DiffTestCase() {
private var projectFixture: IdeaProjectTestFixture? = null
private var project: Project? = null
override fun setUp() {
super.setUp()
projectFixture = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(getTestName(true)).fixture
projectFixture!!.setUp()
project = projectFixture!!.project
}
override fun tearDown() {
projectFixture?.tearDown()
project = null
super.tearDown()
}
fun test1(left: String, base: String, right: String, f: TestBuilder.() -> Unit) {
test(left, base, right, 1, f)
}
fun test2(left: String, base: String, right: String, f: TestBuilder.() -> Unit) {
test(left, base, right, 2, f)
}
fun testN(left: String, base: String, right: String, f: TestBuilder.() -> Unit) {
test(left, base, right, -1, f)
}
fun test(left: String, base: String, right: String, changesCount: Int, f: TestBuilder.() -> Unit) {
val contentFactory = DiffContentFactoryImpl()
val leftContent: DocumentContent = contentFactory.create(parseSource(left))
val baseContent: DocumentContent = contentFactory.create(parseSource(base))
val rightContent: DocumentContent = contentFactory.create(parseSource(right))
val outputContent: DocumentContent = contentFactory.create(parseSource(""))
outputContent.document.setReadOnly(false)
val context = MockMergeContext(project)
val request = MockMergeRequest(leftContent, baseContent, rightContent, outputContent)
val viewer = TextMergeTool.INSTANCE.createComponent(context, request) as TextMergeViewer
try {
val toolbar = viewer.init()
UIUtil.dispatchAllInvocationEvents()
val builder = TestBuilder(viewer, toolbar.toolbarActions ?: emptyList())
builder.assertChangesCount(changesCount)
builder.f()
} finally {
Disposer.dispose(viewer)
}
}
inner class TestBuilder(val mergeViewer: TextMergeViewer, private val actions: List<AnAction>) {
val viewer: MyThreesideViewer = mergeViewer.viewer
val changes: List<TextMergeChange> = viewer.allChanges
val editor: EditorEx = viewer.editor
val document: Document = editor.document
private val textEditor = TextEditorProvider.getInstance().getTextEditor(editor);
private val undoManager = UndoManager.getInstance(project!!)
fun change(num: Int): TextMergeChange {
if (changes.size < num) throw Exception("changes: ${changes.size}, index: $num")
return changes[num]
}
fun activeChanges(): List<TextMergeChange> = viewer.changes
//
// Actions
//
fun runActionByTitle(name: String): Boolean {
val action = actions.filter { name.equals(it.templatePresentation.text) }
assertTrue(action.size == 1, action.toString())
return runAction(action[0])
}
private fun runAction(action: AnAction): Boolean {
val actionEvent = AnActionEvent.createFromAnAction(action, null, ActionPlaces.MAIN_MENU, editor.dataContext)
action.update(actionEvent)
val success = actionEvent.presentation.isEnabledAndVisible
if (success) action.actionPerformed(actionEvent)
return success
}
//
// Modification
//
fun command(affected: TextMergeChange, f: () -> Unit): Unit {
command(listOf(affected), f)
}
fun command(affected: List<TextMergeChange>? = null, f: () -> Unit): Unit {
viewer.executeMergeCommand(null, affected, f)
UIUtil.dispatchAllInvocationEvents()
}
fun write(f: () -> Unit): Unit {
ApplicationManager.getApplication().runWriteAction({ CommandProcessor.getInstance().executeCommand(project, f, null, null) })
UIUtil.dispatchAllInvocationEvents()
}
fun Int.ignore(side: Side, modifier: Boolean = false) {
val change = change(this)
command(change) { viewer.ignoreChange(change, side, modifier) }
}
fun Int.apply(side: Side, modifier: Boolean = false) {
val change = change(this)
command(change) { viewer.replaceChange(change, side, modifier) }
}
//
// Text modification
//
fun insertText(offset: Int, newContent: CharSequence) {
replaceText(offset, offset, newContent)
}
fun deleteText(startOffset: Int, endOffset: Int) {
replaceText(startOffset, endOffset, "")
}
fun replaceText(startOffset: Int, endOffset: Int, newContent: CharSequence) {
write { document.replaceString(startOffset, endOffset, parseSource(newContent)) }
}
fun insertText(offset: LineCol, newContent: CharSequence) {
replaceText(offset.toOffset(), offset.toOffset(), newContent)
}
fun deleteText(startOffset: LineCol, endOffset: LineCol) {
replaceText(startOffset.toOffset(), endOffset.toOffset(), "")
}
fun replaceText(startOffset: LineCol, endOffset: LineCol, newContent: CharSequence) {
write { replaceText(startOffset.toOffset(), endOffset.toOffset(), newContent) }
}
fun replaceText(oldContent: CharSequence, newContent: CharSequence) {
write {
val range = findRange(parseSource(oldContent))
replaceText(range.first, range.second, newContent)
}
}
fun deleteText(oldContent: CharSequence) {
write {
val range = findRange(parseSource(oldContent))
replaceText(range.first, range.second, "")
}
}
fun insertTextBefore(oldContent: CharSequence, newContent: CharSequence) {
write { insertText(findRange(parseSource(oldContent)).first, newContent) }
}
fun insertTextAfter(oldContent: CharSequence, newContent: CharSequence) {
write { insertText(findRange(parseSource(oldContent)).second, newContent) }
}
private fun findRange(oldContent: CharSequence): Couple<Int> {
val text = document.charsSequence
val index1 = StringUtil.indexOf(text, oldContent)
assertTrue(index1 >= 0, "content - '\n$oldContent\n'\ntext - '\n$text'")
val index2 = StringUtil.indexOf(text, oldContent, index1 + 1)
assertTrue(index2 == -1, "content - '\n$oldContent\n'\ntext - '\n$text'")
return Couple(index1, index1 + oldContent.length)
}
//
// Undo
//
fun undo(count: Int = 1) {
if (count == -1) {
while (undoManager.isUndoAvailable(textEditor)) {
undoManager.undo(textEditor)
}
}
else {
for (i in 1..count) {
assertTrue(undoManager.isUndoAvailable(textEditor))
undoManager.undo(textEditor)
}
}
}
fun redo(count: Int = 1) {
if (count == -1) {
while (undoManager.isRedoAvailable(textEditor)) {
undoManager.redo(textEditor)
}
}
else {
for (i in 1..count) {
assertTrue(undoManager.isRedoAvailable(textEditor))
undoManager.redo(textEditor)
}
}
}
fun checkUndo(count: Int = -1, f: TestBuilder.() -> Unit) {
val initialState = ViewerState.recordState(viewer)
f()
UIUtil.dispatchAllInvocationEvents()
val afterState = ViewerState.recordState(viewer)
undo(count)
UIUtil.dispatchAllInvocationEvents()
val undoState = ViewerState.recordState(viewer)
redo(count)
UIUtil.dispatchAllInvocationEvents()
val redoState = ViewerState.recordState(viewer)
assertEquals(initialState, undoState)
assertEquals(afterState, redoState)
}
//
// Checks
//
fun assertChangesCount(expected: Int) {
if (expected == -1) return
val actual = activeChanges().size
assertEquals(expected, actual)
}
fun Int.assertType(type: TextDiffType, changeType: SidesState) {
assertType(type)
assertType(changeType)
}
fun Int.assertType(type: TextDiffType) {
val change = change(this)
assertEquals(change.diffType, type)
}
fun Int.assertType(changeType: SidesState) {
assertTrue(changeType != NONE)
val change = change(this)
val actual = change.type
val isLeftChange = changeType != RIGHT
val isRightChange = changeType != LEFT
assertEquals(Pair(isLeftChange, isRightChange), Pair(actual.isLeftChange, actual.isRightChange))
}
fun Int.assertResolved(type: SidesState) {
val change = change(this)
val isLeftResolved = type == LEFT || type == BOTH
val isRightResolved = type == RIGHT || type == BOTH
assertEquals(Pair(isLeftResolved, isRightResolved), Pair(change.isResolved(Side.LEFT), change.isResolved(Side.RIGHT)))
}
fun Int.assertRange(start: Int, end: Int) {
val change = change(this)
assertEquals(Pair(start, end), Pair(change.startLine, change.endLine))
}
fun Int.assertContent(expected: String, start: Int, end: Int) {
assertContent(expected)
assertRange(start, end)
}
fun Int.assertContent(expected: String) {
val change = change(this)
val document = editor.document
val actual = DiffUtil.getLinesContent(document, change.startLine, change.endLine)
assertEquals(parseSource(expected), actual)
}
fun assertContent(expected: String) {
val actual = viewer.editor.document.charsSequence
assertEquals(parseSource(expected), actual)
}
//
// Helpers
//
operator fun Int.not(): LineColHelper = LineColHelper(this)
operator fun LineColHelper.minus(col: Int): LineCol = LineCol(this.line, col)
inner class LineColHelper(val line: Int) {
}
inner class LineCol(val line: Int, val col: Int) {
fun toOffset(): Int = editor.document.getLineStartOffset(line) + col
}
}
private class MockMergeContext(private val myProject: Project?) : MergeContext() {
override fun getProject(): Project? = myProject
override fun isFocused(): Boolean = false
override fun requestFocus() {
}
override fun finishMerge(result: MergeResult) {
}
}
private class MockMergeRequest(val left: DocumentContent,
val base: DocumentContent,
val right: DocumentContent,
val output: DocumentContent) : TextMergeRequest() {
override fun getTitle(): String? = null
override fun applyResult(result: MergeResult) {
}
override fun getContents(): List<DocumentContent> = listOf(left, base, right)
override fun getOutputContent(): DocumentContent = output
override fun getContentTitles(): List<String?> = listOf(null, null, null)
}
enum class SidesState {
LEFT, RIGHT, BOTH, NONE
}
private data class ViewerState private constructor(private val content: CharSequence,
private val changes: List<ViewerState.ChangeState>) {
companion object {
fun recordState(viewer: MyThreesideViewer): ViewerState {
val content = viewer.editor.document.immutableCharSequence
val changes = viewer.allChanges.map { recordChangeState(viewer, it) }
return ViewerState(content, changes)
}
private fun recordChangeState(viewer: MyThreesideViewer, change: TextMergeChange): ChangeState {
val document = viewer.editor.document;
val content = DiffUtil.getLinesContent(document, change.startLine, change.endLine)
val resolved = if (change.isResolved) BOTH else if (change.isResolved(Side.LEFT)) LEFT else if (change.isResolved(Side.RIGHT)) RIGHT else NONE
val starts = Trio.from { change.getStartLine(it) }
val ends = Trio.from { change.getStartLine(it) }
return ChangeState(content, starts, ends, resolved)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ViewerState) return false
if (!StringUtil.equals(content, other.content)) return false
if (!changes.equals(other.changes)) return false
return true
}
override fun hashCode(): Int = StringUtil.hashCode(content)
private data class ChangeState(private val content: CharSequence,
private val starts: Trio<Int>,
private val ends: Trio<Int>,
private val resolved: SidesState) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ChangeState) return false
if (!StringUtil.equals(content, other.content)) return false
if (!starts.equals(other.starts)) return false
if (!ends.equals(other.ends)) return false
if (!resolved.equals(other.resolved)) return false
return true
}
override fun hashCode(): Int = StringUtil.hashCode(content)
}
}
}
| platform/diff-impl/tests/com/intellij/diff/merge/MergeTestBase.kt | 637163582 |
package com.antyzero.cardcheck.settings
import android.content.Context
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
@Singleton
class SettingsModule {
private lateinit var context: Context
private val contextSettings: ContextSettings by lazy {
ContextSettings(context)
}
@Provides
@Singleton
fun provideSettings(context: Context): Settings {
this.context = context
return contextSettings
}
@Provides
@Singleton
fun provideContextSettings(context: Context): ContextSettings {
this.context = context
return contextSettings
}
} | app/src/main/kotlin/com/antyzero/cardcheck/settings/SettingsModule.kt | 879032715 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opencl.templates
import org.lwjgl.generator.*
import org.lwjgl.opencl.*
val intel_packed_yuv = "INTELPackedYUV".nativeClassCL("intel_packed_yuv", INTEL) {
documentation =
"""
Native bindings to the $extensionLink extension.
The purpose of this extension is to provide OpenCL support for packed YUV images.
Requires ${CL12.link}.
"""
IntConstant(
"Accepted as {@code image_channel_order} of {@code cl_image_format}.",
"YUYV_INTEL"..0x4076,
"UYVY_INTEL"..0x4077,
"YVYU_INTEL"..0x4078,
"VYUY_INTEL"..0x4079
)
} | modules/templates/src/main/kotlin/org/lwjgl/opencl/templates/intel_packed_yuv.kt | 1277699584 |
package com.antyzero.cardcheck.dsl.extension
import org.threeten.bp.LocalDate
import org.threeten.bp.LocalTime
import org.threeten.bp.temporal.ChronoUnit
fun ChronoUnit.betweenWithMidnight(first: LocalTime, second: LocalTime): Long {
val firstDateTime = first.atDate(LocalDate.MIN)
var secondDateTime = second.atDate(LocalDate.MIN)
if (secondDateTime.isBefore(firstDateTime)) {
secondDateTime = secondDateTime.plusDays(1)
}
return ChronoUnit.SECONDS.between(firstDateTime, secondDateTime)
} | app/src/main/kotlin/com/antyzero/cardcheck/dsl/extension/ChronoUnitExtension.kt | 3536617001 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.at.psi.mixins
import com.demonwav.mcdev.platform.mcp.at.psi.AtElement
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
interface AtReturnValueMixin : AtElement {
val classValue: PsiElement?
val primitive: PsiElement?
val returnValueClass: PsiClass?
val returnValueText: String
fun setReturnValue(returnValue: String)
}
| src/main/kotlin/platform/mcp/at/psi/mixins/AtReturnValueMixin.kt | 3520117203 |
//package org.wordpress.aztec
//
//import android.app.Activity
//import android.text.TextUtils
//import org.junit.Assert
//import org.junit.Before
//import org.junit.Test
//import org.junit.runner.RunWith
//import org.robolectric.Robolectric
//import org.robolectric.RobolectricTestRunner
//import org.robolectric.annotation.Config
//import java.util.*
//
///**
// * Testing code behaviour.
// */
//@RunWith(RobolectricTestRunner::class)
//@Config(constants = BuildConfig::class)
//class CodeTest {
//
// val formattingType = AztecTextFormat.FORMAT_CODE
// val codeTag = "code"
// lateinit var editText: AztecText
//
// /**
// * Initialize variables.
// */
// @Before
// fun init() {
// val activity = Robolectric.buildActivity(Activity::class.java).create().visible().get()
// editText = AztecText(activity)
// activity.setContentView(editText)
// }
//
// fun setStyles(editText: AztecText) {
// val styles = ArrayList<ITextFormat>()
// styles.add(formattingType)
// editText.setSelectedStyles(styles)
// }
//
// @Test
// @Throws(Exception::class)
// fun styleSingleItem() {
// editText.append("println(\"hello world\");")
// setStyles(editText)
// Assert.assertEquals("<$codeTag>println(\"hello world\");</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun styleMultipleSelectedItems() {
// junit.framework.Assert.assertTrue(TextUtils.isEmpty(editText.text))
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// editText.append("\n")
// editText.append("third item")
// editText.setSelection(0, editText.length())
// setStyles(editText)
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun stylePartiallySelectedMultipleItems() {
// junit.framework.Assert.assertTrue(TextUtils.isEmpty(editText.text))
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// editText.append("\n")
// editText.append("third item")
// editText.setSelection(4, 15) // we partially selected first and second item
// setStyles(editText)
// Assert.assertEquals("<$codeTag>first item<br>second item</$codeTag>third item", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun styleSurroundedItem() {
// junit.framework.Assert.assertTrue(TextUtils.isEmpty(editText.text))
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// editText.append("\n")
// editText.append("third item")
// editText.setSelection(14)
// setStyles(editText)
// Assert.assertEquals("first item<$codeTag>second item</$codeTag>third item", editText.toHtml())
// }
//
// // enable styling on empty line and enter text
// @Test
// @Throws(Exception::class)
// fun emptyCode() {
// editText.toggleFormatting(formattingType)
// Assert.assertEquals("<$codeTag></$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun styleSingleEnteredItem() {
// setStyles(editText)
// editText.append("first item")
// Assert.assertEquals("<$codeTag>first item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun styleMultipleEnteredItems() {
// setStyles(editText)
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// Assert.assertEquals("<$codeTag>first item<br>second item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun closingPopulatedCode1() {
// val styles = ArrayList<ITextFormat>()
// styles.add(AztecTextFormat.FORMAT_STRIKETHROUGH)
// editText.setSelectedStyles(styles)
// editText.append("first item")
// Assert.assertEquals("<s>first item</s>", editText.toHtml().toString())
// }
//
// @Test
// @Throws(Exception::class)
// fun closingPopulatedCode() {
// val styles = ArrayList<ITextFormat>()
// styles.add(formattingType)
// editText.setSelectedStyles(styles)
// editText.append("first item")
// editText.append("\n")
// editText.append("\n")
// editText.append("not in the code")
// Assert.assertEquals("<$codeTag>first item</$codeTag>not in the code", editText.toHtml().toString())
// }
//
// @Test
// @Throws(Exception::class)
// fun closingEmptyCode() {
// setStyles(editText)
// editText.append("\n")
// Assert.assertEquals("", editText.toHtml().toString())
// }
//
// @Test
// @Throws(Exception::class)
// fun extendingCodeBySplittingItems() {
// setStyles(editText)
// editText.append("firstitem")
// editText.text.insert(5, "\n")
// Assert.assertEquals("<$codeTag>first<br>item</$codeTag>", editText.toHtml().toString())
// }
//
// @Test
// @Throws(Exception::class)
// fun codeSplitWithToolbar() {
// editText.fromHtml("<$codeTag>first item<br>second item<br>third item</$codeTag>")
// editText.setSelection(14)
// setStyles(editText)
// Assert.assertEquals("<$codeTag>first item</$codeTag>second item<$codeTag>third item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun removeCodeStyling() {
// editText.fromHtml("<$codeTag>first item</$codeTag>")
// editText.setSelection(1)
// setStyles(editText)
// Assert.assertEquals("first item", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun removeCodeStylingForPartialSelection() {
// editText.fromHtml("<$codeTag>first item</$codeTag>")
// editText.setSelection(2, 4)
// setStyles(editText)
// Assert.assertEquals("first item", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun removeCodeStylingForMultilinePartialSelection() {
// setStyles(editText)
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// val firstMark = editText.length() - 4
// editText.append("\n")
// editText.append("third item")
// editText.append("\n")
// val secondMark = editText.length() - 4
// editText.append("fourth item")
// editText.append("\n")
// editText.append("\n")
// editText.append("not in code")
// editText.setSelection(firstMark, secondMark)
// editText.setSelectedStyles(ArrayList());
// Assert.assertEquals("<$codeTag>first item</$codeTag>second item<br>third item<$codeTag>fourth item</$codeTag>not in code", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun emptyCodeSurroundedBytItems() {
// setStyles(editText)
// editText.append("first item")
// editText.append("\n")
// val firstMark = editText.length()
// editText.append("second item")
// editText.append("\n")
// val secondMart = editText.length()
// editText.append("third item")
// editText.text.delete(firstMark - 1, secondMart - 2)
// Assert.assertEquals("<$codeTag>first item<br><br>third item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun trailingEmptyLine() {
// setStyles(editText)
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// editText.append("\n")
// editText.append("third item")
// val mark = editText.length()
// editText.append("\n")
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>", editText.toHtml())
//
// editText.append("\n")
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>", editText.toHtml())
//
// editText.append("not in code")
// editText.setSelection(mark)
// editText.text.insert(mark, "\n")
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag><br>not in code", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun openCodeByAddingNewline() {
// editText.fromHtml("<$codeTag>first item<br>second item</$codeTag>not in code")
// val mark = editText.text.indexOf("second item") + "second item".length
// editText.text.insert(mark, "\n")
// editText.text.insert(mark + 1, "third item")
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>not in code", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun openCodeByAppendingTextToTheEnd() {
// editText.fromHtml("<$codeTag>first item<br>second item</$codeTag>not in code")
// editText.setSelection(editText.length())
// editText.text.insert(editText.text.indexOf("\nnot in code"), " (appended)")
// Assert.assertEquals("<$codeTag>first item<br>second item (appended)</$codeTag>not in code", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun openCodeByMovingOutsideTextInsideIt() {
// editText.fromHtml("<$codeTag>first item<br>second item</$codeTag>")
// editText.append("not in code")
//
// editText.text.delete(editText.text.indexOf("not in code"), editText.text.indexOf("not in code"))
// Assert.assertEquals("<$codeTag>first item<br>second itemnot in code</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun codeRemainsClosedWhenLastCharacterIsDeleted() {
// editText.fromHtml("<$codeTag>first item<br>second item</$codeTag>not in code")
// editText.setSelection(editText.length())
//
// val mark = editText.text.indexOf("second item") + "second item".length;
//
// // delete last character from "second item"
// editText.text.delete(mark - 1, mark)
// Assert.assertEquals("<$codeTag>first item<br>second ite</$codeTag>not in code", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun openingAndReopeningOfCode() {
// editText.fromHtml("<$codeTag>first item<br>second item</$codeTag>")
// editText.setSelection(editText.length())
//
// editText.append("\n")
// editText.append("third item")
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>", editText.toHtml())
// editText.append("\n")
// editText.append("\n")
// val mark = editText.length() - 1
// editText.append("not in the code")
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>not in the code", editText.toHtml())
// editText.append("\n")
// editText.append("foo")
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>not in the code<br>foo", editText.toHtml())
//
// // reopen code
// editText.text.delete(mark, mark + 1)
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third itemnot in the code</$codeTag>foo", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun closeCode() {
// editText.fromHtml("<$codeTag>first item</$codeTag>")
// editText.setSelection(editText.length())
//
// Assert.assertEquals("first item", editText.text.toString())
// editText.append("\n")
// Assert.assertEquals("first item\n\u200B", editText.text.toString())
//
// editText.text.delete(editText.length() - 1, editText.length())
// Assert.assertEquals("first item\n", editText.text.toString())
//
// editText.append("not in the code")
// Assert.assertEquals("<$codeTag>first item</$codeTag>not in the code", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun handlecodeReopeningAfterLastElementDeletion() {
// editText.fromHtml("<$codeTag>first item<br>second item<br>third item</$codeTag>")
// editText.setSelection(editText.length())
// editText.text.delete(editText.text.indexOf("third item", 0), editText.length())
// editText.append("not in the code")
// Assert.assertEquals("<$codeTag>first item<br>second item</$codeTag>not in the code", editText.toHtml())
//
// editText.text.insert(editText.text.indexOf("not in the code") - 1, " addition")
// Assert.assertEquals("<$codeTag>first item<br>second item addition</$codeTag>not in the code", editText.toHtml())
//
// editText.text.insert(editText.text.indexOf("not in the code") - 1, "\n")
// editText.text.insert(editText.text.indexOf("not in the code") - 1, "third item")
// Assert.assertEquals("first item\nsecond item addition\nthird item\nnot in the code", editText.text.toString())
// Assert.assertEquals("<$codeTag>first item<br>second item addition<br>third item</$codeTag>not in the code", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun additionToClosedCode() {
// setStyles(editText)
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// val mark = editText.length()
// editText.append("\n")
// editText.append("\n")
// editText.append("not in the code")
// Assert.assertEquals("<$codeTag>first item<br>second item</$codeTag>not in the code", editText.toHtml().toString())
//
// editText.text.insert(mark, " (addition)")
// Assert.assertEquals("<$codeTag>first item<br>second item (addition)</$codeTag>not in the code", editText.toHtml().toString())
// }
//
// @Test
// @Throws(Exception::class)
// fun addItemToCodeFromBottom() {
// setStyles(editText)
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// editText.append("\n")
// editText.append("\n")
// editText.append("third item")
// editText.setSelection(editText.length())
// setStyles(editText)
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun addItemToCodeFromTop() {
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// editText.setSelection(editText.length())
// editText.toggleFormatting(formattingType)
// editText.append("\n")
// editText.append("third item")
// editText.setSelection(0)
// editText.toggleFormatting(formattingType)
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun addItemToCodeFromInside() {
// setStyles(editText)
// editText.append("first item")
// editText.append("\n")
// editText.append("\n")
// editText.append("second item")
// editText.append("\n")
// editText.append("third item")
// editText.setSelection(editText.length())
// editText.toggleFormatting(formattingType)
// Assert.assertEquals("<$codeTag>first item</$codeTag>second item<$codeTag>third item</$codeTag>", editText.toHtml())
//
// editText.setSelection(15)
// editText.toggleFormatting(formattingType)
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun appendToCodeFromTopAtFirstLine() {
// setStyles(editText)
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// editText.setSelection(0)
// editText.text.insert(0, "addition ")
// Assert.assertEquals("<$codeTag>addition first item<br>second item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun appendToCodeFromTop() {
// editText.append("not in code")
// editText.append("\n")
// setStyles(editText)
// val mark = editText.length() - 1
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// editText.setSelection(mark)
// editText.text.insert(mark, "addition ")
// Assert.assertEquals("not in code<$codeTag>addition first item<br>second item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun deleteFirstItemWithKeyboard() {
// setStyles(editText)
// editText.append("first item")
// val firstMark = editText.length()
// editText.append("\n")
// editText.append("second item")
// val secondMark = editText.length()
// editText.append("\n")
// editText.append("third item")
// editText.setSelection(0)
// Assert.assertEquals("first item\nsecond item\nthird item", editText.text.toString())
//
// editText.text.delete(firstMark + 1, secondMark)
// Assert.assertEquals("first item\n\nthird item", editText.text.toString())
// Assert.assertEquals("<$codeTag>first item<br><br>third item</$codeTag>", editText.toHtml())
//
// editText.text.delete(0, firstMark)
// Assert.assertEquals("<$codeTag><br><br>third item</$codeTag>", editText.toHtml())
// }
//}
| aztec/src/test/kotlin/org/wordpress/aztec/CodeTest.kt | 3805715268 |
package com.robotpajamas.blueteeth.extensions
import android.bluetooth.BluetoothAdapter
import android.content.Context
import android.content.pm.PackageManager
inline val Context.isBluetoothSupported: Boolean
get() {
if (!packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
return false
}
val btAdapter = BluetoothAdapter.getDefaultAdapter()
return btAdapter != null
} | blueteeth/src/main/kotlin/com/robotpajamas/blueteeth/extensions/Context.kt | 81357371 |
package org.wordpress.aztec.watchers.event.sequence
open class EventSequence<TextWatcherEvent> : ArrayList<TextWatcherEvent>()
| aztec/src/main/kotlin/org/wordpress/aztec/watchers/event/sequence/EventSequence.kt | 2396491940 |
package eu.kanade.tachiyomi.multisrc.eromuse
import generator.ThemeSourceData.SingleLang
import generator.ThemeSourceGenerator
class EroMuseGenerator : ThemeSourceGenerator {
override val themePkg = "eromuse"
override val themeClass = "EroMuse"
override val baseVersionCode: Int = 1
override val sources = listOf(
SingleLang("8Muses", "https://comics.8muses.com", "en", className = "EightMuses", isNsfw = true, overrideVersionCode = 1),
SingleLang("Erofus", "https://www.erofus.com", "en", isNsfw = true, overrideVersionCode = 1)
)
companion object {
@JvmStatic
fun main(args: Array<String>) {
EroMuseGenerator().createAll()
}
}
}
| multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/eromuse/EroMuseGenerator.kt | 4144638352 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.wall.dto
import com.google.gson.annotations.SerializedName
import com.vk.sdk.api.groups.dto.GroupsGroupFull
import com.vk.sdk.api.users.dto.UsersUserFull
import kotlin.Int
import kotlin.collections.List
/**
* @param count - Total number
* @param items
* @param profiles
* @param groups
*/
data class WallSearchExtendedResponse(
@SerializedName("count")
val count: Int,
@SerializedName("items")
val items: List<WallWallpostFull>,
@SerializedName("profiles")
val profiles: List<UsersUserFull>,
@SerializedName("groups")
val groups: List<GroupsGroupFull>
)
| api/src/main/java/com/vk/sdk/api/wall/dto/WallSearchExtendedResponse.kt | 9945382 |
package com.example.demo.api.realestate.handler.brokers.crud.search
import com.example.demo.api.realestate.domain.jpa.entities.Broker
import com.example.demo.api.realestate.handler.common.response.BrokerDto
import com.example.demo.api.realestate.handler.common.response.ResponsePaging
import com.querydsl.core.QueryResults
data class SearchBrokersResponse(
val paging: ResponsePaging,
val brokers: List<BrokerDto>
) {
companion object {
fun of(resultSet: QueryResults<Broker>): SearchBrokersResponse =
SearchBrokersResponse(
paging = ResponsePaging.ofResultSet(resultSet),
brokers = resultSet.results.map { it.toDto() }
)
}
}
private fun Broker.toDto() = BrokerDto.of(this) | src/main/kotlin/com/example/demo/api/realestate/handler/brokers/crud/search/response.kt | 2773253886 |
package io.bluerain.tweets.data.models
import com.google.gson.annotations.SerializedName
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by hentioe on 17-4-23.
* 数据层: Tweet 模型相关
*/
// 前台 Tweet 模型
data class TweetModel(
var id: Long = 0,
var content: String = "",
var color: String = "",
@SerializedName("create_at") var createAt: Date = Date(),
@SerializedName("update_at") var updateAt: Date = Date(),
@SerializedName("resource_status") var resourceStatus: Int = 0
)
private val dateFormat = SimpleDateFormat("yyyy.MM.dd", Locale.CHINA)
fun TweetModel.createFormatDate(): String = dateFormat.format(this.createAt)
fun TweetModel.statusToString(): String {
when (this.resourceStatus) {
0 -> return ""
1 -> return "(被隐藏的)"
}
return "(特殊状态)"
}
// Tweet Json 传输模型
data class TweetJsonModel(
val id: Long = 0,
var content: String = "",
var color: String = ""
) | app/src/main/kotlin/io/bluerain/tweets/data/models/TweetModel.kt | 3168260431 |
package com.raxdenstudios.square.interceptor.commons.telephony
import com.raxdenstudios.square.interceptor.Interceptor
/**
* Created by Ángel Gómez on 30/12/2016.
*/
interface TelephonyInterceptor : Interceptor
| square-commons/src/main/java/com/raxdenstudios/square/interceptor/commons/telephony/TelephonyInterceptor.kt | 3469007327 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.base.dto
import com.google.gson.annotations.SerializedName
import kotlin.String
enum class BaseLinkProductStatus(
val value: String
) {
@SerializedName("active")
ACTIVE("active"),
@SerializedName("blocked")
BLOCKED("blocked"),
@SerializedName("sold")
SOLD("sold"),
@SerializedName("deleted")
DELETED("deleted"),
@SerializedName("archived")
ARCHIVED("archived");
}
| api/src/main/java/com/vk/sdk/api/base/dto/BaseLinkProductStatus.kt | 136848070 |
package com.intfocus.template.subject.nine.module.text
import com.intfocus.template.base.BasePresenter
import com.intfocus.template.base.BaseView
/**
* @author liuruilin
* @data 2017/11/1
* @describe
*/
interface TextModuleContract {
interface View : BaseView<Presenter> {
fun initModule(entity: TextEntity)
}
interface Presenter : BasePresenter {
fun loadData(mParam: String)
fun update(entity: TextEntity, key: String, listItemType: Int)
}
}
| app/src/main/java/com/intfocus/template/subject/nine/module/text/TextModuleContract.kt | 1773212003 |
package com.intfocus.template.dashboard.kpi
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.View
import com.intfocus.template.ui.view.CustomLinearLayoutManager
import com.yonghui.homemetrics.utils.Utils
/**
* Created by CANC on 2017/7/28.
*/
class KpiScrollerListener(val context: Context,
val recyclerView: RecyclerView,
val titleTop: View) : RecyclerView.OnScrollListener() {
private val statusBarHeight: Int = Utils.getStatusBarHeight(context)
private val mLinearLayoutManager: CustomLinearLayoutManager = recyclerView.layoutManager as CustomLinearLayoutManager
/**
* firstVisibleItem:当前能看见的第一个列表项ID(从0开始)
* visibleItemCount:当前能看见的列表项个数(小半个也算) totalItemCount:列表项共数
*/
override fun onScrolled(view: RecyclerView?, dx: Int, dy: Int) {
val isSignificantDelta = Math.abs(dy) > 4
if (isSignificantDelta) {
if (dy > 0) {
} else {
}
}
val loc = IntArray(2)
val firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition()
if (firstVisibleItem == 0 && recyclerView.getChildAt(firstVisibleItem) != null) {
recyclerView.getChildAt(firstVisibleItem).getLocationOnScreen(loc)
if (loc[1] <= statusBarHeight) {
val alpha = Math.abs(loc[1] - statusBarHeight) * 1.0f / titleTop
.measuredHeight
titleTop.alpha = alpha
} else {
titleTop.alpha = 0f
}
}
}
}
| app/src/main/java/com/intfocus/template/dashboard/kpi/KpiScrollerListener.kt | 2932419390 |
package com.mxt.anitrend.base.custom.viewmodel
import android.content.Context
import android.os.AsyncTask
import android.os.Bundle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.mxt.anitrend.R
import com.mxt.anitrend.base.custom.async.RequestHandler
import com.mxt.anitrend.base.interfaces.event.ResponseCallback
import com.mxt.anitrend.base.interfaces.event.RetroCallback
import com.mxt.anitrend.util.KeyUtil
import com.mxt.anitrend.util.graphql.apiError
import kotlinx.coroutines.*
import retrofit2.Call
import retrofit2.Response
import kotlin.coroutines.CoroutineContext
/**
* Created by max on 2017/10/14.
* View model abstraction contains the generic data model
*/
class ViewModelBase<T>: ViewModel(), RetroCallback<T>, CoroutineScope {
private val job: Job = SupervisorJob()
val model by lazy {
MutableLiveData<T>()
}
var state: ResponseCallback? = null
private var mLoader: RequestHandler<T>? = null
private lateinit var emptyMessage: String
private lateinit var errorMessage: String
private lateinit var tokenMessage: String
val params = Bundle()
fun setContext(context: Context?) {
context?.apply {
emptyMessage = getString(R.string.layout_empty_response)
errorMessage = getString(R.string.text_error_request)
tokenMessage = getString(R.string.text_error_auth_token)
}
}
/**
* Template to make requests for various data types from api, the
* <br></br>
* @param request_type the type of request to execute
*/
fun requestData(@KeyUtil.RequestType request_type: Int, context: Context) {
mLoader = RequestHandler(params, this, request_type)
mLoader?.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, context)
}
/**
* This method will be called when this ViewModel is no longer used and will be destroyed.
*
*
* It is useful when ViewModel observes some data and you need to clear this subscription to
* prevent a leak of this ViewModel.
*/
override fun onCleared() {
cancel()
if (mLoader?.status != AsyncTask.Status.FINISHED)
mLoader?.cancel(true)
mLoader = null
state = null
super.onCleared()
}
/**
* Invoked for a received HTTP response.
*
*
* Note: An HTTP response may still indicate an application-level failure such as a 404 or 500.
* Call [Response.isSuccessful] to determine if the response indicates success.
*
* @param call the origination requesting object
* @param response the response from the network
*/
override fun onResponse(call: Call<T>, response: Response<T>) {
val container: T? = response.body()
if (response.isSuccessful && container != null)
model.setValue(container)
else {
val error = response.apiError()
// Hacky fix that I'm ashamed of
if (response.code() == 400 && error.contains("Invalid token"))
state?.showError(tokenMessage)
else if (response.code() == 401)
state?.showError(tokenMessage)
else
state?.showError(error)
}
}
/**
* Invoked when a network exception occurred talking to the server or when an unexpected
* exception occurred creating the request or processing the response.
*
* @param call the origination requesting object
* @param throwable contains information about the error
*/
override fun onFailure(call: Call<T>, throwable: Throwable) {
state?.showEmpty(throwable.message ?: errorMessage)
throwable.printStackTrace()
}
/**
* The context of this scope.
* Context is encapsulated by the scope and used for implementation of coroutine builders that are extensions on the scope.
* Accessing this property in general code is not recommended for any purposes except accessing the [Job] instance for advanced usages.
*
* By convention, should contain an instance of a [job][Job] to enforce structured concurrency.
*/
override val coroutineContext: CoroutineContext = Dispatchers.IO + job
}
| app/src/main/java/com/mxt/anitrend/base/custom/viewmodel/ViewModelBase.kt | 1905329436 |
package com.intfocus.template.dashboard.report.mode
/**
* Created by liuruilin on 2017/6/15.
*/
class ListPageBean {
var code: Int = 0
var message: String? = null
var data: List<CategoryBean>? = null
}
| app/src/main/java/com/intfocus/template/dashboard/report/mode/ListPageBean.kt | 3871554139 |
package com.mxt.anitrend.model.api.converter
import android.content.Context
import com.google.gson.ExclusionStrategy
import com.google.gson.FieldAttributes
import com.google.gson.GsonBuilder
import com.mxt.anitrend.model.api.converter.request.AniRequestConverter
import com.mxt.anitrend.model.api.converter.response.AniGraphResponseConverter
import io.github.wax911.library.converter.GraphConverter
import io.github.wax911.library.model.request.QueryContainerBuilder
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type
class AniGraphConverter(
context: Context?
) : GraphConverter(context) {
/**
* Response body converter delegates logic processing to a child class that handles
* wrapping and deserialization of the json response data.
*
* @param parameterAnnotations All the annotation applied to request parameters
* @param methodAnnotations All the annotation applied to the requesting method
* @param retrofit The retrofit object representing the response
* @param type The type of the parameter of the request
*
* @see AniRequestConverter
*/
override fun requestBodyConverter(
type: Type?,
parameterAnnotations: Array<Annotation>,
methodAnnotations: Array<Annotation>,
retrofit: Retrofit?
): Converter<QueryContainerBuilder, RequestBody>? =
AniRequestConverter(
methodAnnotations = methodAnnotations,
graphProcessor = graphProcessor,
gson = gson
)
/**
* Response body converter delegates logic processing to a child class that handles
* wrapping and deserialization of the json response data.
* @see GraphResponseConverter
* <br></br>
*
*
* @param annotations All the annotation applied to the requesting Call method
* @see retrofit2.Call
*
* @param retrofit The retrofit object representing the response
* @param type The generic type declared on the Call method
*/
override fun responseBodyConverter(
type: Type?,
annotations: Array<Annotation>,
retrofit: Retrofit
): Converter<ResponseBody, *>? =
AniGraphResponseConverter<Any>(type, gson)
companion object {
/**
* Allows you to provide your own Gson configuration which will be used when serialize or
* deserialize response and request bodies.
*
* @param context any valid application context
*/
fun create(context: Context?) =
AniGraphConverter(context).apply {
gson = GsonBuilder()
.addSerializationExclusionStrategy(object : ExclusionStrategy {
/**
* @param clazz the class object that is under test
* @return true if the class should be ignored; otherwise false
*/
override fun shouldSkipClass(clazz: Class<*>?) = false
/**
* @param f the field object that is under test
* @return true if the field should be ignored; otherwise false
*/
override fun shouldSkipField(f: FieldAttributes?): Boolean {
return f?.name?.equals("operationName") ?: false
||
f?.name?.equals("extensions") ?: false
}
})
.enableComplexMapKeySerialization()
.setLenient()
.create()
}
}
} | app/src/main/java/com/mxt/anitrend/model/api/converter/AniGraphConverter.kt | 794943200 |
package uy.klutter.vertx
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule
import io.vertx.core.json.Json
/**
* Tell the Vert.x and Hazelcast logging facades to log through SLF4j, this must be called very early in your application
* before the logging systems are activated.
*/
fun setupVertxLoggingToSlf4j() {
// must be called before anything in Vertx
System.setProperty("vertx.logger-delegate-factory-class-name", "io.vertx.core.logging.SLF4JLogDelegateFactory")
System.setProperty("hazelcast.logging.type", "slf4j")
}
/**
* Setup the Vert.x singleton for Jackson ObjectMapper to support Kotlin and JDK 8 types. This should be called very early
* in your application lifecycle.
*/
fun setupVertxJsonForKotlin() {
addJacksonJdk8ModulesToMapper(Json.mapper)
addJacksonJdk8ModulesToMapper(Json.prettyMapper)
}
fun addJacksonJdk8ModulesToMapper(mapper: ObjectMapper): ObjectMapper {
return mapper.registerKotlinModule()
.registerModule(JavaTimeModule())
.registerModule(Jdk8Module())
.registerModule(ParameterNamesModule(JsonCreator.Mode.PROPERTIES))
}
| vertx3/src/main/kotlin/uy/klutter/vertx/VertxUtil.kt | 580088503 |
/*
* Copyright (C) 2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xquery.lang.highlighter
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.elementType
import uk.co.reecedunn.intellij.plugin.xpath.model.getUsageType
import uk.co.reecedunn.intellij.plugin.xpm.context.XpmUsageType
import uk.co.reecedunn.intellij.plugin.xpm.lang.highlighter.XpmSemanticHighlighter
import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.PluginDirAttribute
import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.PluginDirNamespaceAttribute
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryDirElemConstructor
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryDirPIConstructor
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryModule
object XQuerySemanticHighlighter : XpmSemanticHighlighter {
private fun getVariableHighlighting(element: PsiElement?): TextAttributesKey = when (element?.getUsageType()) {
XpmUsageType.Parameter -> XQuerySyntaxHighlighterColors.PARAMETER
else -> XQuerySyntaxHighlighterColors.VARIABLE
}
override fun accepts(file: PsiFile): Boolean = file is XQueryModule
override fun getHighlighting(element: PsiElement): TextAttributesKey = when (element.getUsageType()) {
XpmUsageType.Annotation -> XQuerySyntaxHighlighterColors.ANNOTATION
XpmUsageType.Attribute -> XQuerySyntaxHighlighterColors.ATTRIBUTE
XpmUsageType.DecimalFormat -> XQuerySyntaxHighlighterColors.DECIMAL_FORMAT
XpmUsageType.Element -> XQuerySyntaxHighlighterColors.ELEMENT
XpmUsageType.FunctionDecl -> XQuerySyntaxHighlighterColors.FUNCTION_DECL
XpmUsageType.FunctionRef -> XQuerySyntaxHighlighterColors.FUNCTION_CALL
XpmUsageType.MapKey -> XQuerySyntaxHighlighterColors.MAP_KEY
XpmUsageType.Namespace -> XQuerySyntaxHighlighterColors.NS_PREFIX
XpmUsageType.Option -> XQuerySyntaxHighlighterColors.OPTION
XpmUsageType.Parameter -> XQuerySyntaxHighlighterColors.PARAMETER
XpmUsageType.Pragma -> XQuerySyntaxHighlighterColors.PRAGMA
XpmUsageType.ProcessingInstruction -> XQuerySyntaxHighlighterColors.PROCESSING_INSTRUCTION
XpmUsageType.Type -> XQuerySyntaxHighlighterColors.TYPE
XpmUsageType.Variable -> getVariableHighlighting(element.reference?.resolve())
XpmUsageType.Unknown -> XQuerySyntaxHighlighterColors.IDENTIFIER
}
override fun getElementHighlighting(element: PsiElement): TextAttributesKey {
val ret = XQuerySyntaxHighlighter.getTokenHighlights(element.elementType!!)
return when {
ret.isEmpty() -> XQuerySyntaxHighlighterColors.IDENTIFIER
ret.size == 1 -> ret[0]
else -> ret[1]
}
}
override fun getQNamePrefixHighlighting(element: PsiElement): TextAttributesKey = when {
XpmSemanticHighlighter.isXmlnsPrefix(element) -> XQuerySyntaxHighlighterColors.ATTRIBUTE
else -> XQuerySyntaxHighlighterColors.NS_PREFIX
}
override fun highlight(element: PsiElement, holder: AnnotationHolder) {
highlight(element, XQuerySyntaxHighlighterColors.IDENTIFIER, holder)
}
override fun highlight(element: PsiElement, textAttributes: TextAttributesKey, holder: AnnotationHolder) {
holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(element)
.enforcedTextAttributes(TextAttributes.ERASE_MARKER)
.create()
if (supportsXmlTagHighlighting(element.parent.parent)) {
// Workaround IDEA-234709 -- XML_TAG is overriding the text colour of textAttributes.
if (!EditorColorsManager.getInstance().isDarkEditor) {
holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(element)
.textAttributes(XQuerySyntaxHighlighterColors.XML_TAG)
.create()
}
}
holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(element)
.textAttributes(textAttributes)
.create()
}
private fun supportsXmlTagHighlighting(node: PsiElement): Boolean = when (node) {
is PluginDirAttribute -> true
is PluginDirNamespaceAttribute -> true
is XQueryDirElemConstructor -> true
is XQueryDirPIConstructor -> true
else -> false
}
}
| src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/lang/highlighter/XQuerySemanticHighlighter.kt | 328234566 |
package com.habitrpg.android.habitica.ui.views.tasks.form
import android.content.Context
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.accessibility.AccessibilityEvent
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.habitrpg.android.habitica.R
import com.habitrpg.common.habitica.extensions.dpToPx
import com.habitrpg.common.habitica.extensions.nameRes
import com.habitrpg.shared.habitica.models.tasks.HabitResetOption
class HabitResetStreakButtons @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
var tintColor: Int = ContextCompat.getColor(context, R.color.brand_300)
var selectedResetOption: HabitResetOption = HabitResetOption.DAILY
set(value) {
field = value
removeAllViews()
addAllButtons()
selectedButton.sendAccessibilityEvent(
AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION
)
}
private lateinit var selectedButton: TextView
init {
addAllButtons()
}
private fun addAllButtons() {
val lastResetOption = HabitResetOption.values().last()
val margin = 16.dpToPx(context)
val height = 28.dpToPx(context)
for (resetOption in HabitResetOption.values()) {
val button = createButton(resetOption)
val layoutParams = LayoutParams(0, height)
layoutParams.weight = 1f
if (resetOption != lastResetOption) {
layoutParams.marginEnd = margin
}
button.textAlignment = View.TEXT_ALIGNMENT_GRAVITY
button.gravity = Gravity.CENTER
button.layoutParams = layoutParams
addView(button)
if (resetOption == selectedResetOption) {
selectedButton = button
}
}
}
private fun createButton(resetOption: HabitResetOption): TextView {
val isActive = selectedResetOption == resetOption
val button = TextView(context)
val buttonText = context.getString(resetOption.nameRes)
button.text = buttonText
button.contentDescription = toContentDescription(buttonText, isActive)
button.background = ContextCompat.getDrawable(context, R.drawable.layout_rounded_bg_content)
if (isActive) {
button.background.setTint(tintColor)
button.setTextColor(ContextCompat.getColor(context, R.color.white))
button.typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
} else {
button.background.setTint(ContextCompat.getColor(context, R.color.taskform_gray))
button.setTextColor(ContextCompat.getColor(context, R.color.text_secondary))
button.typeface = Typeface.create("sans-serif", Typeface.NORMAL)
}
button.setOnClickListener {
selectedResetOption = resetOption
}
return button
}
private fun toContentDescription(buttonText: CharSequence, isActive: Boolean): String {
val statusString = if (isActive) {
context.getString(R.string.selected)
} else context.getString(R.string.not_selected)
return "$buttonText, $statusString"
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/tasks/form/HabitResetStreakButtons.kt | 1064237031 |
package org.grandtestauto.indoflash
import android.app.Application
import android.content.Context
import android.util.Log
import org.grandtestauto.indoflash.spec.ApplicationSpec
import org.grandtestauto.indoflash.spec.ChapterSpec
import org.grandtestauto.indoflash.spec.WordListSpec
import org.grandtestauto.indoflash.word.Word
import org.grandtestauto.indoflash.word.WordList
import org.grandtestauto.indoflash.word.readFromStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import javax.xml.parsers.DocumentBuilderFactory
const val FAVOURITES_FILE_NAME = "favourites"
const val LOG_ID = "IndoFlash:IndoFlash"
const val PREFERENCES_NAME = "IndoFlash"
const val INDONESIAN_TO_ENGLISH_PREFERENCES_KEY = "IndonesianToEnglish"
const val CHAPTER_PREFERENCES_KEY = "Chapter"
const val WORD_LIST_PREFERENCES_KEY = "WordList"
/**
* The main application. Holds the state such as the list of words
* currently being studied, whether or not to shuffle the list,
* and so on.
*
* @author Tim Lavers
*/
class IndoFlash : Application() {
lateinit private var wordListSpec: WordListSpec
lateinit private var wordList: WordList
lateinit private var currentChapter: ChapterSpec
lateinit private var applicationSpec: ApplicationSpec
private var showIndonesianFirst = false
private var showingFavourites = false
private var shuffle = false
override fun onCreate() {
super.onCreate()
parseSetupFileToApplicationSpec()
showIndonesianFirst = getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE).getBoolean(INDONESIAN_TO_ENGLISH_PREFERENCES_KEY, false)
setInitialChapterAndWordList()
}
private fun setInitialChapterAndWordList() {
val storedChapter = getSetting(CHAPTER_PREFERENCES_KEY)
currentChapter = applicationSpec.chapterForName(storedChapter) ?: applicationSpec.chapterSpecs[0]
val storedWordList = getSetting(WORD_LIST_PREFERENCES_KEY)
wordListSpec = currentChapter.forName(storedWordList) ?: currentChapter.wordLists()[0]
setWordList(wordListSpec)
}
override fun onTerminate() {
super.onTerminate()
}
fun applicationSpec(): ApplicationSpec = applicationSpec
fun addRemoveFavourite(word: Word) {
//If translation is showing first, the word passed in here is the reverse of its stored version in the data files.
val wordToAddOrRemove = if (showIndonesianFirst()) word else Word(word.definition, word.word)
val words = readFromFavourites()
if (showingFavourites) {
words.remove(wordToAddOrRemove)
} else {
words.add(wordToAddOrRemove)
}
writeToFavourites(words)
}
fun clearFavourites() {
writeToFavourites(WordList(emptyList<Word>()))
}
internal fun storedFavourites(): WordList = readFromFavourites()
internal fun wordList(): WordList = wordList
fun toggleShowIndonesianFirst() {
showIndonesianFirst = !showIndonesianFirst
storeSetting(INDONESIAN_TO_ENGLISH_PREFERENCES_KEY, showIndonesianFirst)
}
private fun storeSetting(key: String, value: Boolean) {
getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE).edit().putBoolean(key, value).apply()
}
private fun storeSetting(key: String, value: String) {
getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE).edit().putString(key, value).apply()
}
private fun getSetting(key: String): String = getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE).getString(key, "")
fun showIndonesianFirst(): Boolean = showIndonesianFirst
fun setWordList(wordListSpec: WordListSpec) {
this.wordListSpec = wordListSpec
val fileName = wordListSpec.fileName
if (fileName.equals(FAVOURITES_FILE_NAME, ignoreCase = true)) {
wordList = readFromFavourites()
showingFavourites = true
} else {
wordList = readWordList(fileName)
showingFavourites = false
}
storeSetting(WORD_LIST_PREFERENCES_KEY, wordListSpec.title)
}
fun setCurrentChapter(chapterSpec: ChapterSpec) {
this.currentChapter = chapterSpec
storeSetting(CHAPTER_PREFERENCES_KEY, chapterSpec.title)
}
fun currentChapter(): ChapterSpec = currentChapter
fun currentWordList(): WordListSpec = wordListSpec
fun chapterSpecs(): List<ChapterSpec> = applicationSpec.chapterSpecs
fun shuffle(): Boolean = shuffle
fun toggleShuffle() {
shuffle = !shuffle
}
fun showingFavourites(): Boolean = showingFavourites
private fun parseSetupFileToApplicationSpec() {
val inputStream = resources.openRawResource(R.raw.setup)
try {
val builder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
val document = builder.parse(inputStream)
applicationSpec = ApplicationSpec(document)
} catch (e: Exception) {
handleError("Error reading setup file", e)
}
}
private fun readWordList(fileName: String): WordList {
val raw = R.raw::class.java
try {
val fileNameIntField = raw.getField(fileName)
val fileNameInt = fileNameIntField.getInt(null)
val inputStream = resources.openRawResource(fileNameInt)
val reader = BufferedReader(InputStreamReader(inputStream, "UTF-8"))
return readFromStream(reader)
} catch (e: Throwable) {
Log.e(LOG_ID, "Problem loading file", e)
return WordList(emptyList<Word>())
}
}
private fun readFromFavourites(): WordList {
try {
val fin = openFileInput(FAVOURITES_FILE_NAME)
val reader = InputStreamReader(fin, "UTF-8")
return readFromStream(reader)
} catch (e: Exception) {
Log.d(LOG_ID, "Problem when reading from favourites.", e)
return WordList(emptyList<Word>())
}
}
private fun writeToFavourites(toStore: WordList) {
try {
val fout = openFileOutput(FAVOURITES_FILE_NAME, Context.MODE_PRIVATE)
toStore.store(OutputStreamWriter(fout!!, "UTF-8"))
} catch (e: Exception) {
Log.d(LOG_ID, "Could not find file $FAVOURITES_FILE_NAME when writing to favourites.", e)
}
}
private fun handleError(msg: String, problem: Exception) {
Log.e(LOG_ID, msg, problem)
}
} | app/src/main/java/org/grandtestauto/indoflash/IndoFlash.kt | 378519640 |
/*
* Copyright (C) 2020 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.xslt.ast.schema
import com.intellij.psi.PsiFile
/**
* An XSLT 3.0 schema type.
*/
interface XsltSchemaType : PsiFile
| src/lang-xslt/main/uk/co/reecedunn/intellij/plugin/xslt/ast/schema/XsltSchemaType.kt | 1517651481 |
/*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.ui.issuelist
import giuliolodi.gitnav.data.DataManager
import giuliolodi.gitnav.ui.base.BasePresenter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import org.eclipse.egit.github.core.Issue
import timber.log.Timber
import javax.inject.Inject
/**
* Created by giulio on 02/09/2017.
*/
class IssueClosedPresenter<V: IssueClosedContract.View> : BasePresenter<V>, IssueClosedContract.Presenter<V> {
private val TAG = "IssueClosedPresenter"
private var mOwner: String? = null
private var mName: String? = null
private var PAGE_N: Int = 1
private var ITEMS_PER_PAGE: Int = 10
private var LOADING: Boolean = false
private var LOADING_LIST: Boolean = false
private var mHashMap: HashMap<String,String> = hashMapOf()
private var mIssueList: MutableList<Issue> = mutableListOf()
private var NO_SHOWING: Boolean = false
@Inject
constructor(mCompositeDisposable: CompositeDisposable, mDataManager: DataManager) : super(mCompositeDisposable, mDataManager)
override fun subscribe(isNetworkAvailable: Boolean, owner: String?, name: String?) {
mOwner = owner
mName = name
mHashMap.put("state", "closed")
if (!mIssueList.isEmpty()) getView().showClosedIssues(mIssueList)
else if (LOADING) getView().showLoading()
else if (NO_SHOWING) getView().showNoClosedIssues()
else {
if (isNetworkAvailable) {
getView().showLoading()
LOADING = true
loadClosedIssues()
}
else {
getView().showNoConnectionError()
getView().hideLoading()
LOADING = false
}
}
}
private fun loadClosedIssues() {
getCompositeDisposable().add(getDataManager().pageIssues(mOwner!!, mName!!, PAGE_N, ITEMS_PER_PAGE, mHashMap)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ openIssueList ->
getView().hideLoading()
getView().hideListLoading()
mIssueList.addAll(openIssueList)
getView().showClosedIssues(openIssueList)
if (PAGE_N == 1 && openIssueList.isEmpty()) {
getView().showNoClosedIssues()
NO_SHOWING = true
}
PAGE_N += 1
LOADING = false
LOADING_LIST = false
},
{ throwable ->
throwable?.localizedMessage?.let { getView().showError(it) }
getView().hideLoading()
getView().hideListLoading()
Timber.e(throwable)
LOADING = false
LOADING_LIST = false
}
))
}
override fun onLastItemVisible(isNetworkAvailable: Boolean, dy: Int) {
if (LOADING_LIST)
return
if (isNetworkAvailable) {
LOADING_LIST = true
getView().showListLoading()
loadClosedIssues()
}
else if (dy > 0) {
getView().showNoConnectionError()
getView().hideLoading()
}
}
override fun onUserClick(username: String) {
getView().intentToUserActivity(username)
}
override fun onIssueClick(issueNumber: Int) {
getView().intentToIssueActivity(issueNumber)
}
} | app/src/main/java/giuliolodi/gitnav/ui/issuelist/IssueClosedPresenter.kt | 3833320636 |
package org.stepik.android.domain.course.analytic.batch
import org.stepik.android.domain.base.analytic.AnalyticEvent
import org.stepik.android.domain.base.analytic.AnalyticSource
import org.stepik.android.domain.course.analytic.CourseViewSource
import java.util.EnumSet
class CourseCardSeenAnalyticBatchEvent(
courseId: Long,
source: CourseViewSource
) : AnalyticEvent {
companion object {
private const val DATA = "data"
private const val PARAM_COURSE = "course"
private const val PARAM_SOURCE = "source"
private const val PARAM_PLATFORM = "platform"
private const val PARAM_POSITION = "position"
private const val PARAM_DATA = "data"
private const val PLATFORM_VALUE = "android"
private const val POSITION_VALUE = 1
}
override val name: String =
"catalog-display"
override val params: Map<String, Any> =
mapOf(
DATA to mapOf(
PARAM_COURSE to courseId,
PARAM_SOURCE to source.name,
PARAM_PLATFORM to PLATFORM_VALUE,
PARAM_POSITION to POSITION_VALUE,
PARAM_DATA to source.params
)
)
override val sources: EnumSet<AnalyticSource> =
EnumSet.of(AnalyticSource.STEPIK_API)
} | app/src/main/java/org/stepik/android/domain/course/analytic/batch/CourseCardSeenAnalyticBatchEvent.kt | 143123428 |
package org.stepik.android.view.injection.course_revenue
import dagger.Binds
import dagger.Module
import dagger.Provides
import org.stepik.android.data.course_revenue.repository.CourseBeneficiariesRepositoryImpl
import org.stepik.android.data.course_revenue.source.CourseBeneficiariesRemoteDataSource
import org.stepik.android.domain.course_revenue.repository.CourseBeneficiariesRepository
import org.stepik.android.remote.course_revenue.CourseBeneficiariesRemoteDataSourceImpl
import org.stepik.android.remote.course_revenue.service.CourseBeneficiariesService
import org.stepik.android.view.injection.base.Authorized
import retrofit2.Retrofit
import retrofit2.create
@Module
abstract class CourseBeneficiariesDataModule {
@Binds
internal abstract fun bindCourseBeneficiariesRepository(
courseBeneficiariesRepositoryImpl: CourseBeneficiariesRepositoryImpl
): CourseBeneficiariesRepository
@Binds
internal abstract fun bindCourseBeneficiariesRemoteDataSource(
courseBeneficiariesRemoteDataSourceImpl: CourseBeneficiariesRemoteDataSourceImpl
): CourseBeneficiariesRemoteDataSource
@Module
companion object {
@Provides
@JvmStatic
internal fun provideCourseBeneficiariesService(@Authorized retrofit: Retrofit): CourseBeneficiariesService =
retrofit.create()
}
} | app/src/main/java/org/stepik/android/view/injection/course_revenue/CourseBeneficiariesDataModule.kt | 1464358840 |
package wangdaye.com.geometricweather.main.fragments
import android.animation.Animator
import android.annotation.SuppressLint
import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.view.ViewGroup
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.graphics.ColorUtils
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import wangdaye.com.geometricweather.R
import wangdaye.com.geometricweather.common.basic.GeoActivity
import wangdaye.com.geometricweather.common.basic.livedata.EqualtableLiveData
import wangdaye.com.geometricweather.common.basic.models.Location
import wangdaye.com.geometricweather.common.ui.widgets.SwipeSwitchLayout
import wangdaye.com.geometricweather.common.ui.widgets.SwipeSwitchLayout.OnSwitchListener
import wangdaye.com.geometricweather.databinding.FragmentHomeBinding
import wangdaye.com.geometricweather.main.MainActivityViewModel
import wangdaye.com.geometricweather.main.adapters.main.MainAdapter
import wangdaye.com.geometricweather.main.layouts.MainLayoutManager
import wangdaye.com.geometricweather.main.utils.MainModuleUtils
import wangdaye.com.geometricweather.main.utils.MainThemeColorProvider
import wangdaye.com.geometricweather.settings.SettingsManager
import wangdaye.com.geometricweather.theme.ThemeManager
import wangdaye.com.geometricweather.theme.resource.ResourcesProviderFactory
import wangdaye.com.geometricweather.theme.resource.providers.ResourceProvider
import wangdaye.com.geometricweather.theme.weatherView.WeatherView
import wangdaye.com.geometricweather.theme.weatherView.WeatherViewController
class HomeFragment : MainModuleFragment() {
private lateinit var binding: FragmentHomeBinding
private lateinit var viewModel: MainActivityViewModel
private lateinit var weatherView: WeatherView
private var adapter: MainAdapter? = null
private var scrollListener: OnScrollListener? = null
private var recyclerViewAnimator: Animator? = null
private var resourceProvider: ResourceProvider? = null
private val previewOffset = EqualtableLiveData(0)
private var callback: Callback? = null
interface Callback {
fun onManageIconClicked()
fun onSettingsIconClicked()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentHomeBinding.inflate(layoutInflater, container, false)
initModel()
// attach weather view.
weatherView = ThemeManager
.getInstance(requireContext())
.weatherThemeDelegate
.getWeatherView(requireContext())
(binding.switchLayout.parent as CoordinatorLayout).addView(
weatherView as View,
0,
CoordinatorLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
)
initView()
setCallback(requireActivity() as Callback)
return binding.root
}
override fun onResume() {
super.onResume()
weatherView.setDrawable(!isHidden)
}
override fun onPause() {
super.onPause()
weatherView.setDrawable(false)
}
override fun onDestroyView() {
super.onDestroyView()
adapter = null
binding.recyclerView.clearOnScrollListeners()
scrollListener = null
}
override fun onHiddenChanged(hidden: Boolean) {
super.onHiddenChanged(hidden)
weatherView.setDrawable(!hidden)
}
override fun setSystemBarStyle() {
ThemeManager
.getInstance(requireContext())
.weatherThemeDelegate
.setSystemBarStyle(
requireContext(),
requireActivity().window,
statusShader = scrollListener?.topOverlap == true,
lightStatus = false,
navigationShader = true,
lightNavigation = false
)
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
updateDayNightColors()
updateViews()
}
// init.
private fun initModel() {
viewModel = ViewModelProvider(requireActivity())[MainActivityViewModel::class.java]
}
@SuppressLint("ClickableViewAccessibility", "NonConstantResourceId", "NotifyDataSetChanged")
private fun initView() {
ensureResourceProvider()
weatherView.setGravitySensorEnabled(
SettingsManager.getInstance(requireContext()).isGravitySensorEnabled
)
binding.toolbar.setNavigationOnClickListener {
if (callback != null) {
callback!!.onManageIconClicked()
}
}
binding.toolbar.inflateMenu(R.menu.activity_main)
binding.toolbar.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.action_manage -> if (callback != null) {
callback!!.onManageIconClicked()
}
R.id.action_settings -> if (callback != null) {
callback!!.onSettingsIconClicked()
}
}
true
}
binding.switchLayout.setOnSwitchListener(switchListener)
binding.switchLayout.reset()
binding.indicator.setSwitchView(binding.switchLayout)
binding.indicator.setCurrentIndicatorColor(Color.WHITE)
binding.indicator.setIndicatorColor(
ColorUtils.setAlphaComponent(Color.WHITE, (0.5 * 255).toInt())
)
binding.refreshLayout.setOnRefreshListener {
viewModel.updateWithUpdatingChecking(
triggeredByUser = true,
checkPermissions = true
)
}
val listAnimationEnabled = SettingsManager
.getInstance(requireContext())
.isListAnimationEnabled
val itemAnimationEnabled = SettingsManager
.getInstance(requireContext())
.isItemAnimationEnabled
adapter = MainAdapter(
(requireActivity() as GeoActivity),
binding.recyclerView,
weatherView,
null,
resourceProvider!!,
listAnimationEnabled,
itemAnimationEnabled
)
binding.recyclerView.adapter = adapter
binding.recyclerView.layoutManager = MainLayoutManager()
binding.recyclerView.addOnScrollListener(OnScrollListener().also { scrollListener = it })
binding.recyclerView.setOnTouchListener(indicatorStateListener)
viewModel.currentLocation.observe(viewLifecycleOwner) {
updateViews(it.location)
}
viewModel.loading.observe(viewLifecycleOwner) { setRefreshing(it) }
viewModel.indicator.observe(viewLifecycleOwner) {
binding.switchLayout.isEnabled = it.total > 1
if (binding.switchLayout.totalCount != it.total
|| binding.switchLayout.position != it.index) {
binding.switchLayout.setData(it.index, it.total)
binding.indicator.setSwitchView(binding.switchLayout)
}
binding.indicator.visibility = if (it.total > 1) View.VISIBLE else View.GONE
}
previewOffset.observe(viewLifecycleOwner) {
binding.root.post {
if (isFragmentViewCreated) {
updatePreviewSubviews()
}
}
}
}
private fun updateDayNightColors() {
binding.refreshLayout.setProgressBackgroundColorSchemeColor(
MainThemeColorProvider.getColor(
location = viewModel.currentLocation.value!!.location,
id = R.attr.colorSurface
)
)
}
// control.
@JvmOverloads
fun updateViews(location: Location = viewModel.currentLocation.value!!.location) {
ensureResourceProvider()
updateContentViews(location = location)
binding.root.post {
if (isFragmentViewCreated) {
updatePreviewSubviews()
}
}
}
@SuppressLint("ClickableViewAccessibility", "NotifyDataSetChanged")
private fun updateContentViews(location: Location) {
if (recyclerViewAnimator != null) {
recyclerViewAnimator!!.cancel()
recyclerViewAnimator = null
}
updateDayNightColors()
binding.switchLayout.reset()
if (location.weather == null) {
adapter!!.setNullWeather()
adapter!!.notifyDataSetChanged()
binding.recyclerView.setOnTouchListener { _, event ->
if (event.action == MotionEvent.ACTION_DOWN
&& !binding.refreshLayout.isRefreshing) {
viewModel.updateWithUpdatingChecking(
triggeredByUser = true,
checkPermissions = true
)
}
false
}
return
}
binding.recyclerView.setOnTouchListener(null)
val listAnimationEnabled = SettingsManager
.getInstance(requireContext())
.isListAnimationEnabled
val itemAnimationEnabled = SettingsManager
.getInstance(requireContext())
.isItemAnimationEnabled
adapter!!.update(
(requireActivity() as GeoActivity),
binding.recyclerView,
weatherView,
location,
resourceProvider!!,
listAnimationEnabled,
itemAnimationEnabled
)
adapter!!.notifyDataSetChanged()
scrollListener!!.postReset(binding.recyclerView)
if (!listAnimationEnabled) {
binding.recyclerView.alpha = 0f
recyclerViewAnimator = MainModuleUtils.getEnterAnimator(
binding.recyclerView,
0
)
recyclerViewAnimator!!.startDelay = 150
recyclerViewAnimator!!.start()
}
}
private fun ensureResourceProvider() {
val iconProvider = SettingsManager
.getInstance(requireContext())
.iconProvider
if (resourceProvider == null
|| resourceProvider!!.packageName != iconProvider) {
resourceProvider = ResourcesProviderFactory.getNewInstance()
}
}
private fun updatePreviewSubviews() {
val location = viewModel.getValidLocation(
previewOffset.value!!
)
val daylight = location.isDaylight
binding.toolbar.title = location.getCityName(requireContext())
WeatherViewController.setWeatherCode(
weatherView,
location.weather,
daylight,
resourceProvider!!
)
binding.refreshLayout.setColorSchemeColors(
ThemeManager
.getInstance(requireContext())
.weatherThemeDelegate
.getThemeColors(
requireContext(),
WeatherViewController.getWeatherKind(location.weather),
daylight
)[0]
)
}
private fun setRefreshing(b: Boolean) {
binding.refreshLayout.post {
if (isFragmentViewCreated) {
binding.refreshLayout.isRefreshing = b
}
}
}
// interface.
private fun setCallback(callback: Callback?) {
this.callback = callback
}
// on touch listener.
@SuppressLint("ClickableViewAccessibility")
private val indicatorStateListener = OnTouchListener { _, event ->
when (event.action) {
MotionEvent.ACTION_MOVE ->
binding.indicator.setDisplayState(true)
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL ->
binding.indicator.setDisplayState(false)
}
false
}
// on swipe listener (swipe switch layout).
private val switchListener: OnSwitchListener = object : OnSwitchListener {
override fun onSwiped(swipeDirection: Int, progress: Float) {
binding.indicator.setDisplayState(progress != 0f)
if (progress >= 1) {
previewOffset.setValue(
if (swipeDirection == SwipeSwitchLayout.SWIPE_DIRECTION_LEFT) 1 else -1
)
} else {
previewOffset.setValue(0)
}
}
override fun onSwitched(swipeDirection: Int) {
binding.indicator.setDisplayState(false)
viewModel.offsetLocation(
if (swipeDirection == SwipeSwitchLayout.SWIPE_DIRECTION_LEFT) 1 else -1
)
previewOffset.setValue(0)
}
}
// on scroll changed listener.
private inner class OnScrollListener : RecyclerView.OnScrollListener() {
private var mTopChanged: Boolean? = null
var topOverlap = false
private var mFirstCardMarginTop = 0
private var mScrollY = 0
private var mLastAppBarTranslationY = 0f
fun postReset(recyclerView: RecyclerView) {
recyclerView.post {
if (!isFragmentViewCreated) {
return@post
}
mTopChanged = null
topOverlap = false
mFirstCardMarginTop = 0
mScrollY = 0
mLastAppBarTranslationY = 0f
onScrolled(recyclerView, 0, 0)
}
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
mFirstCardMarginTop = if (recyclerView.childCount > 0) {
recyclerView.getChildAt(0).measuredHeight
} else {
-1
}
mScrollY = recyclerView.computeVerticalScrollOffset()
mLastAppBarTranslationY = binding.appBar.translationY
weatherView.onScroll(mScrollY)
if (adapter != null) {
adapter!!.onScroll()
}
// set translation y of toolbar.
if (adapter != null && mFirstCardMarginTop > 0) {
if (mFirstCardMarginTop >= binding.appBar.measuredHeight
+ adapter!!.currentTemperatureTextHeight) {
when {
mScrollY < (mFirstCardMarginTop
- binding.appBar.measuredHeight
- adapter!!.currentTemperatureTextHeight) -> {
binding.appBar.translationY = 0f
}
mScrollY > mFirstCardMarginTop - binding.appBar.y -> {
binding.appBar.translationY = -binding.appBar.measuredHeight.toFloat()
}
else -> {
binding.appBar.translationY = (
mFirstCardMarginTop
- adapter!!.currentTemperatureTextHeight
- mScrollY
- binding.appBar.measuredHeight
).toFloat()
}
}
} else {
binding.appBar.translationY = -mScrollY.toFloat()
}
}
// set system bar style.
if (mFirstCardMarginTop <= 0) {
mTopChanged = true
topOverlap = false
} else {
mTopChanged = (binding.appBar.translationY != 0f) != (mLastAppBarTranslationY != 0f)
topOverlap = binding.appBar.translationY != 0f
}
if (mTopChanged!!) {
checkToSetSystemBarStyle()
}
}
}
} | app/src/main/java/wangdaye/com/geometricweather/main/fragments/HomeFragment.kt | 3713164026 |
package org.walleth.util
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import org.walleth.base_activities.BaseSubActivity
fun BaseSubActivity.showInputAlert(@StringRes title: Int, action : (input: String) -> Unit) {
val editText = EditText(this)
val container = FrameLayout(this)
val params = LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
params.setMargins(16.toDp(), 0, 16.toDp(), 0)
editText.layoutParams = params
editText.isSingleLine = true
container.addView(editText)
AlertDialog.Builder(this)
.setTitle(title)
.setView(container)
.setPositiveButton(android.R.string.ok) { dialog, _ ->
dialog.cancel()
action(editText.text.toString())
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
| app/src/main/java/org/walleth/util/InputDialog.kt | 1052055230 |
/*
* Copyright (C) 2017 José Roberto de Araújo Júnior
*
* 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.platestack.api.server.internal
import com.github.salomonbrys.kotson.jsonObject
import com.github.salomonbrys.kotson.set
import com.google.gson.JsonObject
import mu.KLogger
import mu.KotlinLogging
import org.platestack.api.message.Text
import org.platestack.api.minecraft.item.ItemStack
import org.platestack.api.plugin.PlatePlugin
interface InternalAccessor {
fun createShowItemJSON(stack: ItemStack): JsonObject {
val json = jsonObject("id" to stack.item.minecraftNamedId)
if(stack.metadata != 0.toShort()) {
json["Damage"] = stack.metadata
}
val data = stack.data
if(data.isNotEmpty()) {
json["tag"] = data.toJson()
}
return json
}
fun createLogger(plugin: PlatePlugin): KLogger = KotlinLogging.logger(plugin.javaClass.name)
@Deprecated("Will be renamed soon™")
fun toJson(text: Text): JsonObject
}
| src/main/kotlin/org/platestack/api/server/internal/InternalAccessor.kt | 3230906103 |
package com.commit451.gitlab.event
/**
* Reload all the issues!
*/
class IssueReloadEvent
| app/src/main/java/com/commit451/gitlab/event/IssueReloadEvent.kt | 2050293700 |
package com.github.k0kubun.gitstar_ranking.db
import com.github.k0kubun.gitstar_ranking.client.UserResponse
import com.github.k0kubun.gitstar_ranking.core.StarsCursor
import com.github.k0kubun.gitstar_ranking.core.User
import java.sql.Timestamp
import org.jooq.DSLContext
import org.jooq.Record
import org.jooq.RecordMapper
import org.jooq.impl.DSL.field
import org.jooq.impl.DSL.now
import org.jooq.impl.DSL.table
class UserQuery(private val database: DSLContext) {
private val userColumns = listOf(
field("id"),
field("type"),
field("login"),
field("stargazers_count"),
field("updated_at", Timestamp::class.java),
)
private val userMapper = RecordMapper<Record, User> { record ->
User(
id = record.get("id", Long::class.java),
type = record.get("type", String::class.java),
login = record.get("login", String::class.java),
stargazersCount = record.get("stargazers_count", Long::class.java),
updatedAt = record.get("updated_at", Timestamp::class.java),
)
}
fun find(id: Long): User? {
return database
.select(userColumns)
.from("users")
.where(field("id").eq(id))
.fetchOne(userMapper)
}
fun findBy(login: String): User? {
return database
.select(userColumns)
.from("users")
.where(field("login").eq(login))
.fetchOne(userMapper)
}
fun create(user: UserResponse) {
database
.insertInto(table("users"))
.columns(
field("id"),
field("type"),
field("login"),
field("avatar_url"),
field("created_at"),
field("updated_at"),
)
.values(
user.id,
user.type,
user.login,
user.avatarUrl,
now(), // created_at
now(), // updated_at
)
.execute()
}
fun update(id: Long, login: String? = null, stargazersCount: Long? = null) {
database
.update(table("users"))
.set(field("updated_at"), now())
.run {
if (login != null) {
set(field("login"), login)
} else this
}
.run {
if (stargazersCount != null) {
set(field("stargazers_count"), stargazersCount)
} else this
}
.where(field("id").eq(id))
.execute()
}
fun destroy(id: Long) {
database
.delete(table("users"))
.where(field("id").eq(id))
.execute()
}
fun count(stargazersCount: Long? = null): Long {
return database
.selectCount()
.from("users")
.where(field("type").eq("User"))
.run {
if (stargazersCount != null) {
and("stargazers_count = ?", stargazersCount)
} else this
}
.fetchOne(0, Long::class.java)!!
}
fun max(column: String): Long? {
return database
.select(field(column))
.from("users")
.orderBy(field(column).desc())
.limit(1)
.fetchOne(column, Long::class.java)
}
fun findStargazersCount(stargazersCountLessThan: Long): Long? {
return database
.select(field("stargazers_count"))
.from("users")
.where(field("stargazers_count").lessThan(stargazersCountLessThan))
.orderBy(field("stargazers_count").desc())
.limit(1)
.fetchOne("stargazers_count", Long::class.java)
}
fun orderByIdAsc(stargazersCount: Long, idAfter: Long, limit: Int): List<User> {
return database
.select(userColumns)
.from("users")
.where(field("stargazers_count").eq(stargazersCount))
.and(field("id").greaterThan(idAfter))
.orderBy(field("id").asc())
.limit(limit)
.fetch(userMapper)
}
fun orderByStarsDesc(limit: Int, after: StarsCursor? = null): List<User> {
return database
.select(userColumns)
.from("users")
.where(field("type").eq("User"))
.run {
if (after != null) {
and("(stargazers_count, id) < (?, ?)", after.stars, after.id)
} else this
}
.orderBy(field("stargazers_count").desc(), field("id").desc())
.limit(limit)
.fetch(userMapper)
}
}
| worker/src/main/kotlin/com/github/k0kubun/gitstar_ranking/db/UserQuery.kt | 2492333881 |
package eu.kanade.presentation.more.settings.widget
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import eu.kanade.presentation.more.settings.LocalPreferenceHighlighted
@Composable
fun TrackingPreferenceWidget(
modifier: Modifier = Modifier,
title: String,
@DrawableRes logoRes: Int,
@ColorInt logoColor: Int,
checked: Boolean,
onClick: (() -> Unit)? = null,
) {
val highlighted = LocalPreferenceHighlighted.current
Box(modifier = Modifier.highlightBackground(highlighted)) {
Row(
modifier = modifier
.clickable(enabled = onClick != null, onClick = { onClick?.invoke() })
.fillMaxWidth()
.padding(horizontal = PrefsHorizontalPadding, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Box(
modifier = Modifier
.size(48.dp)
.background(color = Color(logoColor), shape = RoundedCornerShape(8.dp))
.padding(4.dp),
contentAlignment = Alignment.Center,
) {
Image(
painter = painterResource(id = logoRes),
contentDescription = null,
)
}
Text(
text = title,
modifier = Modifier
.weight(1f)
.padding(horizontal = 16.dp),
maxLines = 1,
style = MaterialTheme.typography.titleLarge,
fontSize = TitleFontSize,
)
if (checked) {
Icon(
imageVector = Icons.Default.Check,
modifier = Modifier
.padding(4.dp)
.size(32.dp),
tint = Color(0xFF4CAF50),
contentDescription = null,
)
}
}
}
}
| app/src/main/java/eu/kanade/presentation/more/settings/widget/TrackingPreferenceWidget.kt | 3986811771 |
package eu.kanade.tachiyomi.data.notification
import android.content.Context
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.NotificationManagerCompat.IMPORTANCE_DEFAULT
import androidx.core.app.NotificationManagerCompat.IMPORTANCE_HIGH
import androidx.core.app.NotificationManagerCompat.IMPORTANCE_LOW
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.util.system.buildNotificationChannel
import eu.kanade.tachiyomi.util.system.buildNotificationChannelGroup
/**
* Class to manage the basic information of all the notifications used in the app.
*/
object Notifications {
/**
* Common notification channel and ids used anywhere.
*/
const val CHANNEL_COMMON = "common_channel"
const val ID_DOWNLOAD_IMAGE = 2
/**
* Notification channel and ids used by the library updater.
*/
private const val GROUP_LIBRARY = "group_library"
const val CHANNEL_LIBRARY_PROGRESS = "library_progress_channel"
const val ID_LIBRARY_PROGRESS = -101
const val ID_LIBRARY_SIZE_WARNING = -103
const val CHANNEL_LIBRARY_ERROR = "library_errors_channel"
const val ID_LIBRARY_ERROR = -102
const val CHANNEL_LIBRARY_SKIPPED = "library_skipped_channel"
const val ID_LIBRARY_SKIPPED = -104
/**
* Notification channel and ids used by the downloader.
*/
private const val GROUP_DOWNLOADER = "group_downloader"
const val CHANNEL_DOWNLOADER_PROGRESS = "downloader_progress_channel"
const val ID_DOWNLOAD_CHAPTER_PROGRESS = -201
const val CHANNEL_DOWNLOADER_COMPLETE = "downloader_complete_channel"
const val ID_DOWNLOAD_CHAPTER_COMPLETE = -203
const val CHANNEL_DOWNLOADER_ERROR = "downloader_error_channel"
const val ID_DOWNLOAD_CHAPTER_ERROR = -202
/**
* Notification channel and ids used by the library updater.
*/
const val CHANNEL_NEW_CHAPTERS = "new_chapters_channel"
const val ID_NEW_CHAPTERS = -301
const val GROUP_NEW_CHAPTERS = "eu.kanade.tachiyomi.NEW_CHAPTERS"
/**
* Notification channel and ids used by the backup/restore system.
*/
private const val GROUP_BACKUP_RESTORE = "group_backup_restore"
const val CHANNEL_BACKUP_RESTORE_PROGRESS = "backup_restore_progress_channel"
const val ID_BACKUP_PROGRESS = -501
const val ID_RESTORE_PROGRESS = -503
const val CHANNEL_BACKUP_RESTORE_COMPLETE = "backup_restore_complete_channel_v2"
const val ID_BACKUP_COMPLETE = -502
const val ID_RESTORE_COMPLETE = -504
/**
* Notification channel used for crash log file sharing.
*/
const val CHANNEL_CRASH_LOGS = "crash_logs_channel"
const val ID_CRASH_LOGS = -601
/**
* Notification channel used for Incognito Mode
*/
const val CHANNEL_INCOGNITO_MODE = "incognito_mode_channel"
const val ID_INCOGNITO_MODE = -701
/**
* Notification channel and ids used for app and extension updates.
*/
private const val GROUP_APK_UPDATES = "group_apk_updates"
const val CHANNEL_APP_UPDATE = "app_apk_update_channel"
const val ID_APP_UPDATER = 1
const val ID_APP_UPDATE_PROMPT = 2
const val CHANNEL_EXTENSIONS_UPDATE = "ext_apk_update_channel"
const val ID_UPDATES_TO_EXTS = -401
const val ID_EXTENSION_INSTALLER = -402
private val deprecatedChannels = listOf(
"downloader_channel",
"backup_restore_complete_channel",
"library_channel",
"library_progress_channel",
"updates_ext_channel",
)
/**
* Creates the notification channels introduced in Android Oreo.
* This won't do anything on Android versions that don't support notification channels.
*
* @param context The application context.
*/
fun createChannels(context: Context) {
val notificationService = NotificationManagerCompat.from(context)
// Delete old notification channels
deprecatedChannels.forEach(notificationService::deleteNotificationChannel)
notificationService.createNotificationChannelGroupsCompat(
listOf(
buildNotificationChannelGroup(GROUP_BACKUP_RESTORE) {
setName(context.getString(R.string.label_backup))
},
buildNotificationChannelGroup(GROUP_DOWNLOADER) {
setName(context.getString(R.string.download_notifier_downloader_title))
},
buildNotificationChannelGroup(GROUP_LIBRARY) {
setName(context.getString(R.string.label_library))
},
buildNotificationChannelGroup(GROUP_APK_UPDATES) {
setName(context.getString(R.string.label_recent_updates))
},
),
)
notificationService.createNotificationChannelsCompat(
listOf(
buildNotificationChannel(CHANNEL_COMMON, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_common))
},
buildNotificationChannel(CHANNEL_LIBRARY_PROGRESS, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_progress))
setGroup(GROUP_LIBRARY)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_LIBRARY_ERROR, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_errors))
setGroup(GROUP_LIBRARY)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_LIBRARY_SKIPPED, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_skipped))
setGroup(GROUP_LIBRARY)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_NEW_CHAPTERS, IMPORTANCE_DEFAULT) {
setName(context.getString(R.string.channel_new_chapters))
},
buildNotificationChannel(CHANNEL_DOWNLOADER_PROGRESS, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_progress))
setGroup(GROUP_DOWNLOADER)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_DOWNLOADER_COMPLETE, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_complete))
setGroup(GROUP_DOWNLOADER)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_DOWNLOADER_ERROR, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_errors))
setGroup(GROUP_DOWNLOADER)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_BACKUP_RESTORE_PROGRESS, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_progress))
setGroup(GROUP_BACKUP_RESTORE)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_BACKUP_RESTORE_COMPLETE, IMPORTANCE_HIGH) {
setName(context.getString(R.string.channel_complete))
setGroup(GROUP_BACKUP_RESTORE)
setShowBadge(false)
setSound(null, null)
},
buildNotificationChannel(CHANNEL_CRASH_LOGS, IMPORTANCE_HIGH) {
setName(context.getString(R.string.channel_crash_logs))
},
buildNotificationChannel(CHANNEL_INCOGNITO_MODE, IMPORTANCE_LOW) {
setName(context.getString(R.string.pref_incognito_mode))
},
buildNotificationChannel(CHANNEL_APP_UPDATE, IMPORTANCE_DEFAULT) {
setGroup(GROUP_APK_UPDATES)
setName(context.getString(R.string.channel_app_updates))
},
buildNotificationChannel(CHANNEL_EXTENSIONS_UPDATE, IMPORTANCE_DEFAULT) {
setGroup(GROUP_APK_UPDATES)
setName(context.getString(R.string.channel_ext_updates))
},
),
)
}
}
| app/src/main/java/eu/kanade/tachiyomi/data/notification/Notifications.kt | 612400893 |
package net.sf.freecol.common.model.specification
import com.badlogic.gdx.utils.ObjectIntMap
typealias GoodsTypeId = String
| core/src/net/sf/freecol/common/model/specification/GoodsType.kt | 3189478960 |
package eu.kanade.tachiyomi.data.updater
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.os.PowerManager
import androidx.core.content.ContextCompat
import eu.kanade.tachiyomi.BuildConfig
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.notification.Notifications
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.NetworkHelper
import eu.kanade.tachiyomi.network.ProgressListener
import eu.kanade.tachiyomi.network.await
import eu.kanade.tachiyomi.network.newCachelessCallWithProgress
import eu.kanade.tachiyomi.util.lang.launchIO
import eu.kanade.tachiyomi.util.storage.getUriCompat
import eu.kanade.tachiyomi.util.storage.saveTo
import eu.kanade.tachiyomi.util.system.acquireWakeLock
import eu.kanade.tachiyomi.util.system.isServiceRunning
import eu.kanade.tachiyomi.util.system.logcat
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import logcat.LogPriority
import okhttp3.Call
import okhttp3.internal.http2.ErrorCode
import okhttp3.internal.http2.StreamResetException
import uy.kohesive.injekt.injectLazy
import java.io.File
class AppUpdateService : Service() {
private val network: NetworkHelper by injectLazy()
/**
* Wake lock that will be held until the service is destroyed.
*/
private lateinit var wakeLock: PowerManager.WakeLock
private lateinit var notifier: AppUpdateNotifier
private var runningJob: Job? = null
private var runningCall: Call? = null
override fun onCreate() {
super.onCreate()
notifier = AppUpdateNotifier(this)
wakeLock = acquireWakeLock(javaClass.name)
startForeground(Notifications.ID_APP_UPDATER, notifier.onDownloadStarted().build())
}
/**
* This method needs to be implemented, but it's not used/needed.
*/
override fun onBind(intent: Intent): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent == null) return START_NOT_STICKY
val url = intent.getStringExtra(EXTRA_DOWNLOAD_URL) ?: return START_NOT_STICKY
val title = intent.getStringExtra(EXTRA_DOWNLOAD_TITLE) ?: getString(R.string.app_name)
runningJob = launchIO {
downloadApk(title, url)
}
runningJob?.invokeOnCompletion { stopSelf(startId) }
return START_NOT_STICKY
}
override fun stopService(name: Intent?): Boolean {
destroyJob()
return super.stopService(name)
}
override fun onDestroy() {
destroyJob()
super.onDestroy()
}
private fun destroyJob() {
runningJob?.cancel()
runningCall?.cancel()
if (wakeLock.isHeld) {
wakeLock.release()
}
}
/**
* Called to start downloading apk of new update
*
* @param url url location of file
*/
private suspend fun downloadApk(title: String, url: String) {
// Show notification download starting.
notifier.onDownloadStarted(title)
val progressListener = object : ProgressListener {
// Progress of the download
var savedProgress = 0
// Keep track of the last notification sent to avoid posting too many.
var lastTick = 0L
override fun update(bytesRead: Long, contentLength: Long, done: Boolean) {
val progress = (100 * (bytesRead.toFloat() / contentLength)).toInt()
val currentTime = System.currentTimeMillis()
if (progress > savedProgress && currentTime - 200 > lastTick) {
savedProgress = progress
lastTick = currentTime
notifier.onProgressChange(progress)
}
}
}
try {
// Download the new update.
val call = network.client.newCachelessCallWithProgress(GET(url), progressListener)
runningCall = call
val response = call.await()
// File where the apk will be saved.
val apkFile = File(externalCacheDir, "update.apk")
if (response.isSuccessful) {
response.body.source().saveTo(apkFile)
} else {
response.close()
throw Exception("Unsuccessful response")
}
notifier.promptInstall(apkFile.getUriCompat(this))
} catch (e: Exception) {
logcat(LogPriority.ERROR, e)
if (e is CancellationException ||
(e is StreamResetException && e.errorCode == ErrorCode.CANCEL)
) {
notifier.cancel()
} else {
notifier.onDownloadError(url)
}
}
}
companion object {
internal const val EXTRA_DOWNLOAD_URL = "${BuildConfig.APPLICATION_ID}.UpdaterService.DOWNLOAD_URL"
internal const val EXTRA_DOWNLOAD_TITLE = "${BuildConfig.APPLICATION_ID}.UpdaterService.DOWNLOAD_TITLE"
/**
* Returns the status of the service.
*
* @param context the application context.
* @return true if the service is running, false otherwise.
*/
private fun isRunning(context: Context): Boolean =
context.isServiceRunning(AppUpdateService::class.java)
/**
* Downloads a new update and let the user install the new version from a notification.
*
* @param context the application context.
* @param url the url to the new update.
*/
fun start(context: Context, url: String, title: String? = context.getString(R.string.app_name)) {
if (!isRunning(context)) {
val intent = Intent(context, AppUpdateService::class.java).apply {
putExtra(EXTRA_DOWNLOAD_TITLE, title)
putExtra(EXTRA_DOWNLOAD_URL, url)
}
ContextCompat.startForegroundService(context, intent)
}
}
/**
* Stops the service.
*
* @param context the application context
*/
fun stop(context: Context) {
context.stopService(Intent(context, AppUpdateService::class.java))
}
/**
* Returns [PendingIntent] that starts a service which downloads the apk specified in url.
*
* @param url the url to the new update.
* @return [PendingIntent]
*/
internal fun downloadApkPendingService(context: Context, url: String): PendingIntent {
val intent = Intent(context, AppUpdateService::class.java).apply {
putExtra(EXTRA_DOWNLOAD_URL, url)
}
return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}
}
}
| app/src/main/java/eu/kanade/tachiyomi/data/updater/AppUpdateService.kt | 964824027 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.recorder.actions
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.diagnostic.Logger
import com.intellij.testGuiFramework.recorder.GuiRecorderManager
import com.intellij.testGuiFramework.recorder.compile.KotlinCompileUtil
import com.intellij.testGuiFramework.recorder.ui.Notifier
/**
* @author Sergey Karashevich
*/
class PerformScriptAction : AnAction(null, "Run GUI Script", AllIcons.Actions.Execute) {
companion object {
val LOG = Logger.getInstance(PerformScriptAction::class.java)
}
override fun actionPerformed(p0: AnActionEvent?) {
LOG.info("Compile and evaluate current script buffer")
Notifier.updateStatus("${Notifier.LONG_OPERATION_PREFIX}Compiling and performing current script")
val editor = GuiRecorderManager.getEditor()
KotlinCompileUtil.compileAndRun(editor.document.text)
}
}
| platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/actions/PerformScriptAction.kt | 787560464 |
package eu.kanade.tachiyomi.data.download
import android.content.Context
import androidx.core.content.edit
import eu.kanade.domain.manga.model.Manga
import eu.kanade.tachiyomi.data.database.models.Chapter
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import uy.kohesive.injekt.injectLazy
/**
* Class used to keep a list of chapters for future deletion.
*
* @param context the application context.
*/
class DownloadPendingDeleter(context: Context) {
private val json: Json by injectLazy()
/**
* Preferences used to store the list of chapters to delete.
*/
private val preferences = context.getSharedPreferences("chapters_to_delete", Context.MODE_PRIVATE)
/**
* Last added chapter, used to avoid decoding from the preference too often.
*/
private var lastAddedEntry: Entry? = null
/**
* Adds a list of chapters for future deletion.
*
* @param chapters the chapters to be deleted.
* @param manga the manga of the chapters.
*/
@Synchronized
fun addChapters(chapters: List<Chapter>, manga: Manga) {
val lastEntry = lastAddedEntry
val newEntry = if (lastEntry != null && lastEntry.manga.id == manga.id) {
// Append new chapters
val newChapters = lastEntry.chapters.addUniqueById(chapters)
// If no chapters were added, do nothing
if (newChapters.size == lastEntry.chapters.size) return
// Last entry matches the manga, reuse it to avoid decoding json from preferences
lastEntry.copy(chapters = newChapters)
} else {
val existingEntry = preferences.getString(manga.id.toString(), null)
if (existingEntry != null) {
// Existing entry found on preferences, decode json and add the new chapter
val savedEntry = json.decodeFromString<Entry>(existingEntry)
// Append new chapters
val newChapters = savedEntry.chapters.addUniqueById(chapters)
// If no chapters were added, do nothing
if (newChapters.size == savedEntry.chapters.size) return
savedEntry.copy(chapters = newChapters)
} else {
// No entry has been found yet, create a new one
Entry(chapters.map { it.toEntry() }, manga.toEntry())
}
}
// Save current state
val json = json.encodeToString(newEntry)
preferences.edit {
putString(newEntry.manga.id.toString(), json)
}
lastAddedEntry = newEntry
}
/**
* Returns the list of chapters to be deleted grouped by its manga.
*
* Note: the returned list of manga and chapters only contain basic information needed by the
* downloader, so don't use them for anything else.
*/
@Synchronized
fun getPendingChapters(): Map<Manga, List<Chapter>> {
val entries = decodeAll()
preferences.edit {
clear()
}
lastAddedEntry = null
return entries.associate { (chapters, manga) ->
manga.toModel() to chapters.map { it.toModel() }
}
}
/**
* Decodes all the chapters from preferences.
*/
private fun decodeAll(): List<Entry> {
return preferences.all.values.mapNotNull { rawEntry ->
try {
(rawEntry as? String)?.let { json.decodeFromString<Entry>(it) }
} catch (e: Exception) {
null
}
}
}
/**
* Returns a copy of chapter entries ensuring no duplicates by chapter id.
*/
private fun List<ChapterEntry>.addUniqueById(chapters: List<Chapter>): List<ChapterEntry> {
val newList = toMutableList()
for (chapter in chapters) {
if (none { it.id == chapter.id }) {
newList.add(chapter.toEntry())
}
}
return newList
}
/**
* Class used to save an entry of chapters with their manga into preferences.
*/
@Serializable
private data class Entry(
val chapters: List<ChapterEntry>,
val manga: MangaEntry,
)
/**
* Class used to save an entry for a chapter into preferences.
*/
@Serializable
private data class ChapterEntry(
val id: Long,
val url: String,
val name: String,
val scanlator: String? = null,
)
/**
* Class used to save an entry for a manga into preferences.
*/
@Serializable
private data class MangaEntry(
val id: Long,
val url: String,
val title: String,
val source: Long,
)
/**
* Returns a manga entry from a manga model.
*/
private fun Manga.toEntry(): MangaEntry {
return MangaEntry(id, url, title, source)
}
/**
* Returns a chapter entry from a chapter model.
*/
private fun Chapter.toEntry(): ChapterEntry {
return ChapterEntry(id!!, url, name, scanlator)
}
/**
* Returns a manga model from a manga entry.
*/
private fun MangaEntry.toModel(): Manga {
return Manga.create().copy(
url = url,
title = title,
source = source,
id = id,
)
}
/**
* Returns a chapter model from a chapter entry.
*/
private fun ChapterEntry.toModel(): Chapter {
return Chapter.create().also {
it.id = id
it.url = url
it.name = name
it.scanlator = scanlator
}
}
}
| app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadPendingDeleter.kt | 951290287 |
package info.nightscout.androidaps.database.daos
import androidx.room.Insert
import androidx.room.Update
import info.nightscout.androidaps.database.daos.workaround.TraceableDaoWorkaround
import info.nightscout.androidaps.database.interfaces.TraceableDBEntry
internal interface TraceableDao<T : TraceableDBEntry> : TraceableDaoWorkaround<T> {
fun findById(id: Long): T?
fun deleteAllEntries()
//fun getAllStartingFrom(id: Long): Single<List<T>>
@Insert
fun insert(entry: T): Long
@Update
fun update(entry: T)
}
/**
* Inserts a new entry
* @return The ID of the newly generated entry
*/
//@Transaction
internal fun <T : TraceableDBEntry> TraceableDao<T>.insertNewEntryImpl(entry: T): Long {
if (entry.id != 0L) throw IllegalArgumentException("ID must be 0.")
if (entry.version != 0) throw IllegalArgumentException("Version must be 0.")
if (entry.referenceId != null) throw IllegalArgumentException("Reference ID must be null.")
if (!entry.foreignKeysValid) throw IllegalArgumentException("One or more foreign keys are invalid (e.g. 0 value).")
val lastModified = System.currentTimeMillis()
entry.dateCreated = lastModified
val id = insert(entry)
entry.id = id
return id
}
/**
* Updates an existing entry
* @return The ID of the newly generated HISTORIC entry
*/
//@Transaction
internal fun <T : TraceableDBEntry> TraceableDao<T>.updateExistingEntryImpl(entry: T): Long {
if (entry.id == 0L) throw IllegalArgumentException("ID must not be 0.")
if (entry.referenceId != null) throw IllegalArgumentException("Reference ID must be null.")
if (!entry.foreignKeysValid) throw IllegalArgumentException("One or more foreign keys are invalid (e.g. 0 value).")
val lastModified = System.currentTimeMillis()
entry.dateCreated = lastModified
val current = findById(entry.id)
?: throw IllegalArgumentException("The entry with the specified ID does not exist.")
if (current.referenceId != null) throw IllegalArgumentException("The entry with the specified ID is historic and cannot be updated.")
entry.version = current.version + 1
update(entry)
current.referenceId = entry.id
current.id = 0
return insert(current)
} | database/src/main/java/info/nightscout/androidaps/database/daos/TraceableDao.kt | 2674670869 |
/**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.materialdialogs.internal.main
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.View.MeasureSpec.AT_MOST
import android.view.View.MeasureSpec.EXACTLY
import android.view.View.MeasureSpec.UNSPECIFIED
import android.view.View.MeasureSpec.getSize
import android.view.View.MeasureSpec.makeMeasureSpec
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.RestrictTo
import androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP
import com.afollestad.materialdialogs.R
import com.afollestad.materialdialogs.utils.MDUtil.additionalPaddingForFont
import com.afollestad.materialdialogs.utils.MDUtil.dimenPx
import com.afollestad.materialdialogs.utils.isNotVisible
import com.afollestad.materialdialogs.utils.isRtl
import com.afollestad.materialdialogs.utils.isVisible
/**
* Manages the header frame of the dialog, including the optional icon and title.
*
* @author Aidan Follestad (afollestad)
*/
@RestrictTo(LIBRARY_GROUP)
class DialogTitleLayout(
context: Context,
attrs: AttributeSet? = null
) : BaseSubLayout(context, attrs) {
private val frameMarginVertical = dimenPx(R.dimen.md_dialog_frame_margin_vertical)
private val titleMarginBottom = dimenPx(R.dimen.md_dialog_title_layout_margin_bottom)
private val frameMarginHorizontal = dimenPx(R.dimen.md_dialog_frame_margin_horizontal)
private val iconMargin = dimenPx(R.dimen.md_icon_margin)
private val iconSize = dimenPx(R.dimen.md_icon_size)
internal lateinit var iconView: ImageView
internal lateinit var titleView: TextView
override fun onFinishInflate() {
super.onFinishInflate()
iconView = findViewById(R.id.md_icon_title)
titleView = findViewById(R.id.md_text_title)
}
fun shouldNotBeVisible() = iconView.isNotVisible() && titleView.isNotVisible()
override fun onMeasure(
widthMeasureSpec: Int,
heightMeasureSpec: Int
) {
if (shouldNotBeVisible()) {
setMeasuredDimension(0, 0)
return
}
val parentWidth = getSize(widthMeasureSpec)
var titleMaxWidth = parentWidth - (frameMarginHorizontal * 2)
if (iconView.isVisible()) {
iconView.measure(
makeMeasureSpec(iconSize, EXACTLY),
makeMeasureSpec(iconSize, EXACTLY)
)
titleMaxWidth -= (iconView.measuredWidth + iconMargin)
}
titleView.measure(
makeMeasureSpec(titleMaxWidth, AT_MOST),
makeMeasureSpec(0, UNSPECIFIED)
)
val iconViewHeight = if (iconView.isVisible()) iconView.measuredHeight else 0
val requiredHeight = iconViewHeight.coerceAtLeast(titleView.measuredHeight)
val actualHeight = requiredHeight + frameMarginVertical + titleMarginBottom
setMeasuredDimension(parentWidth, actualHeight)
}
override fun onLayout(
changed: Boolean,
left: Int,
top: Int,
right: Int,
bottom: Int
) {
if (shouldNotBeVisible()) return
val contentTop = frameMarginVertical
val contentBottom = measuredHeight - titleMarginBottom
val contentHeight = contentBottom - contentTop
val contentMidPoint = contentBottom - (contentHeight / 2)
val titleHalfHeight = titleView.measuredHeight / 2
val titleTop = contentMidPoint - titleHalfHeight
val titleBottom = contentMidPoint + titleHalfHeight +
titleView.additionalPaddingForFont()
var titleLeft: Int
var titleRight: Int
if (isRtl()) {
titleRight = measuredWidth - frameMarginHorizontal
titleLeft = titleRight - titleView.measuredWidth
} else {
titleLeft = frameMarginHorizontal
titleRight = titleLeft + titleView.measuredWidth
}
if (iconView.isVisible()) {
val iconHalfHeight = iconView.measuredHeight / 2
val iconTop = contentMidPoint - iconHalfHeight
val iconBottom = contentMidPoint + iconHalfHeight
val iconLeft: Int
val iconRight: Int
if (isRtl()) {
iconRight = titleRight
iconLeft = iconRight - iconView.measuredWidth
titleRight = iconLeft - iconMargin
titleLeft = titleRight - titleView.measuredWidth
} else {
iconLeft = titleLeft
iconRight = iconLeft + iconView.measuredWidth
titleLeft = iconRight + iconMargin
titleRight = titleLeft + titleView.measuredWidth
}
iconView.layout(iconLeft, iconTop, iconRight, iconBottom)
}
titleView.layout(titleLeft, titleTop, titleRight, titleBottom)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (drawDivider) {
canvas.drawLine(
0f,
measuredHeight.toFloat() - dividerHeight.toFloat(),
measuredWidth.toFloat(),
measuredHeight.toFloat(),
dividerPaint()
)
}
}
}
| core/src/main/java/com/afollestad/materialdialogs/internal/main/DialogTitleLayout.kt | 318133597 |
package com.cdev.showtracker.ui.main
import com.cdev.showtracker.BasePresenter
import com.cdev.showtracker.BaseView
import com.cdev.showtracker.model.TvShowSuggestion
interface MainContract {
interface Presenter : BasePresenter<View> {
fun searchTvShows(query: String)
fun onSearchSuggestionSelected(tvShowSuggestion: TvShowSuggestion)
}
interface View : BaseView {
fun showSuggestions(tvShowSuggestions: List<TvShowSuggestion>)
fun startTvShowDetailScreen(tvShowId: Int)
}
} | app/src/main/java/com/cdev/showtracker/ui/main/MainContract.kt | 2618401453 |
/*
* Copyright (c) 2021. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package app.ss.lessons.data.model.api.request
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
internal data class SSMediaRequest(
val language: String,
val quarterlyId: String
)
| common/lessons-data/src/main/java/app/ss/lessons/data/model/api/request/SSMediaRequest.kt | 2771558220 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.