content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
// WITH_STDLIB
// SUGGESTED_NAMES: triple, intIntIntTriple, intIntTriple, intTriple, getT
// PARAM_TYPES: kotlin.Int
// PARAM_TYPES: kotlin.Int
// PARAM_TYPES: kotlin.Int
// PARAM_DESCRIPTOR: value-parameter a: kotlin.Int defined in foo
// PARAM_DESCRIPTOR: var b: kotlin.Int defined in foo
// PARAM_DESCRIPTOR: var c: kotlin.Int defined in foo
// SIBLING:
fun foo(a: Int): Int {
var b: Int = 1
var c: Int = 2
val t = <selection>if (a > 0) {
b += a
c -= b
b
}
else {
a
}</selection>
println(b + c)
return t
} | plugins/kotlin/idea/tests/testData/refactoring/extractFunction/controlFlow/outputValues/outputValuesWithExpression.kt | 3180206203 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.search.usagesSearch
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.util.MethodSignatureUtil
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.lazyPub
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.project.getNullableModuleInfo
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.resolveToParameterDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMemberDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMethodDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaOrKotlinMemberDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.hasJavaResolutionFacade
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.compiler.IDELanguageSettingsProvider
import org.jetbrains.kotlin.idea.project.TargetPlatformDetector
import org.jetbrains.kotlin.idea.project.findAnalyzerServices
import org.jetbrains.kotlin.idea.references.unwrappedTargets
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport
import org.jetbrains.kotlin.idea.search.ReceiverTypeSearcherInfo
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions
import org.jetbrains.kotlin.idea.util.FuzzyType
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.fuzzyExtensionReceiverType
import org.jetbrains.kotlin.idea.util.toFuzzyType
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.descriptorUtil.isTypeRefinementEnabled
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.sam.getSingleAbstractMethodOrNull
import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.util.isValidOperator
@Deprecated(
"This method is obsolete and will be removed",
ReplaceWith(
"resolveToDescriptorIfAny(BodyResolveMode.FULL)",
"org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny",
"org.jetbrains.kotlin.resolve.lazy.BodyResolveMode"
)
)
@get:JvmName("getDescriptor")
val KtDeclaration.descriptorCompat: DeclarationDescriptor?
get() = if (this is KtParameter) this.descriptorCompat else this.resolveToDescriptorIfAny(BodyResolveMode.FULL)
@Deprecated(
"This method is obsolete and will be removed",
ReplaceWith(
"resolveToParameterDescriptorIfAny(BodyResolveMode.FULL)",
"org.jetbrains.kotlin.idea.caches.resolve.resolveToParameterDescriptorIfAny",
"org.jetbrains.kotlin.resolve.lazy.BodyResolveMode"
)
)
@get:JvmName("getDescriptor")
val KtParameter.descriptorCompat: ValueParameterDescriptor?
get() = this.resolveToParameterDescriptorIfAny(BodyResolveMode.FULL)
class KotlinConstructorCallLazyDescriptorHandle(ktElement: KtDeclaration) :
KotlinSearchUsagesSupport.ConstructorCallHandle {
private val descriptor: ConstructorDescriptor? by lazyPub { ktElement.constructor }
override fun referencedTo(element: KtElement): Boolean =
element.getConstructorCallDescriptor().let {
it != null && descriptor != null && it == descriptor
}
}
class JavaConstructorCallLazyDescriptorHandle(psiMethod: PsiMethod) :
KotlinSearchUsagesSupport.ConstructorCallHandle {
private val descriptor: ConstructorDescriptor? by lazyPub { psiMethod.getJavaMethodDescriptor() as? ConstructorDescriptor }
override fun referencedTo(element: KtElement): Boolean =
element.getConstructorCallDescriptor().let {
it != null && descriptor != null && it == descriptor
}
}
fun tryRenderDeclarationCompactStyle(declaration: KtDeclaration): String? =
declaration.descriptor?.let { DescriptorRenderer.COMPACT.render(it) }
fun isSamInterface(psiClass: PsiClass): Boolean {
val classDescriptor = psiClass.getJavaMemberDescriptor() as? JavaClassDescriptor
return classDescriptor != null && getSingleAbstractMethodOrNull(classDescriptor) != null
}
fun hasType(element: KtExpression): Boolean =
element.analyze(BodyResolveMode.PARTIAL).getType(element) != null
val KtDeclaration.constructor: ConstructorDescriptor?
get() {
val context = this.analyze()
return when (this) {
is KtClassOrObject -> context[BindingContext.CLASS, this]?.unsubstitutedPrimaryConstructor
is KtFunction -> context[BindingContext.CONSTRUCTOR, this]
else -> null
}
}
val KtParameter.propertyDescriptor: PropertyDescriptor?
get() = this.resolveToDescriptorIfAny(BodyResolveMode.FULL) as? PropertyDescriptor
fun PsiReference.checkUsageVsOriginalDescriptor(
targetDescriptor: DeclarationDescriptor,
declarationToDescriptor: (KtDeclaration) -> DeclarationDescriptor? = { it.descriptor },
checker: (usageDescriptor: DeclarationDescriptor, targetDescriptor: DeclarationDescriptor) -> Boolean
): Boolean {
return unwrappedTargets
.filterIsInstance<KtDeclaration>()
.any {
val usageDescriptor = declarationToDescriptor(it)
usageDescriptor != null && checker(usageDescriptor, targetDescriptor)
}
}
fun PsiReference.isConstructorUsage(ktClassOrObject: KtClassOrObject): Boolean = with(element) {
fun checkJavaUsage(): Boolean {
val call = getNonStrictParentOfType<PsiConstructorCall>()
return call == parent && call?.resolveConstructor()?.containingClass?.navigationElement == ktClassOrObject
}
fun checkKotlinUsage(): Boolean {
if (this !is KtElement) return false
val descriptor = getConstructorCallDescriptor() as? ConstructorDescriptor ?: return false
val declaration = DescriptorToSourceUtils.descriptorToDeclaration(descriptor.containingDeclaration)
return declaration == ktClassOrObject || (declaration is KtConstructor<*> && declaration.getContainingClassOrObject() == ktClassOrObject)
}
checkJavaUsage() || checkKotlinUsage()
}
private fun KtElement.getConstructorCallDescriptor(): DeclarationDescriptor? {
val bindingContext = this.analyze()
val constructorCalleeExpression = getNonStrictParentOfType<KtConstructorCalleeExpression>()
if (constructorCalleeExpression != null) {
return bindingContext.get(BindingContext.REFERENCE_TARGET, constructorCalleeExpression.constructorReferenceExpression)
}
val callExpression = getNonStrictParentOfType<KtCallElement>()
if (callExpression != null) {
val callee = callExpression.calleeExpression
if (callee is KtReferenceExpression) {
return bindingContext.get(BindingContext.REFERENCE_TARGET, callee)
}
}
return null
}
// Check if reference resolves to extension function whose receiver is the same as declaration's parent (or its superclass)
// Used in extension search
fun PsiReference.isExtensionOfDeclarationClassUsage(declaration: KtNamedDeclaration): Boolean {
val descriptor = declaration.descriptor ?: return false
return checkUsageVsOriginalDescriptor(descriptor) { usageDescriptor, targetDescriptor ->
when (usageDescriptor) {
targetDescriptor -> false
!is FunctionDescriptor -> false
else -> {
val receiverDescriptor =
usageDescriptor.extensionReceiverParameter?.type?.constructor?.declarationDescriptor
val containingDescriptor = targetDescriptor.containingDeclaration
containingDescriptor == receiverDescriptor
|| (containingDescriptor is ClassDescriptor
&& receiverDescriptor is ClassDescriptor
&& DescriptorUtils.isSubclass(containingDescriptor, receiverDescriptor))
}
}
}
}
// Check if reference resolves to the declaration with the same parent
// Used in overload search
fun PsiReference.isUsageInContainingDeclaration(declaration: KtNamedDeclaration): Boolean {
val descriptor = declaration.descriptor ?: return false
return checkUsageVsOriginalDescriptor(descriptor) { usageDescriptor, targetDescriptor ->
usageDescriptor != targetDescriptor
&& usageDescriptor.containingDeclaration == targetDescriptor.containingDeclaration
}
}
fun PsiReference.isCallableOverrideUsage(declaration: KtNamedDeclaration): Boolean {
val toDescriptor: (KtDeclaration) -> CallableDescriptor? = { sourceDeclaration ->
if (sourceDeclaration is KtParameter) {
// we don't treat parameters in overriding method as "override" here (overriding parameters usages are searched optionally and via searching of overriding methods first)
if (sourceDeclaration.hasValOrVar()) sourceDeclaration.propertyDescriptor else null
} else {
sourceDeclaration.descriptor as? CallableDescriptor
}
}
val targetDescriptor = toDescriptor(declaration) ?: return false
return unwrappedTargets.any {
when (it) {
is KtDeclaration -> {
val usageDescriptor = toDescriptor(it)
usageDescriptor != null && OverridingUtil.overrides(
usageDescriptor,
targetDescriptor,
usageDescriptor.module.isTypeRefinementEnabled(),
false // don't distinguish between expect and non-expect callable descriptors, KT-38298, KT-38589
)
}
is PsiMethod -> {
declaration.toLightMethods().any { superMethod -> MethodSignatureUtil.isSuperMethod(superMethod, it) }
}
else -> false
}
}
}
fun <T : PsiNamedElement> List<T>.filterDataClassComponentsIfDisabled(kotlinOptions: KotlinReferencesSearchOptions): List<T> {
if (kotlinOptions.searchForComponentConventions) return this
fun PsiNamedElement.isComponentElement(): Boolean {
if (this !is PsiMethod) return false
val dataClassParent = ((parent as? KtLightClass)?.kotlinOrigin as? KtClass)?.isData() == true
if (!dataClassParent) return false
if (!Name.isValidIdentifier(name)) return false
val nameIdentifier = Name.identifier(name)
if (!DataClassDescriptorResolver.isComponentLike(nameIdentifier)) return false
return true
}
return filter { !it.isComponentElement() }
}
fun KtFile.forceResolveReferences(elements: List<KtElement>) {
getResolutionFacade().analyze(elements, BodyResolveMode.PARTIAL)
}
private fun PsiElement.resolveTargetToDescriptor(isDestructionDeclarationSearch: Boolean): FunctionDescriptor? {
if (isDestructionDeclarationSearch && this is KtParameter) {
return dataClassComponentFunction()
}
return when {
this is KtDeclaration -> resolveToDescriptorIfAny(BodyResolveMode.FULL)
this is PsiMember && hasJavaResolutionFacade() ->
this.getJavaOrKotlinMemberDescriptor()
else -> null
} as? FunctionDescriptor
}
private fun containsTypeOrDerivedInside(declaration: KtDeclaration, typeToSearch: FuzzyType): Boolean {
fun KotlinType.containsTypeOrDerivedInside(type: FuzzyType): Boolean {
return type.checkIsSuperTypeOf(this) != null || arguments.any { !it.isStarProjection && it.type.containsTypeOrDerivedInside(type) }
}
val descriptor = declaration.resolveToDescriptorIfAny() as? CallableDescriptor
val type = descriptor?.returnType
return type != null && type.containsTypeOrDerivedInside(typeToSearch)
}
private fun FuzzyType.toPsiClass(project: Project): PsiClass? {
val classDescriptor = type.constructor.declarationDescriptor ?: return null
val classDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, classDescriptor)
return when (classDeclaration) {
is PsiClass -> classDeclaration
is KtClassOrObject -> classDeclaration.toLightClass()
else -> null
}
}
private fun PsiElement.extractReceiverType(isDestructionDeclarationSearch: Boolean): FuzzyType? {
val descriptor = resolveTargetToDescriptor(isDestructionDeclarationSearch)?.takeIf { it.isValidOperator() } ?: return null
return if (descriptor.isExtension) {
descriptor.fuzzyExtensionReceiverType()!!
} else {
val classDescriptor = descriptor.containingDeclaration as? ClassDescriptor ?: return null
classDescriptor.defaultType.toFuzzyType(classDescriptor.typeConstructor.parameters)
}
}
fun PsiElement.getReceiverTypeSearcherInfo(isDestructionDeclarationSearch: Boolean): ReceiverTypeSearcherInfo? {
val receiverType = runReadAction { extractReceiverType(isDestructionDeclarationSearch) } ?: return null
val psiClass = runReadAction { receiverType.toPsiClass(project) }
return ReceiverTypeSearcherInfo(psiClass) {
containsTypeOrDerivedInside(it, receiverType)
}
}
fun KtFile.getDefaultImports(): List<ImportPath> {
val moduleInfo = getNullableModuleInfo() ?: return emptyList()
return TargetPlatformDetector.getPlatform(this).findAnalyzerServices(project).getDefaultImports(
IDELanguageSettingsProvider.getLanguageVersionSettings(moduleInfo, project),
includeLowPriorityImports = true
)
}
fun PsiFile.scriptDefinitionExists(): Boolean = findScriptDefinition() != null | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/search/usagesSearch/utils.kt | 4198807933 |
interface Aaa {
fun foo(
e1: String?,
e2: String?
)
} | plugins/kotlin/j2k/new/tests/testData/newJ2k/formatting/parameterList.kt | 543994543 |
// "Replace with safe (?.) call" "true"
// WITH_STDLIB
fun foo(list: List<String>?) {
list<caret>[0]
} | plugins/kotlin/idea/tests/testData/quickfix/replaceInfixOrOperatorCall/list.kt | 2196032114 |
fun t1() : Int{
return 0
<warning>1</warning>
}
fun t1a() : Int {
<error>return</error>
<warning>return 1</warning>
<warning>1</warning>
}
fun t1b() : Int {
return 1
<warning>return 1</warning>
<warning>1</warning>
}
fun t1c() : Int {
return 1
<error>return</error>
<warning>1</warning>
}
fun t2() : Int {
if (1 > 2)
return 1
else return 1
<warning>1</warning>
}
fun t2a() : Int {
if (1 > 2) {
return 1
<warning>1</warning>
} else { return 1
<warning>2</warning>
}
<warning>1</warning>
}
fun t3() : Any {
if (1 > 2)
return 2
else return ""
<warning>1</warning>
}
fun t4(<warning>a</warning> : Boolean) : Int {
do {
return 1
}
while (<warning>a</warning>)
<warning>1</warning>
}
fun t4break(<warning>a</warning> : Boolean) : Int {
do {
break
}
while (<warning>a</warning>)
return 1
}
fun t5() : Int {
do {
return 1
<warning>2</warning>
}
while (<warning>1 > 2</warning>)
<warning>return 1</warning>
}
fun t6() : Int {
while (1 > 2) {
return 1
<warning>2</warning>
}
return 1
}
fun t6break() : Int {
while (1 > 2) {
break
<warning>2</warning>
}
return 1
}
fun t7(b : Int) : Int {
for (i in 1..b) {
return 1
<warning>2</warning>
}
return 1
}
fun t7break(b : Int) : Int {
for (i in 1..b) {
return 1
<warning>2</warning>
}
return 1
}
fun t7() : Int {
try {
return 1
<warning>2</warning>
}
catch (<error>e : Any</error>) {
<warning>2</warning>
}
return 1 // this is OK, like in Java
}
fun t8() : Int {
try {
return 1
<warning>2</warning>
}
catch (<error>e : Any</error>) {
return 1
<warning>2</warning>
}
<warning>return 1</warning>
}
fun blockAndAndMismatch() : Boolean {
(return true) <warning>|| (return false)</warning>
<warning>return true</warning>
}
fun tf() : Int {
try {<warning>return</warning> 1} finally{return 1}
<warning>return 1</warning>
}
fun failtest(<warning>a</warning> : Int) : Int {
if (fail() <warning>|| true</warning>) <warning>{
}</warning>
<warning>return 1</warning>
}
fun foo(a : Nothing) : Unit {
<warning>1</warning>
<warning>a</warning>
<warning>2</warning>
}
fun fail() : Nothing {
throw java.lang.RuntimeException()
}
fun nullIsNotNothing() : Unit {
val x : Int? = 1
if (x != null) {
return
}
fail()
} | plugins/kotlin/idea/tests/testData/checker/UnreachableCode.kt | 3500002666 |
// WITH_STDLIB
const val ONE = 1
fun foo() {
2..1
2.rangeTo(1)
2..1L
10L..-10L
5..ONE
10.toShort()..1.toShort()
//valid
1..1
1..10L
1..2
1.rangeTo(2)
} | plugins/kotlin/idea/tests/testData/inspections/emptyRange/test.kt | 1543075905 |
package org.jetbrains.kotlin.gradle.frontend.webpack
import org.gradle.api.*
import org.gradle.api.tasks.*
import org.jetbrains.kotlin.gradle.frontend.config.*
import org.jetbrains.kotlin.gradle.frontend.util.*
import java.io.*
open class WebPackExtension(project: Project) : BundleConfig {
@get:Input
override val bundlerId: String
get() = "webpack"
@Input
override var bundleName = project.name!!
@Input
override var sourceMapEnabled: Boolean = project.frontendExtension.sourceMaps
@Input
@Optional
var contentPath: File? = null
@Input
var publicPath: String = "/"
@Input
var host: String = "localhost"
@Input
var port: Int = 8088
@Input
var proxyUrl: String = ""
@Input
var stats: String = "errors-only"
@Input
@Optional
var webpackConfigFile: Any? = null
@Input
var mode: String = "development"
}
| kotlin-frontend/src/main/kotlin/org/jetbrains/kotlin/gradle/frontend/webpack/WebPackExtension.kt | 4275436758 |
package io.vertx.kotlin.core.http
import io.vertx.kotlin.core.internal.KotlinHandler
import io.vertx.kotlin.core.streams.ReadStream
/**
*/
class ServerWebSocketStream(override val delegate: io.vertx.core.http.ServerWebSocketStream) : ReadStream<ServerWebSocket> {
override fun exceptionHandler(handler: (Throwable) -> Unit): ServerWebSocketStream {
delegate.exceptionHandler(handler)
return this
}
override fun handler(handler: (ServerWebSocket) -> Unit): ServerWebSocketStream {
delegate.handler(KotlinHandler(handler, { ServerWebSocket(it) }))
return this
}
override fun pause(): ServerWebSocketStream {
delegate.pause()
return this
}
override fun resume(): ServerWebSocketStream {
delegate.resume()
return this
}
override fun endHandler(endHandler: (Unit) -> Unit): ServerWebSocketStream {
delegate.endHandler(KotlinHandler(endHandler, {}))
return this
}
}
| vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/core/http/ServerWebSocketStream.kt | 1049226394 |
package org.droidplanner.android.tlog.adapters
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import org.droidplanner.android.tlog.viewers.TLogPositionViewer
import org.droidplanner.android.tlog.viewers.TLogRawViewer
/**
* Return the appropriate fragment for the selected tlog data viewer.
*
* @author ne0fhyk (Fredia Huya-Kouadio)
*/
class TLogViewerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment? {
return when(position){
1 -> TLogRawViewer()
0 -> TLogPositionViewer()
else -> throw IllegalStateException("Invalid viewer index.")
}
}
override fun getCount() = 2
override fun getPageTitle(position: Int): CharSequence? {
return when(position){
1 -> "All"
0 -> "Position"
else -> throw IllegalStateException("Invalid viewer index.")
}
}
} | Android/src/org/droidplanner/android/tlog/adapters/TLogViewerAdapter.kt | 3897652053 |
/*
* uplink, a simple daemon to implement a simple chat protocol
* Copyright (C) Marco Cilloni <[email protected]> 2016
*
* 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/.
* Exhibit B is not attached this software is compatible with the
* licenses expressed under Section 1.12 of the MPL v2.
*
*/
package com.github.mcilloni.uplink
import io.grpc.Status
import io.grpc.StatusException
import io.grpc.StatusRuntimeException
import java.util.concurrent.ExecutionException
internal inline fun <T> rpc(body: () -> T) = try {
body()
} catch (e: ExecutionException) {
throw normExc(e.cause ?: throw e)
} catch (e: StatusRuntimeException) {
throw if (e.status.code == Status.Code.UNAVAILABLE) UnavailableException() else normExc(e)
}
internal fun normExc(e: Throwable) : Throwable {
val msg = e.message ?: throw e
return when {
msg.contains("EAUTHFAIL") -> AuthFailException(e)
msg.contains("ESERVERFAULT") -> ServerFaultException(e)
msg.contains("ERESERVEDUSER") -> ReservedUserException(e)
msg.contains("EALREADYFRIENDS") -> AlreadyFriendsException(e)
msg.contains("ENOREQUEST") -> NoFriendshipRequestException(e)
msg.contains("ENOTMEMBER") -> NotMemberException(e)
else -> e
}
}
open class UplinkException internal constructor(msg: String, t : Throwable = Throwable()) : Exception(msg, t)
class UnknownErrcodeException internal constructor(errcode: Int, t : Throwable = Throwable()) : UplinkException("unknown errcode $errcode", t)
class AlreadyInvitedException internal constructor(t : Throwable = Throwable()) : UplinkException("user already invited to the given conversation", t)
class AlreadyFriendsException internal constructor(t : Throwable = Throwable()) : UplinkException("already friend with the given user", t)
class EmptyConvException internal constructor(t : Throwable = Throwable()) : UplinkException("empty conversation", t)
class NameAlreadyTakenException internal constructor(t : Throwable = Throwable()) : UplinkException("username already taken", t)
class NoConvException internal constructor(t : Throwable = Throwable()) : UplinkException("no such conversation", t)
class NoFriendshipRequestException internal constructor(t : Throwable = Throwable()) : UplinkException("no friendship request from this user", t)
class NoUserException internal constructor(t : Throwable = Throwable()) : UplinkException("no such user", t)
class NotInvitedException internal constructor(t : Throwable = Throwable()) : UplinkException("user not invited to the given conversation", t)
class NotMemberException internal constructor(t : Throwable = Throwable()) : UplinkException("user not member of the given conversation", t)
class SelfInviteException internal constructor(t : Throwable = Throwable()) : UplinkException("self invite is not allowed", t)
class ServerFaultException internal constructor(t : Throwable = Throwable()) : UplinkException("server error", t)
class BrokeProtoException internal constructor(t : Throwable = Throwable()) : UplinkException("protocol broken, please report", t)
class AuthFailException internal constructor(t : Throwable = Throwable()) : UplinkException("login data rejected", t)
class ReservedUserException internal constructor(t : Throwable = Throwable()) : UplinkException("trying to access data of a reserved user", t)
class UnavailableException internal constructor() : Exception("Uplink is unavailable") | src/main/kotlin/UplinkError.kt | 1219847930 |
package com.excref.kotblog.blog.service.post
import com.excref.kotblog.blog.service.test.AbstractServiceIntegrationTest
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import java.util.*
/**
* @author Rafayel Mirzoyan
* @since 6/11/17 5:04 AM
*/
class PostServiceIntegrationTest : AbstractServiceIntegrationTest() {
//region Dependencies
@Autowired
private lateinit var postService: PostService
//endregion
//region Test methods
@Test
fun testCreate() {
//given
val title = UUID.randomUUID().toString()
val content = UUID.randomUUID().toString()
val blog = helper.persistBlog()
val categoryAndTagUuids = (1..2).map { helper.persistCategory() to helper.persistTag() }.toList()
val categories = categoryAndTagUuids.map { it.first }.toList()
val categoryUuids = categoryAndTagUuids.map { it.first.uuid }.toList()
val tags = categoryAndTagUuids.map { it.second }.toList()
val tagUuids = categoryAndTagUuids.map { it.second.uuid }.toList()
// when
val result = postService.create(title, content, blog.uuid, tagUuids, categoryUuids)
// then
assertThat(result).isNotNull().extracting("title", "content").containsOnly(title, content)
assertThat(blog).isEqualTo(result.blog)
assertThat(categories).isEqualTo(result.categories)
assertThat(tags).isEqualTo(result.tags)
}
@Test
fun testGetUuid() {
// given
val post = helper.persistPost()
// when
val result = postService.getByUuid(post.uuid)
// then
assertThat(result).isNotNull().isEqualTo(post)
}
//endregion
} | blog/service/impl/src/test/kotlin/com/excref/kotblog/blog/service/post/PostServiceIntegrationTest.kt | 748082174 |
package xyz.nulldev.ts.api.v3.util
import io.vertx.core.Handler
import io.vertx.core.buffer.Buffer
import io.vertx.core.http.HttpClientRequest
import io.vertx.core.http.HttpClientResponse
import io.vertx.core.http.HttpServerResponse
import io.vertx.core.http.RequestOptions
import io.vertx.core.streams.ReadStream
import io.vertx.core.streams.WriteStream
import io.vertx.kotlin.core.http.requestOptionsOf
import java.net.URL
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
fun HttpServerResponse.tryEnd() {
if (!closed() && !ended())
end()
}
suspend fun ReadStream<*>.awaitEnd() = suspendCoroutine<Unit> { cont ->
endHandler {
cont.resume(Unit)
}
exceptionHandler {
cont.resumeWithException(it)
}
}
suspend fun ReadStream<*>.resumeAndAwaitEnd() = suspendCoroutine<Unit> { cont ->
endHandler {
cont.resume(Unit)
}
exceptionHandler {
cont.resumeWithException(it)
}
try {
resume()
} catch (t: Throwable) {
cont.resumeWithException(t)
}
}
suspend fun HttpClientResponse.awaitBody() = suspendCoroutine<Buffer?> { cont ->
var resumed = false
bodyHandler {
if (!resumed) {
resumed = true
cont.resume(it)
}
}
exceptionHandler {
pause()
if (!resumed) {
resumed = true
cont.resumeWithException(it)
}
}
endHandler {
if (!resumed) {
resumed = true
cont.resume(null)
}
}
}
fun <T> WriteStream<T>.watched(block: (T) -> Unit) = object : WriteStream<T> {
override fun setWriteQueueMaxSize(maxSize: Int): WriteStream<T> {
[email protected](maxSize)
return this
}
override fun writeQueueFull(): Boolean {
return [email protected]()
}
override fun write(data: T): WriteStream<T> {
block(data)
[email protected](data)
return this
}
override fun end() {
[email protected]()
}
override fun drainHandler(handler: Handler<Void>?): WriteStream<T> {
[email protected](handler)
return this
}
override fun exceptionHandler(handler: Handler<Throwable>?): WriteStream<T> {
[email protected](handler)
return this
}
}
fun <T> combineWriteStreams(a: WriteStream<T>, b: WriteStream<T>) = object : WriteStream<T> {
override fun setWriteQueueMaxSize(maxSize: Int): WriteStream<T> {
a.setWriteQueueMaxSize(maxSize)
b.setWriteQueueMaxSize(maxSize)
return this
}
override fun writeQueueFull(): Boolean {
return a.writeQueueFull() || b.writeQueueFull()
}
override fun write(data: T): WriteStream<T> {
a.write(data)
b.write(data)
return this
}
override fun end() {
a.end()
b.end()
}
override fun drainHandler(handler: Handler<Void>?): WriteStream<T> {
a.drainHandler(handler)
b.drainHandler(handler)
return this
}
override fun exceptionHandler(handler: Handler<Throwable>?): WriteStream<T> {
a.exceptionHandler(handler)
b.exceptionHandler(handler)
return this
}
}
suspend fun HttpClientRequest.awaitResponse() = suspendCoroutine<HttpClientResponse> { cont ->
var resumed = false
handler {
pause()
if (!resumed) {
resumed = true
cont.resume(it)
}
}
exceptionHandler {
pause()
if (!resumed) {
resumed = true
cont.resumeWithException(it)
}
}
endHandler {
pause()
if (!resumed) {
resumed = true
cont.resumeWithException(IllegalStateException("Stream ended with no response!"))
}
}
end()
}
suspend fun <T> ReadStream<T>.awaitSingle() = suspendCoroutine<T> { cont ->
var resumed = false
handler {
pause()
if (!resumed) {
resumed = true
cont.resume(it)
}
}
exceptionHandler {
pause()
if (!resumed) {
resumed = true
cont.resumeWithException(it)
}
}
endHandler {
pause()
if (!resumed) {
resumed = true
cont.resumeWithException(IllegalStateException("Stream ended with no response!"))
}
}
}
fun URL.asRequestOptions(): RequestOptions {
val isSSL = this.protocol.equals("https", false)
return requestOptionsOf(
host = host,
port = if (port != -1) port else if (isSSL) 443 else 80,
ssl = isSSL,
uri = toURI().toString()
)
}
/**
* Reads a specific number of bytes from the input stream
*
* @returns The remaining ReadStream (paused) along with the read ByteArray. If there are less data in the stream than the
* request amount of bytes, the returned byte array will be smaller
*/
suspend fun ReadStream<Buffer>.readBytes(bytes: Int): Pair<ReadStream<Buffer>, ByteArray> = suspendCoroutine { cont ->
require(bytes >= 0)
var remainingBuffer: Buffer? = null
var remainingHandler: Handler<Buffer>? = null
var remainingExceptionHandler: Handler<Throwable>? = null
var remainingEndHandler: Handler<Void>? = null
val remaining = object : ReadStream<Buffer> {
var paused = false
override fun fetch(amount: Long): ReadStream<Buffer> {
if (amount > 0) {
if (remainingBuffer != null) remainingHandler?.handle(remainingBuffer)
remainingBuffer = null
[email protected](amount - 1)
}
return this
}
override fun pause(): ReadStream<Buffer> {
paused = true
[email protected]()
return this
}
override fun resume(): ReadStream<Buffer> {
paused = false
if (remainingBuffer != null) remainingHandler?.handle(remainingBuffer)
remainingBuffer = null
// Handlers could have paused stream again while handling remaining buffer
if (!paused) [email protected]()
return this
}
override fun handler(handler: Handler<Buffer>?): ReadStream<Buffer> {
if (handler != null) remainingHandler = handler
return this
}
override fun exceptionHandler(handler: Handler<Throwable>?): ReadStream<Buffer> {
if (handler != null) remainingExceptionHandler = handler
return this
}
override fun endHandler(endHandler: Handler<Void>?): ReadStream<Buffer> {
if (endHandler != null) remainingEndHandler = endHandler
return this
}
}
val read = Buffer.buffer(bytes)
var allRead = false
handler {
if (allRead) {
remainingHandler?.handle(it)
} else {
val newLength = read.length() + it.length()
if (newLength >= bytes) {
val toRead = bytes - read.length()
read.appendBuffer(it, 0, toRead)
if (newLength > bytes) remainingBuffer = it.slice(toRead, it.length())
pause()
allRead = true
cont.resume(remaining to read.bytes)
} else {
read.appendBuffer(it, 0, it.length())
}
}
}
exceptionHandler {
if (!allRead) {
cont.resumeWithException(it)
allRead = true
} else {
remainingExceptionHandler?.handle(it)
}
}
endHandler {
if (!allRead) {
cont.resume(EmptyReadStream<Buffer>() to read.bytes)
allRead = true
} else {
remainingEndHandler?.handle(it)
}
}
}
| TachiServer/src/main/java/xyz/nulldev/ts/api/v3/util/VertxUtil.kt | 3284087841 |
/*
* Copyright 2019 New Vector Ltd
*
* 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 im.vector.fragments.discovery
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.airbnb.mvrx.MvRx
import com.airbnb.mvrx.args
import com.airbnb.mvrx.fragmentViewModel
import com.airbnb.mvrx.withState
import com.google.android.material.snackbar.Snackbar
import im.vector.R
import im.vector.activity.MXCActionBarActivity
import im.vector.activity.ReviewTermsActivity
import im.vector.activity.util.TERMS_REQUEST_CODE
import im.vector.extensions.withArgs
import im.vector.fragments.VectorBaseMvRxFragment
import kotlinx.android.synthetic.main.fragment_simple_epoxy.*
import org.matrix.androidsdk.features.terms.TermsManager
import org.matrix.androidsdk.rest.model.pid.ThreePid
class VectorSettingsDiscoveryFragment : VectorBaseMvRxFragment(), SettingsDiscoveryController.InteractionListener {
override fun getLayoutResId() = R.layout.fragment_simple_epoxy
private val viewModel by fragmentViewModel(DiscoverySettingsViewModel::class)
private lateinit var controller: SettingsDiscoveryController
lateinit var sharedViewModel: DiscoverySharedViewModel
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
sharedViewModel = ViewModelProviders.of(requireActivity()).get(DiscoverySharedViewModel::class.java)
controller = SettingsDiscoveryController(requireContext(), this).also {
epoxyRecyclerView.setController(it)
}
sharedViewModel.navigateEvent.observe(this, Observer {
if (it.peekContent().first == DiscoverySharedViewModel.NEW_IDENTITY_SERVER_SET_REQUEST) {
viewModel.changeIdentityServer(it.peekContent().second)
}
})
viewModel.errorLiveEvent.observe(this, Observer {
it.getContentIfNotHandled()?.let { throwable ->
Snackbar.make(coordinatorLayout, throwable.toString(), Snackbar.LENGTH_LONG).show()
}
})
}
override fun invalidate() = withState(viewModel) { state ->
controller.setData(state)
}
override fun onResume() {
super.onResume()
(activity as? MXCActionBarActivity)?.supportActionBar?.setTitle(R.string.settings_discovery_category)
//If some 3pids are pending, we can try to check if they have been verified here
viewModel.refreshPendingEmailBindings()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == TERMS_REQUEST_CODE) {
if (Activity.RESULT_OK == resultCode) {
viewModel.refreshModel()
} else {
//add some error?
}
}
super.onActivityResult(requestCode, resultCode, data)
}
override fun onSelectIdentityServer() = withState(viewModel) { state ->
if (state.termsNotSigned) {
ReviewTermsActivity.intent(requireContext(),
TermsManager.ServiceType.IdentityService,
SetIdentityServerViewModel.sanitatizeBaseURL(state.identityServer() ?: ""),
null).also {
startActivityForResult(it, TERMS_REQUEST_CODE)
}
}
}
override fun onTapRevokeEmail(email: String) {
viewModel.revokeEmail(email)
}
override fun onTapShareEmail(email: String) {
viewModel.shareEmail(email)
}
override fun checkEmailVerification(email: String, bind: Boolean) {
viewModel.finalizeBind3pid(ThreePid.MEDIUM_EMAIL, email, bind)
}
override fun checkMsisdnVerification(msisdn: String, code: String, bind: Boolean) {
viewModel.submitMsisdnToken(msisdn, code, bind)
}
override fun onTapRevokeMsisdn(msisdn: String) {
viewModel.revokeMsisdn(msisdn)
}
override fun onTapShareMsisdn(msisdn: String) {
viewModel.shareMsisdn(msisdn)
}
override fun onTapChangeIdentityServer() = withState(viewModel) { state ->
//we should prompt if there are bound items with current is
val pidList = ArrayList<PidInfo>().apply {
state.emailList()?.let { addAll(it) }
state.phoneNumbersList()?.let { addAll(it) }
}
val hasBoundIds = pidList.any { it.isShared() == PidInfo.SharedState.SHARED }
if (hasBoundIds) {
//we should prompt
AlertDialog.Builder(requireActivity())
.setTitle(R.string.change_identity_server)
.setMessage(getString(R.string.settings_discovery_disconnect_with_bound_pid, state.identityServer(), state.identityServer()))
.setPositiveButton(R.string._continue) { _, _ -> navigateToChangeIsFragment(state) }
.setNegativeButton(R.string.cancel, null)
.show()
Unit
} else {
navigateToChangeIsFragment(state)
}
}
override fun onTapDisconnectIdentityServer() {
//we should prompt if there are bound items with current is
withState(viewModel) { state ->
val pidList = ArrayList<PidInfo>().apply {
state.emailList()?.let { addAll(it) }
state.phoneNumbersList()?.let { addAll(it) }
}
val hasBoundIds = pidList.any { it.isShared() == PidInfo.SharedState.SHARED }
if (hasBoundIds) {
//we should prompt
AlertDialog.Builder(requireActivity())
.setTitle(R.string.disconnect_identity_server)
.setMessage(getString(R.string.settings_discovery_disconnect_with_bound_pid, state.identityServer(), state.identityServer()))
.setPositiveButton(R.string._continue) { _, _ -> viewModel.changeIdentityServer(null) }
.setNegativeButton(R.string.cancel, null)
.show()
} else {
viewModel.changeIdentityServer(null)
}
}
}
override fun onTapRetryToRetrieveBindings() {
viewModel.retrieveBinding()
}
private fun navigateToChangeIsFragment(state: DiscoverySettingsState) {
SetIdentityServerFragment.newInstance(args<String>().toString(), state.identityServer()).also {
requireFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.anim_slide_in_bottom, R.anim.anim_slide_out_bottom, R.anim.anim_slide_in_bottom, R.anim.anim_slide_out_bottom)
.replace(R.id.vector_settings_page, it, getString(R.string.identity_server))
.addToBackStack(null)
.commit()
}
}
companion object {
fun newInstance(matrixId: String) = VectorSettingsDiscoveryFragment()
.withArgs {
putString(MvRx.KEY_ARG, matrixId)
}
}
}
| vector/src/main/java/im/vector/fragments/discovery/VectorSettingsDiscoveryFragment.kt | 2556568027 |
/**
* https://www.hackerrank.com/challenges/frequency-queries/problem
*/
package com.raphaelnegrisoli.hackerrank.hashmaps
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.StringBuilder
fun main(args: Array<String>) {
val reader = BufferedReader(InputStreamReader(System.`in`))
val q = reader.readLine()!!.trim().toInt()
val frequency : MutableMap<Int, Int> = HashMap(1000000)
val dataByOccurrence : MutableMap<Int, Int> = HashMap(1000000)
val builder = StringBuilder()
for (i in 0 until q) {
val (op, data) = reader.readLine()!!.trim().split(" ").map { it.toInt() }
when (op) {
1 -> {
val f = frequency[data] ?: 0
frequency[data] = f + 1
dataByOccurrence[f] = if ((dataByOccurrence[f] ?: 0) > 0) dataByOccurrence[f]!! - 1 else 0
dataByOccurrence[f + 1] = (dataByOccurrence[f + 1] ?: 0) + 1
}
2 -> {
val f = frequency[data] ?: 0
frequency[data] = if (f > 0) f - 1 else 0
dataByOccurrence[f] = if ((dataByOccurrence[f] ?: 0) > 0) dataByOccurrence[f]!! - 1 else 0
if (f > 0) {
dataByOccurrence[f - 1] = (dataByOccurrence[f - 1] ?: 0) + 1
}
}
3 -> {
val r = if ((dataByOccurrence[data] ?: 0) > 0) 1 else 0
builder.append(r).append("\n")
}
}
}
println(builder.toString())
} | challenges/hacker-rank/kotlin/src/main/kotlin/com/raphaelnegrisoli/hackerrank/hashmaps/FrequencyQueries.kt | 3566136346 |
package glorantq.ramszesz.memes
/**
* Created by glora on 2017. 07. 26..
*/
class MemeParameter(var type: Type, required: Boolean = true) {
companion object {
enum class Type {
STRING, INT, USER
}
}
var value: Any = "Invalid"
set(value) {
field = value
println("Field value has been set to $field ($value)")
}
} | src/glorantq/ramszesz/memes/MemeParameter.kt | 1559699649 |
package run.smt.karafrunner.modules.impl.image
import org.kohsuke.args4j.Argument
import run.smt.karafrunner.io.output.hightlight
import run.smt.karafrunner.io.output.info
import run.smt.karafrunner.io.output.success
import run.smt.karafrunner.logic.manager.ImageManager
import run.smt.karafrunner.logic.util.PathRegistry.pwd
import run.smt.karafrunner.modules.impl.InstanceAwareModule
import java.io.File
class UpdateImageModule : InstanceAwareModule() {
@Argument(required = false)
private var approximateImagePath: String? = null
override fun doRun() {
info("Updating ${imageName.hightlight()} image")
ImageManager(imageName).updateImage(approximateImagePath?.let { File(it) } ?: pwd)
success("Done")
}
} | src/main/java/run/smt/karafrunner/modules/impl/image/UpdateImageModule.kt | 168785282 |
/*
* Copyright 2016 lizhaotailang
*
* 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.marktony.zhihudaily.data.source.local
import android.support.annotation.VisibleForTesting
import com.marktony.zhihudaily.data.DoubanMomentContent
import com.marktony.zhihudaily.data.source.LocalDataNotFoundException
import com.marktony.zhihudaily.data.source.Result
import com.marktony.zhihudaily.data.source.datasource.DoubanMomentContentDataSource
import com.marktony.zhihudaily.database.dao.DoubanMomentContentDao
import com.marktony.zhihudaily.util.AppExecutors
import kotlinx.coroutines.experimental.withContext
/**
* Created by lizhaotailang on 2017/5/25.
*
* Concrete implementation of a [DoubanMomentContent] data source as database.
*/
class DoubanMomentContentLocalDataSource private constructor(
private val mAppExecutors: AppExecutors,
private val mDoubanMomentContentDao: DoubanMomentContentDao
) : DoubanMomentContentDataSource {
companion object {
private var INSTANCE: DoubanMomentContentLocalDataSource? = null
@JvmStatic
fun getInstance(appExecutors: AppExecutors, doubanMomentContentDao: DoubanMomentContentDao): DoubanMomentContentLocalDataSource {
if (INSTANCE == null) {
synchronized(DoubanMomentContentLocalDataSource::javaClass) {
INSTANCE = DoubanMomentContentLocalDataSource(appExecutors, doubanMomentContentDao)
}
}
return INSTANCE!!
}
@VisibleForTesting
fun clearInstance() {
INSTANCE = null
}
}
override suspend fun getDoubanMomentContent(id: Int): Result<DoubanMomentContent> = withContext(mAppExecutors.ioContext) {
val content = mDoubanMomentContentDao.queryContentById(id)
if (content != null) Result.Success(content) else Result.Error(LocalDataNotFoundException())
}
override suspend fun saveContent(content: DoubanMomentContent) {
withContext(mAppExecutors.ioContext) {
mDoubanMomentContentDao.insert(content)
}
}
}
| app/src/main/java/com/marktony/zhihudaily/data/source/local/DoubanMomentContentLocalDataSource.kt | 4083341276 |
/*
* Copyright 2000-2021 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 jetbrains.buildServer.clouds.azure.arm.connector.tasks
import com.google.common.cache.CacheBuilder
import com.intellij.openapi.diagnostic.Logger
import com.microsoft.azure.management.Azure
import com.microsoft.azure.management.compute.VirtualMachine
import com.microsoft.azure.management.compute.implementation.*
import com.microsoft.azure.management.containerinstance.ContainerGroup
import com.microsoft.azure.management.network.PublicIPAddress
import com.microsoft.azure.management.resources.fluentcore.arm.ResourceUtils
import com.microsoft.azure.management.resources.fluentcore.arm.models.HasId
import jetbrains.buildServer.clouds.azure.arm.AzureCloudDeployTarget
import jetbrains.buildServer.clouds.azure.arm.AzureConstants
import jetbrains.buildServer.clouds.azure.arm.throttler.*
import jetbrains.buildServer.clouds.base.errors.TypedCloudErrorInfo
import jetbrains.buildServer.serverSide.TeamCityProperties
import jetbrains.buildServer.util.StringUtil
import rx.Observable
import rx.Single
import java.time.Clock
import java.time.LocalDateTime
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.atomic.AtomicReference
import kotlin.collections.HashSet
data class FetchInstancesTaskInstanceDescriptor (
val id: String,
val name: String,
val tags: Map<String, String>,
val publicIpAddress: String?,
val provisioningState: String?,
val startDate: Date?,
val powerState: String?,
val error: TypedCloudErrorInfo?
)
data class FetchInstancesTaskParameter(val serverId: String)
class FetchInstancesTaskImpl(private val myNotifications: AzureTaskNotifications) : AzureThrottlerCacheableTask<Azure, FetchInstancesTaskParameter, List<FetchInstancesTaskInstanceDescriptor>> {
private val myTimeoutInSeconds = AtomicLong(60)
private val myIpAddresses = AtomicReference<Array<IPAddressDescriptor>>(emptyArray())
private val myInstancesCache = createCache()
private val myNotifiedInstances = ConcurrentHashMap.newKeySet<String>()
private val myLastUpdatedDate = AtomicReference<LocalDateTime>(LocalDateTime.MIN)
init {
myNotifications.register<AzureTaskVirtualMachineStatusChangedEventArgs> {
updateVirtualMachine(it.api, it.virtualMachine)
}
myNotifications.register<AzureTaskDeploymentStatusChangedEventArgs> { args ->
val dependency = args.deployment.dependencies().firstOrNull { it.resourceType() == VIRTUAL_MACHINES_RESOURCE_TYPE }
if (dependency != null) {
if (args.isDeleting) {
updateVirtualMachine(args.api, dependency.id(), args.isDeleting)
} else {
if (args.deployment.provisioningState() == PROVISIONING_STATE_SUCCEEDED) {
updateVirtualMachine(args.api, dependency.id(), args.isDeleting)
}
}
return@register
}
val containerProvider = args.deployment.providers().firstOrNull { it.namespace() == CONTAINER_INSTANCE_NAMESPACE }
if (containerProvider != null) {
val id = args.deployment.id()
val name = args.deployment.name()
val containerId = ResourceUtils.constructResourceId(
ResourceUtils.subscriptionFromResourceId(id),
ResourceUtils.groupFromResourceId(id),
containerProvider.namespace(),
CONTAINER_GROUPS_RESOURCE_TYPE,
name,
"")
updateContainer(args.api, containerId, args.isDeleting)
}
}
}
override fun create(api: Azure, parameter: FetchInstancesTaskParameter): Single<List<FetchInstancesTaskInstanceDescriptor>> {
if (StringUtil.isEmptyOrSpaces(api.subscriptionId())) {
LOG.debug("FetchInstancesTask returns empty list. Subscription is empty")
return Single
.just(emptyList<FetchInstancesTaskInstanceDescriptor>());
}
val ipAddresses =
fetchIPAddresses(api)
val machineInstancesImpl =
if (TeamCityProperties.getBoolean(TEAMCITY_CLOUDS_AZURE_TASKS_FETCHINSTANCES_FULLSTATEAPI_DISABLE))
Observable.just(emptyMap())
else api.virtualMachines().inner()
.listAsync("true")
.flatMap { x -> Observable.from(x.items()) }
.toMap { vm -> vm.id() }
val machineInstances =
api
.virtualMachines()
.listAsync()
.materialize()
.filter {
if (it.isOnError) LOG.warnAndDebugDetails("Could not read VM state:", it.throwable)
!it.isOnError
}
.dematerialize<VirtualMachine>()
.withLatestFrom(machineInstancesImpl) { vm, vmStatusesMap ->
vm to vmStatusesMap[vm.id()]
}
.flatMap { (vm, vmStatus) ->
fetchVirtualMachineWithCache(vm, vmStatus)
}
val containerInstances =
api
.containerGroups()
.listAsync()
.materialize()
.filter {
if (it.isOnError) LOG.warnAndDebugDetails("Could not read container state:", it.throwable)
!it.isOnError
}
.dematerialize<ContainerGroup>()
.map { getLiveInstanceFromSnapshot(it) ?: fetchContainer(it) }
return machineInstances
.mergeWith(containerInstances)
.toList()
.takeLast(1)
.withLatestFrom(ipAddresses) { instances, ipList ->
myLastUpdatedDate.set(getCurrentUTC())
myIpAddresses.set(ipList.toTypedArray())
val newInstances = instances.associateBy { it.id.toLowerCase() }
myInstancesCache.putAll(newInstances)
val keysInCache = myInstancesCache.asMap().keys.toSet()
val notifiedInstances = HashSet(myNotifiedInstances)
myInstancesCache.invalidateAll(keysInCache.minus(newInstances.keys.plus(notifiedInstances)))
myNotifiedInstances.removeAll(notifiedInstances)
Unit
}
.map { getFilteredResources(parameter) }
.toSingle()
}
private fun getLiveInstanceFromSnapshot(resource: HasId?): InstanceDescriptor? {
if (resource?.id() == null) return null
val instance = myInstancesCache.getIfPresent(resource.id().toLowerCase())
if (instance == null) return null
if (needUpdate(instance.lastUpdatedDate)) return null
return instance
}
private fun fetchIPAddresses(api: Azure): Observable<MutableList<IPAddressDescriptor>> {
return api
.publicIPAddresses()
.listAsync()
.filter { !it.ipAddress().isNullOrBlank() }
.map { IPAddressDescriptor(it.name(), it.resourceGroupName(), it.ipAddress(), getAssignedNetworkInterfaceId(it)) }
.toList()
.takeLast(1)
.doOnNext {
LOG.debug("Received list of ip addresses")
}
.onErrorReturn {
val message = "Failed to get list of public ip addresses: " + it.message
LOG.debug(message, it)
emptyList()
}
}
private fun updateContainer(api: Azure, containerId: String, isDeleting: Boolean) {
if (isDeleting) {
myNotifiedInstances.remove(containerId.toLowerCase())
myInstancesCache.invalidate(containerId.toLowerCase())
return
}
api.containerGroups()
.getByIdAsync(containerId)
.map { it?.let { fetchContainer(it) } }
.withLatestFrom(fetchIPAddresses(api)) {
instance, ipList ->
myIpAddresses.set(ipList.toTypedArray())
if (instance != null) {
myNotifiedInstances.add(instance.id.toLowerCase())
myInstancesCache.put(instance.id.toLowerCase(), instance)
} else {
myNotifiedInstances.remove(containerId.toLowerCase())
myInstancesCache.invalidate(containerId.toLowerCase())
}
}
.take(1)
.toCompletable()
.await()
}
private fun fetchContainer(containerGroup: ContainerGroup): InstanceDescriptor {
val state = containerGroup.containers()[containerGroup.name()]?.instanceView()?.currentState()
val startDate = state?.startTime()?.toDate()
val powerState = state?.state()
val instance = InstanceDescriptor(
containerGroup.id(),
containerGroup.name(),
containerGroup.tags(),
null,
startDate,
powerState,
null,
null,
getCurrentUTC())
return instance
}
private fun fetchVirtualMachineWithCache(vm: VirtualMachine, vmStatus: VirtualMachineInner?): Observable<InstanceDescriptor> {
if (vmStatus?.instanceView() == null) {
val cachedInstance = getLiveInstanceFromSnapshot(vm)
if (cachedInstance != null)
return Observable.just(cachedInstance)
else
return fetchVirtualMachine(vm)
}
return fetchVirtualMachine(vm, vmStatus.instanceView())
}
private fun fetchVirtualMachine(vm: VirtualMachine, instanceView: VirtualMachineInstanceViewInner): Observable<InstanceDescriptor> {
val tags = vm.tags()
val name = vm.name()
val instanceState = getInstanceState(instanceView, tags, name)
LOG.debug("Reading state of virtual machine '$name' using full state API")
return Observable.just(InstanceDescriptor(
vm.id(),
vm.name(),
vm.tags(),
instanceState.provisioningState,
instanceState.startDate,
instanceState.powerState,
null,
vm.primaryNetworkInterfaceId(),
getCurrentUTC()
))
}
private fun fetchVirtualMachine(vm: VirtualMachine): Observable<InstanceDescriptor> {
val tags = vm.tags()
val id = vm.id()
val name = vm.name()
LOG.debug("Reading state of virtual machine '$name'")
return vm.refreshInstanceViewAsync()
.map { getInstanceState(it.inner(), tags, name) }
.onErrorReturn {
LOG.debug("Failed to get status of virtual machine '$name': $it.message", it)
InstanceViewState(null, null, null, it)
}
.map { instanceView ->
val instance = InstanceDescriptor(
id,
name,
tags,
instanceView.provisioningState,
instanceView.startDate,
instanceView.powerState,
if (instanceView.error != null) TypedCloudErrorInfo.fromException(instanceView.error) else null,
vm.primaryNetworkInterfaceId(),
getCurrentUTC())
instance
}
}
private fun updateVirtualMachine(api: Azure, virtualMachine: VirtualMachine) {
fetchVirtualMachine(virtualMachine)
.withLatestFrom(fetchIPAddresses(api)) { instance, ipList ->
myIpAddresses.set(ipList.toTypedArray())
myInstancesCache.put(instance.id.toLowerCase(), instance)
}
.take(1)
.toCompletable()
.await()
}
private fun updateVirtualMachine(api: Azure, virtualMachineId: String, isDeleting: Boolean) {
if (isDeleting) {
myNotifiedInstances.remove(virtualMachineId.toLowerCase())
myInstancesCache.invalidate(virtualMachineId.toLowerCase())
return
}
api.virtualMachines()
.getByIdAsync(virtualMachineId)
.flatMap { if (it != null) fetchVirtualMachine(it) else Observable.just(null) }
.withLatestFrom(fetchIPAddresses(api)) {
instance, ipList ->
myIpAddresses.set(ipList.toTypedArray())
if (instance != null) {
myNotifiedInstances.add(instance.id.toLowerCase())
myInstancesCache.put(instance.id.toLowerCase(), instance)
} else {
myNotifiedInstances.remove(virtualMachineId.toLowerCase())
myInstancesCache.invalidate(virtualMachineId.toLowerCase())
}
}
.take(1)
.toCompletable()
.await()
}
private fun getAssignedNetworkInterfaceId(publicIpAddress: PublicIPAddress?): String? {
if (publicIpAddress == null || !publicIpAddress.hasAssignedNetworkInterface()) return null
val refId: String = publicIpAddress.inner().ipConfiguration().id()
val parentId = ResourceUtils.parentResourceIdFromResourceId(refId)
return parentId
}
override fun getFromCache(parameter: FetchInstancesTaskParameter): List<FetchInstancesTaskInstanceDescriptor>? {
return if (needUpdate(myLastUpdatedDate.get())) null else getFilteredResources(parameter)
}
override fun needCacheUpdate(parameter: FetchInstancesTaskParameter): Boolean {
return needUpdate(myLastUpdatedDate.get())
}
override fun checkThrottleTime(parameter: FetchInstancesTaskParameter): Boolean {
val lastUpdatedDateTime = myLastUpdatedDate.get()
return lastUpdatedDateTime.plusSeconds(getTaskThrottleTime()) < getCurrentUTC()
}
override fun areParametersEqual(parameter: FetchInstancesTaskParameter, other: FetchInstancesTaskParameter): Boolean {
return parameter == other
}
private fun getTaskThrottleTime(): Long {
return TeamCityProperties.getLong(TEAMCITY_CLOUDS_AZURE_THROTTLER_TASK_THROTTLE_TIMEOUT_SEC, 10)
}
private fun getFilteredResources(filter: FetchInstancesTaskParameter): List<FetchInstancesTaskInstanceDescriptor> {
return myInstancesCache.asMap().values
.filter {
val resourceServerId = it.tags[AzureConstants.TAG_SERVER]
filter.serverId.equals(resourceServerId, true).also {
if (!it) LOG.debug("Ignore resource with invalid server tag $resourceServerId")
}
}
.map { instance ->
FetchInstancesTaskInstanceDescriptor(
instance.id,
instance.name,
instance.tags,
getPublicIPAddressOrDefault(instance),
instance.provisioningState,
instance.startDate,
instance.powerState,
instance.error
) }
.toList()
}
override fun invalidateCache() {
myInstancesCache.invalidateAll()
myIpAddresses.set(emptyArray())
myNotifiedInstances.clear()
}
private fun getInstanceState(instanceView: VirtualMachineInstanceViewInner, tags: Map<String, String>, name: String): InstanceViewState {
var provisioningState: String? = null
var startDate: Date? = null
var powerState: String? = null
for (status in instanceView.statuses()) {
val code = status.code()
if (code.startsWith(PROVISIONING_STATE)) {
provisioningState = code.substring(PROVISIONING_STATE.length)
val dateTime = status.time()
if (dateTime != null) {
startDate = dateTime.toDate()
}
}
if (code.startsWith(POWER_STATE)) {
powerState = code.substring(POWER_STATE.length)
}
}
if (tags.containsKey(AzureConstants.TAG_INVESTIGATION)) {
LOG.debug("Virtual machine $name is marked by ${AzureConstants.TAG_INVESTIGATION} tag")
provisioningState = "Investigation"
}
return InstanceViewState(provisioningState, startDate, powerState, null)
}
override fun setCacheTimeout(timeoutInSeconds: Long) {
myTimeoutInSeconds.set(timeoutInSeconds)
}
private fun getPublicIPAddressOrDefault(instance: InstanceDescriptor): String? {
var ipAddresses = myIpAddresses.get()
if (ipAddresses.isEmpty()) return null
val name = instance.name
val ips = ipAddresses.filter {
instance.primaryNetworkInterfaceId != null && it.assignedNetworkInterfaceId == instance.primaryNetworkInterfaceId
}
if (ips.isNotEmpty()) {
for (ip in ips) {
LOG.debug("Received public ip ${ip.ipAddress} for virtual machine $name, assignedNetworkInterfaceId ${ip.assignedNetworkInterfaceId}")
}
val ip = ips.first().ipAddress
if (!ip.isNullOrBlank()) {
return ip
}
} else {
LOG.debug("No public ip received for virtual machine $name")
}
return null
}
private fun createCache() = CacheBuilder.newBuilder().expireAfterWrite(32 * 60, TimeUnit.SECONDS).build<String, InstanceDescriptor>()
private fun getCurrentUTC() = LocalDateTime.now(Clock.systemUTC())
private fun needUpdate(lastUpdatedDate: LocalDateTime) : Boolean {
return lastUpdatedDate.plusSeconds(myTimeoutInSeconds.get()) < getCurrentUTC()
}
data class InstanceViewState (val provisioningState: String?, val startDate: Date?, val powerState: String?, val error: Throwable?)
data class CacheKey (val server: String?)
data class CacheValue(val instances: List<InstanceDescriptor>, val ipAddresses: List<IPAddressDescriptor>, val lastUpdatedDateTime: LocalDateTime)
data class InstanceDescriptor (
val id: String,
val name: String,
val tags: Map<String, String>,
val provisioningState: String?,
val startDate: Date?,
val powerState: String?,
val error: TypedCloudErrorInfo?,
val primaryNetworkInterfaceId: String?,
val lastUpdatedDate: LocalDateTime
)
data class IPAddressDescriptor (
val name: String,
val resourceGroupName: String,
val ipAddress: String,
val assignedNetworkInterfaceId: String?
)
companion object {
private val LOG = Logger.getInstance(FetchInstancesTaskImpl::class.java.name)
private const val PUBLIC_IP_SUFFIX = "-pip"
private const val PROVISIONING_STATE = "ProvisioningState/"
private const val PROVISIONING_STATE_SUCCEEDED = "Succeeded"
private const val POWER_STATE = "PowerState/"
private const val CACHE_KEY = "key"
private const val VIRTUAL_MACHINES_RESOURCE_TYPE = "Microsoft.Compute/virtualMachines"
private const val CONTAINER_INSTANCE_NAMESPACE = "Microsoft.ContainerInstance"
private const val CONTAINER_GROUPS_RESOURCE_TYPE = "containerGroups"
}
}
| plugin-azure-server/src/main/kotlin/jetbrains/buildServer/clouds/azure/arm/connector/tasks/FetchInstancesTaskImpl.kt | 1468562460 |
package org.evomaster.core.search.gene.sql.geometric
import org.evomaster.core.search.gene.*
import org.evomaster.core.logging.LoggingUtil
import org.evomaster.core.search.service.Randomness
import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo
import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class SqlBoxGene(
name: String,
p: SqlPointGene = SqlPointGene("p"),
q: SqlPointGene = SqlPointGene("q")
) : SqlAbstractGeometricGene(name, p, q) {
companion object {
val log: Logger = LoggerFactory.getLogger(SqlBoxGene::class.java)
}
override fun isLocallyValid() : Boolean{
return getViewOfChildren().all { it.isLocallyValid() }
}
override fun copyContent(): Gene = SqlBoxGene(
name,
p.copy() as SqlPointGene,
q.copy() as SqlPointGene
)
override fun copyValueFrom(other: Gene) {
if (other !is SqlBoxGene) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
this.p.copyValueFrom(other.p)
this.q.copyValueFrom(other.q)
}
override fun containsSameValueAs(other: Gene): Boolean {
if (other !is SqlBoxGene) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
return this.p.containsSameValueAs(other.p)
&& this.q.containsSameValueAs(other.q)
}
override fun bindValueBasedOn(gene: Gene): Boolean {
return when {
gene is SqlBoxGene -> {
p.bindValueBasedOn(gene.p) &&
q.bindValueBasedOn(gene.q)
}
else -> {
LoggingUtil.uniqueWarn(log, "cannot bind PointGene with ${gene::class.java.simpleName}")
false
}
}
}
override fun customShouldApplyShallowMutation(
randomness: Randomness,
selectionStrategy: SubsetGeneMutationSelectionStrategy,
enableAdaptiveGeneMutation: Boolean,
additionalGeneMutationInfo: AdditionalGeneMutationInfo?
): Boolean {
return false
}
} | core/src/main/kotlin/org/evomaster/core/search/gene/sql/geometric/SqlBoxGene.kt | 2976448645 |
package com.bubelov.coins.api
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.os.Build
import okhttp3.Interceptor
import okhttp3.Response
import okio.IOException
class ConnectivityCheckingInterceptor(
private val connectivityManager: ConnectivityManager
) : Interceptor, ConnectivityManager.NetworkCallback() {
private var online = false
init {
if (Build.VERSION.SDK_INT >= 24) {
connectivityManager.registerDefaultNetworkCallback(this)
}
}
override fun intercept(chain: Interceptor.Chain): Response {
if (Build.VERSION.SDK_INT < 24) {
@Suppress("DEPRECATION")
online = connectivityManager.activeNetworkInfo?.isConnected ?: false
}
if (online) {
return chain.proceed(chain.request())
} else {
throw IOException("Internet connection is unavailable")
}
}
override fun onCapabilitiesChanged(
network: Network,
capabilities: NetworkCapabilities
) {
online = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
}
} | app/src/main/java/com/bubelov/coins/api/ConnectivityCheckingInterceptor.kt | 4044423148 |
package com.voipgrid.vialer.api
import com.voipgrid.vialer.User
import com.voipgrid.vialer.api.models.PhoneAccount
import org.joda.time.DateTime
import retrofit2.Call
import retrofit2.Response
/**
* This class exists to provide a caching layer between when fetching PhoneAccounts, this is because
* it is a task that we need to perform on potentially hundreds of call records and the actual data
* being retrieved rarely changes, so we do not want to perform the same request very often.
*
*/
class PhoneAccountFetcher(private val api : VoipgridApi) {
private var cache: PhoneAccountsCache = PhoneAccountsCache()
/**
* Fetch a phone account, this has a caching layer in-front of it so
* it can be called frequently without spamming network requests
* for the same record.
*
*/
fun fetch(id: String, callback: Callback) {
cache = loadCacheFromSharedPreferences()
if (cache.isOutdated()) {
invalidateCache()
}
val account = cache[id]
if (account != null) {
callback.onSuccess(account)
return
}
api.phoneAccount(id).enqueue(HttpHandler(id, callback))
}
/**
* Completed resets our cache from both in-memory and shared
* preferences.
*
*/
private fun invalidateCache() {
cache = PhoneAccountsCache()
User.internal.phoneAccountsCache = null
}
/**
* Attempt to check shared preferences for a version of our PhoneAccounts cache.
*
*/
private fun loadCacheFromSharedPreferences() : PhoneAccountsCache {
if (!cache.isEmpty()) return cache
val storedCache : PhoneAccountsCache? = User.internal.phoneAccountsCache
if (storedCache != null) {
return storedCache
}
return PhoneAccountsCache()
}
/**
* The HTTP handler receives responses from the retrofit.
*
*/
inner class HttpHandler(private val id: String, private val callback: Callback) : retrofit2.Callback<PhoneAccount> {
override fun onFailure(call: Call<PhoneAccount>, t: Throwable) {
}
override fun onResponse(call: Call<PhoneAccount>, response: Response<PhoneAccount>) {
if (!response.isSuccessful) {
return
}
val account = response.body() ?: return
cache[id] = account
callback.onSuccess(account)
User.internal.phoneAccountsCache = cache
}
}
/**
* Provide a callback for when the fetcher has found a phone account.
*
*/
interface Callback {
fun onSuccess(phoneAccount: PhoneAccount)
}
/**
* Provides a class to cache the phone accounts that are found.
*
*/
class PhoneAccountsCache : HashMap<String, PhoneAccount>() {
private val initialTime = DateTime()
/**
* Check if the data held by this cache is outdated, if so this should
* be invalidated and the information reset.
*
*/
fun isOutdated() : Boolean {
return initialTime.isBefore(DateTime().minusDays(DAYS_VALID_FOR))
}
companion object {
/**
* We will store the records for this many days before invalidating the cache
* completely and re-fetching the records.
*
*/
const val DAYS_VALID_FOR = 3
}
}
} | app/src/main/java/com/voipgrid/vialer/api/PhoneAccountFetcher.kt | 4198006587 |
package me.proxer.library.entity.info
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import me.proxer.library.enums.MediaLanguage
/**
* Entity holding the data of a single anime episode.
*
* @property hosters The names of the available hosters.
* @property hosterImages The images of the available hosters.
*
* @author Ruben Gees
*/
@JsonClass(generateAdapter = true)
data class AnimeEpisode(
override val number: Int,
override val language: MediaLanguage,
@Json(name = "types") val hosters: Set<String>,
@Json(name = "typeimages") val hosterImages: List<String>
) : Episode(number, language)
| library/src/main/kotlin/me/proxer/library/entity/info/AnimeEpisode.kt | 2547677300 |
package com.ak47.cms.cms
import com.ak47.cms.cms.service.CrawImageService
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
@SpringBootTest
class CrawHuaBanImagesTest {
@Autowired lateinit var CrawImageService: CrawImageService
//@Test
// fun testCrawHuaBanImages() {
// CrawImageService.doCrawHuaBanImages()
// }
} | src/test/kotlin/com/ak47/cms/cms/CrawHuaBanImagesTest.kt | 2258468159 |
package edu.kit.iti.formal.automation.ide.editors
import edu.kit.iti.formal.automation.ide.AntlrLexerFactory
import edu.kit.iti.formal.automation.ide.Colors
import edu.kit.iti.formal.automation.ide.Lookup
import edu.kit.iti.formal.smv.parser.SMVLexer
import edu.kit.iti.formal.smv.parser.SMVLexer.*
import edu.kit.iti.formal.automation.ide.BaseLanguageSupport
import org.antlr.v4.runtime.CharStreams
import org.antlr.v4.runtime.Lexer
import org.fife.ui.rsyntaxtextarea.Style
import org.fife.ui.rsyntaxtextarea.SyntaxScheme
import java.util.*
class SmvLanguageSupport(lookup: Lookup) : BaseLanguageSupport() {
override val mimeType: String = "text/smv"
override val extension: Collection<String> = Collections.singleton("smv")
override val syntaxScheme: SyntaxScheme = SmvSyntaxScheme(lookup)
override val antlrLexerFactory: AntlrLexerFactory
get() = object : AntlrLexerFactory {
override fun create(code: String): Lexer =
SMVLexer(CharStreams.fromString(code))
}
//override val parserData: ParserData?
// get() = ParserData(SMVParser.ruleNames, SMVLexer.VOCABULARY, SMVLexer._ATN)
}
class SmvSyntaxScheme(lookup: Lookup) : SyntaxScheme(true) {
private val colors: Colors by lookup.with()
private val STRUCTURAL_KEYWORDS = setOf(
ASSIGN, TRANS, CTLSPEC, SPEC, PSLSPEC, LTLSPEC, INVAR, INVARSPEC, MODULE,
INIT, NEXT, ARRAY, ASSIGN, BOOLEAN, CASE, COMMA, COMPASSION, CONSTANTS,
CTLSPEC, DEFINE, FAIRNESS, FROZENVAR, INITBIG, INVAR,
INVARSPEC, ISA, IVAR, JUSTICE, LTLSPEC, MODULE, NAME, PROCESS,
PSLSPEC, SIGNED, SPEC,
TRANS, UNSIGNED,
VAR, WORD, OF
)
private val SEPS = setOf(
COLON, COLONEQ, DCOLON, SEMI, LBRACE, RBRACE, LPAREN, RPAREN, RBRACKET, LBRACKET, DOTDOT, DOT)
private val OPERATORS = setOf(S,
IN, INIT, NEXT, LT, LTE, MINUS, MOD, NEQ, O, OR,
PLUS, SHIFTL, SHIFTR, STAR, DIV, EF, EG, EQ, EQUIV, ESAC,
EU, EX, F, G, GT, GTE, H, IMP, V, X, XNOR, XOR, Y, Z, NOT,
AF, AG, AND, AU, AX, T, U, UNION
)
private val LITERALS = setOf(
TRUE, FALSE, WORD_LITERAL, FLOAT, NUMBER
)
override fun getStyle(index: Int): Style {
return when (index) {
in SEPS -> colors.separators
ERROR_CHAR -> colors.error
in STRUCTURAL_KEYWORDS -> colors.structural
in OPERATORS -> colors.control
in LITERALS -> colors.literal
ID -> colors.identifier
SL_COMMENT -> colors.comment
else -> colors.default
}
}
}
| ide/src/main/kotlin/edu/kit/iti/formal/automation/ide/editors/smv.kt | 2310881698 |
/*
* Copyright 2017 Alexey Shtanko
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.shtanko.picasagallery.data.api
import io.reactivex.Flowable
import io.reactivex.Observable
import io.shtanko.picasagallery.data.model.AlbumEntity
import io.shtanko.picasagallery.data.model.AlbumsResponseEntity
import io.shtanko.picasagallery.data.model.UserFeedResponseEntity
interface ApiManager {
fun getUser(userId: String): Observable<UserFeedResponseEntity>
fun getUserAlbums(userId: String): Flowable<List<AlbumEntity>>
fun getAlbums(
userId: String,
albumId: String
): Observable<AlbumsResponseEntity>
} | app/src/main/kotlin/io/shtanko/picasagallery/data/api/ApiManager.kt | 667386218 |
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.app.scene
import com.almasb.fxgl.logging.stackTraceToString
import com.almasb.fxgl.scene.SubScene
import com.almasb.fxgl.ui.MDIWindow
import javafx.scene.control.Button
import javafx.scene.control.ScrollPane
import javafx.scene.control.TextArea
import javafx.scene.layout.VBox
class ErrorSubScene(
val sceneWidth: Double,
val sceneHeight: Double,
/**
* Error to be displayed.
*/
val error: Throwable,
/**
* Action to run on subscene close.
*/
val action: Runnable) : SubScene() {
init {
val btnOK = Button("Exit game")
btnOK.setOnAction {
action.run()
}
val scrollPane = ScrollPane(makeStackTraceArea())
scrollPane.setPrefSize(sceneWidth, sceneHeight)
val window = MDIWindow()
window.isCloseable = false
window.title = "Error Reporter"
window.contentPane.children += VBox(btnOK, scrollPane)
contentRoot.children += window
}
private fun makeStackTraceArea() = TextArea(makeErrorMessage() + "\n\n" + makeStackTrace()).apply {
isEditable = false
isWrapText = true
// guesstimate size
setPrefSize(sceneWidth, (text.count { it == '\n' } + 1) * 20.0)
}
private fun makeErrorMessage(): String {
val name: String
val line: String
if (error.stackTrace.isEmpty()) {
name = "Empty stack trace"
line = "Empty stack trace"
} else {
val trace = error.stackTrace.first()
name = trace.className.substringAfterLast('.') + "." + trace.methodName + "()"
line = trace.toString().substringAfter('(').substringBefore(')')
}
return "Message: ${error.message}\n" +
"Type: ${error.javaClass.simpleName}\n" +
"Method: $name\n" +
"Line: $line"
}
private fun makeStackTrace() = error.stackTraceToString()
} | fxgl/src/main/kotlin/com/almasb/fxgl/app/scene/ErrorSubScene.kt | 3035838649 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.tests
import java.io.*
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.testfixtures.ProjectBuilder
internal fun createProject(): Project {
with(ProjectBuilder.builder().build()) {
plugins.apply("com.facebook.react")
return this
}
}
internal inline fun <reified T : Task> createTestTask(
project: Project = createProject(),
taskName: String = T::class.java.simpleName,
crossinline block: (T) -> Unit = {}
): T = project.tasks.register(taskName, T::class.java) { block(it) }.get()
/** A util function to zip a list of files from [contents] inside the zipfile at [destination]. */
internal fun zipFiles(destination: File, contents: List<File>) {
ZipOutputStream(BufferedOutputStream(FileOutputStream(destination.absolutePath))).use { out ->
for (file in contents) {
FileInputStream(file).use { fi ->
BufferedInputStream(fi).use { origin ->
val entry = ZipEntry(file.name)
out.putNextEntry(entry)
origin.copyTo(out, 1024)
}
}
}
}
}
| packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tests/TaskTestUtils.kt | 1078880364 |
/*
* 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.classes.bukkit
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.characters.bukkit.character.field.RPKCharacterCardFieldService
import com.rpkit.classes.bukkit.character.ClassField
import com.rpkit.classes.bukkit.classes.RPKClassService
import com.rpkit.classes.bukkit.classes.RPKClassServiceImpl
import com.rpkit.classes.bukkit.command.`class`.ClassCommand
import com.rpkit.classes.bukkit.database.table.RPKCharacterClassTable
import com.rpkit.classes.bukkit.database.table.RPKClassExperienceTable
import com.rpkit.classes.bukkit.listener.*
import com.rpkit.classes.bukkit.messages.ClassesMessages
import com.rpkit.classes.bukkit.placeholder.RPKClassesPlaceholderExpansion
import com.rpkit.classes.bukkit.skillpoint.RPKSkillPointServiceImpl
import com.rpkit.core.bukkit.listener.registerListeners
import com.rpkit.core.database.Database
import com.rpkit.core.database.DatabaseConnectionProperties
import com.rpkit.core.database.DatabaseMigrationProperties
import com.rpkit.core.database.UnsupportedDatabaseDialectException
import com.rpkit.core.plugin.RPKPlugin
import com.rpkit.core.service.Services
import com.rpkit.skills.bukkit.skills.RPKSkillPointService
import com.rpkit.stats.bukkit.stat.RPKStatVariable
import com.rpkit.stats.bukkit.stat.RPKStatVariableName
import com.rpkit.stats.bukkit.stat.RPKStatVariableService
import org.bstats.bukkit.Metrics
import org.bukkit.configuration.file.YamlConfiguration
import org.bukkit.plugin.java.JavaPlugin
import java.io.File
class RPKClassesBukkit : JavaPlugin(), RPKPlugin {
lateinit var database: Database
lateinit var messages: ClassesMessages
override fun onEnable() {
System.setProperty("com.rpkit.classes.bukkit.shadow.impl.org.jooq.no-logo", "true")
System.setProperty("com.rpkit.classes.bukkit.shadow.impl.org.jooq.no-tips", "true")
Metrics(this, 4386)
saveDefaultConfig()
messages = ClassesMessages(this)
val databaseConfigFile = File(dataFolder, "database.yml")
if (!databaseConfigFile.exists()) {
saveResource("database.yml", false)
}
val databaseConfig = YamlConfiguration.loadConfiguration(databaseConfigFile)
val databaseUrl = databaseConfig.getString("database.url")
if (databaseUrl == null) {
logger.severe("Database URL not set!")
isEnabled = false
return
}
val databaseUsername = databaseConfig.getString("database.username")
val databasePassword = databaseConfig.getString("database.password")
val databaseSqlDialect = databaseConfig.getString("database.dialect")
val databaseMaximumPoolSize = databaseConfig.getInt("database.maximum-pool-size", 3)
val databaseMinimumIdle = databaseConfig.getInt("database.minimum-idle", 3)
if (databaseSqlDialect == null) {
logger.severe("Database SQL dialect not set!")
isEnabled = false
return
}
database = Database(
DatabaseConnectionProperties(
databaseUrl,
databaseUsername,
databasePassword,
databaseSqlDialect,
databaseMaximumPoolSize,
databaseMinimumIdle
),
DatabaseMigrationProperties(
when (databaseSqlDialect) {
"MYSQL" -> "com/rpkit/classes/migrations/mysql"
"SQLITE" -> "com/rpkit/classes/migrations/sqlite"
else -> throw UnsupportedDatabaseDialectException("Unsupported database dialect $databaseSqlDialect")
},
"flyway_schema_history_classes"
),
classLoader
)
database.addTable(RPKCharacterClassTable(database, this))
database.addTable(RPKClassExperienceTable(database, this))
Services[RPKClassService::class.java] = RPKClassServiceImpl(this)
Services[RPKSkillPointService::class.java] = RPKSkillPointServiceImpl(this)
Services.require(RPKStatVariableService::class.java).whenAvailable { statVariableService ->
Services.require(RPKClassService::class.java).whenAvailable { classService ->
config.getConfigurationSection("classes")
?.getKeys(false)
?.flatMap { className ->
config.getConfigurationSection("classes.$className.stat-variables")?.getKeys(false) ?: setOf()
}
?.toSet()
?.forEach { statVariableName ->
statVariableService.addStatVariable(object : RPKStatVariable {
override val name = RPKStatVariableName(statVariableName)
override fun get(character: RPKCharacter): Double {
val `class` = classService.getPreloadedClass(character)
return `class`?.getStatVariableValue(
this,
classService.getLevel(character, `class`).join()
)?.toDouble()
?: 0.0
}
})
}
}
}
Services.require(RPKCharacterCardFieldService::class.java).whenAvailable { service ->
service.addCharacterCardField(ClassField())
}
registerCommands()
registerListeners()
if (server.pluginManager.getPlugin("PlaceholderAPI") != null) {
RPKClassesPlaceholderExpansion(this).register()
}
}
private fun registerCommands() {
getCommand("class")?.setExecutor(ClassCommand(this))
}
private fun registerListeners() {
registerListeners(
AsyncPlayerPreLoginListener(),
PlayerQuitListener(),
RPKCharacterSwitchListener(),
RPKCharacterUpdateListener(this),
RPKCharacterDeleteListener(this)
)
}
} | bukkit/rpk-classes-bukkit/src/main/kotlin/com/rpkit/classes/bukkit/RPKClassesBukkit.kt | 1042740027 |
package com.arcao.geocaching4locus.import_bookmarks.paging
import androidx.paging.PagingConfig
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.arcao.geocaching4locus.base.usecase.GetUserListsUseCase
import com.arcao.geocaching4locus.base.usecase.entity.GeocacheListEntity
import kotlinx.coroutines.CancellationException
class GeocacheUserListsDataSource(
private val getUserLists: GetUserListsUseCase,
private val pagingConfig: PagingConfig
) : PagingSource<Int, GeocacheListEntity>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, GeocacheListEntity> {
return try {
val page = params.key ?: 0
val skip = page * params.loadSize
val response = getUserLists(
skip = skip,
take = params.loadSize
)
val currentCount = skip + response.size
val totalCount = response.totalCount
LoadResult.Page(
data = response,
prevKey = if (page == 0) null else page - 1,
nextKey = if (currentCount < totalCount) page + (params.loadSize / pagingConfig.pageSize) else null
)
} catch (e: Exception) {
if (e is CancellationException) throw e
LoadResult.Error(e)
}
}
override fun getRefreshKey(state: PagingState<Int, GeocacheListEntity>): Int? {
return state.anchorPosition?.let { anchorPosition ->
state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
}
}
} | app/src/main/java/com/arcao/geocaching4locus/import_bookmarks/paging/GeocacheUserListsDataSource.kt | 1468474843 |
/*
* 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.chat.bukkit.chatgroup
import com.rpkit.core.service.Service
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile
import java.util.concurrent.CompletableFuture
/**
* Provides chat group related operations.
*/
interface RPKChatGroupService : Service {
/**
* Gets a chat group by ID.
* If there is no chat group with the given ID, null is returned.
*
* @param id The ID of the chat group
* @return The chat group, or null if no chat group is found with the given ID
*/
fun getChatGroup(id: RPKChatGroupId): CompletableFuture<out RPKChatGroup?>
/**
* Gets a chat group by name.
* If there is no chat group with the given name, null is returned.
*
* @param name The name of the chat group
* @return The chat group, or null if no chat group is found with the given ID
*/
fun getChatGroup(name: RPKChatGroupName): CompletableFuture<out RPKChatGroup?>
/**
* Adds a chat group to be tracked by this chat group service.
*
* @param chatGroup The chat group to add
*/
fun addChatGroup(chatGroup: RPKChatGroup): CompletableFuture<Void>
fun createChatGroup(name: RPKChatGroupName): CompletableFuture<RPKChatGroup>
/**
* Removes a chat group from being tracked by this chat group service.
*
* @param chatGroup The chat group to remove
*/
fun removeChatGroup(chatGroup: RPKChatGroup): CompletableFuture<Void>
/**
* Updates a chat group in data storage.
*
* @param chatGroup The chat group to update
*/
fun updateChatGroup(chatGroup: RPKChatGroup): CompletableFuture<Void>
/**
* Gets a Minecraft profile's last used chat group.
* If the Minecraft profile has not used a chat group, null is returned.
*
* @param minecraftProfile The Minecraft profile
* @return The last used chat group used by the Minecraft profile, or null if the Minecraft profile has not used a chat group
*/
fun getLastUsedChatGroup(minecraftProfile: RPKMinecraftProfile): CompletableFuture<RPKChatGroup?>
/**
* Sets a Minecraft profile's last used chat group.
*
* @param minecraftProfile The Minecraft profile
* @param chatGroup The chat group to set
*/
fun setLastUsedChatGroup(minecraftProfile: RPKMinecraftProfile, chatGroup: RPKChatGroup): CompletableFuture<Void>
} | bukkit/rpk-chat-lib-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/chatgroup/RPKChatGroupService.kt | 2917313980 |
package net.ltgt.gradle.errorprone
import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.GradleRunner
import org.gradle.util.GradleVersion
import java.io.File
val testGradleVersion = System.getProperty("test.gradle-version", GradleVersion.current().version)
val errorproneVersion = System.getProperty("errorprone.version")!!
const val FAILURE_SOURCE_COMPILATION_ERROR = "Failure.java:6: error: [ArrayEquals]"
fun File.writeSuccessSource() {
File(this.resolve("src/main/java/test").apply { mkdirs() }, "Success.java").apply {
createNewFile()
writeText(
"""
package test;
public class Success {
// See http://errorprone.info/bugpattern/ArrayEquals
@SuppressWarnings("ArrayEquals")
public boolean arrayEquals(int[] a, int[] b) {
return a.equals(b);
}
}
""".trimIndent()
)
}
}
fun File.writeFailureSource() {
File(this.resolve("src/main/java/test").apply { mkdirs() }, "Failure.java").apply {
createNewFile()
writeText(
"""
package test;
public class Failure {
// See http://errorprone.info/bugpattern/ArrayEquals
public boolean arrayEquals(int[] a, int[] b) {
return a.equals(b);
}
}
""".trimIndent()
)
}
}
fun File.buildWithArgs(vararg tasks: String): BuildResult {
return prepareBuild(*tasks)
.build()
}
fun File.buildWithArgsAndFail(vararg tasks: String): BuildResult {
return prepareBuild(*tasks)
.buildAndFail()
}
fun File.prepareBuild(vararg tasks: String): GradleRunner {
return GradleRunner.create()
.withGradleVersion(testGradleVersion)
.withProjectDir(this)
.withPluginClasspath()
.withArguments(*tasks)
.forwardOutput()
}
| src/test/kotlin/net/ltgt/gradle/errorprone/fixtures.kt | 3514013949 |
package br.com.wakim.eslpodclient.dagger
import br.com.wakim.eslpodclient.Application
import br.com.wakim.eslpodclient.android.receiver.ConnectivityBroadcastReceiver
import br.com.wakim.eslpodclient.android.service.DownloadManagerReceiver
import br.com.wakim.eslpodclient.android.service.PlayerService
import br.com.wakim.eslpodclient.android.service.StorageService
import br.com.wakim.eslpodclient.dagger.module.ActivityModule
import br.com.wakim.eslpodclient.dagger.module.AppModule
import br.com.wakim.eslpodclient.dagger.module.InteractorModule
import br.com.wakim.eslpodclient.data.interactor.PreferenceInteractor
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(modules = arrayOf(InteractorModule::class, AppModule::class))
interface AppComponent {
fun inject(app: Application)
fun inject(playerService: PlayerService)
fun inject(storageService: StorageService)
fun inject(downloadManagerReceiver: DownloadManagerReceiver)
fun inject(connectivityBroadcastReceiver: ConnectivityBroadcastReceiver)
fun preferencesManager() : PreferenceInteractor
fun plus(activityModule: ActivityModule) : ActivityComponent
} | app/src/main/java/br/com/wakim/eslpodclient/dagger/AppComponent.kt | 1843717900 |
package cn.yiiguxing.plugin.translate.ui
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.UIUtil
import java.awt.AlphaComposite
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.RenderingHints
import javax.swing.JComponent
/**
* List item circle component
*/
class ListItemCircleComponent : JComponent() {
init {
preferredSize = JBDimension(9, 9)
foreground = UIUtil.getLabelForeground()
}
override fun getComponentGraphics(g: Graphics): Graphics {
return (super.getComponentGraphics(g) as Graphics2D).apply {
composite = ALPHA_COMPOSITE
setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
}
}
override fun paintComponent(g: Graphics) {
g.fillOval(0, 0, width, height)
}
companion object {
private val ALPHA_COMPOSITE = AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, .7f)
}
} | src/main/kotlin/cn/yiiguxing/plugin/translate/ui/ListItemCircleComponent.kt | 1764598120 |
/*
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.editor.resources
import uk.co.nickthecoder.tickle.editor.scene.StageLayer
import uk.co.nickthecoder.tickle.resources.ActorResource
class DesignActorResource : ActorResource() {
var layer: StageLayer? = null
}
| tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/resources/DesignActorResource.kt | 2642801436 |
package domain.processing.entities.objects
import domain.global.entities.NamedEntity
import domain.global.validators.EntityValidator
import domain.global.validators.OutputValidator
import domain.global.validators.Validable
import org.neo4j.ogm.annotation.NodeEntity
/**
* Created by Christian Sperandio on 03/05/2016.
*
*/
@NodeEntity(label = "Output")
class OutputEntity(_name: String = "") : NamedEntity(_name), Validable<OutputEntity> {
var value: String? = null
override fun resetId() {
id = null
}
override fun buildValidator(): EntityValidator<OutputEntity> {
return OutputValidator()
}
}
| src/main/kotlin/domain/processing/entities/objects/OutputEntity.kt | 3553536139 |
package com.fsck.k9.backend.jmap
data class JmapConfig(
val username: String,
val password: String,
val baseUrl: String?,
val accountId: String
)
| backend/jmap/src/main/java/com/fsck/k9/backend/jmap/JmapConfig.kt | 3407486295 |
package br.com.wakim.eslpodclient.ui.podcastlist.view
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.matcher.ViewMatchers.isDisplayed
import android.support.test.espresso.matcher.ViewMatchers.withId
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import br.com.wakim.eslpodclient.R
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class PodcastListActivityTest() {
@get:Rule
val activityRule = ActivityTestRule<PodcastListActivity>(PodcastListActivity::class.java)
@Test
fun test() {
onView(withId(R.id.pb_loading))
.check(matches(isDisplayed()))
}
} | app/src/androidTest/java/br/com/wakim/eslpodclient/ui/podcastlist/view/PodcastListActivityTest.kt | 2898711319 |
package com.github.kittinunf.reactiveandroid.reactive
import com.github.kittinunf.reactiveandroid.MutablePropertyType
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
fun <T : R, R> Observable<T>.bindTo(property: MutablePropertyType<R>): Disposable {
return subscribe {
property.value = it
}
}
fun <T> Observable<T>.cachedPrevious(): Observable<Pair<T?, T?>> {
return scan(Pair<T?, T?>(null, null)) { (_, j), item -> j to item }
.skip(1)
}
inline fun <reified T> Observable<in T>.ofType() = ofType(T::class.java) | reactiveandroid/src/main/kotlin/com/github/kittinunf/reactiveandroid/reactive/ObservableExtension.kt | 2076909179 |
package com.mymikemiller.gamegrumpsplayer
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("com.mymikemiller.gamegrumpsplayer", appContext.packageName)
}
}
| app/src/androidTest/java/com/mymikemiller/gamegrumpsplayer/ExampleInstrumentedTest.kt | 1266225974 |
package org.luxons.sevenwonders.server.validation
import org.luxons.sevenwonders.server.repositories.LobbyRepository
import org.springframework.stereotype.Component
import java.util.regex.Pattern
@Component
class DestinationAccessValidator(private val lobbyRepository: LobbyRepository) {
fun hasAccess(username: String?, destination: String): Boolean {
return when {
username == null -> false // unnamed user cannot belong to anything
hasForbiddenGameReference(username, destination) -> false
hasForbiddenLobbyReference(username, destination) -> false
else -> true
}
}
private fun hasForbiddenGameReference(username: String, destination: String): Boolean {
val gameMatcher = gameDestination.matcher(destination)
if (!gameMatcher.matches()) {
return false // no game reference is always OK
}
val gameId = gameMatcher.group("id").toLong()
return !isUserInLobby(username, gameId)
}
private fun hasForbiddenLobbyReference(username: String, destination: String): Boolean {
val lobbyMatcher = lobbyDestination.matcher(destination)
if (!lobbyMatcher.matches()) {
return false // no lobby reference is always OK
}
val lobbyId = lobbyMatcher.group("id").toLong()
return !isUserInLobby(username, lobbyId)
}
private fun isUserInLobby(username: String, lobbyId: Long): Boolean =
lobbyRepository.find(lobbyId).containsUser(username)
companion object {
private val lobbyDestination = Pattern.compile(".*?/lobby/(?<id>\\d+?)(/.*)?")
private val gameDestination = Pattern.compile(".*?/game/(?<id>\\d+?)(/.*)?")
}
}
| sw-server/src/main/kotlin/org/luxons/sevenwonders/server/validation/DestinationAccessValidator.kt | 913910010 |
//
// Calendar Notifications Plus
// Copyright (C) 2016 Sergey Parshin ([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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
package com.github.quarck.calnotify.permissions
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
object PermissionsManager {
private fun Context.hasPermission(perm: String) =
ContextCompat.checkSelfPermission(this, perm) == PackageManager.PERMISSION_GRANTED
private fun Activity.shouldShowRationale(perm: String) =
ActivityCompat.shouldShowRequestPermissionRationale(this, perm)
fun hasWriteCalendarNoCache(context: Context)
= context.hasPermission(Manifest.permission.WRITE_CALENDAR)
fun hasReadCalendarNoCache(context: Context)
= context.hasPermission(Manifest.permission.READ_CALENDAR)
fun hasCoarseLocationNoCache(context: Context)
= context.hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
private var hasWriteCalendarCached: Boolean = false
private var hasReadCalendarCached: Boolean = false
private var hasAccessCoarseLocationCached: Boolean = false
fun hasWriteCalendar(context: Context): Boolean {
if (!hasWriteCalendarCached)
hasWriteCalendarCached = hasWriteCalendarNoCache(context)
return hasWriteCalendarCached
}
fun hasReadCalendar(context: Context): Boolean {
if (!hasReadCalendarCached)
hasReadCalendarCached = hasReadCalendarNoCache(context)
return hasReadCalendarCached
}
fun hasAccessCoarseLocation(context: Context): Boolean {
if (!hasAccessCoarseLocationCached)
hasAccessCoarseLocationCached = hasCoarseLocationNoCache(context)
return hasAccessCoarseLocationCached
}
fun hasAllCalendarPermissions(context: Context) = hasWriteCalendar(context) && hasReadCalendar(context)
fun hasAllCalendarPermissionsNoCache(context: Context) = hasWriteCalendarNoCache(context) && hasReadCalendarNoCache(context)
fun shouldShowCalendarRationale(activity: Activity) =
activity.shouldShowRationale(Manifest.permission.WRITE_CALENDAR) || activity.shouldShowRationale(Manifest.permission.READ_CALENDAR)
fun shouldShowLocationRationale(activity: Activity) =
activity.shouldShowRationale(Manifest.permission.ACCESS_COARSE_LOCATION)
fun requestCalendarPermissions(activity: Activity) =
ActivityCompat.requestPermissions(activity,
arrayOf(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR), 0)
fun requestLocationPermissions(activity: Activity) =
ActivityCompat.requestPermissions(activity,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), 0)
} | app/src/main/java/com/github/quarck/calnotify/permissions/PermissionsManager.kt | 2956990521 |
package net.perfectdreams.loritta.morenitta.utils.logback
import ch.qos.logback.core.joran.spi.NoAutoStart
import ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP
import java.io.File
@NoAutoStart
class StartupSizeTimeBasedTriggeringPolicy<E> : SizeAndTimeBasedFNATP<E>() {
private var startedX = false
override fun isTriggeringEvent(activeFile: File?, event: E): Boolean {
if (!startedX) {
nextCheck = 0L
return true.also { startedX = it }
}
return super.isTriggeringEvent(activeFile, event)
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/logback/StartupSizeTimeBasedTriggeringPolicy.kt | 1325207108 |
package ru.hyst329.openfool
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.Sprite
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.badlogic.gdx.utils.viewport.FitViewport
import com.kotcrab.vis.ui.widget.VisProgressBar
import com.kotcrab.vis.ui.widget.VisTextButton
/**
* Created by hyst329 on 13.03.2017.
* Licensed under MIT License.
*/
internal class MainMenuScreen(private val game: OpenFoolGame) : Screen {
private val stage: Stage = Stage(FitViewport(800f, 480f))
private var logo: Sprite = Sprite(Texture(Gdx.files.internal("logos/mm_logo.png")))
private var hammerAndSickle: Sprite = Sprite(Texture(Gdx.files.internal("holidays/hammersickle.png")))
private var santaHat: Sprite = Sprite(Texture(Gdx.files.internal("holidays/santahat.png")))
private var canStart: Boolean = false
private val newGameButton: VisTextButton
private val settingsButton: VisTextButton
private val quitButton: VisTextButton
private val progressBar: VisProgressBar
init {
// Initialise the stage
Gdx.input.inputProcessor = stage
game.orientationHelper.requestOrientation(OrientationHelper.Orientation.LANDSCAPE)
newGameButton = VisTextButton(game.localeBundle.get("NewGame"))
newGameButton.setBounds(40f, 300f, 250f, 80f)
newGameButton.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
// super.clicked(event, x, y);
if (canStart)
newGame()
}
})
stage.addActor(newGameButton)
settingsButton = VisTextButton(game.localeBundle.get("Settings"))
settingsButton.setBounds(40f, 200f, 250f, 80f)
settingsButton.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
// super.clicked(event, x, y);
showSettings()
}
})
stage.addActor(settingsButton)
quitButton = VisTextButton(game.localeBundle.get("Quit"))
quitButton.setBounds(40f, 100f, 250f, 80f)
quitButton.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
// super.clicked(event, x, y);
quit()
}
})
stage.addActor(quitButton)
progressBar = VisProgressBar(0f, 1f, 1e-3f, false)
progressBar.setBounds(40f, 40f, 720f, 60f)
progressBar.setAnimateDuration(0.2f)
stage.addActor(progressBar)
}
override fun show() {
}
override fun render(delta: Float) {
when (getCurrentHoliday()) {
Holiday.OCTOBER_REVOLUTION -> Gdx.gl.glClearColor(0.8f, 0.0f, 0.0f, 1f)
Holiday.NEW_YEAR -> Gdx.gl.glClearColor(0.0f, 0.6f, 0.9f, 1f)
null -> Gdx.gl.glClearColor(0.2f, 0.8f, 0.3f, 1f)
}
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
stage.act(delta)
stage.draw()
game.batch.transformMatrix = stage.viewport.camera.view
game.batch.projectionMatrix = stage.viewport.camera.projection
game.batch.begin()
if (game.assetManager.update()) {
canStart = true
logo.setCenter(stage.viewport.worldWidth * 560f / 840f, stage.viewport.worldHeight * 250f / 480f)
logo.draw(game.batch)
when (getCurrentHoliday()) {
Holiday.OCTOBER_REVOLUTION -> {
hammerAndSickle.setCenter(stage.viewport.worldWidth * 165f / 840f, stage.viewport.worldHeight * 430f / 480f)
hammerAndSickle.setScale(0.35f)
hammerAndSickle.draw(game.batch)
}
Holiday.NEW_YEAR -> {
santaHat.setCenter(stage.viewport.worldWidth * 165f / 840f, stage.viewport.worldHeight * 430f / 480f)
santaHat.setScale(0.3f)
santaHat.draw(game.batch)
}
null -> {
}
}
} else {
val progress = game.assetManager.progress
game.font.draw(game.batch, game.localeBundle.format("LoadingAssets",
Math.round(progress * 100)), stage.viewport.worldWidth / 2.8f, stage.viewport.worldHeight / 4.4f)
progressBar.value = progress
}
game.batch.end()
newGameButton.isVisible = canStart
settingsButton.isVisible = canStart
quitButton.isVisible = canStart
progressBar.isVisible = !canStart
if (Gdx.input.isKeyJustPressed(Input.Keys.BACK) || Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE)) {
Gdx.app.exit()
}
}
override fun resize(width: Int, height: Int) {
stage.viewport.update(width, height, true)
stage.viewport.camera.update()
}
override fun pause() {
}
override fun resume() {
}
override fun hide() {
}
override fun dispose() {
}
private fun newGame() {
game.screen = NewGameScreen(game)
dispose()
}
private fun showSettings() {
game.screen = SettingsScreen(game)
dispose()
}
private fun quit() {
dispose()
Gdx.app.exit()
}
}
| core/src/ru/hyst329/openfool/MainMenuScreen.kt | 460512249 |
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.videos
import net.perfectdreams.gabrielaimageserver.client.GabrielaImageServerClient
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images.base.GabrielaImageServerSingleCommandBase
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images.base.SingleImageOptions
class CarlyAaahExecutor(
loritta: LorittaBot,
client: GabrielaImageServerClient
) : GabrielaImageServerSingleCommandBase(
loritta,
client,
{ client.videos.carlyAaah(it) },
"carly_aaah.mp4"
) | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/videos/CarlyAaahExecutor.kt | 2853296181 |
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images.declarations
import net.perfectdreams.gabrielaimageserver.client.GabrielaImageServerClient
import net.perfectdreams.loritta.common.locale.LanguageManager
import net.perfectdreams.loritta.i18n.I18nKeysData
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.common.commands.CommandCategory
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandDeclarationWrapper
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images.BobBurningPaperExecutor
class BobBurningPaperCommand(languageManager: LanguageManager) : CinnamonSlashCommandDeclarationWrapper(languageManager) {
companion object {
val I18N_PREFIX = I18nKeysData.Commands.Command.Bobburningpaper
}
override fun declaration() = slashCommand(I18N_PREFIX.Label, CommandCategory.IMAGES, I18N_PREFIX.Description) {
executor = { BobBurningPaperExecutor(it, it.gabrielaImageServerClient) }
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/images/declarations/BobBurningPaperCommand.kt | 2218920396 |
/*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.tls
import org.junit.Assert
import org.junit.Test
class CertificatesTest {
@Test fun testRoundtrip() {
val certificateString = """
-----BEGIN CERTIFICATE-----
MIIBmjCCAQOgAwIBAgIBATANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDEwhjYXNo
LmFwcDAeFw03MDAxMDEwMDAwMDBaFw03MDAxMDEwMDAwMDFaMBMxETAPBgNVBAMT
CGNhc2guYXBwMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCApFHhtrLan28q
+oMolZuaTfWBA0V5aMIvq32BsloQu6LlvX1wJ4YEoUCjDlPOtpht7XLbUmBnbIzN
89XK4UJVM6Sqp3K88Km8z7gMrdrfTom/274wL25fICR+yDEQ5fUVYBmJAKXZF1ao
I0mIoEx0xFsQhIJ637v2MxJDupd61wIDAQABMA0GCSqGSIb3DQEBCwUAA4GBADam
UVwKh5Ry7es3OxtY3IgQunPUoLc0Gw71gl9Z+7t2FJ5VkcI5gWfutmdxZ2bDXCI8
8V0vxo1pHXnbBrnxhS/Z3TBerw8RyQqcaWOdp+pBXyIWmR+jHk9cHZCqQveTIBsY
jaA9VEhgdaVhxBsT2qzUNDsXlOzGsliznDfoqETb
-----END CERTIFICATE-----
""".trimIndent()
val certificate = certificateString.decodeCertificatePem()
Assert.assertEquals(certificateString, certificate.certificatePem())
}
}
| okhttp-tls/src/test/java/okhttp3/tls/CertificatesTest.kt | 1506197856 |
package com.jaynewstrom.concretesample.application
import android.app.Application
import com.jaynewstrom.concrete.Concrete
import com.jaynewstrom.concrete.ConcreteWall
class ConcreteSampleApplication : Application() {
private lateinit var foundation: ConcreteWall<ApplicationComponent>
override fun onCreate() {
super.onCreate()
foundation = Concrete.pourFoundation(createApplicationComponent())
}
private fun createApplicationComponent(): ApplicationComponent {
return DaggerApplicationComponent.builder().applicationModule(ApplicationModule(this)).build()
}
override fun getSystemService(name: String): Any? {
return if (Concrete.isService(name)) {
foundation
} else {
super.getSystemService(name)
}
}
}
| concrete-sample/src/main/java/com/jaynewstrom/concretesample/application/ConcreteSampleApplication.kt | 3338623234 |
package uk.co.appsbystudio.geoshare.friends.manager
interface FriendsManagerInteractor {
interface OnFirebaseRequestFinishedListener{
fun friendAdded(key: String?, name: String?)
fun friendRemoved(key: String?)
fun error(error: String)
}
fun getFriends(listener: OnFirebaseRequestFinishedListener)
fun removeListener()
} | mobile/src/main/java/uk/co/appsbystudio/geoshare/friends/manager/FriendsManagerInteractor.kt | 3769763966 |
/**
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.java.tree
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.openrewrite.java.JavaParser
import org.openrewrite.java.asClass
import org.openrewrite.java.firstMethodStatement
open class TernaryTest : JavaParser() {
val a: J.CompilationUnit by lazy {
parse("""
public class A {
int n;
public void test() {
String evenOrOdd = n % 2 == 0 ? "even" : "odd";
}
}
""")
}
private val evenOrOdd by lazy { a.firstMethodStatement() as J.VariableDecls }
private val ternary by lazy { evenOrOdd.vars[0].initializer as J.Ternary }
@Test
fun ternary() {
assertEquals("java.lang.String", ternary.type.asClass()?.fullyQualifiedName)
assertTrue(ternary.condition is J.Binary)
assertTrue(ternary.truePart is J.Literal)
assertTrue(ternary.falsePart is J.Literal)
}
@Test
fun format() {
assertEquals("""n % 2 == 0 ? "even" : "odd"""", ternary.printTrimmed())
}
} | rewrite-java/src/test/kotlin/org/openrewrite/java/tree/TernaryTest.kt | 732082310 |
/**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.core.model
import android.os.Parcel
import android.os.Parcelable
import org.apache.commons.lang3.StringUtils
/**
* Bus route entity
*
* @author Carl-Philipp Harmant
* @version 1
*/
data class BusRoute(val id: String, val name: String) : Parcelable {
companion object {
@JvmField
val CREATOR: Parcelable.Creator<BusRoute> = object : Parcelable.Creator<BusRoute> {
override fun createFromParcel(source: Parcel): BusRoute {
return BusRoute(source)
}
override fun newArray(size: Int): Array<BusRoute?> {
return arrayOfNulls(size)
}
}
}
private constructor(source: Parcel) : this(
id = source.readString() ?: StringUtils.EMPTY,
name = source.readString() ?: StringUtils.EMPTY
)
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(id)
dest.writeString(name)
}
}
| android-app/src/main/kotlin/fr/cph/chicago/core/model/BusRoute.kt | 3398957637 |
package com.github.bassaer.chatmessageview.view
import android.content.Context
import android.graphics.BitmapFactory
import android.view.View
import android.widget.TextView
import androidx.test.core.app.ApplicationProvider
import com.github.bassaer.chatmessageview.R
import com.github.bassaer.chatmessageview.model.Attribute
import com.github.bassaer.chatmessageview.model.ChatUser
import com.github.bassaer.chatmessageview.model.Message
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
/**
* MessageAdapter Unit Test
* Created by nakayama on 2018/01/03.
*/
@RunWith(RobolectricTestRunner::class)
internal class MessageAdapterTest {
private lateinit var messageAdapter: MessageAdapter
private lateinit var messageList: ArrayList<Any>
private lateinit var context: Context
@Before
fun setUp() {
context = ApplicationProvider.getApplicationContext()
messageList = ArrayList()
val senderIcon = BitmapFactory.decodeResource(context.resources, R.drawable.ic_account_circle)
val receiverIcon = BitmapFactory.decodeResource(context.resources, R.drawable.ic_action_user)
val sender = ChatUser(0, "User1", senderIcon)
val receiver = ChatUser(1, "User2", receiverIcon)
val message1 = Message.Builder()
.setRight(true)
.setText("message1")
.setUser(sender)
.build()
val message2 = Message.Builder()
.setRight(false)
.setText("message2")
.setUser(receiver)
.build()
messageList.add(message1.dateSeparateText)
messageList.add(message1)
messageList.add(message2)
val attribute = Attribute(context, null)
messageAdapter = MessageAdapter(context, 0, messageList, attribute)
}
@Test
fun getView() {
val messageArray: Array<View?> = arrayOfNulls(messageList.size)
for (i in 0 until messageList.size) {
messageArray[i] = messageAdapter.getView(i, null, null)
}
// Date label
val dateLabel = messageArray[0]?.findViewById<TextView>(R.id.dateLabelText)
var expectingText: String? = messageList[0] as String
assertEquals(expectingText, dateLabel?.text)
// Check Messages
for (i in 1 until messageArray.size) {
val messageText = messageArray[i]?.findViewById<TextView>(R.id.message_text)
expectingText = (messageList[i] as Message).text
assertEquals(expectingText, messageText?.text)
}
}
} | chatmessageview/src/test/kotlin/com/github/bassaer/chatmessageview/view/MessageAdapterTest.kt | 1634834865 |
package net.pterodactylus.sone.web.page
import net.pterodactylus.sone.main.*
import net.pterodactylus.sone.test.*
import net.pterodactylus.util.web.*
import net.pterodactylus.util.web.Method.*
import org.hamcrest.MatcherAssert.*
import org.hamcrest.Matchers.*
import org.junit.*
import org.mockito.Mockito.*
import java.io.*
import java.nio.charset.StandardCharsets.*
class FreenetTemplatePageTest {
private val templateRenderer = deepMock<TemplateRenderer>()
private val loaders = mock<Loaders>()
private val page = TestPage(templateRenderer, loaders)
@Test
fun `path is exposed correctly`() {
assertThat(page.path, equalTo("/test/path"))
}
@Test
fun `getPageTitle() default implementation returns empty string`() {
assertThat(page.getPageTitle(mock()), equalTo(""))
}
@Test
fun `isPrefixPage() default implementation returns false`() {
assertThat(page.isPrefixPage, equalTo(false))
}
@Test
fun `getStylesheets() default implementation returns empty collection`() {
assertThat(page.styleSheets, empty())
}
@Test
fun `getShortcutIcon() default implementation returns null`() {
assertThat(page.shortcutIcon, nullValue())
}
@Test
fun `getRedirectTarget() default implementation returns null`() {
assertThat(page.getRedirectTarget(mock()), nullValue())
}
@Test
fun `getAdditionalLinkNodes() default implementation returns empty collection`() {
assertThat(page.getAdditionalLinkNodes(mock()), empty())
}
@Test
fun `isFullAccessOnly() default implementation returns false`() {
assertThat(page.isFullAccessOnly, equalTo(false))
}
@Test
fun `isLinkExcepted() default implementation returns false`() {
assertThat(page.isLinkExcepted(mock()), equalTo(false))
}
@Test
fun `isEnabled() returns true if full access only is false`() {
assertThat(page.isEnabled(mock()), equalTo(true))
}
@Test
fun `isEnabled() returns false if full access only is true`() {
val page = object : TestPage(templateRenderer, loaders) {
override val isFullAccessOnly = true
}
assertThat(page.isEnabled(mock()), equalTo(false))
}
@Test
fun `page with redirect target throws redirect exception on handleRequest`() {
val page = object : TestPage(templateRenderer, loaders) {
override fun getRedirectTarget(request: FreenetRequest) = "foo"
}
val request = mock<FreenetRequest>()
val response = mock<Response>()
val pageResponse = page.handleRequest(request, response)
assertThat(pageResponse.statusCode, anyOf(equalTo(302), equalTo(307)))
assertThat(pageResponse.headers, contains(hasHeader("location", "foo")))
}
@Test
fun `page with full access only returns unauthorized on handleRequest with non-full access request`() {
val page = object : TestPage(templateRenderer, loaders) {
override val isFullAccessOnly = true
}
val request = deepMock<FreenetRequest>()
val response = Response(null)
val pageResponse = page.handleRequest(request, response)
assertThat(pageResponse.statusCode, equalTo(401))
}
@Test
fun `page redirects on POST without form password`() {
val request = deepMock<FreenetRequest>().apply {
whenever(httpRequest.getPartAsStringFailsafe(any(), anyInt())).thenReturn("")
whenever(method).thenReturn(POST)
}
val response = Response(null)
val pageResponse = page.handleRequest(request, response)
assertThat(pageResponse.statusCode, anyOf(equalTo(302), equalTo(307)))
assertThat(pageResponse.headers, contains(hasHeader("location", "invalid-form-password")))
}
@Test
fun `page redirects on POST with invalid password`() {
val request = deepMock<FreenetRequest>().apply {
whenever(httpRequest.getPartAsStringFailsafe(any(), anyInt())).thenReturn("invalid")
whenever(method).thenReturn(POST)
}
val response = Response(null)
val pageResponse = page.handleRequest(request, response)
assertThat(pageResponse.statusCode, anyOf(equalTo(302), equalTo(307)))
assertThat(pageResponse.headers, contains(hasHeader("location", "invalid-form-password")))
}
@Test
@Dirty
fun `freenet template page creates page with correct title`() {
val page = object : TestPage(templateRenderer, loaders) {
override fun getPageTitle(request: FreenetRequest) = "page title"
}
val request = deepMock<FreenetRequest>()
val pageMakerInteractionFactory = deepMock<PageMakerInteractionFactory>()
whenever(pageMakerInteractionFactory.createPageMaker(request.toadletContext, "page title").renderPage()).thenReturn("<page>")
setField(page, "pageMakerInteractionFactory", pageMakerInteractionFactory)
val response = page.handleRequest(request, Response(ByteArrayOutputStream()))
assertThat(response.statusCode, equalTo(200))
assertThat((response.content as ByteArrayOutputStream).toString(UTF_8.name()), equalTo("<page>"))
}
@Test
fun `template from annotation is loaded`() {
verify(loaders).loadTemplate("template-path")
}
@TemplatePath("template-path")
@ToadletPath("/test/path")
private open class TestPage(templateRenderer: TemplateRenderer, loaders: Loaders) : FreenetTemplatePage(templateRenderer, loaders, "invalid-form-password")
}
| src/test/kotlin/net/pterodactylus/sone/web/page/FreenetTemplatePageTest.kt | 1155801642 |
package com.cout970.magneticraft.systems.worldgen
import com.cout970.magneticraft.systems.config.Config
import net.minecraft.world.World
import net.minecraft.world.chunk.IChunkProvider
import net.minecraft.world.gen.IChunkGenerator
import net.minecraftforge.fml.common.IWorldGenerator
import java.util.*
import com.cout970.magneticraft.features.decoration.Blocks as DecorationBlocks
import com.cout970.magneticraft.features.ores.Blocks as OreBlocks
/**
* Created by cout970 on 15/05/2016.
*/
object WorldGenerator : IWorldGenerator {
val generators = mutableListOf<IWorldGenerator>()
fun init() {
generators.clear()
generators.add(OreGenerator(OreBlocks.OreType.COPPER.getBlockState(OreBlocks.ores), Config.copperOre))
generators.add(OreGenerator(OreBlocks.OreType.LEAD.getBlockState(OreBlocks.ores), Config.leadOre))
generators.add(OreGenerator(OreBlocks.OreType.TUNGSTEN.getBlockState(OreBlocks.ores), Config.tungstenOre))
generators.add(OreGenerator(OreBlocks.OreType.PYRITE.getBlockState(OreBlocks.ores), Config.pyriteOre))
generators.add(GaussianOreGenerator(DecorationBlocks.LimestoneKind.NORMAL.getBlockState(DecorationBlocks.limestone), Config.limestone))
generators.add(OilSourceGenerator(OreBlocks.OilAmount.FULL_100.getBlockState(OreBlocks.oilSource), Config.oil))
}
override fun generate(random: Random, chunkX: Int, chunkZ: Int, world: World?, chunkGenerator: IChunkGenerator, chunkProvider: IChunkProvider) {
generators.forEach {
it.generate(random, chunkX, chunkZ, world, chunkGenerator, chunkProvider)
}
}
} | src/main/kotlin/com/cout970/magneticraft/systems/worldgen/WorldGenerator.kt | 953000980 |
package com.github.bumblebee.command.currency.service
import com.github.bumblebee.command.currency.config.CurrencyChartConfig
import com.github.bumblebee.command.currency.domain.SupportedCurrency
import com.github.bumblebee.command.currency.domain.SupportedCurrency.*
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.runners.MockitoJUnitRunner
import java.time.LocalDate
@RunWith(MockitoJUnitRunner::class)
class ChartArgumentParserTest {
@Mock
private lateinit var config: CurrencyChartConfig
@InjectMocks
private lateinit var parser: ChartArgumentParser
@Before
fun init() {
`when`(config.dateFormat).thenReturn("dd.MM.yyyy")
`when`(config.defaultCurrencies).thenReturn(listOf(USD.name, EUR.name))
}
// Ranges
@Test
fun `should parse two ranges`() {
testRange("01.02.2015 05.04.2015", LocalDate.of(2015, 2, 1), LocalDate.of(2015, 4, 5))
}
@Test
fun `should parse single range`() {
testRange("01.02.2015", LocalDate.of(2015, 2, 1), LocalDate.now())
}
@Test
fun `should parse two ranges with mess`() {
testRange("asdasd 01.02.2015 MESS 05.04.2015 44 zero", LocalDate.of(2015, 2, 1), LocalDate.of(2015, 4, 5))
}
@Test
fun `should parse two reversed ranges with mess`() {
testRange("asdasd MESS 05.04.2015 44 zero 01.02.2015 2014", LocalDate.of(2015, 2, 1), LocalDate.of(2015, 4, 5))
}
@Test
fun `should parse single range with mess`() {
testRange("xyz 42 01.02.2015 bamboo", LocalDate.of(2015, 2, 1), LocalDate.now())
}
@Test
fun `should parse single range with mess and year defined`() {
testRange("xyz 42 01.02.2015 bamboo 2014", LocalDate.of(2015, 2, 1), LocalDate.now())
}
@Test
fun `should parse to defaults`() {
testRange("xyz 42 01.02 bamboo", currentMonthStart(), LocalDate.now())
}
@Test
fun `should parse single future date to defaults`() {
testRange("xyz 42 01.02.2050 bamboo", currentMonthStart(), LocalDate.now())
}
@Test
fun `should parse future dates to current date`() {
testRange("xyz 42 04.06.2014 01.02.2050 bamboo", LocalDate.of(2014, 6, 4), LocalDate.now())
}
@Test
fun `should parse empty to defaults`() {
testRange(null, currentMonthStart(), LocalDate.now())
testRange("", currentMonthStart(), LocalDate.now())
}
@Test
fun `should parse single year `() {
testRange("2014", LocalDate.of(2014, 1, 1), LocalDate.of(2014, 12, 31))
}
@Test
fun `should parse single year with mess`() {
testRange("abc 42 2014 22 ", LocalDate.of(2014, 1, 1), LocalDate.of(2014, 12, 31))
}
@Test
fun `should parse multiple years `() {
testRange("2014 2016", LocalDate.of(2014, 1, 1), LocalDate.of(2016, 12, 31))
}
@Test
fun `should parse multiple years with mess`() {
testRange("rub sa 2014 usd 2016 2017 2001 22", LocalDate.of(2014, 1, 1), LocalDate.of(2016, 12, 31))
}
@Test
fun `should parse concrete dates over years`() {
testRange("2012 2013 01.02.2015 05.04.2015", LocalDate.of(2015, 2, 1), LocalDate.of(2015, 4, 5))
}
@Test
fun `should parse to defaults not supported year`() {
testRange("abc 42 1990 22 ", currentMonthStart(), LocalDate.now())
}
private fun testRange(argument: String?, expectedFrom: LocalDate, expectedTo: LocalDate) {
//when
val (from, to) = parser.getRange(argument)
// then
assertEquals(expectedFrom, from)
assertEquals(expectedTo, to)
}
private fun currentMonthStart(): LocalDate {
return LocalDate.of(LocalDate.now().year, LocalDate.now().month, 1)
}
// Currencies
@Test
fun `should parse single currency`() {
testCurrencies("usd", USD)
}
@Test
fun `should parse multiple currencies`() {
testCurrencies("EUR usd RuB", EUR, USD, RUB)
}
@Test
fun `should parse multiple currencies with mess`() {
testCurrencies("saz 2005 EUR 42 usd bb 01.02.2016 RuB z", EUR, USD, RUB)
}
@Test
fun `should parse to default currencies`() {
testCurrencies(" acb 42", USD, EUR)
testCurrencies("", USD, EUR)
testCurrencies(null, USD, EUR)
}
private fun testCurrencies(argument: String?, vararg expectedCurrencies: SupportedCurrency) {
val currencies = parser.getCurrencies(argument)
assertEquals(expectedCurrencies.size.toLong(), currencies.size.toLong())
for (i in currencies.indices) {
assertEquals(expectedCurrencies[i].name, currencies[i])
}
}
} | telegram-bot-bumblebee-core/src/test/java/com/github/bumblebee/command/currency/service/ChartArgumentParserTest.kt | 794245471 |
package com.github.ysl3000.bukkit.pathfinding.goals
import com.github.ysl3000.bukkit.pathfinding.entity.Insentient
import com.github.ysl3000.bukkit.pathfinding.pathfinding.PathfinderGoal
import org.bukkit.Material
import org.bukkit.entity.Creature
import org.bukkit.entity.Entity
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
import java.util.*
/**
* Created by 2008Choco
*/
class PathfinderGoalGimmiCookie(private val pathfinderGoalEntity: Insentient, private val creature: Creature) : PathfinderGoal {
private var isGenerous = true
private var hasGivenCookie = false
private var nearbyEntities: List<Entity>? = null
private var nearestPlayer: Player? = null
override fun shouldExecute(): Boolean {
if (!isGenerous) {
return false
}
val nearbyEntities = creature.getNearbyEntities(5.0, 5.0, 5.0)
if (nearbyEntities.isEmpty()) {
return false
}
this.nearbyEntities = nearbyEntities
return nearbyEntities.stream().anyMatch { Player::class.java.isInstance(it) }
}
override fun shouldTerminate(): Boolean {
return !hasGivenCookie
}
override fun init() {
this.nearestPlayer = getNearestPlayerFrom(nearbyEntities!!).orElse(null)
this.nearbyEntities = null
this.creature.equipment?.setItemInMainHand(COOKIE)
this.creature.target = nearestPlayer
this.pathfinderGoalEntity.getNavigation().moveTo(nearestPlayer!!)
}
override fun execute() {
this.pathfinderGoalEntity.jump()
if (creature.location.distanceSquared(nearestPlayer!!.location) <= 1) {
this.creature.world.dropItem(nearestPlayer!!.location, COOKIE)
this.creature.equipment?.setItemInMainHand(null)
this.isGenerous = false
this.hasGivenCookie = true
}
}
override fun reset() {
this.nearestPlayer = null
this.hasGivenCookie = false
}
private fun getNearestPlayerFrom(entities: List<Entity>): Optional<Player> {
return entities.stream()
.filter { Player::class.java.isInstance(it) }
.map<Player> { Player::class.java.cast(it) }
.min(Comparator
.comparingDouble { p -> creature.location.distanceSquared(p.location) })
}
companion object {
private val COOKIE = ItemStack(Material.COOKIE)
}
} | PathfinderAPI/src/main/java/com/github/ysl3000/bukkit/pathfinding/goals/PathfinderGoalGimmiCookie.kt | 2680624531 |
package reactivecircus.flowbinding.recyclerview
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.test.filters.LargeTest
import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import reactivecircus.blueprint.testing.action.swipeDownOnView
import reactivecircus.blueprint.testing.action.swipeLeftOnView
import reactivecircus.blueprint.testing.action.swipeRightOnView
import reactivecircus.blueprint.testing.action.swipeUpOnView
import reactivecircus.flowbinding.recyclerview.fixtures.RecyclerViewFragment
import reactivecircus.flowbinding.recyclerview.test.R
import reactivecircus.flowbinding.testing.FlowRecorder
import reactivecircus.flowbinding.testing.launchTest
import reactivecircus.flowbinding.testing.recordWith
@LargeTest
class RecyclerViewScrollStateChangedFlowTest {
@Test
fun recyclerViewScrollStateChanges_vertical() {
launchTest<RecyclerViewFragment> {
val recorder = FlowRecorder<Int>(testScope)
val recyclerView = getViewById<RecyclerView>(R.id.recyclerView).apply {
runOnUiThread {
adapter = TestAdapter(50)
}
}
getInstrumentation().waitForIdleSync()
recyclerView.scrollStateChanges().recordWith(recorder)
recorder.assertNoMoreValues()
swipeUpOnView(R.id.recyclerView)
assertThat(recorder.takeValue())
.isEqualTo(RecyclerView.SCROLL_STATE_DRAGGING)
assertThat(recorder.takeValue())
.isEqualTo(RecyclerView.SCROLL_STATE_SETTLING)
assertThat(recorder.takeValue())
.isEqualTo(RecyclerView.SCROLL_STATE_IDLE)
recorder.assertNoMoreValues()
cancelTestScope()
recorder.clearValues()
swipeDownOnView(R.id.recyclerView)
recorder.assertNoMoreValues()
}
}
@Test
fun recyclerViewScrollStateChanges_horizontal() {
launchTest<RecyclerViewFragment> {
val recorder = FlowRecorder<Int>(testScope)
val recyclerView = getViewById<RecyclerView>(R.id.recyclerView).apply {
runOnUiThread {
adapter = TestAdapter(20)
(layoutManager as LinearLayoutManager).orientation = LinearLayoutManager.HORIZONTAL
}
}
getInstrumentation().waitForIdleSync()
recyclerView.scrollStateChanges().recordWith(recorder)
recorder.assertNoMoreValues()
swipeLeftOnView(R.id.recyclerView)
assertThat(recorder.takeValue())
.isEqualTo(RecyclerView.SCROLL_STATE_DRAGGING)
assertThat(recorder.takeValue())
.isEqualTo(RecyclerView.SCROLL_STATE_SETTLING)
assertThat(recorder.takeValue())
.isEqualTo(RecyclerView.SCROLL_STATE_IDLE)
recorder.assertNoMoreValues()
cancelTestScope()
recorder.clearValues()
swipeRightOnView(R.id.recyclerView)
recorder.assertNoMoreValues()
}
}
}
| flowbinding-recyclerview/src/androidTest/java/reactivecircus/flowbinding/recyclerview/RecyclerViewScrollStateChangedFlowTest.kt | 2667293795 |
package br.com.leandroferreira.wizard_forms.contract
import java.io.Serializable
open class WizardStateHolder<K>(var stateDto : K) : Serializable {
@Transient
private var subscriberList: MutableList<OnStateChangeListener<K>> = mutableListOf()
fun notifyStateChange() = subscriberList.forEach { listener -> listener.getState(stateDto) }
fun subscribeForStateChange(listener: OnStateChangeListener<K>) = subscriberList.add(listener)
private fun readObject(input: java.io.ObjectInputStream) {
input.defaultReadObject()
subscriberList = mutableListOf()
}
}
| wizard_forms/src/main/java/br/com/leandroferreira/wizard_forms/contract/WizardStateHolder.kt | 4213625273 |
package de.ph1b.audiobook.playback.di
import android.content.Context
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.MediaSessionCompat
import com.google.android.exoplayer2.C
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.audio.AudioAttributes
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory
import com.google.android.exoplayer2.source.MediaSourceFactory
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.upstream.DefaultDataSource
import com.squareup.anvil.annotations.ContributesTo
import dagger.Module
import dagger.Provides
import de.ph1b.audiobook.playback.player.OnlyAudioRenderersFactory
import de.ph1b.audiobook.playback.session.PlaybackService
@Module
@ContributesTo(PlaybackScope::class)
object PlaybackServiceModule {
@Provides
@PlaybackScope
fun mediaSession(service: PlaybackService): MediaSessionCompat {
return MediaSessionCompat(service, PlaybackService::class.java.simpleName)
}
@Provides
@PlaybackScope
fun mediaController(context: Context, mediaSession: MediaSessionCompat): MediaControllerCompat {
return MediaControllerCompat(context, mediaSession)
}
@Provides
@PlaybackScope
fun mediaSourceFactory(context: Context): MediaSourceFactory {
val dataSourceFactory = DefaultDataSource.Factory(context)
val extractorsFactory = DefaultExtractorsFactory()
.setConstantBitrateSeekingEnabled(true)
return ProgressiveMediaSource.Factory(dataSourceFactory, extractorsFactory)
}
@Provides
@PlaybackScope
fun exoPlayer(
context: Context,
onlyAudioRenderersFactory: OnlyAudioRenderersFactory,
mediaSourceFactory: MediaSourceFactory,
): ExoPlayer {
val audioAttributes = AudioAttributes.Builder()
.setContentType(C.CONTENT_TYPE_SPEECH)
.setUsage(C.USAGE_MEDIA)
.build()
return ExoPlayer.Builder(context, onlyAudioRenderersFactory, mediaSourceFactory)
.setAudioAttributes(audioAttributes, true)
.build()
}
}
| playback/src/main/kotlin/de/ph1b/audiobook/playback/di/PlaybackServiceModule.kt | 3885458323 |
/*
* Copyright (C) 2021 The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dogglers.data
import com.example.dogglers.R
import com.example.dogglers.model.Dog
/**
* An object to generate a static list of dogs
*/
object DataSource {
val dogs: List<Dog> = listOf(
Dog(
R.drawable.tzeitel,
"Tzeitel",
"7",
"sunbathing"
),
Dog(
R.drawable.leroy,
"Leroy",
"4",
"sleeping in dangerous places"
),
Dog(
R.drawable.frankie,
"Frankie",
"2",
"stealing socks"
),
Dog(
R.drawable.nox,
"Nox",
"8",
"meeting new animals"
),
Dog(
R.drawable.faye,
"Faye",
"8",
"Digging in the garden"
),
Dog(
R.drawable.bella,
"Bella",
"14",
"Chasing sea foam"
)
)
}
| app/src/main/java/com/example/dogglers/data/DataSource.kt | 2633323008 |
package net.xpece.android.preference
import android.content.SharedPreferences
import org.threeten.bp.LocalTime
class LocalTimePreferenceDelegate(
prefs: SharedPreferences, key: String, default: LocalTime? = null) :
PrintablePreferenceDelegate<LocalTime>(prefs, key, default) {
override fun fromString(input: String) = LocalTime.parse(input)!!
}
| commons/src/main/java/net/xpece/android/preference/LocalTimePreferenceDelegate.kt | 1723491744 |
/*
* Copyright 2019 Armory, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.echo.telemetry
import retrofit.client.Response
import retrofit.http.Body
import retrofit.http.POST
import retrofit.mime.TypedInput
interface TelemetryService {
@POST("/log")
fun log(@Body body: TypedInput): Response
}
| echo-telemetry/src/main/java/com/netflix/spinnaker/echo/telemetry/TelemetryService.kt | 108919426 |
/*
* 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.data.log
import android.content.res.Resources
import android.util.Log
import androidx.annotation.StringRes
import com.google.android.horologist.media3.logging.ErrorReporter
public class Logging(
private val res: Resources
) : ErrorReporter {
override fun showMessage(@StringRes message: Int) {
val messageString = res.getString(message)
Log.i("ErrorReporter", messageString)
}
private val ErrorReporter.Level.loggingLevel: Int
get() = when (this) {
ErrorReporter.Level.Error -> Log.ERROR
ErrorReporter.Level.Info -> Log.INFO
ErrorReporter.Level.Debug -> Log.DEBUG
}
override fun logMessage(message: String, category: ErrorReporter.Category, level: ErrorReporter.Level) {
Log.println(level.loggingLevel, category.name, message)
}
}
| media-sample/src/main/java/com/google/android/horologist/mediasample/data/log/Logging.kt | 1868352545 |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.spectralogic.ds3autogen.go.models.response
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableSet
data class Response(
val name: String,
val payloadStruct: String, //The struct definition for the response payload
val expectedCodes: String,
val parseResponseMethod: String, //Contains the Go code for the parse method if one is needed, else empty
val responseCodes: ImmutableList<ResponseCode>,
val imports: ImmutableSet<String>)
| ds3-autogen-go/src/main/kotlin/com/spectralogic/ds3autogen/go/models/response/Response.kt | 746942155 |
/*
* 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.internal.statistic.eventLog
import com.intellij.util.containers.ContainerUtil
import java.util.*
open class LogEvent(val session: String, val bucket: String,
recorderId: String,
recorderVersion: String,
type: String) {
val time = System.currentTimeMillis()
val recorder: LogEventRecorder = LogEventRecorder(removeTabsOrSpaces(recorderId), recorderVersion)
val action: LogEventAction = LogEventAction(removeTabsOrSpaces(type))
fun shouldMerge(next: LogEvent): Boolean {
if (session != next.session) return false
if (bucket != next.bucket) return false
if (recorder.id != next.recorder.id) return false
if (recorder.version != next.recorder.version) return false
if (action.id != next.action.id) return false
if (action.data != next.action.data) return false
return true
}
private fun removeTabsOrSpaces(str : String) : String {
return str.replace(" ", "_").replace("\t", "_")
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEvent
if (session != other.session) return false
if (bucket != other.bucket) return false
if (time != other.time) return false
if (recorder != other.recorder) return false
if (action != other.action) return false
return true
}
override fun hashCode(): Int {
var result = session.hashCode()
result = 31 * result + bucket.hashCode()
result = 31 * result + time.hashCode()
result = 31 * result + recorder.hashCode()
result = 31 * result + action.hashCode()
return result
}
}
class LogEventRecorder(val id: String, val version: String) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEventRecorder
if (id != other.id) return false
if (version != other.version) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + version.hashCode()
return result
}
}
class LogEventAction(val id: String) {
var data: MutableMap<String, Any> = Collections.emptyMap()
fun addData(key: String, value: Any) {
if (data.isEmpty()) {
data = ContainerUtil.newHashMap()
}
data.put(key, value)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEventAction
if (id != other.id) return false
if (data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + (data?.hashCode() ?: 0)
return result
}
} | platform/platform-impl/src/com/intellij/internal/statistic/eventLog/LogEvents.kt | 3183761238 |
package org.koin.core
import org.junit.Assert.assertEquals
import org.junit.Test
import org.koin.Simple
import org.koin.dsl.koinApplication
import org.koin.dsl.module
import java.util.concurrent.Callable
import java.util.concurrent.Executors
class SingleConcurrencyTest {
@Test
fun `never creates two instances from different threads`() {
val executor = Executors.newFixedThreadPool(8)
// This test is repeated many times, because it only fails a very small % of times
repeat(3000) { repetition ->
val app = koinApplication {
modules(module {
single { createComponent() }
})
}
val numberOfInstances = (1..50)
.map { executor.submit(Callable { app.koin.get<Simple.ComponentA>() }) }
.map { it.get() }
.distinctBy { it.toString() }
.count()
assertEquals(
"More than one instance created concurrently for a `single` definition. Failed in repetition $repetition of the test.",
1,
numberOfInstances,
)
}
}
private fun createComponent(): Simple.ComponentA {
Thread.sleep(1) // Simulates a more expensive instance creation
return Simple.ComponentA()
}
} | koin-projects/koin-core/src/test/java/org/koin/core/SingleConcurrencyTest.kt | 2264849140 |
/*
* Copyright 2017-2020 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.koin.androidx.viewmodel.scope
import android.os.Bundle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelStore
import androidx.savedstate.SavedStateRegistryOwner
import org.koin.androidx.viewmodel.ViewModelOwnerDefinition
import org.koin.androidx.viewmodel.ViewModelParameter
import org.koin.androidx.viewmodel.createViewModelProvider
import org.koin.androidx.viewmodel.resolveInstance
import org.koin.core.parameter.ParametersDefinition
import org.koin.core.qualifier.Qualifier
import org.koin.core.scope.Scope
import kotlin.reflect.KClass
/**
* Scope extensions to help for ViewModel
*
* @author Arnaud Giuliani
*/
typealias SavedStateRegistryOwnerDefinition = () -> SavedStateRegistryOwner
typealias ViewModelStoreDefinition = () -> ViewModelStore
fun emptyState(): BundleDefinition = { Bundle() }
typealias BundleDefinition = () -> Bundle
inline fun <reified T : ViewModel> Scope.viewModel(
qualifier: Qualifier? = null,
noinline state: BundleDefinition? = null,
noinline owner: ViewModelOwnerDefinition,
noinline parameters: ParametersDefinition? = null
): Lazy<T> {
return lazy(LazyThreadSafetyMode.NONE) {
getViewModel<T>(qualifier, state, owner, parameters)
}
}
inline fun <reified T : ViewModel> Scope.getViewModel(
qualifier: Qualifier? = null,
noinline state: BundleDefinition? = null,
noinline owner: ViewModelOwnerDefinition,
noinline parameters: ParametersDefinition? = null
): T {
return getViewModel(qualifier, state, owner, T::class, parameters)
}
fun <T : ViewModel> Scope.getViewModel(
qualifier: Qualifier? = null,
state: BundleDefinition? = null,
owner: ViewModelOwnerDefinition,
clazz: KClass<T>,
parameters: ParametersDefinition? = null
): T {
val ownerDef = owner()
return getViewModel(
ViewModelParameter(
clazz,
qualifier,
parameters,
state?.invoke() ?: Bundle(),
ownerDef.store,
ownerDef.stateRegistry
)
)
}
fun <T : ViewModel> Scope.getViewModel(viewModelParameters: ViewModelParameter<T>): T {
val viewModelProvider = createViewModelProvider(viewModelParameters)
return viewModelProvider.resolveInstance(viewModelParameters)
} | koin-projects/koin-androidx-viewmodel/src/main/java/org/koin/androidx/viewmodel/scope/ScopeExt.kt | 4067926228 |
/*
* Copyright 2019 Andrey Tolpeev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.vase4kin.teamcityapp.login.tracker
import com.github.vase4kin.teamcityapp.account.create.tracker.CreateAccountTracker
/**
* Login tracking class
*/
interface LoginTracker : CreateAccountTracker {
companion object {
/**
* First login screen name
*/
const val SCREEN_NAME = "screen_first_login"
const val EVENT_USER_CLICKS_ON_TRY_IT_OUT = "event_user_clicks_on_try_it_out"
const val EVENT_USER_TRIES_TRY_IT_OUT = "event_user_tries_try_it_out"
const val EVENT_USER_DECLINES_TRY_IT_OUT = "event_user_declines_try_it_out"
}
fun trackUserClicksOnTryItOut()
fun trackUserTriesTryItOut()
fun trackUserDeclinesTryingTryItOut()
}
| app/src/main/java/com/github/vase4kin/teamcityapp/login/tracker/LoginTracker.kt | 3476599533 |
package io.noties.markwon.app.sample.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import io.noties.markwon.app.App
import io.noties.markwon.app.R
import io.noties.markwon.app.sample.Sample
import io.noties.markwon.app.utils.hidden
import io.noties.markwon.app.utils.readCode
import io.noties.markwon.syntax.Prism4jSyntaxHighlight
import io.noties.markwon.syntax.Prism4jThemeDefault
import io.noties.prism4j.Prism4j
import io.noties.prism4j.annotations.PrismBundle
@PrismBundle(include = ["java", "kotlin"], grammarLocatorClassName = ".GrammarLocatorSourceCode")
class SampleCodeFragment : Fragment() {
private lateinit var progressBar: View
private lateinit var textView: TextView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_sample_code, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
progressBar = view.findViewById(R.id.progress_bar)
textView = view.findViewById(R.id.text_view)
load()
}
private fun load() {
App.executorService.submit {
val code = sample.readCode(requireContext())
val prism = Prism4j(GrammarLocatorSourceCode())
val highlight = Prism4jSyntaxHighlight.create(prism, Prism4jThemeDefault.create(0))
val language = when (code.language) {
Sample.Language.KOTLIN -> "kotlin"
Sample.Language.JAVA -> "java"
}
val text = highlight.highlight(language, code.sourceCode)
textView.post {
//attached
if (context != null) {
progressBar.hidden = true
textView.text = text
}
}
}
}
private val sample: Sample by lazy(LazyThreadSafetyMode.NONE) {
val temp: Sample = (arguments!!.getParcelable(ARG_SAMPLE))!!
temp
}
companion object {
private const val ARG_SAMPLE = "arg.Sample"
fun init(sample: Sample): SampleCodeFragment {
return SampleCodeFragment().apply {
arguments = Bundle().apply {
putParcelable(ARG_SAMPLE, sample)
}
}
}
}
} | app-sample/src/main/java/io/noties/markwon/app/sample/ui/SampleCodeFragment.kt | 1580808947 |
package iii_properties
import junit.framework.Assert
import org.junit.Test as test
class _19_Lazy_Property {
@test fun testLazy() {
var initialized = false
val lazyProperty = LazyProperty({ initialized = true; 42 })
Assert.assertFalse("Property shouldn't be initialized before access", initialized)
val result: Int = lazyProperty.lazy
Assert.assertTrue("Property should be initialized after access", initialized)
Assert.assertEquals(42, result)
}
@test fun initializedOnce() {
var initialized = 0
val lazyProperty = LazyProperty( { initialized++; 42 })
lazyProperty.lazy
lazyProperty.lazy
Assert.assertEquals("Lazy property should be initialized once", 1, initialized)
}
}
| test/iii_properties/_19_Lazy_Property.kt | 4223193982 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.highlight
import org.rust.lang.RsTestBase
class RsRainbowVisitorTest : RsTestBase() {
fun checkRainbow(code: String, isRainbowOn: Boolean = true, withColor: Boolean = false) {
myFixture.testRainbow(
"main.rs",
code,
isRainbowOn, withColor)
}
fun testPathBinding() = checkRainbow("""
fn main() {
let mut <rainbow>test</rainbow> = "";
<rainbow>test</rainbow> = "";
}
""")
fun testFunctionBinding() = checkRainbow("""
fn foo() {}
fn main() {
foo();
}
""", true)
fun testDifferentColor() = checkRainbow("""
fn main() {
let mut <rainbow color='ff000002'>test</rainbow> = "";
<rainbow color='ff000002'>test</rainbow> = "";
let mut <rainbow color='ff000003'>test</rainbow> = "";
<rainbow color='ff000003'>test</rainbow> = "";
}
""", withColor = true)
fun testComplexDifferentColor() = checkRainbow("""
fn foo(<rainbow color='ff000002'>test</rainbow>: i32) {
let <rainbow color='ff000004'>x</rainbow> = <rainbow color='ff000002'>test</rainbow> + <rainbow color='ff000002'>test</rainbow>;
let <rainbow color='ff000001'>y</rainbow> = {
let <rainbow color='ff000003'>test</rainbow> = <rainbow color='ff000004'>x</rainbow>;
};
<rainbow color='ff000002'>test</rainbow>
}
""", withColor = true)
}
| src/test/kotlin/org/rust/ide/highlight/RsRainbowVisitorTest.kt | 3257427271 |
package wu.seal.jsontokotlin.regression
import com.winterbe.expekt.should
import org.junit.Test
import wu.seal.jsontokotlin.KotlinCodeMaker
import wu.seal.jsontokotlin.test.TestConfig
class Issue334Test {
@Test
fun testDoubleFormatIssue() {
TestConfig.setToTestInitState()
val json="""
[
{
"key": 1.2
},
{
"key": 1
}
]
""".trimIndent()
val expectCode = """
class A : ArrayList<AItem>(){
data class AItem(
@SerializedName("key")
val key: Double = 0.0 // 1.2
)
}
""".trimIndent()
val resultCode = KotlinCodeMaker("A", json).makeKotlinData()
resultCode.should.be.equal(expectCode)
}
} | src/test/kotlin/wu/seal/jsontokotlin/regression/Issue334Test.kt | 1812779598 |
package com.airbnb.mvrx
import org.junit.Assert.assertEquals
import org.junit.Test
class ListExtensionsTest : BaseTest() {
@Test
fun testAppendNull() {
val list = listOf(1, 2, 3)
assertEquals(listOf(1, 2, 3), list.appendAt(null, 3))
}
@Test
fun testAppendAtEnd() {
val list = listOf(1, 2, 3)
assertEquals(listOf(1, 2, 3, 4), list.appendAt(listOf(4), 3))
}
@Test
fun testAppendPastEnd() {
val list = listOf(1, 2, 3)
assertEquals(listOf(1, 2, 3, 4), list.appendAt(listOf(4), 3))
}
@Test
fun testAppendInMiddle() {
val list = listOf(1, 2, 3)
assertEquals(listOf(1, 2, 4), list.appendAt(listOf(4), 2))
}
@Test
fun testAppendAtBeginning() {
val list = listOf(1, 2, 3)
assertEquals(listOf(4), list.appendAt(listOf(4), 0))
}
@Test
fun testAppendAtShorterList() {
val list = listOf(1)
assertEquals(listOf(1, 4), list.appendAt(listOf(4), 3))
}
@Test
fun testAppendSmallListInMiddleOfLongList() {
val list = listOf(1, 2, 3, 4, 5)
assertEquals(listOf(1, 4), list.appendAt(listOf(4), 1))
}
}
| mvrx-rxjava2/src/test/kotlin/com/airbnb/mvrx/ListExtensionsTest.kt | 2994688516 |
package org.http4k.format
import com.google.gson.JsonElement
import org.http4k.asByteBuffer
import org.http4k.asString
import org.http4k.core.Body
import org.http4k.core.ContentType.Companion.APPLICATION_XML
import org.http4k.lens.BiDiBodyLensSpec
import org.http4k.lens.BiDiLensSpec
import org.http4k.lens.ContentNegotiation
import org.http4k.lens.Meta
import org.http4k.lens.ParamMeta
import org.http4k.lens.httpBodyRoot
import org.json.XML
import org.w3c.dom.Document
import java.io.InputStream
import java.io.StringWriter
import java.nio.ByteBuffer
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.TransformerFactory
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stream.StreamResult
import kotlin.reflect.KClass
object Xml : AutoMarshallingXml() {
override fun Any.asXmlString(): String = throw UnsupportedOperationException("")
override fun <T : Any> asA(input: String, target: KClass<T>): T = Gson.asA(input.asXmlToJsonElement(), target)
override fun <T : Any> asA(input: InputStream, target: KClass<T>): T = Gson.asA(input.reader().readText().asXmlToJsonElement(), target)
fun String.asXmlToJsonElement(): JsonElement = Gson.parse(XML.toJSONObject(this, true).toString())
@JvmName("stringAsXmlToJsonElement")
fun asXmlToJsonElement(input: String): JsonElement = input.asXmlToJsonElement()
fun String.asXmlDocument(): Document =
DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.parse(byteInputStream())
fun Document.asXmlString(): String = StringWriter().let {
TransformerFactory.newInstance().newTransformer().transform(DOMSource(this), StreamResult(it))
it.toString()
}
fun <IN : Any> BiDiLensSpec<IN, String>.xml() = map({ it.asXmlDocument() }, { it.asXmlString() })
fun Body.Companion.xml(description: String? = null,
contentNegotiation: ContentNegotiation = ContentNegotiation.None): BiDiBodyLensSpec<Document> =
httpBodyRoot(listOf(Meta(true, "body", ParamMeta.ObjectParam, "body", description)), APPLICATION_XML, contentNegotiation)
.map(Body::payload) { Body(it) }
.map(ByteBuffer::asString, String::asByteBuffer).map({ it.asXmlDocument() }, { it.asXmlString() })
}
| http4k-format/xml/src/main/kotlin/org/http4k/format/Xml.kt | 3448820369 |
package com.wenhui.coroutines
import com.wenhui.coroutines.functions.ConsumeAction
import kotlinx.coroutines.experimental.CoroutineScope
import kotlinx.coroutines.experimental.withContext
internal abstract class BaseOperator<T, R>(private val dependedAction: Action<T>,
private val context: CoroutineContexts) : Action<R> {
override suspend fun runAsync(scope: CoroutineScope): R {
val t = dependedAction.runAsync(scope)
return withContext(context.context) { onRun(t) }
}
override fun run(): R {
val t = dependedAction.run()
return onRun(t)
}
protected abstract fun onRun(input: T): R
}
internal class Transformer<T, R>(dependedAction: Action<T>,
context: CoroutineContexts,
private val transform: Function1<T, R>) : BaseOperator<T, R>(dependedAction, context) {
override fun onRun(input: T): R = transform(input)
}
/**
* Consume the item T.
*
* NOTE: the name Consumer is taken, so User in this case is the Consumer
*/
internal class User<T>(dependedAction: Action<T>,
context: CoroutineContexts,
private val consume: ConsumeAction<T>) : BaseOperator<T, T>(dependedAction, context) {
override fun onRun(input: T): T {
consume(input)
return input
}
}
internal class Filter<T>(dependedAction: Action<T>,
context: CoroutineContexts,
private val filter: FilterAction<T>) : BaseOperator<T, T>(dependedAction, context) {
override fun onRun(input: T): T {
if (!filter(input)) discontinueExecution()
return input
}
}
| coroutines-adapter/src/main/kotlin/com/wenhui/coroutines/Operators.kt | 1127219155 |
/*
* Copyright 2012-2022 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 org.springframework.boot.docs.features.externalconfig.typesafeconfigurationproperties.conversion.durations.javabeanbinding
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.convert.DurationUnit
import java.time.Duration
import java.time.temporal.ChronoUnit
@ConfigurationProperties("my")
class MyProperties {
@DurationUnit(ChronoUnit.SECONDS)
var sessionTimeout = Duration.ofSeconds(30)
var readTimeout = Duration.ofMillis(1000)
} | spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/conversion/durations/javabeanbinding/MyProperties.kt | 1310562350 |
/*
* Copyright (C) 2019 microG Project Team
*
* 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.microg.gms.maps.mapbox.model
import android.graphics.Color
import android.graphics.PointF
import android.util.Log
import com.mapbox.mapboxsdk.plugins.annotation.Symbol
import com.mapbox.mapboxsdk.plugins.annotation.SymbolOptions
import com.mapbox.mapboxsdk.style.layers.Property.ICON_ANCHOR_TOP_LEFT
import com.mapbox.mapboxsdk.utils.ColorUtils
open class BitmapDescriptorImpl(private val id: String, private val size: FloatArray) {
open fun applyTo(options: SymbolOptions, anchor: FloatArray, dpiFactor: Float): SymbolOptions {
return options.withIconImage(id).withIconAnchor(ICON_ANCHOR_TOP_LEFT).withIconOffset(arrayOf(-anchor[0] * size[0] / dpiFactor, -anchor[1] * size[1] / dpiFactor))
}
open fun applyTo(symbol: Symbol, anchor: FloatArray, dpiFactor: Float) {
symbol.iconAnchor = ICON_ANCHOR_TOP_LEFT
symbol.iconOffset = PointF(-anchor[0] * size[0] / dpiFactor, -anchor[1] * size[1] / dpiFactor)
symbol.iconImage = id
}
}
class ColorBitmapDescriptorImpl(id: String, size: FloatArray, val hue: Float) : BitmapDescriptorImpl(id, size) {
override fun applyTo(options: SymbolOptions, anchor: FloatArray, dpiFactor: Float): SymbolOptions = super.applyTo(options, anchor, dpiFactor).withIconColor(ColorUtils.colorToRgbaString(Color.HSVToColor(floatArrayOf(hue, 1.0f, 0.5f))))
override fun applyTo(symbol: Symbol, anchor: FloatArray, dpiFactor: Float) {
super.applyTo(symbol, anchor, dpiFactor)
symbol.setIconColor(Color.HSVToColor(floatArrayOf(hue, 1.0f, 0.5f)))
}
} | play-services-maps-core-mapbox/src/main/kotlin/org/microg/gms/maps/mapbox/model/BitmapDescriptor.kt | 2642282813 |
package lt.vilnius.tvarkau.utils
import org.junit.Test
import java.io.File
import kotlin.test.assertFalse
import kotlin.test.assertTrue
/**
* @author Martynas Jurkus
*/
class PersonalCodeValidatorTest {
@Test
fun too_short_fail() {
assertFalse { PersonalCodeValidator.validate("1234567890") }
}
@Test
fun too_long_fail() {
assertFalse { PersonalCodeValidator.validate("1234567890123") }
}
@Test
fun with_letters_fail() {
assertFalse { PersonalCodeValidator.validate("12345z78901") }
}
@Test
fun checksum_fails() {
assertFalse { PersonalCodeValidator.validate("34508028193") }
}
@Test
fun dataSet_all_pass() {
val result = File(PersonalCodeValidatorTest::class.java.getResource(PERSONAL_CODES).toURI())
.readLines()
.map { PersonalCodeValidator.validate(it) to it }
assertTrue { result.all { it.first } }
}
companion object {
private const val PERSONAL_CODES = "personal_codes.txt"
}
} | app/src/test/java/lt/vilnius/tvarkau/utils/PersonalCodeValidatorTest.kt | 3315155377 |
package com.example.ffi_on_flutter
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| extras/integration_tests/ffi_on_flutter/android/app/src/main/kotlin/com/example/ffi_on_flutter/MainActivity.kt | 3605010089 |
package cn.org.cicada.jdbc.kt.query
import cn.org.cicada.jdbc.kt.dao.JdbcDao
import java.io.Serializable
import kotlin.reflect.KClass
interface QueryFactory {
fun quote(string: String) : String
fun buildInsertSql(jdbcDao: JdbcDao, entity: Any) : Stmt
fun buildUpdateSql(jdbcDao: JdbcDao, entity: Any) : Stmt
fun buildDeleteSql(jdbcDao: JdbcDao, entity: Any) : Stmt
fun <E:Any> buildDeleteSql(jdbcDao: JdbcDao, entityClass: KClass<E>, vararg ids: Serializable) : Stmt
}
| src/main/kotlin/cn/org/cicada/jdbc/kt/query/QueryFactory.kt | 1434342133 |
package com.fracturedskies.engine.jeact.event
import com.fracturedskies.engine.jeact.Component
open class Event(val target: Component<*>) {
var phase: Phase = Phase.CAPTURE
var stopPropogation: Boolean = false
override fun toString() = "${this.javaClass.simpleName}[$phase]($target)"
}
enum class Phase {
CAPTURE,
TARGET,
BUBBLE
} | src/main/kotlin/com/fracturedskies/engine/jeact/event/Event.kt | 1920561002 |
/*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.android.util
import android.app.Activity
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.View
import nl.adaptivity.android.recyclerview.SelectableAdapter
import nl.adaptivity.process.ui.ProcessSyncManager
import nl.adaptivity.sync.SyncManager
open class MasterListFragment<M : SyncManager> : RecyclerFragment() {
/**
* A dummy implementation of the [ListCallbacks] interface that does
* nothing. Used only when this fragment is not attached to an activity.
*/
val sDummyCallbacks = object : ListCallbacks<ProcessSyncManager> {
internal var context = [email protected]?.applicationContext
override val isTwoPane: Boolean
get() = false
override val syncManager: ProcessSyncManager?
get() = ProcessSyncManager(context, null)
override fun onItemClicked(row: Int, id: Long): Boolean {/*dummy, not processed*/
return false
}
override fun onItemSelected(row: Int, id: Long) {/*dummy*/
}
}
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
private var mCallbacks: ListCallbacks<M> = sDummyCallbacks as ListCallbacks<M>
protected val callbacks: ListCallbacks<M>
get() {
if (mCallbacks === sDummyCallbacks) {
var parent = parentFragment
while (parent != null) {
if (parent is ListCallbacks<*>) {
mCallbacks = parent as ListCallbacks<M>
return mCallbacks
}
parent = parent.parentFragment
}
}
return mCallbacks
}
init {
Log.i(MasterListFragment::class.java.simpleName, "Creating a new instanceo of " + javaClass.simpleName)
}
interface ListCallbacks<M : SyncManager> {
val isTwoPane: Boolean
val syncManager: M?
/** Initiate a click. When this returns true, further ignore the event (don't select) */
fun onItemClicked(row: Int, id: Long): Boolean
fun onItemSelected(row: Int, id: Long)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
callbacks
}
override fun onAttach(activity: Activity?) {
super.onAttach(activity)
if (mCallbacks === sDummyCallbacks) {
if (getActivity() is ListCallbacks<*>) {
mCallbacks = getActivity() as ListCallbacks<M>
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Restore the previously serialized activated item position.
if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_ID)) {
setActivatedId(savedInstanceState.getLong(STATE_ACTIVATED_ID))
} else {
val arguments = arguments
if (arguments != null && arguments.containsKey(MasterDetailOuterFragment.ARG_ITEM_ID)) {
setActivatedId(arguments.getLong(MasterDetailOuterFragment.ARG_ITEM_ID))
}
}
}
override fun onDetach() {
super.onDetach()
// Reset the active callbacks interface to the dummy implementation.
mCallbacks = sDummyCallbacks as ListCallbacks<M>
}
protected fun doOnItemClicked(position: Int, nodeId: Long): Boolean {
return callbacks.onItemClicked(position, nodeId)
}
protected fun doOnItemSelected(position: Int, nodeId: Long) {
callbacks.onItemSelected(position, nodeId)
}
protected fun setActivatedId(id: Long) {
val vh = recyclerView!!.findViewHolderForItemId(id)
val adapter = listAdapter
if (adapter is SelectableAdapter<*>) {
val selectableAdapter = adapter as SelectableAdapter<*>
if (vh != null) {
selectableAdapter.setSelectedItem(vh.adapterPosition.toLong())
} else {
selectableAdapter.setSelectedItem(id)
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
val adapter = listAdapter
if (adapter is SelectableAdapter<*>) {
val selectableAdapter = adapter as SelectableAdapter<*>
if (selectableAdapter.selectedId != RecyclerView.NO_ID) {
// Serialize and persist the activated item position.
outState.putLong(STATE_ACTIVATED_ID, selectableAdapter.selectedId)
}
}
}
companion object {
/**
* The serialization (saved instance state) Bundle key representing the
* activated item position. Only used on tablets.
*/
val STATE_ACTIVATED_ID = "activated_id"
}
}
| PMEditor/src/main/java/nl/adaptivity/android/util/MasterListFragment.kt | 3027325639 |
/*
* Copyright (c) 2017.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.diagram
import net.devrieze.util.hasFlag
import nl.adaptivity.diagram.Drawable.Companion.STATE_CUSTOM1
import nl.adaptivity.diagram.Drawable.Companion.STATE_CUSTOM2
import nl.adaptivity.diagram.Drawable.Companion.STATE_CUSTOM3
import nl.adaptivity.diagram.Drawable.Companion.STATE_CUSTOM4
import nl.adaptivity.diagram.Drawable.Companion.STATE_DEFAULT
import nl.adaptivity.diagram.Drawable.Companion.STATE_SELECTED
import nl.adaptivity.diagram.Drawable.Companion.STATE_TOUCHED
import nl.adaptivity.diagram.DrawingStrategy
import nl.adaptivity.diagram.Pen
import nl.adaptivity.diagram.ThemeItem
enum class ProcessThemeItems(
private var fill: Boolean = false,
private var parent: ProcessThemeItems? = null,
private var stroke: Double = 0.0,
private var fontSize: Double = Double.NaN,
vararg private var specifiers: StateSpecifier) : ThemeItem {
LINE(RootDrawableProcessModel.STROKEWIDTH, state(STATE_DEFAULT, 0, 0, 0),
stateStroke(STATE_SELECTED, 0, 0, 255, 255, 2.0),
stateStroke(STATE_TOUCHED, 255, 255, 0, 127, 7.0),
state(STATE_CUSTOM1, 0, 0, 255),
state(STATE_CUSTOM2, 255, 255, 0),
state(STATE_CUSTOM3, 255, 0, 0),
state(STATE_CUSTOM4, 0, 255, 0)) {
override fun getEffectiveState(state: Int): Int {
if (state hasFlag STATE_TOUCHED) return STATE_TOUCHED
return effectiveStateHelper(state).ifInvalid(super.getEffectiveState(state))
}
},
INNERLINE(RootDrawableProcessModel.STROKEWIDTH * 0.85, state(STATE_DEFAULT, 0, 0, 0x20, 0xb0)),
BACKGROUND(state(STATE_DEFAULT, 255, 255, 255)) {
override fun getEffectiveState(state: Int) = STATE_DEFAULT
},
ENDNODEOUTERLINE(RootDrawableProcessModel.ENDNODEOUTERSTROKEWIDTH, LINE),
LINEBG(LINE),
DIAGRAMTEXT(RootDrawableProcessModel.STROKEWIDTH, RootDrawableProcessModel.DIAGRAMTEXT_SIZE,
state(STATE_DEFAULT, 0, 0, 0)),
DIAGRAMLABEL(RootDrawableProcessModel.STROKEWIDTH, RootDrawableProcessModel.DIAGRAMLABEL_SIZE,
state(STATE_DEFAULT, 0, 0, 0));
constructor(stroke: Double, parent: ProcessThemeItems) : this(false, parent = parent, stroke = stroke)
constructor(parent: ProcessThemeItems) : this(fill = true, parent = parent)
constructor(stroke: Double, vararg specifiers: StateSpecifier) : this(fill=false, stroke = stroke, specifiers = *specifiers)
constructor(stroke: Double, fontSize: Double, vararg specifiers: StateSpecifier) :
this(fill = true, stroke = stroke, fontSize = fontSize, specifiers = *specifiers)
constructor(vararg specifiers: StateSpecifier) : this(fill = true, specifiers = *specifiers)
override val itemNo: Int get() = ordinal
override fun getEffectiveState(state: Int): Int {
parent?.let { return it.getEffectiveState(state) }
return effectiveStateHelper(state).ifInvalid(state)
}
internal fun effectiveStateHelper(state: Int): Int {
return when {
state hasFlag STATE_CUSTOM1 -> STATE_CUSTOM1
state hasFlag STATE_CUSTOM2 -> STATE_CUSTOM2
state hasFlag STATE_CUSTOM3 -> STATE_CUSTOM3
state hasFlag STATE_CUSTOM4 -> STATE_CUSTOM4
else -> -1
}
}
override fun <PEN_T : Pen<PEN_T>> createPen(strategy: DrawingStrategy<*, PEN_T, *>, state: Int): PEN_T {
val specifier = getSpecifier(state)
val result = with(specifier) { strategy.newPen().setColor(red, green, blue, alpha) }
if (!fill) {
val stroke = when {
stroke > 0.0 -> stroke
else -> parent?.stroke ?: stroke
}
result.setStrokeWidth(stroke * specifier.strokeMultiplier)
}
if (fontSize.isFinite()) result.setFontSize(fontSize)
return result
}
private fun getSpecifier(state: Int): StateSpecifier {
parent?.apply { return getSpecifier(state) }
specifiers.firstOrNull { it.state == state }?.let { return it }
return specifiers.reduce { a, b ->
when {
b.state hasFlag state && b.state > a.state -> b
else -> a
}
}
}
}
private open class StateSpecifier(val state: Int, val red: Int, val green: Int, val blue: Int, val alpha: Int) {
open val strokeMultiplier: Double get() = 1.0
}
private class StrokeStateSpecifier(state: Int, r: Int, g: Int, b: Int, a: Int, override val strokeMultiplier: Double) :
StateSpecifier(state, r, g, b, a)
@Suppress("NOTHING_TO_INLINE")
private inline fun stateStroke(state: Int, r: Int, g: Int, b: Int, a: Int, strokeMultiplier: Double)
= StrokeStateSpecifier(state, r, g, b, a, strokeMultiplier)
@Suppress("NOTHING_TO_INLINE")
private inline fun state(state: Int, r: Int, g: Int, b: Int) = StateSpecifier(state, r, g, b, 255)
// This method can be useful when colors with alpha are desired.
@Suppress("NOTHING_TO_INLINE")
private inline fun state(state: Int, r: Int, g: Int, b: Int, a: Int) = StateSpecifier(state, r, g, b, a)
@Suppress("NOTHING_TO_INLINE")
private inline fun Int.ifInvalid(alternate:Int): Int = if (this >= 0) this else alternate | PE-diagram/src/commonMain/kotlin/nl.adaptivity.process/diagram/ProcessThemeItems.kt | 2213765219 |
package org.wordpress.android.fluxc.network.rest.wpcom.notifications
import com.google.gson.annotations.SerializedName
import org.wordpress.android.fluxc.network.Response
class RegisterDeviceRestResponse : Response {
@SerializedName("ID")
val id: String? = null
}
| fluxc/src/main/java/org/wordpress/android/fluxc/network/rest/wpcom/notifications/RegisterDeviceRestResponse.kt | 45562917 |
// Copyright 2021 [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 cfig.bootimg.cpio
import cfig.io.Struct3
import org.apache.commons.compress.archivers.cpio.CpioConstants
/*
cpio "New ASCII Format" with 070701 as magic
*/
class NewAsciiCpio(
var c_magic: String = "070701", //start-of-header
var c_ino: Long = 0,//var
var c_mode: Long = 0,//var
var c_uid: Int = 0,
var c_gid: Int = 0,
var c_nlink: Int = 1,
var c_mtime: Long = 0,
var c_filesize: Int = 0,//var
var c_devmajor: Int = 0,
var c_devminor: Int = 0,
var c_rdevmajor: Int = 0,
var c_rdevminor: Int = 0, //end-of-header
var c_namesize: Int = 0, //c_string name with '\0', aka. name_len + 1
var c_check: Int = 0
) {
init {
if (SIZE != Struct3(FORMAT_STRING).calcSize()) {
throw RuntimeException()
}
}
fun encode(): ByteArray {
return Struct3(FORMAT_STRING).pack(
String.format("%s", c_magic),
String.format("%08x", c_ino),
String.format("%08x", c_mode),
String.format("%08x", c_uid),
String.format("%08x", c_gid),
String.format("%08x", c_nlink),
String.format("%08x", c_mtime),
String.format("%08x", c_filesize),
String.format("%08x", c_devmajor),
String.format("%08x", c_devminor),
String.format("%08x", c_rdevmajor),
String.format("%08x", c_rdevminor),
String.format("%08x", c_namesize),
String.format("%08x", c_check),
)
}
private fun fileType(): Long {
return c_mode and CpioConstants.S_IFMT.toLong()
}
fun isRegularFile(): Boolean {
return fileType() == CpioConstants.C_ISREG.toLong()
}
fun isDirectory(): Boolean {
return fileType() == CpioConstants.C_ISDIR.toLong()
}
fun isSymbolicLink(): Boolean {
return fileType() == CpioConstants.C_ISLNK.toLong()
}
companion object {
const val SIZE = 110
const val FORMAT_STRING = "6s8s8s8s8s8s8s8s8s8s8s8s8s8s" //6 + 8 *13
}
}
/* <bits/stat.h>
/* File types. */
#define __S_IFDIR 0040000 /* Directory. */
#define __S_IFCHR 0020000 /* Character device. */
#define __S_IFBLK 0060000 /* Block device. */
#define __S_IFREG 0100000 /* Regular file. */
#define __S_IFIFO 0010000 /* FIFO. */
#define __S_IFLNK 0120000 /* Symbolic link. */
#define __S_IFSOCK 0140000 /* Socket. */
/* Protection bits. */
#define __S_ISUID 04000 /* Set user ID on execution. */
#define __S_ISGID 02000 /* Set group ID on execution. */
#define __S_ISVTX 01000 /* Save swapped text after use (sticky). */
#define __S_IREAD 0400 /* Read by owner. */
#define __S_IWRITE 0200 /* Write by owner. */
#define __S_IEXEC 0100 /* Execute by owner. */
/* Read, write, and execute by owner. */
#define S_IRWXU (__S_IREAD|__S_IWRITE|__S_IEXEC)
#define S_IRGRP (S_IRUSR >> 3) /* Read by group. */
#define S_IWGRP (S_IWUSR >> 3) /* Write by group. */
#define S_IXGRP (S_IXUSR >> 3) /* Execute by group. */
Read, write, and execute by group.
#define S_IRWXG (S_IRWXU >> 3)
#define S_IROTH (S_IRGRP >> 3) /* Read by others. */
#define S_IWOTH (S_IWGRP >> 3) /* Write by others. */
#define S_IXOTH (S_IXGRP >> 3) /* Execute by others. */
Read, write, and execute by others.
#define S_IRWXO (S_IRWXG >> 3)
# define ACCESSPERMS (S_IRWXU|S_IRWXG|S_IRWXO) 0777
*/
| bbootimg/src/main/kotlin/bootimg/cpio/NewAsciiCpio.kt | 770418705 |
/*
* 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.ClientPlayerOnGroundStatePacket
object ClientPlayerOnGroundStateHandler : PacketHandler<ClientPlayerOnGroundStatePacket> {
override fun handle(ctx: NetworkContext, packet: ClientPlayerOnGroundStatePacket) {
val player = ctx.session.player
player.handleOnGroundState(packet.isOnGround)
}
}
| src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/handler/play/ClientPlayerOnGroundStateHandler.kt | 866638354 |
package com.github.feed.sample.ui.common
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import dagger.android.AndroidInjection
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import javax.inject.Inject
abstract class BaseActivity : AppCompatActivity(), HasSupportFragmentInjector {
@Inject lateinit var fragmentInjector: DispatchingAndroidInjector<Fragment>
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
}
override fun supportFragmentInjector(): AndroidInjector<Fragment> {
return fragmentInjector
}
}
| app/src/main/kotlin/com/github/feed/sample/ui/common/BaseActivity.kt | 4136267993 |
package nl.hannahsten.texifyidea.run
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.process.ProcessListener
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.LocalFileSystem
import nl.hannahsten.texifyidea.util.runWriteAction
import java.io.File
/**
* Clean up given files after the process is done.
*/
class FileCleanupListener(private val filesToCleanUp: MutableList<File>) : ProcessListener {
override fun startNotified(event: ProcessEvent) {
}
override fun processTerminated(event: ProcessEvent) {
for (originalFile in filesToCleanUp) {
val file = LocalFileSystem.getInstance().refreshAndFindFileByPath(originalFile.absolutePath) ?: continue
runInEdt {
runWriteAction {
file.delete(this)
}
}
}
filesToCleanUp.clear()
}
override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) {
}
} | src/nl/hannahsten/texifyidea/run/FileCleanupListener.kt | 1814400367 |
package io.rover.sdk.core.data.domain
data class ID(
var rawValue: String
)
| core/src/main/kotlin/io/rover/sdk/core/data/domain/ID.kt | 3321956222 |
package org.rizki.mufrizal.starter.backend.domain.oauth2
/**
*
* @Author Rizki Mufrizal <[email protected]>
* @Web <https://RizkiMufrizal.github.io>
* @Since 20 August 2017
* @Time 6:00 PM
* @Project Starter-BackEnd
* @Package org.rizki.mufrizal.starter.backend.domain.oauth2
* @File AuthorizedGrantTypes
*
*/
enum class AuthorizedGrantTypes {
password, client_credentials, refresh_token, authorization_code, implicit
} | Starter-BackEnd/src/main/kotlin/org/rizki/mufrizal/starter/backend/domain/oauth2/AuthorizedGrantTypes.kt | 2922756611 |
package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.isInternal
import io.gitlab.arturbosch.detekt.rules.isPublic
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtEnumEntry
/**
* Nested classes are often used to implement functionality local to the class it is nested in. Therefore it should
* not be public to other parts of the code.
* Prefer keeping nested classes `private`.
*
* <noncompliant>
* internal class NestedClassesVisibility {
*
* public class NestedPublicClass // should not be public
* }
* </noncompliant>
*
* <compliant>
* internal class NestedClassesVisibility {
*
* internal class NestedPublicClass
* }
* </compliant>
*
* @author Ivan Balaksha
* @author schalkms
* @author Marvin Ramin
*/
class NestedClassesVisibility(config: Config = Config.empty) : Rule(config) {
override val issue: Issue = Issue("NestedClassesVisibility", Severity.Style,
"Nested types are often used for implementing private functionality " +
"and therefore this should not be public.",
Debt.FIVE_MINS)
override fun visitClass(klass: KtClass) {
if (klass.isTopLevel() && klass.isInternal()) {
checkDeclarations(klass)
}
}
private fun checkDeclarations(klass: KtClass) {
klass.declarations
.filterIsInstance<KtClassOrObject>()
.filter { it.isPublic() && it.isNoEnum() && it.isNoCompanionObj() }
.forEach {
report(CodeSmell(issue, Entity.from(it),
"Nested types are often used for implementing private functionality. " +
"However the visibility of ${klass.name} makes it visible externally."))
}
}
private fun KtClassOrObject.isNoEnum() = !this.hasModifier(KtTokens.ENUM_KEYWORD) && this !is KtEnumEntry
private fun KtClassOrObject.isNoCompanionObj() = !this.hasModifier(KtTokens.COMPANION_KEYWORD)
}
| detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/NestedClassesVisibility.kt | 2285421535 |
package com.jamieadkins.gwent.data.update.repository
import com.google.firebase.firestore.FirebaseFirestore
import com.google.gson.reflect.TypeToken
import com.jamieadkins.gwent.data.update.model.FirebaseNotice
import com.jamieadkins.gwent.domain.update.model.Notice
import com.jamieadkins.gwent.domain.update.repository.NoticesRepository
import io.reactivex.Observable
import timber.log.Timber
import javax.inject.Inject
class NoticesRepositoryImpl @Inject constructor(private val firestore: FirebaseFirestore) : NoticesRepository {
override fun getNotices(): Observable<List<Notice>> {
return Observable.create<List<Notice>> { emitter ->
val noticesRef = firestore.collection("notices")
.document("en")
.collection("notices")
val listener = noticesRef.addSnapshotListener { snapshot, e ->
if (e != null) {
emitter.onError(e)
}
val notices = snapshot?.documents?.mapNotNull { doc ->
val data = doc.toObject(FirebaseNotice::class.java)
data?.let {
Notice(
it.id,
it.title,
it.body,
it.enabled
)
}
}
emitter.onNext(notices ?: emptyList())
}
emitter.setCancellable { listener.remove() }
}
.doOnError { Timber.e(it) }
.onErrorReturnItem(emptyList())
}
inline fun <reified T> genericType() = object : TypeToken<T>() {}.type
} | data/src/main/java/com/jamieadkins/gwent/data/update/repository/NoticesRepositoryImpl.kt | 2380455388 |
package com.herolynx.elepantry.ext.android
import android.content.Context
import com.herolynx.elepantry.core.log.debug
object AppManager {
fun isAppInstalled(c: Context, appPackageName: String): Boolean {
val intent = c.packageManager.getLaunchIntentForPackage(appPackageName)
debug("[AppManager] Is application installed - name: $appPackageName, installed: ${intent != null}")
return intent != null
}
} | app/src/main/java/com/herolynx/elepantry/ext/android/AppManager.kt | 3727987847 |
package io.gitlab.arturbosch.detekt.rules.complexity
import io.gitlab.arturbosch.detekt.api.ThresholdedCodeSmell
import io.gitlab.arturbosch.detekt.rules.Case
import io.gitlab.arturbosch.detekt.test.TestConfig
import io.gitlab.arturbosch.detekt.test.lint
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
/**
* @author Artur Bosch
*/
class ComplexMethodSpec : Spek({
given("a complex method") {
it("finds one complex method") {
val subject = ComplexMethod()
subject.lint(Case.ComplexClass.path())
assertThat(subject.findings).hasSize(1)
assertThat((subject.findings[0] as ThresholdedCodeSmell).value).isEqualTo(20)
assertThat((subject.findings[0] as ThresholdedCodeSmell).threshold).isEqualTo(10)
}
}
given("several complex methods") {
val path = Case.ComplexMethods.path()
it("does not report complex methods with a single when expression") {
val config = TestConfig(mapOf(ComplexMethod.IGNORE_SINGLE_WHEN_EXPRESSION to "true"))
val subject = ComplexMethod(config, threshold = 4)
assertThat(subject.lint(path)).hasSize(1)
}
it("reports all complex methods") {
val subject = ComplexMethod(threshold = 4)
assertThat(subject.lint(path)).hasSize(5)
}
}
})
| detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/complexity/ComplexMethodSpec.kt | 3509983004 |
package rxreddit.model
import com.google.gson.annotations.SerializedName
data class MediaMetadata(
@SerializedName("status")
val status: String,
@SerializedName("e")
val e: String,
@SerializedName("m")
val m: String, // encoding?
@SerializedName("p")
val p: List<MediaMetadataPreview>,
@SerializedName("s")
val s: MediaMetadataPreview,
)
data class MediaMetadataPreview(
@SerializedName("x")
val x: Int,
@SerializedName("y")
val y: Int,
@SerializedName("u")
val u: String,
)
| library/src/main/java/rxreddit/model/MediaMetadata.kt | 2757131149 |
package org.rliz.cfm.recorder.common.api
data class AffectedRes(
val affected: Long
)
fun Long.toRes(): AffectedRes = AffectedRes(this)
| server/recorder/src/main/kotlin/org/rliz/cfm/recorder/common/api/AffectedRes.kt | 2437790220 |
package com.vsouhrada.apps.fibo.function.user
import com.vsouhrada.kotlin.android.anko.fibo.function.signin.login.model.AuthCredentials
/**
*
* @author vsouhrada
* @property[userDO] User Domain Object
* @since 0.1.0
*/
data class CreateUserEvent(val credentials: AuthCredentials) | app/src/main/kotlin/com/vsouhrada/kotlin/android/anko/fibo/function/signin/user/model/Events.kt | 3938861018 |
package com.lasthopesoftware.bluewater.client.browsing.items.media.files.access
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.stringlist.FileStringListUtilities
import com.namehillsoftware.handoff.promises.Promise
import com.namehillsoftware.handoff.promises.response.ImmediateResponse
import com.namehillsoftware.handoff.promises.response.PromisedResponse
import java.util.*
abstract class AbstractFileResponder : PromisedResponse<String, Collection<ServiceFile>>, ImmediateResponse<Collection<ServiceFile>, List<ServiceFile>> {
final override fun promiseResponse(stringList: String?): Promise<Collection<ServiceFile>> {
return stringList?.let(FileStringListUtilities::promiseParsedFileStringList) ?: Promise(emptyList())
}
final override fun respond(serviceFiles: Collection<ServiceFile>): List<ServiceFile> {
return if (serviceFiles is List<*>) serviceFiles as List<ServiceFile> else ArrayList(serviceFiles)
}
}
| projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/items/media/files/access/AbstractFileResponder.kt | 3216136532 |
package cc.aoeiuv020.panovel.share
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
/**
*
* Created by AoEiuV020 on 2018.03.07-19:31:38.
*/
class PasteUbuntuTest {
private lateinit var paste: PasteUbuntu
private val text = "PasteUbuntuTest"
@Before
fun setUp() {
paste = PasteUbuntu()
}
@Test
fun upload() {
val link = paste.upload(PasteUbuntu.PasteUbuntuData(text, expiration = Expiration.DAY))
println(link)
assertTrue(link.matches(Regex("https://paste.ubuntu.com/p/\\w*/")))
val receive = paste.download(link)
assertEquals(text, receive)
}
@Test
fun download() {
val receive = paste.download("https://paste.ubuntu.com/p/CH3g747q9S/")
assertEquals("""{
"list": [
{
"author": "二目",
"name": "放开那个女巫",
"requester": {
"type": "cc.aoeiuv020.panovel.api.DetailRequester",
"extra": "https://book.qidian.com/info/1003306811"
},
"site": "起点中文"
}
],
"name": "bs"
}""", receive)
}
} | app/src/test/java/cc/aoeiuv020/panovel/share/PasteUbuntuTest.kt | 3261857793 |
// DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// 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/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.exploration.modelFeatures.reporter
import kotlinx.coroutines.CoroutineName
import org.droidmate.deviceInterface.exploration.isClick
import org.droidmate.exploration.ExplorationContext
import org.droidmate.exploration.modelFeatures.ModelFeature
import org.droidmate.explorationModel.interaction.Interaction
import org.droidmate.explorationModel.interaction.State
import org.droidmate.explorationModel.interaction.Widget
import org.droidmate.misc.withExtension
import org.droidmate.exploration.modelFeatures.misc.plot
import java.nio.file.Files
import java.nio.file.Path
import java.time.temporal.ChronoUnit
import java.util.*
import kotlin.coroutines.CoroutineContext
class EffectiveActionsMF(private val includePlots: Boolean = true) : ModelFeature() {
override val coroutineContext: CoroutineContext = CoroutineName("EffectiveActionsMF")
/**
* Keep track of effective actions during exploration
* This is not used to dump the report at the end
*/
private var totalActions = 0
private var effectiveActions = 0
override suspend fun onNewInteracted(traceId: UUID, targetWidgets: List<Widget>, prevState: State<*>, newState: State<*>) {
totalActions++
if (prevState != newState)
effectiveActions++
}
fun getTotalActions(): Int {
return totalActions
}
fun getEffectiveActions(): Int {
return effectiveActions
}
override suspend fun onAppExplorationFinished(context: ExplorationContext<*, *, *>) {
val sb = StringBuilder()
val header = "Time_Seconds\tTotal_Actions\tTotal_Effective\n"
sb.append(header)
val reportData: HashMap<Long, Pair<Int, Int>> = HashMap()
// Ignore app start
val records = context.explorationTrace.P_getActions().drop(1)
val nrActions = records.size
val startTimeStamp = records.first().startTimestamp
var totalActions = 1
var effectiveActions = 1
for (i in 1 until nrActions) {
val prevAction = records[i - 1]
val currAction = records[i]
val currTimestamp = currAction.startTimestamp
val currTimeDiff = ChronoUnit.SECONDS.between(startTimeStamp, currTimestamp)
if (actionWasEffective(prevAction, currAction))
effectiveActions++
totalActions++
reportData[currTimeDiff] = Pair(totalActions, effectiveActions)
if (i % 100 == 0)
log.info("Processing $i")
}
reportData.keys.sorted().forEach { key ->
val value = reportData[key]!!
sb.appendln("$key\t${value.first}\t${value.second}")
}
val reportFile = context.model.config.baseDir.resolve("effective_actions.txt")
Files.write(reportFile, sb.toString().toByteArray())
if (includePlots) {
log.info("Writing out plot $")
this.writeOutPlot(reportFile, context.model.config.baseDir)
}
}
// Currently used in child projects
@Suppress("MemberVisibilityCanBePrivate")
fun actionWasEffective(prevAction: Interaction<*>, currAction: Interaction<*>): Boolean {
return if ((!prevAction.actionType.isClick()) ||
(! currAction.actionType.isClick()))
true
else {
currAction.prevState != currAction.resState
}
}
private fun writeOutPlot(dataFile: Path, resourceDir: Path) {
val fileName = dataFile.fileName.withExtension("pdf")
val outFile = dataFile.resolveSibling(fileName)
plot(dataFile.toAbsolutePath().toString(), outFile.toAbsolutePath().toString(), resourceDir)
}
} | project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/modelFeatures/reporter/EffectiveActionsMF.kt | 2727870208 |
package com.klask.sessions
import java.io.*
import java.util.Base64
import java.util.HashMap
import java.util.zip.DeflaterOutputStream
import java.util.zip.InflaterInputStream
import javax.servlet.http.Cookie
trait Session {
public fun get(key: String): Any?
public fun set(key: String, value: Serializable?)
public fun set(key: String, value: String?)
public fun remove(key: String)
}
public class SessionImpl(cookie: Cookie?) : Session {
val map: HashMap<String, Serializable?>;
init {
map = deserialize(cookie) ?: hashMapOf()
}
private fun deserialize(cookie: Cookie?): HashMap<String, Serializable?>? {
if (cookie == null) {
return null
}
ByteArrayInputStream(Base64.getUrlDecoder().decode(cookie.getValue())).use {
InflaterInputStream(it).use {
ObjectInputStream(it).use {
[suppress("UNCHECKED_CAST")]
return it.readObject() as HashMap<String, Serializable?>
}
}
}
}
override fun set(key: String, value: String?) {
set(key, value as Serializable?)
}
override fun set(key: String, value: Serializable?) {
map.put(key, value)
}
override fun remove(key: String) {
map.remove(key)
}
override fun get(key: String): Any? {
return map.get(key)
}
fun serialize(): String? {
val compressed = ByteArrayOutputStream().use {
DeflaterOutputStream(it).use {
ObjectOutputStream(it).use {
it.writeObject(map)
}
}
it
}.toByteArray()
return Base64.getUrlEncoder().encodeToString(compressed)!!
}
}
| src/main/kotlin/com/klask/session.kt | 2859746378 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.