content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.bungeecord.framework import com.demonwav.mcdev.util.libraryKind import com.intellij.openapi.roots.libraries.LibraryKind val BUNGEECORD_LIBRARY_KIND: LibraryKind = libraryKind("bungeecord-api") val WATERFALL_LIBRARY_KIND: LibraryKind = libraryKind("waterfall-api")
src/main/kotlin/platform/bungeecord/framework/BungeeCordLibraryKind.kt
3193500692
package io.github.databob import java.util.* class CollectionSizeRange(private val min: Int, private val max: Int) { init { if (min > max) throw IllegalArgumentException("Cannot construct negative sized range") } object generators { val empty = Generators.ofType { -> CollectionSizeRange(0, 0) } fun exactly(value: Int): Generator = Generators.ofType { -> CollectionSizeRange(value, value) } fun between(min: Int, max: Int): Generator = Generators.ofType { -> CollectionSizeRange(min, max) } fun atMost(max: Int): Generator = Generators.ofType { -> CollectionSizeRange(0, max) } } fun toRandomRange(): IntRange = when { min == 0 && max == 0 -> IntRange.EMPTY min == max -> IntRange(0, max - 1) else -> IntRange(0, min - 1 + Random().nextInt(max - min)) } }
src/main/kotlin/io/github/databob/CollectionSizeRange.kt
2658710683
package pl.mareklangiewicz.myutils import org.junit.After import org.junit.Before import org.junit.Test import pl.mareklangiewicz.mycorelib.MyClass import java.util.Arrays /** * Created by Marek Langiewicz on 01.10.15. */ class MyTextUtilsTest { @Before fun setUp() { } @After fun tearDown() { } @Test fun testStr() { val list = Arrays.asList("bla", "ble") println(list.str) } @Test fun testToShortStr() { } @Test fun testToLongStr() { } @Test fun testToVeryLongStr() { } @Test fun testMyCoreLibBuild() { MyClass.bla() } }
myutils/src/test/java/pl/mareklangiewicz/myutils/MyTextUtilsTest.kt
2493414428
package com.engineer.imitate.ui.widget import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.engineer.imitate.R /** * * @author: Rookie * @date: 2018-07-31 15:00 * @version V1.0 */ class CustomDialogFragment: androidx.fragment.app.DialogFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_dialog,container,false) return view } }
imitate/src/main/java/com/engineer/imitate/ui/widget/CustomDialogFragment.kt
208451437
package com.adgvcxz.viewmodel.sample import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.subjects.PublishSubject import io.reactivex.rxjava3.subjects.Subject /** * zhaowei * Created by zhaowei on 2017/7/12. */ class RxBus { private val bus: Subject<Any> by lazy { PublishSubject.create<Any>().toSerialized() } private object Holder { val Instance = RxBus() } companion object { val instance: RxBus by lazy { Holder.Instance } } fun post(event: Any) = bus.onNext(event) fun <T : Any> toObservable(event: Class<T>): Observable<T> = bus.ofType(event) } class ValueChangeEvent(val id: Int, val value: String) class ViewPagerEvent(val value: String)
app/src/main/kotlin/com/adgvcxz/viewmodel/sample/RxBus.kt
2850232559
package com.hedvig.botService.testHelpers import com.hedvig.botService.chat.ConversationTest.Companion.TESTMESSAGE_ID import com.hedvig.botService.enteties.message.Message import com.hedvig.botService.enteties.message.MessageBody import com.hedvig.botService.enteties.message.MessageBodySingleSelect import com.hedvig.botService.enteties.message.MessageBodyText import com.hedvig.botService.enteties.message.MessageHeader import com.hedvig.botService.enteties.message.SelectItem import java.util.Arrays object MessageHelpers { fun createSingleSelectMessage(text: String, fromHedvig: Boolean = false, vararg items: SelectItem): Message { Arrays.asList(*items) return createMessage(MessageBodySingleSelect(text, Arrays.asList(*items)), fromHedvig) } fun createTextMessage(text: String, fromHedvig: Boolean = false): Message { return createMessage(MessageBodyText(text), fromHedvig) } fun createMessage(body: MessageBody, fromHedvig: Boolean = false): Message { val m = Message() m.id = TESTMESSAGE_ID m.globalId = 1 m.header = MessageHeader() m.header.fromId = if (fromHedvig) 1L else -1L m.header.messageId = 1 m.body = body return m } }
src/test/java/com/hedvig/botService/testHelpers/MessageHelpers.kt
4009448007
package v_collections import java.util.HashSet import util.TODO /* * This part of workshop was inspired by: * https://github.com/goldmansachs/gs-collections-kata */ /* * For easy java compatibility we don't introduce our own collections, but use standard Java ones. * However there are two different means of use: mutable and read-only. */ fun useReadonlySet(set: Set<Int>) { // doesn't compile: // set.add(1) } fun useMutableSet(set: MutableSet<Int>) { set.add(1) } /* * There are many operations that help to transform one collection into another, starting with 'to' */ fun example0(list: List<Int>) { list.toSet() val set = HashSet<Int>() list.to(set) } fun Shop.getSetOfCustomers(): Set<Customer> { // Return a set containing all the customers of this shop todoCollectionTask() // return this.customers }
src/v_collections/A_Introduction_.kt
2878605111
// // (C) Copyright 2018-2019 Martin E. Nordberg III // Apache 2.0 License // package jvm.katydid.css.infrastructure import o.katydid.css.colors.* import org.junit.jupiter.api.Test import x.katydid.css.infrastructure.makeDecimalString import kotlin.test.assertEquals import kotlin.test.assertSame @Suppress("RemoveRedundantBackticks") class NumberUtilityTests { @Test fun `Floats format as expected`() { assertEquals("0", makeDecimalString(0f)) assertEquals("0.1", makeDecimalString(0.1f)) assertEquals("0.12", makeDecimalString(0.12f)) assertEquals("0.123", makeDecimalString(0.123f)) assertEquals("0.123", makeDecimalString(0.1234f)) assertEquals("0.124", makeDecimalString(0.12351f)) assertEquals("1", makeDecimalString(1f)) assertEquals("23", makeDecimalString(23.0001f)) } }
Katydid-CSS-JVM/src/test/kotlin/jvm/katydid/css/infrastructure/NumberUtilityTests.kt
2788494820
/* * Copyright (C) 2017-2018 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.marklogic.debugger.stack interface MarkLogicVariable { val namespace: String? val localName: String val value: String }
src/main/java/uk/co/reecedunn/intellij/plugin/marklogic/debugger/stack/MarkLogicVariable.kt
3213610090
package com.bennyhuo.github.view import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.content.Intent import android.os.Bundle import android.view.View import android.widget.EditText import com.bennyhuo.common.ext.hideSoftInput import com.bennyhuo.github.R import com.bennyhuo.github.common.ext.otherwise import com.bennyhuo.github.common.ext.yes import com.bennyhuo.github.presenter.LoginPresenter import com.bennyhuo.github.view.config.Themer import com.bennyhuo.mvp.impl.BaseActivity import com.bennyhuo.tieguanyin.annotations.ActivityBuilder import kotlinx.android.synthetic.main.activity_login.* import kotlinx.android.synthetic.main.app_bar_simple.* import org.jetbrains.anko.sdk15.listeners.onClick import org.jetbrains.anko.toast @ActivityBuilder(flags = [Intent.FLAG_ACTIVITY_NO_HISTORY]) class LoginActivity : BaseActivity<LoginPresenter>() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Themer.applyProperTheme(this) setContentView(R.layout.activity_login) setSupportActionBar(toolbar) signInButton.onClick { presenter.checkUserName(username.text.toString()) .yes { presenter.checkPasswd(password.text.toString()) .yes { hideSoftInput() presenter.doLogin(username.text.toString(), password.text.toString()) } .otherwise { showTips(password, "ε―†η δΈεˆζ³•") } } .otherwise { showTips(username, "η”¨ζˆ·εδΈεˆζ³•") } } } private fun showProgress(show: Boolean) { val shortAnimTime = resources.getInteger(android.R.integer.config_shortAnimTime) loginForm.animate().setDuration(shortAnimTime.toLong()).alpha( (if (show) 0 else 1).toFloat()).setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { loginForm.visibility = if (show) View.GONE else View.VISIBLE } }) loginProgress.animate().setDuration(shortAnimTime.toLong()).alpha( (if (show) 1 else 0).toFloat()).setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { loginProgress.visibility = if (show) View.VISIBLE else View.GONE } }) } private fun showTips(view: EditText, tips: String){ view.requestFocus() view.error = tips } fun onLoginStart(){ showProgress(true) } fun onLoginError(e: Throwable){ e.printStackTrace() toast("登录倱θ΄₯") showProgress(false) } fun onLoginSuccess(){ toast("η™»ε½•ζˆεŠŸ") showProgress(false) startMainActivity() } fun onDataInit(name: String, passwd: String){ username.setText(name) password.setText(passwd) } }
Kotlin/Kotlin-github/app/src/main/java/com/bennyhuo/github/view/LoginActivity.kt
2738935081
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.sample.util import com.tencent.mmkv.MMKV import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch class StringMmkvData( mmkv: MMKV, key: String, defaultState: String ) : BaseMmkvData<String>(defaultState, StringMmkvAdapter(mmkv, key, defaultState)) class BooleanMmkvData( mmkv: MMKV, key: String, defaultState: Boolean ) : BaseMmkvData<Boolean>(defaultState, BooleanMmkvAdapter(mmkv, key, defaultState)) abstract class BaseMmkvData<T>(defaultState: T, private val mmkvAdapter: MmkvAdapter<T>) { private val _stateFlow = MutableStateFlow(defaultState) private val _sharedFlow = MutableSharedFlow<T>() private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) val stateFlow: StateFlow<T> get() = _stateFlow val sharedFlow: SharedFlow<T> get() = _sharedFlow init { _stateFlow.value = mmkvAdapter.state } var value: T get() = stateFlow.value set(value) { mmkvAdapter.state = value _stateFlow.value = value scope.launch { _sharedFlow.emit(value) } } } interface MmkvAdapter<T> { var state: T } class StringMmkvAdapter( private val mmkv: MMKV, private val key: String, private val defaultValue: String ) : MmkvAdapter<String> { override var state: String get() = mmkv.decodeString(key, defaultValue) ?: defaultValue set(value) { mmkv.encode(key, value) } } class BooleanMmkvAdapter( private val mmkv: MMKV, private val key: String, private val defaultValue: Boolean ) : MmkvAdapter<Boolean> { override var state: Boolean get() = mmkv.decodeBool(key, defaultValue) set(value) { mmkv.encode(key, value) } }
sample/src/main/java/com/github/panpf/sketch/sample/util/MmkvData.kt
3740143672
package de.saschahlusiak.freebloks.utils data class Point(val x: Int = 0, val y: Int = 0) data class PointF(val x: Float = 0f, val y: Float = 0f)
common/src/main/java/de/saschahlusiak/freebloks/utils/Point.kt
511605071
package info.deskchan.notification_manager; import info.deskchan.MessageData.Core.AddCommand import info.deskchan.MessageData.Core.SetEventLink import info.deskchan.MessageData.GUI.Control import info.deskchan.MessageData.GUI.SetPanel import info.deskchan.core.MessageDataMap import info.deskchan.core.MessageListener import info.deskchan.core.Plugin; import info.deskchan.core.PluginProxyInterface; import java.text.SimpleDateFormat import java.util.*; public class Main : Plugin { companion object { private lateinit var pluginProxy: PluginProxyInterface private var phraseIdCounter = 0 } /** Single phrase in notification. **/ private class NotificationPhrase { public val text: String public val sender: String? public val date: Date public val id: Int constructor(text: String, sender: String?){ this.text = text this.sender = sender date = Date() id = phraseIdCounter phraseIdCounter++ } public fun getAsControl(): Control { var dateString = "(" + SimpleDateFormat("HH:mm:ss").format(date) + ") " val map = Control( Control.ControlType.Button, "notification" + id, "X", "label", dateString + (if (sender != null) "[" + sender + "]: " else "") + text, "msgTag", "notification:delete", "msgData", id ) return map } } private var managerIsOpened = false private val history = mutableListOf<NotificationPhrase>() private val logLength = 12 private var currentQuery = "" private lateinit var EMPTY: Control private fun historyToNotification(): MutableList<Map<String, Any>>{ val ret = mutableListOf<Map<String, Any>>() val list = history.subList(Math.max(history.size - logLength, 0), history.size) if (list.isEmpty()){ ret.add(EMPTY) } else { list.forEach { it -> ret.add(it.getAsControl()) } } return ret } override fun initialize(pluginProxy: PluginProxyInterface): Boolean { Main.pluginProxy = pluginProxy pluginProxy.setConfigField("name", pluginProxy.getString("plugin.name")) EMPTY = Control( Control.ControlType.Label, null, pluginProxy.getString("no-notifications"), "width", 350 ) /* Open chat request. * Public message * Params: None * Returns: None */ pluginProxy.addMessageListener("notification:open", MessageListener { sender, tag, data -> pluginProxy.sendMessage(SetPanel( "notification", SetPanel.PanelType.WINDOW, SetPanel.ActionType.SHOW )) managerIsOpened = true; }) pluginProxy.sendMessage(AddCommand( "notification:open", "notifications.open-info" )) pluginProxy.sendMessage(SetEventLink( "gui:keyboard-handle", "notification:open", "ALT+N" )) /* Chat has been closed through GUI. */ pluginProxy.addMessageListener("notification:closed", MessageListener { sender, tag, data -> managerIsOpened = false; }) /* Updated textfield input. */ pluginProxy.addMessageListener("notification:update-textfield", MessageListener {sender, tag, data -> //currentQuery = data.toString(); }) /* Someone made request to clear all messages from notification window. We're clearing it. */ pluginProxy.addMessageListener("notification:clear", MessageListener {sender, tag, data -> history.clear() setPanel() }); pluginProxy.addMessageListener("notification:delete", MessageListener {sender, tag, data -> val id = data as Int history.removeIf { it -> it.id == id } setPanel() }) /* New notification occurred */ pluginProxy.addMessageListener("DeskChan:notify", MessageListener {sender, tag, data -> val map = MessageDataMap("message", data) if (map.containsKey("msgData")) map.put("message", map.getString("msgData")) if (!map.containsKey("message")) return@MessageListener history.add(NotificationPhrase(map.getString("message")!!, sender)) setPanel() }) /* Registering "Open Notification Manager" button in menu. */ pluginProxy.sendMessage(SetEventLink( "gui:menu-action", "notification:open", pluginProxy.getString("notifications.open") )) setPanel() pluginProxy.log("Notification Manager loading complete") return true } fun setPanel(){ val message = SetPanel( "notification", SetPanel.PanelType.WINDOW, SetPanel.ActionType.SET, pluginProxy.getString("window-name"), "notification:closed", null ) val controls = historyToNotification() controls.add(Control( Control.ControlType.Button, "clear", pluginProxy.getString("clear"), "msgTag", "notification:clear" )) message.controls = controls Main.pluginProxy.sendMessage(message) } }
src/main/kotlin/info/deskchan/notification_manager/Main.kt
2419948447
package edu.cs4730.cameraxvideodemo_kt import android.Manifest import android.annotation.SuppressLint import android.content.ContentValues import android.content.pm.PackageManager import android.database.Cursor import android.os.Build import android.os.Bundle import android.provider.MediaStore import android.util.Log import android.widget.Toast import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.camera.core.CameraSelector import androidx.camera.core.ImageCapture import androidx.camera.core.Preview import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.video.* import androidx.camera.video.VideoRecordEvent.Finalize import androidx.core.content.ContextCompat import kotlinx.android.synthetic.main.activity_main.* import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.ExecutorService import java.util.concurrent.Executors /** * based on https://codelabs.developers.google.com/codelabs/camerax-getting-started#0 */ class MainActivity : AppCompatActivity() { private var videoCapture: VideoCapture<Recorder>? = null private var currentRecording: Recording? = null lateinit var rpl: ActivityResultLauncher<Array<String>> private lateinit var cameraExecutor: ExecutorService var recording: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) REQUIRED_PERMISSIONS = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { //For API 29+ (q), for 26 to 28. arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO) } else { arrayOf( Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO ) } rpl = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions() ) { if (allPermissionsGranted()) { startCamera() } else { Toast.makeText( applicationContext, "Permissions not granted by the user.", Toast.LENGTH_SHORT ).show() finish() } } // Request camera permissions if (allPermissionsGranted()) { startCamera() } else { rpl.launch(REQUIRED_PERMISSIONS) } // Set up the listener for take photo button camera_capture_button.setOnClickListener { takeVideo() } cameraExecutor = Executors.newSingleThreadExecutor() } @SuppressLint("RestrictedApi", "MissingPermission") private fun takeVideo() { Log.d(TAG, "start") // Get a stable reference of the modifiable image capture use case val videoCapture = videoCapture ?: return if (recording) { //ie already started. currentRecording?.stop() recording = false camera_capture_button.text = "Start Rec" } else { val name = "CameraX-" + SimpleDateFormat(FILENAME_FORMAT, Locale.US) .format(System.currentTimeMillis()) + ".mp4" val cv = ContentValues() cv.put(MediaStore.MediaColumns.DISPLAY_NAME, name) cv.put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4") if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { cv.put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/CameraX-Video") } val mediaStoreOutputOptions = MediaStoreOutputOptions.Builder( contentResolver, MediaStore.Video.Media.EXTERNAL_CONTENT_URI ) .setContentValues(cv) .build() currentRecording = videoCapture.output .prepareRecording(this@MainActivity, mediaStoreOutputOptions) .withAudioEnabled() .start( cameraExecutor ) { videoRecordEvent -> if (videoRecordEvent is Finalize) { val savedUri = videoRecordEvent.outputResults.outputUri //convert uri to useful name. var cursor: Cursor? = null var path: String try { cursor = contentResolver.query( savedUri, arrayOf(MediaStore.MediaColumns.DATA), null, null, null ) cursor!!.moveToFirst() path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)) } finally { cursor!!.close() } Log.wtf(TAG, path) if (path == "") { path = savedUri.toString() } val msg = "Video capture succeeded: $path" runOnUiThread { Toast.makeText( baseContext, msg, Toast.LENGTH_LONG ).show() } Log.d(TAG, msg) currentRecording = null } } recording = true camera_capture_button.text = "Stop Rec" } } @SuppressLint("RestrictedApi") private fun startCamera() { val cameraProviderFuture = ProcessCameraProvider.getInstance(this) cameraProviderFuture.addListener( { try { val cameraProvider = cameraProviderFuture.get() as ProcessCameraProvider val preview = Preview.Builder().build() preview.setSurfaceProvider(viewFinder.surfaceProvider) val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA val recorder = Recorder.Builder() .setQualitySelector( QualitySelector.from( Quality.HIGHEST, FallbackStrategy.higherQualityOrLowerThan(Quality.SD) ) ) .build() videoCapture = VideoCapture.withOutput(recorder) val imageCatpure = ImageCapture.Builder().build() // Unbind use cases before rebinding cameraProvider.unbindAll() // Bind use cases to camera cameraProvider.bindToLifecycle( this@MainActivity, cameraSelector, preview, imageCatpure, videoCapture ) } catch (e: Exception) { Log.e(TAG, "Use case binding failed", e) } }, ContextCompat.getMainExecutor(this) ) } private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all { ContextCompat.checkSelfPermission( baseContext, it ) == PackageManager.PERMISSION_GRANTED } override fun onDestroy() { super.onDestroy() cameraExecutor.shutdown() } companion object { private const val TAG = "CameraXBasic" private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS" private lateinit var REQUIRED_PERMISSIONS: Array<String> } }
CameraXVideoDemo_kt/app/src/main/java/edu/cs4730/cameraxvideodemo_kt/MainActivity.kt
140309552
/* * Copyright 2021 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.window.window import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveableStateHolder import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.awt.ComposeWindow import androidx.compose.ui.isLinux import androidx.compose.ui.isWindows import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Window import androidx.compose.ui.window.WindowPlacement import androidx.compose.ui.window.WindowPosition import androidx.compose.ui.window.WindowState import androidx.compose.ui.window.launchApplication import androidx.compose.ui.window.rememberWindowState import androidx.compose.ui.window.runApplicationTest import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.consumeEach import org.junit.Assume.assumeTrue import org.junit.Test import java.awt.Dimension import java.awt.Point import java.awt.Rectangle import java.awt.Window import java.awt.event.WindowEvent import javax.swing.JFrame import kotlin.math.abs import kotlin.math.max // Note that on Linux some tests are flaky. Swing event listener's on Linux has non-deterministic // nature. To avoid flaky'ness we use delays // (see description of `delay` parameter in TestUtils.runApplicationTest). // It is not a good solution, but it works. // TODO(demin): figure out how can we fix flaky tests on Linux // TODO(demin): fix fullscreen tests on macOs @OptIn(ExperimentalComposeUiApi::class) class WindowStateTest { @Test fun `manually close window`() = runApplicationTest { var window: ComposeWindow? = null var isOpen by mutableStateOf(true) launchApplication { if (isOpen) { Window(onCloseRequest = { isOpen = false }) { window = this.window } } } awaitIdle() assertThat(window?.isShowing).isTrue() window?.dispatchEvent(WindowEvent(window, WindowEvent.WINDOW_CLOSING)) awaitIdle() assertThat(window?.isShowing).isFalse() } @Test fun `programmatically close window`() = runApplicationTest { var window: ComposeWindow? = null var isOpen by mutableStateOf(true) launchApplication { if (isOpen) { Window(onCloseRequest = { isOpen = false }) { window = this.window } } } awaitIdle() assertThat(window?.isShowing).isTrue() isOpen = false awaitIdle() assertThat(window?.isShowing).isFalse() } @Test fun `programmatically open and close nested window`() = runApplicationTest { var parentWindow: ComposeWindow? = null var childWindow: ComposeWindow? = null var isParentOpen by mutableStateOf(true) var isChildOpen by mutableStateOf(false) launchApplication { if (isParentOpen) { Window(onCloseRequest = {}) { parentWindow = this.window if (isChildOpen) { Window(onCloseRequest = {}) { childWindow = this.window } } } } } awaitIdle() assertThat(parentWindow?.isShowing).isTrue() isChildOpen = true awaitIdle() assertThat(parentWindow?.isShowing).isTrue() assertThat(childWindow?.isShowing).isTrue() isChildOpen = false awaitIdle() assertThat(parentWindow?.isShowing).isTrue() assertThat(childWindow?.isShowing).isFalse() isParentOpen = false awaitIdle() assertThat(parentWindow?.isShowing).isFalse() } @Test fun `set size and position before show`() = runApplicationTest(useDelay = isLinux) { val state = WindowState( size = DpSize(200.dp, 200.dp), position = WindowPosition(242.dp, 242.dp) ) var window: ComposeWindow? = null launchApplication { Window(onCloseRequest = {}, state) { window = this.window } } awaitIdle() assertThat(window?.size).isEqualTo(Dimension(200, 200)) assertThat(window?.location).isEqualTo(Point(242, 242)) exitApplication() } @Test fun `change position after show`() = runApplicationTest(useDelay = isLinux) { val state = WindowState( size = DpSize(200.dp, 200.dp), position = WindowPosition(200.dp, 200.dp) ) var window: ComposeWindow? = null launchApplication { Window(onCloseRequest = {}, state) { window = this.window } } awaitIdle() state.position = WindowPosition(242.dp, (242).dp) awaitIdle() assertThat(window?.location).isEqualTo(Point(242, 242)) exitApplication() } @Test fun `change size after show`() = runApplicationTest(useDelay = isLinux) { val state = WindowState( size = DpSize(200.dp, 200.dp), position = WindowPosition(200.dp, 200.dp) ) var window: ComposeWindow? = null launchApplication { Window(onCloseRequest = {}, state) { window = this.window } } awaitIdle() state.size = DpSize(250.dp, 200.dp) awaitIdle() assertThat(window?.size).isEqualTo(Dimension(250, 200)) exitApplication() } @Test fun `center window`() = runApplicationTest { fun Rectangle.center() = Point(x + width / 2, y + height / 2) fun JFrame.center() = bounds.center() fun JFrame.screenCenter() = graphicsConfiguration.bounds.center() infix fun Point.maxDistance(other: Point) = max(abs(x - other.x), abs(y - other.y)) val state = WindowState( size = DpSize(200.dp, 200.dp), position = WindowPosition(Alignment.Center) ) var window: ComposeWindow? = null launchApplication { Window(onCloseRequest = {}, state) { window = this.window } } awaitIdle() assertThat(window!!.center() maxDistance window!!.screenCenter() < 250) exitApplication() } @Test fun `remember position after reattach`() = runApplicationTest(useDelay = isLinux) { val state = WindowState(size = DpSize(200.dp, 200.dp)) var window1: ComposeWindow? = null var window2: ComposeWindow? = null var isWindow1 by mutableStateOf(true) launchApplication { if (isWindow1) { Window(onCloseRequest = {}, state) { window1 = this.window } } else { Window(onCloseRequest = {}, state) { window2 = this.window } } } awaitIdle() state.position = WindowPosition(242.dp, 242.dp) awaitIdle() assertThat(window1?.location == Point(242, 242)) isWindow1 = false awaitIdle() assertThat(window2?.location == Point(242, 242)) exitApplication() } @Test fun `state position should be specified after attach`() = runApplicationTest { val state = WindowState(size = DpSize(200.dp, 200.dp)) launchApplication { Window(onCloseRequest = {}, state) { } } assertThat(state.position.isSpecified).isFalse() awaitIdle() assertThat(state.position.isSpecified).isTrue() exitApplication() } @Test fun `enter fullscreen`() = runApplicationTest(useDelay = isLinux) { // TODO(demin): fix macOs. We disabled it because it is not deterministic. // If we set in skiko SkiaLayer.setFullscreen(true) then isFullscreen still returns false assumeTrue(isWindows || isLinux) val state = WindowState(size = DpSize(200.dp, 200.dp)) var window: ComposeWindow? = null launchApplication { Window(onCloseRequest = {}, state) { window = this.window } } awaitIdle() state.placement = WindowPlacement.Fullscreen awaitIdle() assertThat(window?.placement).isEqualTo(WindowPlacement.Fullscreen) state.placement = WindowPlacement.Floating awaitIdle() assertThat(window?.placement).isEqualTo(WindowPlacement.Floating) exitApplication() } @Test fun maximize() = runApplicationTest(useDelay = isLinux) { val state = WindowState(size = DpSize(200.dp, 200.dp)) var window: ComposeWindow? = null launchApplication { Window(onCloseRequest = {}, state) { window = this.window } } awaitIdle() state.placement = WindowPlacement.Maximized awaitIdle() assertThat(window?.placement).isEqualTo(WindowPlacement.Maximized) state.placement = WindowPlacement.Floating awaitIdle() assertThat(window?.placement).isEqualTo(WindowPlacement.Floating) exitApplication() } @Test fun minimize() = runApplicationTest { val state = WindowState(size = DpSize(200.dp, 200.dp)) var window: ComposeWindow? = null launchApplication { Window(onCloseRequest = {}, state) { window = this.window } } awaitIdle() state.isMinimized = true awaitIdle() assertThat(window?.isMinimized).isTrue() state.isMinimized = false awaitIdle() assertThat(window?.isMinimized).isFalse() exitApplication() } @Test fun `maximize and minimize `() = runApplicationTest { // macOs can't be maximized and minimized at the same time assumeTrue(isWindows || isLinux) val state = WindowState(size = DpSize(200.dp, 200.dp)) var window: ComposeWindow? = null launchApplication { Window(onCloseRequest = {}, state) { window = this.window } } awaitIdle() state.isMinimized = true state.placement = WindowPlacement.Maximized awaitIdle() assertThat(window?.isMinimized).isTrue() assertThat(window?.placement).isEqualTo(WindowPlacement.Maximized) exitApplication() } @Test fun `restore size and position after maximize`() = runApplicationTest { // Swing/macOs can't re-change isMaximized in a deterministic way: // fun main() = runBlocking(Dispatchers.Swing) { // val window = ComposeWindow() // window.size = Dimension(200, 200) // window.isVisible = true // window.isMaximized = true // delay(100) // window.isMaximized = false // we cannot do that on macOs (window is still animating) // delay(1000) // println(window.isMaximized) // prints true // } // Swing/Linux has animations and sometimes adds an offset to the size/position assumeTrue(isWindows) val state = WindowState( size = DpSize(201.dp, 203.dp), position = WindowPosition(196.dp, 257.dp) ) var window: ComposeWindow? = null launchApplication { Window(onCloseRequest = {}, state) { window = this.window } } awaitIdle() assertThat(window?.size).isEqualTo(Dimension(201, 203)) assertThat(window?.location).isEqualTo(Point(196, 257)) state.placement = WindowPlacement.Maximized awaitIdle() assertThat(window?.placement).isEqualTo(WindowPlacement.Maximized) assertThat(window?.size).isNotEqualTo(Dimension(201, 203)) assertThat(window?.location).isNotEqualTo(Point(196, 257)) state.placement = WindowPlacement.Floating awaitIdle() assertThat(window?.placement).isEqualTo(WindowPlacement.Floating) assertThat(window?.size).isEqualTo(Dimension(201, 203)) assertThat(window?.location).isEqualTo(Point(196, 257)) exitApplication() } @Test fun `restore size and position after fullscreen`() = runApplicationTest { // Swing/Linux has animations and sometimes adds an offset to the size/position assumeTrue(isWindows) val state = WindowState( size = DpSize(201.dp, 203.dp), position = WindowPosition(196.dp, 257.dp) ) var window: ComposeWindow? = null launchApplication { Window(onCloseRequest = {}, state) { window = this.window } } awaitIdle() assertThat(window?.size).isEqualTo(Dimension(201, 203)) assertThat(window?.location).isEqualTo(Point(196, 257)) state.placement = WindowPlacement.Fullscreen awaitIdle() assertThat(window?.placement).isEqualTo(WindowPlacement.Fullscreen) assertThat(window?.size).isNotEqualTo(Dimension(201, 203)) assertThat(window?.location).isNotEqualTo(Point(196, 257)) state.placement = WindowPlacement.Floating awaitIdle() assertThat(window?.placement).isEqualTo(WindowPlacement.Floating) assertThat(window?.size).isEqualTo(Dimension(201, 203)) assertThat(window?.location).isEqualTo(Point(196, 257)) exitApplication() } @Test fun `maximize window before show`() = runApplicationTest(useDelay = isLinux) { val state = WindowState( size = DpSize(200.dp, 200.dp), position = WindowPosition(Alignment.Center), placement = WindowPlacement.Maximized, ) var window: ComposeWindow? = null launchApplication { Window(onCloseRequest = {}, state) { window = this.window } } awaitIdle() assertThat(window?.placement).isEqualTo(WindowPlacement.Maximized) exitApplication() } @Test fun `minimize window before show`() = runApplicationTest { // Linux/macos doesn't support this: // fun main() = runBlocking(Dispatchers.Swing) { // val window = ComposeWindow() // window.size = Dimension(200, 200) // window.isMinimized = true // window.isVisible = true // delay(2000) // println(window.isMinimized) // prints false // } // TODO(demin): can we minimize after window.isVisible? assumeTrue(isWindows) val state = WindowState( size = DpSize(200.dp, 200.dp), position = WindowPosition(Alignment.Center), isMinimized = true ) var window: ComposeWindow? = null launchApplication { Window(onCloseRequest = {}, state) { window = this.window } } awaitIdle() assertThat(window?.isMinimized).isTrue() exitApplication() } @Test fun `enter fullscreen before show`() = runApplicationTest { // TODO(demin): probably we have a bug in skiko (we can't change fullscreen on macOs before // showing the window) assumeTrue(isLinux || isWindows) val state = WindowState( size = DpSize(200.dp, 200.dp), position = WindowPosition(Alignment.Center), placement = WindowPlacement.Fullscreen, ) var window: ComposeWindow? = null launchApplication { Window(onCloseRequest = {}, state) { window = this.window } } awaitIdle() assertThat(window?.placement).isEqualTo(WindowPlacement.Fullscreen) exitApplication() } @Test fun `save state`() = runApplicationTest { val initialState = WindowState() val newState = WindowState( placement = WindowPlacement.Maximized, size = DpSize(42.dp, 42.dp), position = WindowPosition(3.dp, 3.dp), isMinimized = true, ) var isOpen by mutableStateOf(true) var index by mutableStateOf(0) val states = mutableListOf<WindowState>() launchApplication { val saveableStateHolder = rememberSaveableStateHolder() saveableStateHolder.SaveableStateProvider(index) { val state = rememberWindowState() LaunchedEffect(Unit) { state.placement = newState.placement state.isMinimized = newState.isMinimized state.size = newState.size state.position = newState.position states.add(state) } } if (isOpen) { Window(onCloseRequest = {}) {} } } awaitIdle() assertThat(states.size == 1) index = 1 awaitIdle() assertThat(states.size == 2) index = 0 awaitIdle() assertThat(states.size == 3) assertThat(states[0].placement == initialState.placement) assertThat(states[0].isMinimized == initialState.isMinimized) assertThat(states[0].size == initialState.size) assertThat(states[0].position == initialState.position) assertThat(states[2].placement == newState.placement) assertThat(states[2].isMinimized == newState.isMinimized) assertThat(states[2].size == newState.size) assertThat(states[2].position == newState.position) isOpen = false } @Test fun `set window height by its content`() = runApplicationTest(useDelay = isLinux) { lateinit var window: ComposeWindow val state = WindowState(size = DpSize(300.dp, Dp.Unspecified)) launchApplication { Window( onCloseRequest = ::exitApplication, state = state ) { window = this.window Box( Modifier .width(400.dp) .height(200.dp) ) } } awaitIdle() assertThat(window.width).isEqualTo(300) assertThat(window.contentSize.height).isEqualTo(200) assertThat(state.size).isEqualTo(DpSize(window.size.width.dp, window.size.height.dp)) exitApplication() } @Test fun `set window width by its content`() = runApplicationTest(useDelay = isLinux) { lateinit var window: ComposeWindow val state = WindowState(size = DpSize(Dp.Unspecified, 300.dp)) launchApplication { Window( onCloseRequest = ::exitApplication, state = state ) { window = this.window Box( Modifier .width(400.dp) .height(200.dp) ) } } awaitIdle() assertThat(window.height).isEqualTo(300) assertThat(window.contentSize.width).isEqualTo(400) assertThat(state.size).isEqualTo(DpSize(window.size.width.dp, window.size.height.dp)) exitApplication() } @Test fun `set window size by its content`() = runApplicationTest(useDelay = isLinux) { lateinit var window: ComposeWindow val state = WindowState(size = DpSize(Dp.Unspecified, Dp.Unspecified)) launchApplication { Window( onCloseRequest = ::exitApplication, state = state ) { window = this.window Box( Modifier .width(400.dp) .height(200.dp) ) } } awaitIdle() assertThat(window.contentSize).isEqualTo(Dimension(400, 200)) assertThat(state.size).isEqualTo(DpSize(window.size.width.dp, window.size.height.dp)) exitApplication() } @Test fun `set window size by its content when window is on the screen`() = runApplicationTest( useDelay = isLinux ) { lateinit var window: ComposeWindow val state = WindowState(size = DpSize(100.dp, 100.dp)) launchApplication { Window( onCloseRequest = ::exitApplication, state = state ) { window = this.window Box( Modifier .width(400.dp) .height(200.dp) ) } } awaitIdle() state.size = DpSize(Dp.Unspecified, Dp.Unspecified) awaitIdle() assertThat(window.contentSize).isEqualTo(Dimension(400, 200)) assertThat(state.size).isEqualTo(DpSize(window.size.width.dp, window.size.height.dp)) exitApplication() } @Test fun `change visible`() = runApplicationTest { lateinit var window: ComposeWindow var visible by mutableStateOf(false) launchApplication { Window(onCloseRequest = ::exitApplication, visible = visible) { window = this.window } } awaitIdle() assertThat(window.isVisible).isEqualTo(false) visible = true awaitIdle() assertThat(window.isVisible).isEqualTo(true) exitApplication() } @Test fun `invisible window should be active`() = runApplicationTest { val receivedNumbers = mutableListOf<Int>() val sendChannel = Channel<Int>(Channel.UNLIMITED) launchApplication { Window(onCloseRequest = ::exitApplication, visible = false) { LaunchedEffect(Unit) { sendChannel.consumeEach { receivedNumbers.add(it) } } } } sendChannel.send(1) awaitIdle() assertThat(receivedNumbers).isEqualTo(listOf(1)) sendChannel.send(2) awaitIdle() assertThat(receivedNumbers).isEqualTo(listOf(1, 2)) exitApplication() } @Test fun `start invisible undecorated window`() = runApplicationTest { val receivedNumbers = mutableListOf<Int>() val sendChannel = Channel<Int>(Channel.UNLIMITED) launchApplication { Window(onCloseRequest = ::exitApplication, visible = false, undecorated = true) { LaunchedEffect(Unit) { sendChannel.consumeEach { receivedNumbers.add(it) } } } } sendChannel.send(1) awaitIdle() assertThat(receivedNumbers).isEqualTo(listOf(1)) sendChannel.send(2) awaitIdle() assertThat(receivedNumbers).isEqualTo(listOf(1, 2)) exitApplication() } private val Window.contentSize get() = Dimension( size.width - insets.left - insets.right, size.height - insets.top - insets.bottom, ) }
compose/ui/ui/src/desktopTest/kotlin/androidx/compose/ui/window/window/WindowStateTest.kt
1703723184
/** * ownCloud Android client application * * @author David GonzΓ‘lez Verdugo * Copyright (C) 2020 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.domain.exceptions import java.lang.Exception class SpecificForbiddenException : Exception()
owncloudDomain/src/main/java/com/owncloud/android/domain/exceptions/SpecificForbiddenException.kt
3569168563
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.refactoring import com.intellij.lang.Language import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.command.WriteCommandAction.runWriteCommandAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileSystemItem import com.intellij.psi.impl.file.PsiFileImplUtil import com.intellij.refactoring.RefactoringActionHandler import com.intellij.refactoring.actions.BaseRefactoringAction import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil import org.rust.RsBundle import org.rust.lang.RsConstants import org.rust.lang.RsLanguage import org.rust.lang.core.psi.RsFile import org.rust.openapiext.checkWriteAccessAllowed class RsDowngradeModuleToFile : BaseRefactoringAction() { override fun isEnabledOnElements(elements: Array<out PsiElement>): Boolean = elements.all { it.isDirectoryMod } override fun isAvailableOnElementInEditorAndFile( element: PsiElement, editor: Editor, file: PsiFile, context: DataContext ): Boolean { return file.isDirectoryMod } override fun getHandler(dataContext: DataContext): RefactoringActionHandler = Handler override fun isAvailableInEditorOnly(): Boolean = false override fun isAvailableForLanguage(language: Language): Boolean = language.`is`(RsLanguage) private object Handler : RefactoringActionHandler { override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext?) { invoke(project, arrayOf(file), dataContext) } override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext?) { runWriteCommandAction( project, RsBundle.message("action.Rust.RsDowngradeModuleToFile.text"), "action.Rust.RsDowngradeModuleToFile", { for (element in elements) { contractModule(element as PsiFileSystemItem) } } ) } } } private fun contractModule(fileOrDirectory: PsiFileSystemItem) { checkWriteAccessAllowed() val (file, dir) = when (fileOrDirectory) { is RsFile -> fileOrDirectory to fileOrDirectory.parent!! is PsiDirectory -> fileOrDirectory.children.single() as RsFile to fileOrDirectory else -> error("Can contract only files and directories") } val dst = dir.parent!! val fileName = "${dir.name}.rs" PsiFileImplUtil.setName(file, fileName) MoveFilesOrDirectoriesUtil.doMoveFile(file, dst) dir.delete() } private val PsiElement.isDirectoryMod: Boolean get() { return when (this) { is RsFile -> name == RsConstants.MOD_RS_FILE && containingDirectory?.children?.size == 1 is PsiDirectory -> { val child = children.singleOrNull() child is RsFile && child.name == RsConstants.MOD_RS_FILE } else -> false } }
src/main/kotlin/org/rust/ide/refactoring/RsDowngradeModuleToFile.kt
3052542039
package com.teamwizardry.librarianlib.foundation.registration import com.teamwizardry.librarianlib.foundation.block.BaseBlock import com.teamwizardry.librarianlib.foundation.block.BlockPropertiesBuilder import com.teamwizardry.librarianlib.foundation.block.FoundationBlockProperties import com.teamwizardry.librarianlib.foundation.block.IFoundationBlock import com.teamwizardry.librarianlib.foundation.item.IFoundationItem import com.teamwizardry.librarianlib.foundation.loot.BlockLootTableGenerator import net.minecraft.block.Block import net.minecraft.block.BlockState import net.minecraft.block.SoundType import net.minecraft.block.material.Material import net.minecraft.block.material.MaterialColor import net.minecraft.client.renderer.model.IBakedModel import net.minecraft.client.renderer.tileentity.ItemStackTileEntityRenderer import net.minecraft.item.* import net.minecraft.tags.ITag import net.minecraft.tags.Tag import net.minecraft.util.IItemProvider import net.minecraft.util.Identifier import net.minecraftforge.client.model.generators.BlockStateProvider import net.minecraftforge.client.model.generators.ItemModelProvider import net.minecraftforge.common.ToolType import java.util.concurrent.Callable import java.util.function.Consumer import java.util.function.Function import java.util.function.Supplier /** * The specs for creating and registering a block. The [BlockItem] instance is generated using the callback provided to * [blockItem], or the block if it's an [IFoundationBlock], or [BlockItem]. Item generation can be completely disabled * using [noItem]. */ public class BlockSpec( /** * The registry name, sans mod ID */ public var id: String ): IItemProvider, BlockPropertiesBuilder<BlockSpec> { /** * The mod ID to register this block under. This is populated by the [RegistrationManager]. */ public var modid: String = "" @JvmSynthetic internal set /** * The registry name of the block. The [mod ID][modid] is populated by the [RegistrationManager]. */ public val registryName: Identifier get() = Identifier(modid, id) /** * Whether a [BlockItem] should be registered for this block */ public var hasItem: Boolean = true private set /** * What render layer this block should be drawn in */ public var renderLayer: RenderLayerSpec = RenderLayerSpec.SOLID private set /** * What item group the [BlockItem] should be in */ public var itemGroup: ItemGroupSpec = ItemGroupSpec.DEFAULT private set /** * The information used during data generation */ public val datagen: DataGen = DataGen() private var blockConstructor: Function<BlockSpec, Block> = Function { BaseBlock(it.blockProperties) } private var itemConstructor: Function<BlockSpec, BlockItem>? = null /** Disables the registration of a [BlockItem] for this block */ public fun noItem(): BlockSpec = build { this.hasItem = false } /** Sets whether a [BlockItem] should be registered for this block */ public fun hasItem(value: Boolean): BlockSpec = build { this.hasItem = value } /** Sets the render layer this block should draw in */ public fun renderLayer(value: RenderLayerSpec): BlockSpec = build { this.renderLayer = value } /** * Sets the item group this block's item should be in */ public fun itemGroup(value: ItemGroupSpec): BlockSpec = build { this.itemGroup = value } /** * Sets the block constructor for deferred evaluation */ public fun block(constructor: Function<BlockSpec, Block>): BlockSpec = build { this.blockConstructor = constructor } /** * Sets the custom [BlockItem] constructor for deferred evaluation */ public fun blockItem(constructor: Function<BlockSpec, BlockItem>): BlockSpec = build { this.itemConstructor = constructor } public fun tileEntity(type: LazyTileEntityType<*>): BlockSpec = build { val tileSpec = type.spec ?: if (type.typeInstance == null) throw IllegalStateException("Can't add a block to a LazyTileEntityType that isn't initialized") else throw IllegalArgumentException("Can't add a block to a LazyTileEntityType that isn't backed by a Foundation TileEntitySpec") tileSpec._validBlocks.add(this.lazy) } /** * Configures the information used for data generation */ public fun datagen(data: Consumer<DataGen>): BlockSpec = build { data.accept(this.datagen) } /** * Configures the information used for data generation */ @JvmSynthetic public inline fun datagen(crossinline data: DataGen.() -> Unit): BlockSpec = datagen(Consumer { it.data() }) public override val blockProperties: FoundationBlockProperties = FoundationBlockProperties() //region item properties public var itemProperties: Item.Properties = Item.Properties() /** * Sets this item's food type */ public fun food(food: Food): BlockSpec = build { itemProperties.food(food) } /** * Sets the maximum stack size for this item */ public fun maxStackSize(maxStackSize: Int): BlockSpec = build { itemProperties.maxStackSize(maxStackSize) } /** * Sets the max damage (i.e. durability) of this item. This also implicitly sets the max stack size to 1. */ public fun maxDamage(maxDamage: Int): BlockSpec = build { itemProperties.maxDamage(maxDamage) } /** * Sets the container item for this item. e.g. bucket for a lava bucket, bottle for a dragon's breath, etc. This is * the item left behind in the crafting grid after a recipe completes. */ public fun containerItem(containerItem: Item): BlockSpec = build { itemProperties.containerItem(containerItem) } /** * Sets this item's rarity */ public fun rarity(rarity: Rarity): BlockSpec = build { itemProperties.rarity(rarity) } /** * Removes the ability to repair this item */ public fun setNoRepair(): BlockSpec = build { itemProperties.setNoRepair() } /** * Sets the tool level of this item */ public fun addToolType(type: ToolType, level: Int): BlockSpec = build { itemProperties.addToolType(type, level) } /** * Sets the [ItemStackTileEntityRenderer]. Note that [IBakedModel.isBuiltInRenderer] must return true for this to * be used. */ public fun setISTER(ister: Supplier<Callable<ItemStackTileEntityRenderer>>): BlockSpec = build { itemProperties.setISTER(ister) } //endregion /** * The lazily-evaluated [Block] instance */ public val blockInstance: Block by lazy { try { blockConstructor.apply(this).setRegistryName(registryName) } catch (e: Exception) { throw RuntimeException("Error instantiating block $registryName", e) } } /** * The lazily-evaluated [BlockItem] instance */ public val itemInstance: Item? by lazy { if (!hasItem) return@lazy null try { val item = itemConstructor?.apply(this) ?: (blockInstance as? IFoundationBlock)?.createBlockItem(itemProperties) ?: BlockItem(blockInstance, itemProperties) item.setRegistryName(registryName) } catch (e: Exception) { throw RuntimeException("Error instantiating block item $registryName", e) } } override fun asItem(): Item { return itemInstance ?: throw IllegalStateException("BlockSpec doesn't have an item") } public val lazy: LazyBlock = LazyBlock(this) /** * Information used when generating data */ public inner class DataGen { @get:JvmSynthetic internal var model: Consumer<BlockStateProvider>? = null private set @get:JvmSynthetic internal var itemModel: Consumer<ItemModelProvider>? = null private set @get:JvmSynthetic internal val names: MutableMap<String, String> = mutableMapOf() @get:JvmSynthetic internal val tags: MutableSet<ITag.INamedTag<Block>> = mutableSetOf() @get:JvmSynthetic internal val itemTags: MutableSet<ITag.INamedTag<Item>> = mutableSetOf() /** * The loot table generation options */ public val lootTable: LootDataGen = LootDataGen() /** * The block instance, for use in data generators */ public val block: Block get() = lazy.get() /** * The item instance, for use in data generators */ public val item: Item? get() = itemInstance /** * Sets the model generation function. Note: this will override [IFoundationBlock.generateBlockState]. */ public fun model(model: Consumer<BlockStateProvider>): DataGen { this.model = model return this } /** * Sets the model generation function. Note: this will override [IFoundationBlock.generateBlockState]. */ @JvmSynthetic public inline fun model(crossinline model: BlockStateProvider.() -> Unit): DataGen = model(Consumer { it.model() }) /** * Sets the item model generation function. Note: this will override [IFoundationItem.generateItemModel]. */ public fun itemModel(model: Consumer<ItemModelProvider>): DataGen { this.itemModel = model return this } /** * Sets the item model generation function. Note: this will override [IFoundationItem.generateItemModel]. */ @JvmSynthetic public inline fun itemModel(crossinline model: ItemModelProvider.() -> Unit): DataGen = itemModel(Consumer { it.model() }) /** * Sets the model generation function to create a simple cube block using the texture at * `yourmodid:block/blockid.png`. */ public fun simpleModel(): DataGen = model { simpleBlock(blockInstance) } /** * Sets the name of this block in the generated en_us lang file */ public fun name(name: String): DataGen = name("en_us", name) /** * Sets the name of this block in the generated lang file */ public fun name(locale: String, name: String): DataGen { this.names[locale] = name return this } /** * Adds the passed tags to this block */ public fun tags(vararg tags: ITag.INamedTag<Block>): DataGen { this.tags.addAll(tags) return this } /** * Adds the passed tags to this block's item */ public fun itemTags(vararg tags: ITag.INamedTag<Item>): DataGen { this.itemTags.addAll(tags) return this } } public inner class LootDataGen { @get:JvmSynthetic internal var generator: Consumer<BlockLootTableGenerator>? = null private set /** * Sets the loot table generation function. Note: this will override [IFoundationBlock.generateLootTable]. */ public fun custom(loot: Consumer<BlockLootTableGenerator>) { this.generator = loot } /** * Sets the loot table generation function. Note: this will override [IFoundationBlock.generateLootTable]. */ @JvmSynthetic public inline fun custom(crossinline loot: BlockLootTableGenerator.() -> Unit) { custom(Consumer { it.loot() }) } // shortcuts: // - drop self // - silk touch } private inline fun build(block: () -> Unit): BlockSpec { block() return this } }
modules/foundation/src/main/kotlin/com/teamwizardry/librarianlib/foundation/registration/BlockSpec.kt
1309544809
package com.riaektiv.cache.ignite import com.riaektiv.dao.markets.SectorDao import com.riaektiv.domain.markets.Sector import org.apache.ignite.Ignite import org.apache.ignite.Ignition import org.apache.ignite.cache.query.SqlQuery import org.apache.ignite.transactions.Transaction import org.junit.Before import org.junit.Test import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull /** * Coding With Passion Since 1991 * Created: 2/24/2017, 6:10 PM Eastern Time * @author Sergey Chuykov */ class SectorCacheStoreIntegrationTest : IgniteCacheTestSupport() { val SECTOR_CACHE: String = Sector::class.java.simpleName lateinit var ignite: Ignite @Before fun before() { ignite = Ignition.start("SectorCacheStoreIntegrationTest.xml") } @Test fun readThrough() { val cache = ignite.createCache<Long, Sector>(SECTOR_CACHE) // preload for (id in 1L..3L) { cache.get(id) } val sqlQuery = SqlQuery<Long, Sector>(Sector::class.java, "from Sector") val cursor = cache.query(sqlQuery) val sectors = mutableMapOf<Long, Sector>() for (entry in cursor) { sectors.put(entry.key, entry.value) } assertEquals("Basic Materials", sectors[1L]?.name) assertEquals("Financial", sectors[3L]?.name) ignite.close() } fun other(callback: () -> Unit): CountDownLatch { val latch = CountDownLatch(1) object : Thread("other") { override fun run() { callback() latch.countDown() } }.start() return latch } @Test fun writeThrough() { val ctx = ApplicationContextHolder.applicationContext val sector = Sector(7L, "Technology") val sectorDao = ctx.getBean(SectorDao::class.java) sectorDao.jdbcDelete(sector.id) val cache = ignite.createCache<Long, Sector>(SECTOR_CACHE) val transactions = ignite.transactions() var tx: Transaction? = null try { tx = transactions.txStart() l.info("before .put(): {}", cache.get(sector.id)) cache.put(sector.id, sector) l.info("after .put(): {}", cache.get(sector.id)) other { val found = cache.get(sector.id) l.info("other thread doesn't see the new cache entry before commit") l.info("get({})={}", sector.id, found) assertNull(found) }.await(1, TimeUnit.MINUTES) // wait for the reader thread l.info("tx.commit()") tx.commit() other { val found = cache.get(sector.id) l.info("found after commit") l.info("get({})={}", sector.id, found) assertNotNull(found) }.await(1, TimeUnit.MINUTES) // wait for the reader thread } catch (e: Exception) { l.error(e.message, e) if (tx != null) { tx.rollback() } } ignite.close() } }
incubator-cache/src/test/java/com/riaektiv/cache/ignite/SectorCacheStoreIntegrationTest.kt
3296550819
/* Copyright 2017-2020 Charles Korn. 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 batect.journeytests import batect.journeytests.testutils.ApplicationRunner import batect.journeytests.testutils.DockerUtils import batect.testutils.createForGroup import batect.testutils.on import batect.testutils.platformLineSeparator import batect.testutils.runBeforeGroup import com.natpryce.hamkrest.absent import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.contains import com.natpryce.hamkrest.containsSubstring import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.isEmpty import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.io.InputStreamReader object DontCleanupAfterSuccessTest : Spek({ describe("a task with a prerequisite") { val runner by createForGroup { ApplicationRunner("task-with-prerequisite") } val cleanupCommands by createForGroup { mutableListOf<String>() } val containersBeforeTest by runBeforeGroup { DockerUtils.getAllCreatedContainers() } val networksBeforeTest by runBeforeGroup { DockerUtils.getAllNetworks() } afterGroup { cleanupCommands.forEach { val commandLine = it.trim().split(" ") val exitCode = ProcessBuilder(commandLine) .start() .waitFor() assertThat(exitCode, equalTo(0)) } val containersAfterTest = DockerUtils.getAllCreatedContainers() val orphanedContainers = containersAfterTest - containersBeforeTest assertThat(orphanedContainers, isEmpty) val networksAfterTest = DockerUtils.getAllNetworks() val orphanedNetworks = networksAfterTest - networksBeforeTest assertThat(orphanedNetworks, isEmpty) } on("running that task with the '--no-cleanup-on-success' option") { val result by runBeforeGroup { runner.runApplication(listOf("--no-cleanup-after-success", "--no-color", "do-stuff")) } val commandsRegex = """For container build-env, view its output by running '(?<logsCommand>docker logs (?<id>.*))', or run a command in the container with '(.*)'\.""".toRegex() val cleanupRegex = """Once you have finished using the containers, clean up all temporary resources created by batect by running:$platformLineSeparator(?<command>(.|$platformLineSeparator)+)$platformLineSeparator""".toRegex() beforeGroup { val cleanupCommand = cleanupRegex.find(result.output)?.groups?.get("command")?.value if (cleanupCommand != null) { cleanupCommands.addAll(cleanupCommand.split("\n")) } } it("prints the output from the main task") { assertThat(result.output, containsSubstring("This is some output from the main task\r\n")) } it("prints the output from the prerequisite task") { assertThat(result.output, containsSubstring("This is some output from the build task\r\n")) } it("returns a non-zero exit code") { assertThat(result.exitCode, !equalTo(0)) } it("does not return the exit code from the task") { assertThat(result.exitCode, !equalTo(123)) } it("prints a message explaining how to see the logs of the container and how to run a command in the container") { assertThat(result.output, contains(commandsRegex)) } it("prints a message explaining how to clean up any containers left behind") { assertThat(result.output, contains(cleanupRegex)) } it("does not delete the container") { val containerId = commandsRegex.find(result.output)?.groups?.get("id")?.value assertThat(containerId, !absent<String>()) val inspectProcess = ProcessBuilder("docker", "inspect", containerId, "--format", "{{.State.Status}}") .redirectErrorStream(true) .start() inspectProcess.waitFor() assertThat(inspectProcess.exitValue(), equalTo(0)) assertThat(InputStreamReader(inspectProcess.inputStream).readText().trim(), equalTo("exited")) } it("the command given to view the logs displays the logs from the container") { val logsCommand = commandsRegex.find(result.output)?.groups?.get("logsCommand")?.value assertThat(logsCommand, !absent<String>()) val logsProcess = ProcessBuilder(logsCommand!!.trim().split(" ")) .redirectErrorStream(true) .start() logsProcess.waitFor() assertThat(InputStreamReader(logsProcess.inputStream).readText().trim(), equalTo("This is some output from the main task")) assertThat(logsProcess.exitValue(), equalTo(0)) } } } })
app/src/journeyTest/kotlin/batect/journeytests/DontCleanupAfterSuccessTest.kt
3996174778
package com.ddu.ui.fragment.work import android.content.Intent import android.net.Uri import android.os.Bundle import com.ddu.R import com.ddu.icore.common.ext.ctx import com.ddu.icore.ui.fragment.DefaultFragment import com.ddu.ui.activity.TestActivity import com.ddu.util.ToastUtils import kotlinx.android.synthetic.main.fragment_work_state.* import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import java.net.URLEncoder /** * Created by lhz on 16/4/6. */ class FragmentA : DefaultFragment() { private var schemeUrl: String? = null set(value) { startTo(value) } var yzbzzUrl: String? = null var httpUrl: String? = null var defaultData = "yzbzz://5" var login = "1" override fun initData(savedInstanceState: Bundle?) { yzbzzUrl = URLEncoder.encode("yzbzz://5?userId=3&phone=186xxx&t=εΌ δΈ‰", "utf-8") httpUrl = URLEncoder.encode("http://www.baidu.com?userId=3&phone=186xxx&t=εΌ δΈ‰", "utf-8") } override fun getLayoutId(): Int { return R.layout.fragment_work_state } override fun initView() { btn_ok.setOnClickListener { if (login.equals("1", ignoreCase = true)) { login = "0" ToastUtils.showToast("登录关闭") } else { login = "1" ToastUtils.showToast("登录开启") } } btn_yzbzz.setOnClickListener { schemeUrl = "yzbzz://3?login=$login" } btn_http.setOnClickListener { schemeUrl = "http://www.baidu.com" } btn_yzbzz_s_e.setOnClickListener { schemeUrl = "yzbzz://100?url=$yzbzzUrl&login=$login" } btn_yzbzz_s_h.setOnClickListener { schemeUrl = "yzbzz://100?url=$httpUrl&login=$login" } btn_yzbzz_s_d_e.setOnClickListener { defaultData = "yzbzz://2" schemeUrl = "yzbzz://101?login=$login" } btn_yzbzz_s_d_h.setOnClickListener { defaultData = "http://www.163.com" schemeUrl = "yzbzz://101?login=$login" } btn_yzbzz_s_d_error.setOnClickListener { defaultData = "yzbzz://102" schemeUrl = "yzbzz://101?login=$login" } btn_yzbzz_s_d_error_o.setOnClickListener { defaultData = "abc**102" schemeUrl = "yzbzz://101?login=$login" } } fun startTo(url: String?) { val intent = Intent(ctx, TestActivity::class.java) val uri = Uri.parse(url) intent.data = uri intent.putExtra("defaultData", defaultData) startActivity(intent) } companion object { fun newInstance(): FragmentA { val fragment = FragmentA() val args = Bundle() fragment.arguments = args return fragment } } fun appendUrl(url: String?, urlParams: Map<String, String>?): String { if (null == url) { return "" } if (urlParams == null || urlParams.size <= 0) { return url } val httpUrl = url!!.toHttpUrlOrNull() ?: return url val urlBuilder = httpUrl.newBuilder() for ((key, value) in urlParams) { urlBuilder.addQueryParameter(key, value) } return urlBuilder.build().toString() } }
app/src/main/java/com/ddu/ui/fragment/work/FragmentA.kt
321258308
/** * An emphasised class. * * _This class [Bar] is awesome._ * * _Even more awesomer is the function [Bar.foo]_ * * _[Bar.hello] is also OK_ */ class Bar { fun foo() {} fun hello() {} }
core/testdata/format/linksInEmphasis.kt
278190534
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.maps.android.compose import android.util.Log import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.test.* import androidx.compose.ui.test.junit4.createComposeRule import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.LatLng import org.junit.Assert.* import org.junit.Before import org.junit.Rule import org.junit.Test import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit private const val TAG = "MapInColumnTests" class MapInColumnTests { @get:Rule val composeTestRule = createComposeRule() private val startingZoom = 10f private val startingPosition = LatLng(1.23, 4.56) private lateinit var cameraPositionState: CameraPositionState private fun initMap(content: @Composable () -> Unit = {}) { val countDownLatch = CountDownLatch(1) composeTestRule.setContent { var scrollingEnabled by remember { mutableStateOf(true) } LaunchedEffect(cameraPositionState.isMoving) { if (!cameraPositionState.isMoving) { scrollingEnabled = true Log.d(TAG, "Map camera stopped moving - Enabling column scrolling...") } } MapInColumn( modifier = Modifier.fillMaxSize(), cameraPositionState, columnScrollingEnabled = scrollingEnabled, onMapTouched = { scrollingEnabled = false Log.d( TAG, "User touched map - Disabling column scrolling after user touched this Box..." ) }, onMapLoaded = { countDownLatch.countDown() } ) } val mapLoaded = countDownLatch.await(30, TimeUnit.SECONDS) assertTrue("Map loaded", mapLoaded) } @Before fun setUp() { cameraPositionState = CameraPositionState( position = CameraPosition.fromLatLngZoom( startingPosition, startingZoom ) ) } @Test fun testStartingCameraPosition() { initMap() startingPosition.assertEquals(cameraPositionState.position.target) } @Test fun testLatLngInVisibleRegion() { initMap() composeTestRule.runOnUiThread { val projection = cameraPositionState.projection assertNotNull(projection) assertTrue( projection!!.visibleRegion.latLngBounds.contains(startingPosition) ) } } @Test fun testLatLngNotInVisibleRegion() { initMap() composeTestRule.runOnUiThread { val projection = cameraPositionState.projection assertNotNull(projection) val latLng = LatLng(23.4, 25.6) assertFalse( projection!!.visibleRegion.latLngBounds.contains(latLng) ) } } // FIXME: https://github.com/googlemaps/android-maps-compose/issues/174 // @Test // fun testScrollColumn_MapCameraRemainsSame() { // initMap() // // Check that the column scrolls to the last item // composeTestRule.onRoot().performTouchInput { swipeUp() } // composeTestRule.waitForIdle() // composeTestRule.onNodeWithTag("Item 1").assertIsNotDisplayed() // // // Check that the map didn't change // startingPosition.assertEquals(cameraPositionState.position.target) // } // @Test // fun testPanMapUp_MapCameraChangesColumnDoesNotScroll() { // initMap() // // Swipe the map up // // FIXME - for some reason this scrolls the entire column instead of just the map // composeTestRule.onNodeWithTag("Map").performTouchInput { swipeUp() } // composeTestRule.waitForIdle() // // // Make sure that the map changed (i.e., we can scroll the map in the column) // startingPosition.assertNotEquals(cameraPositionState.position.target) // // // Check to make sure column didn't scroll // composeTestRule.onNodeWithTag("Item 1").assertIsDisplayed() // } }
app/src/androidTest/java/com/google/maps/android/compose/MapInColumnTests.kt
2415602944
/* Copyright 2017-2020 Charles Korn. 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 batect.config import batect.config.io.ConfigurationException import batect.config.io.deserializers.tryToDeserializeWith import com.charleskorn.kaml.YamlInput import kotlinx.serialization.CompositeDecoder import kotlinx.serialization.Decoder import kotlinx.serialization.Encoder import kotlinx.serialization.KSerializer import kotlinx.serialization.SerialDescriptor import kotlinx.serialization.Serializable import kotlinx.serialization.SerializationException import kotlinx.serialization.Serializer import kotlinx.serialization.internal.SerialClassDescImpl import kotlinx.serialization.internal.StringDescriptor import kotlinx.serialization.internal.StringSerializer import kotlinx.serialization.internal.nullable @Serializable(with = DeviceMount.Companion::class) data class DeviceMount( val localPath: String, val containerPath: String, val options: String? = null ) { override fun toString(): String { if (options == null) { return "$localPath:$containerPath" } else { return "$localPath:$containerPath:$options" } } @Serializer(forClass = DeviceMount::class) companion object : KSerializer<DeviceMount> { override val descriptor: SerialDescriptor = object : SerialClassDescImpl("DeviceMount") { init { addElement("local") addElement("container") addElement("options", isOptional = true) } } private val localPathFieldIndex = descriptor.getElementIndex("local") private val containerPathFieldIndex = descriptor.getElementIndex("container") private val optionsFieldIndex = descriptor.getElementIndex("options") override fun deserialize(decoder: Decoder): DeviceMount { if (decoder !is YamlInput) { throw UnsupportedOperationException("Can only deserialize from YAML source.") } return decoder.tryToDeserializeWith(descriptor) { deserializeFromObject(it) } ?: decoder.tryToDeserializeWith(StringDescriptor) { deserializeFromString(it) } ?: throw ConfigurationException("Device mount definition is not valid. It must either be an object or a literal in the form 'local_path:container_path' or 'local_path:container_path:options'.") } private fun deserializeFromString(input: YamlInput): DeviceMount { val value = input.decodeString() if (value == "") { throw ConfigurationException("Device mount definition cannot be empty.", input.node.location.line, input.node.location.column) } val regex = """(([a-zA-Z]:\\)?[^:]+):([^:]+)(:([^:]+))?""".toRegex() val match = regex.matchEntire(value) if (match == null) { throw invalidMountDefinitionException(value, input) } val local = match.groupValues[1] val container = match.groupValues[3] val options = match.groupValues[5].takeIf { it.isNotEmpty() } return DeviceMount(local, container, options) } private fun invalidMountDefinitionException(value: String, input: YamlInput) = ConfigurationException( "Device mount definition '$value' is not valid. It must be in the form 'local_path:container_path' or 'local_path:container_path:options'.", input.node.location.line, input.node.location.column ) private fun deserializeFromObject(input: YamlInput): DeviceMount { var localPath: String? = null var containerPath: String? = null var options: String? = null loop@ while (true) { when (val i = input.decodeElementIndex(descriptor)) { CompositeDecoder.READ_DONE -> break@loop localPathFieldIndex -> localPath = input.decodeStringElement(descriptor, i) containerPathFieldIndex -> containerPath = input.decodeStringElement(descriptor, i) optionsFieldIndex -> options = input.decodeStringElement(descriptor, i) else -> throw SerializationException("Unknown index $i") } } if (localPath == null) { throw ConfigurationException("Field '${descriptor.getElementName(localPathFieldIndex)}' is required but it is missing.", input.node.location.line, input.node.location.column) } if (containerPath == null) { throw ConfigurationException("Field '${descriptor.getElementName(containerPathFieldIndex)}' is required but it is missing.", input.node.location.line, input.node.location.column) } return DeviceMount(localPath, containerPath, options) } override fun serialize(encoder: Encoder, obj: DeviceMount) { val output = encoder.beginStructure(descriptor) output.encodeStringElement(descriptor, localPathFieldIndex, obj.localPath) output.encodeStringElement(descriptor, containerPathFieldIndex, obj.containerPath) output.encodeSerializableElement(descriptor, optionsFieldIndex, StringSerializer.nullable, obj.options) output.endStructure(descriptor) } } }
app/src/main/kotlin/batect/config/DeviceMount.kt
2926057171
package com.stevenschoen.putionew.files import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import android.widget.TextView import com.stevenschoen.putionew.R class FileTitleBarView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { private val titleView: TextView private val backView: View init { View.inflate(context, R.layout.file_title_bar, this) titleView = findViewById(R.id.file_title_bar_name) backView = findViewById(R.id.file_title_bar_back) } var title: CharSequence set(value) { titleView.text = value } get() = titleView.text }
app/src/main/java/com/stevenschoen/putionew/files/FileTitleBarView.kt
1085184122
/* * Copyright (C) 2019 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.activity.integration.testapp import android.Manifest.permission.ACCESS_FINE_LOCATION import android.app.Activity import android.app.PendingIntent import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.view.View import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.view.ViewManager import android.widget.Button import android.widget.LinearLayout import android.widget.LinearLayout.VERTICAL import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.IntentSenderRequest import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts.CaptureVideo import androidx.activity.result.contract.ActivityResultContracts.CreateDocument import androidx.activity.result.contract.ActivityResultContracts.GetContent import androidx.activity.result.contract.ActivityResultContracts.OpenMultipleDocuments import androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia import androidx.activity.result.contract.ActivityResultContracts.PickMultipleVisualMedia import androidx.activity.result.contract.ActivityResultContracts.RequestPermission import androidx.activity.result.contract.ActivityResultContracts.TakePicture import androidx.activity.result.contract.ActivityResultContracts.TakePicturePreview import androidx.activity.result.launch import androidx.activity.result.registerForActivityResult import androidx.core.content.FileProvider import java.io.File class MainActivity : ComponentActivity() { val requestLocation = registerForActivityResult( RequestPermission(), ACCESS_FINE_LOCATION ) { isGranted -> toast("Location granted: $isGranted") } val takePicturePreview = registerForActivityResult(TakePicturePreview()) { bitmap -> toast("Got picture: $bitmap") } val takePicture = registerForActivityResult(TakePicture()) { success -> toast("Got picture: $success") } val captureVideo: ActivityResultLauncher<Uri> = registerForActivityResult( CaptureVideo() ) { success -> toast("Got video: $success") } val getContent: ActivityResultLauncher<String> = registerForActivityResult( GetContent() ) { uri -> toast("Got image: $uri") } lateinit var pickVisualMedia: ActivityResultLauncher<PickVisualMediaRequest> lateinit var pickMultipleVisualMedia: ActivityResultLauncher<PickVisualMediaRequest> lateinit var createDocument: ActivityResultLauncher<String> lateinit var openDocuments: ActivityResultLauncher<Array<String>> private val intentSender = registerForActivityResult( ActivityResultContracts .StartIntentSenderForResult() ) { toast("Received intent sender callback") } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (android.os.Build.VERSION.SDK_INT >= 19) { pickVisualMedia = registerForActivityResult(PickVisualMedia()) { uri -> toast("Got image: $uri") } pickMultipleVisualMedia = registerForActivityResult(PickMultipleVisualMedia(5)) { uris -> var media = "" uris.forEach { media += "uri: $it \n" } toast("Got media files: $media") } createDocument = registerForActivityResult(CreateDocument("image/png")) { uri -> toast("Created document: $uri") } openDocuments = registerForActivityResult(OpenMultipleDocuments()) { uris -> var docs = "" uris.forEach { docs += "uri: $it \n" } toast("Got documents: $docs") } } setContentView { add(::LinearLayout) { orientation = VERTICAL button("Request location permission") { requestLocation.launch() } button("Get picture thumbnail") { takePicturePreview.launch() } button("Take pic") { val file = File(filesDir, "image") val uri = FileProvider.getUriForFile(this@MainActivity, packageName, file) takePicture.launch(uri) } button("Capture video") { val file = File(filesDir, "video") val uri = FileProvider.getUriForFile(this@MainActivity, packageName, file) captureVideo.launch(uri) } button("Pick an image (w/ GET_CONTENT)") { getContent.launch("image/*") } if (android.os.Build.VERSION.SDK_INT >= 19) { button("Pick an image (w/ photo picker)") { pickVisualMedia.launch( PickVisualMediaRequest(PickVisualMedia.ImageOnly) ) } button("Pick a GIF (w/ photo picker)") { pickVisualMedia.launch( PickVisualMediaRequest(PickVisualMedia.SingleMimeType("image/gif")) ) } button("Pick 5 visual media max (w/ photo picker)") { pickMultipleVisualMedia.launch( PickVisualMediaRequest(PickVisualMedia.ImageAndVideo) ) } button("Create document") { createDocument.launch("Temp") } button("Open documents") { openDocuments.launch(arrayOf("*/*")) } } button("Start IntentSender") { val request = IntentSenderRequest.Builder( PendingIntent.getActivity( context, 0, Intent(MediaStore.ACTION_IMAGE_CAPTURE), 0 ).intentSender ) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK, 1) .build() intentSender.launch(request) } } } } } fun Context.toast(msg: String) { Toast.makeText(this, msg, Toast.LENGTH_LONG).show() } inline fun Activity.setContentView(ui: ViewManager.() -> Unit) = ActivityViewManager(this).apply(ui) class ActivityViewManager(val activity: Activity) : ViewManager { override fun addView(p0: View?, p1: ViewGroup.LayoutParams?) { activity.setContentView(p0) } override fun updateViewLayout(p0: View?, p1: ViewGroup.LayoutParams?) { TODO("not implemented") } override fun removeView(p0: View?) { TODO("not implemented") } } val ViewManager.context get() = when (this) { is View -> context is ActivityViewManager -> activity else -> TODO() } fun <VM : ViewManager, V : View> VM.add(construct: (Context) -> V, init: V.() -> Unit) { construct(context).apply(init).also { addView(it, ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT)) } } fun ViewManager.button(txt: String, listener: (View) -> Unit) { add(::Button) { text = txt setOnClickListener(listener) } }
activity/integration-tests/testapp/src/main/java/androidx/activity/integration/testapp/MainActivity.kt
2873250510
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("UnstableApiUsage") package androidx.compose.ui.lint import com.android.tools.lint.client.api.LintClient import com.android.tools.lint.detector.api.CURRENT_API import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class ApiLintVersionsTest { @Test fun versionsCheck() { LintClient.clientName = LintClient.CLIENT_UNIT_TESTS val registry = UiIssueRegistry() assertThat(registry.api).isEqualTo(CURRENT_API) assertThat(registry.minApi).isEqualTo(10) } }
compose/ui/ui-lint/src/test/java/androidx/compose/ui/lint/ApiLintVersionsTest.kt
950571136
package totoro.yui.db data class Occurence(val id: Long, val chain: String, val word: String, val author: String)
src/main/kotlin/totoro/yui/db/Occurence.kt
1013852750
public class ArrayList<T> fun main(args: Array<String>) { val list = ArrayList<caret><String>() }
kotlin-eclipse-ui-test/testData/completion/autoimport/packageArrayListAutoImport.kt
2443189991
/* * Copyright (C) 2021 pedroSG94. * * 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.pedro.rtmp.amf.v0 import java.io.IOException import java.io.InputStream import java.io.OutputStream import kotlin.jvm.Throws /** * Created by pedro on 20/04/21. * * Contain an empty body */ class AmfNull: AmfData() { @Throws(IOException::class) override fun readBody(input: InputStream) { //no body to read } @Throws(IOException::class) override fun writeBody(output: OutputStream) { //no body to write } override fun getType(): AmfType = AmfType.NULL override fun getSize(): Int = 0 override fun toString(): String { return "AmfNull" } }
rtmp/src/main/java/com/pedro/rtmp/amf/v0/AmfNull.kt
2707772301
package io.mockk.impl.instantiation import io.mockk.InternalPlatformDsl.toStr import io.mockk.impl.log.Logger import io.mockk.proxy.MockKInstantiatior import kotlin.reflect.KClass class JvmInstantiator( val instantiator: MockKInstantiatior, instanceFactoryRegistry: CommonInstanceFactoryRegistry ) : AbstractInstantiator(instanceFactoryRegistry) { override fun <T : Any> instantiate(cls: KClass<T>): T { log.trace { "Building empty instance ${cls.toStr()}" } return instantiateViaInstanceFactoryRegistry(cls) { instantiator.instance(cls.java) } } companion object { val log = Logger<JvmInstantiator>() } }
mockk/jvm/src/main/kotlin/io/mockk/impl/instantiation/JvmInstantiator.kt
4051405374
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengl.templates import org.lwjgl.generator.* import org.lwjgl.opengl.* val NV_blend_equation_advanced = "NVBlendEquationAdvanced".nativeClassGL("NV_blend_equation_advanced", postfix = NV) { documentation = """ Native bindings to the $registryLink extension. This extension adds a number of "advanced" blending equations that can be used to perform new color blending operations, many of which are more complex than the standard blend modes provided by unextended OpenGL. Provides the new blending equations, but guarantees defined results only if each sample is touched no more than once in any single rendering pass. The command #BlendBarrierNV() is provided to indicate a boundary between passes. Requires ${GL20.core}. """ IntConstant( """ Accepted by the {@code pname} parameter of BlendParameteriNV, GetBooleanv, GetIntegerv, GetInteger64v, GetFloatv, and GetDoublev. """, "BLEND_PREMULTIPLIED_SRC_NV"..0x9280, "BLEND_OVERLAP_NV"..0x9281 ) IntConstant( """ Accepted by the {@code value} parameter of BlendParameteriNV when {@code pname} is BLEND_OVERLAP_NV. """, "UNCORRELATED_NV"..0x8521, "DISJOINT_NV"..0x9283, "CONJOINT_NV"..0x9284 ) IntConstant( """ Accepted by the {@code mode} parameter of BlendEquation and BlendEquationi. """, "SRC_NV"..0x9286, "DST_NV"..0x9287, "SRC_OVER_NV"..0x9288, "DST_OVER_NV"..0x9289, "SRC_IN_NV"..0x928A, "DST_IN_NV"..0x928B, "SRC_OUT_NV"..0x928C, "DST_OUT_NV"..0x928D, "SRC_ATOP_NV"..0x928E, "DST_ATOP_NV"..0x928F, "XOR_NV"..0x1506, "MULTIPLY_NV"..0x9294, "SCREEN_NV"..0x9295, "OVERLAY_NV"..0x9296, "DARKEN_NV"..0x9297, "LIGHTEN_NV"..0x9298, "COLORDODGE_NV"..0x9299, "COLORBURN_NV"..0x929A, "HARDLIGHT_NV"..0x929B, "SOFTLIGHT_NV"..0x929C, "DIFFERENCE_NV"..0x929E, "EXCLUSION_NV"..0x92A0, "INVERT_RGB_NV"..0x92A3, "LINEARDODGE_NV"..0x92A4, "LINEARBURN_NV"..0x92A5, "VIVIDLIGHT_NV"..0x92A6, "LINEARLIGHT_NV"..0x92A7, "PINLIGHT_NV"..0x92A8, "HARDMIX_NV"..0x92A9, "HSL_HUE_NV"..0x92AD, "HSL_SATURATION_NV"..0x92AE, "HSL_COLOR_NV"..0x92AF, "HSL_LUMINOSITY_NV"..0x92B0, "PLUS_NV"..0x9291, "PLUS_CLAMPED_NV"..0x92B1, "PLUS_CLAMPED_ALPHA_NV"..0x92B2, "PLUS_DARKER_NV"..0x9292, "MINUS_NV"..0x929F, "MINUS_CLAMPED_NV"..0x92B3, "CONTRAST_NV"..0x92A1, "INVERT_OVG_NV"..0x92B4, "RED_NV"..0x1903, "GREEN_NV"..0x1904, "BLUE_NV"..0x1905 ) void( "BlendParameteriNV", "", GLenum.IN("pname", ""), GLint.IN("value", "") ) void( "BlendBarrierNV", "" ) } val NV_blend_equation_advanced_coherent = "NVBlendEquationAdvancedCoherent".nativeClassGL("NV_blend_equation_advanced_coherent", postfix = NV) { documentation = """ Native bindings to the ${registryLink("NV", "blend_equation_advanced")} extension. Similar to NV_blend_equation_advanced, but guarantees that blending is done coherently and in API primitive ordering. An enable is provided to allow implementations to opt out of fully coherent blending and instead behave as though only NV_blend_equation_advanced were supported. Requires ${GL20.core} and ${NV_blend_equation_advanced.link}. """ IntConstant( """ Accepted by the {@code cap} parameter of Disable, Enable, and IsEnabled, and by the {@code pname} parameter of GetIntegerv, GetBooleanv, GetFloatv, GetDoublev and GetInteger64v. """, "BLEND_ADVANCED_COHERENT_NV"..0x9285 ) }
modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/NV_blend_equation_advanced.kt
625672224
package com.example.kotlin_and_swift import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
shapes/kotlin_and_swift_direct/kotlin/app/src/test/java/com/example/kotlin_and_swift/ExampleUnitTest.kt
1650743313
package io.github.initrc.bootstrap.api import io.github.initrc.bootstrap.model.PhotoResponse import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query /** * Pixabay photo service. */ interface PhotoService { @GET("api") fun getPhotos(@Query("q") query: String, @Query("page") page: Int, @Query("editors_choice") editorsChoice: Boolean = ApiConstants.editorsChoice, @Query("key") key: String = ApiSecrets.key) : Call<PhotoResponse> }
app/src/main/java/io/github/initrc/bootstrap/api/PhotoService.kt
1344653165
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.car.communication.messagingsync import android.content.Context import android.content.SharedPreferences import com.google.android.libraries.car.notifications.NotificationAccessUtils import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch /** * Provides util methods for Messaging Sync Feature */ internal class MessagingUtils constructor(private val context: Context) { private val enabledCars get() = sharedPreferences .getStringSet(ENABLED_CARS_KEY, mutableSetOf()) ?: mutableSetOf() private val sharedPreferences get() = context.getSharedPreferences( MESSAGING_SYNC_SHARED_PREFERENCE_KEY, Context.MODE_PRIVATE ) fun isMessagingSyncEnabled(carId: String) = enabledCars.contains(carId) && NotificationAccessUtils.hasNotificationAccess(context) fun isNotificationAccessEnabled() = NotificationAccessUtils.hasNotificationAccess(context) /** * Handles the user flow to request user permissions and turn on messaging sync. */ fun enableMessagingSync(carId: String, onSuccess: () -> Unit, onFailure: (() -> Unit)?) = CoroutineScope(Dispatchers.Main).launch { val notificationGranted = NotificationAccessUtils.requestNotificationAccess(context) if (notificationGranted) { enableMessagingSyncSharedPreferences(carId) DebugLogs.logMessagingSyncFeatureEnabled() onSuccess() } else { onFailure?.let { it() } } } /** * Turns off messaging sync feature. */ fun disableMessagingSync(carId: String) = sharedPreferences.putStringSet( ENABLED_CARS_KEY, enabledCars.apply { remove(carId) } ).also { DebugLogs.logMessagingSyncFeatureDisabled() } private fun enableMessagingSyncSharedPreferences(carId: String) = sharedPreferences.putStringSet( ENABLED_CARS_KEY, enabledCars.apply { add(carId) } ) private fun SharedPreferences.putStringSet(key: String, set: Set<String>) = edit().putStringSet(key, set).apply() companion object { private const val MESSAGING_SYNC_SHARED_PREFERENCE_KEY = "TrustedDevice.MessagingSyncPreferences" private const val ENABLED_CARS_KEY = "enabledCars" private const val MESSAGING_APP_LIST_FEATURE_FLAG_ENABLED = false } }
communication/src/com/google/android/libraries/car/communication/messagingsync/MessagingUtils.kt
927042835
package ru.fantlab.android.ui.modules.classificator import ru.fantlab.android.ui.base.mvp.BaseMvp interface ClassificatorPagerMvp { interface View : BaseMvp.View { fun onSelected(extra: Int, add: Boolean) fun onSetBadge(tabIndex: Int, count: Int) fun onClassSended() } interface Presenter : BaseMvp.Presenter { fun onSendClassification(workId: Int, query: String) } }
app/src/main/kotlin/ru/fantlab/android/ui/modules/classificator/ClassificatorPagerMvp.kt
1689245364
package com.handstandsam.shoppingapp.multiplatform import com.handstandsam.shoppingapp.di.BaseNetworkGraph import com.handstandsam.shoppingapp.models.LoginRequest import com.handstandsam.shoppingapp.models.NetworkConfig import com.handstandsam.shoppingapp.models.User import com.handstandsam.shoppingapp.network.Response import com.handstandsam.shoppingapp.repository.UserRepo import io.ktor.client.HttpClient class KtorHttpClient { private val httpClient: HttpClient = HttpClient(Platform().ktorHttpClientEngine) val networkGraph: BaseNetworkGraph = object : BaseNetworkGraph( networkConfig = NetworkConfig( baseUrl = "https://shopping-app.s3.amazonaws.com", isMockServer = false, port = 443 ), ktorClient = httpClient ) { /** * Our S3 server can't support POST calls, * so we are just returning a mock for this call. */ override val userRepo: UserRepo = object : UserRepo { override suspend fun login(loginRequest: LoginRequest): Response<User> { return Response.Success( User( firstname = "Live", lastname = "User" ) ) } } } }
multiplatform/src/commonMain/kotlin/com/handstandsam/shoppingapp/multiplatform/KtorHttpClient.kt
2086427741
// Copyright 2022 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.panelmatch.client.exchangetasks import org.wfanet.measurement.api.v2alpha.ExchangeStepAttempt.State /** * Exception to be thrown by exchange tasks upon failure. Allows the task to specify [attemptState], * for example if the attempt should result in a permanent step failure. */ class ExchangeTaskFailedException private constructor(cause: Throwable, val attemptState: State) : Exception(cause) { companion object { /** * Returns an [ExchangeTaskFailedException] with a transient [attemptState], allowing the step * to retry. */ fun ofTransient(cause: Throwable): ExchangeTaskFailedException = ExchangeTaskFailedException(cause, State.FAILED) /** * Returns an [ExchangeTaskFailedException] with a permanent [attemptState], which will mark the * entire exchange as failed. */ fun ofPermanent(cause: Throwable): ExchangeTaskFailedException = ExchangeTaskFailedException(cause, State.FAILED_STEP) } }
src/main/kotlin/org/wfanet/panelmatch/client/exchangetasks/ExchangeTaskFailedException.kt
2940921360
package at.ac.tuwien.caa.docscan.log import android.util.Log import at.ac.tuwien.caa.docscan.logic.PreferencesHandler import com.google.firebase.crashlytics.FirebaseCrashlytics import timber.log.Timber /** * A timber tree which records all [Timber.e] calls with [FirebaseCrashlytics]. */ class FirebaseCrashlyticsTimberTree( private val preferencesHandler: PreferencesHandler ) : Timber.Tree() { companion object { val LOGGABLE_PRIORITIES = listOf(Log.ERROR) } override fun isLoggable(tag: String?, priority: Int): Boolean { if (!preferencesHandler.isCrashReportingEnabled) return false return LOGGABLE_PRIORITIES.contains(priority) } override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { FirebaseCrashlytics.getInstance().log((tag ?: "") + message) t?.let { FirebaseCrashlytics.getInstance().recordException(it) } } }
app/src/main/java/at/ac/tuwien/caa/docscan/log/FirebaseCrashlyticsTimberTree.kt
2602318647
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate") package com.commonsense.android.kotlin.system.logging import com.commonsense.android.kotlin.base.extensions.* /** * Created by Kasper Tvede on 03-06-2018. * Purpose: * A simple Logger that prints the content rather than for example use the android Logger */ object PrintLogger { fun printLog(tag: String, message: String, throwable: Throwable?) { println("$tag:\r\n$message\r\n${throwable?.stackTraceToString()}") } fun addToAllLoggers() { L.warningLoggers.add(::printLog) L.errorLoggers.add(::printLog) L.debugLoggers.add(::printLog) } }
system/src/main/kotlin/com/commonsense/android/kotlin/system/logging/PrintLogger.kt
4082568209
package barinek.bigstar.metrics import com.fasterxml.jackson.databind.ObjectMapper import io.barinek.bigstar.jdbc.DataSourceConfig import io.barinek.bigstar.metrics.Metrics import io.barinek.bigstar.rest.BasicApp import io.barinek.bigstar.rest.RestTemplate import org.eclipse.jetty.server.Handler import org.eclipse.jetty.server.handler.HandlerList import org.eclipse.jetty.servlet.ServletContextHandler import org.eclipse.jetty.servlet.ServletHolder import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.springframework.context.annotation.Configuration import org.springframework.http.converter.HttpMessageConverter import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter import org.springframework.web.context.ContextLoaderListener import org.springframework.web.context.WebApplicationContext import org.springframework.web.context.support.AnnotationConfigWebApplicationContext import org.springframework.web.servlet.DispatcherServlet import org.springframework.web.servlet.config.annotation.EnableWebMvc import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter open class MetricsControllerTest() { var app: TestApp = TestApp() @Before fun setUp() { DataSourceConfig().getJdbcTemplate().execute("delete from accounts") app.start() } @After fun tearDown() { app.stop() } @Test fun testGetMetrics() { DataSourceConfig().getJdbcTemplate().update(""" insert into accounts (name, total_contract_value) values ('John\'s Grocery, Inc.', 6000000), ('Hamburg Inn No. 2', 0), ('Record Collector', 1400000) """) val port = 8081 val response = RestTemplate().doGet("http://localhost:$port/api/metrics") val metrics = ObjectMapper().readValue(response, Metrics::class.java) assertEquals(3, metrics.numberOfAccounts) assertEquals(7400000.00, metrics.totalContractValue, 0.0) } /// class TestApp : BasicApp() { override fun getPort(): Int { return 8081 } override fun handlerList(): HandlerList { val list = HandlerList() list.addHandler(getServletContextHandler(getContext())) return list } private fun getServletContextHandler(context: WebApplicationContext): Handler { return ServletContextHandler().apply { contextPath = "/" addServlet(ServletHolder(DispatcherServlet(context)), "/*") addEventListener(ContextLoaderListener(context)) } } private fun getContext(): WebApplicationContext { return AnnotationConfigWebApplicationContext().apply { setConfigLocation("io.barinek.bigstar.metrics,io.barinek.bigstar.jdbc,barinek.bigstar.metrics") } } } @Configuration @EnableWebMvc open class WebConfig : WebMvcConfigurerAdapter() { override fun configureMessageConverters(converters: MutableList<HttpMessageConverter<*>>) { converters.add(MappingJackson2HttpMessageConverter(ObjectMapper())) } } }
components/metrics/tests/barinek/bigstar/metrics/MetricsControllerTest.kt
3964160724
package com.nurkiewicz.tsclass.parser.ast data class Type(val name: String, val stackSize: Int) { constructor(name: String?) : this( name ?: "void", if(name == "number") 2 else 1 ) fun toJavaType(): org.objectweb.asm.Type { return when (name) { "number" -> org.objectweb.asm.Type.DOUBLE_TYPE "string" -> org.objectweb.asm.Type.getType(String::class.java) else -> throw IllegalArgumentException("Uknown type: " + name) } } override fun toString() = "$name[$stackSize]" companion object { val number = Type("number", 2) } }
src/main/kotlin/com/nurkiewicz/tsclass/parser/ast/Type.kt
3896199214
package de.tum.`in`.tumcampusapp.component.ui.ticket import android.content.Context import androidx.annotation.Size import com.stripe.android.EphemeralKeyProvider import com.stripe.android.EphemeralKeyUpdateListener import de.tum.`in`.tumcampusapp.api.app.TUMCabeClient import de.tum.`in`.tumcampusapp.api.app.exception.NoPrivateKey import de.tum.`in`.tumcampusapp.utils.Utils import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* class TicketEphemeralKeyProvider( private val context: Context, private val onStringResponse: (String) -> Unit ) : EphemeralKeyProvider { override fun createEphemeralKey( @Size(min = 4) apiVersion: String, keyUpdateListener: EphemeralKeyUpdateListener ) { try { TUMCabeClient.getInstance(context).retrieveEphemeralKey(context, apiVersion, object : Callback<HashMap<String, Any>> { override fun onResponse( call: Call<HashMap<String, Any>>, response: Response<HashMap<String, Any>> ) { val responseBody = response.body() if (responseBody != null) { val id = responseBody.toString() keyUpdateListener.onKeyUpdate(id) onStringResponse(id) } } override fun onFailure(call: Call<HashMap<String, Any>>, throwable: Throwable) { Utils.log(throwable) } }) } catch (e: NoPrivateKey) { Utils.log(e) } } }
app/src/main/java/de/tum/in/tumcampusapp/component/ui/ticket/TicketEphemeralKeyProvider.kt
3157253709
package com.intfocus.template.model.response.asset import com.google.gson.annotations.SerializedName import com.intfocus.template.model.response.BaseResult /** * Created by liuruilin on 2017/8/12. */ class AssetsResult : BaseResult() { @SerializedName("data") var data: AssetsMD5? = null }
app/src/main/java/com/intfocus/template/model/response/asset/AssetsResult.kt
2829173061
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plugins.plsqlopen.api.statements import com.felipebz.flr.tests.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.sonar.plugins.plsqlopen.api.PlSqlGrammar import org.sonar.plugins.plsqlopen.api.RuleTest class RollbackStatementTest : RuleTest() { @BeforeEach fun init() { setRootRule(PlSqlGrammar.ROLLBACK_STATEMENT) } @Test fun matchesSimpleRollback() { assertThat(p).matches("rollback;") } @Test fun matchesRollbackWork() { assertThat(p).matches("rollback work;") } @Test fun matchesRollbackForce() { assertThat(p).matches("rollback force 'test';") } @Test fun matchesRollbackToSavepoint() { assertThat(p).matches("rollback to save;") } @Test fun matchesRollbackToSavepointAlternative() { assertThat(p).matches("rollback to savepoint save;") } @Test fun matchesLongRollbackStatement() { assertThat(p).matches("rollback work to savepoint save;") } @Test fun matchesLabeledRollback() { assertThat(p).matches("<<foo>> rollback;") } }
zpa-core/src/test/kotlin/org/sonar/plugins/plsqlopen/api/statements/RollbackStatementTest.kt
3052446074
package io.github.andyswe.elva.data import java.util.* import javax.persistence.* /** * Created by andreas on 2017-09-06. */ @Entity @Cacheable @org.springframework.cache.annotation.Cacheable data class Measurement( @Id @Temporal(TemporalType.TIMESTAMP) val timestamp: Date, val power: Int, val elTotal: Int, val vaTotal: Int) { }
src/main/kotlin/io/github/andyswe/elva/data/Measurement.kt
853089559
package com.intfocus.template.subject.seven.listener /** * **************************************************** * author jameswong * created on: 17/12/21 δΈ‹εˆ5:11 * e-mail: [email protected] * name: * desc: * **************************************************** */ interface ConcernListItemClickListener { fun itemClick(pos: Int) }
app/src/main/java/com/intfocus/template/subject/seven/listener/ConcernListItemClickListener.kt
30641980
package de.tum.`in`.tumcampusapp.component.ui.tufilm import de.tum.`in`.tumcampusapp.api.tumonline.CacheControl import de.tum.`in`.tumcampusapp.component.ui.tufilm.repository.KinoRemoteRepository import de.tum.`in`.tumcampusapp.service.DownloadWorker import javax.inject.Inject class FilmDownloadAction @Inject constructor( private val kinoRemoteRepository: KinoRemoteRepository ) : DownloadWorker.Action { override fun execute(cacheBehaviour: CacheControl) { kinoRemoteRepository.fetchKinos(cacheBehaviour == CacheControl.BYPASS_CACHE) } }
app/src/main/java/de/tum/in/tumcampusapp/component/ui/tufilm/FilmDownloadAction.kt
3559994264
package lijin.heinika.cn.mygankio.http import lijin.heinika.cn.mygankio.entiy.BaseData import rx.functions.Func1 /** * Author: Chenglong.Lu * Email: [email protected] | [email protected] * Date: 16/8/24 * Description: 用ζ₯η»ŸδΈ€ε€„η†Httpηš„resultCode,εΉΆε°†HttpResultηš„Dataιƒ¨εˆ†ε‰₯离出ζ₯θΏ”ε›žη»™subscriber */ class HttpResultFunc<T> : Func1<BaseData<T>, T> { override fun call(androidData: BaseData<T>): T { if (androidData.isError) { throw ApiException("ζœεŠ‘ε™¨θΏ”ε›žι”™θ――") } return androidData.results!! } }
app/src/main/java/lijin/heinika/cn/mygankio/http/HttpResultFunc.kt
2003188981
/* * Copyright (C) 2016-2017, 2019-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.xquery.psi.impl.plugin import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.xdm.types.XsAnyUriValue import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.PluginStylesheetImport import uk.co.reecedunn.intellij.plugin.xquery.lexer.XQueryTokenType class PluginStylesheetImportPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), PluginStylesheetImport, XpmSyntaxValidationElement { // region XpmSyntaxValidationElement override val conformanceElement: PsiElement get() = findChildByType(XQueryTokenType.K_STYLESHEET)!! // endregion // region XQueryImport override val locationUris: Sequence<XsAnyUriValue> get() = children().filterIsInstance<XsAnyUriValue>().filterNotNull() // endregion }
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/plugin/PluginStylesheetImportPsiImpl.kt
3659612870
package de.westnordost.streetcomplete.data.osmnotes import android.util.Log import de.westnordost.streetcomplete.data.NotesApi import de.westnordost.osmapi.common.errors.OsmConflictException import de.westnordost.osmapi.common.errors.OsmNotFoundException import de.westnordost.osmapi.map.data.LatLon import de.westnordost.osmapi.notes.Note import de.westnordost.streetcomplete.data.osm.upload.ConflictException import javax.inject.Inject /** Uploads a new note or a note comment to OSM, with the option to attach a number of photos */ class OsmNoteWithPhotosUploader @Inject constructor( private val notesApi: NotesApi, private val imageUploader: StreetCompleteImageUploader ) { /** Creates a new note * * @throws ImageUploadException if any attached photo could not be uploaded */ fun create(pos: LatLon, text: String, imagePaths: List<String>?): Note { val attachedPhotosText = uploadAndGetAttachedPhotosText(imagePaths) val note = notesApi.create(pos, text + attachedPhotosText) if (!imagePaths.isNullOrEmpty()) { activateImages(note.id) } return note } /** Comments on an existing note * * @throws ImageUploadException if any attached photo could not be uploaded * @throws ConflictException if the note has already been closed or deleted */ fun comment(noteId: Long, text: String, imagePaths: List<String>?): Note { try { val attachedPhotosText = uploadAndGetAttachedPhotosText(imagePaths) val note = notesApi.comment(noteId, text + attachedPhotosText) if (!imagePaths.isNullOrEmpty()) { activateImages(note.id) } return note } catch (e: OsmNotFoundException) { // someone else already closed the note -> our contribution is probably worthless throw ConflictException(e.message, e) } catch (e: OsmConflictException) { throw ConflictException(e.message, e) } } private fun activateImages(noteId: Long) { try { imageUploader.activate(noteId) } catch (e: ImageActivationException) { Log.e("OsmNoteUploader", "Image activation failed", e) } } private fun uploadAndGetAttachedPhotosText(imagePaths: List<String>?): String { if (!imagePaths.isNullOrEmpty()) { val urls = imageUploader.upload(imagePaths) if (urls.isNotEmpty()) { return "\n\nAttached photo(s):\n" + urls.joinToString("\n") } } return "" } }
app/src/main/java/de/westnordost/streetcomplete/data/osmnotes/OsmNoteWithPhotosUploader.kt
2916402112
package com.github.skuznets0v.metro import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication class RestApplication fun main(args: Array<String>) { SpringApplication.run(RestApplication::class.java, *args) }
rest/src/main/kotlin/com/github/skuznets0v/metro/main.kt
1706635791
//KT-3772 Invoke and overload resolution ambiguity open class A { fun invoke(f: A.() -> Unit) = 1 } class B { operator fun invoke(f: B.() -> Unit) = 2 } open class C val C.attr: A get() = A() open class D: C() val D.attr: B get() = B() fun box(): String { val d = D() return if (d.attr {} == 2) "OK" else "fail" }
backend.native/tests/external/codegen/box/functions/invoke/kt3772.kt
1876981293
package tourguide.tourguide import android.app.Application import android.test.ApplicationTestCase /** * [Testing Fundamentals](http://d.android.com/tools/testing/testing_android.html) */ class ApplicationTest : ApplicationTestCase<Application>(Application::class.java)
tourguide/src/androidTest/java/tourguide/tourguide/ApplicationTest.kt
400478982
package org.stepik.android.view.base.ui.extension import android.annotation.TargetApi import android.content.Context import android.net.Uri import android.os.Build import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient import org.stepik.android.view.base.routing.InternalDeeplinkRouter open class ExternalLinkWebViewClient( private val context: Context ) : WebViewClient() { @Suppress("Deprecation") override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { openExternalLink(Uri.parse(url)) return true } @TargetApi(Build.VERSION_CODES.LOLLIPOP) override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { openExternalLink(request.url) return true } private fun openExternalLink(uri: Uri) { InternalDeeplinkRouter.openInternalDeeplink(context, uri) } }
app/src/main/java/org/stepik/android/view/base/ui/extension/ExternalLinkWebViewClient.kt
1473475303
package org.stepic.droid.core.presenters import android.content.res.Resources import com.google.android.gms.tasks.Tasks import com.google.firebase.perf.FirebasePerformance import com.google.firebase.remoteconfig.FirebaseRemoteConfig import com.google.firebase.remoteconfig.ktx.get import io.reactivex.Completable import io.reactivex.Scheduler import io.reactivex.Single import io.reactivex.disposables.Disposable import io.reactivex.rxkotlin.subscribeBy import org.json.JSONObject import org.stepic.droid.analytic.AmplitudeAnalytic import org.stepic.droid.analytic.Analytic import org.stepic.droid.analytic.experiments.DeferredAuthSplitTest import org.stepic.droid.analytic.experiments.OnboardingSplitTestVersion2 import org.stepic.droid.configuration.RemoteConfig import org.stepic.droid.configuration.analytic.* import org.stepic.droid.core.GoogleApiChecker import org.stepic.droid.core.StepikDevicePoster import org.stepic.droid.core.presenters.contracts.SplashView import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepic.droid.di.qualifiers.MainScheduler import org.stepic.droid.di.splash.SplashScope import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepic.droid.storage.operations.DatabaseFacade import org.stepic.droid.util.AppConstants import org.stepic.droid.util.defaultLocale import ru.nobird.android.domain.rx.emptyOnErrorStub import org.stepik.android.view.routing.deeplink.BranchDeepLinkParser import org.stepik.android.view.routing.deeplink.BranchRoute import org.stepik.android.view.splash.notification.RemindRegistrationNotificationDelegate import org.stepik.android.view.splash.notification.RetentionNotificationDelegate import java.util.concurrent.TimeUnit import javax.inject.Inject @SplashScope class SplashPresenter @Inject constructor( @MainScheduler private val mainScheduler: Scheduler, @BackgroundScheduler private val backgroundScheduler: Scheduler, private val sharedPreferenceHelper: SharedPreferenceHelper, private val firebaseRemoteConfig: FirebaseRemoteConfig, private val googleApiChecker: GoogleApiChecker, private val analytic: Analytic, private val stepikDevicePoster: StepikDevicePoster, private val databaseFacade: DatabaseFacade, private val remindRegistrationNotificationDelegate: RemindRegistrationNotificationDelegate, private val retentionNotificationDelegate: RetentionNotificationDelegate, private val deferredAuthSplitTest: DeferredAuthSplitTest, private val onboardingSplitTestVersion2: OnboardingSplitTestVersion2, private val branchDeepLinkParsers: Set<@JvmSuppressWildcards BranchDeepLinkParser> ) : PresenterBase<SplashView>() { sealed class SplashRoute { object Onboarding : SplashRoute() object Launch : SplashRoute() object Home : SplashRoute() object Catalog : SplashRoute() class DeepLink(val route: BranchRoute) : SplashRoute() } companion object { private const val RUSSIAN_LANGUAGE_CODE = "ru" } private val locale = Resources.getSystem().configuration.defaultLocale private var disposable: Disposable? = null fun onSplashCreated(referringParams: JSONObject? = null) { val splashLoadingTrace = FirebasePerformance.startTrace(Analytic.Traces.SPLASH_LOADING) disposable = Completable .fromCallable { countNumberOfLaunches() checkRemoteConfigs() registerDeviceToPushes() executeLegacyOperations() remindRegistrationNotificationDelegate.scheduleRemindRegistrationNotification() retentionNotificationDelegate.scheduleRetentionNotification(shouldResetCounter = true) sharedPreferenceHelper.onNewSession() if (onboardingSplitTestVersion2.currentGroup == OnboardingSplitTestVersion2.Group.None && locale.language == RUSSIAN_LANGUAGE_CODE) { sharedPreferenceHelper.afterOnboardingPassed() sharedPreferenceHelper.setPersonalizedOnboardingWasShown() } if (sharedPreferenceHelper.isEverLogged) { sharedPreferenceHelper.setPersonalizedOnboardingWasShown() } } .andThen(resolveSplashRoute(referringParams)) .subscribeOn(backgroundScheduler) .observeOn(mainScheduler) .doFinally { splashLoadingTrace.stop() } .subscribeBy( onError = emptyOnErrorStub, onSuccess = { when (it) { SplashRoute.Onboarding -> view?.onShowOnboarding() SplashRoute.Launch -> view?.onShowLaunch() SplashRoute.Home -> view?.onShowHome() SplashRoute.Catalog -> view?.onShowCatalog() is SplashRoute.DeepLink -> view?.onDeepLinkRoute(it.route) else -> throw IllegalStateException("It is not reachable") } } ) } private fun resolveSplashRoute(referringParams: JSONObject?): Single<SplashRoute> = // todo move to interactor resolveBranchRoute(referringParams) .map { SplashRoute.DeepLink(it) as SplashRoute } .onErrorReturn { val isLogged = sharedPreferenceHelper.authResponseFromStore != null val isOnboardingNotPassedYet = resolveIsOnboardingNotPassedYet() // val isDeferredAuth = deferredAuthSplitTest.currentGroup.isDeferredAuth && !deferredAuthSplitTest.currentGroup.isCanDismissLaunch when { isOnboardingNotPassedYet -> SplashRoute.Onboarding isLogged -> SplashRoute.Home // isDeferredAuth -> SplashRoute.Catalog else -> SplashRoute.Launch } } private fun resolveIsOnboardingNotPassedYet(): Boolean { // Guard so that this works as usual for every locale except RU if (locale.language != RUSSIAN_LANGUAGE_CODE) { return sharedPreferenceHelper.isOnboardingNotPassedYet } return when (onboardingSplitTestVersion2.currentGroup) { OnboardingSplitTestVersion2.Group.Control -> sharedPreferenceHelper.isOnboardingNotPassedYet OnboardingSplitTestVersion2.Group.Personalized -> !sharedPreferenceHelper.isPersonalizedOnboardingWasShown OnboardingSplitTestVersion2.Group.None -> false OnboardingSplitTestVersion2.Group.ControlPersonalized -> sharedPreferenceHelper.isOnboardingNotPassedYet || !sharedPreferenceHelper.isPersonalizedOnboardingWasShown } } private fun resolveBranchRoute(referringParams: JSONObject?): Single<BranchRoute> = if (referringParams == null) { Single.error(IllegalArgumentException("Params shouldn't be null")) } else { Single.fromCallable { branchDeepLinkParsers.forEach { parser -> val route = parser.parseBranchDeepLink(referringParams) if (route != null) { return@fromCallable route } } return@fromCallable null } } override fun detachView(view: SplashView) { super.detachView(view) disposable?.dispose() disposable = null } private fun checkRemoteConfigs() { if (googleApiChecker.checkPlayServices()) { val remoteConfigTask = firebaseRemoteConfig.fetchAndActivate().addOnCompleteListener { task -> if (task.isSuccessful) { analytic.reportEvent(Analytic.RemoteConfig.FETCHED_SUCCESSFUL) } else { analytic.reportEvent(Analytic.RemoteConfig.FETCHED_UNSUCCESSFUL) } logRemoteConfig() } try { Tasks.await(remoteConfigTask) } catch (exception: Exception) { // no op } } } private fun logRemoteConfig() { analytic.reportUserProperty(MinDelayRateDialogUserProperty(firebaseRemoteConfig[RemoteConfig.MIN_DELAY_RATE_DIALOG_SEC].asLong())) analytic.reportUserProperty(ShowStreakDialogAfterLoginUserProperty(firebaseRemoteConfig[RemoteConfig.SHOW_STREAK_DIALOG_AFTER_LOGIN].asBoolean())) analytic.reportUserProperty(AdaptiveCoursesUserProperty(firebaseRemoteConfig[RemoteConfig.ADAPTIVE_COURSES].asString())) analytic.reportUserProperty(AdaptiveBackendUrlUserProperty(firebaseRemoteConfig[RemoteConfig.ADAPTIVE_BACKEND_URL].asString())) analytic.reportUserProperty(LocalSubmissionsEnabledUserProperty(firebaseRemoteConfig[RemoteConfig.IS_LOCAL_SUBMISSIONS_ENABLED].asBoolean())) analytic.reportUserProperty(SearchQueryParamsUserProperty(firebaseRemoteConfig[RemoteConfig.SEARCH_QUERY_PARAMS_ANDROID].asString())) analytic.reportUserProperty(NewHomeScreenEnabledUserProperty(firebaseRemoteConfig[RemoteConfig.IS_NEW_HOME_SCREEN_ENABLED].asBoolean())) analytic.reportUserProperty(PersonalizedOnboardingCourseListsUserProperty(firebaseRemoteConfig[RemoteConfig.PERSONALIZED_ONBOARDING_COURSE_LISTS].asString())) analytic.reportUserProperty(CourseRevenueAvailableUserProperty(firebaseRemoteConfig[RemoteConfig.IS_COURSE_REVENUE_AVAILABLE_ANDROID].asBoolean())) } private fun countNumberOfLaunches() { val numberOfLaunches = sharedPreferenceHelper.incrementNumberOfLaunches() //after first increment it is 0, because of default value is -1. if (numberOfLaunches <= 0) { analytic.reportAmplitudeEvent(AmplitudeAnalytic.Launch.FIRST_TIME) } if (numberOfLaunches < AppConstants.LAUNCHES_FOR_EXPERT_USER) { analytic.reportEvent(Analytic.Interaction.START_SPLASH, numberOfLaunches.toString() + "") } else { analytic.reportEvent(Analytic.Interaction.START_SPLASH_EXPERT, numberOfLaunches.toString() + "") } analytic.reportAmplitudeEvent(AmplitudeAnalytic.Launch.SESSION_START) } private fun registerDeviceToPushes() { if (!sharedPreferenceHelper.isGcmTokenOk && googleApiChecker.checkPlayServices()) { stepikDevicePoster.registerDevice() } } private fun executeLegacyOperations() { if (sharedPreferenceHelper.isOnboardingNotPassedYet) { databaseFacade.dropOnlyCourseTable() //v11 bug, when slug was not cached. We can remove it, when all users will have v1.11 or above. (flavour problem) sharedPreferenceHelper.afterScheduleAdded() sharedPreferenceHelper.afterNeedDropCoursesIn114() } else if (!sharedPreferenceHelper.isScheduleAdded) { databaseFacade.dropOnlyCourseTable() sharedPreferenceHelper.afterScheduleAdded() sharedPreferenceHelper.afterNeedDropCoursesIn114() } else if (sharedPreferenceHelper.isNeedDropCoursesIn114) { databaseFacade.dropOnlyCourseTable() sharedPreferenceHelper.afterNeedDropCoursesIn114() } } }
app/src/main/java/org/stepic/droid/core/presenters/SplashPresenter.kt
3504570840
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.maddyhome.idea.vim.action.motion.`object` import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Editor import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.action.TextObjectAction import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.MappingMode import com.maddyhome.idea.vim.common.TextRange import com.maddyhome.idea.vim.handler.TextObjectActionHandler import com.maddyhome.idea.vim.helper.enumSetOf import java.util.* import javax.swing.KeyStroke class MotionInnerBlockParenAction : TextObjectAction() { override fun makeActionHandler(): TextObjectActionHandler = object : TextObjectActionHandler() { override fun getRange(editor: Editor, caret: Caret, context: DataContext, count: Int, rawCount: Int, argument: Argument?): TextRange? { return VimPlugin.getMotion().getBlockRange(editor, caret, count, false, '(') } } override val mappingModes: Set<MappingMode> = MappingMode.VO override val keyStrokesSet: Set<List<KeyStroke>> = parseKeysSet("ib", "i(", "i)") override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_MOT_CHARACTERWISE, CommandFlags.FLAG_MOT_INCLUSIVE, CommandFlags.FLAG_TEXT_BLOCK) }
src/com/maddyhome/idea/vim/action/motion/object/MotionInnerBlockParenAction.kt
1428925947
package info.hzvtc.hipixiv.pojo.tag import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName data class BookmarkTagResponse( @SerializedName("bookmark_tags") @Expose val tags : MutableList<BookmarkTag> = ArrayList(), @SerializedName("next_url") @Expose val nextUrl : String = "" )
app/src/main/java/info/hzvtc/hipixiv/pojo/tag/BookmarkTagResponse.kt
3345796074
package promitech.colonization.screen.debug import com.badlogic.gdx.utils.ObjectIntMap import net.sf.freecol.common.model.Specification import net.sf.freecol.common.model.UnitType import net.sf.freecol.common.model.ai.missions.PlayerMissionsContainer import net.sf.freecol.common.model.ai.missions.foreachMission import net.sf.freecol.common.model.ai.missions.goodsToSell.TransportGoodsToSellMissionPlaner import net.sf.freecol.common.model.ai.missions.pioneer.RequestGoodsMission import net.sf.freecol.common.model.ai.missions.transportunit.TransportUnitRequestMission import net.sf.freecol.common.model.player.Player import promitech.colonization.ai.MissionHandlerLogger.logger import promitech.colonization.ai.UnitTypeId import promitech.colonization.ai.calculateNavyTotalCargo import kotlin.LazyThreadSafetyMode.NONE sealed class BuyShipOrder { data class BuyShipNow(val unitType: UnitType): BuyShipOrder() { override fun toString(): String { return "BuyShipNow[${unitType.id}]" } } data class CollectGoldAndBuy(val unitType: UnitType): BuyShipOrder() { override fun toString(): String { return "CollectGoldAndBuy[${unitType.id}]" } } class NoNeedToBuy(): BuyShipOrder() class NoGoldToBuy(): BuyShipOrder() } class BuyShipPlaner( private val player: Player, private val specification: Specification, private val transportGoodsToSellMissionPlaner: TransportGoodsToSellMissionPlaner, private val playerMissionsContainer: PlayerMissionsContainer ) { private val cargoRequestToCapacityRatio = 1.8 private val transportShips = listOf( specification.unitTypes.getById(UnitType.CARAVEL), specification.unitTypes.getById(UnitType.MERCHANTMAN), specification.unitTypes.getById(UnitType.GALLEON), specification.unitTypes.getById(UnitType.FRIGATE) ) private val ownedShips by lazy(NONE) { calculateOwnedShips() } private val cargoAmountWaitingForTransport by lazy(NONE) { transportGoodsToSellMissionPlaner.potentialCargoAmountWaitingForTransport(player) } private val cargoSlotsRequest: CargoSlotsRequest by lazy(NONE) { calculateCargoSlotRequests() } fun createBuyShipPlan(): BuyShipOrder { val freeNavyCargoSlots = player.calculateNavyTotalCargo(transportShipsToSet()) if (cargoSlotsRequest.sum() > freeNavyCargoSlots * cargoRequestToCapacityRatio) { val lastOwnPlusOne = lastOwnPlusOne() val buyOrder = calculateBuyOrder(lastOwnPlusOne) if (logger.isDebug) { logger.debug("player[%s].buyShipPlan cargoSlotRequest > capacity [ %s > %s ] buy ship request, order: %s", player.id, cargoSlotsRequest.sum(), freeNavyCargoSlots * cargoRequestToCapacityRatio, buyOrder ) } return buyOrder } else { if (logger.isDebug) { logger.debug("player[%s].buyShipPlan cargoSlotRequest < capacity [ %s < %s ] do not need buy ship", player.id, cargoSlotsRequest.sum(), freeNavyCargoSlots * cargoRequestToCapacityRatio ) } return BuyShipOrder.NoNeedToBuy() } } fun handleBuyOrders(buyShipOrder: BuyShipOrder) { when (buyShipOrder) { is BuyShipOrder.BuyShipNow -> player.europe.buyUnitByAI(buyShipOrder.unitType) is BuyShipOrder.CollectGoldAndBuy -> return is BuyShipOrder.NoGoldToBuy -> return is BuyShipOrder.NoNeedToBuy -> return } } private fun calculateBuyOrder(shipType: UnitType): BuyShipOrder { if (player.hasGold(shipType.price)) { return BuyShipOrder.BuyShipNow(shipType) } if (player.gold + cargoAmountWaitingForTransport.cargoValue >= shipType.price) { return BuyShipOrder.CollectGoldAndBuy(shipType) } val cheaperVersionShipType = minusOne(shipType) if (player.hasGold(cheaperVersionShipType.price)) { return BuyShipOrder.BuyShipNow(cheaperVersionShipType) } if (player.gold + cargoAmountWaitingForTransport.cargoValue >= cheaperVersionShipType.price) { return BuyShipOrder.CollectGoldAndBuy(cheaperVersionShipType) } if (hasNotAnyShip()) { return BuyShipOrder.CollectGoldAndBuy(cheaperVersionShipType) } return BuyShipOrder.NoGoldToBuy() } private fun lastOwnPlusOne(): UnitType { var lastOwned = transportShips.first() for (transportShip in transportShips) { if (ownedShips.get(transportShip.id, 0) > 0) { lastOwned = transportShip } } return plusOne(lastOwned) } private fun plusOne(unitType: UnitType): UnitType { var found = false for (transportShip in transportShips) { if (transportShip.equalsId(unitType)) { found = true } else if (found) { return transportShip } } return unitType } private fun minusOne(unitType: UnitType): UnitType { var preview = unitType for (transportShip in transportShips) { if (transportShip.equalsId(unitType)) { return preview } preview = transportShip } return unitType } private fun hasNotAnyShip(): Boolean { for (transportShip in transportShips) { if (ownedShips.get(transportShip.id, 0) > 0) { return false } } return true } private fun calculateCargoSlotRequests(): CargoSlotsRequest { val cargoSlotsRequest = CargoSlotsRequest() cargoSlotsRequest.cargoAmountWaitingForTransport = cargoAmountWaitingForTransport.cargoSlots playerMissionsContainer.foreachMission(TransportUnitRequestMission::class.java, { transportUnitRequestMission -> if (transportUnitRequestMission.isWorthEmbark()) { cargoSlotsRequest.transportUnitRequest++ } }) playerMissionsContainer.foreachMission(RequestGoodsMission::class.java, { requestGoodsMission -> cargoSlotsRequest.requestGoods++ }) return cargoSlotsRequest } private fun calculateOwnedShips(): ObjectIntMap<UnitTypeId> { val ownedShips = ObjectIntMap<UnitTypeId>() for (unit in player.units) { if (unit.isNaval && !unit.isDamaged) { ownedShips.getAndIncrement(unit.unitType.id, 0, 1) } } return ownedShips } private fun transportShipsToSet(): Set<UnitTypeId> { val ids = mutableSetOf<UnitTypeId>() for (transportShip in transportShips) { ids.add(transportShip.id) } return ids } fun printDebugInfo() { for (ownShipEntry in ownedShips) { println("ownShipEntry[${ownShipEntry.key}] = ${ownShipEntry.value}") } println("CargoSlotsRequest.cargoAmountWaitingForTransport = ${cargoSlotsRequest.cargoAmountWaitingForTransport}") println("CargoSlotsRequest.requestGoods = ${cargoSlotsRequest.requestGoods}") println("CargoSlotsRequest.transportUnitRequest = ${cargoSlotsRequest.transportUnitRequest}") println("CargoSlotsRequest.sum = ${cargoSlotsRequest.sum()}") val freeNavyCargoSlots = player.calculateNavyTotalCargo(transportShipsToSet()) println("freeNavyCargoSlots = ${freeNavyCargoSlots}") val signal = cargoSlotsRequest.sum() > freeNavyCargoSlots * cargoRequestToCapacityRatio println("buy ship signal (${cargoSlotsRequest.sum()} > ${freeNavyCargoSlots * cargoRequestToCapacityRatio}) = ${signal}") } private class CargoSlotsRequest { var transportUnitRequest: Int = 0 var requestGoods: Int = 0 var cargoAmountWaitingForTransport: Int = 0 fun sum(): Int = transportUnitRequest + requestGoods + cargoAmountWaitingForTransport } }
core/src/promitech/colonization/ai/BuyShipPlaner.kt
27908068
package eu.kanade.domain.source.interactor import eu.kanade.domain.source.model.Pin import eu.kanade.domain.source.model.Pins import eu.kanade.domain.source.model.Source import eu.kanade.domain.source.repository.SourceRepository import eu.kanade.domain.source.service.SourcePreferences import eu.kanade.tachiyomi.source.LocalSource import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged class GetEnabledSources( private val repository: SourceRepository, private val preferences: SourcePreferences, ) { fun subscribe(): Flow<List<Source>> { return combine( preferences.pinnedSources().changes(), preferences.enabledLanguages().changes(), preferences.disabledSources().changes(), preferences.lastUsedSource().changes(), repository.getSources(), ) { pinnedSourceIds, enabledLanguages, disabledSources, lastUsedSource, sources -> val duplicatePins = preferences.duplicatePinnedSources().get() sources .filter { it.lang in enabledLanguages || it.id == LocalSource.ID } .filterNot { it.id.toString() in disabledSources } .sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.name }) .flatMap { val flag = if ("${it.id}" in pinnedSourceIds) Pins.pinned else Pins.unpinned val source = it.copy(pin = flag) val toFlatten = mutableListOf(source) if (source.id == lastUsedSource) { toFlatten.add(source.copy(isUsedLast = true, pin = source.pin - Pin.Actual)) } if (duplicatePins && Pin.Pinned in source.pin) { toFlatten[0] = toFlatten[0].copy(pin = source.pin + Pin.Forced) toFlatten.add(source.copy(pin = source.pin - Pin.Actual)) } toFlatten } } .distinctUntilChanged() } }
app/src/main/java/eu/kanade/domain/source/interactor/GetEnabledSources.kt
3401382922
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danars.encryption.BleEncryption import info.nightscout.shared.logging.LTag class DanaRSPacketBasalSetCancelTemporaryBasal( injector: HasAndroidInjector ) : DanaRSPacket(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__CANCEL_TEMPORARY_BASAL aapsLogger.debug(LTag.PUMPCOMM, "Canceling temp basal") } override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false } else { aapsLogger.error("Result Error: $result") failed = true } } override val friendlyName: String = "BASAL__CANCEL_TEMPORARY_BASAL" }
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetCancelTemporaryBasal.kt
1755647342
package info.nightscout.androidaps.plugins.general.autotune import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.TestBaseWithProfile import info.nightscout.androidaps.data.IobTotal import info.nightscout.androidaps.data.LocalInsulin import info.nightscout.androidaps.data.ProfileSealed import info.nightscout.androidaps.data.PureProfile import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.data.Block import info.nightscout.androidaps.database.data.TargetBlock import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.database.entities.Carbs import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.extensions.shiftBlock import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.plugins.general.autotune.data.* import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.T import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.sharedPreferences.SP import org.json.JSONArray import org.json.JSONObject import org.junit.Assert import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito.`when` import java.io.File import java.util.* class AutotunePrepTest : TestBaseWithProfile() { @Mock lateinit var sp: SP @Mock lateinit var autotuneFS: AutotuneFS @Mock lateinit var injector: HasAndroidInjector @Mock lateinit var activePlugin: ActivePlugin @Mock lateinit var repository: AppRepository private lateinit var autotunePrep: AutotunePrep private lateinit var autotuneIob: TestAutotuneIob private var ts = 0 private var min5mCarbImpact = 0.0 private var autotuneMin = 0.0 private var autotuneMax = 0.0 private var startDayTime = 0L @Before fun initData() { ts = T.msecs(TimeZone.getDefault().getOffset(System.currentTimeMillis()).toLong()).hours().toInt() - 2 } @Test fun autotunePrepTest1() { // Test if categorisation with standard treatments with carbs is Ok val inputIobJson = File("src/test/res/autotune/test1/oaps-iobCalc.2022-05-21.json").readText() //json files build with iob/activity calculated by OAPS val iobOapsCalculation = buildIobOaps(JSONArray(inputIobJson)) autotuneIob = TestAutotuneIob(aapsLogger, repository, profileFunction, sp, dateUtil, activePlugin, autotuneFS, iobOapsCalculation) autotunePrep = AutotunePrep(aapsLogger, sp, dateUtil, autotuneFS, autotuneIob) val inputProfileJson = File("src/test/res/autotune/test1/profile.pump.json").readText() val inputProfile = atProfileFromOapsJson(JSONObject(inputProfileJson), dateUtil)!! val prepJson = File("src/test/res/autotune/test1/autotune.2022-05-21.json").readText() val oapsPreppedGlucose = PreppedGlucose(JSONObject(prepJson), dateUtil) //prep data calculated by OpenAPS autotune val oapsEntriesJson = File("src/test/res/autotune/test1/aaps-entries.2022-05-21.json").readText() autotuneIob.glucose = buildGlucose(JSONArray(oapsEntriesJson)) val oapsTreatmentsJson = File("src/test/res/autotune/test1/aaps-treatments.2022-05-21.json").readText() autotuneIob.meals = buildMeals(JSONArray(oapsTreatmentsJson)) //Only meals is used in unit test, Insulin only used for iob calculation autotuneIob.boluses = buildBoluses(oapsPreppedGlucose) //Values from oapsPrepData because linked to iob calculation method for TBR `when`(sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, 3.0)).thenReturn(min5mCarbImpact) `when`(sp.getBoolean(R.string.key_autotune_categorize_uam_as_basal, false)).thenReturn(false) val aapsPreppedGlucose = autotunePrep.categorizeBGDatums(inputProfile, inputProfile.localInsulin, false) try { aapsPreppedGlucose?.let { // compare all categorization calculated by aaps plugin (aapsPreppedGlucose) with categorization calculated by OpenAPS (oapsPreppedGlucose) for (i in aapsPreppedGlucose.crData.indices) Assert.assertTrue(oapsPreppedGlucose.crData[i].equals(aapsPreppedGlucose.crData[i])) for (i in aapsPreppedGlucose.csfGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.csfGlucoseData[i].equals(aapsPreppedGlucose.csfGlucoseData[i])) oapsPreppedGlucose.isfGlucoseData = oapsPreppedGlucose.isfGlucoseData.sortedBy { it.date } aapsPreppedGlucose.isfGlucoseData = aapsPreppedGlucose.isfGlucoseData.sortedBy { it.date } for (i in aapsPreppedGlucose.isfGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.isfGlucoseData[i].equals(aapsPreppedGlucose.isfGlucoseData[i])) oapsPreppedGlucose.basalGlucoseData = oapsPreppedGlucose.basalGlucoseData.sortedBy { it.date } aapsPreppedGlucose.basalGlucoseData = aapsPreppedGlucose.basalGlucoseData.sortedBy { it.date } for (i in aapsPreppedGlucose.basalGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.basalGlucoseData[i].equals(aapsPreppedGlucose.basalGlucoseData[i])) } ?: Assert.fail() } catch (e: Exception) { Assert.fail() } } @Test fun autotunePrepTest2() { // Test if categorisation without carbs (full UAM) and categorize UAM as basal false is Ok val inputIobJson = File("src/test/res/autotune/test2/oaps-iobCalc.2022-05-21.json").readText() //json files build with iob/activity calculated by OAPS val iobOapsCalculation = buildIobOaps(JSONArray(inputIobJson)) autotuneIob = TestAutotuneIob(aapsLogger, repository, profileFunction, sp, dateUtil, activePlugin, autotuneFS, iobOapsCalculation) autotunePrep = AutotunePrep(aapsLogger, sp, dateUtil, autotuneFS, autotuneIob) val inputProfileJson = File("src/test/res/autotune/test2/profile.pump.json").readText() val inputProfile = atProfileFromOapsJson(JSONObject(inputProfileJson), dateUtil)!! val prepJson = File("src/test/res/autotune/test2/autotune.2022-05-21.json").readText() val oapsPreppedGlucose = PreppedGlucose(JSONObject(prepJson), dateUtil) //prep data calculated by OpenAPS autotune val oapsEntriesJson = File("src/test/res/autotune/test2/aaps-entries.2022-05-21.json").readText() autotuneIob.glucose = buildGlucose(JSONArray(oapsEntriesJson)) val oapsTreatmentsJson = File("src/test/res/autotune/test2/aaps-treatments.2022-05-21.json").readText() autotuneIob.meals = buildMeals(JSONArray(oapsTreatmentsJson)) //Only meals is used in unit test, Insulin only used for iob calculation autotuneIob.boluses = buildBoluses(oapsPreppedGlucose) //Values from oapsPrepData because linked to iob calculation method for TBR `when`(sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, 3.0)).thenReturn(min5mCarbImpact) `when`(sp.getBoolean(R.string.key_autotune_categorize_uam_as_basal, false)).thenReturn(false) // CategorizeUAM as Basal = False val aapsPreppedGlucose = autotunePrep.categorizeBGDatums(inputProfile, inputProfile.localInsulin, false) try { aapsPreppedGlucose?.let { // compare all categorization calculated by aaps plugin (aapsPreppedGlucose) with categorization calculated by OpenAPS (oapsPreppedGlucose) for (i in aapsPreppedGlucose.crData.indices) Assert.assertTrue(oapsPreppedGlucose.crData[i].equals(aapsPreppedGlucose.crData[i])) for (i in aapsPreppedGlucose.csfGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.csfGlucoseData[i].equals(aapsPreppedGlucose.csfGlucoseData[i])) oapsPreppedGlucose.isfGlucoseData = oapsPreppedGlucose.isfGlucoseData.sortedBy { it.date } aapsPreppedGlucose.isfGlucoseData = aapsPreppedGlucose.isfGlucoseData.sortedBy { it.date } for (i in aapsPreppedGlucose.isfGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.isfGlucoseData[i].equals(aapsPreppedGlucose.isfGlucoseData[i])) oapsPreppedGlucose.basalGlucoseData = oapsPreppedGlucose.basalGlucoseData.sortedBy { it.date } aapsPreppedGlucose.basalGlucoseData = aapsPreppedGlucose.basalGlucoseData.sortedBy { it.date } for (i in aapsPreppedGlucose.basalGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.basalGlucoseData[i].equals(aapsPreppedGlucose.basalGlucoseData[i])) } ?: Assert.fail() } catch (e: Exception) { Assert.fail() } } @Test fun autotunePrepTest3() { // Test if categorisation without carbs (full UAM) and categorize UAM as basal true is Ok val inputIobJson = File("src/test/res/autotune/test3/oaps-iobCalc.2022-05-21.json").readText() //json files build with iob/activity calculated by OAPS val iobOapsCalculation = buildIobOaps(JSONArray(inputIobJson)) autotuneIob = TestAutotuneIob(aapsLogger, repository, profileFunction, sp, dateUtil, activePlugin, autotuneFS, iobOapsCalculation) autotunePrep = AutotunePrep(aapsLogger, sp, dateUtil, autotuneFS, autotuneIob) val inputProfileJson = File("src/test/res/autotune/test3/profile.pump.json").readText() val inputProfile = atProfileFromOapsJson(JSONObject(inputProfileJson), dateUtil)!! val prepJson = File("src/test/res/autotune/test3/autotune.2022-05-21.json").readText() val oapsPreppedGlucose = PreppedGlucose(JSONObject(prepJson), dateUtil) //prep data calculated by OpenAPS autotune val oapsEntriesJson = File("src/test/res/autotune/test3/aaps-entries.2022-05-21.json").readText() autotuneIob.glucose = buildGlucose(JSONArray(oapsEntriesJson)) val oapsTreatmentsJson = File("src/test/res/autotune/test3/aaps-treatments.2022-05-21.json").readText() autotuneIob.meals = buildMeals(JSONArray(oapsTreatmentsJson)) //Only meals is used in unit test, Insulin only used for iob calculation autotuneIob.boluses = buildBoluses(oapsPreppedGlucose) //Values from oapsPrepData because linked to iob calculation method for TBR `when`(sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, 3.0)).thenReturn(min5mCarbImpact) `when`(sp.getBoolean(R.string.key_autotune_categorize_uam_as_basal, false)).thenReturn(true) // CategorizeUAM as Basal = True val aapsPreppedGlucose = autotunePrep.categorizeBGDatums(inputProfile, inputProfile.localInsulin, false) try { aapsPreppedGlucose?.let { // compare all categorization calculated by aaps plugin (aapsPreppedGlucose) with categorization calculated by OpenAPS (oapsPreppedGlucose) for (i in aapsPreppedGlucose.crData.indices) Assert.assertTrue(oapsPreppedGlucose.crData[i].equals(aapsPreppedGlucose.crData[i])) for (i in aapsPreppedGlucose.csfGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.csfGlucoseData[i].equals(aapsPreppedGlucose.csfGlucoseData[i])) oapsPreppedGlucose.isfGlucoseData = oapsPreppedGlucose.isfGlucoseData.sortedBy { it.date } aapsPreppedGlucose.isfGlucoseData = aapsPreppedGlucose.isfGlucoseData.sortedBy { it.date } for (i in aapsPreppedGlucose.isfGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.isfGlucoseData[i].equals(aapsPreppedGlucose.isfGlucoseData[i])) oapsPreppedGlucose.basalGlucoseData = oapsPreppedGlucose.basalGlucoseData.sortedBy { it.date } aapsPreppedGlucose.basalGlucoseData = aapsPreppedGlucose.basalGlucoseData.sortedBy { it.date } for (i in aapsPreppedGlucose.basalGlucoseData.indices) Assert.assertTrue(oapsPreppedGlucose.basalGlucoseData[i].equals(aapsPreppedGlucose.basalGlucoseData[i])) } ?: Assert.fail() } catch (e: Exception) { Assert.fail() } } /************************************************************************************************************************************************************************************* * OpenAPS profile for Autotune only have one ISF value and one IC value */ @Suppress("SpellCheckingInspection") private fun atProfileFromOapsJson(jsonObject: JSONObject, dateUtil: DateUtil, defaultUnits: String? = null): ATProfile? { try { min5mCarbImpact = JsonHelper.safeGetDoubleAllowNull(jsonObject, "min_5m_carbimpact") ?: return null autotuneMin = JsonHelper.safeGetDoubleAllowNull(jsonObject, "autosens_min") ?: return null autotuneMax = JsonHelper.safeGetDoubleAllowNull(jsonObject, "autosens_max") ?: return null val txtUnits = JsonHelper.safeGetStringAllowNull(jsonObject, "units", defaultUnits) ?: return null val units = GlucoseUnit.fromText(txtUnits) val dia = JsonHelper.safeGetDoubleAllowNull(jsonObject, "dia") ?: return null val peak = JsonHelper.safeGetIntAllowNull(jsonObject, "insulinPeakTime") ?: return null val localInsulin = LocalInsulin("insulin", peak, dia) val timezone = TimeZone.getTimeZone(JsonHelper.safeGetString(jsonObject, "timezone", "UTC")) val isfJson = jsonObject.getJSONObject("isfProfile") val isfBlocks = ArrayList<Block>(1).also { val isfJsonArray = isfJson.getJSONArray("sensitivities") val value = isfJsonArray.getJSONObject(0).getDouble("sensitivity") it.add(0, Block((T.hours(24).secs()) * 1000L, value)) } val icBlocks = ArrayList<Block>(1).also { val value = jsonObject.getDouble("carb_ratio") it.add(0, Block((T.hours(24).secs()) * 1000L, value)) } val basalBlocks = blockFromJsonArray(jsonObject.getJSONArray("basalprofile")) ?: return null val targetBlocks = ArrayList<TargetBlock>(1).also { it.add(0, TargetBlock((T.hours(24).secs()) * 1000L, 100.0, 100.0)) } val pure = PureProfile( jsonObject = jsonObject, basalBlocks = basalBlocks.shiftBlock(1.0,ts), isfBlocks = isfBlocks, icBlocks = icBlocks, targetBlocks = targetBlocks, glucoseUnit = units, timeZone = timezone, dia = dia ) return ATProfile(ProfileSealed.Pure(pure), localInsulin, profileInjector).also { it.dateUtil = dateUtil } } catch (ignored: Exception) { return null } } private fun blockFromJsonArray(jsonArray: JSONArray?): List<Block>? { val size = jsonArray?.length() ?: return null val ret = ArrayList<Block>(size) try { for (index in 0 until jsonArray.length() - 1) { val o = jsonArray.getJSONObject(index) val tas = o.getInt("minutes") * 60 val next = jsonArray.getJSONObject(index + 1) val nextTas = next.getInt("minutes") * 60 val value = o.getDouble("rate") if (tas % 3600 != 0) return null if (nextTas % 3600 != 0) return null ret.add(index, Block((nextTas - tas) * 1000L, value)) } val last: JSONObject = jsonArray.getJSONObject(jsonArray.length() - 1) val lastTas = last.getInt("minutes") * 60 val value = last.getDouble("rate") ret.add(jsonArray.length() - 1, Block((T.hours(24).secs() - lastTas) * 1000L, value)) } catch (e: Exception) { return null } return ret } private fun buildBoluses(preppedGlucose: PreppedGlucose): ArrayList<Bolus> { //if categorization is correct then I return for dose function the crInsulin calculated in Oaps val boluses: ArrayList<Bolus> = ArrayList() for (i in preppedGlucose.crData.indices) { boluses.add( Bolus( timestamp = preppedGlucose.crData[i].crEndTime, amount = preppedGlucose.crData[i].crInsulin, type = Bolus.Type.NORMAL ) ) } if (boluses.size == 0) //Add at least one insulin treatment for tests to avoid return null in categorization boluses.add( Bolus( timestamp = startDayTime, amount = 1.0, type = Bolus.Type.NORMAL ) ) return boluses } private fun buildMeals(jsonArray: JSONArray): ArrayList<Carbs> { val list: ArrayList<Carbs> = ArrayList() for (index in 0 until jsonArray.length()) { val json = jsonArray.getJSONObject(index) val value = JsonHelper.safeGetDouble(json, "carbs", 0.0) val timestamp = JsonHelper.safeGetLong(json, "date") if (value > 0.0 && timestamp > startDayTime) { list.add(Carbs(timestamp = timestamp, amount = value, duration = 0)) } } return list } private fun buildGlucose(jsonArray: JSONArray): List<GlucoseValue> { val list: ArrayList<GlucoseValue> = ArrayList() for (index in 0 until jsonArray.length()) { val json = jsonArray.getJSONObject(index) val value = JsonHelper.safeGetDouble(json, "sgv") val timestamp = JsonHelper.safeGetLong(json, "date") list.add(GlucoseValue(raw = value, noise = 0.0, value = value, timestamp = timestamp, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) } if (list.size > 0) startDayTime = list[list.size - 1].timestamp return list } private fun buildIobOaps(jsonArray: JSONArray): ArrayList<IobTotal> { //if categorization is correct then I return for dose function the crInsulin calculated in Oaps val list: ArrayList<IobTotal> = ArrayList() for (index in 0 until jsonArray.length()) { val json = jsonArray.getJSONObject(index) val time = JsonHelper.safeGetLong(json, "date") val iob = JsonHelper.safeGetDouble(json, "iob") val activity = JsonHelper.safeGetDouble(json, "activity") val iobTotal = IobTotal(time) iobTotal.iob = iob iobTotal.activity = activity list.add(iobTotal) } return list } class TestAutotuneIob( val aapsLogger: AAPSLogger, repository: AppRepository, val profileFunction: ProfileFunction, val sp: SP, val dateUtil: DateUtil, val activePlugin: ActivePlugin, autotuneFS: AutotuneFS, private val iobOapsCalculation: ArrayList<IobTotal> ) : AutotuneIob( aapsLogger, repository, profileFunction, sp, dateUtil, activePlugin, autotuneFS ) { override fun getIOB(time: Long, localInsulin: LocalInsulin): IobTotal { val bolusIob = IobTotal(time) iobOapsCalculation.forEach { if (it.time == time) return it } return bolusIob } } }
app/src/test/java/info/nightscout/androidaps/plugins/general/autotune/AutotunePrepTest.kt
2498731875
package info.nightscout.androidaps.interfaces import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import java.util.* class Constraint<T : Comparable<T>>(private var value: T) { private var originalValue: T private val reasons: MutableList<String> = ArrayList() private val mostLimiting: MutableList<String> = ArrayList() fun value(): T { return value } fun originalValue(): T { return originalValue } fun set(aapsLogger: AAPSLogger, value: T): Constraint<T> { this.value = value originalValue = value aapsLogger.debug(LTag.CONSTRAINTS, "Setting value $value") return this } fun set(aapsLogger: AAPSLogger, value: T, reason: String, from: Any): Constraint<T> { aapsLogger.debug(LTag.CONSTRAINTS, "Setting value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]") this.value = value addReason(reason, from) addMostLimingReason(reason, from) return this } fun setIfDifferent(aapsLogger: AAPSLogger, value: T, reason: String, from: Any): Constraint<T> { if (this.value != value) { aapsLogger.debug(LTag.CONSTRAINTS, "Setting because of different value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]") this.value = value addReason(reason, from) addMostLimingReason(reason, from) } return this } fun setIfSmaller(aapsLogger: AAPSLogger, value: T, reason: String, from: Any): Constraint<T> { if (value < this.value) { aapsLogger.debug(LTag.CONSTRAINTS, "Setting because of smaller value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]") this.value = value mostLimiting.clear() addMostLimingReason(reason, from) } if (value < originalValue) { addReason(reason, from) } return this } fun setIfGreater(aapsLogger: AAPSLogger, value: T, reason: String, from: Any): Constraint<T> { if (value > this.value) { aapsLogger.debug(LTag.CONSTRAINTS, "Setting because of greater value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]") this.value = value mostLimiting.clear() addMostLimingReason(reason, from) } if (value > originalValue) { addReason(reason, from) } return this } private fun translateFrom(from: Any): String { return from.javaClass.simpleName.replace("Plugin", "") } fun addReason(reason: String, from: Any) { reasons.add(translateFrom(from) + ": " + reason) } private fun addMostLimingReason(reason: String, from: Any) { mostLimiting.add(translateFrom(from) + ": " + reason) } fun getReasons(aapsLogger: AAPSLogger): String { val sb = StringBuilder() for ((count, r) in reasons.withIndex()) { if (count != 0) sb.append("\n") sb.append(r) } aapsLogger.debug(LTag.CONSTRAINTS, "Limiting original value: $originalValue to $value. Reason: $sb") return sb.toString() } val reasonList: List<String> get() = reasons fun getMostLimitedReasons(aapsLogger: AAPSLogger): String { val sb = StringBuilder() for ((count, r) in mostLimiting.withIndex()) { if (count != 0) sb.append("\n") sb.append(r) } aapsLogger.debug(LTag.CONSTRAINTS, "Limiting original value: $originalValue to $value. Reason: $sb") return sb.toString() } val mostLimitedReasonList: List<String> get() = mostLimiting fun copyReasons(another: Constraint<*>) { reasons.addAll(another.reasonList) } init { originalValue = value } }
core/src/main/java/info/nightscout/androidaps/interfaces/Constraint.kt
3803505279
package biz.eventually.atpl.ui.questions import android.arch.lifecycle.LiveData import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.Transformations import android.arch.lifecycle.ViewModel import android.widget.ImageView import biz.eventually.atpl.AtplApplication import biz.eventually.atpl.BuildConfig import biz.eventually.atpl.data.NetworkStatus import biz.eventually.atpl.data.db.Question import biz.eventually.atpl.data.dto.SubjectView import com.squareup.picasso.Picasso import org.jetbrains.anko.doAsync import javax.inject.Inject import javax.inject.Singleton /** * Created by Thibault de Lambilly on 26/11/2017. * */ @Singleton class QuestionViewModel @Inject constructor(private val repository: QuestionRepository) : ViewModel() { // topicId: Long, isSync: Boolean, hasOffline: Boolean var updateLine: MutableLiveData<Triple<Long, Boolean, Boolean>> = MutableLiveData() var networkStatus: LiveData<NetworkStatus> = repository.networkStatus() private var mPosition: MutableLiveData<Int> = MutableLiveData() var question: LiveData<QuestionState> = Transformations.switchMap(mPosition) { mPosition.value?.let { mAnswerIndexTick = -1 val data = MutableLiveData<QuestionState>() mQuestionState = mQuestionState.copy( question = mQuestions[it], index = mPosition.value ?: 0 ) data.postValue(mQuestionState) return@switchMap data } } private var mQuestions: List<Question> = listOf() private var mQuestionState = QuestionState(Question(-1, -1, "", ""), 0, 0) private var mAnswerIndexTick = -1 fun launchTest(topicId: Long, starFist: Boolean) { repository.getQuestions(topicId, starFist, fun(data: List<Question>) { if (data.isNotEmpty()) { mQuestions = data mQuestionState.size = data.size mPosition.value = 0 doAsync { checkExistingPics(mQuestions) } } }) } private fun checkExistingPics(questions: List<Question>) { // https://www.codeday.top/2017/07/31/31373.html val withPics = questions.filter { q -> q.img.isNotEmpty() } val imageViewContainer = ImageView(AtplApplication.get()) withPics.forEach { Picasso.with(AtplApplication.get()).load(BuildConfig.API_ATPL_IMG + it).into(imageViewContainer) } } fun getDataForSubject(subjectId: Long, subjects: List<SubjectView>) { subjects.forEach { // here the topic is in fact a Subject, w/ idWeb = idWeb * -1 if (it.subject.idWeb == (subjectId * -1)) { it.topics.forEach { topic -> val id = topic.idWeb // show sync on the line updateLine.value = Triple(id, true, true) repository.getWebData(id, false, true, true) { // sync done for that line updateLine.value = Triple(id, false, true) // download offline image doAsync { checkExistingPics(repository.getTopicQuestionWithImage(id)) } } } // show the subject button download updateLine.postValue(Triple(subjectId, false, true)) } } } fun tickAnswer(tick: Int) { mAnswerIndexTick = tick } /** * change index position for previous question * returning if ever the answer to the question was good. */ fun previous(): Boolean? { var isGood: Boolean? = null // adding check size while investigating for a crash... if (mAnswerIndexTick > -1 && mAnswerIndexTick < mQuestionState.question.answers.size) { isGood = mQuestionState.question.answers[mAnswerIndexTick].good } mPosition.value?.let { if (it >= 1) mPosition.postValue(it - 1) } return isGood } /** * change index position for next question * returning if ever the answer to the question was good. */ fun next(): Boolean? { var isGood: Boolean? = null mPosition.value?.let { if (mAnswerIndexTick > -1 && it < mQuestionState.question.answers.size) { isGood = mQuestionState.question.answers[mAnswerIndexTick].good } if (it < mQuestions.size - 1) mPosition.postValue(it + 1) } return isGood } fun shuffle() { mQuestions = mQuestions.shuffled() mPosition.value = 0 } }
app/src/main/java/biz/eventually/atpl/ui/questions/QuestionViewModel.kt
2174929983
package io.github.rin_da.ucsynews.domain /** * Created by user on 12/14/16. */
app/src/main/java/io/github/rin_da/ucsynews/domain/DomainUtil.kt
2003329264
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.action.window import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.handler.VimActionHandler /** * @author rasendubi */ class VerticalSplitAction : VimActionHandler.SingleExecution() { override val type: Command.Type = Command.Type.OTHER_READONLY override fun execute( editor: VimEditor, context: ExecutionContext, cmd: Command, operatorArguments: OperatorArguments, ): Boolean { injector.window.splitWindowVertical(context, "") return true } }
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/window/VerticalSplitAction.kt
3475840645
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package org.jetbrains.plugins.ideavim.ex.parser.expressions import com.maddyhome.idea.vim.vimscript.model.datatypes.VimInt import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString import com.maddyhome.idea.vim.vimscript.model.expressions.FunctionCallExpression import com.maddyhome.idea.vim.vimscript.model.expressions.Scope import com.maddyhome.idea.vim.vimscript.model.expressions.ScopeExpression import com.maddyhome.idea.vim.vimscript.parser.VimscriptParser import org.jetbrains.plugins.ideavim.ex.evaluate import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue class FunctionCallExpressionTests { @Test fun `function call with no arguments`() { val ex = VimscriptParser.parseExpression("doSomething()") assertTrue(ex is FunctionCallExpression) assertEquals("doSomething", ex.functionName.evaluate().asString()) assertNull(ex.scope) assertEquals(0, ex.arguments.size) } @Test fun `scoped function call`() { val ex = VimscriptParser.parseExpression("s:doSomething()") assertTrue(ex is FunctionCallExpression) assertEquals("doSomething", ex.functionName.evaluate().asString()) assertNotNull(ex.scope) assertEquals(Scope.SCRIPT_VARIABLE, ex.scope) assertEquals(0, ex.arguments.size) } @Test fun `function call with simple arguments`() { val ex = VimscriptParser.parseExpression("f(0, 'string')") assertTrue(ex is FunctionCallExpression) assertEquals("f", ex.functionName.evaluate().asString()) assertNull(ex.scope) assertNotNull(ex.arguments) assertEquals(2, ex.arguments.size) assertEquals(VimInt(0), ex.arguments[0].evaluate()) assertEquals(VimString("string"), ex.arguments[1].evaluate()) } @Test fun `scope as a function call argument`() { val ex = VimscriptParser.parseExpression("f(s:, 'string')") assertTrue(ex is FunctionCallExpression) assertEquals("f", ex.functionName.evaluate().asString()) assertNull(ex.scope) assertNotNull(ex.arguments) assertEquals(2, ex.arguments.size) assertEquals(ScopeExpression(Scope.SCRIPT_VARIABLE), ex.arguments[0]) assertEquals(VimString("string"), ex.arguments[1].evaluate()) } }
src/test/java/org/jetbrains/plugins/ideavim/ex/parser/expressions/FunctionCallExpressionTests.kt
1908332771
package com.github.felipehjcosta.marvelapp.wiki.di import javax.inject.Scope @Scope @kotlin.annotation.Retention annotation class WikiScope
feature/wiki/src/main/kotlin/com/github/felipehjcosta/marvelapp/wiki/di/WikiScope.kt
2879461918
package forpdateam.ru.forpda.model.data.remote.parser import android.text.Spanned import forpdateam.ru.forpda.model.data.remote.api.ApiUtils import java.util.regex.Matcher open class BaseParser { fun String?.fromHtml(): String? = this?.let { ApiUtils.fromHtml(it) } fun String?.fromHtmlToColored(): Spanned? = this?.let { ApiUtils.coloredFromHtml(it) } fun String?.fromHtmlToSpanned(): Spanned? = this?.let { ApiUtils.spannedFromHtml(it) } inline fun Matcher.findOnce(action: (Matcher) -> Unit): Matcher { if (this.find()) action(this) return this } inline fun Matcher.findAll(action: (Matcher) -> Unit): Matcher { while (this.find()) action(this) return this } inline fun <R> Matcher.map(transform: (Matcher) -> R): List<R> { val data = mutableListOf<R>() findAll { data.add(transform(this)) } return data } inline fun <R> Matcher.mapOnce(transform: (Matcher) -> R): R? { var data: R? = null findOnce { data = transform(this) } return data } }
app/src/main/java/forpdateam/ru/forpda/model/data/remote/parser/BaseParser.kt
3824693330
package org.wordpress.android.ui.reader.viewmodels import androidx.lifecycle.MutableLiveData import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.InternalCoroutinesApi import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.mockito.ArgumentMatchers import org.mockito.ArgumentMatchers.anyBoolean import org.mockito.ArgumentMatchers.anyInt import org.mockito.ArgumentMatchers.anyList import org.mockito.ArgumentMatchers.anyLong import org.mockito.ArgumentMatchers.anyString import org.mockito.Mock import org.mockito.kotlin.KArgumentCaptor import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.wordpress.android.BaseUnitTest import org.wordpress.android.R import org.wordpress.android.TEST_DISPATCHER import org.wordpress.android.datasets.wrappers.ReaderCommentTableWrapper import org.wordpress.android.datasets.wrappers.ReaderPostTableWrapper import org.wordpress.android.fluxc.model.AccountModel import org.wordpress.android.fluxc.model.LikeModel import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.store.AccountStore import org.wordpress.android.fluxc.store.SiteStore import org.wordpress.android.models.ReaderComment import org.wordpress.android.models.ReaderCommentList import org.wordpress.android.models.ReaderPost import org.wordpress.android.test import org.wordpress.android.ui.avatars.TrainOfAvatarsItem.AvatarItem import org.wordpress.android.ui.avatars.TrainOfAvatarsItem.TrailingLabelTextItem import org.wordpress.android.ui.engagement.EngageItem.Liker import org.wordpress.android.ui.engagement.EngagementUtils import org.wordpress.android.ui.engagement.GetLikesHandler import org.wordpress.android.ui.engagement.GetLikesUseCase.GetLikesState import org.wordpress.android.ui.engagement.GetLikesUseCase.GetLikesState.Failure import org.wordpress.android.ui.engagement.GetLikesUseCase.GetLikesState.LikesData import org.wordpress.android.ui.engagement.utils.GetLikesTestConfig.TEST_CONFIG_1 import org.wordpress.android.ui.engagement.utils.GetLikesTestConfig.TEST_CONFIG_5 import org.wordpress.android.ui.engagement.utils.getGetLikesState import org.wordpress.android.ui.pages.SnackbarMessageHolder import org.wordpress.android.ui.reader.ReaderPostDetailUiStateBuilder import org.wordpress.android.ui.reader.discover.ReaderNavigationEvents import org.wordpress.android.ui.reader.discover.ReaderNavigationEvents.OpenEditorForReblog import org.wordpress.android.ui.reader.discover.ReaderNavigationEvents.OpenUrl import org.wordpress.android.ui.reader.discover.ReaderNavigationEvents.ReplaceRelatedPostDetailsWithHistory import org.wordpress.android.ui.reader.discover.ReaderNavigationEvents.ShowEngagedPeopleList import org.wordpress.android.ui.reader.discover.ReaderNavigationEvents.ShowMediaPreview import org.wordpress.android.ui.reader.discover.ReaderNavigationEvents.ShowPostInWebView import org.wordpress.android.ui.reader.discover.ReaderNavigationEvents.ShowPostsByTag import org.wordpress.android.ui.reader.discover.ReaderNavigationEvents.ShowRelatedPostDetails import org.wordpress.android.ui.reader.discover.ReaderNavigationEvents.ShowSitePickerForResult import org.wordpress.android.ui.reader.discover.ReaderPostActions import org.wordpress.android.ui.reader.discover.ReaderPostCardAction.PrimaryAction import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.BOOKMARK import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.COMMENTS import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.FOLLOW import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.LIKE import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.REBLOG import org.wordpress.android.ui.reader.discover.ReaderPostCardActionsHandler import org.wordpress.android.ui.reader.discover.ReaderPostMoreButtonUiStateBuilder import org.wordpress.android.ui.reader.discover.interests.TagUiState import org.wordpress.android.ui.reader.models.ReaderSimplePost import org.wordpress.android.ui.reader.models.ReaderSimplePostList import org.wordpress.android.ui.reader.reblog.ReblogUseCase import org.wordpress.android.ui.reader.services.comment.wrapper.ReaderCommentServiceStarterWrapper import org.wordpress.android.ui.reader.tracker.ReaderTracker import org.wordpress.android.ui.reader.usecases.ReaderFetchPostUseCase import org.wordpress.android.ui.reader.usecases.ReaderFetchPostUseCase.FetchReaderPostState import org.wordpress.android.ui.reader.usecases.ReaderFetchPostUseCase.FetchReaderPostState.AlreadyRunning import org.wordpress.android.ui.reader.usecases.ReaderFetchPostUseCase.FetchReaderPostState.Failed import org.wordpress.android.ui.reader.usecases.ReaderFetchRelatedPostsUseCase import org.wordpress.android.ui.reader.usecases.ReaderFetchRelatedPostsUseCase.FetchRelatedPostsState import org.wordpress.android.ui.reader.usecases.ReaderGetPostUseCase import org.wordpress.android.ui.reader.usecases.ReaderSiteFollowUseCase.FollowSiteState.FollowStatusChanged import org.wordpress.android.ui.reader.utils.ReaderUtilsWrapper import org.wordpress.android.ui.reader.viewmodels.ReaderPostDetailViewModel.CommentSnippetUiState import org.wordpress.android.ui.reader.viewmodels.ReaderPostDetailViewModel.TrainOfFacesUiState import org.wordpress.android.ui.reader.viewmodels.ReaderPostDetailViewModel.UiState import org.wordpress.android.ui.reader.viewmodels.ReaderPostDetailViewModel.UiState.ErrorUiState import org.wordpress.android.ui.reader.viewmodels.ReaderPostDetailViewModel.UiState.LoadingUiState import org.wordpress.android.ui.reader.viewmodels.ReaderPostDetailViewModel.UiState.ReaderPostDetailsUiState import org.wordpress.android.ui.reader.viewmodels.ReaderPostDetailViewModel.UiState.ReaderPostDetailsUiState.RelatedPostsUiState import org.wordpress.android.ui.reader.viewmodels.ReaderPostDetailViewModel.UiState.ReaderPostDetailsUiState.RelatedPostsUiState.ReaderRelatedPostUiState import org.wordpress.android.ui.reader.views.uistates.FollowButtonUiState import org.wordpress.android.ui.reader.views.uistates.ReaderBlogSectionUiState import org.wordpress.android.ui.reader.views.uistates.ReaderBlogSectionUiState.ReaderBlogSectionClickData import org.wordpress.android.ui.reader.views.uistates.ReaderPostDetailsHeaderViewUiState.ReaderPostDetailsHeaderUiState import org.wordpress.android.ui.utils.HtmlMessageUtils import org.wordpress.android.ui.utils.UiDimen.UIDimenRes import org.wordpress.android.ui.utils.UiString.UiStringRes import org.wordpress.android.ui.utils.UiString.UiStringText import org.wordpress.android.util.EventBusWrapper import org.wordpress.android.util.NetworkUtilsWrapper import org.wordpress.android.util.WpUrlUtilsWrapper import org.wordpress.android.util.config.CommentsSnippetFeatureConfig import org.wordpress.android.util.config.LikesEnhancementsFeatureConfig import org.wordpress.android.util.image.ImageType.BLAVATAR_CIRCULAR import org.wordpress.android.viewmodel.ContextProvider import org.wordpress.android.viewmodel.Event private const val POST_PARAM_POSITION = 0 private const val ON_BUTTON_CLICKED_PARAM_POSITION = 2 private const val ON_POST_BLOG_SECTION_CLICKED_PARAM_POSITION = 3 private const val ON_POST_FOLLOW_BUTTON_CLICKED_PARAM_POSITION = 4 private const val ON_TAG_CLICKED_PARAM_POSITION = 5 private const val IS_GLOBAL_RELATED_POSTS_PARAM_POSITION = 2 private const val ON_RELATED_POST_ITEM_CLICKED_PARAM_POSITION = 3 private const val INTERCEPTED_URI = "intercepted uri" @InternalCoroutinesApi @Suppress("LargeClass") class ReaderPostDetailViewModelTest : BaseUnitTest() { private lateinit var viewModel: ReaderPostDetailViewModel @Mock private lateinit var readerPostCardActionsHandler: ReaderPostCardActionsHandler @Mock private lateinit var readerUtilsWrapper: ReaderUtilsWrapper @Mock private lateinit var postDetailsUiStateBuilder: ReaderPostDetailUiStateBuilder @Mock private lateinit var readerPostTableWrapper: ReaderPostTableWrapper @Mock private lateinit var menuUiStateBuilder: ReaderPostMoreButtonUiStateBuilder @Mock private lateinit var reblogUseCase: ReblogUseCase @Mock private lateinit var readerFetchRelatedPostsUseCase: ReaderFetchRelatedPostsUseCase @Mock private lateinit var readerGetPostUseCase: ReaderGetPostUseCase @Mock private lateinit var readerFetchPostUseCase: ReaderFetchPostUseCase @Mock private lateinit var eventBusWrapper: EventBusWrapper @Mock private lateinit var readerSimplePost: ReaderSimplePost @Mock private lateinit var readerTracker: ReaderTracker @Mock private lateinit var siteStore: SiteStore @Mock private lateinit var accountStore: AccountStore @Mock private lateinit var wpUrlUtilsWrapper: WpUrlUtilsWrapper @Mock private lateinit var getLikesHandler: GetLikesHandler @Mock private lateinit var likesEnhancementsFeatureConfig: LikesEnhancementsFeatureConfig @Mock private lateinit var contextProvider: ContextProvider @Mock private lateinit var engagementUtils: EngagementUtils @Mock private lateinit var htmlMessageUtils: HtmlMessageUtils @Mock private lateinit var networkUtilsWrapper: NetworkUtilsWrapper @Mock private lateinit var commentsSnippetFeatureConfig: CommentsSnippetFeatureConfig @Mock private lateinit var readerCommentTableWrapper: ReaderCommentTableWrapper @Mock private lateinit var readerCommentServiceStarterWrapper: ReaderCommentServiceStarterWrapper private val fakePostFollowStatusChangedFeed = MutableLiveData<FollowStatusChanged>() private val fakeRefreshPostFeed = MutableLiveData<Event<Unit>>() private val fakeNavigationFeed = MutableLiveData<Event<ReaderNavigationEvents>>() private val fakeSnackBarFeed = MutableLiveData<Event<SnackbarMessageHolder>>() private val getLikesState = MutableLiveData<GetLikesState>() private lateinit var likesCaptor: KArgumentCaptor<List<LikeModel>> private val snackbarEvents = MutableLiveData<Event<SnackbarMessageHolder>>() private val readerPost = createDummyReaderPost(2) private val readerCommentSnippetList = createDummyReaderPostCommentSnippetList() private val site = SiteModel().apply { siteId = readerPost.blogId } private lateinit var relatedPosts: ReaderSimplePostList @Before @Suppress("LongMethod") fun setUp() = test { viewModel = ReaderPostDetailViewModel( readerPostCardActionsHandler, readerUtilsWrapper, readerPostTableWrapper, menuUiStateBuilder, postDetailsUiStateBuilder, reblogUseCase, readerFetchRelatedPostsUseCase, readerGetPostUseCase, readerFetchPostUseCase, siteStore, accountStore, readerTracker, eventBusWrapper, wpUrlUtilsWrapper, TEST_DISPATCHER, TEST_DISPATCHER, TEST_DISPATCHER, getLikesHandler, likesEnhancementsFeatureConfig, engagementUtils, htmlMessageUtils, contextProvider, networkUtilsWrapper, commentsSnippetFeatureConfig, readerCommentTableWrapper, readerCommentServiceStarterWrapper ) whenever(readerGetPostUseCase.get(any(), any(), any())).thenReturn(Pair(readerPost, false)) whenever(readerPostCardActionsHandler.followStatusUpdated).thenReturn(fakePostFollowStatusChangedFeed) whenever(readerPostCardActionsHandler.refreshPosts).thenReturn(fakeRefreshPostFeed) whenever(readerPostCardActionsHandler.navigationEvents).thenReturn(fakeNavigationFeed) whenever(readerPostCardActionsHandler.snackbarEvents).thenReturn(fakeSnackBarFeed) whenever(siteStore.getSiteBySiteId(readerPost.blogId)).thenReturn(site) whenever(readerUtilsWrapper.getTagFromTagName(anyOrNull(), anyOrNull())).thenReturn(mock()) whenever( readerPostTableWrapper.getBlogPost( anyOrNull(), anyOrNull(), anyOrNull() ) ).thenReturn(readerPost) whenever( readerCommentTableWrapper.getCommentsForPostSnippet( anyOrNull(), anyOrNull() ) ).thenReturn(readerCommentSnippetList) whenever( postDetailsUiStateBuilder.mapPostToUiState( anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull() ) ).thenAnswer { val post = it.getArgument<ReaderPost>(POST_PARAM_POSITION) // propagate some of the arguments createDummyReaderPostDetailsUiState( post, it.getArgument(ON_TAG_CLICKED_PARAM_POSITION), it.getArgument(ON_BUTTON_CLICKED_PARAM_POSITION), it.getArgument(ON_POST_BLOG_SECTION_CLICKED_PARAM_POSITION), it.getArgument(ON_POST_FOLLOW_BUTTON_CLICKED_PARAM_POSITION) ) } relatedPosts = ReaderSimplePostList().apply { add(readerSimplePost) } whenever( postDetailsUiStateBuilder.mapRelatedPostsToUiState( anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull() ) ).thenAnswer { // propagate some of the arguments createDummyRelatedPostsUiState( it.getArgument(IS_GLOBAL_RELATED_POSTS_PARAM_POSITION), it.getArgument(ON_RELATED_POST_ITEM_CLICKED_PARAM_POSITION) ) } whenever( postDetailsUiStateBuilder.buildCommentSnippetUiState( anyOrNull(), anyOrNull(), anyOrNull() ) ).thenAnswer { createDummyCommentSnippetUiState() } whenever(reblogUseCase.onReblogSiteSelected(ArgumentMatchers.anyInt(), anyOrNull())).thenReturn(mock()) whenever(reblogUseCase.convertReblogStateToNavigationEvent(anyOrNull())).thenReturn(mock<OpenEditorForReblog>()) whenever(likesEnhancementsFeatureConfig.isEnabled()).thenReturn(true) whenever(getLikesHandler.snackbarEvents).thenReturn(snackbarEvents) whenever(getLikesHandler.likesStatusUpdate).thenReturn(getLikesState) whenever(commentsSnippetFeatureConfig.isEnabled()).thenReturn(true) likesCaptor = argumentCaptor() } /* SHOW POST - LOADING */ @Test fun `given local post not found, when show post is triggered, then loading state is shown`() = testWithoutLocalPost { val observers = init(showPost = false) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) assertThat(observers.uiStates.first()).isEqualTo(LoadingUiState) } @Test fun `given local post found, when show post is triggered, then loading state is not shown`() = test { val observers = init(showPost = false) whenever(readerGetPostUseCase.get(anyLong(), anyLong(), anyBoolean())).thenReturn(Pair(readerPost, false)) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) assertThat(observers.uiStates.first()).isNotInstanceOf(LoadingUiState::class.java) } /* SHOW POST - GET LOCAL POST */ @Test fun `given local post is found, when show post is triggered, then ui is updated`() = test { val observers = init(showPost = false) whenever(readerGetPostUseCase.get(anyLong(), anyLong(), anyBoolean())).thenReturn(Pair(readerPost, false)) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) assertThat(observers.uiStates.last()).isInstanceOf(ReaderPostDetailsUiState::class.java) } @Test fun `given local post is found, when show post is triggered, then post is updated in webview`() = test { val observers = init(showPost = false) whenever(readerGetPostUseCase.get(anyLong(), anyLong(), anyBoolean())).thenReturn(Pair(readerPost, false)) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) assertThat(observers.navigation.last().peekContent()).isInstanceOf(ShowPostInWebView::class.java) } @Test fun `given local post not found, when show post is triggered, then post is fetched from remote server`() = testWithoutLocalPost { init(showPost = false) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) verify(readerFetchPostUseCase).fetchPost(readerPost.blogId, readerPost.postId, false) } /* SHOW POST - FETCH SUCCESS HANDLING */ @Test fun `given request succeeded, when post is fetched, then post details ui is updated`() = test { val observers = init() whenever(readerGetPostUseCase.get(any(), any(), any())) .thenReturn(Pair(null, false)) .thenReturn(Pair(readerPost, false)) whenever(readerFetchPostUseCase.fetchPost(anyLong(), anyLong(), anyBoolean())) .thenReturn(FetchReaderPostState.Success) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) val postDetailsUiStates = observers.uiStates.filterIsInstance<ReaderPostDetailsUiState>() assertThat(postDetailsUiStates.size).isEqualTo(2) } @Test fun `given request succeeded, when post is fetched, then post is shown in web view`() = test { val observers = init() whenever(readerGetPostUseCase.get(any(), any(), any())) .thenReturn(Pair(null, false)) .thenReturn(Pair(readerPost, false)) whenever(readerFetchPostUseCase.fetchPost(anyLong(), anyLong(), anyBoolean())) .thenReturn(FetchReaderPostState.Success) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) assertThat(observers.navigation.last().peekContent()).isInstanceOf(ShowPostInWebView::class.java) } /* SHOW POST - FETCH ERROR HANDLING */ @Test fun `given no network, when post is fetched, then no network message is shown`() = testWithoutLocalPost { val observers = init() whenever(readerFetchPostUseCase.fetchPost(anyLong(), anyLong(), anyBoolean())).thenReturn(Failed.NoNetwork) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) assertThat(observers.uiStates.last()).isEqualTo(ErrorUiState(UiStringRes(R.string.no_network_message))) } @Test fun `given request failed, when post is fetched, then request failed message is shown`() = testWithoutLocalPost { val observers = init() whenever(readerFetchPostUseCase.fetchPost(anyLong(), anyLong(), anyBoolean())) .thenReturn(Failed.RequestFailed) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) assertThat(observers.uiStates.last()).isEqualTo(ErrorUiState(UiStringRes(R.string.reader_err_get_post_generic))) } @Test fun `given request already running, when post is fetched, then no error is shown`() = testWithoutLocalPost { val observers = init() whenever(readerFetchPostUseCase.fetchPost(anyLong(), anyLong(), anyBoolean())) .thenReturn(AlreadyRunning) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) assertThat(observers.uiStates.filterIsInstance<ErrorUiState>().last().message).isNull() } @Test fun `given post not found, when post is fetched, then post not found message is shown`() = testWithoutLocalPost { val observers = init() whenever(readerFetchPostUseCase.fetchPost(anyLong(), anyLong(), anyBoolean())) .thenReturn(Failed.PostNotFound) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) assertThat(observers.uiStates.last()) .isEqualTo(ErrorUiState(UiStringRes(R.string.reader_err_get_post_not_found))) } @Test fun `given unauthorised, when post is fetched, then error ui is shown`() = testWithoutLocalPost { val observers = init() whenever(readerFetchPostUseCase.fetchPost(anyLong(), anyLong(), anyBoolean())) .thenReturn(Failed.PostNotFound) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) assertThat(observers.uiStates.last()).isInstanceOf(ErrorUiState::class.java) } @Test fun `given unauthorised with signin offer, when error ui shown, then sign in button is visible`() = testWithoutLocalPost { val observers = init(offerSignIn = true) whenever(readerFetchPostUseCase.fetchPost(anyLong(), anyLong(), anyBoolean())) .thenReturn(Failed.NotAuthorised) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) assertThat((observers.uiStates.last() as ErrorUiState).signInButtonVisibility).isEqualTo(true) } @Test fun `given unauthorised without signin offer, when error ui shown, then sign in button is not visible`() = testWithoutLocalPost { val observers = init(offerSignIn = false) whenever(readerFetchPostUseCase.fetchPost(anyLong(), anyLong(), anyBoolean())) .thenReturn(Failed.NotAuthorised) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) assertThat((observers.uiStates.last() as ErrorUiState).signInButtonVisibility).isEqualTo(false) } @Test fun `given unauthorised with no signin offer and no intercept uri, when error ui shown, then correct msg exists`() = testWithoutLocalPost { val observers = init(offerSignIn = false, interceptedUrPresent = false) whenever(readerFetchPostUseCase.fetchPost(anyLong(), anyLong(), anyBoolean())) .thenReturn(Failed.NotAuthorised) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) assertThat((observers.uiStates.last() as ErrorUiState).message) .isEqualTo(UiStringRes(R.string.reader_err_get_post_not_authorized)) } @Test fun `given unauthorised with no signin offer and intercept uri, when error ui shown, then correct msg exists`() = testWithoutLocalPost { val observers = init(offerSignIn = false, interceptedUrPresent = true) whenever(readerFetchPostUseCase.fetchPost(anyLong(), anyLong(), anyBoolean())) .thenReturn(Failed.NotAuthorised) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) assertThat((observers.uiStates.last() as ErrorUiState).message) .isEqualTo(UiStringRes(R.string.reader_err_get_post_not_authorized_fallback)) } @Test fun `given unauthorised with signin offer and no intercept uri, when error ui shown, then correct msg exists`() = testWithoutLocalPost { val observers = init(offerSignIn = true, interceptedUrPresent = false) whenever(readerFetchPostUseCase.fetchPost(anyLong(), anyLong(), anyBoolean())) .thenReturn(Failed.NotAuthorised) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) assertThat((observers.uiStates.last() as ErrorUiState).message) .isEqualTo(UiStringRes(R.string.reader_err_get_post_not_authorized_signin)) } @Test fun `given unauthorised with signin offer and intercept uri, when error ui shown, then correct msg exists`() = testWithoutLocalPost { val observers = init(offerSignIn = true, interceptedUrPresent = true) whenever(readerFetchPostUseCase.fetchPost(anyLong(), anyLong(), anyBoolean())) .thenReturn(Failed.NotAuthorised) viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) assertThat((observers.uiStates.last() as ErrorUiState).message) .isEqualTo(UiStringRes(R.string.reader_err_get_post_not_authorized_signin_fallback)) } /* UPDATE POST */ @Test fun `when post is updated, then ui is updated`() = test { val uiStates = init().uiStates viewModel.onUpdatePost(readerPost) assertThat(uiStates.filterIsInstance<ReaderPostDetailsUiState>().size).isEqualTo(2) } /* READER POST FEATURED IMAGE */ @Test fun `when featured image is clicked, then media preview is shown`() = test { val observers = init() viewModel.onFeaturedImageClicked(blogId = readerPost.blogId, featuredImageUrl = readerPost.featuredImage) assertThat(observers.navigation.last().peekContent()).isInstanceOf(ShowMediaPreview::class.java) } @Test fun `when media preview is requested, then correct media from selected post's site is previewed`() = test { val observers = init() viewModel.onFeaturedImageClicked(blogId = readerPost.blogId, featuredImageUrl = readerPost.featuredImage) assertThat(observers.navigation.last().peekContent() as ShowMediaPreview).isEqualTo( ShowMediaPreview(site = site, featuredImage = readerPost.featuredImage) ) } /* MORE MENU */ @Test fun `when more button is clicked, then more menu is shown`() = test { val uiState = (init().uiStates.last() as ReaderPostDetailsUiState) viewModel.onMoreButtonClicked() assertThat(uiState.moreMenuItems).isNotNull } @Test fun `when user dismisses the menu, then more menu is not shown`() = test { val uiStates = init().uiStates viewModel.onMoreMenuDismissed() assertThat((uiStates.last() as ReaderPostDetailsUiState).moreMenuItems).isNull() } @Test fun `when more menu list item is clicked, then corresponding action is invoked`() = test { init().uiStates viewModel.onMoreMenuItemClicked(FOLLOW) verify(readerPostCardActionsHandler).onAction( eq(readerPost), eq(FOLLOW), eq(false), anyString() ) } /* HEADER */ @Test fun `when tag is clicked, then posts for tag are shown`() = test { val observers = init() val uiState = (observers.uiStates.last() as ReaderPostDetailsUiState) uiState.headerUiState.tagItems[0].onClick!!.invoke("t") assertThat(observers.navigation.last().peekContent()).isInstanceOf(ShowPostsByTag::class.java) } @Test fun `when header blog section is clicked, then selected blog's header click action is invoked`() = test { val uiState = (init().uiStates.last() as ReaderPostDetailsUiState) uiState.headerUiState.blogSectionUiState.blogSectionClickData!!.onBlogSectionClicked!! .invoke(readerPost.postId, readerPost.blogId) verify(readerPostCardActionsHandler).handleHeaderClicked( eq(readerPost.blogId), eq(readerPost.feedId), eq(readerPost.isFollowedByCurrentUser) ) } @Test fun `when header follow button is clicked, then follow action is invoked`() = test { val uiState = (init().uiStates.last() as ReaderPostDetailsUiState) uiState.headerUiState.followButtonUiState.onFollowButtonClicked!!.invoke() verify(readerPostCardActionsHandler).onAction( eq(readerPost), eq(FOLLOW), eq(false), anyString() ) } /* EXCERPT FOOTER */ @Test fun `when visit excerpt link is clicked, then post blog url is opened`() = test { val observers = init() viewModel.onVisitPostExcerptFooterClicked(postLink = readerPost.url) assertThat(observers.navigation.last().peekContent()).isEqualTo(OpenUrl(url = readerPost.url)) } /* RELATED POSTS */ @Test fun `given local related posts fetch succeeds, when related posts are requested, then local related posts shown`() = test { val localRelatedPostsUiState = createDummyRelatedPostsUiState(isGlobal = false) whenever( postDetailsUiStateBuilder.mapRelatedPostsToUiState( sourcePost = eq(readerPost), relatedPosts = eq(relatedPosts), isGlobal = eq(false), onItemClicked = any() ) ).thenReturn(localRelatedPostsUiState) whenever(readerFetchRelatedPostsUseCase.fetchRelatedPosts(readerPost)) .thenReturn( FetchRelatedPostsState.Success( localRelatedPosts = relatedPosts, globalRelatedPosts = ReaderSimplePostList() ) ) val uiStates = init().uiStates viewModel.onRelatedPostsRequested(readerPost) val uiState = (uiStates.last() as ReaderPostDetailsUiState) assertThat(uiState.localRelatedPosts).isEqualTo(localRelatedPostsUiState) } @Test fun `given global related posts fetch succeeds, when related posts requested, then global related posts shown`() = test { val globalRelatedPostsUiState = createDummyRelatedPostsUiState(isGlobal = false) whenever( postDetailsUiStateBuilder.mapRelatedPostsToUiState( sourcePost = eq(readerPost), relatedPosts = eq(relatedPosts), isGlobal = eq(true), onItemClicked = any() ) ).thenReturn(globalRelatedPostsUiState) whenever(readerFetchRelatedPostsUseCase.fetchRelatedPosts(readerPost)) .thenReturn( FetchRelatedPostsState.Success( localRelatedPosts = ReaderSimplePostList(), globalRelatedPosts = relatedPosts ) ) val uiStates = init().uiStates viewModel.onRelatedPostsRequested(readerPost) val uiState = (uiStates.last() as ReaderPostDetailsUiState) assertThat(uiState.globalRelatedPosts).isEqualTo(globalRelatedPostsUiState) } @Test fun `given related posts fetch fails, when related posts are requested, then related posts are not shown`() = test { whenever(readerFetchRelatedPostsUseCase.fetchRelatedPosts(readerPost)) .thenReturn(FetchRelatedPostsState.Failed.RequestFailed) val uiStates = init().uiStates viewModel.onRelatedPostsRequested(readerPost) val uiState = (uiStates.last() as ReaderPostDetailsUiState) with(uiState) { assertThat(localRelatedPosts).isNull() assertThat(globalRelatedPosts).isNull() } } @Test fun `given no network, when related posts are requested, then related posts are not shown`() = test { whenever(readerFetchRelatedPostsUseCase.fetchRelatedPosts(readerPost)) .thenReturn(FetchRelatedPostsState.Failed.NoNetwork) val uiStates = init().uiStates viewModel.onRelatedPostsRequested(readerPost) val uiState = (uiStates.last() as ReaderPostDetailsUiState) with(uiState) { assertThat(localRelatedPosts).isNull() assertThat(globalRelatedPosts).isNull() } } @Test fun `given related posts fetch in progress, when related posts are requested, then related posts are not shown`() = test { whenever(readerFetchRelatedPostsUseCase.fetchRelatedPosts(readerPost)) .thenReturn(FetchRelatedPostsState.AlreadyRunning) val uiStates = init().uiStates viewModel.onRelatedPostsRequested(readerPost) val uiState = (uiStates.last() as ReaderPostDetailsUiState) with(uiState) { assertThat(localRelatedPosts).isNull() assertThat(globalRelatedPosts).isNull() } } @Test fun `given wp com post, when related posts are requested, then related posts are fetched`() = test { whenever(readerFetchRelatedPostsUseCase.fetchRelatedPosts(readerPost)).thenReturn(mock()) viewModel.onRelatedPostsRequested(readerPost) verify(readerFetchRelatedPostsUseCase).fetchRelatedPosts(readerPost) } @Test fun `given non wp com post, when related posts are requested, then related posts are not fetched`() = test { val nonWpComPost = createDummyReaderPost(id = 1, isWpComPost = false) viewModel.onRelatedPostsRequested(nonWpComPost) verify(readerFetchRelatedPostsUseCase, times(0)).fetchRelatedPosts(readerPost) } @Test fun `when related post is clicked from non related post details screen, then related post details screen shown`() = test { whenever(readerFetchRelatedPostsUseCase.fetchRelatedPosts(readerPost)) .thenReturn( FetchRelatedPostsState.Success( localRelatedPosts = ReaderSimplePostList(), globalRelatedPosts = relatedPosts ) ) val observers = init(isRelatedPost = false) viewModel.onRelatedPostsRequested(readerPost) val uiState = (observers.uiStates.last() as ReaderPostDetailsUiState) val relatedPost = uiState.globalRelatedPosts?.cards?.first() relatedPost?.onItemClicked?.invoke(relatedPost.postId, relatedPost.blogId, relatedPost.isGlobal) assertThat(observers.navigation.last().peekContent()).isInstanceOf(ShowRelatedPostDetails::class.java) } @Test fun `when related post is clicked from related post screen, then related post replaced with history`() = test { whenever(readerFetchRelatedPostsUseCase.fetchRelatedPosts(readerPost)) .thenReturn( FetchRelatedPostsState.Success( localRelatedPosts = ReaderSimplePostList(), globalRelatedPosts = relatedPosts ) ) val observers = init(isRelatedPost = true) viewModel.onRelatedPostsRequested(readerPost) val uiState = (observers.uiStates.last() as ReaderPostDetailsUiState) val relatedPost = uiState.globalRelatedPosts?.cards?.first() relatedPost?.onItemClicked?.invoke(relatedPost.postId, relatedPost.blogId, relatedPost.isGlobal) assertThat(observers.navigation.last().peekContent()) .isInstanceOf(ReplaceRelatedPostDetailsWithHistory::class.java) } /* FOOTER */ @Test fun `when like button is clicked, then like action is invoked`() = test { val uiState = (init().uiStates.last() as ReaderPostDetailsUiState) uiState.actions.likeAction.onClicked!!.invoke(readerPost.postId, 200, LIKE) verify(readerPostCardActionsHandler).onAction( eq(readerPost), eq(LIKE), eq(false), anyString() ) } @Test fun `when comments button is clicked, then comments action is invoked`() = test { val uiState = (init().uiStates.last() as ReaderPostDetailsUiState) uiState.actions.commentsAction.onClicked!!.invoke(readerPost.postId, 200, COMMENTS) verify(readerPostCardActionsHandler).onAction( eq(readerPost), eq(COMMENTS), eq(false), anyString() ) } @Test fun `when reblog button is clicked, then reblog action is invoked`() = test { val uiState = (init().uiStates.last() as ReaderPostDetailsUiState) uiState.actions.commentsAction.onClicked!!.invoke(readerPost.postId, 200, REBLOG) verify(readerPostCardActionsHandler).onAction( eq(readerPost), eq(REBLOG), eq(false), anyString() ) } @Test fun `when site is picked for reblog action, then editor is opened for reblog`() { val navigaitonObserver = init().navigation fakeNavigationFeed.value = Event(ShowSitePickerForResult(mock(), mock(), mock())) viewModel.onReblogSiteSelected(1) assertThat(navigaitonObserver.last().peekContent()).isInstanceOf(OpenEditorForReblog::class.java) } @Test fun `when bookmark button is clicked, then bookmark action is invoked`() = test { val uiState = (init().uiStates.last() as ReaderPostDetailsUiState) uiState.actions.commentsAction.onClicked!!.invoke(readerPost.postId, 200, BOOKMARK) verify(readerPostCardActionsHandler).onAction( eq(readerPost), eq(BOOKMARK), eq(false), anyString() ) } @Test fun `likes for post are refreshed on request`() = test { val likesState = getGetLikesState(TEST_CONFIG_1) as LikesData whenever(accountStore.account).thenReturn(AccountModel().apply { userId = -1 }) getLikesState.value = likesState init() viewModel.onRefreshLikersData(viewModel.post!!) verify( getLikesHandler, times(1) ).handleGetLikesForPost(anyOrNull(), anyBoolean(), anyInt()) } @Test fun `user avatar is added as last on like action`() = test { val likesState = (getGetLikesState(TEST_CONFIG_1) as LikesData) whenever(accountStore.account).thenReturn(AccountModel().apply { userId = -1 avatarUrl = "https://avatar.url.example/image.jpg" }) whenever(engagementUtils.likesToTrainOfFaces(likesCaptor.capture())).thenReturn(listOf()) getLikesState.value = likesState val post = ReaderPost().apply { isExternal = false isLikedByCurrentUser = true } viewModel.post = post init() viewModel.onRefreshLikersData(post, true) verify( getLikesHandler, times(0) ).handleGetLikesForPost(anyOrNull(), anyBoolean(), anyInt()) val listOfFaces = likesCaptor.lastValue assertThat(listOfFaces.size).isEqualTo(ReaderPostDetailViewModel.MAX_NUM_LIKES_FACES_WITH_SELF) assertThat(listOfFaces.last().likerAvatarUrl).isEqualTo(accountStore.account.avatarUrl) } @Test fun `ui state show likers faces when data available`() { val likesState = getGetLikesState(TEST_CONFIG_1) as LikesData val likers = MutableList(5) { mock<AvatarItem>() } val testTextString = "10 bloggers like this." getLikesState.value = likesState whenever(accountStore.account).thenReturn(AccountModel().apply { userId = -1 }) whenever(engagementUtils.likesToTrainOfFaces(anyList())).thenReturn(likers) whenever(htmlMessageUtils.getHtmlMessageFromStringFormatResId(anyInt(), anyInt())).thenReturn(testTextString) val post = mock<ReaderPost>() whenever(post.isWP).thenReturn(true) viewModel.post = post val likeObserver = init().likesUiState getLikesState.value = likesState assertThat(likeObserver).isNotEmpty with(likeObserver.first()) { assertThat(showLoading).isFalse assertThat(engageItemsList).isEqualTo( likers + TrailingLabelTextItem( UiStringText( testTextString ), R.attr.wpColorOnSurfaceMedium ) ) assertThat(showEmptyState).isFalse assertThat(emptyStateTitle).isNull() } } @Test fun `ui state shows empty state on failure and no cached data`() { val likesState = getGetLikesState(TEST_CONFIG_5) as Failure val likers = listOf<Liker>() getLikesState.value = likesState val post = mock<ReaderPost>() whenever(post.isWP).thenReturn(true) viewModel.post = post val likeObserver = init().likesUiState getLikesState.value = likesState assertThat(likeObserver).isNotEmpty with(likeObserver.first()) { assertThat(showLoading).isFalse assertThat(engageItemsList).isEqualTo(likers) assertThat(showEmptyState).isTrue assertThat(emptyStateTitle is UiStringRes).isTrue } } @Test fun `likers list is shown when like faces are clicked`() { val post = mock<ReaderPost>() viewModel.post = post val navigation = init().navigation viewModel.onLikeFacesClicked() assertThat(navigation.last().peekContent()).isInstanceOf(ShowEngagedPeopleList::class.java) } @Test fun `navigating back from comments updates data in snippet and bottom bar`() { val commentSnippetUiStates = init().commentSnippetUiState val modifiedPost = createDummyReaderPost(readerPost.postId) modifiedPost.numReplies = 10 whenever( readerPostTableWrapper.getBlogPost( anyOrNull(), anyOrNull(), anyOrNull() ) ).thenReturn(modifiedPost) whenever( postDetailsUiStateBuilder.buildCommentSnippetUiState( anyOrNull(), anyOrNull(), anyOrNull() ) ).thenAnswer { createDummyCommentSnippetUiState(10) } viewModel.onUserNavigateFromComments() assertThat(viewModel.post?.numReplies).isEqualTo(10) assertThat(commentSnippetUiStates).isNotEmpty with(commentSnippetUiStates.last()) { assertThat(commentsNumber).isEqualTo(10) } } @Test fun `onRefreshCommentsData does not start comment snippet service for external posts`() { val externalPost = createDummyReaderPost(1, isWpComPost = false) whenever( readerPostTableWrapper.getBlogPost( anyOrNull(), anyOrNull(), anyOrNull() ) ).thenReturn(externalPost) viewModel.onRefreshCommentsData(1, 1) verify(readerCommentServiceStarterWrapper, never()).startServiceForCommentSnippet( anyOrNull(), anyOrNull(), anyOrNull() ) } private fun <T> testWithoutLocalPost(block: suspend CoroutineScope.() -> T) { test { whenever(readerGetPostUseCase.get(any(), any(), any())).thenReturn(Pair(null, false)) block() } } private fun createDummyReaderPost(id: Long, isWpComPost: Boolean = true): ReaderPost = ReaderPost().apply { this.postId = id this.blogId = id * 100 this.feedId = id * 1000 this.title = "DummyPost" this.featuredVideo = id.toString() this.featuredImage = "/featured_image/$id/url" this.isExternal = !isWpComPost this.numReplies = 1 } private fun createDummyReaderPostCommentSnippetList(): ReaderCommentList = ReaderCommentList().apply { val comment = ReaderComment() comment.commentId = 3 add(comment) } private fun createDummyReaderPostDetailsUiState( post: ReaderPost, onTagClicked: (String) -> Unit, onButtonClicked: (Long, Long, ReaderPostCardActionType) -> Unit, onBlogSectionClicked: (Long, Long) -> Unit, onFollowButtonClicked: (() -> Unit) ): ReaderPostDetailsUiState { return ReaderPostDetailsUiState( postId = post.postId, blogId = post.blogId, featuredImageUiState = mock(), headerUiState = ReaderPostDetailsHeaderUiState( UiStringText(post.title), post.authorName, listOf(TagUiState("", "", false, onTagClicked)), true, ReaderBlogSectionUiState( postId = post.postId, blogId = post.blogId, dateLine = "", blogName = mock(), blogUrl = "", avatarOrBlavatarUrl = "", authorAvatarUrl = "", isAuthorAvatarVisible = false, blavatarType = BLAVATAR_CIRCULAR, blogSectionClickData = ReaderBlogSectionClickData(onBlogSectionClicked, 0) ), FollowButtonUiState( onFollowButtonClicked = onFollowButtonClicked, isFollowed = false, isEnabled = true, isVisible = true ), "" ), excerptFooterUiState = mock(), moreMenuItems = mock(), actions = ReaderPostActions( bookmarkAction = PrimaryAction(true, onClicked = onButtonClicked, type = BOOKMARK), likeAction = PrimaryAction(true, onClicked = onButtonClicked, type = LIKE), reblogAction = PrimaryAction(true, onClicked = onButtonClicked, type = REBLOG), commentsAction = PrimaryAction(true, onClicked = onButtonClicked, type = COMMENTS) ) ) } private fun createDummyRelatedPostsUiState( isGlobal: Boolean, onRelatedPostItemClicked: ((Long, Long, Boolean) -> Unit)? = null ) = RelatedPostsUiState( cards = relatedPosts.map { ReaderRelatedPostUiState( postId = it.postId, blogId = it.siteId, isGlobal = isGlobal, title = UiStringText(""), excerpt = UiStringText(""), featuredImageUrl = "", featuredImageVisibility = false, featuredImageCornerRadius = UIDimenRes(R.dimen.reader_featured_image_corner_radius), onItemClicked = onRelatedPostItemClicked ?: mock() ) }, isGlobal = isGlobal, headerLabel = UiStringText(""), railcarJsonStrings = emptyList() ) private fun createDummyCommentSnippetUiState(numberOfComments: Int = 1) = CommentSnippetUiState( commentsNumber = numberOfComments, showFollowConversation = true, emptyList() ) private fun init( showPost: Boolean = true, isRelatedPost: Boolean = false, isFeed: Boolean = false, offerSignIn: Boolean = false, interceptedUrPresent: Boolean = false ): Observers { val uiStates = mutableListOf<UiState>() viewModel.uiState.observeForever { uiStates.add(it) } val navigation = mutableListOf<Event<ReaderNavigationEvents>>() viewModel.navigationEvents.observeForever { navigation.add(it) } val msgs = mutableListOf<Event<SnackbarMessageHolder>>() viewModel.snackbarEvents.observeForever { msgs.add(it) } val likesUiStates = mutableListOf<TrainOfFacesUiState>() viewModel.likesUiState.observeForever { likesUiStates.add(it) } val commentSnippetUiStates = mutableListOf<CommentSnippetUiState>() viewModel.commentSnippetState.observeForever { commentSnippetUiStates.add(it) } val interceptedUri = INTERCEPTED_URI.takeIf { interceptedUrPresent } if (offerSignIn) { whenever(wpUrlUtilsWrapper.isWordPressCom(interceptedUri)).thenReturn(true) whenever(accountStore.hasAccessToken()).thenReturn(false) } else { whenever(wpUrlUtilsWrapper.isWordPressCom(interceptedUri)).thenReturn(false) } viewModel.start(isRelatedPost = isRelatedPost, isFeed = isFeed, interceptedUri = interceptedUri) if (showPost) { viewModel.onShowPost(blogId = readerPost.blogId, postId = readerPost.postId) } return Observers( uiStates, navigation, msgs, likesUiStates, commentSnippetUiStates ) } private data class Observers( val uiStates: List<UiState>, val navigation: List<Event<ReaderNavigationEvents>>, val snackbarMsgs: List<Event<SnackbarMessageHolder>>, val likesUiState: List<TrainOfFacesUiState>, val commentSnippetUiState: List<CommentSnippetUiState> ) }
WordPress/src/test/java/org/wordpress/android/ui/reader/viewmodels/ReaderPostDetailViewModelTest.kt
500366558
package ee.es import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test import java.io.File class ExportControllerTest { @Disabled @Test fun testWriteExportConfig() { val config = exportConfig() val objectMapper: ObjectMapper = jacksonObjectMapper() objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.writeValue(exportConfigFile(), config) } @Disabled @Test fun testReadExportConfig() { val config = exportConfig() val objectMapper: ObjectMapper = jacksonObjectMapper() val loadedConfig = objectMapper.readValue(exportConfigFile(), ExportConfig::class.java) assertEquals(config, loadedConfig) } //@Disabled @Test fun testExport() { val config = exportConfig() val controller = ExportController(config) controller.export() } private fun exportConfig(): ExportConfig { val config = ExportConfig("D:/TC_CACHE/logs/export/tid1.log") config.indexes = arrayOf("logstash-2017.05.18") config.fields = arrayOf("logdate", "type", "level", "logger", "dur", "kind", "message") val thread: String = "0:ffff0a7f642d:912b6af:591c0cff:207dff" /*config.searchSource = SearchSourceBuilder.searchSource().query(match_phrase { "thread" to { query = thread } }).sort("@logdate", SortOrder.ASC).sort("sequence", SortOrder.ASC).toString() println(config.searchSource) */ return config } private fun exportConfigFile() = File("D:/TC_CACHE/logs/export/exportConfig.json") }
ee-elastic/src/test/kotlin/ee/es/ExportControllerTest.kt
2896397979
/* * Copyright (C) 2020 Tobias Preuss * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.avpptr.umweltzone.details import android.app.Activity import android.os.Bundle import android.os.Parcelable import android.view.LayoutInflater import android.view.View import android.widget.LinearLayout import android.widget.LinearLayout.LayoutParams import android.widget.TextView import androidx.annotation.LayoutRes import androidx.core.os.bundleOf import androidx.core.view.isVisible import de.avpptr.umweltzone.BuildConfig import de.avpptr.umweltzone.R import de.avpptr.umweltzone.base.BaseFragment import de.avpptr.umweltzone.details.dataconverters.toDetailsViewModel import de.avpptr.umweltzone.details.dataconverters.toOtherDetailsViewModel import de.avpptr.umweltzone.details.viewmodels.DpzDetailsViewModel import de.avpptr.umweltzone.details.viewmodels.LezDetailsViewModel import de.avpptr.umweltzone.details.viewmodels.OtherDetailsViewModel import de.avpptr.umweltzone.extensions.textOrHide import de.avpptr.umweltzone.extensions.typeOrHide import de.avpptr.umweltzone.models.AdministrativeZone import de.avpptr.umweltzone.models.ChildZone import de.avpptr.umweltzone.models.DieselProhibitionZone import de.avpptr.umweltzone.models.LowEmissionZone import de.avpptr.umweltzone.utils.ViewHelper import info.metadude.kotlin.library.roadsigns.RoadSign import org.parceler.Parcels class DetailsFragment : BaseFragment() { private val zoneDetailsView by lazy { view?.findViewById(R.id.zoneDetailsView) as LinearLayout } private var administrativeZone: AdministrativeZone? = null public override fun getLayoutResource() = R.layout.fragment_zone_details override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val extras = arguments if (extras != null) { val parcelable = extras.getParcelable<Parcelable>(BUNDLE_KEY_ADMINISTRATIVE_ZONE) administrativeZone = Parcels.unwrap<AdministrativeZone>(parcelable) } } override fun onResume() { super.onResume() if (activity != null && administrativeZone != null) { updateDetails(activity!!, administrativeZone!!) updateSubTitle(administrativeZone!!.displayName) } } private fun updateDetails(activity: Activity, zone: AdministrativeZone) { zoneDetailsView.removeAllViews() zone.childZones.forEach { updateChildZoneDetails(activity, it) } addOtherDetails(zone.toOtherDetailsViewModel()) addVerticalSpace() } private fun updateChildZoneDetails(activity: Activity, childZone: ChildZone) { when (childZone) { is LowEmissionZone -> addLowEmissionZoneDetails(childZone.toDetailsViewModel(activity)) is DieselProhibitionZone -> addDieselProhibitionZoneDetails(childZone.toDetailsViewModel(activity)) } } private fun addLowEmissionZoneDetails(viewModel: LezDetailsViewModel) { val detailsView = layoutInflater.inflate(R.layout.details_low_emission_zone) updateLezDetails(detailsView, viewModel) zoneDetailsView.addChildView(detailsView) } private fun addDieselProhibitionZoneDetails(viewModel: DpzDetailsViewModel) { val detailsView = layoutInflater.inflate(R.layout.details_diesel_prohibition_zone) updateDpzDetails(detailsView, viewModel) zoneDetailsView.addChildView(detailsView) } private fun addOtherDetails(viewModel: OtherDetailsViewModel) { val detailsView = layoutInflater.inflate(R.layout.details_other) updateOtherDetails(detailsView, viewModel) zoneDetailsView.addChildView(detailsView) } private fun addVerticalSpace() { val detailsView = layoutInflater.inflate(R.layout.vertical_space) zoneDetailsView.addChildView(detailsView) } private fun LayoutInflater.inflate(@LayoutRes resource: Int) = inflate(resource, zoneDetailsView, false) private fun LinearLayout.addChildView(view: View) = addView(view, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)) private fun updateLezDetails(rootView: View, model: LezDetailsViewModel) { val roadSignView = rootView.findViewById(R.id.detailsLezRoadSignView) as RoadSign val listOfCitiesView = rootView.findViewById(R.id.detailsLezListOfCitiesView) as TextView val zoneNumberSinceView = rootView.findViewById(R.id.detailsLezZoneNumberSinceView) as TextView val nextZoneNumberAsOfView = rootView.findViewById(R.id.detailsLezNextZoneNumberAsOfView) as TextView val abroadLicensedVehicleZoneInfoView = rootView.findViewById(R.id.detailsLezAbroadLicensedVehicleZoneInfoView) as TextView val geometryUpdatedAtView = rootView.findViewById(R.id.detailsLezGeometryUpdatedAtView) as TextView val geometrySourceView = rootView.findViewById(R.id.detailsLezGeometrySourceView) as TextView return with(model) { roadSignView.typeOrHide = roadSignType listOfCitiesView.textOrHide = listOfCitiesText zoneNumberSinceView.textOrHide = zoneNumberSinceText nextZoneNumberAsOfView.textOrHide = nextZoneNumberAsOfText abroadLicensedVehicleZoneInfoView.textOrHide = abroadLicensedVehicleZoneNumberText geometryUpdatedAtView.textOrHide = geometryUpdatedAtText geometrySourceView.textOrHide = geometrySourceText } } private fun updateDpzDetails(rootView: View, model: DpzDetailsViewModel) { val displayNameView = rootView.findViewById(R.id.detailsDpzDisplayNameView) as TextView val roadSignView = rootView.findViewById(R.id.detailsDpzRoadSignView) as RoadSign val allowedEmissionStandardInDpzView = rootView.findViewById(R.id.detailsDpzAllowedEmissionStandardInDpzView) as TextView val isCongruentWithLowEmissionZoneView = rootView.findViewById(R.id.detailsDpzIsCongruentWithLowEmissionZoneView) as TextView val zoneNumberForResidentsSinceView = rootView.findViewById(R.id.detailsDpzZoneNumberForResidentsSinceView) as TextView val zoneNumberForNonResidentsSinceView = rootView.findViewById(R.id.detailsDpzZoneNumberForNonResidentsSinceView) as TextView val prohibitedVehiclesView = rootView.findViewById(R.id.detailsDpzProhibitedVehiclesView) as TextView val geometrySourceView = rootView.findViewById(R.id.detailsDpzGeometrySourceView) as TextView val geometryUpdatedAtView = rootView.findViewById(R.id.detailsDpzGeometryUpdatedAtView) as TextView return with(model) { displayNameView.textOrHide = displayName roadSignView.typeOrHide = roadSignType allowedEmissionStandardInDpzView.textOrHide = allowedEmissionStandardInDpz isCongruentWithLowEmissionZoneView.textOrHide = isCongruentWithLowEmissionZone zoneNumberForResidentsSinceView.textOrHide = zoneNumberForResidentsSince zoneNumberForNonResidentsSinceView.textOrHide = zoneNumberForNonResidentsSince prohibitedVehiclesView.textOrHide = prohibitedVehicles geometrySourceView.textOrHide = geometrySource geometryUpdatedAtView.textOrHide = geometryUpdatedAt } } private fun updateOtherDetails(rootView: View, model: OtherDetailsViewModel) { val furtherInformationView = rootView.findViewById(R.id.detailsOtherFurtherInformationView) as TextView val badgeOnlineView = rootView.findViewById(R.id.detailsOtherBadgeOnlineView) as TextView val activity = requireActivity() return with(model) { ViewHelper.setupTextViewExtended(activity, furtherInformationView, R.string.city_info_further_information, furtherInformation) if (urlBadgeOnline.isEmpty()) { badgeOnlineView.isVisible = false } else { badgeOnlineView.isVisible = true ViewHelper.setupTextViewExtended(activity, badgeOnlineView, R.string.city_info_badge_online_title, urlBadgeOnline) } } } companion object { const val FRAGMENT_TAG = BuildConfig.APPLICATION_ID + ".DETAILS_FRAGMENT_TAG" const val BUNDLE_KEY_ADMINISTRATIVE_ZONE = BuildConfig.APPLICATION_ID + ".ADMINISTRATIVE_ZONE_BUNDLE_KEY" @JvmStatic fun newInstance(administrativeZone: AdministrativeZone): DetailsFragment { val fragment = DetailsFragment() val parcelable = Parcels.wrap(administrativeZone) val extras = bundleOf( BUNDLE_KEY_ADMINISTRATIVE_ZONE to parcelable ) fragment.arguments = extras return fragment } } }
Umweltzone/src/main/java/de/avpptr/umweltzone/details/DetailsFragment.kt
746741481
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.project import com.intellij.openapi.module.Module import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.idea.base.facet.implementedModules import org.jetbrains.kotlin.idea.base.facet.implementingModules import org.jetbrains.kotlin.idea.base.facet.kotlinSourceRootType import org.jetbrains.kotlin.idea.base.projectStructure.kotlinSourceRootType import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo import org.jetbrains.kotlin.idea.base.projectStructure.unwrapModuleSourceInfo import org.jetbrains.kotlin.idea.caches.project.* import org.jetbrains.kotlin.resolve.ModulePath import org.jetbrains.kotlin.resolve.ModuleStructureOracle import java.util.* class IdeaModuleStructureOracle : ModuleStructureOracle { override fun hasImplementingModules(module: ModuleDescriptor): Boolean { return module.implementingDescriptors.isNotEmpty() } override fun findAllReversedDependsOnPaths(module: ModuleDescriptor): List<ModulePath> { val currentPath: Stack<ModuleInfo> = Stack() return sequence<ModuleInfoPath> { val root = module.moduleInfo if (root != null) { yieldPathsFromSubgraph( root, currentPath, getChilds = { with(DependsOnGraphHelper) { it.unwrapModuleSourceInfo()?.predecessorsInDependsOnGraph() ?: emptyList() } } ) } }.map { it.toModulePath() }.toList() } override fun findAllDependsOnPaths(module: ModuleDescriptor): List<ModulePath> { val currentPath: Stack<ModuleInfo> = Stack() return sequence<ModuleInfoPath> { val root = module.moduleInfo if (root != null) { yieldPathsFromSubgraph( root, currentPath, getChilds = { with(DependsOnGraphHelper) { it.unwrapModuleSourceInfo()?.successorsInDependsOnGraph() ?: emptyList() } } ) } }.map { it.toModulePath() }.toList() } private suspend fun SequenceScope<ModuleInfoPath>.yieldPathsFromSubgraph( root: ModuleInfo, currentPath: Stack<ModuleInfo>, getChilds: (ModuleInfo) -> List<ModuleInfo> ) { currentPath.push(root) val childs = getChilds(root) if (childs.isEmpty()) { yield(ModuleInfoPath(currentPath.toList())) } else { childs.forEach { yieldPathsFromSubgraph(it, currentPath, getChilds) } } currentPath.pop() } private class ModuleInfoPath(val nodes: List<ModuleInfo>) private fun ModuleInfoPath.toModulePath(): ModulePath = ModulePath(nodes.mapNotNull { it.unwrapModuleSourceInfo()?.toDescriptor() }) } object DependsOnGraphHelper { fun ModuleDescriptor.predecessorsInDependsOnGraph(): List<ModuleDescriptor> { return moduleSourceInfo ?.predecessorsInDependsOnGraph() ?.mapNotNull { it.toDescriptor() } ?: emptyList() } fun ModuleSourceInfo.predecessorsInDependsOnGraph(): List<ModuleSourceInfo> { val sourceRootType = this.kotlinSourceRootType ?: return emptyList() return this.module.predecessorsInDependsOnGraph().mapNotNull { it.getModuleInfo(sourceRootType) } } fun Module.predecessorsInDependsOnGraph(): List<Module> { return implementingModules } fun ModuleDescriptor.successorsInDependsOnGraph(): List<ModuleDescriptor> { return moduleSourceInfo ?.successorsInDependsOnGraph() ?.mapNotNull { it.toDescriptor() } ?: emptyList() } fun ModuleSourceInfo.successorsInDependsOnGraph(): List<ModuleSourceInfo> { return module.successorsInDependsOnGraph().mapNotNull { module -> val sourceRootType = module.kotlinSourceRootType ?: return@mapNotNull null module.getModuleInfo(sourceRootType) } } fun Module.successorsInDependsOnGraph(): List<Module> { return implementedModules } } private val ModuleDescriptor.moduleInfo: ModuleInfo? get() = getCapability(ModuleInfo.Capability)?.unwrapModuleSourceInfo() private val ModuleDescriptor.moduleSourceInfo: ModuleSourceInfo? get() = moduleInfo as? ModuleSourceInfo
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/project/IdeaModuleStructureOracle.kt
2403733617
package com.proff.teamcity.cachedSubversion import com.proff.teamcity.cachedSubversion.svnClient.iSvnClient import jetbrains.buildServer.messages.DefaultMessagesInfo import org.tmatesoft.svn.core.SVNException import org.tmatesoft.svn.core.SVNURL import org.tmatesoft.svn.core.wc.SVNRevision import java.io.File class cacheHelper(val build: iRunningBuild, val fileHelper: iFileHelper) : iCacheHelper { override fun doCache(vcs: vcsCheckoutSettings, client: iSvnClient): SVNURL? { val cacheRule = getCacheUrl(vcs.url) if (cacheRule != null) { val target = doCache(cacheRule, vcs.revision, client) val root = client.getRootUri(vcs.url, SVNRevision.create(vcs.revision)) return target.appendPath(vcs.url.removePrefix(root.toString()), false) } return null } private fun getCacheUrl(url: String): cacheRule? { if (build.agentConfiguration(cachedSubversionConstants.DISABLED_CONFIG_KEY) != null) return null val rules = getCacheRules() for (rule in rules) { val cur = rule.source.removePathTail().toString() if (!cur.isNullOrBlank() && (url == cur || url.startsWith(cur + "/"))) return rule } return null } private fun doCache(rule: cacheRule, revision: Long, client: iSvnClient): SVNURL { build.activity("caching ${rule.source}").use { val cacheTarget = getCacheTarget(rule) if (cacheTarget.file != null && !fileHelper.exists(cacheTarget.file)) { fileHelper.mkdirs(cacheTarget.file) build.message("creating cache repository") client.createAndInitialize(rule.source, cacheTarget.file) } else { client.initializeIfRequired(rule.source, cacheTarget.url) } build.message("synchronizing to ${cacheTarget.url}") doSync(cacheTarget, revision, client) return cacheTarget.url } } private fun doSync(cacheTarget: cacheTarget, revision: Long, client: iSvnClient) { var delay = 1 while (true) { try { if (build.interruptReason() != null) { return } val lastRevision = client.lastRevision(cacheTarget.url) if (lastRevision < revision) { client.synchronize(cacheTarget.url) if (cacheTarget.file != null) { val newLastRevision = client.lastRevision(cacheTarget.url) if (lastRevision / 1000 < newLastRevision / 1000) { build.message("packing") client.pack(cacheTarget.file) } } } return } catch(e: RepositoryLockedException) { build.message("repo is locked by ${e.holder}, retry after $delay seconds") Thread.sleep((delay * 1000).toLong()) if (delay < 60) delay++ } } } private fun getCacheTarget(cacheRule: cacheRule): cacheTarget { if (!cacheRule.name.isNullOrBlank()) { val customPath = build.agentConfiguration(cachedSubversionConstants.CACHE_PATH_CONFIG_KEY + "." + cacheRule.name) if (!customPath.isNullOrBlank()) { try { return cacheTarget(SVNURL.parseURIEncoded(customPath)) } catch(e: SVNException) { return cacheTarget(File(customPath)) } } } if (cacheRule.target != null) return cacheRule.target var root = File(build.agentSystemDirectory(), "cachedSubversion") val customPath = build.agentConfiguration(cachedSubversionConstants.CACHE_PATH_CONFIG_KEY) if (customPath != null) root = File(customPath) val cacheFile = File(root, md5(cacheRule.source.toString()).toHexString()) return cacheTarget(cacheFile) } private fun getCacheRules(): List<cacheRule> { val value = build.config(cachedSubversionConstants.REPOSITORIES_CONFIG_KEY) var result = listOf<cacheRule>() if (value != null) result = value.split("\n").map { cacheRule(it.trim()) } return result } }
cachedSubversion-agent/src/main/java/com/proff/teamcity/cachedSubversion/cacheHelper.kt
3516620243
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.integrations.maven.codeInsight.completion import com.intellij.codeInsight.completion.* import com.intellij.codeInsight.completion.CompletionUtil.DUMMY_IDENTIFIER import com.intellij.codeInsight.completion.CompletionUtil.DUMMY_IDENTIFIER_TRIMMED import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.Key import com.intellij.openapi.util.text.StringUtil import com.intellij.patterns.PatternCondition import com.intellij.patterns.PlatformPatterns.psiElement import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.ProcessingContext import org.jetbrains.concurrency.Promise import org.jetbrains.idea.maven.dom.converters.MavenDependencyCompletionUtil import org.jetbrains.idea.maven.dom.model.completion.MavenVersionNegatingWeigher import org.jetbrains.idea.maven.onlinecompletion.model.MavenRepositoryArtifactInfo import org.jetbrains.idea.reposearch.DependencySearchService import org.jetbrains.idea.reposearch.RepositoryArtifactData import org.jetbrains.idea.reposearch.SearchParameters import org.jetbrains.plugins.gradle.codeInsight.AbstractGradleCompletionContributor import org.jetbrains.plugins.groovy.lang.completion.GrDummyIdentifierProvider.DUMMY_IDENTIFIER_DECAPITALIZED import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression import org.jetbrains.plugins.groovy.lang.psi.api.util.GrNamedArgumentsOwner import java.util.concurrent.ConcurrentLinkedDeque /** * @author Vladislav.Soroka */ class MavenDependenciesGradleCompletionContributor : AbstractGradleCompletionContributor() { init { // map-style notation: // e.g.: // compile group: 'com.google.code.guice', name: 'guice', version: '1.0' // runtime([group:'junit', name:'junit-dep', version:'4.7']) // compile(group:'junit', name:'junit-dep', version:'4.7') extend(CompletionType.BASIC, IN_MAP_DEPENDENCY_NOTATION, object : CompletionProvider<CompletionParameters>() { override fun addCompletions(params: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { val parent = params.position.parent?.parent if (parent !is GrNamedArgument || parent.parent !is GrNamedArgumentsOwner) { return } result.stopHere() val searchParameters = createSearchParameters(params) val cld = ConcurrentLinkedDeque<MavenRepositoryArtifactInfo>() val dependencySearch = DependencySearchService.getInstance(parent.project) result.restartCompletionOnAnyPrefixChange() if (GROUP_LABEL == parent.labelName) { val groupId = trimDummy(findNamedArgumentValue(parent.parent as GrNamedArgumentsOwner, GROUP_LABEL)) val searchPromise = dependencySearch.fulltextSearch(groupId, searchParameters) { (it as? MavenRepositoryArtifactInfo)?.let { cld.add(it) } } waitAndAdd(searchPromise, cld) { result.addElement(MavenDependencyCompletionUtil.lookupElement(it).withInsertHandler(GradleMapStyleInsertGroupHandler.INSTANCE)) } } else if (NAME_LABEL == parent.labelName) { val groupId = trimDummy(findNamedArgumentValue(parent.parent as GrNamedArgumentsOwner, GROUP_LABEL)) val artifactId = trimDummy(findNamedArgumentValue(parent.parent as GrNamedArgumentsOwner, NAME_LABEL)) val searchPromise = searchArtifactId(groupId, artifactId, dependencySearch, searchParameters) { (it as? MavenRepositoryArtifactInfo)?.let { cld.add(it) } } waitAndAdd(searchPromise, cld) { result.addElement( MavenDependencyCompletionUtil.lookupElement(it).withInsertHandler(GradleMapStyleInsertArtifactIdHandler.INSTANCE)) } } else if (VERSION_LABEL == parent.labelName) { val groupId = trimDummy(findNamedArgumentValue(parent.parent as GrNamedArgumentsOwner, GROUP_LABEL)) val artifactId = trimDummy(findNamedArgumentValue(parent.parent as GrNamedArgumentsOwner, NAME_LABEL)) val searchPromise = searchArtifactId(groupId, artifactId, dependencySearch, searchParameters) { (it as? MavenRepositoryArtifactInfo)?.let { cld.add(it) } } val newResult = result.withRelevanceSorter(CompletionService.getCompletionService().emptySorter().weigh( MavenVersionNegatingWeigher())) waitAndAdd(searchPromise, cld) { repo -> repo.items.forEach { newResult.addElement(MavenDependencyCompletionUtil.lookupElement(it, it.version)) } } } } }) // group:name:version notation // e.g.: // compile 'junit:junit:4.11' // compile('junit:junit:4.11') extend(CompletionType.BASIC, IN_METHOD_DEPENDENCY_NOTATION, object : CompletionProvider<CompletionParameters>() { override fun addCompletions(params: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { val element = params.position.parent if (element !is GrLiteral || element.parent !is GrArgumentList) { //try val parent = element?.parent if (parent !is GrLiteral || parent.parent !is GrArgumentList) return } result.stopHere() val completionPrefix = CompletionUtil.findReferenceOrAlphanumericPrefix(params) val quote = params.position.text.firstOrNull() ?: '\'' val suffix = params.originalPosition?.text?.let { StringUtil.unquoteString(it).substring(completionPrefix.length) } val cld = ConcurrentLinkedDeque<MavenRepositoryArtifactInfo>() val splitted = completionPrefix.split(":") val groupId = splitted[0] val artifactId = splitted.getOrNull(1) val version = splitted.getOrNull(2) val dependencySearch = DependencySearchService.getInstance(element.project) val searchPromise = searchStringDependency(groupId, artifactId, dependencySearch, createSearchParameters(params)) { (it as? MavenRepositoryArtifactInfo)?.let { cld.add(it) } } result.restartCompletionOnAnyPrefixChange() val additionalData = CompletionData(suffix, quote) if (version != null) { val newResult = result.withRelevanceSorter(CompletionSorter.emptySorter().weigh(MavenVersionNegatingWeigher())) waitAndAdd(searchPromise, cld, completeVersions(newResult, additionalData)) } else { waitAndAdd(searchPromise, cld, completeGroupAndArtifact(result, additionalData)) } } }) } private fun completeVersions(result: CompletionResultSet, data: CompletionData): (MavenRepositoryArtifactInfo) -> Unit = { info -> result.addAllElements(info.items.filter { it.version != null }.map { item -> LookupElementBuilder.create(item, MavenDependencyCompletionUtil.getLookupString(item)) .withPresentableText(item.version!!) .withInsertHandler(GradleStringStyleVersionHandler) .also { it.putUserData(COMPLETION_DATA_KEY, data) } }) } private fun completeGroupAndArtifact(result: CompletionResultSet, data: CompletionData): (MavenRepositoryArtifactInfo) -> Unit = { info -> result.addElement(MavenDependencyCompletionUtil.lookupElement(info) .withInsertHandler(GradleStringStyleGroupAndArtifactHandler) .also { it.putUserData(COMPLETION_DATA_KEY, data) }) } private fun searchStringDependency(groupId: String, artifactId: String?, service: DependencySearchService, searchParameters: SearchParameters, consumer: (RepositoryArtifactData) -> Unit): Promise<Int> { if (artifactId == null) { return service.fulltextSearch(groupId, searchParameters, consumer) } else { return service.suggestPrefix(groupId, artifactId, searchParameters, consumer) } } private fun searchArtifactId(groupId: String, artifactId: String, service: DependencySearchService, searchParameters: SearchParameters, consumer: (RepositoryArtifactData) -> Unit): Promise<Int> { if (groupId.isBlank()) { return service.fulltextSearch(artifactId, searchParameters, consumer) } return service.suggestPrefix(groupId, artifactId, searchParameters, consumer) } private fun waitAndAdd(searchPromise: Promise<Int>, cld: ConcurrentLinkedDeque<MavenRepositoryArtifactInfo>, handler: (MavenRepositoryArtifactInfo) -> Unit) { while (searchPromise.state == Promise.State.PENDING || !cld.isEmpty()) { ProgressManager.checkCanceled() val item = cld.poll() if (item != null) { handler.invoke(item) } } } companion object { internal const val GROUP_LABEL = "group" internal const val NAME_LABEL = "name" internal const val VERSION_LABEL = "version" internal const val DEPENDENCIES_SCRIPT_BLOCK = "dependencies" data class CompletionData(val suffix: String?, val quote: Char) val COMPLETION_DATA_KEY = Key.create<CompletionData>("COMPLETION_DATA") private val DEPENDENCIES_CALL_PATTERN = psiElement() .inside(true, psiElement(GrMethodCallExpression::class.java).with( object : PatternCondition<GrMethodCallExpression>("withInvokedExpressionText") { override fun accepts(expression: GrMethodCallExpression, context: ProcessingContext): Boolean { if (checkExpression(expression)) return true return checkExpression(PsiTreeUtil.getParentOfType(expression, GrMethodCallExpression::class.java)) } private fun checkExpression(expression: GrMethodCallExpression?): Boolean { if (expression == null) return false val grExpression = expression.invokedExpression return DEPENDENCIES_SCRIPT_BLOCK == grExpression.text } })) private val IN_MAP_DEPENDENCY_NOTATION = psiElement() .and(GRADLE_FILE_PATTERN) .withParent(GrLiteral::class.java) .withSuperParent(2, psiElement(GrNamedArgument::class.java)) .and(DEPENDENCIES_CALL_PATTERN) private val IN_METHOD_DEPENDENCY_NOTATION = psiElement() .and(GRADLE_FILE_PATTERN) .and(DEPENDENCIES_CALL_PATTERN) private fun createSearchParameters(params: CompletionParameters): SearchParameters { return SearchParameters(params.invocationCount < 2, ApplicationManager.getApplication().isUnitTestMode) } private fun trimDummy(value: String?): String { return if (value == null) { "" } else StringUtil.trim(value.replace(DUMMY_IDENTIFIER, "") .replace(DUMMY_IDENTIFIER_TRIMMED, "") .replace(DUMMY_IDENTIFIER_DECAPITALIZED, "")) } } }
plugins/gradle-maven/src/org/jetbrains/plugins/gradle/integrations/maven/codeInsight/completion/MavenDependenciesGradleCompletionContributor.kt
2029176582
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.script.configuration import com.intellij.ide.BrowserUtil import com.intellij.ide.scratch.ScratchUtil import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotificationProvider import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings import org.jetbrains.kotlin.idea.util.KOTLIN_AWARE_SOURCE_ROOT_TYPES import org.jetbrains.kotlin.scripting.definitions.isNonScript import java.util.function.Function import javax.swing.JComponent class ScriptingSupportChecker: EditorNotificationProvider { override fun collectNotificationData(project: Project, file: VirtualFile): Function<in FileEditor, out JComponent?> { if (!Registry.`is`("kotlin.scripting.support.warning") || file.isNonScript() || ScratchUtil.isScratch(file)) { return EditorNotificationProvider.CONST_NULL } // warning panel is hidden if (!KotlinScriptingSettings.getInstance(project).showSupportWarning) { return EditorNotificationProvider.CONST_NULL } val providers = ScriptingSupportCheckerProvider.CHECKER_PROVIDERS.getExtensionList(project) // if script file is under source root val projectFileIndex = ProjectRootManager.getInstance(project).fileIndex if (projectFileIndex.isUnderSourceRootOfType( file, KOTLIN_AWARE_SOURCE_ROOT_TYPES ) && providers.none { it.isSupportedUnderSourceRoot(file) } ) { return Function { EditorNotificationPanel(it).apply { text = KotlinBundle.message("kotlin.script.in.project.sources") createActionLabel( KotlinBundle.message("kotlin.script.warning.more.info"), Runnable { BrowserUtil.browse(KotlinBundle.message("kotlin.script.in.project.sources.link")) }, false ) addHideAction(file, project) } } } if (providers.none { it.isSupportedScriptExtension(file) }) { return Function { EditorNotificationPanel(it).apply { text = KotlinBundle.message("kotlin.script.in.beta.stage") createActionLabel( KotlinBundle.message("kotlin.script.warning.more.info"), Runnable { BrowserUtil.browse(KotlinBundle.message("kotlin.script.in.beta.stage.link")) }, false ) addHideAction(file, project) } } } return EditorNotificationProvider.CONST_NULL } } private fun EditorNotificationPanel.addHideAction( file: VirtualFile, project: Project ) { createActionLabel( KotlinBundle.message("kotlin.script.in.project.sources.hide"), Runnable { KotlinScriptingSettings.getInstance(project).showSupportWarning = false val fileEditorManager = FileEditorManager.getInstance(project) fileEditorManager.getSelectedEditor(file)?.let { editor -> fileEditorManager.removeTopComponent(editor, this) } }, false ) } private fun VirtualFile.supportedScriptExtensions() = name.endsWith(".main.kts") || name.endsWith(".space.kts") || name.endsWith(".gradle.kts")
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/script/configuration/ScriptingSupportChecker.kt
4037466492
package com.radikal.pcnotifications.model.persistence.impl import android.content.ContentResolver import android.net.Uri import android.telephony.TelephonyManager import android.util.Log import com.radikal.pcnotifications.model.domain.Sms import com.radikal.pcnotifications.model.persistence.SmsDao import com.radikal.pcnotifications.utils.RECEIVED import com.radikal.pcnotifications.utils.SENT import java.util.* import javax.inject.Inject import com.github.tamir7.contacts.Contact import com.github.tamir7.contacts.Contacts /** * Created by tudor on 25.04.2017. */ class SqliteSmsDao @Inject constructor() : SmsDao { val TAG: String = javaClass.simpleName val smsInboxUri: Uri = Uri.parse("content://sms/inbox") val smsSentUri: Uri = Uri.parse("content://sms/sent") @Inject lateinit var contentResolver: ContentResolver @Inject lateinit var telephonyManager: TelephonyManager override fun getAllReceived(): List<Sms> { return getSms(smsInboxUri) } override fun getAllSent(): List<Sms> { return getSms(smsSentUri) } private fun getSms(uri: Uri): MutableList<Sms> { var smsType: Int if (uri == smsInboxUri) { smsType = RECEIVED } else if (uri == smsSentUri) { smsType = SENT } else { throw IllegalArgumentException("Provided URI is invalid") } var smsList: MutableList<Sms> = ArrayList() val cursor = contentResolver.query(uri, null, null, null, null) val allContacts = Contacts.getQuery().find() while (cursor.moveToNext()) { var sender = cursor.getString(cursor.getColumnIndex("address")).replace(" ", "") val contactsByPhoneNumber = Contacts.getQuery() contactsByPhoneNumber.whereEqualTo(Contact.Field.PhoneNumber, sender) val contacts = contactsByPhoneNumber.find() var displayName = sender if (contacts.size == 0) { Log.e(TAG, "Contact not found for number: " + sender) allContacts.forEach { val contact = it it.phoneNumbers.forEach { if (it.normalizedNumber?.replace(" ", "") == sender || it.number?.replace(" ", "") == sender) { Log.v(TAG, "Found contact for number $sender and display name: ${contact.displayName}") displayName = contact.displayName } } } } else { displayName = contacts[0].displayName } var message = cursor.getString(cursor.getColumnIndex("body")) var date = cursor.getString(cursor.getColumnIndex("date")) smsList.add(Sms(com.radikal.pcnotifications.model.domain.Contact(displayName, sender), message, Date(date.toLong()), smsType)) } cursor.close() return smsList } }
mobile/app/src/main/kotlin/com/radikal/pcnotifications/model/persistence/impl/SqliteSmsDao.kt
2098897366
/* * Copyright (C) 2020 Tobias Preuss * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.avpptr.umweltzone.zones sealed class ChildZonesCount(val value: Int) { object ONE : ChildZonesCount(1) object TWO : ChildZonesCount(2) object THREE : ChildZonesCount(3) }
Umweltzone/src/main/java/de/avpptr/umweltzone/zones/ChildZonesCount.kt
2537666304
package org.snakeskin.hid.impl import edu.wpi.first.wpilibj.Joystick import org.snakeskin.hid.provider.IHatValueProvider class WPIJoystickHatValueProvider(val joystick: Joystick, val id: Int): IHatValueProvider { override fun read(): Int { return joystick.getPOV(id) } }
SnakeSkin-FRC/src/main/kotlin/org/snakeskin/hid/impl/WPIJoystickHatValueProvider.kt
1476794695
package com.daveme.chocolateCakePHP import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiFile import com.jetbrains.php.lang.psi.elements.PhpClass sealed class Cake(val viewDirectory: String, val elementTop: String) { abstract fun templatePath(settings: Settings, controllerName: String, controllerAction: String): String abstract fun elementPath(settings: Settings, elementPath: String): String abstract fun isCakeViewFile(settings: Settings, topDir: PsiDirectory?, file: PsiFile): Boolean } fun topSourceDirectoryFromFile(settings: Settings, file: PsiFile): PsiDirectory? { val originalFile = file.originalFile return pluginDirectoryFromFile(settings, originalFile) ?: appDirectoryFromFile(settings, originalFile) ?: templateDirectoryFromFile(settings, originalFile) } private fun templateDirectoryFromFile(settings: Settings, originalFile: PsiFile): PsiDirectory? { if (!settings.cake3Enabled) { return null } var dir: PsiDirectory? = originalFile.containingDirectory while (dir != null) { if (dir.name == "templates") { return dir } dir = dir.parent } return null } fun isCakeViewFile(settings: Settings, file: PsiFile): Boolean { if (!settings.enabled) { return false } val hasCakeFour = if (settings.cake3Enabled) file.name.endsWith("php") else false val hasCakeThree = if (settings.cake3Enabled) file.name.endsWith(settings.cakeTemplateExtension) else false val hasCakeTwo = if (settings.cake2Enabled) file.name.endsWith(settings.cake2TemplateExtension) else false val topDir = topSourceDirectoryFromFile(settings, file) if (hasCakeFour && CakeFour.isCakeViewFile(settings, topDir, file)) { return true } if (hasCakeThree && CakeThree.isCakeViewFile(settings, topDir, file)) { return true } if (hasCakeTwo && CakeTwo.isCakeViewFile(settings, topDir, file)) { return true } return false } private fun pluginDirectoryFromFile(settings: Settings, file: PsiFile): PsiDirectory? { if (!settings.cake3Enabled) { return null } var first: PsiDirectory? = file.containingDirectory var second = first?.parent var third = second?.parent while (third != null && third.name != settings.pluginPath) { first = second second = third third = third.parent } if (third?.name == settings.pluginPath) { return first } return null } private fun appDirectoryFromFile(settings: Settings, file: PsiFile): PsiDirectory? { var dir: PsiDirectory? = file.containingDirectory while (dir != null) { if (settings.cake3Enabled) { if (dir.name == settings.appDirectory) { return dir } } if (settings.cake2Enabled) { if (dir.name == settings.cake2AppDirectory) { return dir } } dir = dir.parent } return null } object CakeFour : Cake(viewDirectory = "templates", elementTop = "element") { override fun templatePath(settings: Settings, controllerName: String, controllerAction: String) = "../$viewDirectory/$controllerName/$controllerAction.php" override fun elementPath(settings: Settings, elementPath: String): String = "../$viewDirectory/$elementTop/$elementPath.php" override fun isCakeViewFile(settings: Settings, topDir: PsiDirectory?, file: PsiFile): Boolean { return topDir?.name == viewDirectory } } object CakeThree : Cake(viewDirectory = "Template", elementTop = "Element") { override fun templatePath(settings: Settings, controllerName: String, controllerAction: String) = "$viewDirectory/$controllerName/$controllerAction.${settings.cakeTemplateExtension}" override fun elementPath(settings: Settings, elementPath: String): String = "$viewDirectory/$elementTop/$elementPath.${settings.cakeTemplateExtension}" override fun isCakeViewFile(settings: Settings, topDir: PsiDirectory?, file: PsiFile): Boolean { var dir = file.originalFile.containingDirectory while (dir != null && dir != topDir) { if (settings.cake3Enabled) { if (dir.name == viewDirectory && dir.parent == topDir) { return true } } dir = dir.parentDirectory } return false } } object CakeTwo : Cake(viewDirectory = "View", elementTop = "Elements") { override fun templatePath(settings: Settings, controllerName: String, controllerAction: String) = "${viewDirectory}/$controllerName/$controllerAction.${settings.cake2TemplateExtension}" override fun elementPath(settings: Settings, elementPath: String): String = "${viewDirectory}/${elementTop}/$elementPath.${settings.cake2TemplateExtension}" override fun isCakeViewFile(settings: Settings, topDir: PsiDirectory?, file: PsiFile): Boolean { var dir = file.originalFile.containingDirectory while (dir != null && dir != topDir) { if (dir.name == viewDirectory && dir.parent == topDir) { return true } dir = dir.parentDirectory } return false } fun isModelClass(classes: Collection<PhpClass>): Boolean { return classes.any { phpClass -> phpClass.superFQN == "\\AppModel" } } }
src/main/kotlin/com/daveme/chocolateCakePHP/Cake.kt
3005259990
package io.ipoli.android.pet.usecase import io.ipoli.android.Constants import io.ipoli.android.TestUtil import io.ipoli.android.pet.Pet import io.ipoli.android.pet.PetAvatar import io.ipoli.android.player.data.Player import org.amshove.kluent.`should be equal to` import org.amshove.kluent.`should be instance of` import org.amshove.kluent.`should be` import org.amshove.kluent.shouldThrow import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it /** * Created by Venelin Valkov <[email protected]> * on 12/5/17. */ class RevivePetUseCaseSpek : Spek({ describe("RevivePetUseCase") { fun executeUseCase(player: Player) = RevivePetUseCase(TestUtil.playerRepoMock(player)).execute(Unit) it("should require dead pet") { val player = TestUtil.player.copy( pet = Pet( "", avatar = PetAvatar.ELEPHANT, healthPoints = 10, moodPoints = 10 ) ) val exec = { executeUseCase(player) } exec shouldThrow IllegalArgumentException::class } it("should not revive when not enough gems") { val pet = TestUtil.player.pet val player = TestUtil.player.copy( gems = Constants.REVIVE_PET_GEM_PRICE - 1, pet = pet.copy( healthPoints = 0, moodPoints = 0 ) ) val result = executeUseCase(player) result.`should be`(RevivePetUseCase.Result.TooExpensive) } it("should revive pet") { val pet = TestUtil.player.pet val player = TestUtil.player.copy( gems = Constants.REVIVE_PET_GEM_PRICE, pet = pet.copy( healthPoints = 0, moodPoints = 0 ) ) val result = executeUseCase(player) result.`should be instance of`(RevivePetUseCase.Result.PetRevived::class) val newPlayer = (result as RevivePetUseCase.Result.PetRevived).player newPlayer.gems.`should be equal to`(0) val newPet = newPlayer.pet newPet.healthPoints.`should be equal to`(Constants.DEFAULT_PET_HP) newPet.moodPoints.`should be equal to`(Constants.DEFAULT_PET_MP) } } })
app/src/test/java/io/ipoli/android/pet/usecase/RevivePetUseCaseSpek.kt
1303263235
package io.ipoli.android.quest.schedule.addquest import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.content.res.ColorStateList import android.support.design.widget.FloatingActionButton import android.view.View import android.view.ViewGroup import android.view.animation.AccelerateDecelerateInterpolator import com.bluelinelabs.conductor.RestoreViewOnCreateController import io.ipoli.android.R import io.ipoli.android.common.ViewUtils import io.ipoli.android.common.navigation.Navigator import io.ipoli.android.common.view.* import io.ipoli.android.common.view.changehandler.CircularRevealChangeHandler import org.threeten.bp.LocalDate /** * Created by Polina Zhelyazkova <[email protected]> * on 4/25/18. */ class AddQuestAnimationHelper( private val controller: RestoreViewOnCreateController, private val addContainer: ViewGroup, private val fab: FloatingActionButton, private val background: View ) { fun openAddContainer(currentDate: LocalDate? = LocalDate.now()) { fab.isClickable = false val halfWidth = addContainer.width / 2 val fabSet = createFabAnimator(fab, halfWidth.toFloat() - fab.width / 2) fabSet.start() fabSet.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { addContainer.visible() fab.invisible() animateShowAddContainer(background) val handler = CircularRevealChangeHandler( addContainer, addContainer, duration = controller.shortAnimTime ) val childRouter = controller.getChildRouter(addContainer, "add-quest") Navigator(childRouter) .setAddQuest( closeListener = { childRouter.popCurrentController() closeAddContainer() }, currentDate = currentDate, changeHandler = handler ) } }) } fun closeAddContainer(endListener: (() -> Unit)? = null) { background.gone() val duration = background.resources.getInteger(android.R.integer.config_shortAnimTime).toLong() val revealAnim = RevealAnimator().createWithEndRadius( view = addContainer, endRadius = (fab.width / 2).toFloat(), reverse = true ) revealAnim.duration = duration revealAnim.startDelay = 300 revealAnim.interpolator = AccelerateDecelerateInterpolator() revealAnim.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { if (controller.view == null) { return } addContainer.invisible() addContainer.requestFocus() fab.visible() val fabSet = createFabAnimator( fab, (addContainer.width - fab.width - ViewUtils.dpToPx(16f, fab.context)), reverse = true ) fabSet.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { fab.isClickable = true endListener?.invoke() } }) fabSet.start() } }) revealAnim.start() } private fun createFabAnimator( fab: FloatingActionButton, x: Float, reverse: Boolean = false ): AnimatorSet { val duration = fab.resources.getInteger(android.R.integer.config_shortAnimTime) .toLong() val fabTranslation = ObjectAnimator.ofFloat(fab, "x", x) val fabColor = controller.attrData(R.attr.colorAccent) val transitionColor = controller.colorRes(controller.colorSurfaceResource) val startColor = if (reverse) transitionColor else fabColor val endColor = if (reverse) fabColor else transitionColor val rgbAnim = ObjectAnimator.ofArgb( fab, "backgroundTint", startColor, endColor ) rgbAnim.addUpdateListener { animation -> val value = animation.animatedValue as Int fab.backgroundTintList = ColorStateList.valueOf(value) } return AnimatorSet().also { it.playTogether(fabTranslation, rgbAnim) it.interpolator = AccelerateDecelerateInterpolator() it.duration = duration } } private fun animateShowAddContainer(background: View) { background.alpha = 0f background.visible() background.animate().alpha(1f).setDuration(controller.longAnimTime).start() } }
app/src/main/java/io/ipoli/android/quest/schedule/addquest/AddQuestAnimationHelper.kt
3172962016
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.actions import com.intellij.ide.fileTemplates.DefaultTemplatePropertiesProvider import com.intellij.ide.fileTemplates.FileTemplate import com.intellij.psi.PsiDirectory import org.jetbrains.kotlin.idea.core.getFqNameWithImplicitPrefixOrRoot import java.util.* class KotlinDefaultTemplatePropertiesProvider : DefaultTemplatePropertiesProvider { override fun fillProperties(directory: PsiDirectory, props: Properties) { props.setProperty( FileTemplate.ATTRIBUTE_PACKAGE_NAME, directory.getFqNameWithImplicitPrefixOrRoot().asString() ) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/KotlinDefaultTemplatePropertiesProvider.kt
967377180
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.deft.api.annotations.Default import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class FinalFieldsEntityImpl(val dataSource: FinalFieldsEntityData) : FinalFieldsEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override val descriptor: AnotherDataClass get() = dataSource.descriptor override var description: String = dataSource.description override var anotherVersion: Int = dataSource.anotherVersion override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: FinalFieldsEntityData?) : ModifiableWorkspaceEntityBase<FinalFieldsEntity, FinalFieldsEntityData>( result), FinalFieldsEntity.Builder { constructor() : this(FinalFieldsEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity FinalFieldsEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isDescriptorInitialized()) { error("Field FinalFieldsEntity#descriptor should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as FinalFieldsEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.descriptor != dataSource.descriptor) this.descriptor = dataSource.descriptor if (this.description != dataSource.description) this.description = dataSource.description if (this.anotherVersion != dataSource.anotherVersion) this.anotherVersion = dataSource.anotherVersion if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var descriptor: AnotherDataClass get() = getEntityData().descriptor set(value) { checkModificationAllowed() getEntityData(true).descriptor = value changedProperty.add("descriptor") } override var description: String get() = getEntityData().description set(value) { checkModificationAllowed() getEntityData(true).description = value changedProperty.add("description") } override var anotherVersion: Int get() = getEntityData().anotherVersion set(value) { checkModificationAllowed() getEntityData(true).anotherVersion = value changedProperty.add("anotherVersion") } override fun getEntityClass(): Class<FinalFieldsEntity> = FinalFieldsEntity::class.java } } class FinalFieldsEntityData : WorkspaceEntityData<FinalFieldsEntity>() { lateinit var descriptor: AnotherDataClass var description: String = "Default description" var anotherVersion: Int = 0 fun isDescriptorInitialized(): Boolean = ::descriptor.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<FinalFieldsEntity> { val modifiable = FinalFieldsEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): FinalFieldsEntity { return getCached(snapshot) { val entity = FinalFieldsEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return FinalFieldsEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return FinalFieldsEntity(descriptor, entitySource) { this.description = [email protected] this.anotherVersion = [email protected] } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as FinalFieldsEntityData if (this.entitySource != other.entitySource) return false if (this.descriptor != other.descriptor) return false if (this.description != other.description) return false if (this.anotherVersion != other.anotherVersion) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as FinalFieldsEntityData if (this.descriptor != other.descriptor) return false if (this.description != other.description) return false if (this.anotherVersion != other.anotherVersion) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + descriptor.hashCode() result = 31 * result + description.hashCode() result = 31 * result + anotherVersion.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + descriptor.hashCode() result = 31 * result + description.hashCode() result = 31 * result + anotherVersion.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.add(AnotherDataClass::class.java) collector.sameForAllEntities = true } }
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/FinalFieldsEntityImpl.kt
3518841554
fun <caret>foo(n: Int): Int = 1 class A(val n: Int) { fun bar(n: Int): Int { return foo(n) + this.n } }
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/PropagateWithThisQualificationInClassMemberAfter.kt
3462050372
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.nj2k.inference.common import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.* import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.collectors.CallExpressionConstraintCollector import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.collectors.CommonConstraintsCollector import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.collectors.FunctionConstraintsCollector import org.jetbrains.kotlin.idea.j2k.post.processing.inference.nullability.NullabilityConstraintBoundProvider import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.nj2k.inference.AbstractConstraintCollectorTest import org.jetbrains.kotlin.psi.KtTypeElement abstract class AbstractCommonConstraintCollectorTest : AbstractConstraintCollectorTest() { override fun createInferenceFacade(resolutionFacade: ResolutionFacade): InferenceFacade = InferenceFacade( object : ContextCollector(resolutionFacade) { override fun ClassReference.getState(typeElement: KtTypeElement?): State = State.UNKNOWN }, ConstraintsCollectorAggregator( resolutionFacade, NullabilityConstraintBoundProvider(), listOf( CommonConstraintsCollector(), CallExpressionConstraintCollector(), FunctionConstraintsCollector(ResolveSuperFunctionsProvider(resolutionFacade)) ) ), BoundTypeCalculatorImpl(resolutionFacade, BoundTypeEnhancer.ID), object : StateUpdater() { override fun TypeElementBasedTypeVariable.updateState() = Unit }, object : DefaultStateProvider() { override fun defaultStateFor(typeVariable: TypeVariable): State = State.LOWER }, renderDebugTypes = true ) }
plugins/kotlin/j2k/new/tests/test/org/jetbrains/kotlin/nj2k/inference/common/AbstractCommonConstraintCollectorTest.kt
2238597437
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.service.task import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VfsUtil import com.intellij.testFramework.ExtensionTestUtil import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.UsefulTestCase import com.intellij.testFramework.common.runAll import com.intellij.testFramework.fixtures.IdeaProjectTestFixture import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory import org.gradle.tooling.LongRunningOperation import org.gradle.util.GradleVersion import org.jetbrains.plugins.gradle.importing.GradleImportingTestCase import org.jetbrains.plugins.gradle.importing.TestGradleBuildScriptBuilder import org.jetbrains.plugins.gradle.service.project.GradleOperationHelperExtension import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext import org.jetbrains.plugins.gradle.settings.DistributionType import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings import org.jetbrains.plugins.gradle.testFramework.util.createBuildFile import org.jetbrains.plugins.gradle.tooling.builder.AbstractModelBuilderTest import org.jetbrains.plugins.gradle.util.GradleConstants import org.junit.Test import java.util.concurrent.atomic.AtomicReference class GradleTaskManagerTest: UsefulTestCase() { private lateinit var myTestFixture: IdeaProjectTestFixture private lateinit var myProject: Project private lateinit var tm: GradleTaskManager private lateinit var taskId: ExternalSystemTaskId private lateinit var gradleExecSettings: GradleExecutionSettings override fun setUp() { super.setUp() myTestFixture = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(name).fixture myTestFixture.setUp() myProject = myTestFixture.project tm = GradleTaskManager() taskId = ExternalSystemTaskId.create(GradleConstants.SYSTEM_ID, ExternalSystemTaskType.EXECUTE_TASK, myProject) gradleExecSettings = GradleExecutionSettings(null, null, DistributionType.WRAPPED, false) } override fun tearDown() { runAll( { myTestFixture.tearDown() }, { super.tearDown() } ) } @Test fun `test task manager uses wrapper task when configured`() { val output = runHelpTask(GradleVersion.version("4.8.1")) assertTrue("Gradle 4.8.1 should be started", output.anyLineContains("Welcome to Gradle 4.8.1")) } @Test fun `test task manager calls Operation Helper Extension`() { val executed: AtomicReference<Boolean> = AtomicReference(false) val ext = TestOperationHelperExtension(prepareExec = { executed.set(true) }) ExtensionTestUtil.maskExtensions(GradleOperationHelperExtension.EP_NAME, listOf(ext), testRootDisposable, false) runHelpTask(GradleVersion.version("4.8.1")) assertTrue(executed.get()) } @Test fun `test gradle-version-specific init scripts executed`() { val oldMessage = "this should be executed for gradle 3.0" val oldVer = VersionSpecificInitScript("""println('$oldMessage')""") { v -> v == GradleVersion.version("3.0") } val intervalMessage = "this should be executed for gradle between 4 and 6" val intervalVer = VersionSpecificInitScript("println('$intervalMessage')") { v -> v > GradleVersion.version("4.0") && v <= GradleVersion.version("6.0") } val newerVerMessage = "this should be executed for gradle 4.8 and newer" val newerVer = VersionSpecificInitScript("println('$newerVerMessage')") { v -> v >= GradleVersion.version("4.8") } val initScripts = listOf(oldVer, intervalVer, newerVer) gradleExecSettings.putUserData(GradleTaskManager.VERSION_SPECIFIC_SCRIPTS_KEY, initScripts) val output = runHelpTask(GradleVersion.version("4.9")) assertFalse(output.anyLineContains(oldMessage)) assertTrue(output.anyLineContains(intervalMessage)) assertTrue(output.anyLineContains(newerVerMessage)) } @Test fun `test task manager uses wrapper task when wrapper already exists`() { runWriteAction { val baseDir = PlatformTestUtil.getOrCreateProjectBaseDir(myProject) val wrapperProps = baseDir .createChildDirectory(this, "gradle") .createChildDirectory(this, "wrapper") .createChildData(this, "gradle-wrapper.properties") VfsUtil.saveText(wrapperProps, """ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=${AbstractModelBuilderTest.DistributionLocator().getDistributionFor(GradleVersion.version("4.8"))} zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists """.trimIndent()) } val output = runHelpTask(GradleVersion.version("4.9")) assertTrue("Gradle 4.9 should execute 'help' task", output.anyLineContains("Welcome to Gradle 4.9")) assertFalse("Gradle 4.8 should not execute 'help' task", output.anyLineContains("Welcome to Gradle 4.8")) } private fun runHelpTask(gradleVersion: GradleVersion): TaskExecutionOutput { createBuildFile(gradleVersion) { withPrefix { call("wrapper") { assign("gradleVersion", gradleVersion.version) } } } gradleExecSettings.javaHome = GradleImportingTestCase.requireJdkHome(gradleVersion) val listener = TaskExecutionOutput() tm.executeTasks( taskId, listOf("help"), myProject.basePath!!, gradleExecSettings, null, listener ) return listener } private fun createBuildFile(gradleVersion: GradleVersion, configure: TestGradleBuildScriptBuilder.() -> Unit) { val projectRoot = runWriteAction { PlatformTestUtil.getOrCreateProjectBaseDir(myProject) } projectRoot.createBuildFile(gradleVersion, configure = configure) } } class TaskExecutionOutput: ExternalSystemTaskNotificationListenerAdapter() { private val storage = mutableListOf<String>() override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) { storage.add(text) } fun anyLineContains(something: String): Boolean = storage.any { it.contains(something) } } class TestOperationHelperExtension(val prepareSync: () -> Unit = {}, val prepareExec: () -> Unit = {}): GradleOperationHelperExtension { override fun prepareForSync(operation: LongRunningOperation, resolverCtx: ProjectResolverContext) { prepareSync() } override fun prepareForExecution(id: ExternalSystemTaskId, operation: LongRunningOperation, gradleExecutionSettings: GradleExecutionSettings) { prepareExec() } }
plugins/gradle/testSources/org/jetbrains/plugins/gradle/service/task/GradleTaskManagerTest.kt
3845540338
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.findUsages import com.intellij.codeInsight.highlighting.HighlightUsagesDescriptionLocation import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.ElementDescriptionLocation import com.intellij.psi.ElementDescriptionProvider import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.refactoring.util.CommonRefactoringUtil import com.intellij.refactoring.util.RefactoringDescriptionLocation import com.intellij.usageView.UsageViewLongNameLocation import com.intellij.usageView.UsageViewShortNameLocation import com.intellij.usageView.UsageViewTypeLocation import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.base.util.collapseSpaces import org.jetbrains.kotlin.name.FqNameUnsafe import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType open class KotlinElementDescriptionProviderBase : ElementDescriptionProvider { private tailrec fun KtNamedDeclaration.parentForFqName(): KtNamedDeclaration? { val parent = getStrictParentOfType<KtNamedDeclaration>() ?: return null if (parent is KtProperty && parent.isLocal) return parent.parentForFqName() return parent } private fun KtNamedDeclaration.name() = nameAsName ?: Name.special("<no name provided>") private fun KtNamedDeclaration.fqName(): FqNameUnsafe { containingClassOrObject?.let { if (it is KtObjectDeclaration && it.isCompanion()) { return it.fqName().child(name()) } return FqNameUnsafe("${it.name()}.${name()}") } val internalSegments = generateSequence(this) { it.parentForFqName() } .filterIsInstance<KtNamedDeclaration>() .map { it.name ?: "<no name provided>" } .toList() .asReversed() val packageSegments = containingKtFile.packageFqName.pathSegments() return FqNameUnsafe((packageSegments + internalSegments).joinToString(".")) } private fun KtTypeReference.renderShort(): String { return accept( object : KtVisitor<String, Unit>() { private val visitor get() = this override fun visitTypeReference(typeReference: KtTypeReference, data: Unit): String { val typeText = typeReference.typeElement?.accept(this, data) ?: "???" return if (typeReference.hasParentheses()) "($typeText)" else typeText } override fun visitIntersectionType(definitelyNotNullType: KtIntersectionType, data: Unit): String { return buildString { append(definitelyNotNullType.getLeftTypeRef()?.typeElement?.accept(visitor, data) ?: "???") append(" & ") append(definitelyNotNullType.getRightTypeRef()?.typeElement?.accept(visitor, data) ?: "???") } } override fun visitDynamicType(type: KtDynamicType, data: Unit) = type.text override fun visitFunctionType(type: KtFunctionType, data: Unit): String { return buildString { type.receiverTypeReference?.let { append(it.accept(visitor, data)).append('.') } type.parameters.joinTo(this, prefix = "(", postfix = ")") { it.accept(visitor, data) } append(" -> ") append(type.returnTypeReference?.accept(visitor, data) ?: "???") } } override fun visitNullableType(nullableType: KtNullableType, data: Unit): String { val innerTypeText = nullableType.innerType?.accept(this, data) ?: return "???" return "$innerTypeText?" } override fun visitSelfType(type: KtSelfType, data: Unit) = type.text override fun visitUserType(type: KtUserType, data: Unit): String { return buildString { append(type.referencedName ?: "???") val arguments = type.typeArguments if (arguments.isNotEmpty()) { arguments.joinTo(this, prefix = "<", postfix = ">") { it.typeReference?.accept(visitor, data) ?: it.text } } } } override fun visitParameter(parameter: KtParameter, data: Unit) = parameter.typeReference?.accept(this, data) ?: "???" }, Unit ) } //TODO: Implement in FIR protected open val PsiElement.isRenameJavaSyntheticPropertyHandler get() = false protected open val PsiElement.isRenameKotlinPropertyProcessor get() = false override fun getElementDescription(element: PsiElement, location: ElementDescriptionLocation): String? { val shouldUnwrap = location !is UsageViewShortNameLocation && location !is UsageViewLongNameLocation val targetElement = if (shouldUnwrap) element.unwrapped ?: element else element fun elementKind() = when (targetElement) { is KtClass -> if (targetElement.isInterface()) KotlinBundle.message("find.usages.interface") else KotlinBundle.message("find.usages.class") is KtObjectDeclaration -> if (targetElement.isCompanion()) KotlinBundle.message("find.usages.companion.object") else KotlinBundle.message("find.usages.object") is KtNamedFunction -> KotlinBundle.message("find.usages.function") is KtPropertyAccessor -> KotlinBundle.message( "find.usages.for.property", (if (targetElement.isGetter) KotlinBundle.message("find.usages.getter") else KotlinBundle.message("find.usages.setter")) ) + " " is KtFunctionLiteral -> KotlinBundle.message("find.usages.lambda") is KtPrimaryConstructor, is KtSecondaryConstructor -> KotlinBundle.message("find.usages.constructor") is KtProperty -> if (targetElement.isLocal) KotlinBundle.message("find.usages.variable") else KotlinBundle.message("find.usages.property") is KtTypeParameter -> KotlinBundle.message("find.usages.type.parameter") is KtParameter -> KotlinBundle.message("find.usages.parameter") is KtDestructuringDeclarationEntry -> KotlinBundle.message("find.usages.variable") is KtTypeAlias -> KotlinBundle.message("find.usages.type.alias") is KtLabeledExpression -> KotlinBundle.message("find.usages.label") is KtImportAlias -> KotlinBundle.message("find.usages.import.alias") is KtLightClassForFacade -> KotlinBundle.message("find.usages.facade.class") else -> { //TODO Implement in FIR when { targetElement.isRenameJavaSyntheticPropertyHandler -> KotlinBundle.message("find.usages.property") targetElement.isRenameKotlinPropertyProcessor -> KotlinBundle.message("find.usages.property.accessor") else -> null } } } val namedElement = if (targetElement is KtPropertyAccessor) { targetElement.parent as? KtProperty } else targetElement as? PsiNamedElement if (namedElement == null) { return if (targetElement is KtElement) "'" + StringUtil.shortenTextWithEllipsis( targetElement.text.collapseSpaces(), 53, 0 ) + "'" else null } if (namedElement.language != KotlinLanguage.INSTANCE) return null return when (location) { is UsageViewTypeLocation -> elementKind() is UsageViewShortNameLocation, is UsageViewLongNameLocation -> namedElement.name is RefactoringDescriptionLocation -> { val kind = elementKind() ?: return null if (namedElement !is KtNamedDeclaration) return null val renderFqName = location.includeParent() && namedElement !is KtTypeParameter && namedElement !is KtParameter && namedElement !is KtConstructor<*> @Suppress("HardCodedStringLiteral") val desc = when (namedElement) { is KtFunction -> { val baseText = buildString { append(namedElement.name ?: "") namedElement.valueParameters.joinTo(this, prefix = "(", postfix = ")") { (if (it.isVarArg) "vararg " else "") + (it.typeReference?.renderShort() ?: "") } namedElement.receiverTypeReference?.let { append(" on ").append(it.renderShort()) } } val parentFqName = if (renderFqName) namedElement.fqName().parent() else null if (parentFqName?.isRoot != false) baseText else "${parentFqName.asString()}.$baseText" } else -> (if (renderFqName) namedElement.fqName().asString() else namedElement.name) ?: "" } "$kind ${CommonRefactoringUtil.htmlEmphasize(desc)}" } is HighlightUsagesDescriptionLocation -> { val kind = elementKind() ?: return null if (namedElement !is KtNamedDeclaration) return null "$kind ${namedElement.name}" } else -> null } } }
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/KotlinElementDescriptionProvider.kt
2258820884
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl.welcomeScreen.projectActions import com.intellij.ide.lightEdit.LightEditCompatible import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataKey import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.wm.impl.welcomeScreen.recentProjects.RecentProjectTreeItem import com.intellij.ui.treeStructure.Tree /** * @author Konstantin Bulenkov */ abstract class RecentProjectsWelcomeScreenActionBase : DumbAwareAction(), LightEditCompatible { override fun getActionUpdateThread() = ActionUpdateThread.EDT companion object { internal val RECENT_PROJECT_SELECTED_ITEM_KEY = DataKey.create<RecentProjectTreeItem>("RECENT_PROJECT_SELECTED_ITEM") internal val RECENT_PROJECT_TREE_KEY = DataKey.create<Tree>("RECENT_PROJECT_TREE") internal fun getSelectedItem(event: AnActionEvent): RecentProjectTreeItem? { return event.getData(RECENT_PROJECT_SELECTED_ITEM_KEY) } @JvmStatic fun getTree(event: AnActionEvent): Tree? { return event.getData(RECENT_PROJECT_TREE_KEY) } } }
platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/projectActions/RecentProjectsWelcomeScreenActionBase.kt
3867876907
package com.onyx.extension import com.onyx.buffer.BufferPool import com.onyx.buffer.BufferStream import java.nio.ByteBuffer inline fun <T> withBuffer(buffer: ByteBuffer, body: (buffer:ByteBuffer) -> T) = try { body.invoke(buffer) } finally { BufferPool.recycle(buffer) } inline fun <T> BufferStream?.perform(body: (stream: BufferStream?) -> T): T = try { body.invoke(this) } finally { this?.recycle() }
onyx-database/src/main/kotlin/com/onyx/extension/BufferStream$Recycle.kt
4261228621
package io.github.knes1.kotao.brew.util import java.io.StringWriter import java.io.Writer import java.time.Instant import java.time.LocalDate import java.time.ZoneOffset import java.time.format.DateTimeFormatter import javax.xml.stream.XMLOutputFactory /** * Utility Url data class and extension functions for generating sitemaps. * * Sitemap is a set of urls. Therefore, to generate sitemap xml, use toXml extension functions * on a set of sitemap urls. * * Example: * * setOf(Url("http://example.com", "2016-01-01")).toXml() * * @author knesek * Created on: 6/14/16 */ data class Url ( val loc: String, val lastmod: String ) { constructor(loc: String, lastmod: Instant = Instant.now()) : this(loc, lastmod.atOffset(ZoneOffset.UTC).toLocalDate()) constructor(loc: String, lastmod: LocalDate) : this(loc, DateTimeFormatter.ISO_DATE.format(lastmod)) } fun Collection<Url>.toXml(writer: Writer) { val factory = XMLOutputFactory.newInstance() val sitemapNS = "http://www.sitemaps.org/schemas/sitemap/0.9" val schemaNS = "http://www.w3.org/2001/XMLSchema-instance" factory.createXMLStreamWriter(writer).apply { try { writeStartDocument() writeStartElement("", "urlset", sitemapNS) writeNamespace("", sitemapNS) writeNamespace("xsi", schemaNS) writeAttribute(schemaNS, "schemaLocation", "$sitemapNS $sitemapNS/sitemap.xsd") forEach { writeStartElement("url") writeStartElement("loc") //collapse index.html in sitemap val loc = if (it.loc.endsWith("index.html")) { it.loc.substring(0, it.loc.length - "index.html".length) } else { it.loc } writeCharacters(loc) writeEndElement() writeStartElement("lastmod") writeCharacters(it.lastmod) writeEndElement() writeEndElement() //url } writeEndElement() //urlset writeEndDocument() } catch (e: Exception) { throw RuntimeException("Failed generating sitemap xml: ${e.message}", e) } finally { flush() close() } } } fun Collection<Url>.toXml() = StringWriter().apply { toXml(this) }.toString()
src/main/kotlin/io/github/knes1/kotao/brew/util/SiteMap.kt
2507464759
package kt15259 interface ObjectFace private fun makeFace() = object : ObjectFace { //Breakpoint! init { 5 } } fun main() { makeFace() } // STEP_OVER: 1 // EXPRESSION: this // RESULT: 'this' is not defined in this context // TODO: Muted on the IR Evaluator // This is affected by additional steps in initializers by the IR backend.
plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/kt15259.kt
1519169228
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testGuiFramework.recorder import com.intellij.ide.IdeEventQueue import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.ex.AnActionListener import com.intellij.openapi.diagnostic.Logger import com.intellij.testGuiFramework.recorder.ui.GuiScriptEditorPanel import java.awt.event.KeyEvent import java.awt.event.MouseEvent /** * @author Sergey Karashevich */ object GlobalActionRecorder { private val LOG = Logger.getInstance("#${GlobalActionRecorder::class.qualifiedName}") var isActive: Boolean = false private set private val globalActionListener = object : AnActionListener { override fun beforeActionPerformed(action: AnAction?, dataContext: DataContext?, event: AnActionEvent?) { if (event?.place == GuiScriptEditorPanel.GUI_SCRIPT_EDITOR_PLACE) return //avoid GUI Script Editor Actions if(action == null) return EventDispatcher.processActionEvent(action, event) LOG.info("IDEA is going to perform action ${action.templatePresentation.text}") } override fun beforeEditorTyping(c: Char, dataContext: DataContext?) { LOG.info("IDEA typing detected: ${c}") } override fun afterActionPerformed(action: AnAction?, dataContext: DataContext?, event: AnActionEvent?) { if (event?.place == GuiScriptEditorPanel.GUI_SCRIPT_EDITOR_PLACE) return //avoid GUI Script Editor Actions if (action == null) return LOG.info("IDEA action performed ${action.templatePresentation.text}") } } private val globalAwtProcessor = IdeEventQueue.EventDispatcher { awtEvent -> when (awtEvent) { is MouseEvent -> EventDispatcher.processMouseEvent(awtEvent) is KeyEvent -> EventDispatcher.processKeyBoardEvent(awtEvent) } false } fun activate() { if (isActive) return LOG.info("Global action recorder is active") ActionManager.getInstance().addAnActionListener(globalActionListener) IdeEventQueue.getInstance().addDispatcher(globalAwtProcessor, GuiRecorderManager.frame) //todo: add disposal dependency on component isActive = true } fun deactivate() { if (isActive) { LOG.info("Global action recorder is non active") ActionManager.getInstance().removeAnActionListener(globalActionListener) IdeEventQueue.getInstance().removeDispatcher(globalAwtProcessor) } isActive = false ContextChecker.clearContext() } }
platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/GlobalActionRecorder.kt
298568151
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.tests.auth import io.ktor.client.* import io.ktor.http.* import io.ktor.http.auth.* import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.server.testing.* import io.ktor.util.* import kotlinx.coroutines.* import java.time.* import java.util.concurrent.* import kotlin.math.* import kotlin.test.* @Suppress("DEPRECATION") class OAuth1aSignatureTest { @Test fun testSignatureBaseString() { val header = HttpAuthHeader.Parameterized( "OAuth", mapOf( "oauth_consumer_key" to "1CV4Ud1ZOOzRMwmRyCEe0PY7J", "oauth_nonce" to "e685449bf73912c1ebb57220a2158380", "oauth_signature_method" to "HMAC-SHA1", "oauth_timestamp" to "1447068216", "oauth_version" to "1.0" ) ) val baseString = signatureBaseStringInternal( header, HttpMethod.Post, "https://api.twitter.com/oauth/request_token", emptyList() ) assertEquals( "POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&" + "oauth_consumer_key%3D1CV4Ud1ZOOzRMwmRyCEe0PY7J%26oauth_nonce%3De685449bf73912c1ebb57220a2158380%26" + "oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1447068216%26oauth_version%3D1.0", baseString ) } @Test fun testSignatureBaseStringWithCallback() { val header = HttpAuthHeader.Parameterized( "OAuth", mapOf( "oauth_callback" to "http://localhost/sign-in-with-twitter/", "oauth_consumer_key" to "1CV4Ud1ZOOzRMwmRyCEe0PY7J", "oauth_nonce" to "2f085f69a50e55ea6f1bd4e2b3907448", "oauth_signature_method" to "HMAC-SHA1", "oauth_timestamp" to "1447072553", "oauth_version" to "1.0" ) ) val baseString = signatureBaseStringInternal( header, HttpMethod.Post, "https://api.twitter.com/oauth/request_token", emptyList() ) assertEquals( "POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&" + "oauth_callback%3Dhttp%253A%252F%252Flocalhost%252Fsign-in-with-twitter%252F%26" + "oauth_consumer_key%3D1CV4Ud1ZOOzRMwmRyCEe0PY7J%26oauth_nonce%3D2f085f69a50e55ea6f1bd4e2b3907448%26" + "oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1447072553%26oauth_version%3D1.0", baseString ) } } @Suppress("DEPRECATION") class OAuth1aFlowTest { private var testClient: HttpClient? = null @BeforeTest fun createServer() { testClient = createOAuthServer( object : TestingOAuthServer { override fun requestToken( ctx: ApplicationCall, callback: String?, consumerKey: String, nonce: String, signature: String, signatureMethod: String, timestamp: Long ): TestOAuthTokenResponse { if (consumerKey != "1CV4Ud1ZOOzRMwmRyCEe0PY7J") { throw IllegalArgumentException("Bad consumer key specified: $consumerKey") } if (signatureMethod != "HMAC-SHA1") { throw IllegalArgumentException("Bad signature method specified: $signatureMethod") } val now = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) if (abs(now - timestamp) > 10000) { throw IllegalArgumentException("timestamp is too old: $timestamp (now $now)") } return TestOAuthTokenResponse( callback == "http://localhost/login?redirected=true", "token1", "tokenSecret1" ) } override suspend fun authorize(call: ApplicationCall, oauthToken: String) { if (oauthToken != "token1") { call.respondRedirect("http://localhost/login?redirected=true&error=Wrong+token+$oauthToken") } call.respondRedirect( "http://localhost/login?redirected=true&oauth_token=$oauthToken&oauth_verifier=verifier1" ) } override fun accessToken( ctx: ApplicationCall, consumerKey: String, nonce: String, signature: String, signatureMethod: String, timestamp: Long, token: String, verifier: String ): OAuthAccessTokenResponse.OAuth1a { if (consumerKey != "1CV4Ud1ZOOzRMwmRyCEe0PY7J") { throw IllegalArgumentException("Bad consumer key specified $consumerKey") } if (signatureMethod != "HMAC-SHA1") { throw IllegalArgumentException("Bad signature method specified: $signatureMethod") } val now = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) if (abs(now - timestamp) > 10000) { throw IllegalArgumentException("timestamp is too old: $timestamp (now $now)") } // NOTE real server should test it but as we don't test the whole workflow in one test we can't do it // if (nonce !in knownNonceSet) { // throw IllegalArgumentException("Bad nonce specified: $nonce") // } if (token != "token1") { throw IllegalArgumentException("Wrong token specified: $token") } if (verifier != "verifier1") { throw IllegalArgumentException("Wrong verifier specified: $verifier") } return OAuthAccessTokenResponse.OAuth1a( "temp-token-1", "temp-secret-1", Parameters.Empty ) } } ) } @AfterTest fun destroyServer() { testClient?.close() testClient = null } private val executor = Executors.newSingleThreadExecutor() private val dispatcher = executor.asCoroutineDispatcher() private val settings = OAuthServerSettings.OAuth1aServerSettings( name = "oauth1a", requestTokenUrl = "https://login-server-com/oauth/request_token", authorizeUrl = "https://login-server-com/oauth/authorize", accessTokenUrl = "https://login-server-com/oauth/access_token", consumerKey = "1CV4Ud1ZOOzRMwmRyCEe0PY7J", consumerSecret = "0xPR3CQaGOilgXCGUt4g6SpBkhti9DOGkWtBCOImNFomedZ3ZU" ) @AfterTest fun tearDown() { executor.shutdownNow() } @Test fun testRequestToken() { withTestApplication { application.configureServer("http://localhost/login?redirected=true") val result = handleRequest(HttpMethod.Get, "/login") waitExecutor() assertEquals(HttpStatusCode.Found, result.response.status()) assertNull(result.response.content) assertEquals( "https://login-server-com/oauth/authorize?oauth_token=token1", result.response.headers[HttpHeaders.Location], "Redirect target location is not valid" ) } } @Test fun testRequestTokenWrongConsumerKey() { withTestApplication { application.configureServer( "http://localhost/login?redirected=true", mutateSettings = { OAuthServerSettings.OAuth1aServerSettings( name, requestTokenUrl, authorizeUrl, accessTokenUrl, "badConsumerKey", consumerSecret ) } ) val result = handleRequest(HttpMethod.Get, "/login") waitExecutor() assertEquals(HttpStatusCode.Unauthorized, result.response.status()) } } @Test fun testRequestTokenFailedRedirect() { withTestApplication { application.configureServer("http://localhost/login") val result = handleRequest(HttpMethod.Get, "/login") waitExecutor() assertEquals(HttpStatusCode.Unauthorized, result.response.status()) } } @Test fun testAccessToken() { withTestApplication { application.configureServer() val result = handleRequest( HttpMethod.Get, "/login?redirected=true&oauth_token=token1&oauth_verifier=verifier1" ) waitExecutor() assertEquals(HttpStatusCode.OK, result.response.status()) assertTrue { result.response.content!!.startsWith("Ho, ") } assertFalse { result.response.content!!.contains("[]") } } } @Test fun testAccessTokenWrongVerifier() { withTestApplication { application.configureServer() val result = handleRequest( HttpMethod.Get, "/login?redirected=true&oauth_token=token1&oauth_verifier=verifier2" ) waitExecutor() assertEquals(HttpStatusCode.Found, result.response.status()) assertNotNull(result.response.headers[HttpHeaders.Location]) assertTrue { result.response.headers[HttpHeaders.Location]!! .startsWith("https://login-server-com/oauth/authorize") } } } @Test fun testRequestTokenLowLevel() { withTestApplication { application.routing { get("/login") { @Suppress("DEPRECATION_ERROR") oauthRespondRedirect(testClient!!, dispatcher, settings, "http://localhost/login?redirected=true") } } val result = handleRequest(HttpMethod.Get, "/login") waitExecutor() assertEquals(HttpStatusCode.Found, result.response.status()) assertEquals( "https://login-server-com/oauth/authorize?oauth_token=token1", result.response.headers[HttpHeaders.Location], "Redirect target location is not valid" ) } } @Test fun testAccessTokenLowLevel() { withTestApplication { application.routing { get("/login") { @Suppress("DEPRECATION_ERROR") oauthHandleCallback( testClient!!, dispatcher, settings, "http://localhost/login?redirected=true", "/" ) { token -> call.respondText("Ho, $token") } } } val result = handleRequest( HttpMethod.Get, "/login?redirected=true&oauth_token=token1&oauth_verifier=verifier1" ) waitExecutor() assertEquals(HttpStatusCode.OK, result.response.status()) assertTrue { result.response.content!!.startsWith("Ho, ") } assertFalse { result.response.content!!.contains("null") } } } @Test fun testAccessTokenLowLevelErrorRedirect() { withTestApplication { application.routing { get("/login") { @Suppress("DEPRECATION_ERROR") oauthHandleCallback( testClient!!, dispatcher, settings, "http://localhost/login?redirected=true", "/" ) { token -> call.respondText("Ho, $token") } } } val result = handleRequest( HttpMethod.Get, "/login?redirected=true&oauth_token=token1&error_description=failed" ) assertEquals(HttpStatusCode.Found, result.response.status()) } } private fun Application.configureServer( redirectUrl: String = "http://localhost/login?redirected=true", mutateSettings: OAuthServerSettings.OAuth1aServerSettings.() -> OAuthServerSettings.OAuth1aServerSettings = { this } ) { install(Authentication) { oauth { client = testClient!! providerLookup = { settings.mutateSettings() } urlProvider = { redirectUrl } } } routing { authenticate { get("/login") { call.respondText("Ho, ${call.authentication.principal}") } } } } private fun waitExecutor() { val latch = CountDownLatch(1) executor.submit { latch.countDown() } latch.await(1L, TimeUnit.MINUTES) } } // NOTICE in fact we can potentially reorganize it to provide API for ktor-users to build their own OAuth servers // for now we have it only for the testing purpose private interface TestingOAuthServer { fun requestToken( ctx: ApplicationCall, callback: String?, consumerKey: String, nonce: String, signature: String, signatureMethod: String, timestamp: Long ): TestOAuthTokenResponse suspend fun authorize(call: ApplicationCall, oauthToken: String) fun accessToken( ctx: ApplicationCall, consumerKey: String, nonce: String, signature: String, signatureMethod: String, timestamp: Long, token: String, verifier: String ): OAuthAccessTokenResponse.OAuth1a } private fun createOAuthServer(server: TestingOAuthServer): HttpClient { val environment = createTestEnvironment { module { routing { post("/oauth/request_token") { val authHeader = call.request.parseAuthorizationHeader() ?: throw IllegalArgumentException("No auth header found") assertEquals(AuthScheme.OAuth, authHeader.authScheme, "This is not an OAuth request") if (authHeader !is HttpAuthHeader.Parameterized) { call.fail( "Bad OAuth header supplied: should be parameterized auth header but token68 blob found" ) return@post } val callback = authHeader.parameter(HttpAuthHeader.Parameters.OAuthCallback)?.decodeURLPart() val consumerKey = authHeader.requireParameter(HttpAuthHeader.Parameters.OAuthConsumerKey) val nonce = authHeader.requireParameter(HttpAuthHeader.Parameters.OAuthNonce) val signatureMethod = authHeader.requireParameter(HttpAuthHeader.Parameters.OAuthSignatureMethod) val signature = authHeader.requireParameter(HttpAuthHeader.Parameters.OAuthSignature) val timestamp = authHeader.requireParameter(HttpAuthHeader.Parameters.OAuthTimestamp).toLong() val version = authHeader.requireParameter(HttpAuthHeader.Parameters.OAuthVersion) assertEquals("1.0", version) try { val rr = server.requestToken( call, callback, consumerKey, nonce, signature, signatureMethod, timestamp ) call.response.status(HttpStatusCode.OK) call.respondText( listOf( HttpAuthHeader.Parameters.OAuthToken to rr.token, HttpAuthHeader.Parameters.OAuthTokenSecret to rr.tokenSecret, HttpAuthHeader.Parameters.OAuthCallbackConfirmed to rr.callbackConfirmed.toString() ).formUrlEncode(), ContentType.Application.FormUrlEncoded ) } catch (e: Exception) { call.fail(e.message) } } post("/oauth/access_token") { val authHeader = call.request.parseAuthorizationHeader() ?: throw IllegalArgumentException("No auth header found") assertEquals(AuthScheme.OAuth, authHeader.authScheme, "This is not an OAuth request") if (authHeader !is HttpAuthHeader.Parameterized) { throw IllegalStateException( "Bad OAuth header supplied: should be parameterized auth header but token68 blob found" ) } val consumerKey = authHeader.requireParameter(HttpAuthHeader.Parameters.OAuthConsumerKey) val nonce = authHeader.requireParameter(HttpAuthHeader.Parameters.OAuthNonce) val signature = authHeader.requireParameter(HttpAuthHeader.Parameters.OAuthSignature) val signatureMethod = authHeader.requireParameter(HttpAuthHeader.Parameters.OAuthSignatureMethod) val timestamp = authHeader.requireParameter(HttpAuthHeader.Parameters.OAuthTimestamp).toLong() val token = authHeader.requireParameter(HttpAuthHeader.Parameters.OAuthToken) val version = authHeader.requireParameter(HttpAuthHeader.Parameters.OAuthVersion) if (version != "1.0") { call.fail("Only version 1.0 is supported") } if (!call.request.contentType().match(ContentType.Application.FormUrlEncoded)) { call.fail("content type should be ${ContentType.Application.FormUrlEncoded}") } val values = call.receiveParameters() val verifier = values[HttpAuthHeader.Parameters.OAuthVerifier] ?: throw IllegalArgumentException("oauth_verified is not provided in the POST request body") try { val tokenPair = server.accessToken( call, consumerKey, nonce, signature, signatureMethod, timestamp, token, verifier ) call.response.status(HttpStatusCode.OK) call.respondText( ( listOf( HttpAuthHeader.Parameters.OAuthToken to tokenPair.token, HttpAuthHeader.Parameters.OAuthTokenSecret to tokenPair.tokenSecret ) + tokenPair.extraParameters.flattenEntries() ).formUrlEncode(), ContentType.Application.FormUrlEncoded ) } catch (e: Exception) { call.fail(e.message) } } post("/oauth/authorize") { val oauthToken = call.parameters[HttpAuthHeader.Parameters.OAuthToken] ?: throw IllegalArgumentException("No oauth_token parameter specified") server.authorize(call, oauthToken) call.response.status(HttpStatusCode.OK) } } } } with(TestApplicationEngine(environment)) { start() return client.config { expectSuccess = false } } } private suspend fun ApplicationCall.fail(text: String?) { val message = text ?: "Auth failed" response.status(HttpStatusCode.InternalServerError) respondText(message) } private fun HttpAuthHeader.Parameterized.requireParameter(name: String): String = parameter(name)?.decodeURLPart() ?: throw IllegalArgumentException("No $name parameter specified in OAuth header") data class TestOAuthTokenResponse(val callbackConfirmed: Boolean, val token: String, val tokenSecret: String)
ktor-server/ktor-server-plugins/ktor-server-auth/jvm/test/io/ktor/tests/auth/OAuth1aTest.kt
1652309378
package com.airbnb.lottie.sample.compose.utils import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp fun Modifier.maybeBackground(color: Color?): Modifier { return if (color == null) { this } else { this.then(background(color)) } } fun Modifier.drawTopBorder(color: Color = Color.DarkGray) = this.then(drawBehind { drawRect(color, Offset.Zero, size = Size(size.width, 1f)) }) fun Modifier.drawBottomBorder(color: Color = Color.DarkGray) = this.then(drawBehind { drawRect(color, Offset(0f, size.height - 1f), size = Size(size.width, 1f)) }) fun Modifier.maybeDrawBorder(draw: Boolean, color: Color = Color.Black, width: Dp = 1.dp): Modifier { return if (draw) { this.then(border(width, color)) } else { this } }
sample-compose/src/main/java/com/airbnb/lottie/sample/compose/utils/ComposeExtensions.kt
1627206533
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* val ARB_program_interface_query = "ARBProgramInterfaceQuery".nativeClassGL("ARB_program_interface_query") { documentation = """ Native bindings to the $registryLink extension. This extension provides a single unified set of query commands that can be used by applications to determine properties of various interfaces and resources used by program objects to communicate with application code, fixed-function OpenGL pipeline stages, and other programs. In unextended OpenGL 4.2, there is a separate set of query commands for each different type of interface or resource used by the program. These different sets of queries are structured nearly identically, but the queries for some interfaces have limited capability (e.g., there is no ability to enumerate fragment shader outputs). With the single set of query commands provided by this extension, a consistent set of queries is available for all interfaces, and a new interface can be added without having to introduce a completely new set of query commands. These queries are intended to provide a superset of the capabilities provided by similar queries in OpenGL 4.2, and should allow for the deprecation of the existing queries. This extension defines two terms: interfaces and active resources. Each interface of a program object provides a way for the program to communicate with application code, fixed-function OpenGL pipeline stages, and other programs. Examples of interfaces for a program object include inputs (receiving values from vertex attributes or outputs of other programs), outputs (sending values to other programs or per-fragment operations), uniforms (receiving values from API calls), uniform blocks (receiving values from bound buffer objects), subroutines and subroutine uniforms (receiving API calls to indicate functions to call during program execution), and atomic counter buffers (holding values to be manipulated by atomic counter shader functions). Each interface of a program has a set of active resources used by the program. For example, the resources of a program's input interface includes all active input variables used by the first stage of the program. The resources of a program's uniform block interface consists of the set of uniform blocks with at least one member used by any shader in the program. Requires ${GL20.core}. ${GL43.promoted} """ IntConstant( """ Accepted by the {@code programInterface} parameter of GetProgramInterfaceiv, GetProgramResourceIndex, GetProgramResourceName, GetProgramResourceiv, GetProgramResourceLocation, and GetProgramResourceLocationIndex. """, "UNIFORM"..0x92E1, "UNIFORM_BLOCK"..0x92E2, "PROGRAM_INPUT"..0x92E3, "PROGRAM_OUTPUT"..0x92E4, "BUFFER_VARIABLE"..0x92E5, "SHADER_STORAGE_BLOCK"..0x92E6, "VERTEX_SUBROUTINE"..0x92E8, "TESS_CONTROL_SUBROUTINE"..0x92E9, "TESS_EVALUATION_SUBROUTINE"..0x92EA, "GEOMETRY_SUBROUTINE"..0x92EB, "FRAGMENT_SUBROUTINE"..0x92EC, "COMPUTE_SUBROUTINE"..0x92ED, "VERTEX_SUBROUTINE_UNIFORM"..0x92EE, "TESS_CONTROL_SUBROUTINE_UNIFORM"..0x92EF, "TESS_EVALUATION_SUBROUTINE_UNIFORM"..0x92F0, "GEOMETRY_SUBROUTINE_UNIFORM"..0x92F1, "FRAGMENT_SUBROUTINE_UNIFORM"..0x92F2, "COMPUTE_SUBROUTINE_UNIFORM"..0x92F3, "TRANSFORM_FEEDBACK_VARYING"..0x92F4 ) IntConstant( "Accepted by the {@code pname} parameter of GetProgramInterfaceiv.", "ACTIVE_RESOURCES"..0x92F5, "MAX_NAME_LENGTH"..0x92F6, "MAX_NUM_ACTIVE_VARIABLES"..0x92F7, "MAX_NUM_COMPATIBLE_SUBROUTINES"..0x92F8 ) IntConstant( "Accepted in the {@code props} array of GetProgramResourceiv.", "NAME_LENGTH"..0x92F9, "TYPE"..0x92FA, "ARRAY_SIZE"..0x92FB, "OFFSET"..0x92FC, "BLOCK_INDEX"..0x92FD, "ARRAY_STRIDE"..0x92FE, "MATRIX_STRIDE"..0x92FF, "IS_ROW_MAJOR"..0x9300, "ATOMIC_COUNTER_BUFFER_INDEX"..0x9301, "BUFFER_BINDING"..0x9302, "BUFFER_DATA_SIZE"..0x9303, "NUM_ACTIVE_VARIABLES"..0x9304, "ACTIVE_VARIABLES"..0x9305, "REFERENCED_BY_VERTEX_SHADER"..0x9306, "REFERENCED_BY_TESS_CONTROL_SHADER"..0x9307, "REFERENCED_BY_TESS_EVALUATION_SHADER"..0x9308, "REFERENCED_BY_GEOMETRY_SHADER"..0x9309, "REFERENCED_BY_FRAGMENT_SHADER"..0x930A, "REFERENCED_BY_COMPUTE_SHADER"..0x930B, "TOP_LEVEL_ARRAY_SIZE"..0x930C, "TOP_LEVEL_ARRAY_STRIDE"..0x930D, "LOCATION"..0x930E, "LOCATION_INDEX"..0x930F, "IS_PER_PATCH"..0x92E7 ) reuse(GL43C, "GetProgramInterfaceiv") reuse(GL43C, "GetProgramResourceIndex") reuse(GL43C, "GetProgramResourceName") reuse(GL43C, "GetProgramResourceiv") reuse(GL43C, "GetProgramResourceLocation") reuse(GL43C, "GetProgramResourceLocationIndex") }
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_program_interface_query.kt
2787210990
package com.scientists.happy.botanist.controller import android.app.Activity import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.* import com.bumptech.glide.Glide import com.firebase.ui.database.FirebaseListAdapter import com.firebase.ui.storage.images.FirebaseImageLoader import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.ValueEventListener import com.google.firebase.storage.StorageReference import com.scientists.happy.botanist.R import com.scientists.happy.botanist.data.Plant import za.co.riggaroo.materialhelptutorial.TutorialItem import java.util.* class EditPlantController(activity: AppCompatActivity) : ActivityController(activity) { private val mPlantId: String = activity.intent.extras.getString("plant_id") private var mPlantName: String? = null private var mPhotoNum: Int = 0 private var mPhotoPointer = -1 private val mPlantReference = databaseManager.getPlantReference(mPlantId) private val mUserPhotosReference = databaseManager.userPhotosReference private val mUserStorage = databaseManager.userStorage init { mPlantReference.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { if (dataSnapshot.exists()) { val plant = dataSnapshot.getValue(Plant::class.java) if (plant != null) { val nameTextView = activity.findViewById<TextView>(R.id.name_text_view) mPlantName = plant.name nameTextView.text = mPlantName mPhotoNum = plant.photoNum mPhotoPointer = plant.photoPointer } } } override fun onCancelled(databaseError: DatabaseError) { } }) } override fun load() { showProgressDialog(activity.getString(R.string.loading_text)) loadNameSection() val grid = activity.findViewById<GridView>(R.id.photo_grid_view) grid.emptyView = activity.findViewById(R.id.empty_grid_view) populatePhotoGrid(activity) hideProgressDialog() } override fun loadTutorialItems(): ArrayList<TutorialItem>? { return null } /** * populate a grid with plant photos * @param activity - the current activity */ private fun populatePhotoGrid(activity: Activity) { val grid = activity.findViewById<GridView>(R.id.photo_grid_view) val emptyGridView = activity.findViewById<TextView>(R.id.empty_grid_view) val loadingProgressBar = activity.findViewById<ProgressBar>(R.id.loading_indicator) loadingProgressBar.visibility = View.VISIBLE if (mUserPhotosReference != null) { // An SQL-like hack to retrieve only data with values that matches the query: "plantId*" // This is needed to query only images that correspond to the specific plant being edited val query = mUserPhotosReference.orderByValue().startAt(mPlantId).endAt(mPlantId + "\uf8ff") val adapter = object : FirebaseListAdapter<String>(activity, String::class.java, R.layout.grid_item_photo, query) { /** * Populate a photo grid item * @param view - the current view * * * @param photoName - the photo to display * * * @param position - the position */ override fun populateView(view: View, photoName: String, position: Int) { val profilePhotoRef = mPlantReference.child("profilePhoto") val storageReference = mUserStorage.child(photoName) val picture = view.findViewById<ImageView>(R.id.photo_image_view) val isProfilePicture = BooleanArray(1) Glide.with(activity).using(FirebaseImageLoader()).load(storageReference).dontAnimate() .placeholder(R.drawable.flowey).into(picture) val setButton = view.findViewById<View>(R.id.set_photo_btn) setButton.setOnClickListener { profilePhotoRef.setValue(photoName) notifyDataSetChanged() } view.findViewById<ImageView>(R.id.delete_photo_btn).setOnClickListener { buildDeletePhotoDialog(storageReference, profilePhotoRef, position, isProfilePicture[0]).show() } profilePhotoRef.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val profilePhoto = dataSnapshot.value as String? val isSetIndicator = view.findViewById<View>(R.id.is_set_indicator) isProfilePicture[0] = profilePhoto != null && profilePhoto == photoName if (isProfilePicture[0]) { setButton.visibility = View.GONE isSetIndicator.visibility = View.VISIBLE } else { setButton.visibility = View.VISIBLE isSetIndicator.visibility = View.GONE } } override fun onCancelled(databaseError: DatabaseError) { } }) } override fun onDataChanged() { super.onDataChanged() val photoNumRef = mPlantReference.child("photoNum") // Keep photoNum up to date. (photoNum is zero-based) photoNumRef.setValue(count - 1) } /** * Delete Photo dialog * @return Return the dialog window warning user of photo removal */ private fun buildDeletePhotoDialog(storageReference: StorageReference, profilePhotoRef: DatabaseReference, position: Int, isProfilePicture: Boolean): AlertDialog { //Instantiate an AlertDialog.Builder with its constructor val builder = AlertDialog.Builder(activity) //Chain together various setter methods to set the dialog characteristics builder.setTitle(R.string.dialog_delete_photo_title).setMessage(R.string.dialog_delete_photo_text) // Add the buttons builder.setPositiveButton(R.string.yes) { _, _ -> storageReference.delete().addOnCompleteListener { task -> if (task.isSuccessful) { getRef(position).removeValue() if (isProfilePicture) { profilePhotoRef.setValue("default") } // Keep photoCount up-to-date databaseManager.photoCount = databaseManager.photoCount - 1 } } } builder.setNegativeButton(R.string.no) { _, _ -> } // Get the AlertDialog from create() return builder.create() } } // After digging deep, I discovered that Firebase keeps some local information in ".info" val connectedRef = databaseManager.userConnectionReference connectedRef.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val connected = snapshot.value as Boolean if (connected) { emptyGridView.setText(R.string.loading_text) loadingProgressBar.visibility = View.VISIBLE } else { Toast.makeText(activity, R.string.msg_network_error, Toast.LENGTH_SHORT).show() emptyGridView.setText(R.string.msg_network_error) loadingProgressBar.visibility = View.GONE } } override fun onCancelled(error: DatabaseError) {} }) mUserPhotosReference.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { loadingProgressBar.visibility = View.GONE emptyGridView.setText(R.string.grid_photos_empty_text) } override fun onCancelled(databaseError: DatabaseError) { emptyGridView.setText(R.string.msg_unexpected_error) loadingProgressBar.visibility = View.GONE } }) grid.adapter = adapter } } private fun loadNameSection() { activity.findViewById<Button>(R.id.rename_button).setOnClickListener { val builder = AlertDialog.Builder(activity) val dialogView = View.inflate(activity, R.layout.dialog_name_input, null) val inputEditText = dialogView.findViewById<EditText>(R.id.name_edit_text) inputEditText.setText(mPlantName) builder.setView(dialogView).setTitle(R.string.rename) // Set up the buttons builder.setPositiveButton(R.string.mdtp_ok) { _, _ -> mPlantReference.child("name").setValue(inputEditText.text.toString()) } builder.setNegativeButton(R.string.mdtp_cancel) { dialog, _ -> dialog.cancel() } builder.create().show() } } }
app/src/main/java/com/scientists/happy/botanist/controller/EditPlantController.kt
1164204375
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.updateSettings.impl import com.intellij.ide.IdeBundle import com.intellij.ide.util.DelegatingProgressIndicator import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.BuildNumber import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.util.ArrayUtil import com.intellij.util.Restarter import com.intellij.util.io.HttpRequests import java.io.File import java.io.IOException import java.net.URL import java.nio.file.Files import java.nio.file.Paths import javax.swing.UIManager object UpdateInstaller { const val UPDATER_MAIN_CLASS = "com.intellij.updater.Runner" private val patchesUrl: URL get() = URL(System.getProperty("idea.patches.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls.patchesUrl) @JvmStatic @Throws(IOException::class) fun downloadPatchChain(chain: List<BuildNumber>, forceHttps: Boolean, indicator: ProgressIndicator): List<File> { indicator.text = IdeBundle.message("update.downloading.patch.progress") val files = mutableListOf<File>() val product = ApplicationInfo.getInstance().build.productCode val jdk = if (System.getProperty("idea.java.redist", "").lastIndexOf("NoJavaDistribution") >= 0) "-no-jdk" else "" val share = 1.0 / (chain.size - 1) for (i in 1 until chain.size) { val from = chain[i - 1].withoutProductCode().asString() val to = chain[i].withoutProductCode().asString() val patchName = "${product}-${from}-${to}-patch${jdk}-${PatchInfo.OS_SUFFIX}.jar" val patchFile = File(getTempDir(), "patch${i}.jar") val url = URL(patchesUrl, patchName).toString() val partIndicator = object : DelegatingProgressIndicator(indicator) { override fun setFraction(fraction: Double) { super.setFraction((i - 1) * share + fraction / share) } } HttpRequests.request(url).gzip(false).forceHttps(forceHttps).saveToFile(patchFile, partIndicator) files += patchFile } return files } @JvmStatic fun installPluginUpdates(downloaders: Collection<PluginDownloader>, indicator: ProgressIndicator): Boolean { indicator.text = IdeBundle.message("update.downloading.plugins.progress") UpdateChecker.saveDisabledToUpdatePlugins() val disabledToUpdate = UpdateChecker.disabledToUpdatePlugins val readyToInstall = mutableListOf<PluginDownloader>() for (downloader in downloaders) { try { if (downloader.pluginId !in disabledToUpdate && downloader.prepareToInstall(indicator)) { readyToInstall += downloader } indicator.checkCanceled() } catch (e: ProcessCanceledException) { throw e } catch (e: Exception) { Logger.getInstance(UpdateChecker::class.java).info(e) } } var installed = false ProgressManager.getInstance().executeNonCancelableSection { for (downloader in readyToInstall) { try { downloader.install() installed = true } catch (e: Exception) { Logger.getInstance(UpdateChecker::class.java).info(e) } } } return installed } @JvmStatic fun cleanupPatch() { val tempDir = getTempDir() if (tempDir.exists()) FileUtil.delete(tempDir) } @JvmStatic @Throws(IOException::class) fun preparePatchCommand(patchFile: File, indicator: ProgressIndicator): Array<String> = preparePatchCommand(listOf(patchFile), indicator) @JvmStatic @Throws(IOException::class) fun preparePatchCommand(patchFiles: List<File>, indicator: ProgressIndicator): Array<String> { indicator.text = IdeBundle.message("update.preparing.patch.progress") val log4j = findLib("log4j.jar") val jna = findLib("jna.jar") val jnaUtils = findLib("jna-platform.jar") val tempDir = getTempDir() if (FileUtil.isAncestor(PathManager.getHomePath(), tempDir.path, true)) { throw IOException("Temp directory inside installation: $tempDir") } if (!(tempDir.exists() || tempDir.mkdirs())) { throw IOException("Cannot create temp directory: $tempDir") } val log4jCopy = log4j.copyTo(File(tempDir, log4j.name), true) val jnaCopy = jna.copyTo(File(tempDir, jna.name), true) val jnaUtilsCopy = jnaUtils.copyTo(File(tempDir, jnaUtils.name), true) var java = System.getProperty("java.home") if (FileUtil.isAncestor(PathManager.getHomePath(), java, true)) { val javaCopy = File(tempDir, "jre") FileUtil.copyDir(File(java), javaCopy) java = javaCopy.path } val args = arrayListOf<String>() if (SystemInfo.isWindows && !Files.isWritable(Paths.get(PathManager.getHomePath()))) { val launcher = PathManager.findBinFile("launcher.exe") val elevator = PathManager.findBinFile("elevator.exe") // "launcher" depends on "elevator" if (launcher != null && elevator != null && launcher.canExecute() && elevator.canExecute()) { args += Restarter.createTempExecutable(launcher).path Restarter.createTempExecutable(elevator) } } args += File(java, if (SystemInfo.isWindows) "bin\\java.exe" else "bin/java").path args += "-Xmx900m" args += "-cp" args += arrayOf(patchFiles.last().path, log4jCopy.path, jnaCopy.path, jnaUtilsCopy.path).joinToString(File.pathSeparator) args += "-Djna.nosys=true" args += "-Djna.boot.library.path=" args += "-Djna.debug_load=true" args += "-Djna.debug_load.jna=true" args += "-Djava.io.tmpdir=${tempDir.path}" args += "-Didea.updater.log=${PathManager.getLogPath()}" args += "-Dswing.defaultlaf=${UIManager.getSystemLookAndFeelClassName()}" args += UPDATER_MAIN_CLASS args += if (patchFiles.size == 1) "install" else "batch-install" args += PathManager.getHomePath() if (patchFiles.size > 1) { args += patchFiles.joinToString(File.pathSeparator) } return ArrayUtil.toStringArray(args) } private fun findLib(libName: String): File { val libFile = File(PathManager.getLibPath(), libName) return if (libFile.exists()) libFile else throw IOException("Missing: ${libFile}") } private fun getTempDir() = File(PathManager.getTempPath(), "patch-update") }
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInstaller.kt
1866581394
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * 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 org.hisp.dhis.android.core.dataset.internal import dagger.Reusable import io.reactivex.Completable import javax.inject.Inject import org.hisp.dhis.android.core.arch.call.factories.internal.UidsCall import org.hisp.dhis.android.core.arch.call.factories.internal.UidsCallFactory import org.hisp.dhis.android.core.arch.db.stores.internal.LinkStore import org.hisp.dhis.android.core.arch.helpers.UidsHelper.getUids import org.hisp.dhis.android.core.arch.modules.internal.UntypedModuleDownloader import org.hisp.dhis.android.core.dataelement.DataElement import org.hisp.dhis.android.core.dataset.DataSet import org.hisp.dhis.android.core.dataset.DataSetOrganisationUnitLink import org.hisp.dhis.android.core.dataset.DataSetOrganisationUnitLinkTableInfo import org.hisp.dhis.android.core.option.Option import org.hisp.dhis.android.core.option.OptionSet import org.hisp.dhis.android.core.period.internal.PeriodHandler import org.hisp.dhis.android.core.validation.ValidationRule import org.hisp.dhis.android.core.validation.internal.ValidationRuleUidsCall @Reusable internal class DataSetModuleDownloader @Inject internal constructor( private val dataSetCallFactory: UidsCallFactory<DataSet>, private val dataElementCallFactory: UidsCallFactory<DataElement>, private val optionSetCall: UidsCall<OptionSet>, private val optionCall: UidsCall<Option>, private val validationRuleCall: UidsCall<ValidationRule>, private val validationRuleUidsCall: ValidationRuleUidsCall, private val periodHandler: PeriodHandler, private val dataSetOrganisationUnitLinkStore: LinkStore<DataSetOrganisationUnitLink> ) : UntypedModuleDownloader { override fun downloadMetadata(): Completable { return Completable.fromCallable { val orgUnitDataSetUids = dataSetOrganisationUnitLinkStore .selectDistinctSlaves(DataSetOrganisationUnitLinkTableInfo.Columns.DATA_SET) val dataSets = dataSetCallFactory.create(orgUnitDataSetUids).call() val dataElements = dataElementCallFactory.create( DataSetParentUidsHelper.getDataElementUids(dataSets) ).call() val optionSetUids = DataSetParentUidsHelper.getAssignedOptionSetUids(dataElements) optionSetCall.download(optionSetUids).blockingGet() optionCall.download(optionSetUids).blockingGet() val validationRuleUids = validationRuleUidsCall.download(getUids(dataSets)).blockingGet() validationRuleCall.download(getUids(validationRuleUids)).blockingGet() periodHandler.generateAndPersist() } } }
core/src/main/java/org/hisp/dhis/android/core/dataset/internal/DataSetModuleDownloader.kt
208314022
/* * Copyright (C) 2016-Present The MoonLake ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mcmoonlake.api.packet import com.mcmoonlake.api.isExplorationOrLaterVer data class PacketOutCollect( var itemEntityId: Int, var entityId: Int, /** * * Pick up the amount, Only valid at 1.11 or higher. * * 拾取数量, δ»…εœ¨ 1.11 ζˆ–ζ›΄ι«˜η‰ˆζœ¬ζœ‰ζ•ˆ. */ var pickupCount: Int ) : PacketOutBukkitAbstract("PacketPlayOutCollect") { @Deprecated("") constructor() : this(-1, -1, -1) override fun read(data: PacketBuffer) { itemEntityId = data.readVarInt() entityId = data.readVarInt() if(isExplorationOrLaterVer) pickupCount = data.readVarInt() } override fun write(data: PacketBuffer) { data.writeVarInt(itemEntityId) data.writeVarInt(entityId) if(isExplorationOrLaterVer) data.writeVarInt(pickupCount) } }
API/src/main/kotlin/com/mcmoonlake/api/packet/PacketOutCollect.kt
2850860341