content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.github.developer__ import android.content.Context import android.graphics.drawable.Drawable import android.util.AttributeSet import android.view.LayoutInflater import android.widget.RelativeLayout import com.github.developer__.asycn.ClipDrawableProcessorTask import com.github.developer__.extensions.loadImage import com.github.developer__.extensions.stayVisibleOrGone import kotlinx.android.synthetic.main.slider_layout.view.* /** * Created by Jemo on 12/5/16. */ class BeforeAfterSlider : RelativeLayout, ClipDrawableProcessorTask.OnAfterImageLoaded{ constructor(context: Context): super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { val attr = context.theme.obtainStyledAttributes(attrs, R.styleable.BeforeAfterSlider,0,0) try { val thumbDrawable = attr.getDrawable(R.styleable.BeforeAfterSlider_slider_thumb) val beforeImage = attr.getDrawable(R.styleable.BeforeAfterSlider_before_image) val afterImageUrl = attr.getDrawable(R.styleable.BeforeAfterSlider_after_image) setSliderThumb(thumbDrawable) setBeforeImage(beforeImage) setAfterImage(afterImageUrl) }finally { attr.recycle() } } init { LayoutInflater.from(context).inflate(R.layout.slider_layout, this) } /** * set original image */ fun setBeforeImage(imageUri: String): BeforeAfterSlider { before_image_view_id.loadImage(imageUri) return this } fun setBeforeImage(imgDrawable: Drawable?): BeforeAfterSlider { before_image_view_id.loadImage(imgDrawable) return this } /** * set changed image */ fun setAfterImage(imageUri: String) { ClipDrawableProcessorTask<String>(after_image_view_id, seekbar_id, context, this).execute(imageUri) } /** * set changed image */ fun setAfterImage(imageDrawable: Drawable?) { ClipDrawableProcessorTask<Drawable>(after_image_view_id, seekbar_id, context, this).execute(imageDrawable) } /** * set thumb */ fun setSliderThumb(thumb: Drawable?){ thumb?.let { seekbar_id.thumb = thumb } } /** * fired up after second image loading will be finished */ override fun onLoadedFinished(loadedSuccess: Boolean) { seekbar_id.stayVisibleOrGone(loadedSuccess) } }
beforeafterslider/src/main/java/com/github/developer__/BeforeAfterSlider.kt
3191283035
package com.simplemobiletools.gallery.pro.fragments import android.provider.MediaStore import android.provider.MediaStore.Files import android.provider.MediaStore.Images import android.view.MotionEvent import androidx.exifinterface.media.ExifInterface import androidx.fragment.app.Fragment import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.gallery.pro.R import com.simplemobiletools.gallery.pro.extensions.config import com.simplemobiletools.gallery.pro.helpers.* import com.simplemobiletools.gallery.pro.models.Medium import java.io.File abstract class ViewPagerFragment : Fragment() { var listener: FragmentListener? = null private var mTouchDownTime = 0L private var mTouchDownX = 0f private var mTouchDownY = 0f private var mCloseDownThreshold = 100f private var mIgnoreCloseDown = false abstract fun fullscreenToggled(isFullscreen: Boolean) interface FragmentListener { fun fragmentClicked() fun videoEnded(): Boolean fun goToPrevItem() fun goToNextItem() fun launchViewVideoIntent(path: String) fun isSlideShowActive(): Boolean } fun getMediumExtendedDetails(medium: Medium): String { val file = File(medium.path) if (context?.getDoesFilePathExist(file.absolutePath) == false) { return "" } val path = "${file.parent.trimEnd('/')}/" val exif = try { ExifInterface(medium.path) } catch (e: Exception) { return "" } val details = StringBuilder() val detailsFlag = context!!.config.extendedDetails if (detailsFlag and EXT_NAME != 0) { medium.name.let { if (it.isNotEmpty()) details.appendln(it) } } if (detailsFlag and EXT_PATH != 0) { path.let { if (it.isNotEmpty()) details.appendln(it) } } if (detailsFlag and EXT_SIZE != 0) { file.length().formatSize().let { if (it.isNotEmpty()) details.appendln(it) } } if (detailsFlag and EXT_RESOLUTION != 0) { context!!.getResolution(file.absolutePath)?.formatAsResolution().let { if (it?.isNotEmpty() == true) details.appendln(it) } } if (detailsFlag and EXT_LAST_MODIFIED != 0) { getFileLastModified(file).let { if (it.isNotEmpty()) details.appendln(it) } } if (detailsFlag and EXT_DATE_TAKEN != 0) { exif.getExifDateTaken(context!!).let { if (it.isNotEmpty()) details.appendln(it) } } if (detailsFlag and EXT_CAMERA_MODEL != 0) { exif.getExifCameraModel().let { if (it.isNotEmpty()) details.appendln(it) } } if (detailsFlag and EXT_EXIF_PROPERTIES != 0) { exif.getExifProperties().let { if (it.isNotEmpty()) details.appendln(it) } } if (detailsFlag and EXT_GPS != 0) { getLatLonAltitude(medium.path).let { if (it.isNotEmpty()) details.appendln(it) } } return details.toString().trim() } fun getPathToLoad(medium: Medium) = if (context?.isPathOnOTG(medium.path) == true) medium.path.getOTGPublicPath(context!!) else medium.path private fun getFileLastModified(file: File): String { val projection = arrayOf(Images.Media.DATE_MODIFIED) val uri = Files.getContentUri("external") val selection = "${MediaStore.MediaColumns.DATA} = ?" val selectionArgs = arrayOf(file.absolutePath) val cursor = context!!.contentResolver.query(uri, projection, selection, selectionArgs, null) cursor?.use { return if (cursor.moveToFirst()) { val dateModified = cursor.getLongValue(Images.Media.DATE_MODIFIED) * 1000L dateModified.formatDate(context!!) } else { file.lastModified().formatDate(context!!) } } return "" } private fun getLatLonAltitude(path: String): String { var result = "" val exif = try { ExifInterface(path) } catch (e: Exception) { return "" } val latLon = FloatArray(2) if (exif.getLatLong(latLon)) { result = "${latLon[0]}, ${latLon[1]}" } val altitude = exif.getAltitude(0.0) if (altitude != 0.0) { result += ", ${altitude}m" } return result.trimStart(',').trim() } protected fun handleEvent(event: MotionEvent) { when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { mTouchDownTime = System.currentTimeMillis() mTouchDownX = event.x mTouchDownY = event.y } MotionEvent.ACTION_POINTER_DOWN -> mIgnoreCloseDown = true MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { val diffX = mTouchDownX - event.x val diffY = mTouchDownY - event.y val downGestureDuration = System.currentTimeMillis() - mTouchDownTime if (!mIgnoreCloseDown && Math.abs(diffY) > Math.abs(diffX) && diffY < -mCloseDownThreshold && downGestureDuration < MAX_CLOSE_DOWN_GESTURE_DURATION && context?.config?.allowDownGesture == true) { activity?.finish() activity?.overridePendingTransition(0, R.anim.slide_down) } mIgnoreCloseDown = false } } } }
app/src/main/kotlin/com/simplemobiletools/gallery/pro/fragments/ViewPagerFragment.kt
540051917
package com.github.stephanenicolas.heatcontrol.features.setting.ui import android.content.Context import android.support.v7.widget.RecyclerView.ViewHolder import android.widget.Button import com.github.stephanenicolas.heatcontrol.R class AddNewHostViewHolder(context: Context) : ViewHolder(Button(context)) { var button: Button init { button = itemView as Button button.setText(R.string.add_host) } }
app/src/main/java/com/github/stephanenicolas/heatcontrol/features/setting/ui/AddNewHostViewHolder.kt
3250255567
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.legacy.readitlater import android.os.Bundle import android.view.MenuItem import jp.hazuki.yuzubrowser.legacy.R import jp.hazuki.yuzubrowser.ui.app.ThemeActivity class ReadItLaterActivity : ThemeActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.fragment_base) supportActionBar?.setDisplayHomeAsUpEnabled(true) if (savedInstanceState == null) { supportFragmentManager.beginTransaction() .replace(R.id.container, ReadItLaterFragment()) .commit() } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } } return super.onOptionsItemSelected(item) } }
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/readitlater/ReadItLaterActivity.kt
3725661419
package org.evomaster.e2etests.spring.graphql.nullableInput import com.foo.graphql.nullableInput.NullableInputController import org.evomaster.core.EMConfig import org.evomaster.e2etests.spring.graphql.SpringTestBase import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test class GQLNullableInputEMTest : SpringTestBase() { companion object { @BeforeAll @JvmStatic fun init() { initClass(NullableInputController()) } } @Test fun testRunEM() { runTestHandlingFlakyAndCompilation( "GQL_NullableInputEM", "org.foo.graphql.NullableInputEM", 20 ) { args: MutableList<String> -> args.add("--problemType") args.add(EMConfig.ProblemType.GRAPHQL.toString()) val solution = initAndRun(args) Assertions.assertTrue(solution.individuals.size >= 1) assertHasAtLeastOneResponseWithData(solution) assertValueInDataAtLeastOnce(solution, "flowersNullInNullOut") assertValueInDataAtLeastOnce(solution, "flowersNullIn") assertValueInDataAtLeastOnce(solution, "flowersNullOut") assertValueInDataAtLeastOnce(solution, "flowersNotNullInOut") assertValueInDataAtLeastOnce(solution, "flowersScalarNullable") assertValueInDataAtLeastOnce(solution, "flowersScalarNotNullable") assertNoneWithErrors(solution) } } }
e2e-tests/spring-graphql/src/test/kotlin/org/evomaster/e2etests/spring/graphql/nullableInput/GQLNullableInputEMTest.kt
3076197072
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * Author: Loïc Siret <[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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package cx.ring.tv.camera import android.content.Context import android.hardware.Camera import android.view.SurfaceView import android.view.SurfaceHolder import java.lang.Exception class CameraPreview(context: Context, private var mCamera: Camera?) : SurfaceView(context), SurfaceHolder.Callback { fun stop() { mCamera?.let { camera -> try { camera.stopPreview() } catch (e: Exception) { // intentionally left blank } camera.release() mCamera = null } } override fun surfaceCreated(surfaceHolder: SurfaceHolder) { mCamera?.let { camera -> try { camera.setPreviewDisplay(surfaceHolder) camera.startPreview() } catch (e: Exception) { // left blank for now } } } override fun surfaceDestroyed(surfaceHolder: SurfaceHolder) { stop() } override fun surfaceChanged(surfaceHolder: SurfaceHolder, format: Int, width: Int, height: Int) { mCamera?.let { camera -> try { camera.setPreviewDisplay(surfaceHolder) camera.startPreview() } catch (e: Exception) { // intentionally left blank for a test } } } // Constructor that obtains context and camera init { holder.addCallback(this) } }
ring-android/app/src/main/java/cx/ring/tv/camera/CameraPreview.kt
2298191805
package io.github.crabzilla.webpgc import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.datatype.jdk8.Jdk8Module import io.github.crabzilla.framework.DomainEvent import io.github.crabzilla.framework.Entity import io.github.crabzilla.framework.EntityJsonAware import io.github.crabzilla.framework.UnitOfWork import io.github.crabzilla.internal.UnitOfWorkEvents import io.vertx.config.ConfigRetriever import io.vertx.config.ConfigRetrieverOptions import io.vertx.config.ConfigStoreOptions import io.vertx.core.* import io.vertx.core.http.HttpServer import io.vertx.core.json.Json import io.vertx.core.json.JsonObject import io.vertx.core.logging.SLF4JLogDelegateFactory import io.vertx.ext.web.RoutingContext import org.slf4j.LoggerFactory import java.io.IOException import java.net.ServerSocket private val log = LoggerFactory.getLogger("webpgc") fun getConfig(vertx: Vertx, configFile: String) : Future<JsonObject> { // slf4j setup System.setProperty(io.vertx.core.logging.LoggerFactory.LOGGER_DELEGATE_FACTORY_CLASS_NAME, SLF4JLogDelegateFactory::class.java.name) LoggerFactory.getLogger(io.vertx.core.logging.LoggerFactory::class.java) // Jackson setup Json.mapper .registerModule(Jdk8Module()) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // get config val future: Future<JsonObject> = Future.future() configRetriever(vertx, configFile).getConfig { gotConfig -> if (gotConfig.succeeded()) { val config = gotConfig.result() log.info("*** config:\n${config.encodePrettily()}") val readHttpPort = config.getInteger("READ_HTTP_PORT") val nextFreeReadHttpPort = nextFreePort(readHttpPort, readHttpPort + 20) config.put("READ_HTTP_PORT", nextFreeReadHttpPort) log.info("*** next free READ_HTTP_PORT: $nextFreeReadHttpPort") val writeHttpPort = config.getInteger("WRITE_HTTP_PORT") val nextFreeWriteHttpPort = nextFreePort(writeHttpPort, writeHttpPort + 20) config.put("WRITE_HTTP_PORT", nextFreeWriteHttpPort) log.info("*** next free WRITE_HTTP_PORT: $nextFreeWriteHttpPort") future.complete(config) } else { future.fail(gotConfig.cause()) } } return future } private fun configRetriever(vertx: Vertx, configFile: String): ConfigRetriever { val envOptions = ConfigStoreOptions() .setType("file") .setFormat("properties") .setConfig(JsonObject().put("path", configFile)) val options = ConfigRetrieverOptions().addStore(envOptions) return ConfigRetriever.create(vertx, options) } fun deploy(vertx: Vertx, verticle: String, deploymentOptions: DeploymentOptions): Future<String> { val future: Future<String> = Future.future() vertx.deployVerticle(verticle, deploymentOptions, future) return future } fun deploySingleton(vertx: Vertx, verticle: String, dOpt: DeploymentOptions, processId: String): Future<String> { val future: Future<String> = Future.future() vertx.eventBus().send<String>(verticle, processId) { isWorking -> if (isWorking.succeeded()) { log.info("No need to start $verticle: " + isWorking.result().body()) } else { log.info("*** Deploying $verticle") vertx.deployVerticle(verticle, dOpt) { wasDeployed -> if (wasDeployed.succeeded()) { log.info("$verticle started") future.complete("singleton ${wasDeployed.result()}") } else { log.error("$verticle not started", wasDeployed.cause()) future.fail(wasDeployed.cause()) } } } } return future } fun deployHandler(vertx: Vertx): Handler<AsyncResult<CompositeFuture>> { return Handler { deploys -> if (deploys.succeeded()) { val deploymentIds = deploys.result().list<String>() log.info("Verticles were successfully deployed") Runtime.getRuntime().addShutdownHook(object : Thread() { override fun run() { for (id in deploymentIds) { if (id.startsWith("singleton")) { log.info("Keeping singleton deployment $id") } else { log.info("Undeploying $id") vertx.undeploy(id) } } log.info("Closing vertx") vertx.close() } }) } else { log.error("When deploying", deploys.cause()) } } } fun listenHandler(future: Future<Void>): Handler<AsyncResult<HttpServer>> { return Handler { startedFuture -> if (startedFuture.succeeded()) { log.info("Server started on port " + startedFuture.result().actualPort()) future.complete() } else { log.error("oops, something went wrong during server initialization", startedFuture.cause()) future.fail(startedFuture.cause()) } } } private fun nextFreePort(from: Int, to: Int): Int { var port = from while (true) { if (isLocalPortFree(port)) { return port } else { if (port == to) { throw IllegalStateException("Could not find any from available from $from to $to"); } else { port += 1 } } } } private fun isLocalPortFree(port: Int): Boolean { return try { log.info("Trying port $port...") ServerSocket(port).close() true } catch (e: IOException) { false } } fun toUnitOfWorkEvents(json: JsonObject, jsonFunctions: Map<String, EntityJsonAware<out Entity>>): UnitOfWorkEvents? { val uowId = json.getLong("uowId") val entityName = json.getString(UnitOfWork.JsonMetadata.ENTITY_NAME) val entityId = json.getInteger(UnitOfWork.JsonMetadata.ENTITY_ID) val eventsArray = json.getJsonArray(UnitOfWork.JsonMetadata.EVENTS) val jsonAware = jsonFunctions[entityName] if (jsonAware == null) { log.error("JsonAware for $entityName wasn't found") return null } val jsonToEventPair: (Int) -> Pair<String, DomainEvent> = { index -> val jsonObject = eventsArray.getJsonObject(index) val eventName = jsonObject.getString(UnitOfWork.JsonMetadata.EVENT_NAME) val eventJson = jsonObject.getJsonObject(UnitOfWork.JsonMetadata.EVENTS_JSON_CONTENT) val domainEvent = jsonAware.eventFromJson(eventName, eventJson) domainEvent } val events: List<Pair<String, DomainEvent>> = List(eventsArray.size(), jsonToEventPair) return UnitOfWorkEvents(uowId, entityId, events) } fun errorHandler(paramName: String) : Handler<RoutingContext> { return Handler { WebCommandVerticle.log.error(it.failure().message, it.failure()) when (it.failure()) { is NumberFormatException -> it.response().setStatusCode(400).end("path param $paramName must be a number") else -> { it.failure().printStackTrace() it.response().setStatusCode(500).end("server error") } } } }
crabzilla-web-pg-client/src/main/java/io/github/crabzilla/webpgc/webpgc.kt
985248388
package me.proxer.library.api.chat import me.proxer.library.ProxerCall import me.proxer.library.api.Endpoint import me.proxer.library.entity.chat.ChatMessage /** * Endpoint for retrieving messages in a chat room. * * This behaves differently based on the parameter messageId: * 1) messageId = 0: Returns the last messages from the chat room. * 2) messageId != 0: Returns all messages older than that passed from the chat room. * * @author Ruben Gees */ class ChatMessagesEndpoint internal constructor( private val internalApi: InternalApi, private val roomId: String ) : Endpoint<List<ChatMessage>> { private var messageId: String? = null /** * Sets the message id to load from. */ fun messageId(messageId: String?) = this.apply { this.messageId = messageId } override fun build(): ProxerCall<List<ChatMessage>> { return internalApi.messages(roomId, messageId) } }
library/src/main/kotlin/me/proxer/library/api/chat/ChatMessagesEndpoint.kt
2215935691
package asmble.compile.jvm import asmble.annotation.WasmExport import asmble.annotation.WasmExternalKind import asmble.annotation.WasmImport import asmble.annotation.WasmModule import org.objectweb.asm.Handle import org.objectweb.asm.Opcodes import org.objectweb.asm.Type import org.objectweb.asm.tree.* import java.lang.invoke.MethodHandle open class Linker { fun link(ctx: Context) { // Quick check to prevent duplicate names ctx.classes.groupBy { it.name }.values.forEach { require(it.size == 1) { "Duplicate module name: ${it.first().name}"} } // Common items ctx.cls.superName = Object::class.ref.asmName ctx.cls.version = Opcodes.V1_8 ctx.cls.access += Opcodes.ACC_PUBLIC addConstructor(ctx) addDefaultMaxMemField(ctx) // Go over each module and add its creation and instance methods ctx.classes.forEach { addCreationMethod(ctx, it) addInstanceField(ctx, it) addInstanceMethod(ctx, it) } TODO() } fun addConstructor(ctx: Context) { // Just the default empty constructor ctx.cls.methods.plusAssign( Func( access = Opcodes.ACC_PUBLIC, name = "<init>", params = emptyList(), ret = Void::class.ref, insns = listOf( VarInsnNode(Opcodes.ALOAD, 0), MethodInsnNode(Opcodes.INVOKESPECIAL, Object::class.ref.asmName, "<init>", "()V", false), InsnNode(Opcodes.RETURN) ) ).toMethodNode() ) } fun addDefaultMaxMemField(ctx: Context) { (Int.MAX_VALUE / Mem.PAGE_SIZE).let { maxAllowed -> require(ctx.defaultMaxMemPages <= maxAllowed) { "Page size ${ctx.defaultMaxMemPages} over max allowed $maxAllowed" } } ctx.cls.fields.plusAssign(FieldNode( // Make it volatile since it will be publicly mutable Opcodes.ACC_PUBLIC + Opcodes.ACC_VOLATILE, "defaultMaxMem", "I", null, ctx.defaultMaxMemPages * Mem.PAGE_SIZE )) } fun addCreationMethod(ctx: Context, mod: ModuleClass) { // The creation method accepts everything needed for import in order of // imports. For creating a mod w/ self-built memory, we use a default max // mem field on the linkage class if there isn't a default already. val params = mod.importClasses(ctx) var func = Func( access = Opcodes.ACC_PROTECTED, name = "create" + mod.name.javaIdent.capitalize(), params = params.map(ModuleClass::ref), ret = mod.ref ) // The stack here on out is for building params to constructor... // The constructor we'll use is: // * Mem-class based constructor if it's an import // * Max-mem int based constructor if mem is self-built and doesn't have a no-mem-no-max ctr // * Should be only single constructor with imports when there's no mem val memClassCtr = mod.cls.constructors.find { it.parameters.firstOrNull()?.type?.ref == ctx.mem.memType } val constructor = if (memClassCtr == null) mod.cls.constructors.singleOrNull() else { // Use the import annotated one if there if (memClassCtr.parameters.first().isAnnotationPresent(WasmImport::class.java)) memClassCtr else { // If there is a non-int-starting constructor, we want to use that val nonMaxMemCtr = mod.cls.constructors.find { it != memClassCtr && it.parameters.firstOrNull()?.type != Integer.TYPE } if (nonMaxMemCtr != null) nonMaxMemCtr else { // Use the max-mem constructor and put the int on the stack func = func.addInsns( VarInsnNode(Opcodes.ALOAD, 0), FieldInsnNode(Opcodes.GETFIELD, ctx.cls.name, "defaultMaxMem", "I") ) mod.cls.constructors.find { it.parameters.firstOrNull()?.type != Integer.TYPE } } } } if (constructor == null) error("Unable to find suitable constructor for ${mod.cls}") // Now just go over the imports and put them on the stack func = constructor.parameters.fold(func) { func, param -> param.getAnnotation(WasmImport::class.java).let { import -> when (import.kind) { // Invoke the mem handle to get the mem // TODO: for imported memory, fail if import.limit < limits.init * page size at runtime // TODO: for imported memory, fail if import.cap > limits.max * page size at runtime WasmExternalKind.MEMORY -> func.addInsns( VarInsnNode(Opcodes.ALOAD, 1 + params.indexOfFirst { it.name == import.module }), ctx.resolveImportHandle(import).let { memGet -> MethodInsnNode(Opcodes.INVOKEVIRTUAL, memGet.owner, memGet.name, memGet.desc, false) } ) // Bind the method WasmExternalKind.FUNCTION -> func.addInsns( LdcInsnNode(ctx.resolveImportHandle(import)), VarInsnNode(Opcodes.ALOAD, 1 + params.indexOfFirst { it.name == import.module }), MethodHandle::bindTo.invokeVirtual() ) // Bind the getter WasmExternalKind.GLOBAL -> func.addInsns( LdcInsnNode(ctx.resolveImportHandle(import)), VarInsnNode(Opcodes.ALOAD, 1 + params.indexOfFirst { it.name == import.module }), MethodHandle::bindTo.invokeVirtual() ) // Invoke to get handle array // TODO: for imported table, fail if import.size < limits.init * page size at runtime // TODO: for imported table, fail if import.size > limits.max * page size at runtime WasmExternalKind.TABLE -> func.addInsns( VarInsnNode(Opcodes.ALOAD, 1 + params.indexOfFirst { it.name == import.module }), ctx.resolveImportHandle(import).let { tblGet -> MethodInsnNode(Opcodes.INVOKEVIRTUAL, tblGet.owner, tblGet.name, tblGet.desc, false) } ) } } } // Now with all items on the stack we can instantiate and return func = func.addInsns( TypeInsnNode(Opcodes.NEW, mod.ref.asmName), InsnNode(Opcodes.DUP), MethodInsnNode( Opcodes.INVOKESPECIAL, mod.ref.asmName, "<init>", constructor.ref.asmDesc, false ), InsnNode(Opcodes.ARETURN) ) ctx.cls.methods.plusAssign(func.toMethodNode()) } fun addInstanceField(ctx: Context, mod: ModuleClass) { // Simple protected field that is lazily populated (but doesn't need to be volatile) ctx.cls.fields.plusAssign( FieldNode(Opcodes.ACC_PROTECTED, "instance" + mod.name.javaIdent.capitalize(), mod.ref.asmDesc, null, null) ) } fun addInstanceMethod(ctx: Context, mod: ModuleClass) { // The instance method accepts no parameters. It lazily populates a field by calling the // creation method. The parameters for the creation method are the imports that are // accessed via their instance methods. The entire method is synchronized as that is the // most straightforward way to thread-safely lock the lazy population for now. val params = mod.importClasses(ctx) var func = Func( access = Opcodes.ACC_PUBLIC + Opcodes.ACC_SYNCHRONIZED, name = mod.name.javaIdent, ret = mod.ref ) val alreadyThereLabel = LabelNode() func = func.addInsns( VarInsnNode(Opcodes.ALOAD, 0), FieldInsnNode(Opcodes.GETFIELD, ctx.cls.name, "instance" + mod.name.javaIdent.capitalize(), mod.ref.asmDesc), JumpInsnNode(Opcodes.IFNONNULL, alreadyThereLabel), VarInsnNode(Opcodes.ALOAD, 0) ) func = params.fold(func) { func, importMod -> func.addInsns( VarInsnNode(Opcodes.ALOAD, 0), MethodInsnNode(Opcodes.INVOKEVIRTUAL, importMod.ref.asmName, importMod.name.javaIdent, importMod.ref.asMethodRetDesc(), false) ) } func = func.addInsns( FieldInsnNode(Opcodes.PUTFIELD, ctx.cls.name, "instance" + mod.name.javaIdent.capitalize(), mod.ref.asmDesc), alreadyThereLabel, VarInsnNode(Opcodes.ALOAD, 0), FieldInsnNode(Opcodes.GETFIELD, ctx.cls.name, "instance" + mod.name.javaIdent.capitalize(), mod.ref.asmDesc), InsnNode(Opcodes.ARETURN) ) ctx.cls.methods.plusAssign(func.toMethodNode()) } class ModuleClass(val cls: Class<*>, overrideName: String? = null) { val name = overrideName ?: cls.getDeclaredAnnotation(WasmModule::class.java)?.name ?: error("No module name available for class $cls") val ref = TypeRef(Type.getType(cls)) fun importClasses(ctx: Context): List<ModuleClass> { // Try to find constructor with mem class first, otherwise there should be only one val constructorWithImports = cls.constructors.find { it.parameters.firstOrNull()?.type?.ref == ctx.mem.memType } ?: cls.constructors.singleOrNull() ?: error("Unable to find suitable constructor for $cls") return constructorWithImports.parameters.toList().mapNotNull { it.getAnnotation(WasmImport::class.java)?.module }.distinct().map(ctx::namedModuleClass) } } data class Context( val classes: List<ModuleClass>, val className: String, val cls: ClassNode = ClassNode().also { it.name = className.replace('.', '/') }, val mem: Mem = ByteBufferMem, val defaultMaxMemPages: Int = 10 ) { fun namedModuleClass(name: String) = classes.find { it.name == name } ?: error("No module named '$name'") fun resolveImportMethod(import: WasmImport) = namedModuleClass(import.module).cls.methods.find { method -> method.getAnnotation(WasmExport::class.java)?.value == import.field && method.ref.asmDesc == import.desc } ?: error("Unable to find export named '${import.field}' in module '${import.module}'") fun resolveImportHandle(import: WasmImport) = resolveImportMethod(import).let { method -> Handle(Opcodes.INVOKEVIRTUAL, method.declaringClass.ref.asmName, method.name, method.ref.asmDesc, false) } } companion object : Linker() }
compiler/src/main/kotlin/asmble/compile/jvm/Linker.kt
3352968830
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl import org.gradle.api.Action import org.gradle.vcs.VcsMapping import org.gradle.vcs.git.GitVersionControlSpec import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doNothing import com.nhaarman.mockito_kotlin.inOrder import com.nhaarman.mockito_kotlin.mock import org.junit.Test class SourceControlExtensionsTest { @Test fun `vcs mapping from`() { val vcsMapping = mock<VcsMapping>() doNothing().`when`(vcsMapping).from(any<Class<GitVersionControlSpec>>(), any<Action<GitVersionControlSpec>>()) vcsMapping.from<GitVersionControlSpec> { } inOrder(vcsMapping) { verify(vcsMapping).from(any<Class<GitVersionControlSpec>>(), any<Action<GitVersionControlSpec>>()) verifyNoMoreInteractions() } } }
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/SourceControlExtensionsTest.kt
2257313943
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ @file:Suppress("UNUSED", "PublicApiImplicitType") package jp.nephy.penicillin.endpoints.lists import jp.nephy.penicillin.core.request.action.CursorJsonObjectApiAction import jp.nephy.penicillin.core.request.parameters import jp.nephy.penicillin.core.session.get import jp.nephy.penicillin.endpoints.Lists import jp.nephy.penicillin.endpoints.Option import jp.nephy.penicillin.models.cursor.CursorLists /** * Returns the lists the specified user has been added to. If user_id or screen_name are not provided, the memberships for the authenticating user are returned. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-memberships) * * @param count The amount of results to return per page. Defaults to 20. No more than 1000 results will ever be returned in a single page. * @param cursor Breaks the results into pages. Provide a value of -1 to begin paging. Provide values as returned in the response body's next_cursor and previous_cursor attributes to page back and forth in the list. It is recommended to always use cursors when the method supports them. See [Cursoring](https://developer.twitter.com/en/docs/basics/cursoring) for more information. * @param filterToOwnedLists When set to true , t or 1 , will return just lists the authenticating user owns, and the user represented by user_id or screen_name is a member of. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [CursorJsonObjectApiAction] for [CursorLists] model. */ fun Lists.memberships( count: Int? = null, cursor: Long? = null, filterToOwnedLists: Boolean? = null, vararg options: Option ) = membershipsInternal(null, null, count, cursor, filterToOwnedLists, *options) /** * Returns the lists the specified user has been added to. If user_id or screen_name are not provided, the memberships for the authenticating user are returned. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-memberships) * * @param userId The ID of the user for whom to return results. Helpful for disambiguating when a valid user ID is also a valid screen name. * @param count The amount of results to return per page. Defaults to 20. No more than 1000 results will ever be returned in a single page. * @param cursor Breaks the results into pages. Provide a value of -1 to begin paging. Provide values as returned in the response body's next_cursor and previous_cursor attributes to page back and forth in the list. It is recommended to always use cursors when the method supports them. See [Cursoring](https://developer.twitter.com/en/docs/basics/cursoring) for more information. * @param filterToOwnedLists When set to true , t or 1 , will return just lists the authenticating user owns, and the user represented by user_id or screen_name is a member of. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [CursorJsonObjectApiAction] for [CursorLists] model. */ fun Lists.membershipsByUserId( userId: Long, count: Int? = null, cursor: Long? = null, filterToOwnedLists: Boolean? = null, vararg options: Option ) = membershipsInternal(userId, null, count, cursor, filterToOwnedLists, *options) /** * Returns the lists the specified user has been added to. If user_id or screen_name are not provided, the memberships for the authenticating user are returned. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-memberships) * * @param screenName The screen name of the user for whom to return results. Helpful for disambiguating when a valid screen name is also a user ID. * @param count The amount of results to return per page. Defaults to 20. No more than 1000 results will ever be returned in a single page. * @param cursor Breaks the results into pages. Provide a value of -1 to begin paging. Provide values as returned in the response body's next_cursor and previous_cursor attributes to page back and forth in the list. It is recommended to always use cursors when the method supports them. See [Cursoring](https://developer.twitter.com/en/docs/basics/cursoring) for more information. * @param filterToOwnedLists When set to true , t or 1 , will return just lists the authenticating user owns, and the user represented by user_id or screen_name is a member of. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [CursorJsonObjectApiAction] for [CursorLists] model. */ fun Lists.membershipsByScreenName( screenName: String, count: Int? = null, cursor: Long? = null, filterToOwnedLists: Boolean? = null, vararg options: Option ) = membershipsInternal(null, screenName, count, cursor, filterToOwnedLists, *options) private fun Lists.membershipsInternal( userId: Long? = null, screenName: String? = null, count: Int? = null, cursor: Long? = null, filterToOwnedLists: Boolean? = null, vararg options: Option ) = client.session.get("/1.1/lists/memberships.json") { parameters( "user_id" to userId, "screen_name" to screenName, "count" to count, "cursor" to cursor, "filter_to_owned_lists" to filterToOwnedLists, *options ) }.cursorJsonObject<CursorLists>() /** * Shorthand property to [Lists.memberships]. * @see Lists.memberships */ val Lists.memberships get() = memberships()
src/main/kotlin/jp/nephy/penicillin/endpoints/lists/Memberships.kt
3809395232
package guideme.volunteers.helpers.dataservices.errors class UserNotSignedInException : Exception()
data_structure/src/main/java/guideme/volunteers/helpers/dataservices/errors/UserNotSignedInException.kt
1598893833
/* * Copyright 2019 Andrey Mukamolov * 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.bookcrossing.mobile.ui.map import com.bookcrossing.mobile.models.Coordinates import moxy.MvpView import moxy.viewstate.strategy.AddToEndSingleStrategy import moxy.viewstate.strategy.StateStrategyType /** * View for map screen */ @StateStrategyType(AddToEndSingleStrategy::class) interface MvpMapView : MvpView { /** * Book position was loaded, so we can show it on the map as a marker */ fun onBookMarkerLoaded(key: String, coordinates: Coordinates) /** * Error happened during loading book position */ fun onErrorToLoadMarker() }
app/src/main/java/com/bookcrossing/mobile/ui/map/MvpMapView.kt
1872056471
package com.battlelancer.seriesguide.shows.tools import android.content.Context import android.widget.TextView import androidx.core.content.ContextCompat import com.battlelancer.seriesguide.R import com.battlelancer.seriesguide.util.Utils /** * Show status valued as stored in the database in [com.battlelancer.seriesguide.provider.SeriesGuideContract.Shows.STATUS]. */ // Compare with https://www.themoviedb.org/bible/tv#59f7403f9251416e7100002b // Note: used to order shows by status, so ensure similar are next to each other. interface ShowStatus { companion object { const val IN_PRODUCTION = 5 const val PILOT = 4 const val PLANNED = 2 /** * Episodes are to be released. */ const val RETURNING = 1 /** * Typically all episodes released, with a planned ending. */ const val ENDED = 0 const val UNKNOWN = -1 /** * Typically all episodes released, but abruptly ended. */ const val CANCELED = -2 /** * Decodes the [ShowTools.Status] and returns the localized text representation. * May be `null` if status is unknown. */ fun getStatus(context: Context, encodedStatus: Int): String? { return when (encodedStatus) { IN_PRODUCTION -> context.getString(R.string.show_status_in_production) PILOT -> context.getString(R.string.show_status_pilot) CANCELED -> context.getString(R.string.show_status_canceled) PLANNED -> context.getString(R.string.show_isUpcoming) RETURNING -> context.getString(R.string.show_isalive) ENDED -> context.getString(R.string.show_isnotalive) else -> { // status unknown, display nothing null } } } /** * Gets the show status from [getStatus] and sets a status dependant text color on the * given view. * * @param encodedStatus Detection based on [ShowStatus]. */ fun setStatusAndColor(view: TextView, encodedStatus: Int) { view.text = getStatus(view.context, encodedStatus) if (encodedStatus == RETURNING) { view.setTextColor( ContextCompat.getColor( view.context, Utils.resolveAttributeToResourceId( view.context.theme, R.attr.colorSecondary ) ) ) } else { view.setTextColor( ContextCompat.getColor( view.context, Utils.resolveAttributeToResourceId( view.context.theme, android.R.attr.textColorSecondary ) ) ) } } } }
app/src/main/java/com/battlelancer/seriesguide/shows/tools/ShowStatus.kt
3611461554
package com.github.satahippy.mailru data class MailruResponse<T>( var email: String, var time: Long, var status: Int, var body: T ) data class InternalLoginRequest( var Login: String, var Password: String, var act_token: String, var page: String, var Domain: String, var FromAccount: String, var new_auth_form: Int, var saveauth: Int, var lang: String ) : FormUrlEncodedRequest data class Sort( var type: String, var order: String ) enum class FileType { file, folder } data class FolderOrFile( var count: FolderCount?, var name: String, var home: String, var size: Long?, var kind: FileType, var type: FileType, var tree: String?, var mtime: Int?, var rev: Int?, var grev: Int?, var virus_scan: String?, var hash: String?, var list: List<FolderOrFile>? ) data class FolderCount( var folders: Int, var files: Int )
src/main/kotlin/com/github/satahippy/mailru/Dto.kt
3608094129
package com.alekseyzhelo.lbm.gui.lwjgl.color.colormap import com.alekseyzhelo.lbm.gui.lwjgl.color.FloatColor import com.alekseyzhelo.lbm.gui.lwjgl.util.ResourcesUtil /** * @author Aleks on 03-07-2016. */ object CoolwarmDiscreteColormap : Colormap { private val r: FloatArray private val g: FloatArray private val b: FloatArray private val range: Int init { val fileEntries = ResourcesUtil.loadCSVResource("/colormaps/CoolWarmFloat257.csv") val skippedFirst = fileEntries.subList(1, fileEntries.size) range = skippedFirst.size - 1 r = FloatArray(range + 1) g = FloatArray(range + 1) b = FloatArray(range + 1) for (i in 0..range) { r[i] = skippedFirst[i][1].toFloat() g[i] = skippedFirst[i][2].toFloat() b[i] = skippedFirst[i][3].toFloat() } } override fun getColor(normalized: Float): FloatColor { val index = (normalized * range).toInt() return FloatColor(r[index], g[index], b[index]) } override fun getName(): String { return "coolwarm" } }
LWJGL_APP/src/main/java/com/alekseyzhelo/lbm/gui/lwjgl/color/colormap/DiscreteColormaps.kt
2618926809
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.composemail.ui.mails import androidx.compose.runtime.mutableStateOf class MailItemState(val id: Int, private val onSelected: (id: Int, isSelected: Boolean) -> Unit) { private val _isSelected = mutableStateOf(false) val isSelected get() = _isSelected.value fun setSelected(isSelected: Boolean) { onSelected(id, isSelected) _isSelected.value = isSelected } }
demoProjects/ComposeMail/app/src/main/java/com/example/composemail/ui/mails/MailItemState.kt
444263023
package tw.shounenwind.kmnbottool.skeleton import android.annotation.SuppressLint import android.app.ActivityOptions import android.content.Intent import android.os.Build import android.util.Pair import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import com.google.android.material.appbar.AppBarLayout import kotlinx.coroutines.* import tw.shounenwind.kmnbottool.R import tw.shounenwind.kmnbottool.util.LogUtil import tw.shounenwind.kmnbottool.widget.ProgressDialog @SuppressLint("Registered") open class BaseActivity : AppCompatActivity() { private var progressDialog: ProgressDialog? = null protected var mainScope: CoroutineScope? = MainScope() override fun setContentView(layoutResID: Int) { super.setContentView(layoutResID) bindToolbar() } override fun setContentView(view: View?) { super.setContentView(view) bindToolbar() } override fun setContentView(view: View?, params: ViewGroup.LayoutParams?) { super.setContentView(view, params) bindToolbar() } private fun bindToolbar(){ findViewById<Toolbar>(R.id.toolbar)?.apply { setSupportActionBar(this) } } fun bindToolbarHomeButton(){ supportActionBar?.apply { setHomeButtonEnabled(true) setDisplayHomeAsUpEnabled(true) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { onBackPressed() true } else -> { super.onOptionsItemSelected(item) } } } fun startActivityWithTransition(intent: Intent) { val appBarLayout = findViewById<AppBarLayout>(R.id.appbar) if (appBarLayout != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT != Build.VERSION_CODES.N && Build.VERSION.SDK_INT != Build.VERSION_CODES.N_MR1) { val options = ActivityOptions.makeSceneTransitionAnimation( this, appBarLayout, appBarLayout.transitionName ) startActivity(intent, options.toBundle()) } else { startActivity(intent) } } fun startActivityWithTransition(intent: Intent, vararg pairs: Pair<View, String>) { val appBarLayout = findViewById<AppBarLayout>(R.id.appbar) if (appBarLayout != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT != Build.VERSION_CODES.N && Build.VERSION.SDK_INT != Build.VERSION_CODES.N_MR1) { val options = ActivityOptions.makeSceneTransitionAnimation( this, Pair.create(appBarLayout, appBarLayout.transitionName), *pairs ) startActivity(intent, options.toBundle()) } else { startActivity(intent) } } fun startActivityForResultWithTransition(intent: Intent, responseCode: Int) { val appBarLayout = findViewById<AppBarLayout>(R.id.appbar) if (appBarLayout != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT != Build.VERSION_CODES.N && Build.VERSION.SDK_INT != Build.VERSION_CODES.N_MR1) { val options = ActivityOptions.makeSceneTransitionAnimation( this, appBarLayout, appBarLayout.transitionName ) startActivityForResult(intent, responseCode, options.toBundle()) } else { startActivityForResult(intent, responseCode) } } protected suspend fun showProgressDialog(text: String) = withContext(Dispatchers.Main) { progressDialog = ProgressDialog(this@BaseActivity).apply { setContent(text) setCancelable(false) show() } } protected suspend fun dismissProgressDialog() = withContext(Dispatchers.Main) { LogUtil.catchAndPrint { progressDialog!!.dismiss() } } override fun onDestroy() { mainScope?.cancel() mainScope = null super.onDestroy() } }
app/src/main/java/tw/shounenwind/kmnbottool/skeleton/BaseActivity.kt
3286823641
package com.razielsarafan.wtnv.controller.fragment import android.os.Bundle import android.support.v4.app.Fragment import android.text.Html import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.razielsarafan.wtnv.R import com.razielsarafan.wtnv.api.WTNVApi import com.razielsarafan.wtnv.model.Transcript import retrofit.Callback import retrofit.RetrofitError import retrofit.client.Response class TranscriptFragment : Fragment(), Callback<Transcript> { private var textViewTranscript: TextView? = null private var transcript: String? = null private var transcriptId: String = "" override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val v = inflater!!.inflate(R.layout.fragment_transcript, container, false) textViewTranscript = v.findViewById(R.id.textViewTranscript) as TextView textViewTranscript?.movementMethod = LinkMovementMethod.getInstance() WTNVApi.getInstance(activity).getTranscriptForInterface(transcriptId, this) bind() return v } override fun success(s: Transcript, response: Response?) { transcript = "<br>${s.value}<br>${cecilspeaks}<br>".replace("\n", "<br>") bind() } private fun bind() { if (transcript != null && textViewTranscript != null) { textViewTranscript?.text = Html.fromHtml(transcript) } } override fun failure(error: RetrofitError) { error.printStackTrace() } companion object { private val cecilspeaks = "These transcripts have been kindly made by <a href=\"http://cecilspeaks.tumblr.com\">tumblr user cecilspeaks</a>. It would probably be cool if you followed them or sent them some thank you notes, as they gave me permission to use them free of charge." fun getInstance(transcriptId: String): TranscriptFragment { val fragment = TranscriptFragment() fragment.transcriptId = transcriptId return fragment } } }
app/src/main/java/com/razielsarafan/wtnv/controller/fragment/TranscriptFragment.kt
2858183608
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.rolling.bukkit.command.turnorder import com.rpkit.core.command.RPKCommandExecutor import com.rpkit.core.command.result.* import com.rpkit.core.command.sender.RPKCommandSender import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile import com.rpkit.rolling.bukkit.RPKRollingBukkit import com.rpkit.rolling.bukkit.command.result.InvalidTurnOrderFailure import com.rpkit.rolling.bukkit.turnorder.RPKTurnOrderService import java.util.concurrent.CompletableFuture class TurnOrderRemoveCommand(private val plugin: RPKRollingBukkit) : RPKCommandExecutor { override fun onCommand(sender: RPKCommandSender, args: Array<out String>): CompletableFuture<out CommandResult> { if (!sender.hasPermission("rpkit.rolling.command.turnorder.remove")) { sender.sendMessage(plugin.messages.noPermissionTurnOrderRemove) return CompletableFuture.completedFuture(NoPermissionFailure("rpkit.rolling.command.turnorder.remove")) } if (args.isEmpty()) { sender.sendMessage(plugin.messages.turnOrderRemoveUsage) return CompletableFuture.completedFuture(IncorrectUsageFailure()) } val turnOrderService = Services[RPKTurnOrderService::class.java] if (turnOrderService == null) { sender.sendMessage(plugin.messages.noTurnOrderService) return CompletableFuture.completedFuture(MissingServiceFailure(RPKTurnOrderService::class.java)) } var argOffset = 0 var turnOrder = if (args.size > 1) { turnOrderService.getTurnOrder(args[0]) } else null if (turnOrder == null && sender is RPKMinecraftProfile) { turnOrder = turnOrderService.getActiveTurnOrder(sender) } else { argOffset = 1 } if (turnOrder == null) { sender.sendMessage(plugin.messages.turnOrderRemoveInvalidTurnOrder) return CompletableFuture.completedFuture(InvalidTurnOrderFailure()) } args.drop(argOffset).forEach(turnOrder::remove) sender.sendMessage(plugin.messages.turnOrderRemoveValid) return CompletableFuture.completedFuture(CommandSuccess) } }
bukkit/rpk-rolling-bukkit/src/main/kotlin/com/rpkit/rolling/bukkit/command/turnorder/TurnOrderRemoveCommand.kt
3658820708
package lunchbox.domain.resolvers import lunchbox.domain.models.LunchOffer import lunchbox.domain.models.LunchProvider.AOK_CAFETERIA import lunchbox.util.date.DateValidator import lunchbox.util.html.HtmlParser import lunchbox.util.string.StringParser import org.jsoup.nodes.Element import org.springframework.stereotype.Component import java.net.URL import java.time.DayOfWeek import java.time.LocalDate import java.time.Month @Component class LunchResolverAokCafeteria( val dateValidator: DateValidator, val htmlParser: HtmlParser ) : LunchResolver { override val provider = AOK_CAFETERIA override fun resolve(): List<LunchOffer> = resolve(URL("${provider.menuUrl}/speiseplan/16/ajax/")) fun resolve(htmlUrl: URL): List<LunchOffer> { val site = htmlParser.parse(htmlUrl) val weekDates = site.select(".child") .mapNotNull { StringParser.parseLocalDate(it.text()) } .map { it.with(DayOfWeek.MONDAY) } val weekDivs = site.select("div[class*=child_menu]") val offers = mutableListOf<LunchOffer>() for ((date, weekDiv) in weekDates.zip(weekDivs)) offers += resolveByWeek(date, weekDiv) return offers } private fun resolveByWeek(date: LocalDate, weekDiv: Element): List<LunchOffer> { val day2node = weekDiv.children().chunked(2).filter { it.size > 1 } val offers = mutableListOf<LunchOffer>() for ((dayElem, offersDiv) in day2node) { val day = calcDay(dayElem, date) ?: return emptyList() offers += resolveByDay(day, offersDiv) } return offers } private fun calcDay(dateElem: Element, date: LocalDate): LocalDate? { val weekdayString = dateElem.select(".day").text() val weekday = Weekday.values().find { weekdayString.startsWith(it.label) } if (weekday != null) return date.plusDays(weekday.order) val shortDate = dateElem.select(".short-date").text() val year = if (shortDate.trim().endsWith("01.") && date.month == Month.DECEMBER) date.year + 1 else date.year return StringParser.parseLocalDate("$shortDate$year") } private fun resolveByDay(day: LocalDate, offersDiv: Element): List<LunchOffer> { val offerDivs = offersDiv.select(".day-usual") val offers = mutableListOf<LunchOffer>() for (offerElem in offerDivs) { val typ = offerElem.selectFirst("span")?.text() ?: "" val name = offerElem.select("span:nth-of-type(2)").text() if (!typ.contains("Tagesgericht") && !typ.contains("Menü")) continue if (name.isEmpty() || listOf("Ferien", "Betriebsferien", "Weihnachten", "Ostern", "Ostermontag", "Pfingstmontag").contains(name) ) continue val zusatzstoffe = offerElem.select("small").text() var (title, description) = StringParser.splitOfferName( name, listOf(" auf ", " mit ", " von ", " im ", " in ", " an ", ", ", " (", " und ") ) description = clearDescription(description) val tags = parseTags(name, typ, zusatzstoffe) offers += LunchOffer(0, title, description, day, null, tags, provider.id) } return offers } private fun clearDescription(description: String): String = description .replace(Regex("^, "), "") .replace("(", "") .replace(")", ",") .replace(Regex(",([^ ])"), ", $1") .replace(", , ", ", ") .trim() private fun parseTags(name: String, typ: String, zusatzstoffe: String): Set<String> { val result = mutableSetOf<String>() if (name.contains("vegan", ignoreCase = true)) result += "vegan" else if (name.contains("vegetarisch", ignoreCase = true) || zusatzstoffe.contains("V")) result += "vegetarisch" if (typ.contains("vorbestellen", ignoreCase = true)) result += "auf Vorbestellung" return result } enum class Weekday( val label: String, val order: Long ) { MONTAG("Mo", 0), DIENSTAG("Di", 1), MITTWOCH("Mi", 2), DONNERSTAG("Do", 3), FREITAG("Fr", 4); } }
backend-spring-kotlin/src/main/kotlin/lunchbox/domain/resolvers/LunchResolverAokCafeteria.kt
1464707969
/* Tickle Copyright (C) 2017 Nick Robinson 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 uk.co.nickthecoder.tickle.action.movement import org.joml.Vector2d import uk.co.nickthecoder.tickle.action.Action import uk.co.nickthecoder.tickle.stage.StageView class FollowMouse( val position: Vector2d, val view: StageView) : Action { private val mouse = Vector2d() override fun act(): Boolean { view.mousePosition(mouse) position.set(mouse) return false } }
tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/action/movement/FollowMouse.kt
2259070788
// automatically generated by the FlatBuffers compiler, do not modify import java.nio.* import kotlin.math.sign import com.google.flatbuffers.* @Suppress("unused") @ExperimentalUnsignedTypes class Movie : Table() { fun __init(_i: Int, _bb: ByteBuffer) { __reset(_i, _bb) } fun __assign(_i: Int, _bb: ByteBuffer) : Movie { __init(_i, _bb) return this } val mainCharacterType : UByte get() { val o = __offset(4) return if(o != 0) bb.get(o + bb_pos).toUByte() else 0u } fun mutateMainCharacterType(mainCharacterType: UByte) : Boolean { val o = __offset(4) return if (o != 0) { bb.put(o + bb_pos, mainCharacterType.toByte()) true } else { false } } fun mainCharacter(obj: Table) : Table? { val o = __offset(6); return if (o != 0) __union(obj, o + bb_pos) else null } fun charactersType(j: Int) : UByte { val o = __offset(8) return if (o != 0) { bb.get(__vector(o) + j * 1).toUByte() } else { 0u } } val charactersTypeLength : Int get() { val o = __offset(8); return if (o != 0) __vector_len(o) else 0 } val charactersTypeAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(8, 1) fun charactersTypeInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 8, 1) fun mutateCharactersType(j: Int, charactersType: UByte) : Boolean { val o = __offset(8) return if (o != 0) { bb.put(__vector(o) + j * 1, charactersType.toByte()) true } else { false } } fun characters(obj: Table, j: Int) : Table? { val o = __offset(10) return if (o != 0) { __union(obj, __vector(o) + j * 4) } else { null } } val charactersLength : Int get() { val o = __offset(10); return if (o != 0) __vector_len(o) else 0 } companion object { fun validateVersion() = Constants.FLATBUFFERS_2_0_0() fun getRootAsMovie(_bb: ByteBuffer): Movie = getRootAsMovie(_bb, Movie()) fun getRootAsMovie(_bb: ByteBuffer, obj: Movie): Movie { _bb.order(ByteOrder.LITTLE_ENDIAN) return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) } fun MovieBufferHasIdentifier(_bb: ByteBuffer) : Boolean = __has_identifier(_bb, "MOVI") fun createMovie(builder: FlatBufferBuilder, mainCharacterType: UByte, mainCharacterOffset: Int, charactersTypeOffset: Int, charactersOffset: Int) : Int { builder.startTable(4) addCharacters(builder, charactersOffset) addCharactersType(builder, charactersTypeOffset) addMainCharacter(builder, mainCharacterOffset) addMainCharacterType(builder, mainCharacterType) return endMovie(builder) } fun startMovie(builder: FlatBufferBuilder) = builder.startTable(4) fun addMainCharacterType(builder: FlatBufferBuilder, mainCharacterType: UByte) = builder.addByte(0, mainCharacterType.toByte(), 0) fun addMainCharacter(builder: FlatBufferBuilder, mainCharacter: Int) = builder.addOffset(1, mainCharacter, 0) fun addCharactersType(builder: FlatBufferBuilder, charactersType: Int) = builder.addOffset(2, charactersType, 0) fun createCharactersTypeVector(builder: FlatBufferBuilder, data: UByteArray) : Int { builder.startVector(1, data.size, 1) for (i in data.size - 1 downTo 0) { builder.addByte(data[i].toByte()) } return builder.endVector() } fun startCharactersTypeVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(1, numElems, 1) fun addCharacters(builder: FlatBufferBuilder, characters: Int) = builder.addOffset(3, characters, 0) fun createCharactersVector(builder: FlatBufferBuilder, data: IntArray) : Int { builder.startVector(4, data.size, 4) for (i in data.size - 1 downTo 0) { builder.addOffset(data[i]) } return builder.endVector() } fun startCharactersVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(4, numElems, 4) fun endMovie(builder: FlatBufferBuilder) : Int { val o = builder.endTable() return o } fun finishMovieBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finish(offset, "MOVI") fun finishSizePrefixedMovieBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finishSizePrefixed(offset, "MOVI") } }
tests/union_vector/Movie.kt
2038177518
package com.github.shchurov.gitterclient.domain.models class Token(val accessToken: String)
app/src/main/kotlin/com/github/shchurov/gitterclient/domain/models/Token.kt
1890215602
package com.dropbox.core.examples.account_info import com.dropbox.core.examples.CredentialsUtil import com.dropbox.core.examples.TestUtil import org.junit.Assume.assumeTrue import org.junit.Before import org.junit.Test /** * An example command-line application that grab access token and refresh token from credential * file, and then call APIV2. If the access token has expired, SDK will automatically refresh and * get a new one, and store them into the original DbxCredential object. */ class AccountInfoExampleTest { @Before fun setup() { assumeTrue(TestUtil.isRunningInCI()) } @Test fun accountInfo() { AccountInfoExample.runExample(CredentialsUtil.getDbxCredential()) } }
examples/examples/src/test/java/com/dropbox/core/examples/account_info/AccountInfoExampleTest.kt
4027300414
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.multiwindowplayground.logger /** * Simple [LogNode] filter, removes everything except the message. * Useful for situations like on-screen log output where you don't want a lot of metadata * displayed, just easy-to-read message updates as they're happening. */ class MessageOnlyLogFilter : LogNode { var next: LogNode? = null override fun println(priority: Int, tag: String?, msg: String, tr: Throwable?) { next?.println(Log.NONE, null, msg, null) } }
kotlinApp/Application/src/main/java/com/android/multiwindowplayground/logger/MessageOnlyLogFilter.kt
3839518147
package org.rust.ide.inspections class RustExtraSemicolonInspectionTest : RustInspectionsTestBase() { fun testNotApplicableWithoutReturnType() = checkByText<RustExtraSemicolonInspection>(""" fn foo() { 92; } """) fun testNotApplicableForLet() = checkByText<RustExtraSemicolonInspection>(""" fn foo() -> i32 { let x = 92; } """) fun testNotApplicableWithExplicitReturn() = checkByText<RustExtraSemicolonInspection>(""" fn foo() -> i32 { return 92; } """) fun testNotApplicableWithExplicitUnitType() = checkByText<RustExtraSemicolonInspection>(""" fn fun() -> () { 2 + 2; } """) fun testNotApplicableWithMacro() = checkByText<RustExtraSemicolonInspection>(""" fn fun() -> i32 { panic!("diverge"); } """) fun testFix() = checkFixByText<RustExtraSemicolonInspection>("Remove semicolon", """ fn foo() -> i32 { let x = 92; <warning descr="Function returns () instead of i32">x;<caret></warning> } """, """ fn foo() -> i32 { let x = 92; x } """) }
src/test/kotlin/org/rust/ide/inspections/RustExtraSemicolonInspectionTest.kt
4171646514
package tutorial.functional fun foo(bar: Int = 0, baz: Int) { /*……*/ } fun foo(bar: Int = 0, baz: Int = 1, qux: () -> Unit) { /*……*/ } fun foo(vararg strings: String) { /*……*/ } fun double(x: Int) = x * 2 fun <T> asList(vararg ts: T): List<T> { val result = ArrayList<T>() for (t in ts) // ts is an Array result.add(t) return result } infix fun Int.shl(x: Int): Int { //…… return 1 } class MyStringCollection { infix fun add(s: String) { /*……*/ } fun build() { this add "abc" // 正确 add("abc") // 正确 //add "abc" // 错误:必须指定接收者 } } //fun dfs(graph: Graph) { // val visited = HashSet<Vertex>() // fun dfs(current: Vertex) { // if (!visited.add(current)) return // for (v in current.neighbors) // dfs(v) // } // // dfs(graph.vertices[0]) //} val eps = 1E-10 // "good enough", could be 10^-15 private fun findFixPointIteration(): Double { var x = 1.0 while (true) { val y = Math.cos(x) if (Math.abs(x - y) < eps) return x x = Math.cos(x) } } tailrec fun findFixPointTailRec(x: Double = 1.0): Double = if (Math.abs(x - Math.cos(x)) < eps) x else findFixPointTailRec(Math.cos(x)) fun main() { foo(baz = 1) // 使用默认值 bar = 0 foo(1) { println("hello") } // 使用默认值 baz = 1 foo(qux = { println("hello") }) // 使用两个默认值 bar = 0 与 baz = 1 foo { println("hello") } // 使用两个默认值 bar = 0 与 baz = 1 foo(strings = *arrayOf("a", "b", "c")) // 用中缀表示法调用该函数 1 shl 2 // 等同于这样 1.shl(2) println("normal iteration: " + findFixPointIteration()) println("tail recursion: " + findFixPointTailRec()) }
src/kotlin/src/tutorial/functional/Functions.kt
1395030396
package net.perfectdreams.loritta.cinnamon.pudding.utils import net.perfectdreams.loritta.cinnamon.pudding.Pudding import java.util.concurrent.Executors import java.util.concurrent.TimeUnit class PuddingTasks(private val pudding: Pudding) { private val executorService = Executors.newScheduledThreadPool(1) fun start() { executorService.scheduleWithFixedDelay( PartitionCreator(pudding), 0L, 1L, TimeUnit.DAYS ) executorService.scheduleWithFixedDelay( AutoExpireInteractionsData(pudding), 0L, 1L, TimeUnit.MINUTES ) } fun shutdown() { executorService.shutdown() } }
pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/utils/PuddingTasks.kt
119807296
package net.perfectdreams.loritta.morenitta.commands.vanilla.images import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.gifs.GifSequenceWriter import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.morenitta.utils.MiscUtils import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.perfectdreams.loritta.morenitta.api.commands.Command import net.perfectdreams.loritta.morenitta.utils.extensions.readImage import java.awt.Color import java.awt.image.BufferedImage import java.io.File import javax.imageio.stream.FileImageOutputStream class TriggeredCommand(loritta: LorittaBot) : AbstractCommand(loritta, "triggered", category = net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) { override fun getDescriptionKey() = LocaleKeyData("commands.command.triggered.description") override fun getExamplesKey() = Command.SINGLE_IMAGE_EXAMPLES_KEY // TODO: Fix Usage override fun needsToUploadFiles(): Boolean { return true } override suspend fun run(context: CommandContext,locale: BaseLocale) { val contextImage = context.getImageAt(0) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; } val input = contextImage val triggeredLabel = readImage(File(LorittaBot.ASSETS, "triggered.png")) // scale val subtractW = input.width / 16 val subtractH = input.height / 16 val inputWidth = input.width - subtractW val inputHeight = input.height - subtractH // ogWidth --- input.width // ogHeight --- x val a1 = triggeredLabel.height * inputWidth val labelHeight = a1 / triggeredLabel.width val scaledTriggeredLabel = triggeredLabel.getScaledInstance(inputWidth, labelHeight, BufferedImage.SCALE_SMOOTH) val base = BufferedImage(inputWidth, inputHeight + scaledTriggeredLabel.getHeight(null), BufferedImage.TYPE_INT_ARGB) val tint = BufferedImage(base.width, inputHeight, BufferedImage.TYPE_INT_ARGB) val color = Color(255, 0, 0, 60) val graphics = base.graphics val tintGraphics = tint.graphics tintGraphics.color = color tintGraphics.fillRect(0, 0, tint.width, tint.height) var fileName = LorittaBot.TEMP + "triggered-" + System.currentTimeMillis() + ".gif" val outputFile = File(fileName) var output = FileImageOutputStream(outputFile) val writer = GifSequenceWriter(output, BufferedImage.TYPE_INT_ARGB, 4, true) for (i in 0..5) { var offsetX = LorittaBot.RANDOM.nextInt(0, subtractW) var offsetY = LorittaBot.RANDOM.nextInt(0, subtractH) val subimage = input.getSubimage(offsetX, offsetY, inputWidth, inputHeight) graphics.drawImage(subimage, 0, 0, null) graphics.drawImage(tint, 0, 0, null) graphics.drawImage(scaledTriggeredLabel, 0, inputHeight, null) writer.writeToSequence(base) } writer.close() output.close() loritta.gifsicle.optimizeGIF(outputFile) context.sendFile(outputFile, "triggered.gif", context.getAsMention(true)) outputFile.delete() } }
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/TriggeredCommand.kt
2536545268
package net.perfectdreams.loritta.morenitta.utils.counter object CounterUtils { fun generatePrettyCounter(count: Int, list: List<String>, padding: Int): String { var counter = "" for (char in count.toString()) { val emote = list[char.toString().toInt()] counter += emote } val paddingCount = padding - count.toString().length if (paddingCount > 0) { for (i in 0 until paddingCount) { counter = list[0] + counter } } return counter } fun getEmojis(theme: CounterThemes): List<String> { return theme.emotes ?: throw UnsupportedOperationException("Theme ${theme.name} doesn't have emotes!") } }
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/counter/CounterUtils.kt
3869369953
package net.perfectdreams.loritta.cinnamon.showtime.backend.utils enum class NitroPayAdType { STANDARD_BANNER, VIDEO_PLAYER }
web/showtime/backend/src/main/kotlin/net/perfectdreams/loritta/cinnamon/showtime/backend/utils/NitroPayAdType.kt
3041723114
package com.sightsguru.app.utils import android.content.res.Resources class ViewUtils { companion object { fun dpToPx(resources: Resources, dpValue: Int): Int { return (dpValue * resources.displayMetrics.density).toInt() } } }
app/src/main/java/com/sightsguru/app/utils/ViewUtils.kt
2936538318
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vanniktech.emoji.twitter.category import com.vanniktech.emoji.EmojiCategory import com.vanniktech.emoji.twitter.TwitterEmoji internal class SmileysAndPeopleCategory : EmojiCategory { override val categoryNames: Map<String, String> get() = mapOf( "en" to "Faces", "de" to "Gesichter", ) override val emojis = ALL_EMOJIS private companion object { val ALL_EMOJIS: List<TwitterEmoji> = SmileysAndPeopleCategoryChunk0.EMOJIS + SmileysAndPeopleCategoryChunk1.EMOJIS + SmileysAndPeopleCategoryChunk2.EMOJIS + SmileysAndPeopleCategoryChunk3.EMOJIS + SmileysAndPeopleCategoryChunk4.EMOJIS } }
emoji-twitter/src/commonMain/kotlin/com/vanniktech/emoji/twitter/category/SmileysAndPeopleCategory.kt
2041270319
/* * Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.vladsch.smart import com.intellij.openapi.util.text.CharSequenceWithStringHash import com.intellij.util.text.CharSequenceBackedByArray /** * NOTE: if original is not null then editing and non-raw access is directed to it though super class calls so that this * class doubles as a fast access proxy with tracking preserved because all affected requests will be directed to the original * */ open class SmartCharArraySequence(original: SmartCharSequenceBase<*>?, chars: CharArray, startIndex: Int = 0, endIndex: Int = chars.size) : SmartCharSequenceBase<SmartCharArraySequence>(), CharSequenceBackedByArray, CharSequenceWithStringHash { @JvmOverloads constructor(chars: CharArray, start: Int = 0, end: Int = chars.size) : this(null, chars, start, end) @JvmOverloads constructor(chars: String, start: Int = 0, end: Int = chars.length) : this(null, chars.toCharArray(), start, end) final protected val myOriginal: SmartCharSequenceBase<*>? = original final protected val myVersion: SmartVersion = if (original != null) SmartCacheVersion(original.version) else SmartImmutableVersion() final protected val myChars: CharArray = chars final protected val myStart: Int = startIndex final protected val myEnd: Int = endIndex init { if (myStart < 0 || myEnd > myChars.size) { throw IllegalArgumentException("TrackingCharArraySequence(chars, " + myStart + ", " + myEnd + ") is outside data source range [0, " + myChars.size + ")") } } override fun addStats(stats: SmartCharSequence.Stats) { stats.segments++ } /* * raw access, never via proxy or in proxy via original */ override fun properSubSequence(startIndex: Int, endIndex: Int): SmartCharArraySequence { return SmartCharArraySequence(myOriginal, myChars, myStart + startIndex, myStart + endIndex) } override fun charAtImpl(index: Int): Char = myChars[myStart + index] override fun getCharsImpl(dst: CharArray, dstOffset: Int) = getChars(dst, dstOffset) override fun getCharsImpl(): CharArray = chars override fun toString(): String { return String(myChars, myStart, myEnd - myStart) } // always on original override fun getCachedProxy(): SmartCharSequence = if (myOriginal != null) super.getCachedProxy() else this /* * use proxy if fresh otherwise raw access */ override val freshProxyOrNull: SmartCharArraySequence? get() = this override fun getChars(): CharArray { if (myStart == 0) return myChars val chars = CharArray(length) System.arraycopy(myChars, myStart, chars, 0, length) return chars } override fun getChars(dst: CharArray, dstOffset: Int) { // if (dstOffset + length > dst.size) { // val tmp = 0 // } System.arraycopy(myChars, myStart, dst, dstOffset, length) } override fun get(index: Int): Char = myChars[myStart + index] override fun subSequence(startIndex: Int, endIndex: Int): SmartCharArraySequence { if (myOriginal != null) return super.subSequence(startIndex, endIndex) checkBounds(startIndex, endIndex) if (startIndex == 0 && endIndex == length) return this return properSubSequence(startIndex, endIndex) } /* * Implementation */ override fun getVersion(): SmartVersion = myVersion override val length: Int get() = myEnd - myStart override fun trackedSourceLocation(index: Int): TrackedLocation { checkIndex(index) if (myOriginal != null) { val trackedLocation = myOriginal.trackedSourceLocation(index + myStart) if (myStart == 0) return trackedLocation return trackedLocation.withIndex(trackedLocation.index - myStart) .withPrevClosest(trackedLocation.prevIndex - myStart) .withNextClosest(trackedLocation.nextIndex - myStart) } return TrackedLocation(index, myStart + index, myChars) } override fun trackedLocation(source: Any?, offset: Int): TrackedLocation? { if (myOriginal != null) { val trackedLocation = myOriginal.trackedLocation(source, offset) if (trackedLocation != null && trackedLocation.index >= myStart && trackedLocation.index < myEnd) { if (myStart == 0) return trackedLocation return trackedLocation.withIndex(trackedLocation.index - myStart) .withPrevClosest(trackedLocation.prevIndex - myStart) .withNextClosest(trackedLocation.nextIndex - myStart) } } return if ((source == null || source === myChars) && offset >= myStart && offset < myEnd) TrackedLocation(offset - myStart, offset, myChars) else null } override fun splicedWith(other: CharSequence?): SmartCharSequence? { if (myOriginal != null) return myOriginal.splicedWith(other) if (other is SmartCharArraySequence) { if (myChars == other.myChars && myEnd == other.myStart) { return SmartCharArraySequence(myChars, myStart, other.myEnd) } } return null } override fun getMarkers(id: String?): List<TrackedLocation> { if (myOriginal != null) return myOriginal.getMarkers(id) return TrackedLocation.EMPTY_LIST } override fun reversed(): SmartCharSequence { if (myOriginal != null) return myOriginal.reversed() return SmartReversedCharSequence(myChars, myStart, myEnd) } }
src/com/vladsch/smart/SmartCharArraySequence.kt
662838652
package redux import redux.api.Dispatcher import redux.api.Reducer import redux.api.Store import redux.api.Store.Creator import redux.api.Store.Enhancer import redux.api.Store.Subscriber import redux.api.enhancer.Middleware /* * Copyright (C) 2016 Michael Pardo * * 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. */ fun <S : Any> applyMiddleware(vararg middlewares: Middleware<S>): Enhancer<S> { return Enhancer { next -> Creator { reducer, initialState -> object : Store<S> { private val store = next.create(reducer, initialState) private val rootDispatcher = middlewares.foldRight(store as Dispatcher) { middleware, next -> Dispatcher { action -> middleware.dispatch(this, next, action) } } override fun dispatch(action: Any) = rootDispatcher.dispatch(action) override fun getState() = store.state override fun replaceReducer(reducer: Reducer<S>) = store.replaceReducer(reducer) override fun subscribe(subscriber: Subscriber) = store.subscribe(subscriber) } } } }
lib/src/main/kotlin/redux/Middleware.kt
3579530616
package cn.luo.yuan.maze.model.dlc import cn.luo.yuan.maze.model.IDModel import cn.luo.yuan.maze.model.goods.Goods import cn.luo.yuan.maze.model.skill.Skill import cn.luo.yuan.maze.utils.Field import cn.luo.yuan.maze.utils.StringUtils /** * Copyright @Luo * Created by Gavin Luo on 8/15/2017. */ class SkillDLC : SingleItemDLC, Cloneable { override fun getItem(): IDModel? { return skill } companion object { private const val serialVersionUID = Field.SERVER_VERSION } var skill: Skill? = null set(value){ field = value title = skill!!.name desc = skill!!.displayName } private var delete = false override fun isDelete(): Boolean { return delete } override fun markDelete() { delete = true } override var title: String = StringUtils.EMPTY_STRING override var desc: String = StringUtils.EMPTY_STRING override var debrisCost: Int = 0 override fun clone(): DLC { return super.clone() as SkillDLC } }
dataModel/src/cn/luo/yuan/maze/model/dlc/SkillDLC.kt
2903885004
package cn.luo.yuan.maze.model.goods import cn.luo.yuan.maze.model.Hero import java.util.* /** * Created by gluo on 5/5/2017. */ class GoodsProperties(val hero: Hero) : HashMap<String, Any>(5) { }
dataModel/src/cn/luo/yuan/maze/model/goods/GoodsProperties.kt
3289416373
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * 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 io.lumeer.core.adapter import io.lumeer.api.model.* import io.lumeer.api.model.Collection import io.lumeer.api.model.common.Resource import io.lumeer.core.facade.PusherFacade import io.lumeer.core.facade.PusherFacade.ObjectWithParent import io.lumeer.core.facade.PusherFacade.ResourceId import io.lumeer.storage.api.dao.CollectionDao import io.lumeer.storage.api.dao.LinkTypeDao import io.lumeer.storage.api.dao.ViewDao import org.marvec.pusher.data.BackupDataEvent import org.marvec.pusher.data.Event class PusherAdapter( private val appId: AppId?, private val facadeAdapter: FacadeAdapter, private val resourceAdapter: ResourceAdapter, private val permissionAdapter: PermissionAdapter, private val viewDao: ViewDao, private val linkTypeDao: LinkTypeDao, private val collectionDao: CollectionDao, ) { fun checkLinkTypePermissionsChange(organization: Organization, project: Project?, user: User, originalLinkType: LinkType, updatedLinkType: LinkType): List<Event> { val rolesDifference = permissionAdapter.getLinkTypeReadersDifference(organization, project, originalLinkType, updatedLinkType) val changedUsers = rolesDifference.changedUsers().toMutableSet().minus(user.id) val removedReadersNotifications = rolesDifference.removedUsers .map { userId -> createEventForRemove(originalLinkType.javaClass.simpleName, ResourceId(appId, originalLinkType.id, organization.id.orEmpty(), project?.id.orEmpty()), userId) } .toMutableList() if (changedUsers.isEmpty()) { return removedReadersNotifications } val allLinkTypes = linkTypeDao.allLinkTypes.filter { it.id != originalLinkType.id } val allViews = viewDao.allViews val allCollections = collectionDao.allCollections val linkTypesBefore = allLinkTypes.plus(originalLinkType) val linkTypesAfter = allLinkTypes.plus(updatedLinkType) changedUsers.forEach { userId -> removedReadersNotifications.addAll(createCollectionsChangeNotifications(organization, project, Pair(linkTypesBefore, linkTypesAfter), Pair(allCollections, allCollections), Pair(allViews, allViews), userId)) } return removedReadersNotifications } fun checkCollectionsPermissionsChange(organization: Organization, project: Project?, user: User, originalCollection: Collection, updatedCollection: Collection): List<Event> { val rolesDifference = permissionAdapter.getResourceReadersDifference(organization, project, originalCollection, updatedCollection) val changedUsers = rolesDifference.changedUsers().toMutableSet().minus(user.id) val removedReadersNotifications = rolesDifference.removedUsers .map { userId -> createEventForRemove(originalCollection.javaClass.simpleName, ResourceId(appId, originalCollection.id, organization.id.orEmpty(), project?.id.orEmpty()), userId) } .toMutableList() if (changedUsers.isEmpty()) { return removedReadersNotifications } val allLinkTypes = linkTypeDao.allLinkTypes val allViews = viewDao.allViews val allCollections = collectionDao.allCollections.filter { it.id != originalCollection.id } val collectionsBefore = allCollections.plus(originalCollection) val collectionsAfter = allCollections.plus(updatedCollection) changedUsers.forEach { userId -> removedReadersNotifications.addAll(createLinksChangeNotifications(organization, project, Pair(allLinkTypes, allLinkTypes), Pair(collectionsBefore, collectionsAfter), Pair(allViews, allViews), userId)) } return removedReadersNotifications } fun checkViewPermissionsChange(organization: Organization, project: Project?, user: User, originalView: View?, updatedView: View): List<Event> { if (originalView == null) { return listOf() } val rolesDifference = permissionAdapter.getResourceReadersDifference(organization, project, originalView, updatedView) val changedUsers = rolesDifference.changedUsers().toMutableSet().minus(user.id) val removedReadersNotifications = rolesDifference.removedUsers .map { userId -> createEventForRemove(originalView.javaClass.simpleName, ResourceId(appId, originalView.id, organization.id.orEmpty(), project?.id.orEmpty()), userId) } .toMutableList() if (changedUsers.isEmpty()) { return removedReadersNotifications } val allViews = viewDao.allViews.filter { it.id != originalView.id } val allCollections = collectionDao.allCollections val allLinkTypes = linkTypeDao.allLinkTypes val viewsBefore = allViews.plus(originalView) val viewsAfter = allViews.plus(updatedView) changedUsers.forEach { userId -> removedReadersNotifications.addAll(createCollectionsAndLinksChangeNotifications(organization, project, Pair(allLinkTypes, allLinkTypes), Pair(allCollections, allCollections), Pair(viewsBefore, viewsAfter), userId)) } return removedReadersNotifications } private fun createCollectionsChangeNotifications(organization: Organization, project: Project?, linkTypes: Pair<List<LinkType>, List<LinkType>>, collections: Pair<List<Collection>, List<Collection>>, views: Pair<List<View>, List<View>>, userId: String): List<Event> { val collectionsBefore = resourceAdapter.getAllCollections(organization, project, linkTypes.first, views.first, collections.first, userId).toMutableList() val collectionsAfter = resourceAdapter.getAllCollections(organization, project, linkTypes.second, views.second, collections.second, userId).toMutableList() val notifications = mutableListOf<Event>() val lostCollections = collectionsBefore.toMutableSet().minus(collectionsAfter) val gainedCollections = collectionsAfter.toMutableSet().minus(collectionsBefore) lostCollections.forEach { notifications.add(createEventForRemove(it.javaClass.simpleName, ResourceId(appId, it.id, organization.id.orEmpty(), project?.id.orEmpty()), userId)) } gainedCollections.forEach { notifications.add(createEventForWorkspaceObject(organization, project, filterUserRoles(organization, project, userId, it), it.id, PusherFacade.UPDATE_EVENT_SUFFIX, userId)) } return notifications } private fun createLinksChangeNotifications(organization: Organization, project: Project?, linkTypes: Pair<List<LinkType>, List<LinkType>>, collections: Pair<List<Collection>, List<Collection>>, views: Pair<List<View>, List<View>>, userId: String): List<Event> { val linkTypesBefore = resourceAdapter.getAllLinkTypes(organization, project, linkTypes.first, views.first, collections.first, userId).toMutableList() val linkTypesAfter = resourceAdapter.getAllLinkTypes(organization, project, linkTypes.second, views.second, collections.second, userId).toMutableList() val notifications = mutableListOf<Event>() val lostLinkTypes = linkTypesBefore.toMutableSet().minus(linkTypesAfter) val gainedLinkTypes = linkTypesAfter.toMutableSet().minus(linkTypesBefore) lostLinkTypes.forEach { notifications.add(createEventForRemove(it.javaClass.simpleName, ResourceId(appId, it.id, organization.id.orEmpty(), project?.id.orEmpty()), userId)) } gainedLinkTypes.forEach { notifications.add(createEventForWorkspaceObject(organization, project, filterUserRoles(organization, project, userId, it), it.id, PusherFacade.UPDATE_EVENT_SUFFIX, userId)) } return notifications } private fun createCollectionsAndLinksChangeNotifications(organization: Organization, project: Project?, linkTypes: Pair<List<LinkType>, List<LinkType>>, collections: Pair<List<Collection>, List<Collection>>, views: Pair<List<View>, List<View>>, userId: String): List<Event> { println("createCollectionsAndLinksChangeNotifications " + userId) return createCollectionsChangeNotifications(organization, project, linkTypes, collections, views, userId).plus(createLinksChangeNotifications(organization, project, linkTypes, collections, views, userId)) } fun createEvent(organization: Organization?, project: Project?, any: Any, event: String, userId: String): Event { return if (any is Document) { createEventForWorkspaceObject(organization, project, any, any.id, event, userId) } else if (any is LinkType) { createEventForWorkspaceObject(organization, project, any, any.id, event, userId) } else if (any is LinkInstance) { createEventForWorkspaceObject(organization, project, any, any.id, event, userId) } else if (any is Resource) { createEventForResource(organization, project, any, event, userId) } else if (any is ResourceComment) { createEventForWorkspaceObject(organization, project, any, any.id, event, userId) } else if (any is ObjectWithParent) { if (any.`object` is Resource) { createEventForNestedResource(organization, project, any, event, userId) } else { createEventForObjectWithParent(any, event, userId) } } else { createEventForObject(any, event, userId) } } fun createEventForWorkspaceObject(organization: Organization?, project: Project?, any: Any, id: String, event: String, userId: String): Event { val organizationId = organization?.id.orEmpty() val projectId = project?.id.orEmpty() if (PusherFacade.REMOVE_EVENT_SUFFIX == event) { return createEventForRemove(any.javaClass.simpleName, ResourceId(appId, id, organizationId, projectId), userId) } val normalMessage = if (any is LinkType) { ObjectWithParent(appId, filterUserRoles(organization, project, userId, any), organizationId, projectId) } else { ObjectWithParent(appId, any, organizationId, projectId) } val extraId = when (any) { is Document -> { any.collectionId } is LinkInstance -> { any.linkTypeId } is ResourceComment -> { any.resourceType.toString() + '/' + any.resourceId } else -> null } val alternateMessage = ResourceId(appId, id, organizationId, projectId, extraId) return createEventForObjectWithParent(normalMessage, alternateMessage, event, userId) } fun createEventForRemove(className: String, any: ResourceId, userId: String): Event { return Event(PusherFacade.eventChannel(userId), className + PusherFacade.REMOVE_EVENT_SUFFIX, any, null) } fun createEventForResource(organization: Organization?, project: Project?, resource: Resource, event: String, userId: String): Event { return if (PusherFacade.REMOVE_EVENT_SUFFIX == event) { createEventForRemove(resource.javaClass.simpleName, getResourceId(organization, project, resource), userId) } else createEventForObject(filterUserRoles(organization, project, userId, resource), getResourceId(organization, project, resource), event, userId) } fun createEventForObject(any: Any, event: String, userId: String): Event { return Event(eventChannel(userId), any.javaClass.simpleName + event, any) } fun createEventForObject(`object`: Any, backupObject: Any, event: String, userId: String): BackupDataEvent { return BackupDataEvent(eventChannel(userId), `object`.javaClass.simpleName + event, `object`, backupObject, null) } private fun createEventForNestedResource(organization: Organization?, project: Project?, objectWithParent: ObjectWithParent, event: String, userId: String): Event { val resource = objectWithParent.`object` as Resource if (PusherFacade.REMOVE_EVENT_SUFFIX == event) { return createEventForRemove(resource.javaClass.simpleName, getResourceId(organization, project, resource), userId) } val filteredResource = filterUserRoles(organization, project, userId, resource) val newObjectWithParent = ObjectWithParent(appId, filteredResource, objectWithParent.organizationId, objectWithParent.projectId) newObjectWithParent.correlationId = objectWithParent.correlationId return createEventForObjectWithParent(newObjectWithParent, getResourceId(organization, project, resource), event, userId) } fun createEventForObjectWithParent(objectWithParent: ObjectWithParent, event: String, userId: String): Event { return Event(eventChannel(userId), objectWithParent.`object`.javaClass.simpleName + event, objectWithParent) } fun createEventForObjectWithParent(objectWithParent: ObjectWithParent, backupObject: Any, event: String, userId: String): BackupDataEvent { return BackupDataEvent(eventChannel(userId), objectWithParent.`object`.javaClass.simpleName + event, objectWithParent, backupObject, null) } private fun getResourceId(organization: Organization?, project: Project?, resource: Resource): ResourceId { if (resource is Organization) { return ResourceId(appId, resource.getId(), null, null) } else if (resource is Project) { return ResourceId(appId, resource.getId(), organization?.id.orEmpty(), null) } return ResourceId(appId, resource.id, organization?.id.orEmpty(), project?.id.orEmpty()) } private fun <T : Resource> filterUserRoles(organization: Organization?, project: Project?, userId: String, resource: T): T { return facadeAdapter.mapResource(organization, project, resource.copy(), permissionAdapter.getUser(userId)) } private fun filterUserRoles(organization: Organization?, project: Project?, userId: String, linkType: LinkType): LinkType { return facadeAdapter.mapLinkType(organization, project, LinkType(linkType), permissionAdapter.getUser(userId)) } companion object { @JvmStatic fun eventChannel(userId: String): String { return PusherFacade.PRIVATE_CHANNEL_PREFIX + userId } } }
lumeer-core/src/main/kotlin/io/lumeer/core/adapter/PusherAdapter.kt
2988814880
package com.izettle.kotlin import java.util.Optional /** * Convert a Java Optional to a Kotlin nullable type to avoid handling Optionals in Kotlin. * * Usage: * ``` * optional.asNullable()?.let { "has value $it" } ?: "empty" * ``` * * @see Optional */ fun <T : Any> Optional<T>.asNullable(): T? = this.orElse(null)
izettle-kotlin/src/main/kotlin/com/izettle/kotlin/Optionals.kt
446906727
/* * 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 com.example.android.dagger.di import com.example.android.dagger.login.LoginComponent import com.example.android.dagger.registration.RegistrationComponent import com.example.android.dagger.user.UserComponent import dagger.Module // This module tells a Component which are its subcomponents @Module( subcomponents = [ RegistrationComponent::class, LoginComponent::class, UserComponent::class ] ) class AppSubcomponents
android-dagger-master/app/src/main/java/com/example/android/dagger/di/AppSubcomponents.kt
2309273317
package com.cout970.magneticraft.systems.tilemodules import com.cout970.magneticraft.api.internal.pneumatic.PneumaticBuffer import com.cout970.magneticraft.misc.tileentity.getCap import com.cout970.magneticraft.misc.tileentity.shouldTick import com.cout970.magneticraft.misc.vector.createAABBUsing import com.cout970.magneticraft.misc.vector.toVec3d import com.cout970.magneticraft.misc.world.isClient import com.cout970.magneticraft.registry.ITEM_HANDLER import com.cout970.magneticraft.systems.tileentities.IModule import com.cout970.magneticraft.systems.tileentities.IModuleContainer import net.minecraft.entity.item.EntityItem import net.minecraft.util.EnumFacing class ModuleTransposer( val buffer: PneumaticBuffer, val itemFilter: ModuleItemFilter, val facing: () -> EnumFacing, override val name: String = "module_transposer" ) : IModule { override lateinit var container: IModuleContainer override fun update() { if (world.isClient || buffer.blocked || !container.shouldTick(5)) return val frontPos = pos.offset(facing().opposite) val inventory = world.getCap(ITEM_HANDLER, frontPos, facing()) if (inventory != null) { for (slot in 0 until inventory.slots) { val stack = inventory.extractItem(slot, 64, true) if (stack.isEmpty) continue if (!itemFilter.filterAllowStack(stack)) continue buffer.add(inventory.extractItem(slot, 64, false)) return } return } val start = frontPos.toVec3d() val end = start.addVector(1.0, 1.0, 1.0) val aabb = start.createAABBUsing(end) val items = world.getEntitiesWithinAABB(EntityItem::class.java, aabb) .filter { !it.isDead } .toMutableSet() while (items.isNotEmpty()) { val target = items.first() if (itemFilter.filterAllowStack(target.item)) { buffer.add(target.item) target.setDead() break } items.remove(target) } } }
src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/ModuleTransposer.kt
3668859691
package com.github.shynixn.petblocks.api.business.service import com.github.shynixn.petblocks.api.persistence.entity.PetMeta /** * Created by Shynixn 2019. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2019 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ interface GUIPetStorageService { /** * Opens the storage of the given [petMeta] for the given player. * If the petMeta belongs to a different player than the given player, the * inventory gets opened in readOnlyMode. */ fun <P> openStorage(player: P, petMeta: PetMeta, from: Int, to: Int) /** * Returns if the given [inventory] matches the storage inventory of this service. */ fun <I> isStorage(inventory: I): Boolean /** * Saves the storage inventory to the database and clears all resources. */ fun <P> saveStorage(player: P) }
petblocks-api/src/main/kotlin/com/github/shynixn/petblocks/api/business/service/GUIPetStorageService.kt
3824723543
/* * Copyright 2020-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.lettuce.core.api.coroutines import io.lettuce.core.ExperimentalLettuceCoroutinesApi import io.lettuce.core.TransactionResult import io.lettuce.core.api.reactive.RedisTransactionalReactiveCommands import kotlinx.coroutines.reactive.awaitLast /** * Coroutine executed commands (based on reactive commands) for Transactions. * * @param <K> Key type. * @param <V> Value type. * @author Mikhael Sokolov * @since 6.0 */ @ExperimentalLettuceCoroutinesApi internal class RedisTransactionalCoroutinesCommandsImpl<K : Any, V : Any>(private val ops: RedisTransactionalReactiveCommands<K, V>) : RedisTransactionalCoroutinesCommands<K, V> { override suspend fun discard(): String = ops.discard().awaitLast() override suspend fun exec(): TransactionResult = ops.exec().awaitLast() override suspend fun multi(): String = ops.multi().awaitLast() override suspend fun watch(vararg keys: K): String = ops.watch(*keys).awaitLast() override suspend fun unwatch(): String = ops.unwatch().awaitLast() }
src/main/kotlin/io/lettuce/core/api/coroutines/RedisTransactionalCoroutinesCommandsImpl.kt
3519966200
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.integration import okhttp3.HttpUrl import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.gradle.integtests.fixtures.RepoScriptBlockUtil.jcenterRepository import org.gradle.kotlin.dsl.embeddedKotlinVersion import org.gradle.kotlin.dsl.fixtures.DeepThought import org.gradle.kotlin.dsl.fixtures.LightThought import org.gradle.kotlin.dsl.fixtures.ZeroThought import org.gradle.kotlin.dsl.fixtures.containsMultiLineString import org.gradle.kotlin.dsl.support.normaliseLineSeparators import org.gradle.test.fixtures.dsl.GradleDsl import org.gradle.test.fixtures.file.LeaksFileHandles import org.hamcrest.CoreMatchers.allOf import org.hamcrest.CoreMatchers.containsString import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Assert.assertNotEquals import org.junit.Test class GradleKotlinDslIntegrationTest : AbstractPluginIntegrationTest() { @Test fun `given a buildscript block, it will be used to compute the runtime classpath`() { checkBuildscriptBlockIsUsedToComputeRuntimeClasspathAfter { it } } @Test fun `given a buildscript block separated by CRLF, it will be used to compute the runtime classpath`() { checkBuildscriptBlockIsUsedToComputeRuntimeClasspathAfter { it.replace("\r\n", "\n").replace("\n", "\r\n") } } private fun checkBuildscriptBlockIsUsedToComputeRuntimeClasspathAfter(buildscriptTransformation: (String) -> String) { withClassJar("fixture.jar", DeepThought::class.java) withBuildScript(""" buildscript { dependencies { classpath(files("fixture.jar")) } } task("compute") { doLast { val computer = ${DeepThought::class.qualifiedName}() val answer = computer.compute() println("*" + answer + "*") } } """.let(buildscriptTransformation)) assert( build("compute").output.contains("*42*")) } @Test fun `given a script plugin with a buildscript block, it will be used to compute its classpath`() { withClassJar("fixture.jar", DeepThought::class.java) withFile("other.gradle.kts", """ buildscript { dependencies { classpath(files("fixture.jar")) } } task("compute") { doLast { val computer = ${DeepThought::class.qualifiedName}() val answer = computer.compute() println("*" + answer + "*") } } """) withBuildScript(""" apply(from = "other.gradle.kts") """) assert( build("compute").output.contains("*42*")) } @Test fun `given a buildSrc dir, it will be added to the compilation classpath`() { withFile("buildSrc/src/main/groovy/build/DeepThought.groovy", """ package build class DeepThought { def compute() { 42 } } """) withBuildScript(""" task("compute") { doLast { val computer = build.DeepThought() val answer = computer.compute() println("*" + answer + "*") } } """) assert( build("compute").output.contains("*42*")) } @Test fun `given a Kotlin project in buildSrc, it will be added to the compilation classpath`() { requireGradleDistributionOnEmbeddedExecuter() withKotlinBuildSrc() withFile("buildSrc/src/main/kotlin/build/DeepThought.kt", """ package build class DeepThought() { fun compute(handler: (Int) -> Unit) { handler(42) } } """) withFile("buildSrc/src/main/kotlin/build/DeepThoughtPlugin.kt", """ package build import org.gradle.api.* import org.gradle.kotlin.dsl.* class DeepThoughtPlugin : Plugin<Project> { override fun apply(project: Project) { project.run { task("compute") { doLast { DeepThought().compute { answer -> println("*" + answer + "*") } } } } } } """) withBuildScript(""" buildscript { // buildSrc types are available within buildscript // and must always be fully qualified build.DeepThought().compute { answer -> println("buildscript: " + answer) } } apply<build.DeepThoughtPlugin>() """) val output = build("compute").output assert(output.contains("buildscript: 42")) assert(output.contains("*42*")) } @Test fun `can compile against a different (but compatible) version of the Kotlin compiler`() { requireGradleDistributionOnEmbeddedExecuter() val differentKotlinVersion = "1.3.30" val expectedKotlinCompilerVersionString = "1.3.30" assertNotEquals(embeddedKotlinVersion, differentKotlinVersion) withBuildScript(""" import org.jetbrains.kotlin.config.KotlinCompilerVersion import org.jetbrains.kotlin.gradle.tasks.KotlinCompile buildscript { repositories { jcenter() } dependencies { classpath(kotlin("gradle-plugin", version = "$differentKotlinVersion")) } } apply(plugin = "kotlin") tasks.withType<KotlinCompile> { // can configure the Kotlin compiler kotlinOptions.suppressWarnings = true } task("print-kotlin-version") { doLast { val compileOptions = tasks.filterIsInstance<KotlinCompile>().joinToString(prefix="[", postfix="]") { it.name + "=" + it.kotlinOptions.suppressWarnings } println(KotlinCompilerVersion.VERSION + compileOptions) } } """) assertThat( build("print-kotlin-version").output, containsString("$expectedKotlinCompilerVersionString[compileKotlin=true, compileTestKotlin=true]")) } @Test fun `can apply base plugin via plugins block`() { withBuildScript(""" plugins { id("base") } task("plugins") { doLast { println(plugins.map { "*" + it::class.simpleName + "*" }) } } """) assertThat( build("plugins").output, containsString("*BasePlugin*")) } @Test fun `can use Closure only APIs`() { withBuildScript(""" gradle.buildFinished(closureOf<org.gradle.BuildResult> { println("*" + action + "*") // <- BuildResult.getAction() }) """) assert( build("build").output.contains("*Build*")) } @Test fun `given an exception thrown during buildscript block execution, its stack trace should contain correct file and line info`() { withBuildScript(""" // line 1 // line 2 // line 3 buildscript { // line 4 throw IllegalStateException() // line 5 } """) assertThat( buildFailureOutput(), containsString("build.gradle.kts:5")) } @Test fun `given a script with more than one buildscript block, it throws exception with offending block line number`() { withBuildScript(""" // line 1 buildscript {} // line 2 buildscript {} // line 3 """) assertThat( buildFailureOutput(), containsString("build.gradle.kts:3:13: Unexpected `buildscript` block found. Only one `buildscript` block is allowed per script.")) } @Test fun `given a script with more than one plugins block, it throws exception with offending block line number`() { withBuildScript(""" // line 1 plugins {} // line 2 plugins {} // line 3 """) assertThat( buildFailureOutput(), containsString("build.gradle.kts:3:13: Unexpected `plugins` block found. Only one `plugins` block is allowed per script.")) } @Test fun `given a buildscript block compilation error, it reports correct error location`() { assertCorrectLocationIsReportedForErrorIn("buildscript") } @Test fun `given a plugins block compilation error, it reports correct error location`() { assertCorrectLocationIsReportedForErrorIn("plugins") } private fun assertCorrectLocationIsReportedForErrorIn(block: String) { val buildFile = withBuildScript(""" $block { val module = "foo:bar:${'$'}fooBarVersion" } """) assertThat( buildFailureOutput("tasks"), containsString("e: $buildFile:3:44: Unresolved reference: fooBarVersion")) } @Test fun `sub-project build script inherits parent project compilation classpath`() { withClassJar("fixture.jar", DeepThought::class.java) withBuildScript(""" buildscript { dependencies { classpath(files("fixture.jar")) } } """) withSettings("include(\"sub-project\")") withBuildScriptIn("sub-project", """ task("compute") { doLast { val computer = ${DeepThought::class.qualifiedName}() val answer = computer.compute() println("*" + answer + "*") } } """) assert( build(":sub-project:compute").output.contains("*42*")) } @Test fun `given non-existing build script file name set in settings do not fail`() { withSettings("rootProject.buildFileName = \"does-not-exist.gradle.kts\"") build("help") } @Test fun `build with groovy settings and kotlin-dsl build script succeeds`() { withFile("settings.gradle", """ println 'Groovy DSL Settings' """) withBuildScript(""" println("Kotlin DSL Build Script") """) assertThat( build("help").output, allOf( containsString("Groovy DSL Settings"), containsString("Kotlin DSL Build Script"))) } @Test fun `build script can use jdk8 extensions`() { assumeJavaLessThan9() withBuildScript(""" // without kotlin-stdlib-jdk8 we get: // > Retrieving groups by name is not supported on this platform. val regex = Regex("(?<bla>.*)") val groups = regex.matchEntire("abc")?.groups println("*" + groups?.get("bla")?.value + "*") """) assertThat( build("help").output, containsString("*abc*")) } @Test fun `settings script can use buildscript dependencies`() { withSettings(""" buildscript { ${jcenterRepository(GradleDsl.KOTLIN)} dependencies { classpath("org.apache.commons:commons-lang3:3.6") } } println(org.apache.commons.lang3.StringUtils.reverse("Gradle")) """) assertThat( build("help").output, containsString("eldarG")) } @Test fun `script plugin can by applied to either Project or Settings`() { withFile("common.gradle.kts", """ println("Target is Settings? ${"$"}{Settings::class.java.isAssignableFrom(this::class.java)}") println("Target is Project? ${"$"}{Project::class.java.isAssignableFrom(this::class.java)}") """) withSettings(""" apply(from = "common.gradle.kts") """) assertThat( build("help").output, allOf( containsString("Target is Settings? true"), containsString("Target is Project? false"))) withSettings("") withBuildScript(""" apply(from = "common.gradle.kts") """) assertThat( build("help").output, allOf( containsString("Target is Settings? false"), containsString("Target is Project? true"))) } @Test fun `scripts can use the gradle script api`() { fun usageFor(target: String) = """ logger.error("Error logging from $target") require(logging is LoggingManager, { "logging" }) require(resources is ResourceHandler, { "resources" }) require(relativePath("src/../settings.gradle.kts") == "settings.gradle.kts", { "relativePath(path)" }) require(uri("settings.gradle.kts").toString().endsWith("settings.gradle.kts"), { "uri(path)" }) require(file("settings.gradle.kts").isFile, { "file(path)" }) require(files("settings.gradle.kts").files.isNotEmpty(), { "files(paths)" }) require(fileTree(".").contains(file("settings.gradle.kts")), { "fileTree(path)" }) require(copySpec {} != null, { "copySpec {}" }) require(mkdir("some").isDirectory, { "mkdir(path)" }) require(delete("some"), { "delete(path)" }) require(delete {} != null, { "delete {}" }) """ withSettings(usageFor("Settings")) withBuildScript(usageFor("Project")) assertThat( build("help").error, allOf( containsString("Error logging from Settings"), containsString("Error logging from Project"))) } @Test fun `automatically applies build scan plugin when --scan is provided on command-line and a script is applied in the buildscript block`() { withBuildScript(""" buildscript { rootProject.apply(from = rootProject.file("gradle/dependencies.gradle.kts")) } buildScan { termsOfServiceUrl = "https://gradle.com/terms-of-service" termsOfServiceAgree = "yes" } """) withFile("gradle/dependencies.gradle.kts") canPublishBuildScan() } @Test fun `can use shorthand notation for bound callable references with inline functions in build scripts`() { withBuildScript(""" fun foo(it: Any) = true // The inline modifier is important. This does not fail when this is no inline function. inline fun bar(f: (Any) -> Boolean) = print("*" + f(Unit) + "*") bar(::foo) """) assertThat( build().output, containsString("*true*")) } @Test fun `script compilation error message`() { val buildFile = withBuildScript("foo") assertThat( buildFailureOutput().normaliseLineSeparators(), containsString(""" FAILURE: Build failed with an exception. * Where: Build file '${buildFile.canonicalPath}' line: 1 * What went wrong: Script compilation error: Line 1: foo ^ Unresolved reference: foo 1 error """.replaceIndent()) ) } @Test fun `multiline script compilation error message`() { withBuildScript("publishing { }") assertThat( buildFailureOutput().normaliseLineSeparators(), containsString(""" * What went wrong: Script compilation errors: Line 1: publishing { } ^ Expression 'publishing' cannot be invoked as a function. The function 'invoke()' is not found Line 1: publishing { } ^ Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:${' '} public val PluginDependenciesSpec.publishing: PluginDependencySpec defined in org.gradle.kotlin.dsl 2 errors """.replaceIndent())) } @Test fun `multiple script compilation errors message`() { val buildFile = withBuildScript("println(foo)\n\n\n\n\nprintln(\"foo\").bar.bazar\n\n\n\nprintln(cathedral)") assertThat( buildFailureOutput().normaliseLineSeparators(), allOf( containsString(""" FAILURE: Build failed with an exception. * Where: Build file '${buildFile.canonicalPath}' line: 1 * What went wrong: Script compilation errors: """.replaceIndent()), containsString(""" | Line 01: println(foo) | ^ Unresolved reference: foo """.trimMargin()), containsString(""" | Line 06: println("foo").bar.bazar | ^ Unresolved reference: bar """.trimMargin()), containsString(""" | Line 10: println(cathedral) | ^ Unresolved reference: cathedral """.trimMargin()))) } @Test fun `given a remote buildscript, file paths are resolved relative to root project dir`() { val remoteScript = """ apply(from = "./gradle/answer.gradle.kts") """ withFile("gradle/answer.gradle.kts", """ val answer by extra { "42" } """) MockWebServer().use { server -> server.enqueue(MockResponse().setBody(remoteScript)) server.start() val remoteScriptUrl = server.safeUrl("/remote.gradle.kts") withBuildScript(""" apply(from = "$remoteScriptUrl") val answer: String by extra println("*" + answer + "*") """) assert(build().output.contains("*42*")) } } private fun MockWebServer.safeUrl(path: String, scheme: String = "http"): HttpUrl? { return HttpUrl.Builder() .scheme(scheme) .host("127.0.0.1") .port(port) .build() .resolve(path) } @Test fun `given a script from a jar, file paths are resolved relative to root project dir`() { val scriptFromJar = """ apply(from = "./gradle/answer.gradle.kts") """ withZip( "fixture.jar", sequenceOf("common.gradle.kts" to scriptFromJar.toByteArray())) withFile("gradle/answer.gradle.kts", """ val answer by extra { "42" } """) withBuildScript(""" buildscript { dependencies { classpath(files("fixture.jar")) } } apply(from = project.buildscript.classLoader.getResource("common.gradle.kts").toURI()) val answer: String by extra println("*" + answer + "*") """) assert(build().output.contains("*42*")) } @Test fun `script handler belongs to the current script`() { val init = withFile("some.init.gradle.kts", """ println("init: ${'$'}{initscript.sourceFile}") """) val settings = withSettings(""" println("settings: ${'$'}{buildscript.sourceFile}") """) val other = withFile("other.gradle.kts", """ println("other: ${'$'}{buildscript.sourceFile}") """) val main = withBuildScript(""" apply(from = "other.gradle.kts") println("main: ${'$'}{buildscript.sourceFile}") """) assertThat( build("-I", init.absolutePath, "help", "-q").output, containsMultiLineString(""" init: ${init.absolutePath} settings: ${settings.absolutePath} other: ${other.absolutePath} main: ${main.absolutePath} """)) } @Test fun `can cross configure buildscript`() { withClassJar("zero.jar", ZeroThought::class.java) withClassJar("light.jar", LightThought::class.java) withClassJar("deep.jar", DeepThought::class.java) val init = withFile("some.init.gradle.kts", """ projectsLoaded { rootProject.buildscript { dependencies { classpath(files("zero.jar")) } } } """) withSettings(""" include("sub") gradle.projectsLoaded { rootProject.buildscript { dependencies { classpath(files("light.jar")) } } } """) withBuildScript(""" project(":sub") { buildscript { dependencies { classpath(files("../deep.jar")) } } } """) withFile("sub/build.gradle.kts", """ task("think") { doLast { val zero = ${ZeroThought::class.qualifiedName}() val light = ${LightThought::class.qualifiedName}() val deep = ${DeepThought::class.qualifiedName}() println("*" + zero.compute() + "*") println("*" + light.compute() + "*") println("*" + deep.compute() + "*") } } """) assertThat( build("-I", init.absolutePath, ":sub:think").output, containsMultiLineString(""" *0* *23* *42* """)) } @Test @LeaksFileHandles("Kotlin Compiler Daemon working directory") fun `given generic extension types they can be accessed and configured`() { requireGradleDistributionOnEmbeddedExecuter() withDefaultSettingsIn("buildSrc") withFile("buildSrc/build.gradle.kts", """ plugins { `kotlin-dsl` } gradlePlugin { plugins { register("my") { id = "my" implementationClass = "my.MyPlugin" } } } $repositoriesBlock """) withFile("buildSrc/src/main/kotlin/my/MyPlugin.kt", """ package my import org.gradle.api.* import org.gradle.kotlin.dsl.* class Book(val name: String) class MyPlugin : Plugin<Project> { override fun apply(project: Project): Unit = project.run { extensions.add(typeOf<MutableMap<String, String>>(), "mapOfString", mutableMapOf("foo" to "bar")) extensions.add(typeOf<MutableMap<String, Int>>(), "mapOfInt", mutableMapOf("deep" to 42)) extensions.add(typeOf<NamedDomainObjectContainer<Book>>(), "books", container(Book::class)) } } """) withBuildScript(""" plugins { id("my") } configure<MutableMap<String, String>> { put("bazar", "cathedral") } require(the<MutableMap<String, String>>() == mapOf("foo" to "bar", "bazar" to "cathedral")) configure<MutableMap<String, Int>> { put("zero", 0) } require(the<MutableMap<String, Int>>() == mapOf("deep" to 42, "zero" to 0)) require(the<MutableMap<*, *>>() == mapOf("foo" to "bar", "bazar" to "cathedral")) configure<NamedDomainObjectContainer<my.Book>> { create("The Dosadi experiment") } require(the<NamedDomainObjectContainer<my.Book>>().size == 1) """) build("help") } @Test fun `can use kotlin java8 inline-only methods`() { withBuildScript(""" task("test") { doLast { println(project.properties.getOrDefault("non-existent-property", "default-value")) } } """) assertThat( build("-q", "test").output.trim(), equalTo("default-value") ) } @Test fun `can apply script plugin with package name`() { withFile("gradle/script.gradle.kts", """ package gradle task("ok") { doLast { println("ok!") } } """) withBuildScript(""" apply(from = "gradle/script.gradle.kts") """) assertThat( build("-q", "ok").output.trim(), equalTo("ok!") ) } }
subprojects/kotlin-dsl-integ-tests/src/integTest/kotlin/org/gradle/kotlin/dsl/integration/GradleKotlinDslIntegrationTest.kt
1635161235
package com.bl_lia.kirakiratter.presentation.activity import android.os.Bundle import android.support.design.widget.AppBarLayout import android.support.design.widget.CollapsingToolbarLayout import android.support.design.widget.Snackbar import android.support.v4.content.ContextCompat import android.text.method.LinkMovementMethod import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewTreeObserver import com.bl_lia.kirakiratter.App import com.bl_lia.kirakiratter.R import com.bl_lia.kirakiratter.domain.entity.Account import com.bl_lia.kirakiratter.domain.entity.Relationship import com.bl_lia.kirakiratter.domain.extension.asHtml import com.bl_lia.kirakiratter.domain.extension.preparedErrorMessage import com.bl_lia.kirakiratter.presentation.fragment.AccountFragment import com.bl_lia.kirakiratter.presentation.internal.di.component.AccountComponent import com.bl_lia.kirakiratter.presentation.internal.di.component.DaggerAccountComponent import com.bl_lia.kirakiratter.presentation.internal.di.module.ActivityModule import com.bl_lia.kirakiratter.presentation.presenter.AccountPresenter import com.bl_lia.kirakiratter.presentation.transform.AvatarTransformation import com.squareup.picasso.Picasso import com.trello.rxlifecycle2.components.support.RxAppCompatActivity import io.reactivex.Single import jp.wasabeef.picasso.transformations.BlurTransformation import kotlinx.android.synthetic.main.activity_account.* import javax.inject.Inject class AccountActivity : RxAppCompatActivity() { companion object { val INTENT_PARAM_ACCOUNT = "intent_param_account" } @Inject lateinit var presenter: AccountPresenter private var relationship: Relationship? = null private var isOtherAccount: Boolean = false private val account: Single<Account> by lazy { presenter.verifyCredentials() .map { me -> if (intent.hasExtra(INTENT_PARAM_ACCOUNT)) { val account = intent.getSerializableExtra(INTENT_PARAM_ACCOUNT) as Account isOtherAccount = me.id != account.id account } else { me } } } private val component: AccountComponent by lazy{ DaggerAccountComponent.builder() .applicationComponent((application as App).component) .activityModule(ActivityModule(this)) .build() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_account) component.inject(this) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) if (savedInstanceState == null) { account.compose(bindToLifecycle()).subscribe { account, error -> supportFragmentManager.beginTransaction().apply { val fragment = AccountFragment.newInstance(account) replace(R.id.layout_list, fragment) }.commit() } } initView() } private fun initView() { account.subscribe { account, error -> if (error != null) { showError(error) return@subscribe } layout_appbar.addOnOffsetChangedListener(AppBarOffsetChangedListener(layout_collapsing_toolbar, account.preparedDisplayName ?: " ")) Picasso.with(this) .load(account.avatar) .transform(AvatarTransformation(ContextCompat.getColor(this, R.color.content_border))) .into(image_avatar) if (account.header?.isNotEmpty() ?: false) { Picasso.with(this) .load(account.header) .transform(BlurTransformation(this)) .into(image_header) } text_accont_name.text = account.preparedDisplayName text_account_description.text = account.note?.asHtml() text_account_description.movementMethod = LinkMovementMethod.getInstance() presenter.relationship(account) .subscribe { rel, error -> if (error != null) { showError(error) return@subscribe } relationship = rel text_followed_you.visibility = if (rel.followedBy) View.VISIBLE else View.GONE invalidateOptionsMenu() } image_header.viewTreeObserver.addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { loadHeaderImage(image_header.width, image_header.height) image_header.viewTreeObserver.removeOnGlobalLayoutListener(this) } }) } } override fun onPrepareOptionsMenu(menu: Menu?): Boolean { if (relationship != null && isOtherAccount) { if (relationship?.following ?: false) { menu?.removeItem(R.id.menu_follow) } else { menu?.removeItem(R.id.menu_unfollow) } } else { menu?.clear() } return super.onPrepareOptionsMenu(menu) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_account, menu) return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item != null) { when (item.itemId) { R.id.menu_follow -> { account.flatMap { account -> presenter.follow(account) }.subscribe { rel, error -> if (error != null) { showError(error) return@subscribe } relationship = rel invalidateOptionsMenu() } return true } R.id.menu_unfollow -> { account.flatMap { account -> presenter.unfollow(account) }.subscribe { rel, error -> if (error != null) { showError(error) return@subscribe } relationship = rel invalidateOptionsMenu() } return true } android.R.id.home -> { onBackPressed() return true } else -> return false } } else { return false } } private fun loadHeaderImage(width: Int, height: Int) { account.subscribe { account -> if (account.header?.isNotEmpty() ?: false) { Picasso.with(this) .load(account.header) .resize(width, height) .centerCrop() .transform(BlurTransformation(this)) .into(image_header) } } } private fun showError(error: Throwable) { Snackbar.make(layout_content, error.preparedErrorMessage(this), Snackbar.LENGTH_LONG).show() } internal class AppBarOffsetChangedListener(val collapsingLayout: CollapsingToolbarLayout, val title: String) : AppBarLayout.OnOffsetChangedListener { private var isShow: Boolean = false private var scrollRange: Int = -1 override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) { if (scrollRange == -1) { scrollRange = appBarLayout?.totalScrollRange ?: -1 } if (scrollRange + (verticalOffset) == 0) { collapsingLayout.title = title isShow = true } else { collapsingLayout.title = " " isShow = false } } } }
app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/activity/AccountActivity.kt
3176890716
package com.idapgroup.android.mvp.impl import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.idapgroup.android.mvp.LceView import com.idapgroup.android.mvp.MvpPresenter /** Fragment for displaying loading states(load, content, error) */ abstract class LcePresenterActivity<V, out P : MvpPresenter<V>> : BasePresenterActivity<V, P>(), LceView { protected val lceViewHandler = LceViewHandler() open val lceViewCreator: LceViewCreator = SimpleLceViewCreator({ inflater, container -> onCreateContentView(inflater, container) }) abstract fun onCreateContentView(inflater: LayoutInflater, container: ViewGroup): View override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(lceViewHandler, lceViewCreator) } override fun showLoad() { lceViewHandler.showLoad() } override fun showContent() { lceViewHandler.showContent() } override fun showError(errorMessage: String, retry : (() -> Unit)?) { lceViewHandler.showError(errorMessage, retry) } }
mvp/src/main/java/com/idapgroup/android/mvp/impl/LcePresenterActivity.kt
1503504096
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.activity.robots import androidx.test.uiautomator.By import androidx.test.uiautomator.UiSelector import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.mozilla.focus.R import org.mozilla.focus.helpers.TestHelper.getStringResource import org.mozilla.focus.helpers.TestHelper.mDevice import org.mozilla.focus.helpers.TestHelper.packageName import org.mozilla.focus.helpers.TestHelper.pressEnterKey import org.mozilla.focus.helpers.TestHelper.waitingTime import org.mozilla.focus.idlingResources.SessionLoadedIdlingResource class SearchRobot { fun verifySearchBarIsDisplayed() = assertTrue(searchBar.exists()) fun typeInSearchBar(searchString: String) { assertTrue(searchBar.waitForExists(waitingTime)) searchBar.clearTextField() searchBar.text = searchString } // Would you like to turn on search suggestions? Yes No // fresh install only fun allowEnableSearchSuggestions() { if (searchSuggestionsTitle.waitForExists(waitingTime)) { searchSuggestionsButtonYes.waitForExists(waitingTime) searchSuggestionsButtonYes.click() } } // Would you like to turn on search suggestions? Yes No // fresh install only fun denyEnableSearchSuggestions() { if (searchSuggestionsTitle.waitForExists(waitingTime)) { searchSuggestionsButtonNo.waitForExists(waitingTime) searchSuggestionsButtonNo.click() } } fun verifySearchSuggestionsAreShown() { suggestionsList.waitForExists(waitingTime) assertTrue(suggestionsList.childCount >= 1) } fun verifySearchSuggestionsAreNotShown() { assertFalse(suggestionsList.exists()) } fun verifySearchEditBarContainsText(text: String) { mDevice.findObject(UiSelector().textContains(text)).waitForExists(waitingTime) assertTrue(searchBar.text.equals(text)) } fun verifySearchEditBarIsEmpty() { searchBar.waitForExists(waitingTime) assertTrue(searchBar.text.equals(getStringResource(R.string.urlbar_hint))) } fun clickToolbar() { toolbar.waitForExists(waitingTime) toolbar.click() } fun longPressSearchBar() { searchBar.waitForExists(waitingTime) searchBar.longClick() } fun clearSearchBar() = clearSearchButton.click() fun verifySearchSuggestionsContain(title: String) { assertTrue( suggestionsList.getChild(UiSelector().textContains(title)).waitForExists(waitingTime), ) } class Transition { private lateinit var sessionLoadedIdlingResource: SessionLoadedIdlingResource fun loadPage(url: String, interact: BrowserRobot.() -> Unit): BrowserRobot.Transition { val geckoEngineView = mDevice.findObject(UiSelector().resourceId("$packageName:id/engineView")) val trackingProtectionDialog = mDevice.findObject(UiSelector().resourceId("$packageName:id/message")) sessionLoadedIdlingResource = SessionLoadedIdlingResource() searchScreen { typeInSearchBar(url) } pressEnterKey() runWithIdleRes(sessionLoadedIdlingResource) { assertTrue( BrowserRobot().progressBar.waitUntilGone(waitingTime), ) assertTrue( geckoEngineView.waitForExists(waitingTime) || trackingProtectionDialog.waitForExists(waitingTime), ) } BrowserRobot().interact() return BrowserRobot.Transition() } fun pasteAndLoadLink(interact: BrowserRobot.() -> Unit): BrowserRobot.Transition { var currentTries = 0 while (currentTries++ < 3) { try { mDevice.findObject(UiSelector().textContains("Paste")).waitForExists(waitingTime) val pasteText = mDevice.findObject(By.textContains("Paste")) pasteText.click() mDevice.pressEnter() break } catch (e: NullPointerException) { SearchRobot().longPressSearchBar() } } BrowserRobot().interact() return BrowserRobot.Transition() } } } fun searchScreen(interact: SearchRobot.() -> Unit): SearchRobot.Transition { SearchRobot().interact() return SearchRobot.Transition() } private val searchBar = mDevice.findObject(UiSelector().resourceId("$packageName:id/mozac_browser_toolbar_edit_url_view")) private val toolbar = mDevice.findObject(UiSelector().resourceId("$packageName:id/mozac_browser_toolbar_url_view")) private val searchSuggestionsTitle = mDevice.findObject( UiSelector() .resourceId("$packageName:id/enable_search_suggestions_title") .enabled(true), ) private val searchSuggestionsButtonYes = mDevice.findObject( UiSelector() .resourceId("$packageName:id/enable_search_suggestions_button") .enabled(true), ) private val searchSuggestionsButtonNo = mDevice.findObject( UiSelector() .resourceId("$packageName:id/disable_search_suggestions_button") .enabled(true), ) private val suggestionsList = mDevice.findObject( UiSelector() .resourceId("$packageName:id/search_suggestions_view"), ) private val clearSearchButton = mDevice.findObject(UiSelector().resourceId("$packageName:id/mozac_browser_toolbar_clear_view"))
app/src/androidTest/java/org/mozilla/focus/activity/robots/SearchRobot.kt
2511434275
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.mediasample.ui.util import android.app.Activity import android.view.View import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.platform.LocalView import androidx.core.view.doOnPreDraw // From https://github.com/androidx/androidx/blob/42d58ade87b9338c563ee8f182057a7da93f5c78/compose/integration-tests/macrobenchmark-target/src/main/java/androidx/compose/integration/macrobenchmark/target/FullyDrawnStartupActivity.kt @Composable fun ReportFullyDrawn() { val localView: View = LocalView.current SideEffect { val activity = localView.context as? Activity if (activity != null) { localView.doOnPreDraw { activity.reportFullyDrawn() } } } }
media-sample/src/main/java/com/google/android/horologist/mediasample/ui/util/ReportFullyDrawn.kt
238558901
package ktsearch import org.junit.Test import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import java.io.File /** * @author cary on 7/30/16. */ class SearcherTest { private fun getSettings(): SearchSettings { return getDefaultSettings().copy(startPath=".", searchPatterns=setOf(Regex("Searcher"))) } private val testFilePath = "/testFile2.txt" /*************************************************************************** * filterFile tests **************************************************************************/ @Test fun testFilterFile_IsHidden_False() { val settings = getSettings() val searcher = Searcher(settings) val file = File(".gitignore") assertEquals(null, searcher.filterToSearchFile(file)) } @Test fun testFilterFile_IsHiddenIncludeHidden_True() { val settings = getSettings().copy(excludeHidden = false) val searcher = Searcher(settings) val file = File(".gitignore") val searchFile = SearchFile(file, FileType.TEXT) assertEquals(searchFile, searcher.filterToSearchFile(file)) } @Test fun testFilterFile_ArchiveNoSearchArchives_False() { val settings = getSettings() val searcher = Searcher(settings) val file = File("archive.zip") assertEquals(null, searcher.filterToSearchFile(file)) } @Test fun testFilterFile_ArchiveSearchArchives_True() { val settings = getSettings().copy(searchArchives = true) val searcher = Searcher(settings) val file = File("archive.zip") val searchFile = SearchFile(file, FileType.ARCHIVE) assertEquals(searchFile, searcher.filterToSearchFile(file)) } @Test fun testFilterFile_IsArchiveSearchFile_True() { val settings = getSettings().copy(searchArchives = true, inArchiveExtensions = setOf("zip")) val searcher = Searcher(settings) val file = File("archive.zip") val searchFile = SearchFile(file, FileType.ARCHIVE) assertEquals(searchFile, searcher.filterToSearchFile(file)) } @Test fun testFilterFile_NotIsArchiveSearchFile_False() { val settings = getSettings().copy(outExtensions = setOf("zip")) val searcher = Searcher(settings) val file = File("archive.zip") assertEquals(null, searcher.filterToSearchFile(file)) } @Test fun testFilterFile_ArchiveFileArchivesOnly_True() { val settings = getSettings().copy(archivesOnly = true) val searcher = Searcher(settings) val file = File("archive.zip") val searchFile = SearchFile(file, FileType.ARCHIVE) assertEquals(searchFile, searcher.filterToSearchFile(file)) } @Test fun testFilterFile_NoExtensionsNoPatterns_True() { val settings = getSettings() val searcher = Searcher(settings) val file = File("FileUtil.cs") val searchFile = SearchFile(file, FileType.TEXT) assertEquals(searchFile, searcher.filterToSearchFile(file)) } @Test fun testFilterFile_IsSearchFile_True() { val settings = getSettings().copy(inExtensions = setOf("cs")) val searcher = Searcher(settings) val file = File("FileUtil.cs") val searchFile = SearchFile(file, FileType.TEXT) assertEquals(searchFile, searcher.filterToSearchFile(file)) } @Test fun testFilterFile_NotIsSearchFile_False() { val settings = getSettings().copy(outExtensions = setOf("cs")) val searcher = Searcher(settings) val file = File("FileUtil.cs") assertEquals(null, searcher.filterToSearchFile(file)) } @Test fun testFilterFile_NonArchiveFileArchivesOnly_False() { val settings = getSettings().copy(archivesOnly = true) val searcher = Searcher(settings) val file = File("FileUtil.cs") assertEquals(null, searcher.filterToSearchFile(file)) } /*************************************************************************** * isSearchDir tests **************************************************************************/ @Test fun testisSearchDir_SingleDot_True() { val settings = getSettings() val searcher = Searcher(settings) assertTrue(searcher.isSearchDir(File("."))) } @Test fun testisSearchDir_DoubleDot_True() { val settings = getSettings() val searcher = Searcher(settings) assertTrue(searcher.isSearchDir(File(".."))) } @Test fun testisSearchDir_IsHidden_False() { val settings = getSettings() val searcher = Searcher(settings) assertFalse(searcher.isSearchDir(File(".git"))) } @Test fun testisSearchDir_IsHiddenIncludeHidden_True() { val settings = getSettings().copy(excludeHidden = false) val searcher = Searcher(settings) assertTrue(searcher.isSearchDir(File(".git"))) } @Test fun testisSearchDir_NoPatterns_True() { val settings = getSettings() val searcher = Searcher(settings) assertTrue(searcher.isSearchDir(File("/Users"))) } @Test fun testisSearchDir_MatchesInPattern_True() { val settings = getSettings().copy(inDirPatterns = setOf(Regex("Search"))) val searcher = Searcher(settings) assertTrue(searcher.isSearchDir(File("CsSearch"))) } @Test fun testisSearchDir_MatchesOutPattern_False() { val settings = getSettings().copy(outDirPatterns = setOf(Regex("Search"))) val searcher = Searcher(settings) assertFalse(searcher.isSearchDir(File("CsSearch"))) } @Test fun testisSearchDir_DoesNotMatchInPattern_False() { val settings = getSettings().copy(inDirPatterns = setOf(Regex("SearchFiles"))) val searcher = Searcher(settings) assertFalse(searcher.isSearchDir(File("CsSearch"))) } @Test fun testisSearchDir_DoesNotMatchOutPattern_True() { val settings = getSettings().copy(outDirPatterns = setOf(Regex("SearchFiles"))) val searcher = Searcher(settings) val dir = File("CsSearch") assertTrue(searcher.isSearchDir(dir)) } /*************************************************************************** * isSearchFile tests **************************************************************************/ @Test fun testIsSearchFile_NoExtensionsNoPatterns_True() { val settings = getSettings() val searcher = Searcher(settings) val file = SearchFile(File("FileUtil.cs"), FileType.CODE) assertTrue(searcher.isSearchFile(file)) } @Test fun testIsSearchFile_MatchesInExtension_True() { val settings = getSettings().copy(inExtensions = setOf("cs")) val searcher = Searcher(settings) val file = SearchFile(File("FileUtil.cs"), FileType.CODE) assertTrue(searcher.isSearchFile(file)) } @Test fun testIsSearchFile_DoesNotMatchInExtension_False() { val settings = getSettings().copy(inExtensions = setOf("java")) val searcher = Searcher(settings) val file = SearchFile(File("FileUtil.cs"), FileType.CODE) assertFalse(searcher.isSearchFile(file)) } @Test fun testIsSearchFile_MatchesOutExtension_False() { val settings = getSettings().copy(outExtensions = setOf("cs")) val searcher = Searcher(settings) val file = SearchFile(File("FileUtil.cs"), FileType.CODE) assertFalse(searcher.isSearchFile(file)) } @Test fun testIsSearchFile_DoesNotMatchOutExtension_True() { val settings = getSettings().copy(outExtensions = setOf("java")) val searcher = Searcher(settings) val file = SearchFile(File("FileUtil.cs"), FileType.CODE) assertTrue(searcher.isSearchFile(file)) } @Test fun testIsSearchFile_MatchesInPattern_True() { val settings = getSettings().copy(inFilePatterns = setOf(Regex("Search"))) val searcher = Searcher(settings) val file = SearchFile(File("Searcher.cs"), FileType.CODE) assertTrue(searcher.isSearchFile(file)) } @Test fun testIsSearchFile_DoesNotMatchInPattern_False() { val settings = getSettings().copy(inFilePatterns = setOf(Regex("Search"))) val searcher = Searcher(settings) val file = SearchFile(File("FileUtil.cs"), FileType.CODE) assertFalse(searcher.isSearchFile(file)) } @Test fun testIsSearchFile_MatchesOutPattern_False() { val settings = getSettings().copy(outFilePatterns = setOf(Regex("Search"))) val searcher = Searcher(settings) val file = SearchFile(File("Searcher.cs"), FileType.CODE) assertFalse(searcher.isSearchFile(file)) } @Test fun testIsSearchFile_DoesNotMatchOutPattern_True() { val settings = getSettings().copy(outFilePatterns = setOf(Regex("Search"))) val searcher = Searcher(settings) val file = SearchFile(File("FileUtil.cs"), FileType.CODE) assertTrue(searcher.isSearchFile(file)) } /*************************************************************************** * isArchiveSearchFile tests **************************************************************************/ @Test fun testIsArchiveSearchFile_NoExtensionsNoPatterns_True() { val settings = getSettings() val searcher = Searcher(settings) val file = SearchFile(File("archive.zip"), FileType.ARCHIVE) assertTrue(searcher.isArchiveSearchFile(file)) } @Test fun testIsArchiveSearchFile_MatchesInExtension_True() { val settings = getSettings().copy(inArchiveExtensions = setOf("zip")) val searcher = Searcher(settings) val file = SearchFile(File("archive.zip"), FileType.ARCHIVE) assertTrue(searcher.isArchiveSearchFile(file)) } @Test fun testIsArchiveSearchFile_DoesNotMatchInExtension_False() { val settings = getSettings().copy(inArchiveExtensions = setOf("gz")) val searcher = Searcher(settings) val file = SearchFile(File("archive.zip"), FileType.ARCHIVE) assertFalse(searcher.isArchiveSearchFile(file)) } @Test fun testIsArchiveSearchFile_MatchesOutExtension_False() { val settings = getSettings().copy(outArchiveExtensions = setOf("zip")) val searcher = Searcher(settings) val file = SearchFile(File("archive.zip"), FileType.ARCHIVE) assertFalse(searcher.isArchiveSearchFile(file)) } @Test fun testIsArchiveSearchFile_DoesNotMatchOutExtension_True() { val settings = getSettings().copy(outArchiveExtensions = setOf("gz")) val searcher = Searcher(settings) val file = SearchFile(File("archive.zip"), FileType.ARCHIVE) assertTrue(searcher.isArchiveSearchFile(file)) } @Test fun testIsArchiveSearchFile_MatchesInPattern_True() { val settings = getSettings().copy(inArchiveFilePatterns = setOf(Regex("arch"))) val searcher = Searcher(settings) val file = SearchFile(File("archive.zip"), FileType.ARCHIVE) assertTrue(searcher.isArchiveSearchFile(file)) } @Test fun testIsArchiveSearchFile_DoesNotMatchInPattern_False() { val settings = getSettings().copy(inArchiveFilePatterns = setOf(Regex("archives"))) val searcher = Searcher(settings) val file = SearchFile(File("archive.zip"), FileType.ARCHIVE) assertFalse(searcher.isArchiveSearchFile(file)) } @Test fun testIsArchiveSearchFile_MatchesOutPattern_False() { val settings = getSettings().copy(outArchiveFilePatterns = setOf(Regex("arch"))) val searcher = Searcher(settings) val file = SearchFile(File("archive.zip"), FileType.ARCHIVE) assertFalse(searcher.isArchiveSearchFile(file)) } @Test fun testIsArchiveSearchFile_DoesNotMatchOutPattern_True() { val settings = getSettings().copy(outArchiveFilePatterns = setOf(Regex("archives"))) val searcher = Searcher(settings) val file = SearchFile(File("archive.zip"), FileType.ARCHIVE) assertTrue(searcher.isArchiveSearchFile(file)) } /*************************************************************************** * searchStringIterator tests **************************************************************************/ @Test fun testSearchStringIterator() { val settings = getSettings() val searcher = Searcher(settings) val lineIterator = javaClass.getResourceAsStream(testFilePath).reader().readLines().iterator() val results = searcher.searchLineIterator(lineIterator) assertEquals(results.size.toLong(), 2) val firstResult = results[0] val expectedFirstLineNum = 29 assertEquals(firstResult.lineNum, expectedFirstLineNum) val expectedFirstMatchStartIndex = 3 assertEquals(firstResult.matchStartIndex, expectedFirstMatchStartIndex) val expectedFirstMatchEndIndex = 11 assertEquals(firstResult.matchEndIndex, expectedFirstMatchEndIndex) val secondResult = results[1] val expectedSecondLineNum = 35 assertEquals(secondResult.lineNum, expectedSecondLineNum) val expectedSecondMatchStartIndex = 24 assertEquals(secondResult.matchStartIndex, expectedSecondMatchStartIndex) val expectedSecondMatchEndIndex = 32 assertEquals(secondResult.matchEndIndex, expectedSecondMatchEndIndex) } /*************************************************************************** * searchMultiLineString tests **************************************************************************/ @Test fun testSearchMultiLineString() { val settings = getSettings() val searcher = Searcher(settings) val contents = javaClass.getResourceAsStream(testFilePath).reader().readText() val results = searcher.searchMultilineString(contents) assertEquals(results.size.toLong(), 2) val firstResult = results[0] val expectedFirstLineNum = 29 assertEquals(firstResult.lineNum, expectedFirstLineNum) val expectedFirstMatchStartIndex = 3 assertEquals(firstResult.matchStartIndex, expectedFirstMatchStartIndex) val expectedFirstMatchEndIndex = 11 assertEquals(firstResult.matchEndIndex, expectedFirstMatchEndIndex) val secondResult = results[1] val expectedSecondLineNum = 35 assertEquals(secondResult.lineNum, expectedSecondLineNum) val expectedSecondMatchStartIndex = 24 assertEquals(secondResult.matchStartIndex, expectedSecondMatchStartIndex) val expectedSecondMatchEndIndex = 32 assertEquals(secondResult.matchEndIndex, expectedSecondMatchEndIndex) } @Test fun testSearchMultiLineStringWithLinesBefore() { val settings = getSettings().copy(linesBefore = 2) val searcher = Searcher(settings) val contents = javaClass.getResourceAsStream(testFilePath).reader().readText() val results = searcher.searchMultilineString(contents) assertEquals(results.size.toLong(), 2) val firstResult = results[0] val expectedFirstLineNum = 29 assertEquals(firstResult.lineNum, expectedFirstLineNum) val expectedFirstMatchStartIndex = 3 assertEquals(firstResult.matchStartIndex, expectedFirstMatchStartIndex) val expectedFirstMatchEndIndex = 11 assertEquals(firstResult.matchEndIndex, expectedFirstMatchEndIndex) val secondResult = results[1] val expectedSecondLineNum = 35 assertEquals(secondResult.lineNum, expectedSecondLineNum) val expectedSecondMatchStartIndex = 24 assertEquals(secondResult.matchStartIndex, expectedSecondMatchStartIndex) val expectedSecondMatchEndIndex = 32 assertEquals(secondResult.matchEndIndex, expectedSecondMatchEndIndex) } }
kotlin/ktsearch/src/test/kotlin/ktsearch/SearcherTest.kt
2946854507
package org.wordpress.android.fluxc.model import com.yarolegovich.wellsql.core.Identifiable import com.yarolegovich.wellsql.core.annotation.Column import com.yarolegovich.wellsql.core.annotation.PrimaryKey import com.yarolegovich.wellsql.core.annotation.Table import org.wordpress.android.fluxc.persistence.WellSqlConfig @Table(addOn = WellSqlConfig.ADDON_WOOCOMMERCE) data class WCOrderStatusModel(@PrimaryKey @Column private var id: Int = 0) : Identifiable { constructor(statusKey: String) : this() { this.statusKey = statusKey } @Column var localSiteId = 0 @Column var statusKey = "" @Column var label = "" @Column var statusCount = 0 override fun setId(id: Int) { this.id = id } override fun getId() = id }
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/model/WCOrderStatusModel.kt
697276027
package org.algo4j.win import org.algo4j.test.println import org.algo4j.util.Loader import org.jetbrains.annotations.TestOnly import org.junit.BeforeClass /** * Created by ice1000 on 2016/12/18. * @author ice1000 */ object WinAPITest { /** * from http://blog.csdn.net/kevin1491/article/details/49837289 * 小酒窝/长睫毛/迷人的无可救药 */ @TestOnly fun beepXiaoJiuWo() { listOf(Pair(659, 625), Pair(659, 250), Pair(698, 500), Pair(659, 250), Pair(578, 250), Pair(578, 625), Pair(578, 250), Pair(784, 500), Pair(578, 250), Pair(523, 250), Pair(523, 625), Pair(523, 250), Pair(880, 500), Pair(784, 500), Pair(659, 625), Pair(698, 125), Pair(659, 125), Pair(578, 500), Pair(578, 500), Pair(659, 625), Pair(659, 250), Pair(698, 500), Pair(784, 250), Pair(659, 250), Pair(784, 625), Pair(784, 250), Pair(1175, 500), Pair(988, 250), Pair(1046, 250), Pair(1046, 1000), Pair(1046, 250), Pair(988, 250), Pair(880, 250), Pair(988, 250), Pair(1046, 625), Pair(988, 250), Pair(1046, 1000), Pair(1046, 250), Pair(988, 250), Pair(1046, 250), Pair(988, 250), Pair(1046, 500), Pair(659, 250), Pair(784, 250), Pair(784, 1250), Pair(880, 250), Pair(988, 250), Pair(1046, 250), Pair(988, 250), Pair(1046, 250), Pair(988, 250), Pair(1046, 500), Pair(1175, 500), Pair(1318, 500), Pair(1318, 1500), Pair(880, 250), Pair(988, 250), Pair(1046, 250), Pair(988, 250), Pair(1046, 250), Pair(988, 250), Pair(1046, 500), Pair(1318, 500), Pair(988, 250), Pair(880, 250), Pair(988, 250), Pair(880, 250), Pair(988, 250), Pair(784, 250), Pair(784, 250), Pair(1046, 250), Pair(1046, 1000), Pair(1318, 375), Pair(1397, 125), Pair(1397, 250), Pair(1318, 250), Pair(1175, 1000), Pair(0, 250), Pair(784, 250), Pair(1046, 250), Pair(1175, 250), Pair(1318, 250), Pair(1046, 250), Pair(1046, 250), Pair(784, 250), Pair(784, 500), Pair(784, 250), Pair(1318, 250), Pair(1175, 250), Pair(1318, 250), Pair(1175, 250), Pair(1046, 250), Pair(784, 250), Pair(784, 250), Pair(880, 250), Pair(988, 250), Pair(1046, 250), Pair(880, 250), Pair(880, 250), Pair(659, 250), Pair(659, 500), Pair(0, 250), Pair(988, 250), Pair(1046, 250), Pair(988, 250), Pair(1046, 250), Pair(1175, 250), Pair(880, 250), Pair(784, 250), Pair(784, 500), Pair(880, 500), Pair(784, 250), Pair(880, 250), Pair(988, 500), Pair(1318, 250), Pair(1397, 250), Pair(1318, 250), Pair(1397, 250), Pair(1318, 250), Pair(1175, 250), Pair(1175, 250), Pair(1046, 500), Pair(784, 250), Pair(784, 250), Pair(698, 250), Pair(698, 250), Pair(1046, 250), Pair(1046, 250), Pair(1318, 250), Pair(1318, 250), Pair(1046, 250), Pair(1175, 1000), Pair(0, 250), Pair(784, 250), Pair(1046, 250), Pair(1175, 250), Pair(1318, 250), Pair(1046, 250), Pair(1046, 250), Pair(784, 250), Pair(784, 500), Pair(784, 250), Pair(1318, 250), Pair(1175, 250), Pair(1318, 250), Pair(1175, 250), Pair(1046, 250), Pair(784, 250), Pair(784, 250), Pair(880, 250), Pair(988, 250), Pair(1046, 250), Pair(880, 250), Pair(880, 250), Pair(659, 250), Pair(659, 500), Pair(659, 250), Pair(988, 250), Pair(1046, 250), Pair(988, 250), Pair(1046, 250), Pair(1175, 250), Pair(880, 250), Pair(784, 250), Pair(784, 500), Pair(880, 250), Pair(988, 250), Pair(1046, 250), Pair(1175, 500), Pair(1318, 250), Pair(1397, 250), Pair(1318, 250), Pair(1397, 250), Pair(1175, 250), Pair(1046, 250), Pair(1175, 250), Pair(1046, 250), Pair(1046, 500), Pair(1175, 250), Pair(1046, 250), Pair(1175, 250), Pair(880, 250), Pair(1046, 500), Pair(1175, 250), Pair(1046, 250), Pair(1046, 2000), Pair(1175, 250), Pair(1046, 250), Pair(1175, 250), Pair(880, 250), Pair(988, 500), Pair(988, 250), Pair(1046, 250), Pair(1046, 2000)) .forEach { (freq, dur) -> WinAPI.beep(freq, dur) } } /** * from http://www.cnblogs.com/morewindows/archive/2011/08/15/2139544.html * 祝你生日快乐 */ @TestOnly fun beep2() { listOf(392, 392, 440, 392, 523, 494, 392, 392, 440, 392, 587, 523, 392, 392, 784, 659, 523, 494, 440, 689, 689, 523, 587, 523 ).zip(listOf( 375, 125, 500, 500, 500, 1000, 375, 125, 500, 500, 500, 1000, 375, 125, 500, 500, 500, 500, 1000, 375, 125, 500, 500, 500, 1000 )).forEach { (freq, dur) -> WinAPI.beep(freq, dur) } } @TestOnly fun messageBoxA() { WinAPI.messageBoxA("ass we can", "boy next door", WinAPI.MessageBoxType.MB_ICONSTOP) .println() WinAPI.messageBoxA("deep dark fantasy", "oh my shoulder", WinAPI.MessageBoxType.MB_DEFBUTTON3) .println() WinAPI.messageBoxA("hey boy", "you get the wrong door", WinAPI.MessageBoxType.MB_DEFBUTTON3) .println() WinAPI.messageBoxA("fuck you", "ah fuck you", WinAPI.MessageBoxType.MB_HELP) .println() WinAPI.messageBoxA("change the", "boss of this gym", WinAPI.MessageBoxType.MB_DEFMASK) .println() } @JvmStatic @BeforeClass fun init() { Loader.loadJni() } fun batteryStatus() { WinAPI.getSystemPowerStatus().run { println("电源状态: $acLineStatus ") println("电池状态: $batteryFlag ") println("电量百分比: $batteryLifePercent %") println("剩余电量: $batteryLifeTime s") println("总电量: $batteryFullLifeTime s") } } @JvmStatic fun main(args: Array<String>) { init() batteryStatus() messageBoxA() beep2() // beepXiaoJiuWo() } }
src/test/kotlin/org/algo4j/win/WinAPITest.kt
402212245
package com.eden.orchid.posts import com.eden.orchid.testhelpers.OrchidIntegrationTest import com.eden.orchid.testhelpers.nothingRendered import com.eden.orchid.testhelpers.pageWasRendered import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import strikt.api.expectThat @DisplayName("Tests page-rendering behavior of Posts generator") class PostsGeneratorTest : OrchidIntegrationTest(PostsModule()) { @Test @DisplayName("Files, formatted correctly in the `posts` directory, gets rendered correctly without any configuration.") fun test01() { resource("posts/2018-01-01-post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/2018/1/1/post-one/index.html") } @Test @DisplayName("Files, formatted correctly in the `posts/{year}` directory, gets rendered correctly without any configuration.") fun test02() { resource("posts/2018/01-01-post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/2018/1/1/post-one/index.html") } @Test @DisplayName("Files, formatted correctly in the `posts/{year}/{month}` directory, get rendered correctly without any configuration.") fun test03() { resource("posts/2018/01/01-post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/2018/1/1/post-one/index.html") } @Test @DisplayName("Files, formatted correctly in the `posts/{year}/{month}/{day}` directory, get rendered correctly without any configuration.") fun test04() { resource("posts/2018/01/01/post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/2018/1/1/post-one/index.html") } @Test @DisplayName("The `permalink` can be set in a post's options.") fun test05() { resource("posts/2018-01-01-post-one.md", "", mapOf("permalink" to "blog/:year/:month/:slug")) val testResults = execute() expectThat(testResults).pageWasRendered("/blog/2018/1/post-one/index.html") } @Test @DisplayName("The `permalink` can be set in `defaultOptions`, which is applied to all posts by default.") fun test06() { configObject("posts", """{"defaultConfig": {"permalink": "blog/:year/:month/:slug"}}""") resource("posts/2018-01-01-post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/blog/2018/1/post-one/index.html") } @Test @DisplayName("The `permalink` in a post's options overrides the one set in `defaultOptions`.") fun test07() { configObject("posts", """{"defaultConfig": {"permalink": "defaultConfig/:year/:month/:slug"}}""") resource("posts/2018-01-01-post-one.md", "", mapOf("permalink" to "postConfig/:year/:month/:slug")) val testResults = execute() expectThat(testResults).pageWasRendered("/postConfig/2018/1/post-one/index.html") } @Test @DisplayName("Posts supports multiple categories. Setting a category as a string value uses all category defaults.") fun tet08() { configObject("posts", """{"categories": ["cat1", "cat2"]}""") resource("posts/cat1/2018-01-01-post-one.md") resource("posts/cat2/2018-02-02-post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/cat1/2018/1/1/post-one/index.html") expectThat(testResults).pageWasRendered("/cat2/2018/2/2/post-one/index.html") } @Test @DisplayName("Posts supports multiple categories. You can list each category as an Object to customize its options.") fun test09() { configObject("posts", """{"categories": [{"cat1": {}}, {"cat2": {}}]}""") resource("posts/cat1/2018-01-01-post-one.md") resource("posts/cat2/2018-02-02-post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/cat1/2018/1/1/post-one/index.html") expectThat(testResults).pageWasRendered("/cat2/2018/2/2/post-one/index.html") } @Test @DisplayName("Posts supports multiple categories. Rather than a list for the categories, you can use a single Object, where each key points to the options for the value, to query easily.") fun test10() { configObject("posts", """ {"categories": {"cat1": {}, "cat2": {}}}""") resource("posts/cat1/2018-01-01-post-one.md") resource("posts/cat2/2018-02-02-post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/cat1/2018/1/1/post-one/index.html") expectThat(testResults).pageWasRendered("/cat2/2018/2/2/post-one/index.html") } @Test @DisplayName("Categories can be hierarchical, by using a path rather than just a key.") fun test11() { configObject("posts", """{"categories": ["cat1", "cat1/cat2"]}""") resource("posts/cat1/2018-01-01-post-one.md") resource("posts/cat1/cat2/2018-02-02-post-one.md") val testResults = execute() expectThat(testResults).pageWasRendered("/cat1/2018/1/1/post-one/index.html") expectThat(testResults).pageWasRendered("/cat1/cat2/2018/2/2/post-one/index.html") } @Test @DisplayName("Hierarchical categories must have every category level individually-defined.") fun test12() { configObject("posts", """{"categories": ["cat1", "cat2/cat3"]}""") resource("posts/cat1/2018-01-01-post-one.md") resource("posts/cat1/cat2/2018-02-02-post-one.md") val testResults = execute() expectThat(testResults).nothingRendered() } @Test @DisplayName("Authors can be specified both in post config, and as files in the 'posts/authors/' directory.") fun test13() { configObject("posts", """{"authors": ["author-one"]}""") resource("posts/authors/author-two.md", "", "{}") val testResults = execute() expectThat(testResults).pageWasRendered("/authors/author-one/index.html") expectThat(testResults).pageWasRendered("/authors/author-two/index.html") } @Test @DisplayName("Authors can be specified both in post config as objects as well as Strings.") fun test14() { configObject("posts", """{"authors": ["Author One", {"name": "Author Two", "email": "[email protected]"}]}""") val testResults = execute() expectThat(testResults).pageWasRendered("/authors/author-one/index.html") expectThat(testResults).pageWasRendered("/authors/author-two/index.html") } @Test @DisplayName("The Posts generator finishes successfully when there are no resources for it.") fun test15() { val testResults = execute() expectThat(testResults).nothingRendered() } @Test @DisplayName("The Wiki generator finishes successfully when there are no resources for it, when using multiple categories.") fun test16() { configObject("posts", """{"categories": ["cat1", "cat2/cat3"]}""") val testResults = execute() expectThat(testResults).nothingRendered() } }
plugins/OrchidPosts/src/test/kotlin/com/eden/orchid/posts/PostsGeneratorTest.kt
4065408739
package us.mikeandwan.photos object Constants { const val API_BASE_URL = "https://apidev.mikeandwan.us:5011" const val AUTH_BASE_URL = "https://authdev.mikeandwan.us:5001" const val WWW_BASE_URL = "https://wwwdev.mikeandwan.us:5021" }
MaWPhotos/src/development/java/us/mikeandwan/photos/Constants.kt
2769509591
package io.piano.android.composer import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.anyOrNull import com.nhaarman.mockitokotlin2.argumentCaptor import com.nhaarman.mockitokotlin2.doNothing import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.doThrow import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.never import com.nhaarman.mockitokotlin2.spy import com.nhaarman.mockitokotlin2.times import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import io.piano.android.composer.listeners.EventTypeListener import io.piano.android.composer.listeners.ExceptionListener import io.piano.android.composer.listeners.ExperienceExecuteListener import io.piano.android.composer.listeners.ShowTemplateListener import io.piano.android.composer.listeners.UserSegmentListener import io.piano.android.composer.model.Data import io.piano.android.composer.model.Event import io.piano.android.composer.model.EventsContainer import io.piano.android.composer.model.ExperienceRequest import io.piano.android.composer.model.ExperienceResponse import io.piano.android.composer.model.events.EventType import io.piano.android.composer.model.events.ExperienceExecute import io.piano.android.composer.model.events.ShowTemplate import io.piano.android.composer.model.events.UserSegment import okhttp3.ResponseBody import retrofit2.Call import retrofit2.Callback import retrofit2.Response import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith class ComposerTest { private val experienceCall: Call<Data<ExperienceResponse>> = mock() private val composerApi: ComposerApi = mock() { on { getExperience(any()) } doReturn experienceCall } private val generalApi: GeneralApi = mock() private val prefsStorage: PrefsStorage = mock() { on { tpAccessCookie } doReturn DUMMY_STRING } private val httpHelper: HttpHelper = mock() { on { convertExperienceRequest(any(), anyOrNull(), anyOrNull(), anyOrNull()) } doReturn mapOf() on { buildEventTracking(any(), any(), any(), any()) } doReturn mapOf() on { buildShowTemplateParameters( any(), any(), any(), anyOrNull(), anyOrNull() ) } doReturn mapOf( DUMMY_STRING to DUMMY_STRING2 ) } private val composer: Composer = spy( Composer( composerApi, generalApi, httpHelper, prefsStorage, DUMMY_AID, Composer.Endpoint.SANDBOX ) ) private val experienceRequest: ExperienceRequest = mock() private val resultListeners = listOf( mock<ShowTemplateListener>(), mock<UserSegmentListener>() ) private val exceptionListener: ExceptionListener = mock() private fun verifyExceptionListenerArgument(exc: Throwable?, times: Int = 1) { val exceptionCaptor = argumentCaptor<ComposerException>() verify(exceptionListener, times(times)).onException(exceptionCaptor.capture()) with(exceptionCaptor.lastValue) { assertEquals(exc, cause) } } private fun getExperienceWithCallbackCheck(callbackTest: (Callback<Data<ExperienceResponse>>) -> Unit) { doNothing().`when`(composer).processExperienceResponse(any(), any(), any(), any()) composer.getExperience(experienceRequest, resultListeners, exceptionListener) verify(httpHelper).convertExperienceRequest(any(), anyOrNull(), anyOrNull(), anyOrNull()) verify(composerApi).getExperience(any()) val callbackCaptor = argumentCaptor<Callback<Data<ExperienceResponse>>>() verify(experienceCall).enqueue(callbackCaptor.capture()) callbackTest(callbackCaptor.lastValue) } @Test fun emptyAidInit() { assertFailsWith<IllegalArgumentException> { Composer( composerApi, generalApi, httpHelper, prefsStorage, "", Composer.Endpoint.SANDBOX ) } } @Test fun accessToken() { assertEquals(DUMMY_STRING, composer.accessToken) } @Test fun getExperienceResponseException() = getExperienceWithCallbackCheck { val response = Response.success<Data<ExperienceResponse>>(null) it.onResponse(experienceCall, response) verifyExceptionListenerArgument(null) verify(composer, never()).processExperienceResponse(any(), any(), any(), any()) } @Test fun getExperienceResponseContainsErrors() = getExperienceWithCallbackCheck { val response = Response.success( Data<ExperienceResponse>( mock(), listOf( mock(), mock() ) ) ) it.onResponse(experienceCall, response) verifyExceptionListenerArgument(null) verify(composer, never()).processExperienceResponse(any(), any(), any(), any()) } @Test fun getExperienceResponseSuccess() = getExperienceWithCallbackCheck { val experienceResponse: ExperienceResponse = mock() val response = Response.success( Data(experienceResponse, emptyList()) ) it.onResponse(experienceCall, response) verify(composer).processExperienceResponse( experienceRequest, experienceResponse, resultListeners, exceptionListener ) verify(exceptionListener, never()).onException(any()) } @Test fun getExperienceFailure() = getExperienceWithCallbackCheck { val exc = RuntimeException() it.onFailure(experienceCall, exc) verifyExceptionListenerArgument(exc) verify(composer, never()).processExperienceResponse(any(), any(), any(), any()) } @Test fun processExperienceResponse() { val eventTypes = listOf( ShowTemplate("", "", mock(), null, mock(), true), mock<ExperienceExecute>(), mock<UserSegment>() ) val response = ExperienceResponse( null, null, null, 0, 0, null, null, EventsContainer( eventTypes.map { Event(mock(), mock(), it) } ) ) val iterations = eventTypes.size val exc = RuntimeException() val showTemplateListener = mock<ShowTemplateListener>() { on { canProcess(any()) } doReturn true } val experienceExecuteListener = mock<ExperienceExecuteListener>() { on { canProcess(any()) } doReturn false } val userSegmentListener = mock<UserSegmentListener>() { on { canProcess(any()) } doReturn true on { onExecuted(any()) } doThrow exc } val listeners = listOf( showTemplateListener, experienceExecuteListener, userSegmentListener ) composer.processExperienceResponse( experienceRequest, response, listeners, exceptionListener ) verify(httpHelper).afterExecute(experienceRequest, response) verify(showTemplateListener, times(iterations)).canProcess(any()) verify(showTemplateListener, times(iterations)).onExecuted(any()) verify(experienceExecuteListener, times(iterations)).canProcess(any()) verify(experienceExecuteListener, never()).onExecuted(any()) verify(userSegmentListener, times(iterations)).canProcess(any()) verify(userSegmentListener, times(iterations)).onExecuted(any()) verifyExceptionListenerArgument(exc, iterations) } @Test fun processExperienceResponseNoListeners() { val experienceResponse = ExperienceResponse( null, null, null, 0, 0, null, null, EventsContainer(listOf(Event(mock(), mock(), mock()))) ) composer.processExperienceResponse( experienceRequest, experienceResponse, listOf(), exceptionListener ) verify(httpHelper).afterExecute(experienceRequest, experienceResponse) verify(exceptionListener, never()).onException(any()) } @Test fun processExperienceResponseNoEvents() { val response = ExperienceResponse( null, null, null, 0, 0, null, null, EventsContainer(emptyList()) ) composer.processExperienceResponse( experienceRequest, response, resultListeners, exceptionListener ) verify(httpHelper).afterExecute(experienceRequest, response) for (listener in resultListeners) { verify(listener, never()).canProcess(any()) @Suppress("UNCHECKED_CAST") verify(listener as EventTypeListener<EventType>, never()).onExecuted(any()) } verify(exceptionListener, never()).onException(any()) } @Test fun trackExternalEvents() { val call: Call<ResponseBody> = mock() whenever(generalApi.trackExternalEvent(any())).doReturn(call) composer.trackCloseEvent(DUMMY_STRING) verify(httpHelper).buildEventTracking( DUMMY_STRING, Composer.EVENT_TYPE_EXTERNAL_EVENT, Composer.EVENT_GROUP_CLOSE ) composer.trackRecommendationsDisplay(DUMMY_STRING) verify(httpHelper).buildEventTracking( DUMMY_STRING, Composer.EVENT_TYPE_EXTERNAL_EVENT, Composer.EVENT_GROUP_INIT, Composer.CX_CUSTOM_PARAMS ) composer.trackRecommendationsClick(DUMMY_STRING) verify(httpHelper).buildEventTracking( DUMMY_STRING, Composer.EVENT_TYPE_EXTERNAL_LINK, Composer.EVENT_GROUP_CLICK, Composer.CX_CUSTOM_PARAMS ) verify(generalApi, times(3)).trackExternalEvent(any()) verify(call, times(3)).enqueue(any()) } @Test fun trackCustomFormImpression() { val call: Call<ResponseBody> = mock() whenever(generalApi.customFormImpression(any())).doReturn(call) composer.trackCustomFormImpression(DUMMY_STRING, DUMMY_STRING2) verify(httpHelper).buildCustomFormTracking(DUMMY_AID, DUMMY_STRING, DUMMY_STRING2, null) verify(generalApi).customFormImpression(any()) verify(call).enqueue(any()) } @Test fun trackCustomFormSubmission() { val call: Call<ResponseBody> = mock() whenever(generalApi.customFormSubmission(any())).doReturn(call) composer.trackCustomFormSubmission(DUMMY_STRING, DUMMY_STRING2) verify(httpHelper).buildCustomFormTracking(DUMMY_AID, DUMMY_STRING, DUMMY_STRING2, null) verify(generalApi).customFormSubmission(any()) verify(call).enqueue(any()) } companion object { private const val DUMMY_AID = "AID" const val DUMMY_STRING = "DUMMY" const val DUMMY_STRING2 = "DUMMY2" } }
composer/src/test/java/io/piano/android/composer/ComposerTest.kt
3167409703
package com.charlag.promind.ui.component.widget import android.app.IntentService import android.content.Intent /** * Created by charlag on 11/06/2017. */ class ActionService @SuppressWarnings("unused") constructor() : IntentService("ActionSerivce") { override fun onHandleIntent(intent: Intent) { val originalIntent = Intent.parseUri(intent.dataString, Intent.URI_INTENT_SCHEME) startActivity(originalIntent) } }
app/src/main/java/com/charlag/promind/ui/component/widget/ActionService.kt
2169952723
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.data.repositories.shows import app.tivi.data.bodyOrThrow import app.tivi.data.entities.TiviShow import app.tivi.data.mappers.TraktShowToTiviShow import com.uwetrottmann.trakt5.enums.Extended import com.uwetrottmann.trakt5.enums.IdType import com.uwetrottmann.trakt5.enums.Type import com.uwetrottmann.trakt5.services.Search import com.uwetrottmann.trakt5.services.Shows import retrofit2.awaitResponse import javax.inject.Inject import javax.inject.Provider class TraktShowDataSource @Inject constructor( private val showService: Provider<Shows>, private val searchService: Provider<Search>, private val mapper: TraktShowToTiviShow ) : ShowDataSource { override suspend fun getShow(show: TiviShow): TiviShow { var traktId = show.traktId if (traktId == null && show.tmdbId != null) { // We need to fetch the search for the trakt id traktId = searchService.get() .idLookup( IdType.TMDB, show.tmdbId.toString(), Type.SHOW, Extended.NOSEASONS, 1, 1 ) .awaitResponse() .let { it.body()?.getOrNull(0)?.show?.ids?.trakt } } if (traktId == null) { traktId = searchService.get() .textQueryShow( show.title, null /* years */, null /* genres */, null /* lang */, show.country /* countries */, null /* runtime */, null /* ratings */, null /* certs */, show.network /* networks */, null /* status */, Extended.NOSEASONS, 1, 1 ) .awaitResponse() .let { it.body()?.firstOrNull()?.show?.ids?.trakt } } return if (traktId != null) { showService.get() .summary(traktId.toString(), Extended.FULL) .awaitResponse() .let { mapper.map(it.bodyOrThrow()) } } else { throw IllegalArgumentException("Trakt ID for show does not exist: [$show]") } } }
data/src/main/java/app/tivi/data/repositories/shows/TraktShowDataSource.kt
1295371521
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.util.PsiTreeUtil import org.rust.ide.inspections.fixes.RenameFix import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* /** * Base class for naming inspections. Implements the core logic of checking names * and registering problems. */ abstract class RsNamingInspection( val elementType: String, val styleName: String, val lint: RsLint, elementTitle: String = elementType ) : RsLocalInspectionTool() { val dispName = elementTitle + " naming convention" override fun getDisplayName() = dispName fun inspect(id: PsiElement?, holder: ProblemsHolder, fix: Boolean = true) { if (id == null) return val (isOk, suggestedName) = checkName(id.text) if (isOk || suggestedName == null || lint.levelFor(id) == RsLintLevel.ALLOW) return val fixEl = id.parent val fixes = if (fix && fixEl is PsiNamedElement) arrayOf(RenameFix(fixEl, suggestedName)) else emptyArray() holder.registerProblem( id, "$elementType `${id.text}` should have $styleName case name such as `$suggestedName`", *fixes) } abstract fun checkName(name: String): Pair<Boolean, String?> } /** * Checks if the name is CamelCase. */ open class RsCamelCaseNamingInspection( elementType: String, elementTitle: String = elementType ) : RsNamingInspection(elementType, "a camel", RsLint.NonCamelCaseTypes, elementTitle) { override fun checkName(name: String): Pair<Boolean, String?> { val str = name.trim('_') if (!str.isEmpty() && str[0].canStartWord && '_' !in str) { return Pair(true, null) } return Pair(false, if (str.isEmpty()) "CamelCase" else suggestName(name)) } private fun suggestName(name: String): String { val result = StringBuilder(name.length) var wasUnderscore = true var startWord = true for (char in name) { when { char == '_' -> wasUnderscore = true wasUnderscore || startWord && char.canStartWord -> { result.append(char.toUpperCase()) wasUnderscore = false startWord = false } else -> { startWord = char.isLowerCase() result.append(char.toLowerCase()) } } } return if (result.isEmpty()) "CamelCase" else result.toString() } private val Char.canStartWord: Boolean get() = isUpperCase() || isDigit() } /** * Checks if the name is snake_case. */ open class RsSnakeCaseNamingInspection(elementType: String) : RsNamingInspection(elementType, "a snake", RsLint.NonSnakeCase) { override fun checkName(name: String): Pair<Boolean, String?> { val str = name.trim('_') if (!str.isEmpty() && str.all { !it.isLetter() || it.isLowerCase() }) { return Pair(true, null) } return Pair(false, if (str.isEmpty()) "snake_case" else name.toSnakeCase(false)) } } /** * Checks if the name is UPPER_CASE. */ open class RsUpperCaseNamingInspection(elementType: String) : RsNamingInspection(elementType, "an upper", RsLint.NonUpperCaseGlobals) { override fun checkName(name: String): Pair<Boolean, String?> { val str = name.trim('_') if (!str.isEmpty() && str.all { !it.isLetter() || it.isUpperCase() }) { return Pair(true, null) } return Pair(false, if (str.isEmpty()) "UPPER_CASE" else name.toSnakeCase(true)) } } fun String.toSnakeCase(upper: Boolean): String { val result = StringBuilder(length + 3) // 3 is a reasonable margin for growth when `_`s are added result.append(takeWhile { it == '_' || it == '\'' }) // Preserve prefix var firstPart = true drop(result.length).splitToSequence('_').forEach pit@ { part -> if (part.isEmpty()) return@pit if (!firstPart) { result.append('_') } firstPart = false var newWord = false var firstWord = true part.forEach { char -> if (newWord && char.isUpperCase()) { if (!firstWord) { result.append('_') } newWord = false } else { newWord = char.isLowerCase() } result.append(if (upper) char.toUpperCase() else char.toLowerCase()) firstWord = false } } return result.toString() } // // Concrete inspections // class RsArgumentNamingInspection : RsSnakeCaseNamingInspection("Argument") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitPatBinding(el: RsPatBinding) { if (el.parent?.parent is RsValueParameter) { inspect(el.identifier, holder) } } } } class RsConstNamingInspection : RsUpperCaseNamingInspection("Constant") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitConstant(el: RsConstant) { if (el.kind == RsConstantKind.CONST) { inspect(el.identifier, holder) } } } } class RsStaticConstNamingInspection : RsUpperCaseNamingInspection("Static constant") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitConstant(el: RsConstant) { if (el.kind != RsConstantKind.CONST) { inspect(el.identifier, holder) } } } } class RsEnumNamingInspection : RsCamelCaseNamingInspection("Type", "Enum") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitEnumItem(el: RsEnumItem) = inspect(el.identifier, holder) } } class RsEnumVariantNamingInspection : RsCamelCaseNamingInspection("Enum variant") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitEnumVariant(el: RsEnumVariant) = inspect(el.identifier, holder) } } class RsFunctionNamingInspection : RsSnakeCaseNamingInspection("Function") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitFunction(el: RsFunction) { if (el.owner is RsFunctionOwner.Free) { inspect(el.identifier, holder) } } } } class RsMethodNamingInspection : RsSnakeCaseNamingInspection("Method") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitFunction(el: RsFunction) = when (el.owner) { is RsFunctionOwner.Trait, is RsFunctionOwner.Impl -> inspect(el.identifier, holder) else -> Unit } } } class RsLifetimeNamingInspection : RsSnakeCaseNamingInspection("Lifetime") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitLifetimeParameter(el: RsLifetimeParameter) = inspect(el, holder, false) } } class RsMacroNamingInspection : RsSnakeCaseNamingInspection("Macro") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitMacroDefinition(el: RsMacroDefinition) = inspect(el.nameIdentifier, holder, false) } } class RsModuleNamingInspection : RsSnakeCaseNamingInspection("Module") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitModDeclItem(el: RsModDeclItem) = inspect(el.identifier, holder) override fun visitModItem(el: RsModItem) = inspect(el.identifier, holder) } } class RsStructNamingInspection : RsCamelCaseNamingInspection("Type", "Struct") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitStructItem(el: RsStructItem) = inspect(el.identifier, holder) } } class RsFieldNamingInspection : RsSnakeCaseNamingInspection("Field") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitFieldDecl(el: RsFieldDecl) = inspect(el.identifier, holder) } } class RsTraitNamingInspection : RsCamelCaseNamingInspection("Trait") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitTraitItem(el: RsTraitItem) = inspect(el.identifier, holder) } } class RsTypeAliasNamingInspection : RsCamelCaseNamingInspection("Type", "Type alias") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitTypeAlias(el: RsTypeAlias) { if (el.owner is RsTypeAliasOwner.Free) { inspect(el.identifier, holder) } } } } class RsAssocTypeNamingInspection : RsCamelCaseNamingInspection("Type", "Associated type") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitTypeAlias(el: RsTypeAlias) { if (el.owner is RsTypeAliasOwner.Trait) { inspect(el.identifier, holder, false) } } } } class RsTypeParameterNamingInspection : RsCamelCaseNamingInspection("Type parameter") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitTypeParameter(el: RsTypeParameter) = inspect(el.identifier, holder) } } class RsVariableNamingInspection : RsSnakeCaseNamingInspection("Variable") { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitPatBinding(el: RsPatBinding) { val pattern = PsiTreeUtil.getTopmostParentOfType(el, RsPat::class.java) ?: return when (pattern.parent) { is RsLetDecl -> inspect(el.identifier, holder) } } } }
src/main/kotlin/org/rust/ide/inspections/RsNamingInspection.kt
91121923
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions class RemoveParenthesesFromExprIntentionTest : RsIntentionTestBase(RemoveParenthesesFromExprIntention()) { fun testRemoveParenthesesFromExpr() = doAvailableTest(""" fn test() { let a = (4 + 3/*caret*/); } """, """ fn test() { let a = 4 + 3/*caret*/; } """) }
src/test/kotlin/org/rust/ide/intentions/RemoveParenthesesFromExprIntentionTest.kt
2105359048
package co.makery.todomvc.frontend import kotlinx.html.* import kotlinx.html.dom.create import kotlinx.html.js.li import org.w3c.dom.HTMLElement import kotlin.browser.document class Template { private fun defaultTemplate(todo: Todo): HTMLElement = document.create.li { val completed = if (todo.completed) "completed" else "" attributes.put("data-id", todo.id) classes += completed div(classes = "view") { checkBoxInput(classes = "toggle") { checked = todo.completed } label { +todo.title } button(classes = "destroy") } } fun show(todos: List<Todo>): String = todos.joinToString("\n", transform = { todo -> defaultTemplate(todo).outerHTML }) fun itemCounter(activeCount: Int): String { val plural = if (activeCount == 1) "" else "s" return document.create.strong { +"$activeCount" }.outerHTML + " item $plural left" } }
frontend/src/main/kotlin/co/makery/todomvc/frontend/template.kt
561073632
/* * Copyright (c) 2020. Rei Matsushita * * 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 me.rei_m.hyakuninisshu.state.material.model import androidx.annotation.StringRes import me.rei_m.hyakuninisshu.domain.karuta.model.KarutaColor import me.rei_m.hyakuninisshu.state.R /** * 資料の色で絞り込むフィルター. * * @param value 色の値 * @param resId テキスト表示用のID */ enum class ColorFilter( val value: KarutaColor?, @param:StringRes val resId: Int ) { ALL(null, R.string.color_not_select), BLUE(KarutaColor.BLUE, R.string.color_blue), PINK(KarutaColor.PINK, R.string.color_pink), YELLOW(KarutaColor.YELLOW, R.string.color_yellow), GREEN(KarutaColor.GREEN, R.string.color_green), ORANGE(KarutaColor.ORANGE, R.string.color_orange); companion object { operator fun get(ordinal: Int) = values()[ordinal] } }
state/src/main/java/me/rei_m/hyakuninisshu/state/material/model/ColorFilter.kt
461756903
package com.sangcomz.fishbundemo import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.sangcomz.fishbundemo.databinding.ActivityWithfragmentBinding class WithFragmentActivity : AppCompatActivity() { private lateinit var subFragment: SubFragment private lateinit var binding: ActivityWithfragmentBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityWithfragmentBinding.inflate(layoutInflater) setContentView(binding.root) subFragment = SubFragment.newInstance() supportFragmentManager.beginTransaction().add(binding.areaContainer.id, subFragment) .commit() } }
FishBunDemo/src/main/java/com/sangcomz/fishbundemo/WithFragmentActivity.kt
3092101570
package work.beltran.discogsbrowser.collection.adapter import androidx.recyclerview.widget.DiffUtil class AlbumDiffCallback( private val oldList: List<CollectionItem>, private val newList: List<CollectionItem> ) : DiffUtil.Callback() { override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val oldItem = oldList[oldItemPosition] val newItem = newList[newItemPosition] return when { oldItem is CollectionItem.LoadingItem && newItem is CollectionItem.LoadingItem -> true oldItem is CollectionItem.AlbumItem && newItem is CollectionItem.AlbumItem -> { oldItem.album.id == newItem.album.id } else -> false } } override fun getOldListSize(): Int { return oldList.size } override fun getNewListSize(): Int { return newList.size } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition] == newList[newItemPosition] } }
collection/collection-ui/src/main/java/work/beltran/discogsbrowser/collection/adapter/AlbumDiffCallback.kt
560241315
package com.vito.work.weather.admin.controllers import com.vito.work.weather.service.LocationService import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.RequestMapping import javax.annotation.Resource import javax.servlet.http.HttpServletRequest /** * Created by lingzhiyuan. * Date : 16/4/10. * Time : 上午11:47. * Description: * */ @Controller @RequestMapping("/admin") class BasicController { @Resource lateinit var locationService: LocationService @RequestMapping("","/") fun toIndex(): String { return "admin/index" } @RequestMapping("login") fun login(): String { return "admin/login" } @RequestMapping("logout") fun logout(request: HttpServletRequest): String { request.logout() return "admin/login" } }
src/main/kotlin/com/vito/work/weather/admin/controllers/BasicController.kt
2336852050
package kodando.rxjs external interface Observer<in T> { val closed: Boolean? fun next(data: T) fun error(error: Throwable) fun complete() }
kodando-rxjs/src/main/kotlin/kodando/rxjs/Observer.kt
3618404076
/* * Copyright (C) 2021 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.zipline.loader import okio.ByteString interface ZiplineHttpClient { suspend fun download(url: String): ByteString }
zipline-loader/src/commonMain/kotlin/app/cash/zipline/loader/ZiplineHttpClient.kt
883447286
/* * Copyright 2020 Alex Almeida Tavella * * 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 br.com.core.android import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import javax.inject.Inject import javax.inject.Provider class DefaultViewModelProviderFactory @Inject constructor( private val viewModels: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>> ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return viewModels[modelClass]?.get()?.let { @Suppress("UNCHECKED_CAST") it as? T ?: throw IllegalStateException("ViewModel [$it] not a type of $modelClass") } ?: throw IllegalStateException("No ViewModel found for $modelClass") } }
core-android/src/main/java/br/com/core/android/DefaultViewModelProviderFactory.kt
1633434191
package de.westnordost.streetcomplete.quests.parking_lanes sealed class ParkingLane data class ParallelParkingLane(val position: ParkingLanePosition?) : ParkingLane() data class DiagonalParkingLane(val position: ParkingLanePosition?) : ParkingLane() data class PerpendicularParkingLane(val position: ParkingLanePosition?) : ParkingLane() object MarkedParkingLane: ParkingLane() object NoParking : ParkingLane() object NoStopping : ParkingLane() object FireLane: ParkingLane() object NoParkingLane : ParkingLane() object UnknownParkingLane : ParkingLane() enum class ParkingLanePosition { ON_STREET, HALF_ON_KERB, ON_KERB, LAY_BY, PAINTED_AREA_ONLY, SHOULDER, UNKNOWN } val ParkingLane.estimatedWidthOnRoad: Float get() = when(this) { is ParallelParkingLane -> 2f * (position?.estimatedWidthFactor ?: 1f) is DiagonalParkingLane -> 3f * (position?.estimatedWidthFactor ?: 1f) is PerpendicularParkingLane -> 4f * (position?.estimatedWidthFactor ?: 1f) else -> 0f // otherwise let's assume it's not on the street itself } val ParkingLanePosition.estimatedWidthFactor: Float get() = when(this) { ParkingLanePosition.ON_STREET -> 1f ParkingLanePosition.HALF_ON_KERB -> 0.5f ParkingLanePosition.ON_KERB -> 0f else -> 0.5f // otherwise let's assume it is somehow on the street }
app/src/main/java/de/westnordost/streetcomplete/quests/parking_lanes/ParkingLane.kt
1906078574
@file:Suppress("NOTHING_TO_INLINE", "unused") package com.boardgamegeek.extensions import android.app.Activity import android.content.* import android.content.pm.PackageManager import android.graphics.Bitmap import android.os.Build import android.text.Html import android.text.SpannedString import android.text.TextUtils import android.widget.Toast import androidx.annotation.DrawableRes import androidx.annotation.PluralsRes import androidx.annotation.StringRes import androidx.appcompat.app.AlertDialog import androidx.appcompat.content.res.AppCompatResources import androidx.core.graphics.drawable.toBitmap import androidx.core.os.bundleOf import androidx.preference.PreferenceManager import com.boardgamegeek.R import com.boardgamegeek.auth.Authenticator import com.boardgamegeek.provider.BggContract fun Context.preferences(name: String? = null): SharedPreferences = if (name.isNullOrEmpty()) PreferenceManager.getDefaultSharedPreferences(this) else this.getSharedPreferences(name, Context.MODE_PRIVATE) @Suppress("DEPRECATION") fun Context.getText(@StringRes id: Int, vararg args: Any): CharSequence { val encodedArgs = encodeArgs(args) val htmlString = String.format(Html.toHtml(SpannedString(getText(id))), *encodedArgs.toTypedArray()) return Html.fromHtml(htmlString).trimTrailingWhitespace() } @Suppress("DEPRECATION") fun Context.getQuantityText(@PluralsRes id: Int, quantity: Int, vararg args: Any?): CharSequence { val encodedArgs = encodeArgs(args) val htmlString = String.format(Html.toHtml(SpannedString(resources.getQuantityText(id, quantity))), *encodedArgs.toTypedArray()) return Html.fromHtml(htmlString).trimTrailingWhitespace() } private fun encodeArgs(args: Array<out Any?>): List<Any?> { val encodedArgs = mutableListOf<Any?>() for (i in args.indices) { val arg = args[i] encodedArgs.add(if (arg is String) TextUtils.htmlEncode(arg) else arg) } return encodedArgs } /** * Get the version name of the package, or "?.?" if not found. */ fun Context.versionName(): String { return try { packageManager.getPackageInfo(packageName, 0).versionName } catch (e: PackageManager.NameNotFoundException) { "?.?" } } fun Context.cancelSync() { this.cancelNotification(NotificationTags.SYNC_PROGRESS) Authenticator.getAccount(this)?.let { account -> ContentResolver.cancelSync(account, BggContract.CONTENT_AUTHORITY) } } inline fun <reified T : Activity> Context.startActivity(vararg params: Pair<String, Any?>) = startActivity(T::class.java, params) fun Context.startActivity(activity: Class<out Activity>, params: Array<out Pair<String, Any?>>) { startActivity(createIntent(activity, params)) } inline fun <reified T : Any> Context.intentFor(vararg params: Pair<String, Any?>): Intent = createIntent(T::class.java, params) fun <T> Context.createIntent(clazz: Class<out T>, params: Array<out Pair<String, Any?>>): Intent { val intent = Intent(this, clazz) if (params.isNotEmpty()) intent.putExtras(bundleOf(*params)) return intent } inline fun Context.toast(message: Int): Toast = Toast .makeText(this, message, Toast.LENGTH_SHORT) .apply { show() } inline fun Context.toast(message: CharSequence): Toast = Toast .makeText(this, message, Toast.LENGTH_SHORT) .apply { show() } inline fun Context.longToast(message: Int): Toast = Toast .makeText(this, message, Toast.LENGTH_LONG) .apply { show() } fun Context.showDialog(message: String, okButtonResId: Int = R.string.ok, okListener: DialogInterface.OnClickListener) { AlertDialog.Builder(this) .setMessage(message) .setCancelable(true) .setNegativeButton(R.string.cancel, null) .setPositiveButton(okButtonResId, okListener) .show() } fun Context.getBitmap(@DrawableRes resId: Int, tintColor: Int? = null): Bitmap { return AppCompatResources.getDrawable(this, resId)!!.apply { if (tintColor != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { setTint(tintColor) } }.toBitmap() }
app/src/main/java/com/boardgamegeek/extensions/Context.kt
2543556663
package com.hendraanggrian.openpss.schema import com.hendraanggrian.openpss.nosql.Document import com.hendraanggrian.openpss.nosql.Schema import com.hendraanggrian.openpss.nosql.StringId import kotlin.reflect.KProperty import kotlinx.nosql.string object GlobalSettings : Schema<GlobalSetting>("global_settings", GlobalSetting::class) { val key = string("key") val value = string("value") val LANGUAGE = "language" to "en-US" // or equivalent to Language.EN_US.fullCode val INVOICE_HEADERS = "invoice_headers" to "" } data class GlobalSetting( val key: String, var value: String ) : Document<GlobalSettings> { companion object { val KEY_LANGUAGE by GlobalSettings.LANGUAGE val KEY_INVOICE_HEADERS by GlobalSettings.INVOICE_HEADERS private operator fun Pair<String, String>.getValue( thisRef: Any?, property: KProperty<*> ): String = first } override lateinit var id: StringId<GlobalSettings> inline val valueList: List<String> get() = value.split("|") }
openpss/src/com/hendraanggrian/openpss/schema/GlobalSetting.kt
2222009727
package org.wordpress.android.fluxc.persistence import androidx.room.Dao import androidx.room.Entity import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.PrimaryKey import androidx.room.Query import kotlinx.coroutines.flow.Flow @Dao interface BloggingRemindersDao { @Query("SELECT * FROM BloggingReminders") fun getAll(): Flow<List<BloggingReminders>> @Query("SELECT * FROM BloggingReminders WHERE localSiteId = :siteId") fun liveGetBySiteId(siteId: Int): Flow<BloggingReminders?> @Query("SELECT * FROM BloggingReminders WHERE localSiteId = :siteId") suspend fun getBySiteId(siteId: Int): List<BloggingReminders> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(type: BloggingReminders): Long @Entity(tableName = "BloggingReminders") data class BloggingReminders( @PrimaryKey val localSiteId: Int, val monday: Boolean = false, val tuesday: Boolean = false, val wednesday: Boolean = false, val thursday: Boolean = false, val friday: Boolean = false, val saturday: Boolean = false, val sunday: Boolean = false, val hour: Int = 10, val minute: Int = 0, val isPromptRemindersOptedIn: Boolean = false ) }
fluxc/src/main/java/org/wordpress/android/fluxc/persistence/BloggingRemindersDao.kt
3528839460
package template.factory import template.Template internal interface Factory<out T : Template> { fun newTemplate(): T }
template/src/main/java/template/factory/Factory.kt
1588856198
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.vanilla.packet.handler.play import org.lanternpowered.server.network.NetworkContext import org.lanternpowered.server.network.packet.PacketHandler import org.lanternpowered.server.network.vanilla.packet.type.play.RegisterChannelsPacket object RegisterChannelsHandler : PacketHandler<RegisterChannelsPacket> { override fun handle(ctx: NetworkContext, packet: RegisterChannelsPacket) { val channels = packet.channels val registeredChannels = ctx.session.registeredChannels registeredChannels.removeAll(channels) } }
src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/handler/play/RegisterChannelsHandler.kt
381420271
package io.github.dmi3coder.scorsero.score import io.github.dmi3coder.scorsero.MainApplication import io.github.dmi3coder.scorsero.data.Score import io.github.dmi3coder.scorsero.data.source.ScoreRepository import io.github.dmi3coder.scorsero.score.ScoreCreationContract.ViewState import java.util.Date import javax.inject.Inject /** * Created by dim3coder on 11:59 PM 7/4/17. */ class ScoreCreationPresenter( var view: ScoreCreationContract.View) : ScoreCreationContract.Presenter { @Inject lateinit var repository: ScoreRepository var operationScore: Score? = null override fun start() { this.start(Score()) } override fun start(score: Score) { operationScore = score view.setPresenter(this) view.setScore(operationScore) } override fun processScore(scoreData: Score?, state: ViewState) { if (scoreData!!.creationDate == null) scoreData.creationDate = Date().time if (scoreData.id == null) { repository.insert(scoreData) } else { repository.update(scoreData) } view.clear() operationScore = Score() view.setScore(operationScore) } }
app/src/main/java/io/github/dmi3coder/scorsero/score/ScoreCreationPresenter.kt
245969174
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.vanilla.recipe import org.lanternpowered.server.network.buffer.ByteBuffer import org.lanternpowered.server.network.item.NetworkItemStack import org.lanternpowered.server.network.packet.CodecContext import org.spongepowered.api.item.inventory.ItemStack class ShapelessNetworkRecipe( id: String, group: String?, private val result: ItemStack, private val ingredients: List<NetworkIngredient> ) : GroupedNetworkRecipe(id, NetworkRecipeTypes.CRAFTING_SHAPELESS, group) { override fun writeProperties(ctx: CodecContext, buf: ByteBuffer) { super.writeProperties(ctx, buf) buf.writeVarInt(this.ingredients.size) for (ingredient in this.ingredients) ingredient.write(ctx, buf) NetworkItemStack.write(ctx, buf, this.result) } }
src/main/kotlin/org/lanternpowered/server/network/vanilla/recipe/ShapelessNetworkRecipe.kt
3866124586
package antimattermod.core.Energy.Filler import antimattermod.core.Energy.Filler.TileFiller import net.minecraft.entity.player.EntityPlayer import net.minecraft.entity.player.InventoryPlayer import net.minecraft.inventory.Container import net.minecraft.inventory.IInventory import net.minecraft.inventory.Slot import net.minecraft.item.ItemStack /** * @author kojin15. */ class FillerContainer(private val x: Int, private val y: Int, private val z: Int, private val tile: TileFiller, private val playerInventory: InventoryPlayer) : Container() { init { for (i in 0..5) { for (j in 0..3) { this.addSlotToContainer(Slot(tile, j + i * 4, 186 + j * 18, 8 + i * 18)) } } this.addSlotToContainer(patternSlot(tile, 24, 80, 14)) for (i in 0..2) { for (j in 0..8) { this.addSlotToContainer(Slot(playerInventory, j + i * 9 + 9, 8 + j * 18, 108 + i * 18)) } } for (i in 0..8) { this.addSlotToContainer(Slot(playerInventory, i, 8 + i * 18, 166)) } } val fillerSize = 24 val playerSize = 27 val hotbarSize = 9 val fillerIndex = 0 val playerIndex = fillerIndex + fillerSize val hotbarIndex = playerIndex + playerSize override fun canInteractWith(player: EntityPlayer?): Boolean { return true } override fun transferStackInSlot(player: EntityPlayer?, clickedIndex: Int): ItemStack? { var itemstack: ItemStack? = null val slot: Slot = this.inventorySlots[clickedIndex] as Slot if (slot.hasStack) { val baseStack = slot.stack itemstack = baseStack.copy() if (clickedIndex < playerIndex) { if (!this.mergeItemStack(baseStack, playerIndex, hotbarIndex + hotbarSize, true)) return null } else if (!this.mergeItemStack(baseStack, fillerIndex, fillerIndex + fillerSize, false)) return null if (baseStack.stackSize == 0) slot.putStack(null) else slot.onSlotChanged() } return itemstack } class patternSlot(iInventory: IInventory, id: Int, x: Int, y: Int) : Slot(iInventory, id, x, y) { override fun canTakeStack(p_82869_1_: EntityPlayer?): Boolean { return false } override fun isItemValid(p_75214_1_: ItemStack?): Boolean { return false } } }
src/main/java/antimattermod/core/Energy/Filler/FillerContainer.kt
3094968667
package com.mercadopago.android.px.internal.features.generic_modal interface ViewModel { fun onButtonClicked(actionable: Actionable, isMain: Boolean) fun onDialogDismissed() }
px-checkout/src/main/java/com/mercadopago/android/px/internal/features/generic_modal/ViewModel.kt
3461715136
package com.mercadopago import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.TextView import android.widget.Toast import com.mercadopago.example.R class FakeKycActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_fake_kyc) val callback = intent.data?.getQueryParameter(QUERY_CALLBACK) findViewById<TextView>(R.id.initiative).text = intent.data?.getQueryParameter(QUERY_INITIATIVE) ?: "NO INITIATIVE" findViewById<TextView>(R.id.callback).text = callback ?: "NO CALLBACK" findViewById<View>(R.id.yes_button).setOnClickListener { if (callback.isNullOrEmpty()) { Toast.makeText(this, "No callback to call", Toast.LENGTH_SHORT).show() return@setOnClickListener } val intent = Intent(Intent.ACTION_VIEW).apply { data = Uri.parse(callback) } val isIntentSafe = packageManager.queryIntentActivities(intent, 0).size > 0 if (isIntentSafe) { startActivity(intent) finish() } else { Toast.makeText(this, "No one listening to callback", Toast.LENGTH_SHORT).show() } } findViewById<View>(R.id.no_button).setOnClickListener { finish() } } companion object { private const val QUERY_INITIATIVE = "initiative" private const val QUERY_CALLBACK = "callback" } }
example/src/main/java/com/mercadopago/FakeKycActivity.kt
1735703074
package com.esafirm.imagepicker.listeners interface OnImageClickListener { fun onImageClick(isSelected: Boolean): Boolean }
imagepicker/src/main/java/com/esafirm/imagepicker/listeners/OnImageClickListener.kt
896665915
package com.mercadopago.android.px.internal.extensions import android.app.Activity import android.graphics.Rect import android.view.View internal fun CharSequence?.isNotNullNorEmpty() = !isNullOrEmpty() internal fun CharSequence?.orIfEmpty(fallback: String) = if (isNotNullNorEmpty()) this!! else fallback internal fun View.gone() = apply { visibility = View.GONE } internal fun View.visible() = apply { visibility = View.VISIBLE } internal fun View.invisible() = apply { visibility = View.INVISIBLE } internal fun Any?.runIfNull(action: ()->Unit) { if(this == null) { action.invoke() } } internal fun Activity.addKeyBoardListener( onKeyBoardOpen: (() -> Unit)? = null, onKeyBoardClose: (() -> Unit)? = null ) { window.decorView.rootView?.apply { viewTreeObserver?.addOnGlobalLayoutListener { val r = Rect() getWindowVisibleDisplayFrame(r) val heightDiff = rootView.height - (r.bottom - r.top) if (heightDiff > rootView.height * 0.15) { onKeyBoardOpen?.invoke() } else { onKeyBoardClose?.invoke() } } } }
px-checkout/src/main/java/com/mercadopago/android/px/internal/extensions/BaseExtensions.kt
3357156865
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package debop4k.mongodb.spring.cache import debop4k.core.io.serializers.Serializers import debop4k.core.loggerOf import org.eclipse.collections.impl.map.mutable.ConcurrentHashMap import org.springframework.beans.factory.DisposableBean import org.springframework.cache.Cache import org.springframework.cache.CacheManager import org.springframework.data.mongodb.core.MongoTemplate /** * MongoDB를 저장소로 사용하는 Spring @Cacheable용 Cache 관리자입니다. * Spring Application Context 에 MongoCacheManager를 Bean으로 등록하셔야 합니다. * <p> * <pre><code> * @Bean * public MongoCacheMaanger mongoCacheManager() { * return new MongoCacheManager(mongo, 120); * } * </code></pre> * * @author [email protected] */ class MongodbCacheManager @JvmOverloads constructor(val mongo: MongoTemplate, val expirationInSeconds: Long = 60 * 60 * 1000L) : CacheManager, DisposableBean { private val log = loggerOf(javaClass) val valueSerializer = Serializers.FST val caches = ConcurrentHashMap<String, Cache>() val expires = ConcurrentHashMap<String, Long>() override fun getCacheNames(): MutableCollection<String>? = caches.keys override fun getCache(name: String?): Cache { return caches.getIfAbsentPut(name!!) { key -> val expiration = computeExpiration(key) MongodbCache(key, mongo, expiration, valueSerializer) } } override fun destroy() { log.debug("MongoDB를 저장소로 사용하는 CacheManager를 제거합니다...") if (caches.notEmpty()) { try { caches.values.forEach { it.clear() } caches.clear() expires.clear() } catch(ignored: Exception) { log.warn("MongodbCacheManager를 제거하는데 실패했습니다.", ignored) } } } private fun computeExpiration(name: String): Long = expires.getIfAbsentPut(name, expirationInSeconds) }
debop4k-data-mongodb/src/main/kotlin/debop4k/mongodb/spring/cache/MongodbCacheManager.kt
436203277
package com.polito.sismic 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) } }
app/src/test/java/com/polito/sismic/ExampleUnitTest.kt
3882037094
package com.hea3ven.dulcedeleche object DulceDeLecheModClient : DulceDeLecheMod() { init { addModule("redstone", "com.hea3ven.dulcedeleche.modules.redstone.RedstoneModuleClient.INSTANCE") } }
src/main/kotlin/com/hea3ven/dulcedeleche/DulceDeLecheModClient.kt
141961564
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.gradle.codeInsight import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionProvider import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.completion.CompletionType import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.icons.AllIcons import com.intellij.lang.ASTNode import com.intellij.openapi.util.Ref import com.intellij.patterns.PlatformPatterns.psiElement import com.intellij.psi.PsiElement import com.intellij.util.ProcessingContext import icons.ExternalSystemIcons import icons.GradleIcons import org.jetbrains.plugins.gradle.service.resolve.GradleExtensionsContributor import org.jetbrains.plugins.gradle.service.resolve.GradleExtensionsContributor.Companion.getDocumentation import org.jetbrains.plugins.groovy.dsl.holders.NonCodeMembersHolder import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightVariable /** * @author Vladislav.Soroka * @since 12/12/2016 */ class PropertiesTasksCompletionContributor : AbstractGradleCompletionContributor() { class PropertiesTasksCompletionProvider : CompletionProvider<CompletionParameters>() { override fun addCompletions(params: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { val position = params.position val prevSibling = position.prevSibling if (prevSibling is ASTNode && prevSibling.elementType == GroovyTokenTypes.mDOT) return val extensionsData = GradleExtensionsContributor.getExtensionsFor(position) ?: return for (gradleProp in extensionsData.findAllProperties()) { val docRef = Ref.create<String>() val propVar = object : GrLightVariable(position.manager, gradleProp.name, gradleProp.typeFqn, position) { override fun getNavigationElement(): PsiElement { val navigationElement = super.getNavigationElement() navigationElement.putUserData(NonCodeMembersHolder.DOCUMENTATION, docRef.get()) return navigationElement } } docRef.set(getDocumentation(gradleProp, propVar)) val elementBuilder = LookupElementBuilder.create(propVar, gradleProp.name) .withIcon(AllIcons.Nodes.Property) .withPresentableText(gradleProp.name) .withTailText(" via ext", true) .withTypeText(propVar.type.presentableText, GradleIcons.Gradle, false) result.addElement(elementBuilder) } for (gradleTask in extensionsData.tasks) { val docRef = Ref.create<String>() val taskVar = object : GrLightVariable(position.manager, gradleTask.name, gradleTask.typeFqn, position) { override fun getNavigationElement(): PsiElement { val navigationElement = super.getNavigationElement() navigationElement.putUserData(NonCodeMembersHolder.DOCUMENTATION, docRef.get()) return navigationElement } } docRef.set(getDocumentation(gradleTask, taskVar)) val elementBuilder = LookupElementBuilder.create(taskVar, gradleTask.name) .withIcon(ExternalSystemIcons.Task) .withPresentableText(gradleTask.name) .withTailText(" task", true) .withTypeText(taskVar.type.presentableText) result.addElement(elementBuilder) } } } init { extend(CompletionType.BASIC, PATTERN, PropertiesTasksCompletionProvider()) } companion object { private val PATTERN = psiElement().and(GRADLE_FILE_PATTERN).withParent(GrReferenceExpression::class.java) } }
plugins/gradle/src/org/jetbrains/plugins/gradle/codeInsight/PropertiesTasksCompletionContributor.kt
2597789432
/* * Copyright 2020 Google LLC. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mlkit.vision.demo.kotlin.textdetector import android.content.Context import android.util.Log import com.google.android.gms.tasks.Task import com.google.mlkit.vision.common.InputImage import com.google.mlkit.vision.demo.GraphicOverlay import com.google.mlkit.vision.demo.kotlin.VisionProcessorBase import com.google.mlkit.vision.demo.preference.PreferenceUtils import com.google.mlkit.vision.text.Text import com.google.mlkit.vision.text.TextRecognition import com.google.mlkit.vision.text.TextRecognizer import com.google.mlkit.vision.text.TextRecognizerOptionsInterface /** Processor for the text detector demo. */ class TextRecognitionProcessor( private val context: Context, textRecognizerOptions: TextRecognizerOptionsInterface ) : VisionProcessorBase<Text>(context) { private val textRecognizer: TextRecognizer = TextRecognition.getClient(textRecognizerOptions) private val shouldGroupRecognizedTextInBlocks: Boolean = PreferenceUtils.shouldGroupRecognizedTextInBlocks(context) private val showLanguageTag: Boolean = PreferenceUtils.showLanguageTag(context) private val showConfidence: Boolean = PreferenceUtils.shouldShowTextConfidence(context) override fun stop() { super.stop() textRecognizer.close() } override fun detectInImage(image: InputImage): Task<Text> { return textRecognizer.process(image) } override fun onSuccess(text: Text, graphicOverlay: GraphicOverlay) { Log.d(TAG, "On-device Text detection successful") logExtrasForTesting(text) graphicOverlay.add( TextGraphic( graphicOverlay, text, shouldGroupRecognizedTextInBlocks, showLanguageTag, showConfidence ) ) } override fun onFailure(e: Exception) { Log.w(TAG, "Text detection failed.$e") } companion object { private const val TAG = "TextRecProcessor" private fun logExtrasForTesting(text: Text?) { if (text != null) { Log.v(MANUAL_TESTING_LOG, "Detected text has : " + text.textBlocks.size + " blocks") for (i in text.textBlocks.indices) { val lines = text.textBlocks[i].lines Log.v( MANUAL_TESTING_LOG, String.format("Detected text block %d has %d lines", i, lines.size) ) for (j in lines.indices) { val elements = lines[j].elements Log.v( MANUAL_TESTING_LOG, String.format("Detected text line %d has %d elements", j, elements.size) ) for (k in elements.indices) { val element = elements[k] Log.v( MANUAL_TESTING_LOG, String.format("Detected text element %d says: %s", k, element.text) ) Log.v( MANUAL_TESTING_LOG, String.format( "Detected text element %d has a bounding box: %s", k, element.boundingBox!!.flattenToString() ) ) Log.v( MANUAL_TESTING_LOG, String.format( "Expected corner point size is 4, get %d", element.cornerPoints!!.size ) ) for (point in element.cornerPoints!!) { Log.v( MANUAL_TESTING_LOG, String.format( "Corner point for element %d is located at: x - %d, y = %d", k, point.x, point.y ) ) } } } } } } } }
android/vision-quickstart/app/src/main/java/com/google/mlkit/vision/demo/kotlin/textdetector/TextRecognitionProcessor.kt
2684635552
/* * 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 org.jetbrains.plugins.groovy.lang.typing import com.intellij.psi.PsiType import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty import org.jetbrains.plugins.groovy.lang.psi.util.advancedResolve import org.jetbrains.plugins.groovy.lang.psi.util.getArrayClassType import org.jetbrains.plugins.groovy.lang.psi.util.getSimpleArrayAccessType import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil.extractReturnTypeFromCandidate class DefaultIndexAccessTypeCalculator : GrTypeCalculator<GrIndexProperty> { override fun getType(expression: GrIndexProperty): PsiType? { return expression.getArrayClassType() ?: expression.getSimpleArrayAccessType() ?: extractReturnTypeFromCandidate(expression.advancedResolve(), expression, null) } }
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/DefaultIndexAccessTypeCalculator.kt
1143046456
/* * Copyright (C) 2014-2022 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.ui.dialogs import android.content.Intent import android.os.Environment import android.view.View.INVISIBLE import android.view.View.VISIBLE import androidx.appcompat.widget.AppCompatCheckBox import androidx.appcompat.widget.AppCompatTextView import androidx.core.text.HtmlCompat import androidx.preference.PreferenceManager import com.afollestad.materialdialogs.DialogAction import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.internal.MDButton import com.amaze.filemanager.R import com.amaze.filemanager.application.AppConfig import com.amaze.filemanager.asynchronous.services.EncryptService import com.amaze.filemanager.asynchronous.services.EncryptService.TAG_SOURCE import com.amaze.filemanager.filesystem.HybridFileParcelable import com.amaze.filemanager.filesystem.RandomPathGenerator import com.amaze.filemanager.filesystem.files.CryptUtil.AESCRYPT_EXTENSION import com.amaze.filemanager.filesystem.files.CryptUtil.CRYPT_EXTENSION import com.amaze.filemanager.filesystem.files.EncryptDecryptUtils import com.amaze.filemanager.test.getString import com.amaze.filemanager.ui.activities.MainActivity import com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants import com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants.ENCRYPT_PASSWORD_FINGERPRINT import com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants.ENCRYPT_PASSWORD_MASTER import com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants.PREFERENCE_CRYPT_FINGERPRINT import com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants.PREFERENCE_CRYPT_FINGERPRINT_DEFAULT import com.amaze.filemanager.ui.views.WarnableTextInputLayout import com.google.android.material.textfield.TextInputEditText import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Assert.fail import org.junit.Before import org.junit.Test import org.robolectric.shadows.ShadowDialog import java.io.File import kotlin.random.Random class EncryptWithPresetPasswordSaveAsDialogTest : AbstractEncryptDialogTests() { private val randomizer = Random(System.currentTimeMillis()) private lateinit var file: File private lateinit var tilFileSaveAs: WarnableTextInputLayout private lateinit var editTextFileSaveAs: TextInputEditText private lateinit var checkboxUseAze: AppCompatCheckBox private lateinit var textViewCryptInfo: AppCompatTextView private lateinit var okButton: MDButton /** * MainActivity setup. */ @Before override fun setUp() { super.setUp() file = File( Environment.getExternalStorageDirectory(), RandomPathGenerator.generateRandomPath( randomizer, 16 ) ) } /** * Post test cleanup. */ @After override fun tearDown() { super.tearDown() PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) .edit().putBoolean( PREFERENCE_CRYPT_FINGERPRINT, PREFERENCE_CRYPT_FINGERPRINT_DEFAULT ).apply() } /** * Test case when fingerprint encrypt option is enabled. * * Ensure optional checkbox is disabled - Fingerprint encryption cannot do AESCrypt. */ @Test fun testWhenFingerprintOptionEnabled() { PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) .edit() .putBoolean(PREFERENCE_CRYPT_FINGERPRINT, true) .apply() performTest( testContent = { _, _, _ -> assertEquals("${file.name}$CRYPT_EXTENSION", editTextFileSaveAs.text.toString()) assertEquals(INVISIBLE, checkboxUseAze.visibility) assertEquals(INVISIBLE, textViewCryptInfo.visibility) }, callback = object : EncryptDecryptUtils.EncryptButtonCallbackInterface { override fun onButtonPressed(intent: Intent, password: String) { assertEquals(ENCRYPT_PASSWORD_FINGERPRINT, password) assertEquals(file.absolutePath, intent.getStringExtra(TAG_SOURCE)) assertFalse(intent.getBooleanExtra(EncryptService.TAG_AESCRYPT, true)) assertEquals( "${file.name}$CRYPT_EXTENSION", intent.getStringExtra(EncryptService.TAG_ENCRYPT_TARGET) ) } } ) } /** * Test filename validation when fingerprint option enabled. * Shall never let but .aze go through */ @Test fun testFilenameValidationWhenFingerprintOptionEnabled() { PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) .edit() .putBoolean(PREFERENCE_CRYPT_FINGERPRINT, true) .apply() performTest(testContent = { _, _, _ -> editTextFileSaveAs.setText("${file.name}.error") assertFalse(okButton.isEnabled) assertEquals( getString(R.string.encrypt_file_must_end_with_aze), tilFileSaveAs.error ) editTextFileSaveAs.setText("${file.name}.aes") assertFalse(okButton.isEnabled) assertEquals( getString(R.string.encrypt_file_must_end_with_aze), tilFileSaveAs.error ) }) } /** * Test filename validation when fingerprint option enabled. * Shall never let but .aze go through */ @Test fun testFilenameValidationWhenFingerprintOptionDisabled() { PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) .edit() .putBoolean(PREFERENCE_CRYPT_FINGERPRINT, false) .apply() performTest( password = ENCRYPT_PASSWORD_MASTER, testContent = { _, _, _ -> editTextFileSaveAs.setText("${file.name}.error") assertFalse(okButton.isEnabled) assertEquals( getString(R.string.encrypt_file_must_end_with_aes), tilFileSaveAs.error ) editTextFileSaveAs.setText("${file.name}.aze") assertFalse(okButton.isEnabled) assertEquals( getString(R.string.encrypt_file_must_end_with_aes), tilFileSaveAs.error ) checkboxUseAze.isChecked = true assertTrue(okButton.isEnabled) assertNull(tilFileSaveAs.error) } ) } /** * Test case when fingerprint option is disabled. * * Must be master password then. Sorry, no validation at this point - upstream is responsible * for that. */ @Test fun testWhenFingerprintOptionDisabled() { PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) .edit() .putBoolean(PREFERENCE_CRYPT_FINGERPRINT, false) .apply() performTest( password = ENCRYPT_PASSWORD_MASTER, testContent = { _, _, _ -> assertEquals("${file.name}$AESCRYPT_EXTENSION", editTextFileSaveAs.text.toString()) assertEquals(VISIBLE, checkboxUseAze.visibility) assertEquals(VISIBLE, textViewCryptInfo.visibility) }, callback = object : EncryptDecryptUtils.EncryptButtonCallbackInterface { override fun onButtonPressed(intent: Intent, password: String) { assertEquals(ENCRYPT_PASSWORD_MASTER, password) assertEquals(file.absolutePath, intent.getStringExtra(TAG_SOURCE)) assertTrue(intent.getBooleanExtra(EncryptService.TAG_AESCRYPT, false)) assertEquals( "${file.name}$AESCRYPT_EXTENSION", intent.getStringExtra(EncryptService.TAG_ENCRYPT_TARGET) ) } } ) } /** * Test invalid password put into the dialog argument, which shall never happen. */ @Test(expected = IllegalArgumentException::class) fun testWithInvalidFixedPasswordArgument() { PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) .edit() .putBoolean(PREFERENCE_CRYPT_FINGERPRINT, false) .apply() performTest( password = "abcdefgh", testContent = { _, _, _ -> } ) } /** * Test logic when aze encryption checkbox is ticked. */ @Test fun testAzecryptCheckbox() { performTest( password = ENCRYPT_PASSWORD_MASTER, testContent = { _, _, _ -> checkboxUseAze.isChecked = true assertEquals( HtmlCompat.fromHtml( getString(R.string.encrypt_option_use_azecrypt_desc), HtmlCompat.FROM_HTML_MODE_COMPACT ) .toString(), textViewCryptInfo.text.toString() ) assertTrue(ShadowDialog.getShownDialogs().size == 2) assertTrue(ShadowDialog.getLatestDialog() is MaterialDialog) (ShadowDialog.getLatestDialog() as MaterialDialog).run { assertEquals(getString(R.string.warning), titleView.text) assertEquals( getString(R.string.crypt_warning_key), contentView?.text.toString() ) assertEquals( getString(R.string.warning_never_show), getActionButton(DialogAction.NEGATIVE).text ) assertEquals( getString(R.string.warning_confirm), getActionButton(DialogAction.POSITIVE).text ) assertTrue(getActionButton(DialogAction.POSITIVE).performClick()) } assertEquals(2, ShadowDialog.getShownDialogs().size) assertFalse(ShadowDialog.getLatestDialog().isShowing) assertTrue(true == editTextFileSaveAs.text?.endsWith(CRYPT_EXTENSION)) checkboxUseAze.isChecked = false assertEquals( HtmlCompat.fromHtml( getString(R.string.encrypt_option_use_aescrypt_desc), HtmlCompat.FROM_HTML_MODE_COMPACT ) .toString(), textViewCryptInfo.text.toString() ) assertEquals(2, ShadowDialog.getShownDialogs().size) assertFalse(ShadowDialog.getLatestDialog().isShowing) assertTrue(true == editTextFileSaveAs.text?.endsWith(AESCRYPT_EXTENSION)) checkboxUseAze.isChecked = true assertEquals( HtmlCompat.fromHtml( getString(R.string.encrypt_option_use_azecrypt_desc), HtmlCompat.FROM_HTML_MODE_COMPACT ) .toString(), textViewCryptInfo.text.toString() ) assertEquals(3, ShadowDialog.getShownDialogs().size) assertTrue(ShadowDialog.getLatestDialog().isShowing) assertTrue(true == editTextFileSaveAs.text?.endsWith(CRYPT_EXTENSION)) (ShadowDialog.getLatestDialog() as MaterialDialog) .getActionButton(DialogAction.NEGATIVE).performClick() assertEquals(3, ShadowDialog.getShownDialogs().size) assertFalse(ShadowDialog.getLatestDialog().isShowing) assertTrue( PreferenceManager.getDefaultSharedPreferences(AppConfig.getInstance()) .getBoolean(PreferencesConstants.PREFERENCE_CRYPT_WARNING_REMEMBER, false) ) checkboxUseAze.isChecked = false assertEquals(3, ShadowDialog.getShownDialogs().size) // no new dialog checkboxUseAze.isChecked = true assertEquals(3, ShadowDialog.getShownDialogs().size) } ) } private fun performTest( testContent: (dialog: MaterialDialog, intent: Intent, activity: MainActivity) -> Unit, password: String = ENCRYPT_PASSWORD_FINGERPRINT, callback: EncryptDecryptUtils.EncryptButtonCallbackInterface = object : EncryptDecryptUtils.EncryptButtonCallbackInterface {} ) { scenario.onActivity { activity -> Intent().putExtra(TAG_SOURCE, HybridFileParcelable(file.absolutePath)).let { intent -> EncryptWithPresetPasswordSaveAsDialog.show( activity, intent, activity, password, callback ) ShadowDialog.getLatestDialog()?.run { assertTrue(this is MaterialDialog) (this as MaterialDialog).let { editTextFileSaveAs = findViewById<TextInputEditText>( R.id.edit_text_encrypt_save_as ) tilFileSaveAs = findViewById<WarnableTextInputLayout>( R.id.til_encrypt_save_as ) checkboxUseAze = findViewById<AppCompatCheckBox>(R.id.checkbox_use_aze) textViewCryptInfo = findViewById<AppCompatTextView>( R.id.text_view_crypt_info ) okButton = getActionButton(DialogAction.POSITIVE) testContent.invoke(it, intent, activity) } } ?: fail("Dialog cannot be seen?") } } } }
app/src/test/java/com/amaze/filemanager/ui/dialogs/EncryptWithPresetPasswordSaveAsDialogTest.kt
1318738860
/* * Copyright © 2020. Daniel Schaal <[email protected]> * * This file is part of ocreader. * * ocreader 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. * * ocreader 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 Foobar. If not, see <http://www.gnu.org/licenses/>. */ package email.schaal.ocreader.database.model import io.realm.Realm interface Insertable { fun insert(realm: Realm) fun delete(realm: Realm) }
app/src/main/java/email/schaal/ocreader/database/model/Insertable.kt
4267348456
package com.cout970.magneticraft.systems.tilemodules.conveyorbelt import com.cout970.magneticraft.AABB import com.cout970.magneticraft.IVector2 import com.cout970.magneticraft.misc.vector.vec2Of open class BitMap(val map: BooleanArray = BooleanArray(16 * 16)) : IBitMap { override operator fun get(x: Int, y: Int): Boolean { val index = x + y * 16 if (index < 0 || index >= 16 * 16) return false return map[index] } override operator fun set(x: Int, y: Int, value: Boolean) { val index = x + y * 16 if (index < 0 || index >= 16 * 16) return map[index] = value } override fun mark(box: AABB) { mark(vec2Of(box.minX, box.minZ) * 16, vec2Of(box.maxX, box.maxZ) * 16) } override fun mark(start: IVector2, end: IVector2) { for (i in Math.floor(start.x).toInt() until Math.ceil(end.x).toInt()) { for (j in Math.floor(start.y).toInt() until Math.ceil(end.y).toInt()) { this[i, j] = true } } } override fun unmark(box: AABB) { unmark(vec2Of(box.minX, box.minZ) * 16, vec2Of(box.maxX, box.maxZ) * 16) } override fun unmark(start: IVector2, end: IVector2) { for (i in Math.floor(start.x).toInt() until Math.ceil(end.x).toInt()) { for (j in Math.floor(start.y).toInt() until Math.ceil(end.y).toInt()) { this[i, j] = false } } } // Returns true if there and empty space in the hitbox area override fun test(box: AABB): Boolean { return test(vec2Of(box.minX, box.minZ) * 16, vec2Of(box.maxX, box.maxZ) * 16) } override fun test(start: IVector2, end: IVector2): Boolean { for (i in Math.floor(start.x).toInt() until Math.ceil(end.x).toInt()) { for (j in Math.floor(start.y).toInt() until Math.ceil(end.y).toInt()) { if (this[i, j]) return false } } return true } override fun clear() { for (i in 0 until 16 * 16) { map[i] = false } } override fun copy(): BitMap { return BitMap(map.clone()) } override fun toString(): String { return buildString { append("BitMap(\n") for (i in 0 until 16) { for (j in 0 until 16) { if (this@BitMap[i, j]) { append("#") } else { append("_") } } append('\n') } append(")") } } }
src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/conveyorbelt/BitMap.kt
687494497
package org.jetbrains.kotlin import com.google.gson.annotations.Expose import org.jetbrains.kotlin.konan.target.KonanTarget import org.jetbrains.kotlin.konan.target.Xcode import kotlin.math.min /** * Compares two strings assuming that both are representing numeric version strings. * Examples of numeric version strings: "12.4.1.2", "9", "0.5". */ private fun compareStringsAsVersions(version1: String, version2: String): Int { val version1 = version1.split('.').map { it.toInt() } val version2 = version2.split('.').map { it.toInt() } val minimalLength = min(version1.size, version2.size) for (index in 0 until minimalLength) { if (version1[index] < version2[index]) return -1 if (version1[index] > version2[index]) return 1 } return version1.size.compareTo(version2.size) } /** * Returns parsed output of `xcrun simctl list runtimes -j`. */ private fun Xcode.getSimulatorRuntimeDescriptors(): List<SimulatorRuntimeDescriptor> = gson.fromJson(simulatorRuntimes, ListRuntimesReport::class.java).runtimes /** * Returns first available simulator runtime for [target] with at least [osMinVersion] OS version. * */ fun Xcode.getLatestSimulatorRuntimeFor(target: KonanTarget, osMinVersion: String): SimulatorRuntimeDescriptor? { val osName = when (target) { KonanTarget.IOS_X64 -> "iOS" KonanTarget.WATCHOS_X64, KonanTarget.WATCHOS_X86 -> "watchOS" KonanTarget.TVOS_X64 -> "tvOS" else -> error("Unexpected simulator target: $target") } return getSimulatorRuntimeDescriptors().firstOrNull { it.checkAvailability() && it.name.startsWith(osName) && compareStringsAsVersions(it.version, osMinVersion) >= 0 } } // Result of `xcrun simctl list runtimes -j`. data class ListRuntimesReport( @Expose val runtimes: List<SimulatorRuntimeDescriptor> ) data class SimulatorRuntimeDescriptor( @Expose val version: String, // bundlePath field may not exist in the old Xcode (prior to 10.3). @Expose val bundlePath: String? = null, @Expose val isAvailable: Boolean? = null, @Expose val availability: String? = null, @Expose val name: String, @Expose val identifier: String, @Expose val buildversion: String ) { /** * Different Xcode/macOS combinations give different fields that checks * runtime availability. This method is an umbrella for these fields. */ fun checkAvailability(): Boolean { if (isAvailable == true) return true if (availability?.contains("unavailable") == true) return false return false } }
build-tools/src/main/kotlin/org/jetbrains/kotlin/XcRunRuntimeUtils.kt
2285143408
package net.nemerosa.ontrack.extension.oidc import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import net.nemerosa.ontrack.extension.oidc.settings.OIDCSettingsService import net.nemerosa.ontrack.extension.oidc.settings.OntrackOIDCProvider import net.nemerosa.ontrack.it.AbstractDSLTestJUnit4Support import net.nemerosa.ontrack.model.security.AccountInput import net.nemerosa.ontrack.model.security.AuthenticationSource import net.nemerosa.ontrack.model.security.ProvidedGroupsService import net.nemerosa.ontrack.model.structure.ID import net.nemerosa.ontrack.test.TestUtils.uid import net.nemerosa.ontrack.test.assertIs import org.junit.After import org.junit.Before import org.junit.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.oauth2.core.oidc.OidcUserInfo import org.springframework.security.oauth2.core.oidc.user.OidcUser import kotlin.test.assertEquals import kotlin.test.assertFailsWith class OntrackOidcUserServiceIT : AbstractDSLTestJUnit4Support() { @Autowired private lateinit var providedGroupsService: ProvidedGroupsService @Autowired private lateinit var oidcSettingsService: OIDCSettingsService private lateinit var userService: OntrackOidcUserService private lateinit var clientRegistration: OntrackClientRegistration private lateinit var oidcUserInfo: OidcUserInfo private lateinit var oidcUser: OidcUser @Before fun before() { userService = OntrackOidcUserService( accountService, securityService, providedGroupsService, oidcSettingsService ) clientRegistration = mock() whenever(clientRegistration.registrationId).thenReturn("test") whenever(clientRegistration.clientName).thenReturn("Test") oidcUserInfo = mock() oidcUser = mock() whenever(oidcUser.userInfo).thenReturn(oidcUserInfo) } @After fun cleanup() { asAdmin { oidcSettingsService.providers.forEach { oidcSettingsService.deleteProvider(it.id) } } } @Test fun `Email not available`() { whenever(oidcUserInfo.email).thenReturn(null) assertFailsWith<OidcEmailRequiredException> { userService.linkOidcUser(clientRegistration, oidcUser) } } @Test fun `Email not filled`() { whenever(oidcUserInfo.email).thenReturn("") assertFailsWith<OidcEmailRequiredException> { userService.linkOidcUser(clientRegistration, oidcUser) } } @Test fun `Account to be created with full name as email`() { val email = "${uid("n")}@nemerosa.net" whenever(oidcUserInfo.email).thenReturn(email) registerProvider() val user = userService.linkOidcUser(clientRegistration, oidcUser) assertIs<OntrackOidcUser>(user) { ontrackUser -> val accountId = ontrackUser.id() asAdmin { val account = accountService.getAccount(ID.of(accountId)) assertEquals(email, account.name) assertEquals(email, account.email) assertEquals(email, account.fullName) assertEquals("oidc", account.authenticationSource.provider) assertEquals("test", account.authenticationSource.key) } } } @Test fun `Account to be created with specified full name`() { val email = "${uid("n")}@nemerosa.net" val fullName = uid("N") whenever(oidcUserInfo.email).thenReturn(email) whenever(oidcUser.fullName).thenReturn(fullName) registerProvider() val user = userService.linkOidcUser(clientRegistration, oidcUser) assertIs<OntrackOidcUser>(user) { ontrackUser -> val accountId = ontrackUser.id() asAdmin { val account = accountService.getAccount(ID.of(accountId)) assertEquals(email, account.name) assertEquals(email, account.email) assertEquals(fullName, account.fullName) assertEquals("oidc", account.authenticationSource.provider) assertEquals("test", account.authenticationSource.key) } } } @Test fun `No filter on groups`() { val email = "${uid("n")}@nemerosa.net" val fullName = uid("N") whenever(oidcUserInfo.email).thenReturn(email) whenever(oidcUser.fullName).thenReturn(fullName) whenever(oidcUser.getClaimAsStringList("groups")).thenReturn( listOf( "ontrack-admins", "ontrack-users", "other-group" ) ) registerProvider() val user = userService.linkOidcUser(clientRegistration, oidcUser) assertIs<OntrackOidcUser>(user) { ontrackUser -> val accountId = ontrackUser.id() asAdmin { val authSource = OidcAuthenticationSourceProvider.asSource(clientRegistration) val groups = providedGroupsService.getProvidedGroups(accountId, authSource) assertEquals( setOf( "ontrack-admins", "ontrack-users", "other-group" ), groups ) } } } @Test fun `Filter on groups`() { val email = "${uid("n")}@nemerosa.net" val fullName = uid("N") whenever(oidcUserInfo.email).thenReturn(email) whenever(oidcUser.fullName).thenReturn(fullName) whenever(oidcUser.getClaimAsStringList("groups")).thenReturn( listOf( "ontrack-admins", "ontrack-users", "other-group" ) ) registerProvider(groupFilter = "ontrack-.*") val user = userService.linkOidcUser(clientRegistration, oidcUser) assertIs<OntrackOidcUser>(user) { ontrackUser -> val accountId = ontrackUser.id() asAdmin { val authSource = OidcAuthenticationSourceProvider.asSource(clientRegistration) val groups = providedGroupsService.getProvidedGroups(accountId, authSource) assertEquals( setOf( "ontrack-admins", "ontrack-users" ), groups ) } } } @Test fun `With existing account`() { val email = "${uid("n")}@nemerosa.net" val fullName = uid("N") whenever(oidcUserInfo.email).thenReturn(email) whenever(oidcUser.fullName).thenReturn(fullName) registerProvider() val user = userService.linkOidcUser(clientRegistration, oidcUser) assertIs<OntrackOidcUser>(user) { ontrackUser -> val account = ontrackUser.account // Logs a second time val secondUser = userService.linkOidcUser(clientRegistration, oidcUser) // Checks the account is the same assertIs<OntrackOidcUser>(secondUser) { assertEquals(account.id, it.account.id, "Using the same account") } } } @Test fun `With existing account from another provider`() { val email = "${uid("n")}@nemerosa.net" val fullName = uid("N") whenever(oidcUserInfo.email).thenReturn(email) whenever(oidcUser.fullName).thenReturn(fullName) registerProvider() registerProvider(id = "other") // Creates an account using this provider asAdmin { accountService.create( AccountInput( name = email, fullName = fullName, email = email, password = null, groups = emptySet(), disabled = false, locked = false, ), AuthenticationSource( provider = "oidc", key = "other", name = "Other" ) ) } assertFailsWith<OidcNonOidcExistingUserException> { userService.linkOidcUser(clientRegistration, oidcUser) } } private fun registerProvider( id: String = "test", name: String = "Test", groupFilter: String? = null ) { asAdmin { val provider = oidcSettingsService.getProviderById(id) if (provider == null) { oidcSettingsService.createProvider( OntrackOIDCProvider( id = id, name = name, description = "", issuerId = "", clientId = "", clientSecret = "", groupFilter = groupFilter, forceHttps = false, disabled = false, ) ) } else { oidcSettingsService.updateProvider( OntrackOIDCProvider( id = id, name = name, description = "", issuerId = "", clientId = "", clientSecret = "", groupFilter = null, forceHttps = false, disabled = false, ) ) } } } }
ontrack-extension-oidc/src/test/java/net/nemerosa/ontrack/extension/oidc/OntrackOidcUserServiceIT.kt
3942150703
/* The MIT License (MIT) Copyright (c) 2016 Tom Needham Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.thomas.needham.neurophidea.designer.editor.snnet import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.NavigatableFileEditor import org.jetbrains.annotations.NotNull /** * Created by thoma on 23/06/2016. */ interface SnnetEditor : NavigatableFileEditor { @NotNull fun getEditor(): Editor? }
neuroph-plugin/src/com/thomas/needham/neurophidea/designer/editor/snnet/SnnetEditor.kt
2075332000
package net.nemerosa.ontrack.extension.scm.catalog.sync import net.nemerosa.ontrack.model.settings.SettingsProvider import net.nemerosa.ontrack.model.support.SettingsRepository import net.nemerosa.ontrack.model.support.getBoolean import net.nemerosa.ontrack.model.support.getString import org.springframework.stereotype.Component /** * Reading the SCM catalog sync settings. */ @Component class SCMCatalogSyncSettingsProvider( private val settingsRepository: SettingsRepository, ) : SettingsProvider<SCMCatalogSyncSettings> { override fun getSettings() = SCMCatalogSyncSettings( syncEnabled = settingsRepository.getBoolean( SCMCatalogSyncSettings::syncEnabled, DEFAULT_SCM_CATALOG_SYNC_SETTINGS_ENABLED ), orphanDisablingEnabled = settingsRepository.getBoolean( SCMCatalogSyncSettings::orphanDisablingEnabled, DEFAULT_SCM_CATALOG_SYNC_SETTINGS_ORPHAN_DISABLED ), scm = settingsRepository.getString( SCMCatalogSyncSettings::scm, DEFAULT_SCM_CATALOG_SYNC_SETTINGS_SCM ), config = settingsRepository.getString( SCMCatalogSyncSettings::config, DEFAULT_SCM_CATALOG_SYNC_SETTINGS_CONFIG ), repository = settingsRepository.getString( SCMCatalogSyncSettings::repository, DEFAULT_SCM_CATALOG_SYNC_SETTINGS_REPOSITORY ), ) override fun getSettingsClass(): Class<SCMCatalogSyncSettings> = SCMCatalogSyncSettings::class.java }
ontrack-extension-scm/src/main/java/net/nemerosa/ontrack/extension/scm/catalog/sync/SCMCatalogSyncSettingsProvider.kt
4143229876
package io.sportner.cblmapper.mappers import com.couchbase.lite.internal.utils.DateUtils import java.util.* import kotlin.reflect.KClass import kotlin.reflect.KTypeProjection class DateDefaultTypeAdapter : CBLMTypeAdapter<Date> { override fun decode(value: Any?, typeOfT: KClass<Date>, typesParameter: List<KTypeProjection>?, context: CBLMapperDecoderContext): Date? { return DateUtils.fromJson(value as String?) } override fun encode(value: Any, typeOfT: KClass<Date>, typesParameter: List<KTypeProjection>?, context: CBLMapperEncoderContext): Any? { return DateUtils.toJson(value as Date) } }
cblmapper/src/main/java/io/sportner/cblmapper/mappers/DateDefaultTypeAdapter.kt
3398871125
package graphql.execution import graphql.ExecutionResult import graphql.ExecutionResultImpl import graphql.GraphQLException import graphql.language.Field import graphql.schema.GraphQLObjectType import java.util.LinkedHashMap import java.util.concurrent.* /** * * ExecutorServiceExecutionStrategy uses an [ExecutorService] to parallelize the resolve. * Due to the nature of [.execute] implementation, [ExecutorService] * MUST have the following 2 characteristics: * * * 1. The underlying [java.util.concurrent.ThreadPoolExecutor] MUST have a reasonable `maximumPoolSize` * * 2. The underlying [java.util.concurrent.ThreadPoolExecutor] SHALL NOT use its task queue. * * * Failure to follow 1. and 2. can result in a very large number of threads created or hanging. (deadlock) * See `graphql.execution.ExecutorServiceExecutionStrategyTest` for example usage. */ class ExecutorServiceExecutionStrategy(val executorService: ExecutorService) : AbstractExecutionStrategy() { override fun execute(executionContext: ExecutionContext, parentType: GraphQLObjectType, source: Any, fields: Map<String, List<Field>>): CompletionStage<ExecutionResult> { val futures = fields.asSequence() .associateBy({ it.key }) { executorService.submit( Callable { resolveField(executionContext, parentType, source, it.value) }) } try { val promise = CompletableFuture<ExecutionResult>() val results = LinkedHashMap<String, Any?>() for ((fieldName, future) in futures) { future.get().thenAccept({ executionResult -> results.put(fieldName, executionResult?.data()) // Last one to finish completes the promise if (results.size == futures.keys.size) { promise.complete(ExecutionResultImpl(results, executionContext.errors())) } }) } return promise } catch (e: InterruptedException) { throw GraphQLException(e) } catch (e: ExecutionException) { throw GraphQLException(e) } } }
src/main/kotlin/graphql/execution/ExecutorServiceExecutionStrategy.kt
3011246998
package com.beust.kobalt.app.remote import com.beust.kobalt.api.ITemplate import com.beust.kobalt.app.Templates import com.beust.kobalt.internal.PluginInfo import com.google.common.collect.ListMultimap import com.google.gson.Gson import org.slf4j.Logger import spark.ResponseTransformer import spark.Route import spark.Spark import java.util.concurrent.Executors class SparkServer(val cleanUpCallback: () -> Unit, val pluginInfo : PluginInfo) : KobaltServer.IServer { companion object { lateinit var cleanUpCallback: () -> Unit val URL_QUIT = "/quit" lateinit var watchDog: WatchDog } init { SparkServer.cleanUpCallback = cleanUpCallback } class JsonTransformer : ResponseTransformer { val gson = Gson() override fun render(model: Any) = gson.toJson(model) } private fun jsonRoute(path: String, route: Route) = Spark.get(path, "application/json", route, JsonTransformer()) val log: Logger = org.slf4j.LoggerFactory.getLogger("SparkServer") override fun run(port: Int) { val threadPool = Executors.newFixedThreadPool(2) watchDog = WatchDog(port, 60 * 10 /* 10 minutes */, log) threadPool.submit { watchDog.run() } log.debug("Server running") Spark.port(port) Spark.webSocket("/v1/getDependencyGraph", GetDependencyGraphHandler::class.java) Spark.get("/ping") { req, res -> watchDog.rearm() log.debug(" Received ping") """ { "result" : "ok" } """ } Spark.get(URL_QUIT, { req, res -> log.debug(" Received quit") threadPool.let { executor -> executor.submit { Thread.sleep(1000) Spark.stop() executor.shutdown() } KobaltServer.OK } }) jsonRoute("/v0/getTemplates", Route { request, response -> TemplatesData.create(Templates().getTemplates(pluginInfo)) }) Spark.init() } } class ProgressCommand(val progress: Int? = null, val message: String? = null) { companion object { val NAME = "ProgressCommand" } } class WebSocketCommand(val commandName: String, val errorMessage: String? = null, val payload: String) class TemplateData(val pluginName: String, val templates: List<String>) class TemplatesData(val templates: List<TemplateData>) { companion object { fun create(map: ListMultimap<String, ITemplate>) : TemplatesData { val templateList = arrayListOf<TemplateData>() map.keySet().forEach { pluginName -> val list = map[pluginName].map { it.templateName } templateList.add(TemplateData(pluginName, list)) } return TemplatesData(templateList) } } }
src/main/kotlin/com/beust/kobalt/app/remote/SparkServer.kt
2230976468
package gg.octave.bot.commands.music.search import com.jagrosh.jdautilities.menu.Selector import com.jagrosh.jdautilities.menu.SelectorBuilder import gg.octave.bot.Launcher import gg.octave.bot.listeners.FlightEventAdapter import gg.octave.bot.music.MusicLimitException import gg.octave.bot.music.MusicManager import gg.octave.bot.music.TrackContext import gg.octave.bot.music.TrackScheduler import gg.octave.bot.utils.extensions.config import gg.octave.bot.utils.extensions.data import gg.octave.bot.utils.extensions.selfMember import gg.octave.bot.utils.extensions.voiceChannel import gg.octave.bot.utils.getDisplayValue import me.devoxin.flight.api.Context import me.devoxin.flight.api.annotations.Command import me.devoxin.flight.api.annotations.Greedy import me.devoxin.flight.api.entities.Cog import net.dv8tion.jda.api.EmbedBuilder import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit class Play : Cog { @Command(aliases = ["p"], description = "Plays music in a voice channel.") fun play(ctx: Context, @Greedy query: String?) { val botChannel = ctx.selfMember!!.voiceState?.channel val userChannel = ctx.voiceChannel if (botChannel != null && botChannel != userChannel) { return ctx.send("The bot is already playing music in another channel.") } val manager = Launcher.players.getExisting(ctx.guild) if (query == null) { if (manager == null) { return ctx.send("There's no music player in this guild.\n\uD83C\uDFB6` ${ctx.trigger}play (song/url)` to start playing some music!") } when { manager.player.isPaused -> { manager.player.isPaused = false ctx.send { setTitle("Play Music") setDescription("Music is no longer paused.") } } manager.player.playingTrack != null -> { ctx.send("Music is already playing. Are you trying to queue a track? Try adding a search term with this command!") } manager.scheduler.queue.isEmpty() -> { ctx.send { setTitle("Empty Queue") setDescription("There is no music queued right now. Add some songs with `${ctx.trigger}play (song/url)`.") } } } return } val args = query.split(" +".toRegex()).toTypedArray() prompt(ctx, manager).handle { _, _ -> if (ctx.data.music.isVotePlay && !FlightEventAdapter.isDJ(ctx, false)) { val newManager = try { Launcher.players.get(ctx.guild) } catch (e: MusicLimitException) { return@handle e.sendToContext(ctx) } startPlayVote(ctx, newManager, args, false, "") } else { play(ctx, args, false, "") } }.exceptionally { ctx.send("An error occurred!") it.printStackTrace() return@exceptionally } } private fun prompt(ctx: Context, manager: MusicManager?): CompletableFuture<Void> { val future = CompletableFuture<Void>() val oldQueue = TrackScheduler.getQueueForGuild(ctx.guild!!.id) if (manager == null && !oldQueue.isEmpty()) { SelectorBuilder(Launcher.eventWaiter) .setType(Selector.Type.MESSAGE) .title { "Would you like to keep your old queue?" } .description { "Thanks for using Octave!" } .addOption("Yes, keep it.") { ctx.send("Kept old queue. Playing new song first and continuing with your queue...") future.complete(null) }.addOption("No, start a new queue.") { oldQueue.clear() ctx.send("Scrapped old queue. A new queue will start.") future.complete(null) }.build().display(ctx.textChannel!!) } else { future.complete(null) } return future } companion object { fun play(ctx: Context, args: Array<String>, isSearchResult: Boolean, uri: String) { val manager = try { Launcher.players.get(ctx.guild) } catch (e: MusicLimitException) { return e.sendToContext(ctx) } val config = ctx.config //Reset expire time if play has been called. manager.scheduler.queue.clearExpire() val query = when { "https://" in args[0] || "http://" in args[0] || args[0].startsWith("spotify:") -> { args[0].removePrefix("<").removeSuffix(">") } isSearchResult -> uri else -> "ytsearch:${args.joinToString(" ").trim()}" } val trackContext = TrackContext(ctx.author.idLong, ctx.textChannel!!.idLong) manager.loadAndPlay( ctx, query, trackContext, if (!isSearchResult) "You can search and pick results using ${config.prefix}youtube or ${config.prefix}soundcloud while in a channel." else null ) } fun startPlayVote(ctx: Context, manager: MusicManager, args: Array<String>, isSearchResult: Boolean, uri: String) { if (manager.isVotingToPlay) { return ctx.send("There is already a vote going on!") } val data = ctx.data val voteSkipCooldown = if (data.music.votePlayCooldown <= 0) { ctx.config.votePlayCooldown.toMillis() } else { data.music.votePlayCooldown } if (System.currentTimeMillis() - manager.lastPlayVoteTime < voteSkipCooldown) { return ctx.send("You must wait $voteSkipCooldown before starting a new vote.") } val votePlayDuration = if (data.music.votePlayDuration == 0L) { data.music.votePlayDuration } else { ctx.config.votePlayDuration.toMillis() } val votePlayDurationText = if (data.music.votePlayDuration == 0L) { ctx.config.votePlayDurationText } else { getDisplayValue(data.music.votePlayDuration) } manager.lastPlayVoteTime = System.currentTimeMillis() manager.isVotingToPlay = true val channel = ctx.selfMember!!.voiceState!!.channel ?: ctx.voiceChannel!! val halfPeople = channel.members.filter { !it.user.isBot }.size / 2 ctx.messageChannel.sendMessage(EmbedBuilder().apply { setTitle("Vote Play") setDescription( buildString { append(ctx.author.asMention) append(" has voted to **play** a track!") append(" React with :thumbsup:\n") append("If there are more than $halfPeople vote(s) within $votePlayDurationText, the track will be queued.") } ) }.build()) .submit() .thenCompose { m -> m.addReaction("👍") .submit() .thenApply { m } } .thenCompose { it.editMessage(EmbedBuilder(it.embeds[0]) .apply { setDescription("Voting has ended! Check the newer messages for results.") clearFields() }.build() ).submitAfter(votePlayDuration, TimeUnit.MILLISECONDS) }.thenAccept { m -> val votes = m.reactions.firstOrNull { it.reactionEmote.name == "👍" }?.count?.minus(1) ?: 0 ctx.send { setTitle("Vote Skip") setDescription( buildString { if (votes > halfPeople) { appendln("The vote has passed! The song will be queued.") play(ctx, args, isSearchResult, uri) } else { appendln("The vote has failed! The song will not be queued.") } } ) addField("Results", "__$votes Play Votes__", false) } }.whenComplete { _, _ -> manager.isVotingToPlay = false } } } }
src/main/kotlin/gg/octave/bot/commands/music/search/Play.kt
835715241
package be.florien.anyflow.data.user import be.florien.anyflow.data.PingService import be.florien.anyflow.data.UpdateService import be.florien.anyflow.data.server.AmpacheApi import be.florien.anyflow.injection.PlayerComponent import be.florien.anyflow.injection.QuickActionsComponent import be.florien.anyflow.injection.UserScope import be.florien.anyflow.player.PlayerService import dagger.BindsInstance import dagger.Subcomponent /** * Component used to add dependency injection about data into classes */ @UserScope @Subcomponent(modules = [UserModule::class]) interface UserComponent { fun inject(playerService: PlayerService) fun inject(updateService: UpdateService) fun inject(pingService: PingService) fun playerComponentBuilder(): PlayerComponent.Builder fun quickActionsComponentBuilder(): QuickActionsComponent.Builder @Subcomponent.Builder interface Builder { @BindsInstance fun ampacheApi(ampacheApi: AmpacheApi): Builder fun build(): UserComponent } }
app/src/main/java/be/florien/anyflow/data/user/UserComponent.kt
2813474398
/* * * Nextcloud Android client application * * @author Tobias Kaminsky * Copyright (C) 2022 Tobias Kaminsky * Copyright (C) 2022 Nextcloud GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.nextcloud.client.jobs import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import androidx.core.app.NotificationCompat import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.work.Worker import androidx.work.WorkerParameters import com.nextcloud.client.account.User import com.nextcloud.client.account.UserAccountManager import com.nextcloud.client.device.PowerManagementService import com.nextcloud.client.network.ConnectivityService import com.nextcloud.client.utils.FileUploaderDelegate import com.owncloud.android.R import com.owncloud.android.datamodel.FileDataStorageManager import com.owncloud.android.datamodel.ThumbnailsCacheManager import com.owncloud.android.datamodel.UploadsStorageManager import com.owncloud.android.db.OCUpload import com.owncloud.android.lib.common.OwnCloudAccount import com.owncloud.android.lib.common.OwnCloudClientManagerFactory import com.owncloud.android.lib.common.network.OnDatatransferProgressListener import com.owncloud.android.lib.common.operations.RemoteOperationResult import com.owncloud.android.lib.common.utils.Log_OC import com.owncloud.android.lib.resources.files.FileUtils import com.owncloud.android.operations.UploadFileOperation import com.owncloud.android.ui.activity.UploadListActivity import com.owncloud.android.ui.notifications.NotificationUtils import com.owncloud.android.utils.theme.ViewThemeUtils import java.io.File @Suppress("LongParameterList") class FilesUploadWorker( val uploadsStorageManager: UploadsStorageManager, val connectivityService: ConnectivityService, val powerManagementService: PowerManagementService, val userAccountManager: UserAccountManager, val viewThemeUtils: ViewThemeUtils, val localBroadcastManager: LocalBroadcastManager, val context: Context, params: WorkerParameters ) : Worker(context, params), OnDatatransferProgressListener { private var lastPercent = 0 private val notificationBuilder: NotificationCompat.Builder = NotificationUtils.newNotificationBuilder(context, viewThemeUtils) private val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager private val fileUploaderDelegate = FileUploaderDelegate() override fun doWork(): Result { val accountName = inputData.getString(ACCOUNT) if (accountName.isNullOrEmpty()) { Log_OC.w(TAG, "User was null for file upload worker") return Result.failure() // user account is needed } // get all pending uploads var currentAndPendingUploadsForAccount = uploadsStorageManager.getCurrentAndPendingUploadsForAccount(MAX_UPLOADS_QUERY, accountName) while (currentAndPendingUploadsForAccount.isNotEmpty()) { Log_OC.d(TAG, "Handling ${currentAndPendingUploadsForAccount.size} uploads for account $accountName") handlePendingUploads(currentAndPendingUploadsForAccount, accountName) currentAndPendingUploadsForAccount = uploadsStorageManager.getCurrentAndPendingUploadsForAccount(MAX_UPLOADS_QUERY, accountName) } Log_OC.d(TAG, "No more pending uploads for account $accountName, stopping work") return Result.success() } private fun handlePendingUploads(uploads: Array<OCUpload>, accountName: String) { val user = userAccountManager.getUser(accountName) for (upload in uploads) { // create upload file operation if (user.isPresent) { val uploadFileOperation = createUploadFileOperation(upload, user.get()) val result = upload(uploadFileOperation, user.get()) fileUploaderDelegate.sendBroadcastUploadFinished( uploadFileOperation, result, uploadFileOperation.oldFile?.storagePath, context, localBroadcastManager ) } else { // user not present anymore, remove upload uploadsStorageManager.removeUpload(upload.uploadId) } } } /** * from @{link FileUploader#retryUploads()} */ private fun createUploadFileOperation(upload: OCUpload, user: User): UploadFileOperation { return UploadFileOperation( uploadsStorageManager, connectivityService, powerManagementService, user, null, upload, upload.nameCollisionPolicy, upload.localAction, context, upload.isUseWifiOnly, upload.isWhileChargingOnly, true, FileDataStorageManager(user, context.contentResolver) ).apply { addDataTransferProgressListener(this@FilesUploadWorker) } } @Suppress("TooGenericExceptionCaught") private fun upload(uploadFileOperation: UploadFileOperation, user: User): RemoteOperationResult<Any?> { lateinit var uploadResult: RemoteOperationResult<Any?> // start notification createNotification(uploadFileOperation) try { val storageManager = uploadFileOperation.storageManager // always get client from client manager, to get fresh credentials in case of update val ocAccount = OwnCloudAccount(user.toPlatformAccount(), context) val uploadClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, context) uploadResult = uploadFileOperation.execute(uploadClient) // generate new Thumbnail val task = ThumbnailsCacheManager.ThumbnailGenerationTask(storageManager, user) val file = File(uploadFileOperation.originalStoragePath) val remoteId: String? = uploadFileOperation.file.remoteId task.execute(ThumbnailsCacheManager.ThumbnailGenerationTaskObject(file, remoteId)) } catch (e: Exception) { Log_OC.e(TAG, "Error uploading", e) uploadResult = RemoteOperationResult<Any?>(e) } finally { uploadsStorageManager.updateDatabaseUploadResult(uploadResult, uploadFileOperation) // cancel notification notificationManager.cancel(FOREGROUND_SERVICE_ID) } return uploadResult } /** * adapted from [com.owncloud.android.files.services.FileUploader.notifyUploadStart] */ private fun createNotification(uploadFileOperation: UploadFileOperation) { notificationBuilder .setOngoing(true) .setSmallIcon(R.drawable.notification_icon) .setTicker(context.getString(R.string.uploader_upload_in_progress_ticker)) .setProgress(MAX_PROGRESS, 0, false) .setContentText( String.format( context.getString(R.string.uploader_upload_in_progress_content), 0, uploadFileOperation.fileName ) ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationBuilder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_UPLOAD) } // includes a pending intent in the notification showing the details val intent = UploadListActivity.createIntent( uploadFileOperation.file, uploadFileOperation.user, Intent.FLAG_ACTIVITY_CLEAR_TOP, context ) notificationBuilder.setContentIntent( PendingIntent.getActivity( context, System.currentTimeMillis().toInt(), intent, PendingIntent.FLAG_IMMUTABLE ) ) if (!uploadFileOperation.isInstantPicture && !uploadFileOperation.isInstantVideo) { notificationManager.notify(FOREGROUND_SERVICE_ID, notificationBuilder.build()) } // else wait until the upload really start (onTransferProgress is called), so that if it's discarded // due to lack of Wifi, no notification is shown // TODO generalize for automated uploads } /** * see [com.owncloud.android.files.services.FileUploader.onTransferProgress] */ override fun onTransferProgress( progressRate: Long, totalTransferredSoFar: Long, totalToTransfer: Long, fileAbsoluteName: String ) { val percent = (MAX_PROGRESS * totalTransferredSoFar.toDouble() / totalToTransfer.toDouble()).toInt() if (percent != lastPercent) { notificationBuilder.setProgress(MAX_PROGRESS, percent, false) val fileName: String = fileAbsoluteName.substring(fileAbsoluteName.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1) val text = String.format(context.getString(R.string.uploader_upload_in_progress_content), percent, fileName) notificationBuilder.setContentText(text) notificationManager.notify(FOREGROUND_SERVICE_ID, notificationBuilder.build()) } lastPercent = percent } companion object { val TAG: String = FilesUploadWorker::class.java.simpleName private const val MAX_UPLOADS_QUERY = 100 private const val FOREGROUND_SERVICE_ID: Int = 412 private const val MAX_PROGRESS: Int = 100 const val ACCOUNT = "data_account" } }
app/src/main/java/com/nextcloud/client/jobs/FilesUploadWorker.kt
53228578
// 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.execution.impl import com.intellij.execution.application.ApplicationConfigurationType import com.intellij.execution.impl.RunConfigurableNodeKind.* import com.intellij.execution.junit.JUnitConfigurationType import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.Trinity import com.intellij.testFramework.DisposableRule import com.intellij.testFramework.EdtRule import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.RunsInEdt import com.intellij.testFramework.assertions.Assertions.assertThat import com.intellij.ui.RowsDnDSupport import com.intellij.ui.RowsDnDSupport.RefinedDropSupport.Position.* import com.intellij.ui.treeStructure.Tree import org.jdom.Element import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.util.* import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.TreePath private val ORDER = arrayOf(CONFIGURATION_TYPE, //Application FOLDER, //1 CONFIGURATION, CONFIGURATION, CONFIGURATION, CONFIGURATION, CONFIGURATION, TEMPORARY_CONFIGURATION, TEMPORARY_CONFIGURATION, FOLDER, //2 TEMPORARY_CONFIGURATION, FOLDER, //3 CONFIGURATION, TEMPORARY_CONFIGURATION, CONFIGURATION_TYPE, //JUnit FOLDER, //4 CONFIGURATION, CONFIGURATION, FOLDER, //5 CONFIGURATION, CONFIGURATION, TEMPORARY_CONFIGURATION, UNKNOWN //Defaults ) @RunsInEdt internal class RunConfigurableTest { companion object { @JvmField @ClassRule val projectRule = ProjectRule() private fun createRunManager(element: Element): RunManagerImpl { val runManager = RunManagerImpl(projectRule.project) runManager.initializeConfigurationTypes(listOf(ApplicationConfigurationType.getInstance(), JUnitConfigurationType.getInstance())) runManager.loadState(element) return runManager } private class MockRunConfigurable(override val runManager: RunManagerImpl) : RunConfigurable(projectRule.project) { init { createComponent() } } } @JvmField @Rule val edtRule = EdtRule() @JvmField @Rule val disposableRule = DisposableRule() private val configurable by lazy { val result = MockRunConfigurable(createRunManager(JDOMUtil.load(RunConfigurableTest::class.java.getResourceAsStream("folders.xml")))) Disposer.register(disposableRule.disposable, result) result } private val root: DefaultMutableTreeNode get() = configurable.root private val tree: Tree get() = configurable.tree private val model: RunConfigurable.MyTreeModel get() = configurable.treeModel @Test fun dnd() { doExpand() val never = intArrayOf(-1, 0, 14, 22, 23, 999) for (i in -1..16) { for (j in never) { if ((j == 14 || j == 21) && i == j) { continue } assertCannot(j, i, ABOVE) assertCannot(j, i, INTO) assertCannot(j, i, BELOW) } } assertCan(3, 3, BELOW) assertCan(3, 3, ABOVE) assertCannot(3, 2, BELOW) assertCan(3, 2, ABOVE) assertCannot(3, 1, BELOW) assertCannot(3, 0, BELOW) assertCan(2, 14, ABOVE) assertCan(1, 14, ABOVE) assertCan(1, 11, ABOVE) assertCannot(1, 10, ABOVE) assertCannot(1, 10, BELOW) assertCannot(8, 6, ABOVE) assertCan(8, 6, BELOW) assertCannot(5, 7, BELOW) assertCan(5, 7, ABOVE) assertCannot(15, 11, INTO) assertCannot(18, 21, ABOVE) assertCan(15, 21, ABOVE) assertThat(model.isDropInto(tree, 2, 9)).isTrue() assertThat(model.isDropInto(tree, 2, 1)).isTrue() assertThat(model.isDropInto(tree, 12, 9)).isTrue() assertThat(model.isDropInto(tree, 12, 1)).isTrue() assertThat(model.isDropInto(tree, 999, 9)).isFalse() assertThat(model.isDropInto(tree, 999, 1)).isFalse() assertThat(model.isDropInto(tree, 2, 999)).isFalse() assertThat(model.isDropInto(tree, 2, -1)).isFalse() } private fun doExpand() { val toExpand = ArrayList<DefaultMutableTreeNode>() RunConfigurable.collectNodesRecursively(root, toExpand, FOLDER) assertThat(toExpand).hasSize(5) val toExpand2 = ArrayList<DefaultMutableTreeNode>() RunConfigurable.collectNodesRecursively(root, toExpand2, CONFIGURATION_TYPE) toExpand.addAll(toExpand2) for (node in toExpand) { tree.expandPath(TreePath(node.path)) } assertThat(ORDER.mapIndexed { index, _ -> RunConfigurable.getKind(tree.getPathForRow(index).lastPathComponent as DefaultMutableTreeNode) }).containsExactly(*ORDER) } private fun assertCan(oldIndex: Int, newIndex: Int, position: RowsDnDSupport.RefinedDropSupport.Position) { assertDrop(oldIndex, newIndex, position, true) } private fun assertCannot(oldIndex: Int, newIndex: Int, position: RowsDnDSupport.RefinedDropSupport.Position) { assertDrop(oldIndex, newIndex, position, false) } private fun assertDrop(oldIndex: Int, newIndex: Int, position: RowsDnDSupport.RefinedDropSupport.Position, canDrop: Boolean) { val message = StringBuilder() message.append("(").append(oldIndex).append(")").append(tree.getPathForRow(oldIndex)).append("->") message.append("(").append(newIndex).append(")").append(tree.getPathForRow(newIndex)).append(position) if (canDrop) { // message.toString() assertThat(model.canDrop(oldIndex, newIndex, position)).isTrue() } else { // message.toString() assertThat(model.canDrop(oldIndex, newIndex, position)).isFalse() } } @Test fun testMoveUpDown() { doExpand() checkPositionToMove(0, 1, null) checkPositionToMove(2, 1, Trinity.create<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>(2, 3, BELOW)) checkPositionToMove(2, -1, null) checkPositionToMove(14, 1, null) checkPositionToMove(14, -1, null) checkPositionToMove(15, -1, null) checkPositionToMove(16, -1, null) checkPositionToMove(3, -1, Trinity.create<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>(3, 2, ABOVE)) checkPositionToMove(6, 1, Trinity.create<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>(6, 9, BELOW)) checkPositionToMove(7, 1, Trinity.create<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>(7, 8, BELOW)) checkPositionToMove(10, -1, Trinity.create<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>(10, 8, BELOW)) checkPositionToMove(8, 1, Trinity.create<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>(8, 9, BELOW)) checkPositionToMove(21, -1, Trinity.create<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>(21, 20, BELOW)) checkPositionToMove(21, 1, null) checkPositionToMove(20, 1, Trinity.create<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>(20, 21, ABOVE)) checkPositionToMove(20, -1, Trinity.create<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>(20, 19, ABOVE)) checkPositionToMove(19, 1, Trinity.create<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>(19, 20, BELOW)) checkPositionToMove(19, -1, Trinity.create<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>(19, 17, BELOW)) checkPositionToMove(17, -1, Trinity.create<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>(17, 16, ABOVE)) checkPositionToMove(17, 1, Trinity.create<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>(17, 18, BELOW)) } private fun checkPositionToMove(selectedRow: Int, direction: Int, expected: Trinity<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>?) { tree.setSelectionRow(selectedRow) assertThat(configurable.getAvailableDropPosition(direction)).isEqualTo(expected) } @Test fun sort() { doExpand() assertThat(configurable.isModified).isFalse() model.drop(2, 0, ABOVE) assertThat(configurable.isModified).isTrue() configurable.apply() assertThat(configurable.runManager.allSettings.map { it.name }).containsExactly("Renamer", "UI", "AuTest", "Simples", "OutAndErr", "C148C_TersePrincess", "Periods", "C148E_Porcelain", "ErrAndOut", "All in titled", "All in titled2", "All in titled3", "All in titled4", "All in titled5") assertThat(configurable.isModified).isFalse() model.drop(4, 8, BELOW) configurable.apply() assertThat(configurable.runManager.allSettings.map { it.name }).isEqualTo(listOf("Renamer", "AuTest", "Simples", "UI", "OutAndErr", "C148C_TersePrincess", "Periods", "C148E_Porcelain", "ErrAndOut", "All in titled", "All in titled2", "All in titled3", "All in titled4", "All in titled5")) } }
java/java-tests/testSrc/com/intellij/execution/impl/RunConfigurableTest.kt
2520364699