content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
fun a() {
if (<caret>)
}
// SET_FALSE: ALIGN_MULTILINE_METHOD_BRACKETS | plugins/kotlin/idea/tests/testData/indentationOnNewline/emptyParameters/EmptyConditionInIf.kt | 2832726960 |
fun foo(a: String, b: String) {
lateinit var c: String<caret>
c = a
c = b
} | plugins/kotlin/idea/tests/testData/intentions/joinDeclarationAndAssignment/hasLateinit.kt | 3748697398 |
fun x() {/* ReanalyzableFunctionStructureElement */
fun y() {
}
}
class A {/* NonReanalyzableDeclarationStructureElement */
fun z() {/* ReanalyzableFunctionStructureElement */
fun q() {
}
}
} | plugins/kotlin/fir-low-level-api/testdata/fileStructure/localFun.kt | 2713923734 |
package com.simplemobiletools.calendar.pro.fragments
import android.content.Context
import android.content.res.Resources
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import androidx.fragment.app.Fragment
import com.simplemobiletools.calendar.pro.R
import com.simplemobiletools.calendar.pro.activities.MainActivity
import com.simplemobiletools.calendar.pro.extensions.config
import com.simplemobiletools.calendar.pro.extensions.getViewBitmap
import com.simplemobiletools.calendar.pro.extensions.printBitmap
import com.simplemobiletools.calendar.pro.helpers.Config
import com.simplemobiletools.calendar.pro.helpers.DAY_CODE
import com.simplemobiletools.calendar.pro.helpers.Formatter
import com.simplemobiletools.calendar.pro.helpers.MonthlyCalendarImpl
import com.simplemobiletools.calendar.pro.interfaces.MonthlyCalendar
import com.simplemobiletools.calendar.pro.interfaces.NavigationListener
import com.simplemobiletools.calendar.pro.models.DayMonthly
import com.simplemobiletools.commons.extensions.applyColorFilter
import com.simplemobiletools.commons.extensions.beGone
import com.simplemobiletools.commons.extensions.beVisible
import com.simplemobiletools.commons.extensions.getProperTextColor
import kotlinx.android.synthetic.main.fragment_month.view.*
import kotlinx.android.synthetic.main.top_navigation.view.*
import org.joda.time.DateTime
class MonthFragment : Fragment(), MonthlyCalendar {
private var mTextColor = 0
private var mSundayFirst = false
private var mShowWeekNumbers = false
private var mDayCode = ""
private var mPackageName = ""
private var mLastHash = 0L
private var mCalendar: MonthlyCalendarImpl? = null
var listener: NavigationListener? = null
lateinit var mRes: Resources
lateinit var mHolder: RelativeLayout
lateinit var mConfig: Config
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_month, container, false)
mRes = resources
mPackageName = requireActivity().packageName
mHolder = view.month_calendar_holder
mDayCode = requireArguments().getString(DAY_CODE)!!
mConfig = requireContext().config
storeStateVariables()
setupButtons()
mCalendar = MonthlyCalendarImpl(this, requireContext())
return view
}
override fun onPause() {
super.onPause()
storeStateVariables()
}
override fun onResume() {
super.onResume()
if (mConfig.showWeekNumbers != mShowWeekNumbers) {
mLastHash = -1L
}
mCalendar!!.apply {
mTargetDate = Formatter.getDateTimeFromCode(mDayCode)
getDays(false) // prefill the screen asap, even if without events
}
storeStateVariables()
updateCalendar()
}
private fun storeStateVariables() {
mConfig.apply {
mSundayFirst = isSundayFirst
mShowWeekNumbers = showWeekNumbers
}
}
fun updateCalendar() {
mCalendar?.updateMonthlyCalendar(Formatter.getDateTimeFromCode(mDayCode))
}
override fun updateMonthlyCalendar(context: Context, month: String, days: ArrayList<DayMonthly>, checkedEvents: Boolean, currTargetDate: DateTime) {
val newHash = month.hashCode() + days.hashCode().toLong()
if ((mLastHash != 0L && !checkedEvents) || mLastHash == newHash) {
return
}
mLastHash = newHash
activity?.runOnUiThread {
mHolder.top_value.apply {
text = month
contentDescription = text
if (activity != null) {
setTextColor(requireActivity().getProperTextColor())
}
}
updateDays(days)
}
}
private fun setupButtons() {
mTextColor = requireContext().getProperTextColor()
mHolder.top_left_arrow.apply {
applyColorFilter(mTextColor)
background = null
setOnClickListener {
listener?.goLeft()
}
val pointerLeft = requireContext().getDrawable(R.drawable.ic_chevron_left_vector)
pointerLeft?.isAutoMirrored = true
setImageDrawable(pointerLeft)
}
mHolder.top_right_arrow.apply {
applyColorFilter(mTextColor)
background = null
setOnClickListener {
listener?.goRight()
}
val pointerRight = requireContext().getDrawable(R.drawable.ic_chevron_right_vector)
pointerRight?.isAutoMirrored = true
setImageDrawable(pointerRight)
}
mHolder.top_value.apply {
setTextColor(requireContext().getProperTextColor())
setOnClickListener {
(activity as MainActivity).showGoToDateDialog()
}
}
}
private fun updateDays(days: ArrayList<DayMonthly>) {
mHolder.month_view_wrapper.updateDays(days, true) {
(activity as MainActivity).openDayFromMonthly(Formatter.getDateTimeFromCode(it.code))
}
}
fun printCurrentView() {
mHolder.apply {
top_left_arrow.beGone()
top_right_arrow.beGone()
top_value.setTextColor(resources.getColor(R.color.theme_light_text_color))
month_view_wrapper.togglePrintMode()
requireContext().printBitmap(month_calendar_holder.getViewBitmap())
top_left_arrow.beVisible()
top_right_arrow.beVisible()
top_value.setTextColor(requireContext().getProperTextColor())
month_view_wrapper.togglePrintMode()
}
}
}
| app/src/main/kotlin/com/simplemobiletools/calendar/pro/fragments/MonthFragment.kt | 1864688905 |
package com.intellij.ide.actions.searcheverywhere.ml.features.statistician
import com.intellij.openapi.components.Service
import com.intellij.openapi.util.Key
import com.intellij.psi.statistics.StatisticsManager
@Service(Service.Level.APP)
internal class SearchEverywhereStatisticianService {
companion object {
val KEY: Key<SearchEverywhereStatistician<in Any>> = Key.create("searchEverywhere")
}
fun increaseUseCount(element: Any) = getSerializedInfo(element)?.let { StatisticsManager.getInstance().incUseCount(it) }
fun getCombinedStats(element: Any): SearchEverywhereStatisticianStats? {
val statisticsManager = StatisticsManager.getInstance()
val info = getSerializedInfo(element) ?: return null
val allValues = statisticsManager.getAllValues(info.context).associateWith { statisticsManager.getUseCount(it) }
val useCount = allValues.entries.firstOrNull { it.key.value == info.value }?.value ?: 0
val isMostPopular = useCount > 0 && useCount == allValues.maxOf { it.value }
val recency = statisticsManager.getLastUseRecency(info)
return SearchEverywhereStatisticianStats(useCount, isMostPopular, recency)
}
private fun getSerializedInfo(element: Any) = StatisticsManager.serialize(KEY, element, "") // location is obtained from element
}
| plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/features/statistician/SearchEverywhereStatisticianService.kt | 609740409 |
package cy.github
import org.json.simple.*
import org.json.simple.parser.*
import java.io.*
import java.net.*
fun String.encodeURLComponent() = URLEncoder.encode(this, "UTF-8")!!
internal fun <T> URLConnection.withReader(block: (Reader) -> T): T = inputStream.reader().use(block)
internal fun JSONObject.getAsLong(key: String) = (get(key) as? Number)?.toLong()
internal fun Reader.toJSONObject(): JSONObject? = JSONParser().parse(this) as? JSONObject
fun String.parseSCMUrl(): Repo? =
"^scm:git:([^@]+@)?(ssh://|https?://)?([^:]+)[:/]([^/]+)/([^/]+)\\.git".toRegex().matchEntire(this)?.let { match ->
Repo(endpointOf(match.groups[2]?.value, match.groups[3]!!.value), match.groups[4]!!.value, match.groups[5]!!.value)
}
| github-release-shared/src/main/kotlin/util.kt | 4152998491 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.eclipse
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.rules.ProjectModelRule
import com.intellij.testFramework.rules.TempDirectory
import org.junit.Assume.assumeTrue
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestName
class EclipseEml2ModulesTest {
@JvmField
@Rule
val tempDirectory = TempDirectory()
@JvmField
@Rule
val testName = TestName()
@Test
fun testSourceRootPaths() {
doTest("ws-internals")
}
@Test
fun testAnotherSourceRootPaths() {
doTest("anotherPath")
}
private fun doTest(secondRootName: String) {
assumeTrue(ProjectModelRule.isWorkspaceModelEnabled)
val testName = testName.methodName.removePrefix("test").decapitalize()
val testRoot = eclipseTestDataRoot.resolve("eml").resolve(testName)
val commonRoot = eclipseTestDataRoot.resolve("common").resolve("twoModulesWithClasspathStorage")
checkEmlFileGeneration(listOf(testRoot, commonRoot), tempDirectory, listOf(
"test" to "srcPath/sourceRootPaths/sourceRootPaths",
"ws-internals" to "srcPath/$secondRootName/ws-internals"
))
}
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
} | plugins/eclipse/testSources/org/jetbrains/idea/eclipse/EclipseEml2ModulesTest.kt | 2130934865 |
package com.sedsoftware.yaptalker.domain.repository
import com.sedsoftware.yaptalker.domain.entity.base.Emoji
import io.reactivex.Observable
interface EmojiRepository {
fun getEmojiList(): Observable<Emoji>
}
| domain/src/main/java/com/sedsoftware/yaptalker/domain/repository/EmojiRepository.kt | 441996812 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.paging
import androidx.arch.core.util.Function
@Suppress("DEPRECATION")
internal class WrapperPositionalDataSource<A : Any, B : Any>(
private val source: PositionalDataSource<A>,
val listFunction: Function<List<A>, List<B>>
) : PositionalDataSource<B>() {
override val isInvalid
get() = source.isInvalid
override fun addInvalidatedCallback(onInvalidatedCallback: InvalidatedCallback) {
source.addInvalidatedCallback(onInvalidatedCallback)
}
override fun removeInvalidatedCallback(onInvalidatedCallback: InvalidatedCallback) {
source.removeInvalidatedCallback(onInvalidatedCallback)
}
override fun invalidate() = source.invalidate()
override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<B>) {
source.loadInitial(
params,
object : LoadInitialCallback<A>() {
override fun onResult(data: List<A>, position: Int, totalCount: Int) =
callback.onResult(convert(listFunction, data), position, totalCount)
override fun onResult(data: List<A>, position: Int) =
callback.onResult(convert(listFunction, data), position)
}
)
}
override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<B>) {
source.loadRange(
params,
object : LoadRangeCallback<A>() {
override fun onResult(data: List<A>) =
callback.onResult(convert(listFunction, data))
}
)
}
}
| paging/paging-common/src/main/kotlin/androidx/paging/WrapperPositionalDataSource.kt | 2930391472 |
// TODO: Declarations have no implementation and should be considered as "overloaded"
interface <lineMarker descr="Is implemented by Second Click or press ... to navigate">First</lineMarker> {
val <lineMarker descr="<html><body>Is implemented in <br/> Second</body></html>">some</lineMarker>: Int
var <lineMarker descr="<html><body>Is implemented in <br/> Second</body></html>">other</lineMarker>: String
get
set
fun <lineMarker descr="<html><body>Is implemented in <br> Second</body></html>">foo</lineMarker>()
}
interface Second : First {
override val <lineMarker descr="Overrides property in 'First'">some</lineMarker>: Int
override var <lineMarker descr="Overrides property in 'First'">other</lineMarker>: String
override fun <lineMarker descr="Overrides function in 'First'">foo</lineMarker>()
} | plugins/kotlin/idea/tests/testData/codeInsight/lineMarker/overrideImplement/OverridenTraitDeclarations.kt | 426969054 |
lateinit var x: java.lang.Readable
lateinit var y: java.nio.CharBuffer
val h = x.read(p<caret>0 = y)
// REF: CharBuffer var1
| plugins/kotlin/idea/tests/testData/resolve/references/JavaParameter.kt | 2533020221 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.application.constraints
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Job
import kotlinx.coroutines.Runnable
import kotlinx.coroutines.cancel
import java.util.function.BooleanSupplier
import kotlin.coroutines.AbstractCoroutineContextElement
import kotlin.coroutines.Continuation
import kotlin.coroutines.ContinuationInterceptor
import kotlin.coroutines.CoroutineContext
internal fun createConstrainedCoroutineDispatcher(executionScheduler: ConstrainedExecutionScheduler,
cancellationCondition: BooleanSupplier? = null,
expiration: Expiration? = null): ContinuationInterceptor {
val dispatcher = ConstrainedCoroutineDispatcherImpl(executionScheduler, cancellationCondition)
return when (expiration) {
null -> dispatcher
else -> ExpirableContinuationInterceptor(dispatcher, expiration)
}
}
internal class ConstrainedCoroutineDispatcherImpl(private val executionScheduler: ConstrainedExecutionScheduler,
private val cancellationCondition: BooleanSupplier?) : CoroutineDispatcher() {
override fun dispatch(context: CoroutineContext, block: Runnable) {
val condition = cancellationCondition?.let {
BooleanSupplier {
true.also {
if (cancellationCondition.asBoolean) context.cancel()
}
}
}
executionScheduler.scheduleWithinConstraints(block, condition)
}
override fun toString(): String = executionScheduler.toString()
}
internal class ExpirableContinuationInterceptor(private val dispatcher: CoroutineDispatcher,
private val expiration: Expiration)
: AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {
/** Invoked once on each newly launched coroutine when dispatching it for the first time. */
override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> {
expiration.cancelJobOnExpiration(continuation.context[Job]!!)
return dispatcher.interceptContinuation(continuation)
}
override fun toString(): String = dispatcher.toString()
}
| platform/platform-impl/src/com/intellij/openapi/application/constraints/ConstrainedCoroutineDispatcher.kt | 3904815072 |
package de.mydevtime.sponge.plugin.lootchest.commands
import de.mydevtime.sponge.plugin.lootchest.data.Constant
import de.mydevtime.sponge.plugin.lootchest.manager.ChestManager
import org.spongepowered.api.command.CommandException
import org.spongepowered.api.command.CommandResult
import org.spongepowered.api.command.CommandSource
import org.spongepowered.api.command.args.CommandContext
import org.spongepowered.api.command.source.CommandBlockSource
import org.spongepowered.api.command.source.ConsoleSource
import org.spongepowered.api.command.spec.CommandExecutor
import org.spongepowered.api.entity.living.player.Player
class Info_CMD(val cm: ChestManager) : CommandExecutor
{
override fun execute(p0: CommandSource?, p1: CommandContext?): CommandResult
{
if (p0 == null || p1 == null)
{
throw NullPointerException("CommandSource or CommandContext or both are null!")
}
if (p0 is ConsoleSource)
{
throw CommandException(Constant.ERROR_CMD_CONSOLE)
}
if (p0 is CommandBlockSource)
{
throw CommandException(Constant.ERROR_CMD_COMMANDBLOCK)
}
p1.checkPermission(p0, Constant.PERMISSION_CMD_INFO)
if (p1.hasAny("-help"))
{
p0.sendMessage(Constant.HELP_CMD_INFO)
return CommandResult.success()
}
if (!Constant.LIST_PLAYER_INFO.contains(p0))
{
Constant.LIST_PLAYER_INFO.add(p0 as Player)
}
p0.sendMessage(Constant.DESC_CMD_INFO)
return CommandResult.success()
}
} | src/main/java/de/mydevtime/sponge/plugin/lootchest/commands/Info_CMD.kt | 398458401 |
val s: String? = null
if (!s!!.isEmpty()) {
} | plugins/kotlin/j2k/old/tests/testData/fileOrElement/prefixOperator/nullableIf.kt | 1592519758 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("GradleImportingTestUtil")
package org.jetbrains.plugins.gradle.util
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.testFramework.PlatformTestUtil
import org.jetbrains.concurrency.Promise
import java.nio.file.Path
import java.util.concurrent.TimeUnit
/**
* @param action or some async calls have to produce project reload
* for example invokeLater { refreshProject(project, spec) }
* @throws java.lang.AssertionError if import is failed or isn't started
*/
fun <R> waitForMultipleProjectsReload(expectedProjects: List<Path>, action: ThrowableComputable<R, Throwable>): R {
return waitForTask(getProjectDataLoadPromise(expectedProjects), action)
}
fun <R> waitForProjectReload(action: ThrowableComputable<R, Throwable>): R = waitForTask(getProjectDataLoadPromise(), action)
fun <R> waitForTaskExecution(action: ThrowableComputable<R, Throwable>): R = waitForTask(getExecutionTaskFinishPromise(), action)
private fun <R> waitForTask(finishTaskPromise: Promise<*>, action: ThrowableComputable<R, Throwable>): R {
val result = action.compute()
invokeAndWaitIfNeeded {
PlatformTestUtil.waitForPromise(finishTaskPromise, TimeUnit.MINUTES.toMillis(1))
}
return result
} | plugins/gradle/testSources/org/jetbrains/plugins/gradle/util/GradleImportingTestUtil.kt | 1588143358 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.usageView.UsageInfo
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeInsight.shorten.addDelayedImportRequest
import org.jetbrains.kotlin.idea.core.moveFunctionLiteralOutsideParentheses
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicatorInput
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.RemoveEmptyParenthesesFromLambdaCallApplicator
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinParameterInfo
import org.jetbrains.kotlin.idea.refactoring.changeSignature.isInsideOfCallerBody
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.createNameCounterpartMap
import org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable.KotlinIntroduceVariableHandler
import org.jetbrains.kotlin.idea.refactoring.replaceListPsiAndKeepDelimiters
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.*
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.*
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.util.kind
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.kotlin.utils.sure
class KotlinFunctionCallUsage(
element: KtCallElement,
private val callee: KotlinCallableDefinitionUsage<*>,
forcedResolvedCall: ResolvedCall<*>? = null
) : KotlinUsageInfo<KtCallElement>(element) {
private val context = element.analyze(BodyResolveMode.FULL)
private val resolvedCall = forcedResolvedCall ?: element.getResolvedCall(context)
private val skipUnmatchedArgumentsCheck = forcedResolvedCall != null
override fun processUsage(changeInfo: KotlinChangeInfo, element: KtCallElement, allUsages: Array<out UsageInfo>): Boolean {
processUsageAndGetResult(changeInfo, element, allUsages)
return true
}
fun processUsageAndGetResult(
changeInfo: KotlinChangeInfo,
element: KtCallElement,
allUsages: Array<out UsageInfo>,
skipRedundantArgumentList: Boolean = false,
): KtElement {
if (shouldSkipUsage(element)) return element
var result: KtElement = element
changeNameIfNeeded(changeInfo, element)
if (element.valueArgumentList == null && changeInfo.isParameterSetOrOrderChanged && element.lambdaArguments.isNotEmpty()) {
val anchor = element.typeArgumentList ?: element.calleeExpression
if (anchor != null) {
element.addAfter(KtPsiFactory(element).createCallArguments("()"), anchor)
}
}
if (element.valueArgumentList != null) {
if (changeInfo.isParameterSetOrOrderChanged) {
result = updateArgumentsAndReceiver(changeInfo, element, allUsages, skipRedundantArgumentList)
} else {
changeArgumentNames(changeInfo, element)
}
}
if (changeInfo.getNewParametersCount() == 0 && element is KtSuperTypeCallEntry) {
val enumEntry = element.getStrictParentOfType<KtEnumEntry>()
if (enumEntry != null && enumEntry.initializerList == element.parent) {
val initializerList = enumEntry.initializerList
enumEntry.deleteChildRange(enumEntry.getColon() ?: initializerList, initializerList)
}
}
return result
}
private fun shouldSkipUsage(element: KtCallElement): Boolean {
// TODO: We probable need more clever processing of invalid calls, but for now default to Java-like behaviour
if (resolvedCall == null && element !is KtSuperTypeCallEntry) return true
if (resolvedCall == null || resolvedCall.isReallySuccess()) return false
// TODO: investigate why arguments are not recorded for enum constructor call
if (element is KtSuperTypeCallEntry && element.parent.parent is KtEnumEntry && element.valueArguments.isEmpty()) return false
if (skipUnmatchedArgumentsCheck) return false
if (!resolvedCall.call.valueArguments.all { resolvedCall.getArgumentMapping(it) is ArgumentMatch }) return true
val arguments = resolvedCall.valueArguments
return !resolvedCall.resultingDescriptor.valueParameters.all { arguments.containsKey(it) }
}
private val isPropertyJavaUsage: Boolean
get() {
val calleeElement = this.callee.element
if (calleeElement !is KtProperty && calleeElement !is KtParameter) return false
return resolvedCall?.resultingDescriptor is JavaMethodDescriptor
}
private fun changeNameIfNeeded(changeInfo: KotlinChangeInfo, element: KtCallElement) {
if (!changeInfo.isNameChanged) return
val callee = element.calleeExpression as? KtSimpleNameExpression ?: return
var newName = changeInfo.newName
if (isPropertyJavaUsage) {
val currentName = callee.getReferencedName()
if (JvmAbi.isGetterName(currentName))
newName = JvmAbi.getterName(newName)
else if (JvmAbi.isSetterName(currentName)) newName = JvmAbi.setterName(newName)
}
callee.replace(KtPsiFactory(project).createSimpleName(newName))
}
private fun getReceiverExpressionIfMatched(
receiverValue: ReceiverValue?,
originalDescriptor: DeclarationDescriptor,
psiFactory: KtPsiFactory
): KtExpression? {
if (receiverValue == null) return null
// Replace descriptor of extension function/property with descriptor of its receiver
// to simplify checking against receiver value in the corresponding resolved call
val adjustedDescriptor = if (originalDescriptor is CallableDescriptor && originalDescriptor !is ReceiverParameterDescriptor) {
originalDescriptor.extensionReceiverParameter ?: return null
} else originalDescriptor
val currentIsExtension = resolvedCall!!.extensionReceiver == receiverValue
val originalIsExtension = adjustedDescriptor is ReceiverParameterDescriptor && adjustedDescriptor.value is ExtensionReceiver
if (currentIsExtension != originalIsExtension) return null
val originalType = when (adjustedDescriptor) {
is ReceiverParameterDescriptor -> adjustedDescriptor.type
is ClassDescriptor -> adjustedDescriptor.defaultType
else -> null
}
if (originalType == null || !KotlinTypeChecker.DEFAULT.isSubtypeOf(receiverValue.type, originalType)) return null
return getReceiverExpression(receiverValue, psiFactory)
}
private fun needSeparateVariable(element: PsiElement): Boolean {
return when {
element is KtConstantExpression || element is KtThisExpression || element is KtSimpleNameExpression -> false
element is KtBinaryExpression && OperatorConventions.ASSIGNMENT_OPERATIONS.contains(element.operationToken) -> true
element is KtUnaryExpression && OperatorConventions.INCREMENT_OPERATIONS.contains(element.operationToken) -> true
element is KtCallExpression -> element.getResolvedCall(context)?.resultingDescriptor is ConstructorDescriptor
else -> element.children.any { needSeparateVariable(it) }
}
}
private fun substituteReferences(
expression: KtExpression,
referenceMap: Map<PsiReference, DeclarationDescriptor>,
psiFactory: KtPsiFactory
): KtExpression {
if (referenceMap.isEmpty() || resolvedCall == null) return expression
var newExpression = expression.copy() as KtExpression
val nameCounterpartMap = createNameCounterpartMap(expression, newExpression)
val valueArguments = resolvedCall.valueArguments
val replacements = ArrayList<Pair<KtExpression, KtExpression>>()
loop@ for ((ref, descriptor) in referenceMap.entries) {
var argumentExpression: KtExpression?
val addReceiver: Boolean
if (descriptor is ValueParameterDescriptor) {
// Ordinary parameter
// Find corresponding parameter in the current function (may differ from 'descriptor' if original function is part of override hierarchy)
val parameterDescriptor = resolvedCall.resultingDescriptor.valueParameters[descriptor.index]
val resolvedValueArgument = valueArguments[parameterDescriptor] as? ExpressionValueArgument ?: continue
val argument = resolvedValueArgument.valueArgument ?: continue
addReceiver = false
argumentExpression = argument.getArgumentExpression()
} else {
addReceiver = descriptor !is ReceiverParameterDescriptor
argumentExpression =
getReceiverExpressionIfMatched(resolvedCall.extensionReceiver, descriptor, psiFactory)
?: getReceiverExpressionIfMatched(resolvedCall.dispatchReceiver, descriptor, psiFactory)
}
if (argumentExpression == null) continue
if (needSeparateVariable(argumentExpression)
&& PsiTreeUtil.getNonStrictParentOfType(
element,
KtConstructorDelegationCall::class.java,
KtSuperTypeListEntry::class.java,
KtParameter::class.java
) == null
) {
KotlinIntroduceVariableHandler.doRefactoring(
project, null, argumentExpression,
isVar = false,
occurrencesToReplace = listOf(argumentExpression),
onNonInteractiveFinish = {
argumentExpression = psiFactory.createExpression(it.name!!)
})
}
var expressionToReplace: KtExpression = nameCounterpartMap[ref.element] ?: continue
val parent = expressionToReplace.parent
if (parent is KtThisExpression) {
expressionToReplace = parent
}
if (addReceiver) {
val callExpression = expressionToReplace.getParentOfTypeAndBranch<KtCallExpression>(true) { calleeExpression }
when {
callExpression != null -> expressionToReplace = callExpression
parent is KtOperationExpression && parent.operationReference == expressionToReplace -> continue@loop
}
val replacement = psiFactory.createExpression("${argumentExpression!!.text}.${expressionToReplace.text}")
replacements.add(expressionToReplace to replacement)
} else {
replacements.add(expressionToReplace to argumentExpression!!)
}
}
// Sort by descending offset so that call arguments are replaced before call itself
ContainerUtil.sort(replacements, REVERSED_TEXT_OFFSET_COMPARATOR)
for ((expressionToReplace, replacingExpression) in replacements) {
val replaced = expressionToReplace.replaced(replacingExpression)
if (expressionToReplace == newExpression) {
newExpression = replaced
}
}
return newExpression
}
class ArgumentInfo(
val parameter: KotlinParameterInfo,
val parameterIndex: Int,
val resolvedArgument: ResolvedValueArgument?,
val receiverValue: ReceiverValue?
) {
private val mainValueArgument: ValueArgument?
get() = resolvedArgument?.arguments?.firstOrNull()
val wasNamed: Boolean
get() = mainValueArgument?.isNamed() ?: false
var name: String? = null
private set
fun makeNamed(callee: KotlinCallableDefinitionUsage<*>) {
name = parameter.getInheritedName(callee)
}
fun shouldSkip() = parameter.defaultValue != null && mainValueArgument == null
}
private fun getResolvedValueArgument(oldIndex: Int): ResolvedValueArgument? {
if (oldIndex < 0) return null
val parameterDescriptor = resolvedCall!!.resultingDescriptor.valueParameters[oldIndex]
return resolvedCall.valueArguments[parameterDescriptor]
}
private fun ArgumentInfo.getArgumentByDefaultValue(
element: KtCallElement,
allUsages: Array<out UsageInfo>,
psiFactory: KtPsiFactory
): KtValueArgument {
val isInsideOfCallerBody = element.isInsideOfCallerBody(allUsages)
val defaultValueForCall = parameter.defaultValueForCall
val argValue = when {
isInsideOfCallerBody -> psiFactory.createExpression(parameter.name)
defaultValueForCall != null -> substituteReferences(
defaultValueForCall,
parameter.defaultValueParameterReferences,
psiFactory,
).asMarkedForShortening()
else -> null
}
val argName = (if (isInsideOfCallerBody) null else name)?.let { Name.identifier(it) }
return psiFactory.createArgument(argValue ?: psiFactory.createExpression("0"), argName).apply {
if (argValue == null) {
getArgumentExpression()?.delete()
}
}
}
private fun ExpressionReceiver.wrapInvalidated(element: KtCallElement): ExpressionReceiver = object : ExpressionReceiver by this {
override val expression = element.getQualifiedExpressionForSelector()!!.receiverExpression
}
private fun updateArgumentsAndReceiver(
changeInfo: KotlinChangeInfo,
element: KtCallElement,
allUsages: Array<out UsageInfo>,
skipRedundantArgumentList: Boolean,
): KtElement {
if (isPropertyJavaUsage) return updateJavaPropertyCall(changeInfo, element)
val fullCallElement = element.getQualifiedExpressionForSelector() ?: element
val oldArguments = element.valueArguments
val newParameters = changeInfo.getNonReceiverParameters()
val purelyNamedCall = element is KtCallExpression && oldArguments.isNotEmpty() && oldArguments.all { it.isNamed() }
val newReceiverInfo = changeInfo.receiverParameterInfo
val originalReceiverInfo = changeInfo.methodDescriptor.receiver
val extensionReceiver = resolvedCall?.extensionReceiver
val dispatchReceiver = resolvedCall?.dispatchReceiver
// Do not add extension receiver to calls with explicit dispatch receiver except for objects
if (newReceiverInfo != null &&
fullCallElement is KtQualifiedExpression &&
dispatchReceiver is ExpressionReceiver
) {
if (isObjectReceiver(dispatchReceiver)) {
//It's safe to replace object reference with a new receiver, but we shall import the function
addDelayedImportRequest(changeInfo.method, element.containingKtFile)
} else {
return element
}
}
val newArgumentInfos = newParameters.asSequence().withIndex().map {
val (index, param) = it
val oldIndex = param.oldIndex
val resolvedArgument = if (oldIndex >= 0) getResolvedValueArgument(oldIndex) else null
var receiverValue = if (param == originalReceiverInfo) extensionReceiver else null
// Workaround for recursive calls where implicit extension receiver is transformed into ordinary value argument
// Receiver expression retained in the original resolved call is no longer valid at this point
if (receiverValue is ExpressionReceiver && !receiverValue.expression.isValid) {
receiverValue = receiverValue.wrapInvalidated(element)
}
ArgumentInfo(param, index, resolvedArgument, receiverValue)
}.toList()
val lastParameterIndex = newParameters.lastIndex
val canMixArguments = element.languageVersionSettings.supportsFeature(LanguageFeature.MixedNamedArgumentsInTheirOwnPosition)
var firstNamedIndex = newArgumentInfos.firstOrNull {
!canMixArguments && it.wasNamed ||
it.parameter.isNewParameter && it.parameter.defaultValue != null ||
it.resolvedArgument is VarargValueArgument && it.parameterIndex < lastParameterIndex
}?.parameterIndex
if (firstNamedIndex == null) {
val lastNonDefaultArgIndex = (lastParameterIndex downTo 0).firstOrNull { !newArgumentInfos[it].shouldSkip() } ?: -1
firstNamedIndex = (0..lastNonDefaultArgIndex).firstOrNull { newArgumentInfos[it].shouldSkip() }
}
val lastPositionalIndex = if (firstNamedIndex != null) firstNamedIndex - 1 else lastParameterIndex
val namedRange = lastPositionalIndex + 1..lastParameterIndex
for ((index, argument) in newArgumentInfos.withIndex()) {
if (purelyNamedCall || argument.wasNamed || index in namedRange) {
argument.makeNamed(callee)
}
}
val psiFactory = KtPsiFactory(element.project)
val newArgumentList = psiFactory.createCallArguments("()").apply {
for (argInfo in newArgumentInfos) {
if (argInfo.shouldSkip()) continue
val name = argInfo.name?.let { Name.identifier(it) }
if (argInfo.receiverValue != null) {
val receiverExpression = getReceiverExpression(argInfo.receiverValue, psiFactory) ?: continue
addArgument(psiFactory.createArgument(receiverExpression, name))
continue
}
when (val resolvedArgument = argInfo.resolvedArgument) {
null, is DefaultValueArgument -> addArgument(argInfo.getArgumentByDefaultValue(element, allUsages, psiFactory))
is ExpressionValueArgument -> {
val valueArgument = resolvedArgument.valueArgument
val newValueArgument: KtValueArgument = when {
valueArgument == null -> argInfo.getArgumentByDefaultValue(element, allUsages, psiFactory)
valueArgument is KtLambdaArgument -> psiFactory.createArgument(valueArgument.getArgumentExpression(), name)
valueArgument is KtValueArgument && valueArgument.getArgumentName()?.asName == name -> valueArgument
else -> psiFactory.createArgument(valueArgument.getArgumentExpression(), name)
}
addArgument(newValueArgument)
}
// TODO: Support Kotlin varargs
is VarargValueArgument -> resolvedArgument.arguments.forEach {
if (it is KtValueArgument) addArgument(it)
}
else -> return element
}
}
}
newArgumentList.arguments.singleOrNull()?.let {
if (it.getArgumentExpression() == null) {
newArgumentList.removeArgument(it)
}
}
val lastOldArgument = oldArguments.lastOrNull()
val lastNewParameter = newParameters.lastOrNull()
val lastNewArgument = newArgumentList.arguments.lastOrNull()
val oldLastResolvedArgument = getResolvedValueArgument(lastNewParameter?.oldIndex ?: -1) as? ExpressionValueArgument
val lambdaArgumentNotTouched = lastOldArgument is KtLambdaArgument && oldLastResolvedArgument?.valueArgument == lastOldArgument
val newLambdaArgumentAddedLast = lastNewParameter != null
&& lastNewParameter.isNewParameter
&& lastNewParameter.defaultValueForCall is KtLambdaExpression
&& lastNewArgument?.getArgumentExpression() is KtLambdaExpression
&& !lastNewArgument.isNamed()
if (lambdaArgumentNotTouched) {
newArgumentList.removeArgument(newArgumentList.arguments.last())
} else {
val lambdaArguments = element.lambdaArguments
if (lambdaArguments.isNotEmpty()) {
element.deleteChildRange(lambdaArguments.first(), lambdaArguments.last())
}
}
val oldArgumentList = element.valueArgumentList.sure { "Argument list is expected: " + element.text }
for (argument in replaceListPsiAndKeepDelimiters(changeInfo, oldArgumentList, newArgumentList) { arguments }.arguments) {
if (argument.getArgumentExpression() == null) argument.delete()
}
var newElement: KtElement = element
if (newReceiverInfo != originalReceiverInfo) {
val replacingElement: PsiElement = if (newReceiverInfo != null) {
val receiverArgument = getResolvedValueArgument(newReceiverInfo.oldIndex)?.arguments?.singleOrNull()
val extensionReceiverExpression = receiverArgument?.getArgumentExpression()
val defaultValueForCall = newReceiverInfo.defaultValueForCall
val receiver = extensionReceiverExpression?.let { psiFactory.createExpression(it.text) }
?: defaultValueForCall?.asMarkedForShortening()
?: psiFactory.createExpression("_")
psiFactory.createExpressionByPattern("$0.$1", receiver, element)
} else {
element.copy()
}
newElement = fullCallElement.replace(replacingElement) as KtElement
}
val newCallExpression = newElement.safeAs<KtExpression>()?.getPossiblyQualifiedCallExpression()
if (!lambdaArgumentNotTouched && newLambdaArgumentAddedLast) {
newCallExpression?.moveFunctionLiteralOutsideParentheses()
}
if (!skipRedundantArgumentList) {
newCallExpression?.valueArgumentList?.let {
if (RemoveEmptyParenthesesFromLambdaCallApplicator.applicator.isApplicableByPsi(it, it.project)) {
RemoveEmptyParenthesesFromLambdaCallApplicator.applicator.applyTo(
it, KotlinApplicatorInput.Empty, it.project, editor = null
)
}
}
}
newElement.flushElementsForShorteningToWaitList()
return newElement
}
private fun isObjectReceiver(dispatchReceiver: ReceiverValue) = dispatchReceiver.safeAs<ClassValueReceiver>()?.classQualifier?.descriptor?.kind == ClassKind.OBJECT
private fun changeArgumentNames(changeInfo: KotlinChangeInfo, element: KtCallElement) {
for (argument in element.valueArguments) {
val argumentName = argument.getArgumentName()
val argumentNameExpression = argumentName?.referenceExpression ?: continue
val oldParameterIndex = changeInfo.getOldParameterIndex(argumentNameExpression.getReferencedName()) ?: continue
val newParameterIndex = if (changeInfo.receiverParameterInfo != null) oldParameterIndex + 1 else oldParameterIndex
val parameterInfo = changeInfo.newParameters[newParameterIndex]
changeArgumentName(argumentNameExpression, parameterInfo)
}
}
private fun changeArgumentName(argumentNameExpression: KtSimpleNameExpression?, parameterInfo: KotlinParameterInfo) {
val identifier = argumentNameExpression?.getIdentifier() ?: return
val newName = parameterInfo.getInheritedName(callee)
identifier.replace(KtPsiFactory(project).createIdentifier(newName))
}
companion object {
private val REVERSED_TEXT_OFFSET_COMPARATOR = Comparator<Pair<KtElement, KtElement>> { p1, p2 ->
val offset1 = p1.first.startOffset
val offset2 = p2.first.startOffset
when {
offset1 < offset2 -> 1
offset1 > offset2 -> -1
else -> 0
}
}
private fun updateJavaPropertyCall(changeInfo: KotlinChangeInfo, element: KtCallElement): KtElement {
val newReceiverInfo = changeInfo.receiverParameterInfo
val originalReceiverInfo = changeInfo.methodDescriptor.receiver
if (newReceiverInfo == originalReceiverInfo) return element
val arguments = element.valueArgumentList.sure { "Argument list is expected: " + element.text }
val oldArguments = element.valueArguments
val psiFactory = KtPsiFactory(element.project)
val firstArgument = oldArguments.firstOrNull() as KtValueArgument?
when {
newReceiverInfo != null -> {
val defaultValueForCall = newReceiverInfo.defaultValueForCall ?: psiFactory.createExpression("_")
val newReceiverArgument = psiFactory.createArgument(defaultValueForCall, null, false)
if (originalReceiverInfo != null) {
firstArgument?.replace(newReceiverArgument)
} else {
arguments.addArgumentAfter(newReceiverArgument, null)
}
}
firstArgument != null -> arguments.removeArgument(firstArgument)
}
return element
}
private fun getReceiverExpression(receiver: ReceiverValue, psiFactory: KtPsiFactory): KtExpression? {
return when (receiver) {
is ExpressionReceiver -> receiver.expression
is ImplicitReceiver -> {
val descriptor = receiver.declarationDescriptor
val thisText = if (descriptor is ClassDescriptor && !DescriptorUtils.isAnonymousObject(descriptor)) {
"this@" + descriptor.name.asString()
} else {
"this"
}
psiFactory.createExpression(thisText)
}
else -> null
}
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinFunctionCallUsage.kt | 4000923392 |
// 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.debugger.surroundWith
import com.intellij.debugger.DebuggerInvocationUtil
import com.intellij.debugger.DebuggerManagerEx
import com.intellij.debugger.JavaDebuggerBundle
import com.intellij.debugger.impl.DebuggerContextImpl
import com.intellij.openapi.application.Result
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.surroundWith.KotlinExpressionSurrounder
import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinDebuggerEvaluationBundle
import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinRuntimeTypeEvaluator
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
class KotlinRuntimeTypeCastSurrounder : KotlinExpressionSurrounder() {
override fun isApplicable(expression: KtExpression): Boolean {
if (!super.isApplicable(expression)) return false
if (!expression.isPhysical) return false
val file = expression.containingFile
if (file !is KtCodeFragment) return false
val type = expression.analyze(BodyResolveMode.PARTIAL).getType(expression) ?: return false
return TypeUtils.canHaveSubtypes(KotlinTypeChecker.DEFAULT, type)
}
override fun surroundExpression(project: Project, editor: Editor, expression: KtExpression): TextRange? {
val debuggerContext = DebuggerManagerEx.getInstanceEx(project).context
val debuggerSession = debuggerContext.debuggerSession
if (debuggerSession != null) {
val progressWindow = ProgressWindow(true, expression.project)
val worker = SurroundWithCastWorker(editor, expression, debuggerContext, progressWindow)
progressWindow.title = JavaDebuggerBundle.message("title.evaluating")
debuggerContext.debugProcess?.managerThread?.startProgress(worker, progressWindow)
}
return null
}
override fun getTemplateDescription(): String {
return KotlinDebuggerEvaluationBundle.message("surround.with.runtime.type.cast.template")
}
private inner class SurroundWithCastWorker(
private val myEditor: Editor,
expression: KtExpression,
context: DebuggerContextImpl,
indicator: ProgressIndicator
) : KotlinRuntimeTypeEvaluator(myEditor, expression, context, indicator) {
override fun typeCalculationFinished(type: KotlinType?) {
if (type == null) return
hold()
val project = myEditor.project
DebuggerInvocationUtil.invokeLater(project, Runnable {
object : WriteCommandAction<Any>(project, JavaDebuggerBundle.message("command.name.surround.with.runtime.cast")) {
override fun run(result: Result<in Any>) {
try {
val factory = KtPsiFactory(myElement.project)
val fqName = DescriptorUtils.getFqName(type.constructor.declarationDescriptor!!)
val parentCast = factory.createExpression("(expr as " + fqName.asString() + ")") as KtParenthesizedExpression
val cast = parentCast.expression as KtBinaryExpressionWithTypeRHS
cast.left.replace(myElement)
val expr = myElement.replace(parentCast) as KtExpression
ShortenReferences.DEFAULT.process(expr)
val range = expr.textRange
myEditor.selectionModel.setSelection(range.startOffset, range.endOffset)
myEditor.caretModel.moveToOffset(range.endOffset)
myEditor.scrollingModel.scrollToCaret(ScrollType.RELATIVE)
} finally {
release()
}
}
}.execute()
}, myProgressIndicator.modalityState)
}
}
}
| plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/surroundWith/KotlinRuntimeTypeCastSurrounder.kt | 3706089071 |
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.idea.util.isExplicitTypeReferenceNeededForTypeInference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
open class RemovePsiElementSimpleFix private constructor(element: PsiElement, @Nls private val text: String) :
KotlinPsiOnlyQuickFixAction<PsiElement>(element) {
override fun getFamilyName() = KotlinBundle.message("remove.element")
override fun getText() = text
public override fun invoke(project: Project, editor: Editor?, file: KtFile) {
element?.delete()
}
object RemoveImportFactory : QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) {
public override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> {
val directive = psiElement.getNonStrictParentOfType<KtImportDirective>() ?: return emptyList()
val refText = directive.importedReference?.let { KotlinBundle.message("for.0", it.text) } ?: ""
return listOf(RemovePsiElementSimpleFix(directive, KotlinBundle.message("remove.conflicting.import.0", refText)))
}
}
object RemoveSpreadFactory : QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) {
public override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> {
val element = psiElement
if (element.node.elementType != KtTokens.MUL) return emptyList()
return listOf(RemovePsiElementSimpleFix(element, KotlinBundle.message("remove.star")))
}
}
object RemoveTypeArgumentsFactory :
QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) {
public override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> {
val element = psiElement.getNonStrictParentOfType<KtTypeArgumentList>() ?: return emptyList()
return listOf(RemovePsiElementSimpleFix(element, KotlinBundle.message("remove.type.arguments")))
}
}
object RemoveTypeParametersFactory :
QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) {
public override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> {
// FIR passes the KtProperty while FE1.0 passes the type parameter list.
val element = if (psiElement is KtProperty) {
psiElement.typeParameterList
} else {
psiElement.getNonStrictParentOfType<KtTypeParameterList>()
} ?: return emptyList()
return listOf(RemovePsiElementSimpleFix(element, KotlinBundle.message("remove.type.parameters")))
}
}
object RemoveVariableFactory : QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) {
public override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> {
if (psiElement is KtDestructuringDeclarationEntry) return emptyList()
val ktProperty = psiElement.getNonStrictParentOfType<KtProperty>() ?: return emptyList()
if (ktProperty.isExplicitTypeReferenceNeededForTypeInference()) return emptyList()
val removePropertyFix = object : RemovePsiElementSimpleFix(ktProperty, KotlinBundle.message("remove.variable.0", ktProperty.name.toString())) {
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
removeProperty(element as? KtProperty ?: return)
}
}
return listOf(removePropertyFix)
}
fun removeProperty(ktProperty: KtProperty) {
val initializer = ktProperty.initializer
if (initializer != null && initializer !is KtConstantExpression) {
val commentSaver = CommentSaver(ktProperty)
val replaced = ktProperty.replace(initializer)
commentSaver.restore(replaced)
} else {
ktProperty.delete()
}
}
}
}
| plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/RemovePsiElementSimpleFix.kt | 566690863 |
package de.stefanmedack.ccctv.ui.search
import android.arch.lifecycle.ViewModel
import de.stefanmedack.ccctv.persistence.toEntity
import de.stefanmedack.ccctv.ui.search.uiModels.SearchResultUiModel
import de.stefanmedack.ccctv.util.EMPTY_STRING
import de.stefanmedack.ccctv.util.applySchedulers
import info.metadude.kotlin.library.c3media.RxC3MediaService
import io.reactivex.Observable
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class SearchViewModel @Inject constructor(
private val c3MediaService: RxC3MediaService
) : ViewModel() {
fun bindSearch(searchQueryChanges: Observable<String>): Observable<SearchResultUiModel> = searchQueryChanges
.debounce(333, TimeUnit.MILLISECONDS)
.flatMap {
if (it.length > 1)
this.loadSearchResult(it)
else
Observable.just(SearchResultUiModel(showResults = false))
}
private fun loadSearchResult(searchTerm: String): Observable<SearchResultUiModel>? = c3MediaService
.searchEvents(searchTerm)
.applySchedulers()
.map { SearchResultUiModel(searchTerm, it.events.mapNotNull { it.toEntity(EMPTY_STRING) }) }
.toObservable()
} | app/src/main/java/de/stefanmedack/ccctv/ui/search/SearchViewModel.kt | 2267581804 |
// "Create class 'Foo'" "true"
// ERROR: Unresolved reference: Foo
class A(val n: Int)
fun test() = J.Foo(abc = 1, ghi = A(2), def = "s") | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/callExpression/callWithExplicitParamNamesAndJavaQualifier.after.kt | 3173914533 |
// WITH_STDLIB
val x by lazy {
1
}<caret> | plugins/kotlin/idea/tests/testData/intentions/convertLazyPropertyToOrdinary/singleStatement2.kt | 3347073401 |
// 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 com.intellij.internal.statistic.eventLog
import com.jetbrains.fus.reporting.model.lion3.LogEvent
import com.jetbrains.fus.reporting.model.lion3.LogEventAction
interface StatisticsEventMergeStrategy {
fun shouldMerge(lastEvent: LogEvent, newEvent: LogEvent): Boolean
}
class FilteredEventMergeStrategy(private val ignoredFields: Set<String>) : StatisticsEventMergeStrategy {
override fun shouldMerge(lastEvent: LogEvent, newEvent: LogEvent): Boolean {
if (lastEvent.session != newEvent.session) return false
if (lastEvent.bucket != newEvent.bucket) return false
if (lastEvent.build != newEvent.build) return false
if (lastEvent.recorderVersion != newEvent.recorderVersion) return false
if (lastEvent.group.id != newEvent.group.id) return false
if (lastEvent.group.version != newEvent.group.version) return false
if (!shouldMergeEvents(lastEvent.event, newEvent.event)) return false
return true
}
private fun shouldMergeEvents(lastEvent: LogEventAction, newEvent: LogEventAction): Boolean {
if (lastEvent.state || newEvent.state) return false
if (lastEvent.id != newEvent.id) return false
if (lastEvent.data.size != newEvent.data.size) return false
for (datum in lastEvent.data) {
val key = datum.key
if (!ignoredFields.contains(key)) {
val value = newEvent.data[key]
if (value == null || value != datum.value) return false
}
}
return true
}
} | platform/statistics/src/com/intellij/internal/statistic/eventLog/StatisticsEventMergeStrategy.kt | 2420262872 |
// 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 training.featuresSuggester
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.parents
import com.intellij.xdebugger.XDebuggerManager
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.breakpoints.XBreakpoint
import com.intellij.xdebugger.breakpoints.XLineBreakpoint
import training.featuresSuggester.actions.Action
import training.featuresSuggester.settings.FeatureSuggesterSettings
import java.awt.datatransfer.DataFlavor
import java.awt.datatransfer.Transferable
import java.awt.datatransfer.UnsupportedFlavorException
import java.io.IOException
data class TextFragment(val startOffset: Int, val endOffset: Int, val text: String)
internal object SuggestingUtils {
var forceShowSuggestions: Boolean
get() = Registry.`is`("feature.suggester.force.show.suggestions", false)
set(value) = Registry.get("feature.suggester.force.show.suggestions").setValue(value)
fun isActionsProcessingEnabled(project: Project): Boolean {
return !project.isDisposed && !DumbService.isDumb(project) && FeatureSuggesterSettings.instance().isAnySuggesterEnabled
}
fun handleAction(project: Project, action: Action) {
if (isActionsProcessingEnabled(project)) {
project.getService(FeatureSuggestersManager::class.java)?.actionPerformed(action)
}
}
fun findBreakpointOnPosition(project: Project, position: XSourcePosition): XBreakpoint<*>? {
val breakpointManager = XDebuggerManager.getInstance(project)?.breakpointManager ?: return null
return breakpointManager.allBreakpoints.find { b ->
b is XLineBreakpoint<*> && b.fileUrl == position.file.url && b.line == position.line
}
}
fun Transferable.asString(): String? {
return try {
getTransferData(DataFlavor.stringFlavor) as? String
}
catch (ex: IOException) {
null
}
catch (ex: UnsupportedFlavorException) {
null
}
}
fun Editor.getSelection(): TextFragment? {
with(selectionModel) {
return if (selectedText != null) {
TextFragment(selectionStart, selectionEnd, selectedText!!)
}
else {
null
}
}
}
}
inline fun <reified T : PsiElement> PsiElement.getParentOfType(): T? {
return PsiTreeUtil.getParentOfType(this, T::class.java)
}
fun PsiElement.getParentByPredicate(predicate: (PsiElement) -> Boolean): PsiElement? {
return parents(true).find(predicate)
}
| plugins/ide-features-trainer/src/training/featuresSuggester/SuggestingUtils.kt | 1533305007 |
// IS_APPLICABLE: false
// WITH_STDLIB
fun test(xs: List<String>) {
for (x in xs) {
x.isNotEmpty() ||<caret> (break)
}
} | plugins/kotlin/idea/tests/testData/intentions/convertBinaryExpressionWithDemorgansLaw/hasBreak.kt | 3038095443 |
// 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.debugger.coroutine.proxy
import org.jetbrains.kotlin.idea.debugger.coroutine.data.CoroutineInfoData
interface CoroutineInfoProvider {
fun dumpCoroutinesInfo(): List<CoroutineInfoData>
}
| plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/CoroutineInfoProvider.kt | 4128266717 |
import newPack.newFun
fun x() {
newFun(1 + 1)
newFun(2 + 1)
}
fun y() {
newFun(3 + 1)
}
| plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/wholeProject/function.after.1.kt | 2219307165 |
// DISABLE-ERRORS
// WITH_STDLIB
<caret>var x: Int by lazy { 1 } | plugins/kotlin/idea/tests/testData/intentions/convertLazyPropertyToOrdinary/var.kt | 200203902 |
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtProperty
// OPTIONS: usages
package server
class A {
companion object {
var <caret>foo: String = "foo"
}
}
| plugins/kotlin/idea/tests/testData/findUsages/kotlin/findPropertyUsages/javaClassObjectPropertyUsages2.0.kt | 1508376989 |
interface T {
fun foo(a: () -> Any): T = this
}
fun foo(t: T) {
t.foo { <caret>1 }
.foo {2}
.foo({ 3 })
}
/*
1
{ 1 }
t.foo{...}
t.foo{...}.foo{...}
t.foo{...}.foo{...}.foo(...)
*/ | plugins/kotlin/idea/tests/testData/smartSelection/lambdaCalls.kt | 2493719424 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.merge
abstract class GitMergeProviderTestBase : GitMergeProviderTestCase() {
protected abstract fun `invoke conflicting operation`(branchCurrent: String, branchLast: String)
fun `test merge - change vs change`() {
`init branch - change`("A")
`init branch - change`("B")
`invoke conflicting operation`("A", "B")
`assert all revisions and paths loaded`("A", "B")
}
fun `test merge - change vs change and rename`() {
`init branch - change`("A")
`init branch - change and rename`("B")
`invoke conflicting operation`("A", "B")
`assert all revisions and paths loaded`("A", "B")
}
fun `test merge - change and rename vs change`() {
`init branch - change and rename`("A")
`init branch - change`("B")
`invoke conflicting operation`("A", "B")
`assert all revisions and paths loaded`("A", "B")
}
fun `test merge - change and rename vs change and rename - same renames`() {
`init branch - change and rename`("A")
`init branch - change and rename`("B")
`invoke conflicting operation`("A", "B")
`assert all revisions and paths loaded`("A", "B")
}
fun `test change vs deleted`() {
`init branch - change`("A")
`init branch - delete`("B")
`invoke conflicting operation`("A", "B")
`assert all revisions loaded`("A", "B")
`assert revision GOOD, path GOOD`(Side.ORIGINAL)
`assert revision GOOD, path BAD `(Side.LAST)
`assert revision GOOD, path GOOD`(Side.CURRENT)
}
fun `test deleted vs change`() {
`init branch - delete`("A")
`init branch - change`("B")
`invoke conflicting operation`("A", "B")
`assert all revisions loaded`("A", "B")
`assert revision GOOD, path GOOD`(Side.ORIGINAL)
`assert revision GOOD, path GOOD`(Side.LAST)
`assert revision GOOD, path BAD `(Side.CURRENT)
}
fun `test rename vs deleted`() {
`init branch - rename`("A")
`init branch - delete`("B")
`invoke conflicting operation`("A", "B")
`assert all revisions loaded`("A", "B")
if (gitUsingOrtMergeAlg()) {
`assert revision GOOD, path GOOD`(Side.ORIGINAL)
`assert revision GOOD, path BAD `(Side.LAST)
`assert revision GOOD, path GOOD`(Side.CURRENT)
}
else {
`assert revision GOOD, path BAD `(Side.ORIGINAL)
`assert revision GOOD, path BAD `(Side.LAST)
`assert revision GOOD, path GOOD`(Side.CURRENT)
}
}
fun `test deleted vs rename`() {
`init branch - delete`("A")
`init branch - rename`("B")
`invoke conflicting operation`("A", "B")
`assert all revisions loaded`("A", "B")
if (gitUsingOrtMergeAlg()) {
`assert revision GOOD, path GOOD`(Side.ORIGINAL)
`assert revision GOOD, path GOOD`(Side.LAST)
`assert revision GOOD, path BAD `(Side.CURRENT)
}
else {
`assert revision GOOD, path BAD `(Side.ORIGINAL)
`assert revision GOOD, path GOOD`(Side.LAST)
`assert revision GOOD, path BAD `(Side.CURRENT)
}
}
}
| plugins/git4idea/tests/git4idea/merge/GitMergeProviderTestBase.kt | 669396084 |
package com.jetbrains.packagesearch.intellij.plugin.gradle.configuration
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.util.xmlb.annotations.OptionTag
import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration
@State(
name = "PackageSearchGradleConfiguration",
storages = [(Storage(PackageSearchGeneralConfiguration.StorageFileName))],
)
internal class PackageSearchGradleConfiguration : BaseState(), PersistentStateComponent<PackageSearchGradleConfiguration> {
companion object {
@JvmStatic
fun getInstance(project: Project) = project.service<PackageSearchGradleConfiguration>()
}
override fun getState(): PackageSearchGradleConfiguration = this
override fun loadState(state: PackageSearchGradleConfiguration) {
this.copyFrom(state)
}
@get:OptionTag("GRADLE_SCOPES")
var gradleScopes by string(PackageSearchGradleConfigurationDefaults.GradleScopes)
@get:OptionTag("GRADLE_SCOPES_DEFAULT")
var defaultGradleScope by string(PackageSearchGradleConfigurationDefaults.GradleDefaultScope)
@get:OptionTag("UPDATE_SCOPES_ON_USE")
var updateScopesOnUsage by property(true)
fun determineDefaultGradleScope(): String =
if (!defaultGradleScope.isNullOrEmpty()) {
defaultGradleScope!!
} else {
PackageSearchGradleConfigurationDefaults.GradleDefaultScope
}
fun addGradleScope(scope: String) {
val currentScopes = getGradleScopes()
if (!currentScopes.contains(scope)) {
gradleScopes = currentScopes.joinToString(",") + ",$scope"
this.incrementModificationCount()
}
}
fun getGradleScopes(): List<String> {
var scopes = gradleScopes.orEmpty().split(",", ";", "\n")
.map { it.trim() }
.filter { it.isNotEmpty() }
if (scopes.isEmpty()) {
scopes = PackageSearchGradleConfigurationDefaults.GradleScopes.split(",", ";", "\n")
.map { it.trim() }
.filter { it.isNotEmpty() }
}
return scopes
}
}
| plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/gradle/configuration/PackageSearchGradleConfiguration.kt | 1236254090 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.authentication.util
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.util.Url
import com.intellij.util.Urls.newUrl
import org.jetbrains.plugins.github.api.*
import org.jetbrains.plugins.github.api.data.GithubAuthenticatedUser
object GHSecurityUtil {
private const val REPO_SCOPE = "repo"
private const val GIST_SCOPE = "gist"
private const val READ_ORG_SCOPE = "read:org"
private const val WORKFLOW_SCOPE = "workflow"
val MASTER_SCOPES = listOf(REPO_SCOPE, GIST_SCOPE, READ_ORG_SCOPE, WORKFLOW_SCOPE)
const val DEFAULT_CLIENT_NAME = "Github Integration Plugin"
@JvmStatic
internal fun loadCurrentUserWithScopes(executor: GithubApiRequestExecutor,
progressIndicator: ProgressIndicator,
server: GithubServerPath): Pair<GithubAuthenticatedUser, String?> {
var scopes: String? = null
val details = executor.execute(progressIndicator,
object : GithubApiRequest.Get.Json<GithubAuthenticatedUser>(
GithubApiRequests.getUrl(server,
GithubApiRequests.CurrentUser.urlSuffix),
GithubAuthenticatedUser::class.java) {
override fun extractResult(response: GithubApiResponse): GithubAuthenticatedUser {
scopes = response.findHeader("X-OAuth-Scopes")
return super.extractResult(response)
}
}.withOperationName("get profile information"))
return details to scopes
}
@JvmStatic
internal fun isEnoughScopes(grantedScopes: String): Boolean {
val scopesArray = grantedScopes.split(", ")
if (scopesArray.isEmpty()) return false
if (!scopesArray.contains(REPO_SCOPE)) return false
if (!scopesArray.contains(GIST_SCOPE)) return false
if (scopesArray.none { it.endsWith(":org") }) return false
return true
}
internal fun buildNewTokenUrl(server: GithubServerPath): String {
val productName = ApplicationNamesInfo.getInstance().fullProductName
return server
.append("settings/tokens/new")
.addParameters(mapOf(
"description" to "$productName GitHub integration plugin",
"scopes" to MASTER_SCOPES.joinToString(",")
))
.toExternalForm()
}
private fun GithubServerPath.append(path: String): Url =
newUrl(schema, host + port?.let { ":$it" }.orEmpty(), suffix.orEmpty() + "/" + path)
} | plugins/github/src/org/jetbrains/plugins/github/authentication/util/GHSecurityUtil.kt | 126849351 |
package com.intellij.aws.cloudformation.inspections
import com.intellij.aws.cloudformation.CloudFormationInspections
import com.intellij.aws.cloudformation.CloudFormationParser
import com.intellij.aws.cloudformation.CloudFormationPsiUtils
import com.intellij.codeInspection.*
import com.intellij.psi.PsiFile
abstract class FormatViolationInspection : LocalInspectionTool() {
override fun runForWholeFile(): Boolean = true
override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? {
if (!CloudFormationPsiUtils.isCloudFormationFile(file)) {
return null
}
val parsed = CloudFormationParser.parse(file)
val inspected = CloudFormationInspections.inspectFile(parsed)
val problems = parsed.problems.plus(inspected.problems).map {
manager.createProblemDescriptor(
it.element,
it.description,
isOnTheFly,
LocalQuickFix.EMPTY_ARRAY,
ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
}
return problems.toTypedArray()
}
override fun getStaticDescription(): String? = ""
}
class JsonFormatViolationInspection: FormatViolationInspection()
class YamlFormatViolationInspection: FormatViolationInspection()
| src/main/kotlin/com/intellij/aws/cloudformation/inspections/FormatViolationInspection.kt | 2728277907 |
/*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.ui.player
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentPagerAdapter
import android.view.View
import com.gigamole.navigationtabstrip.NavigationTabStrip
import com.sinyuk.fanfou.R
import com.sinyuk.fanfou.base.AbstractFragment
import com.sinyuk.fanfou.di.Injectable
import com.sinyuk.fanfou.domain.DO.Player
import com.sinyuk.fanfou.domain.TIMELINE_FAVORITES
import com.sinyuk.fanfou.domain.TIMELINE_USER
import com.sinyuk.fanfou.ui.photo.PhotoGridView
import com.sinyuk.fanfou.ui.timeline.TimelineView
import kotlinx.android.synthetic.main.navigation_view.*
/**
* Created by sinyuk on 2017/12/23.
*
*/
class NavigationView : AbstractFragment(), Injectable {
override fun layoutId() = R.layout.navigation_view
companion object {
fun newInstance(player: Player?) = NavigationView().apply {
arguments = Bundle().apply { putParcelable("player", player) }
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
assert(arguments != null)
val player = arguments!!.getParcelable<Player>("player")!!
fragmentList = arrayListOf(TimelineView.playerTimeline(TIMELINE_USER, player), PhotoGridView.newInstance(player), TimelineView.playerTimeline(TIMELINE_FAVORITES, player))
setupViewPager()
}
lateinit var fragmentList: MutableList<Fragment>
private fun setupViewPager() {
viewPager.offscreenPageLimit = fragmentList.size - 1
viewPager.adapter = object : FragmentPagerAdapter(childFragmentManager) {
override fun getItem(position: Int) = fragmentList[position]
override fun getCount() = fragmentList.size
}
tabStrip.setTabIndex(0, true)
tabStrip.onTabStripSelectedIndexListener = object : NavigationTabStrip.OnTabStripSelectedIndexListener {
override fun onStartTabSelected(title: String?, index: Int) {
}
override fun onEndTabSelected(title: String?, index: Int) {
viewPager.setCurrentItem(index, false)
}
}
}
} | presentation/src/main/java/com/sinyuk/fanfou/ui/player/NavigationView.kt | 1307637617 |
/*
* Copyright 2017-2022 Adobe.
*
* 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.adobe.testing.s3mock.its
import com.adobe.testing.s3mock.util.DigestUtil
import com.amazonaws.ClientConfiguration
import com.amazonaws.auth.AWSStaticCredentialsProvider
import com.amazonaws.auth.BasicAWSCredentials
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration
import com.amazonaws.services.s3.AmazonS3
import com.amazonaws.services.s3.AmazonS3ClientBuilder
import com.amazonaws.services.s3.model.PutObjectRequest
import com.amazonaws.services.s3.model.PutObjectResult
import com.amazonaws.services.s3.transfer.TransferManager
import com.amazonaws.services.s3.transfer.TransferManagerBuilder
import org.apache.http.conn.ssl.NoopHostnameVerifier
import org.apache.http.conn.ssl.SSLConnectionSocketFactory
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.TestInfo
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider
import software.amazon.awssdk.core.ResponseInputStream
import software.amazon.awssdk.core.sync.RequestBody
import software.amazon.awssdk.http.SdkHttpConfigurationOption
import software.amazon.awssdk.http.apache.ApacheHttpClient
import software.amazon.awssdk.regions.Region
import software.amazon.awssdk.services.s3.S3Client
import software.amazon.awssdk.services.s3.S3Configuration
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest
import software.amazon.awssdk.services.s3.model.Bucket
import software.amazon.awssdk.services.s3.model.CreateBucketRequest
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest
import software.amazon.awssdk.services.s3.model.DeleteObjectResponse
import software.amazon.awssdk.services.s3.model.EncodingType
import software.amazon.awssdk.services.s3.model.GetObjectLockConfigurationRequest
import software.amazon.awssdk.services.s3.model.GetObjectRequest
import software.amazon.awssdk.services.s3.model.GetObjectResponse
import software.amazon.awssdk.services.s3.model.HeadBucketRequest
import software.amazon.awssdk.services.s3.model.ListMultipartUploadsRequest
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request
import software.amazon.awssdk.services.s3.model.MultipartUpload
import software.amazon.awssdk.services.s3.model.ObjectLockEnabled
import software.amazon.awssdk.services.s3.model.ObjectLockLegalHold
import software.amazon.awssdk.services.s3.model.ObjectLockLegalHoldStatus
import software.amazon.awssdk.services.s3.model.PutObjectLegalHoldRequest
import software.amazon.awssdk.services.s3.model.PutObjectResponse
import software.amazon.awssdk.services.s3.model.S3Exception
import software.amazon.awssdk.services.s3.model.S3Object
import software.amazon.awssdk.utils.AttributeMap
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream
import java.net.Socket
import java.net.URI
import java.security.KeyManagementException
import java.security.NoSuchAlgorithmException
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.time.Instant
import java.util.Random
import java.util.UUID
import java.util.concurrent.Executors
import java.util.concurrent.ThreadFactory
import java.util.function.Consumer
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLEngine
import javax.net.ssl.TrustManager
import javax.net.ssl.X509ExtendedTrustManager
/**
* Base type for S3 Mock integration tests. Sets up S3 Client, Certificates, initial Buckets, etc.
*/
internal abstract class S3TestBase {
lateinit var s3Client: AmazonS3
lateinit var s3ClientV2: S3Client
/**
* Configures the S3-Client to be used in the Test. Sets the SSL context to accept untrusted SSL
* connections.
*/
@BeforeEach
open fun prepareS3Client() {
s3Client = defaultTestAmazonS3ClientBuilder().build()
s3ClientV2 = createS3ClientV2()
}
protected fun defaultTestAmazonS3ClientBuilder(): AmazonS3ClientBuilder {
return AmazonS3ClientBuilder.standard()
.withCredentials(AWSStaticCredentialsProvider(BasicAWSCredentials(accessKeyId, secretAccessKey)))
.withClientConfiguration(ignoringInvalidSslCertificates(ClientConfiguration()))
.withEndpointConfiguration(
EndpointConfiguration(serviceEndpoint, s3Region)
)
.enablePathStyleAccess()
}
protected val randomName: String
get() = UUID.randomUUID().toString()
protected fun bucketName(testInfo: TestInfo): String {
val methodName = testInfo.testMethod.get().name
var normalizedName = methodName.lowercase().replace('_', '-')
if (normalizedName.length > 50) {
//max bucket name length is 63, shorten name to 50 since we add the timestamp below.
normalizedName = normalizedName.substring(0,50)
}
val timestamp = Instant.now().epochSecond
return "$normalizedName-$timestamp"
}
protected val serviceEndpoint: String
get() = s3Endpoint ?: "https://$host:$port"
protected fun createS3ClientV2(): S3Client {
return S3Client.builder()
.region(Region.of(s3Region))
.credentialsProvider(
StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKeyId, secretAccessKey))
)
.serviceConfiguration(S3Configuration.builder().pathStyleAccessEnabled(true).build())
.endpointOverride(URI.create(serviceEndpoint))
.httpClient(
ApacheHttpClient.builder().buildWithDefaults(
AttributeMap.builder()
.put(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES, true)
.build()
)
)
.build()
}
/**
* Deletes all existing buckets.
*/
@AfterEach
fun cleanupStores() {
for (bucket in s3ClientV2.listBuckets().buckets()) {
//Empty all buckets
deleteMultipartUploads(bucket)
deleteObjectsInBucket(bucket, isObjectLockEnabled(bucket))
//Delete all "non-initial" buckets.
if (!INITIAL_BUCKET_NAMES.contains(bucket.name())) {
deleteBucket(bucket)
}
}
}
fun givenBucketV1(testInfo: TestInfo): String {
val bucketName = bucketName(testInfo)
return givenBucketV1(bucketName)
}
private fun givenBucketV1(bucketName: String): String {
s3Client.createBucket(bucketName)
return bucketName
}
fun givenRandomBucketV1(): String {
return givenBucketV1(randomName)
}
private fun givenObjectV1(bucketName: String, key: String): PutObjectResult {
val uploadFile = File(key)
return s3Client.putObject(PutObjectRequest(bucketName, key, uploadFile))
}
fun givenBucketAndObjectV1(testInfo: TestInfo, key: String): Pair<String, PutObjectResult> {
val bucketName = givenBucketV1(testInfo)
val putObjectResult = givenObjectV1(bucketName, key)
return Pair(bucketName, putObjectResult)
}
fun givenBucketV2(testInfo: TestInfo): String {
val bucketName = bucketName(testInfo)
return givenBucketV2(bucketName)
}
fun givenBucketV2(bucketName: String): String {
s3ClientV2.createBucket(CreateBucketRequest.builder().bucket(bucketName).build())
return bucketName
}
fun givenRandomBucketV2(): String {
return givenBucketV2(randomName)
}
fun givenObjectV2(bucketName: String, key: String): PutObjectResponse {
val uploadFile = File(key)
return s3ClientV2.putObject(
software.amazon.awssdk.services.s3.model.PutObjectRequest.builder()
.bucket(bucketName).key(key).build(),
RequestBody.fromFile(uploadFile)
)
}
fun deleteObjectV2(bucketName: String, key: String): DeleteObjectResponse {
return s3ClientV2.deleteObject(
DeleteObjectRequest.builder().bucket(bucketName).key(key).build()
)
}
fun getObjectV2(bucketName: String, key: String): ResponseInputStream<GetObjectResponse> {
return s3ClientV2.getObject(
GetObjectRequest.builder().bucket(bucketName).key(key).build()
)
}
fun givenBucketAndObjectV2(testInfo: TestInfo, key: String): Pair<String, PutObjectResponse> {
val bucketName = givenBucketV2(testInfo)
val putObjectResponse = givenObjectV2(bucketName, key)
return Pair(bucketName, putObjectResponse)
}
private fun deleteBucket(bucket: Bucket) {
s3ClientV2.deleteBucket(DeleteBucketRequest.builder().bucket(bucket.name()).build())
val bucketDeleted = s3ClientV2.waiter()
.waitUntilBucketNotExists(HeadBucketRequest.builder().bucket(bucket.name()).build())
val bucketDeletedResponse = bucketDeleted.matched().exception().get()
assertThat(bucketDeletedResponse).isNotNull
}
private fun deleteObjectsInBucket(bucket: Bucket, objectLockEnabled: Boolean) {
s3ClientV2.listObjectsV2(
ListObjectsV2Request.builder().bucket(bucket.name()).encodingType(EncodingType.URL).build()
).contents().forEach(
Consumer { s3Object: S3Object ->
if (objectLockEnabled) {
//must remove potential legal hold, otherwise object can't be deleted
s3ClientV2.putObjectLegalHold(
PutObjectLegalHoldRequest
.builder()
.bucket(bucket.name())
.key(s3Object.key())
.legalHold(
ObjectLockLegalHold.builder().status(ObjectLockLegalHoldStatus.OFF).build()
)
.build()
)
}
s3ClientV2.deleteObject(
DeleteObjectRequest.builder().bucket(bucket.name()).key(s3Object.key()).build()
)
})
}
private fun isObjectLockEnabled(bucket: Bucket): Boolean {
return try {
ObjectLockEnabled.ENABLED == s3ClientV2.getObjectLockConfiguration(
GetObjectLockConfigurationRequest.builder().bucket(bucket.name()).build()
).objectLockConfiguration().objectLockEnabled()
} catch (e: S3Exception) {
//#getObjectLockConfiguration throws S3Exception if not set
false
}
}
private fun deleteMultipartUploads(bucket: Bucket) {
s3ClientV2.listMultipartUploads(
ListMultipartUploadsRequest.builder().bucket(bucket.name()).build()
).uploads().forEach(Consumer { upload: MultipartUpload ->
s3ClientV2.abortMultipartUpload(
AbortMultipartUploadRequest.builder().bucket(bucket.name()).key(upload.key())
.uploadId(upload.uploadId()).build()
)
}
)
}
private val s3Endpoint: String?
get() = System.getProperty("it.s3mock.endpoint", null)
private val accessKeyId: String
get() = System.getProperty("it.s3mock.access.key.id", "foo")
private val secretAccessKey: String
get() = System.getProperty("it.s3mock.secret.access.key", "bar")
private val s3Region: String
get() = System.getProperty("it.s3mock.region", "us-east-1")
private val port: Int
get() = Integer.getInteger("it.s3mock.port_https", 9191)
protected val host: String
get() = System.getProperty("it.s3mock.host", "localhost")
protected val httpPort: Int
get() = Integer.getInteger("it.s3mock.port_http", 9090)
private fun ignoringInvalidSslCertificates(clientConfiguration: ClientConfiguration):
ClientConfiguration {
clientConfiguration.apacheHttpClientConfig
.withSslSocketFactory(
SSLConnectionSocketFactory(
createBlindlyTrustingSslContext(),
NoopHostnameVerifier.INSTANCE
)
)
return clientConfiguration
}
private fun createBlindlyTrustingSslContext(): SSLContext {
return try {
val sc = SSLContext.getInstance("TLS")
sc.init(null, arrayOf<TrustManager>(object : X509ExtendedTrustManager() {
override fun getAcceptedIssuers(): Array<X509Certificate> {
return arrayOf()
}
override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) {
// no-op
}
override fun checkClientTrusted(
arg0: Array<X509Certificate>, arg1: String,
arg2: SSLEngine
) {
// no-op
}
override fun checkClientTrusted(
arg0: Array<X509Certificate>, arg1: String,
arg2: Socket
) {
// no-op
}
override fun checkServerTrusted(
arg0: Array<X509Certificate>, arg1: String,
arg2: SSLEngine
) {
// no-op
}
override fun checkServerTrusted(
arg0: Array<X509Certificate>, arg1: String,
arg2: Socket
) {
// no-op
}
override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) {
// no-op
}
}
), SecureRandom())
sc
} catch (e: NoSuchAlgorithmException) {
throw RuntimeException("Unexpected exception", e)
} catch (e: KeyManagementException) {
throw RuntimeException("Unexpected exception", e)
}
}
fun createTransferManager(): TransferManager {
val threadFactory: ThreadFactory = object : ThreadFactory {
private var threadCount = 1
override fun newThread(r: Runnable): Thread {
val thread = Thread(r)
thread.name = "s3-transfer-" + threadCount++
return thread
}
}
return TransferManagerBuilder.standard()
.withS3Client(s3Client)
.withExecutorFactory { Executors.newFixedThreadPool(THREAD_COUNT, threadFactory) }
.build()
}
fun randomInputStream(size: Int): InputStream {
val content = ByteArray(size)
Random().nextBytes(content)
return ByteArrayInputStream(content)
}
fun verifyObjectContent(uploadFile: File, s3Object: com.amazonaws.services.s3.model.S3Object) {
val uploadFileIs: InputStream = FileInputStream(uploadFile)
val uploadDigest = DigestUtil.hexDigest(uploadFileIs)
val downloadedDigest = DigestUtil.hexDigest(s3Object.objectContent)
uploadFileIs.close()
s3Object.close()
assertThat(uploadDigest)
.isEqualTo(downloadedDigest)
.`as`("Up- and downloaded Files should have equal digests")
}
/**
* Creates 5+MB of random bytes to upload as a valid part
* (all parts but the last must be at least 5MB in size)
*/
fun randomBytes(): ByteArray {
val size = _5MB.toInt() + random.nextInt(_1MB)
val bytes = ByteArray(size)
random.nextBytes(bytes)
return bytes
}
@Throws(IOException::class)
fun readStreamIntoByteArray(inputStream: InputStream): ByteArray {
inputStream.use { `in` ->
val outputStream = ByteArrayOutputStream(BUFFER_SIZE)
val buffer = ByteArray(BUFFER_SIZE)
var bytesRead: Int
while (`in`.read(buffer).also { bytesRead = it } != -1) {
outputStream.write(buffer, 0, bytesRead)
}
outputStream.flush()
return outputStream.toByteArray()
}
}
fun concatByteArrays(arr1: ByteArray, arr2: ByteArray): ByteArray {
val result = ByteArray(arr1.size + arr2.size)
System.arraycopy(arr1, 0, result, 0, arr1.size)
System.arraycopy(arr2, 0, result, arr1.size, arr2.size)
return result
}
companion object {
val INITIAL_BUCKET_NAMES: Collection<String> = listOf("bucket-a", "bucket-b")
const val TEST_ENC_KEY_ID = "valid-test-key-id"
const val UPLOAD_FILE_NAME = "src/test/resources/sampleFile.txt"
const val TEST_WRONG_KEY_ID = "key-ID-WRONGWRONGWRONG"
const val _1MB = 1024 * 1024
const val _2MB = 2L * _1MB
const val _5MB = 5L * _1MB
const val _6MB = 6L * _1MB
private const val _6BYTE = 6L
private const val THREAD_COUNT = 50
val random = Random()
const val BUFFER_SIZE = 128 * 1024
}
}
| integration-tests/src/test/kotlin/com/adobe/testing/s3mock/its/S3TestBase.kt | 297243597 |
package `is`.xyz.mpv
import kotlinx.android.synthetic.main.player.*
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.AssetManager
import android.content.res.ColorStateList
import android.os.Bundle
import android.os.Handler
import android.provider.Settings
import android.util.Log
import android.media.AudioManager
import android.net.Uri
import android.os.Build
import android.preference.PreferenceManager.getDefaultSharedPreferences
import androidx.core.content.ContextCompat
import android.view.*
import android.widget.SeekBar
import android.widget.Toast
import android.widget.Toast.LENGTH_SHORT
import android.widget.Toast.makeText
import kotlinx.android.synthetic.main.player.view.*
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
class MPVActivity : Activity(), EventObserver, TouchGesturesObserver {
private lateinit var fadeHandler: Handler
private lateinit var fadeRunnable: FadeOutControlsRunnable
private var activityIsForeground = true
private var userIsOperatingSeekbar = false
private lateinit var toast: Toast
private lateinit var gestures: TouchGestures
private lateinit var audioManager: AudioManager
private val seekBarChangeListener = object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
if (!fromUser)
return
player.timePos = progress
updatePlaybackPos(progress)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
userIsOperatingSeekbar = true
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
userIsOperatingSeekbar = false
}
}
private var statsEnabled = false
private var statsOnlyFPS = false
private var statsLuaMode = 0 // ==0 disabled, >0 page number
private var gesturesEnabled = true
private var backgroundPlayMode = ""
private var shouldSavePosition = false
private var autoRotationMode = ""
private fun initListeners() {
controls.cycleAudioBtn.setOnClickListener { _ -> cycleAudio() }
controls.cycleAudioBtn.setOnLongClickListener { _ -> pickAudio(); true }
controls.cycleSubsBtn.setOnClickListener { _ ->cycleSub() }
controls.cycleSubsBtn.setOnLongClickListener { _ -> pickSub(); true }
}
private fun initMessageToast() {
toast = makeText(applicationContext, "This totally shouldn't be seen", LENGTH_SHORT)
toast.setGravity(Gravity.TOP or Gravity.CENTER_HORIZONTAL, 0, 0)
}
private var playbackHasStarted = false
private var onload_commands = ArrayList<Array<String>>()
override fun onCreate(icicle: Bundle?) {
super.onCreate(icicle)
// Do copyAssets here and not in MainActivity because mpv can be launched from a file browser
copyAssets()
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
setContentView(R.layout.player)
// Init controls to be hidden and view fullscreen
initControls()
// Initialize listeners for the player view
initListeners()
// Initialize toast used for short messages
initMessageToast()
// set up a callback handler and a runnable for fading the controls out
fadeHandler = Handler()
fadeRunnable = FadeOutControlsRunnable(this, controls)
syncSettings()
// set initial screen orientation (depending on settings)
updateOrientation(true)
val filepath: String?
if (intent.action == Intent.ACTION_VIEW) {
filepath = resolveUri(intent.data)
parseIntentExtras(intent.extras)
} else {
filepath = intent.getStringExtra("filepath")
}
if (filepath == null) {
Log.e(TAG, "No file given, exiting")
finish()
return
}
player.initialize(applicationContext.filesDir.path)
player.addObserver(this)
player.playFile(filepath)
playbackSeekbar.setOnSeekBarChangeListener(seekBarChangeListener)
if (this.gesturesEnabled) {
val dm = resources.displayMetrics
gestures = TouchGestures(dm.widthPixels.toFloat(), dm.heightPixels.toFloat(), this)
player.setOnTouchListener { _, e -> gestures.onTouchEvent(e) }
}
audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
volumeControlStream = AudioManager.STREAM_MUSIC
}
override fun onDestroy() {
// take the background service with us
val intent = Intent(this, BackgroundPlaybackService::class.java)
applicationContext.stopService(intent)
player.removeObserver(this)
player.destroy()
super.onDestroy()
}
private fun copyAssets() {
val assetManager = applicationContext.assets
val files = arrayOf("subfont.ttf", "cacert.pem")
val configDir = applicationContext.filesDir.path
for (filename in files) {
var ins: InputStream? = null
var out: OutputStream? = null
try {
ins = assetManager.open(filename, AssetManager.ACCESS_STREAMING)
val outFile = File("$configDir/$filename")
// Note that .available() officially returns an *estimated* number of bytes available
// this is only true for generic streams, asset streams return the full file size
if (outFile.length() == ins.available().toLong()) {
Log.w(TAG, "Skipping copy of asset file (exists same size): $filename")
continue
}
out = FileOutputStream(outFile)
ins.copyTo(out)
Log.w(TAG, "Copied asset file: $filename")
} catch (e: IOException) {
Log.e(TAG, "Failed to copy asset file: $filename", e)
} finally {
ins?.close()
out?.close()
}
}
}
private fun shouldBackground(): Boolean {
if (isFinishing) // about to exit?
return false
if (player.paused ?: true)
return false
when (backgroundPlayMode) {
"always" -> return true
"never" -> return false
}
// backgroundPlayMode == "audio-only"
val fmt = MPVLib.getPropertyString("video-format")
return fmt.isNullOrEmpty() || arrayOf("mjpeg", "png", "bmp").indexOf(fmt) != -1
}
override fun onPause() {
val multiWindowMode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) isInMultiWindowMode else false
if (multiWindowMode) {
Log.v(TAG, "Going into multi-window mode")
super.onPause()
return
}
val shouldBackground = shouldBackground()
if (shouldBackground && !MPVLib.getPropertyString("video-format").isNullOrEmpty())
BackgroundPlaybackService.thumbnail = MPVLib.grabThumbnail(THUMB_SIZE)
else
BackgroundPlaybackService.thumbnail = null
// player.onPause() modifies the playback state, so save stuff beforehand
if (isFinishing)
savePosition()
player.onPause()
super.onPause()
activityIsForeground = false
if (shouldBackground) {
Log.v(TAG, "Resuming playback in background")
// start background playback service
val serviceIntent = Intent(this, BackgroundPlaybackService::class.java)
applicationContext.startService(serviceIntent)
}
}
private fun syncSettings() {
// FIXME: settings should be in their own class completely
val prefs = getDefaultSharedPreferences(this.applicationContext)
val statsMode = prefs.getString("stats_mode", "")
if (statsMode.isNullOrBlank()) {
this.statsEnabled = false
this.statsLuaMode = 0
} else if (statsMode == "native" || statsMode == "native_fps") {
this.statsEnabled = true
this.statsLuaMode = 0
this.statsOnlyFPS = statsMode == "native_fps"
} else if (statsMode == "lua1" || statsMode == "lua2") {
this.statsEnabled = false
this.statsLuaMode = if (statsMode == "lua1") 1 else 2
}
this.gesturesEnabled = prefs.getBoolean("touch_gestures", true)
this.backgroundPlayMode = prefs.getString("background_play", "never")
this.shouldSavePosition = prefs.getBoolean("save_position", false)
this.autoRotationMode = prefs.getString("auto_rotation", "auto")
if (this.statsOnlyFPS)
statsTextView.setTextColor((0xFF00FF00).toInt()) // green
if (this.autoRotationMode != "auto")
orientationBtn.visibility = View.VISIBLE
}
override fun onResume() {
// If we weren't actually in the background (e.g. multi window mode), don't reinitialize stuff
if (activityIsForeground) {
super.onResume()
return
}
// Init controls to be hidden and view fullscreen
initControls()
syncSettings()
activityIsForeground = true
refreshUi()
// stop background playback if still running
val intent = Intent(this, BackgroundPlaybackService::class.java)
applicationContext.stopService(intent)
player.onResume()
super.onResume()
}
private fun savePosition() {
if (!shouldSavePosition)
return
if (MPVLib.getPropertyBoolean("eof-reached") ?: true) {
Log.d(TAG, "player indicates EOF, not saving watch-later config")
return
}
MPVLib.command(arrayOf("write-watch-later-config"))
}
private fun updateStats() {
if (this.statsOnlyFPS) {
statsTextView.text = "${player.estimatedVfFps} FPS"
return
}
val text = "File: ${player.filename}\n\n" +
"Video: ${player.videoCodec} hwdec: ${player.hwdecActive}\n" +
"\tA-V: ${player.avsync}\n" +
"\tDropped: decoder: ${player.decoderFrameDropCount}, VO: ${player.frameDropCount}\n" +
"\tFPS: ${player.fps} (specified) ${player.estimatedVfFps} (estimated)\n" +
"\tResolution: ${player.videoW}x${player.videoH}\n\n" +
"Audio: ${player.audioCodec}\n" +
"\tSample rate: ${player.audioSampleRate} Hz\n" +
"\tChannels: ${player.audioChannels}"
statsTextView.text = text
}
private fun showControls() {
// remove all callbacks that were to be run for fading
fadeHandler.removeCallbacks(fadeRunnable)
// set the main controls as 75%, actual seek bar|buttons as 100%
controls.alpha = 1f
// Open, Sesame!
controls.visibility = View.VISIBLE
top_controls.visibility = View.VISIBLE
if (this.statsEnabled) {
updateStats()
statsTextView.visibility = View.VISIBLE
}
window.decorView.systemUiVisibility = 0
// add a new callback to hide the controls once again
fadeHandler.postDelayed(fadeRunnable, CONTROLS_DISPLAY_TIMEOUT)
}
fun initControls() {
/* Init controls to be hidden */
// use GONE here instead of INVISIBLE (which makes more sense) because of Android bug with surface views
// see http://stackoverflow.com/a/12655713/2606891
controls.visibility = View.GONE
top_controls.visibility = View.GONE
statsTextView.visibility = View.GONE
val flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE
window.decorView.systemUiVisibility = flags
}
private fun hideControls() {
fadeHandler.removeCallbacks(fadeRunnable)
fadeHandler.post(fadeRunnable)
}
private fun toggleControls(): Boolean {
return if (controls.visibility == View.VISIBLE) {
hideControls()
false
} else {
showControls()
true
}
}
override fun dispatchKeyEvent(ev: KeyEvent): Boolean {
showControls()
// try built-in event handler first, forward all other events to libmpv
if (ev.action == KeyEvent.ACTION_DOWN && interceptKeyDown(ev)) {
return true
} else if (player.onKey(ev)) {
return true
}
return super.dispatchKeyEvent(ev)
}
private var mightWantToToggleControls = false
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
if (super.dispatchTouchEvent(ev)) {
// reset delay if the event has been handled
if (controls.visibility == View.VISIBLE)
showControls()
if (ev.action == MotionEvent.ACTION_UP)
return true
}
if (ev.action == MotionEvent.ACTION_DOWN)
mightWantToToggleControls = true
if (ev.action == MotionEvent.ACTION_UP && mightWantToToggleControls)
toggleControls()
return true
}
private fun interceptKeyDown(event: KeyEvent): Boolean {
// intercept some keys to provide functionality "native" to
// mpv-android even if libmpv already implements these
var unhandeled = 0
when (event.unicodeChar.toChar()) {
// overrides a default binding:
'j' -> cycleSub()
'#' -> cycleAudio()
else -> unhandeled++
}
when (event.keyCode) {
// no default binding:
KeyEvent.KEYCODE_CAPTIONS -> cycleSub()
KeyEvent.KEYCODE_HEADSETHOOK -> player.cyclePause()
KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK -> cycleAudio()
KeyEvent.KEYCODE_INFO -> toggleControls()
// overrides a default binding:
KeyEvent.KEYCODE_MEDIA_PAUSE -> player.paused = true
KeyEvent.KEYCODE_MEDIA_PLAY -> player.paused = false
else -> unhandeled++
}
return unhandeled < 2
}
@Suppress("UNUSED_PARAMETER")
fun playPause(view: View) = player.cyclePause()
@Suppress("UNUSED_PARAMETER")
fun playlistPrev(view: View) = MPVLib.command(arrayOf("playlist-prev"))
@Suppress("UNUSED_PARAMETER")
fun playlistNext(view: View) = MPVLib.command(arrayOf("playlist-next"))
private fun showToast(msg: String) {
toast.setText(msg)
toast.show()
}
private fun resolveUri(data: Uri): String? {
val filepath = when (data.scheme) {
"file" -> data.path
"content" -> openContentFd(data)
"http", "https", "rtmp", "rtmps", "rtp", "rtsp", "mms", "mmst", "mmsh", "udp"
-> data.toString()
else -> null
}
if (filepath == null)
Log.e(TAG, "unknown scheme: ${data.scheme}")
return filepath
}
private fun openContentFd(uri: Uri): String? {
val resolver = applicationContext.contentResolver
return try {
val fd = resolver.openFileDescriptor(uri, "r")
"fdclose://${fd.detachFd()}"
} catch(e: Exception) {
Log.e(TAG, "Failed to open content fd: $e")
null
}
}
private fun parseIntentExtras(extras: Bundle?) {
onload_commands.clear()
if (extras == null)
return
// API reference: http://mx.j2inter.com/api (partially implemented)
if (extras.getByte("decode_mode") == 2.toByte())
onload_commands.add(arrayOf("set", "file-local-options/hwdec", "no"))
if (extras.containsKey("subs")) {
val subList = extras.getParcelableArray("subs")?.mapNotNull { it as? Uri } ?: emptyList()
val subsToEnable = extras.getParcelableArray("subs.enable")?.mapNotNull { it as? Uri } ?: emptyList()
for (suburi in subList) {
val subfile = resolveUri(suburi) ?: continue
val flag = if (subsToEnable.filter({ it.compareTo(suburi) == 0 }).any()) "select" else "auto"
Log.v(TAG, "Adding subtitles from intent extras: $subfile")
onload_commands.add(arrayOf("sub-add", subfile, flag))
}
}
if (extras.getInt("position", 0) > 0) {
val pos = extras.getInt("position", 0) / 1000f
onload_commands.add(arrayOf("set", "start", pos.toString()))
}
}
data class TrackData(val track_id: Int, val track_type: String)
private fun trackSwitchNotification(f: () -> TrackData) {
val (track_id, track_type) = f()
val trackPrefix = when (track_type) {
"audio" -> "Audio"
"sub" -> "Subs"
"video" -> "Video"
else -> "Unknown"
}
if (track_id == -1) {
showToast("$trackPrefix Off")
return
}
val trackName = player.tracks[track_type]?.firstOrNull{ it.mpvId == track_id }?.name ?: "???"
showToast("$trackPrefix $trackName")
}
private fun cycleAudio() = trackSwitchNotification {
player.cycleAudio(); TrackData(player.aid, "audio")
}
private fun cycleSub() = trackSwitchNotification {
player.cycleSub(); TrackData(player.sid, "sub")
}
private fun selectTrack(type: String, get: () -> Int, set: (Int) -> Unit) {
val tracks = player.tracks[type]!!
val selectedMpvId = get()
val selectedIndex = tracks.indexOfFirst { it.mpvId == selectedMpvId }
val wasPlayerPaused = player.paused ?: true // default to not changing state after switch
player.paused = true
with (AlertDialog.Builder(this)) {
setSingleChoiceItems(tracks.map { it.name }.toTypedArray(), selectedIndex) { dialog, item ->
val trackId = tracks[item].mpvId
set(trackId)
dialog.dismiss()
trackSwitchNotification { TrackData(trackId, type) }
}
setOnDismissListener { if (!wasPlayerPaused) player.paused = false }
create().show()
}
}
private fun pickAudio() = selectTrack("audio", { player.aid }, { player.aid = it })
private fun pickSub() = selectTrack("sub", { player.sid }, { player.sid = it })
@Suppress("UNUSED_PARAMETER")
fun switchDecoder(view: View) {
player.cycleHwdec()
updateDecoderButton()
}
@Suppress("UNUSED_PARAMETER")
fun cycleSpeed(view: View) {
player.cycleSpeed()
updateSpeedButton()
}
@Suppress("UNUSED_PARAMETER")
fun cycleOrientation(view: View) {
requestedOrientation = if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
else
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
}
private fun prettyTime(d: Int): String {
val hours = d / 3600
val minutes = d % 3600 / 60
val seconds = d % 60
if (hours == 0)
return "%02d:%02d".format(minutes, seconds)
return "%d:%02d:%02d".format(hours, minutes, seconds)
}
private fun refreshUi() {
// forces update of entire UI, used when returning from background playback
if (player.timePos == null)
return
updatePlaybackStatus(player.paused!!)
updatePlaybackPos(player.timePos!!)
updatePlaybackDuration(player.duration!!)
updatePlaylistButtons()
}
fun updatePlaybackPos(position: Int) {
playbackPositionTxt.text = prettyTime(position)
if (!userIsOperatingSeekbar)
playbackSeekbar.progress = position
updateDecoderButton()
updateSpeedButton()
}
private fun updatePlaybackDuration(duration: Int) {
playbackDurationTxt.text = prettyTime(duration)
if (!userIsOperatingSeekbar)
playbackSeekbar.max = duration
}
private fun updatePlaybackStatus(paused: Boolean) {
val r = if (paused) R.drawable.ic_play_arrow_black_24dp else R.drawable.ic_pause_black_24dp
playBtn.setImageResource(r)
}
private fun updateDecoderButton() {
cycleDecoderBtn.text = if (player.hwdecActive!!) "HW" else "SW"
}
private fun updateSpeedButton() {
cycleSpeedBtn.text = "${player.playbackSpeed}x"
}
private fun updatePlaylistButtons() {
val plCount = MPVLib.getPropertyInt("playlist-count") ?: 1
val plPos = MPVLib.getPropertyInt("playlist-pos") ?: 0
if (plCount == 1) {
// use View.GONE so the buttons won't take up any space
prevBtn.visibility = View.GONE
nextBtn.visibility = View.GONE
return
}
prevBtn.visibility = View.VISIBLE
nextBtn.visibility = View.VISIBLE
val g = ContextCompat.getColor(applicationContext, R.color.tint_disabled)
val w = ContextCompat.getColor(applicationContext, R.color.tint_normal)
prevBtn.imageTintList = ColorStateList.valueOf(if (plPos == 0) g else w)
nextBtn.imageTintList = ColorStateList.valueOf(if (plPos == plCount-1) g else w)
}
private fun updateOrientation(initial: Boolean = false) {
if (autoRotationMode != "auto") {
if (!initial)
return // don't reset at runtime
requestedOrientation = if (autoRotationMode == "landscape")
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
else
ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
}
if (initial)
return
val ratio = (player.videoW ?: 0) / (player.videoH ?: 1).toFloat()
Log.v(TAG, "auto rotation: aspect ratio = ${ratio}")
if (ratio == 0f || ratio in (1f / ASPECT_RATIO_MIN) .. ASPECT_RATIO_MIN) {
// video is square, let Android do what it wants
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
return
}
requestedOrientation = if (ratio > 1f)
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
else
ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
}
private fun eventPropertyUi(property: String) {
when (property) {
"track-list" -> player.loadTracks()
"video-params" -> updateOrientation()
}
}
private fun eventPropertyUi(property: String, value: Boolean) {
when (property) {
"pause" -> updatePlaybackStatus(value)
}
}
private fun eventPropertyUi(property: String, value: Long) {
when (property) {
"time-pos" -> updatePlaybackPos(value.toInt())
"duration" -> updatePlaybackDuration(value.toInt())
}
}
@Suppress("UNUSED_PARAMETER")
private fun eventPropertyUi(property: String, value: String) {
}
private fun eventUi(eventId: Int) {
when (eventId) {
MPVLib.mpvEventId.MPV_EVENT_PLAYBACK_RESTART -> updatePlaybackStatus(player.paused!!)
MPVLib.mpvEventId.MPV_EVENT_START_FILE -> updatePlaylistButtons()
}
}
override fun eventProperty(property: String) {
if (!activityIsForeground) return
runOnUiThread { eventPropertyUi(property) }
}
override fun eventProperty(property: String, value: Boolean) {
if (!activityIsForeground) return
runOnUiThread { eventPropertyUi(property, value) }
}
override fun eventProperty(property: String, value: Long) {
if (!activityIsForeground) return
runOnUiThread { eventPropertyUi(property, value) }
}
override fun eventProperty(property: String, value: String) {
if (!activityIsForeground) return
runOnUiThread { eventPropertyUi(property, value) }
}
override fun event(eventId: Int) {
// exit properly even when in background
if (playbackHasStarted && eventId == MPVLib.mpvEventId.MPV_EVENT_IDLE)
finish()
else if(eventId == MPVLib.mpvEventId.MPV_EVENT_SHUTDOWN)
finish()
if (!activityIsForeground) return
// deliberately not on the UI thread
if (eventId == MPVLib.mpvEventId.MPV_EVENT_START_FILE) {
playbackHasStarted = true
for (c in onload_commands)
MPVLib.command(c)
if (this.statsLuaMode > 0) {
MPVLib.command(arrayOf("script-binding", "stats/display-stats-toggle"))
MPVLib.command(arrayOf("script-binding", "stats/${this.statsLuaMode}"))
}
}
runOnUiThread { eventUi(eventId) }
}
private fun getInitialBrightness(): Float {
// "local" brightness first
val lp = window.attributes
if (lp.screenBrightness >= 0f)
return lp.screenBrightness
// read system pref: https://stackoverflow.com/questions/4544967//#answer-8114307
// (doesn't work with auto-brightness mode)
val resolver = applicationContext.contentResolver
return try {
Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS) / 255f
} catch (e: Settings.SettingNotFoundException) {
0.5f
}
}
private var initialSeek = 0
private var initialBright = 0f
private var initialVolume = 0
private var maxVolume = 0
override fun onPropertyChange(p: PropertyChange, diff: Float) {
when (p) {
PropertyChange.Init -> {
mightWantToToggleControls = false
initialSeek = player.timePos ?: -1
initialBright = getInitialBrightness()
initialVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
gestureTextView.visibility = View.VISIBLE
gestureTextView.text = ""
}
PropertyChange.Seek -> {
// disable seeking on livestreams and when timePos is not available
if (player.duration ?: 0 == 0 || initialSeek < 0)
return
val newPos = Math.min(Math.max(0, initialSeek + diff.toInt()), player.duration!!)
val newDiff = newPos - initialSeek
// seek faster than assigning to timePos but less precise
MPVLib.command(arrayOf("seek", newPos.toString(), "absolute", "keyframes"))
updatePlaybackPos(newPos)
val diffText = (if (newDiff >= 0) "+" else "-") + prettyTime(Math.abs(newDiff.toInt()))
gestureTextView.text = "${prettyTime(newPos)}\n[$diffText]"
}
PropertyChange.Volume -> {
val newVolume = Math.min(Math.max(0, initialVolume + (diff * maxVolume).toInt()), maxVolume)
val newVolumePercent = 100 * newVolume / maxVolume
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, 0)
gestureTextView.text = "V: $newVolumePercent%"
}
PropertyChange.Bright -> {
val lp = window.attributes
val newBright = Math.min(Math.max(0f, initialBright + diff), 1f)
lp.screenBrightness = newBright
window.attributes = lp
gestureTextView.text = "B: ${Math.round(newBright * 100)}%"
}
PropertyChange.Finalize -> gestureTextView.visibility = View.GONE
}
}
companion object {
private val TAG = "mpv"
// how long should controls be displayed on screen (ms)
private val CONTROLS_DISPLAY_TIMEOUT = 2000L
// size (px) of the thumbnail displayed with background play notification
private val THUMB_SIZE = 192
// smallest aspect ratio that is considered non-square
private val ASPECT_RATIO_MIN = 1.2f // covers 5:4 and up
}
}
internal class FadeOutControlsRunnable(private val activity: MPVActivity, private val controls: View) : Runnable {
override fun run() {
controls.animate().alpha(0f).setDuration(500).setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
activity.initControls()
}
})
}
}
| app/src/main/java/is/xyz/mpv/MPVActivity.kt | 1377639176 |
package net.xaethos.trackernotifier.api
import com.squareup.okhttp.Interceptor
import com.squareup.okhttp.Response
import net.xaethos.trackernotifier.BuildConfig
import net.xaethos.trackernotifier.utils.Log
import net.xaethos.trackernotifier.utils.empty
import retrofit.MoshiConverterFactory
import retrofit.Retrofit
import retrofit.RxJavaCallAdapterFactory
import java.util.concurrent.TimeUnit
class TrackerClient internal constructor(retrofit: Retrofit) {
private val authInterceptor = AuthInterceptor()
val me = retrofit.create(MeApi::class.java)
val notifications = retrofit.create(NotificationsApi::class.java)
val stories = retrofit.create(StoriesApi::class.java)
val comments = retrofit.create(CommentsApi::class.java)
init {
retrofit.client().interceptors().add(0, authInterceptor)
}
fun hasToken() = !authInterceptor.trackerToken.empty
fun setToken(trackerToken: String?) {
authInterceptor.trackerToken = trackerToken
}
private class AuthInterceptor : Interceptor {
var trackerToken: String? = null
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val token = trackerToken
if (token.empty) return chain.proceed(request)
val authorizedRequest = request.newBuilder().header("X-TrackerToken", token).build()
return chain.proceed(authorizedRequest)
}
}
private class LoggingInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val startTime = System.nanoTime()
Log.v { "Sending request ${request.method()} ${request.url()}\n${request.headers()}" }
val response = chain.proceed(request)
val elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)
Log.v { "Received response for ${request.url()} in ${elapsed}ms\n${response.headers()}" }
return response
}
}
companion object {
val instance: TrackerClient by lazy {
val retrofit = Retrofit.Builder()
.baseUrl("https://www.pivotaltracker.com/services/v5/")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(MoshiConverterFactory.create())
.build()
if (BuildConfig.DEBUG) retrofit.client().interceptors().add(LoggingInterceptor())
TrackerClient(retrofit)
}
}
}
| app/src/main/java/net/xaethos/trackernotifier/api/TrackerClient.kt | 1272022401 |
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.collection
import com.google.common.truth.Truth.assertThat
import org.junit.Assert.assertEquals
import org.junit.Test
class ArrayMapTest {
@Test fun empty() {
val map = arrayMapOf<String, String>()
assertEquals(0, map.size)
}
@Test fun nonEmpty() {
val map = arrayMapOf("foo" to "bar", "bar" to "baz")
assertThat(map).containsExactly("foo", "bar", "bar", "baz")
}
@Test fun duplicateKeyKeepsLast() {
val map = arrayMapOf("foo" to "bar", "foo" to "baz")
assertThat(map).containsExactly("foo", "baz")
}
}
| collection/ktx/src/test/java/androidx/collection/ArrayMapTest.kt | 4264922504 |
package moonpi
import moonpi.gui.Window
import moonpi.gui.runInGui
import java.util.concurrent.Executors
fun main(args: Array<String>) {
val worker = Executors.newSingleThreadExecutor()
val eventBus = EventBus(worker)
val environment = Environment()
environment.prepare()
val configurationService = ConfigurationService(environment, eventBus)
configurationService.loadConfiguration()
val sshService = JschSshService(configurationService, eventBus)
val pictureService = PictureService(environment, configurationService, sshService, eventBus)
pictureService.loadHistory()
runInGui {
val window = Window(pictureService, configurationService, eventBus, worker)
window.isVisible = true
}
}
| src/main/kotlin/moonpi/main.kt | 2907676465 |
/*
Java Virtual Machine for Android
Copyright (C) 2017 David Laurell
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
*/
package net.daverix.ajvm.io
data class StringReference(val index: Int)
| core/src/commonMain/kotlin/net/daverix/ajvm/io/StringReference.kt | 3964007658 |
/*
* Copyright (c) 2017 Kotlin Algorithm Club
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.uuddlrlrba.ktalgs.geometry
class QuadNode<V> private constructor(
private val NW: QuadTree<V>,
private val NE: QuadTree<V>,
private val SW: QuadTree<V>,
private val SE: QuadTree<V>) : QuadTree<V> {
override val frame: Rect = Rect(NW.frame.TL, SE.frame.BR)
constructor(frame: Rect) : this(
QuadNil<V>(Rect(frame.origin, frame.width / 2, frame.height / 2)),
QuadNil<V>(Rect(Point(frame.x1 + frame.width / 2 + 1, frame.y1), frame.width / 2, frame.height / 2)),
QuadNil<V>(Rect(Point(frame.x1, frame.y1 + frame.height / 2 + 1), frame.width / 2, frame.height / 2)),
QuadNil<V>(Rect(frame.center, frame.width / 2, frame.height / 2))
)
override fun get(rect: Rect): Iterable<V> =
(if (NW.frame.intersects(rect)) NW[rect] else emptyList()) +
(if (NE.frame.intersects(rect)) NE[rect] else emptyList()) +
(if (SW.frame.intersects(rect)) SW[rect] else emptyList()) +
(if (SE.frame.intersects(rect)) SE[rect] else emptyList())
override fun plus(pair: Pair<Point, V>): QuadTree<V> = QuadNode(
if (NW.frame.isInside(pair.first)) NW + pair else NW,
if (NE.frame.isInside(pair.first)) NE + pair else NE,
if (SW.frame.isInside(pair.first)) SW + pair else SW,
if (SE.frame.isInside(pair.first)) SE + pair else SE
)
}
class QuadLeaf<V>(override val frame: Rect, val value: Pair<Point, V>) : QuadTree<V> {
override fun get(rect: Rect): Iterable<V> =
if (rect.isInside(value.first)) listOf(value.second)
else emptyList()
override fun plus(pair: Pair<Point, V>): QuadTree<V> = QuadNode<V>(frame.cover(pair.first)) + value + pair
}
class QuadNil<V>(override val frame: Rect) : QuadTree<V> {
override fun get(rect: Rect): Iterable<V> = emptyList()
override fun plus(pair: Pair<Point, V>): QuadLeaf<V> = QuadLeaf(frame.cover(pair.first), value = pair)
}
interface QuadTree<V> {
val frame: Rect
operator fun get(rect: Rect): Iterable<V>
operator fun plus(pair: Pair<Point, V>): QuadTree<V>
}
fun<V> emptyQuadTree(frame: Rect): QuadTree<V> = QuadNil(frame)
fun<V> quadTreeOf(frame: Rect, vararg pairs: Pair<Point, V>): QuadTree<V> {
var empty = emptyQuadTree<V>(frame)
for (pair in pairs) {
empty += pair
}
return empty
}
| src/main/io/uuddlrlrba/ktalgs/geometry/QuadTree.kt | 3917839500 |
package com.expensivebelly.dagger2retaingraph.feature
import android.content.Context
import android.os.Bundle
import android.widget.TextView
import com.expensivebelly.dagger2retaingraph.R
import com.expensivebelly.dagger2retaingraph.core.RetainGraphActivity
import com.expensivebelly.dagger2retaingraph.core.behavior.PresenterBehavior
import com.expensivebelly.dagger2retaingraph.feature.di.DaggerMainComponent
import com.expensivebelly.dagger2retaingraph.feature.di.MainComponent
import javax.inject.Inject
/**
* Dependency graph is retained through configuration changes in the Activity
*/
class MainActivity : RetainGraphActivity<MainComponent>(), IMainView {
init {
addBehavior(PresenterBehavior(this) { presenter })
}
@Inject
lateinit var presenter: MainPresenter
private val messageView by lazy {
findViewById<TextView>(R.id.text_message)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
component.inject(this)
}
override fun display(message: String) {
messageView.text = message
}
override fun buildComponent(context: Context) = DaggerMainComponent.builder().build()
} | app/src/main/java/com/expensivebelly/dagger2retaingraph/feature/MainActivity.kt | 4254010301 |
package com.quran.labs.androidquran.core
import android.app.Application
import android.content.Context
import androidx.test.runner.AndroidJUnitRunner
import com.quran.labs.androidquran.base.TestApplication
class QuranTestRunner : AndroidJUnitRunner() {
override fun newApplication(
cl: ClassLoader?,
className: String?,
context: Context?
): Application {
return super.newApplication(cl, TestApplication::class.qualifiedName, context)
}
}
| app/src/androidTest/java/com/quran/labs/androidquran/core/QuranTestRunner.kt | 1270880916 |
/*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.adblock.ui.original
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.text.InputType
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import androidx.fragment.app.DialogFragment
import jp.hazuki.yuzubrowser.adblock.repository.original.AdBlock
import jp.hazuki.yuzubrowser.core.utility.extensions.density
class AdBlockEditDialog : DialogFragment() {
private var listener: AdBlockEditDialogListener? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val params = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
val density = activity!!.density
val marginWidth = (4 * density + 0.5f).toInt()
val marginHeight = (16 * density + 0.5f).toInt()
params.setMargins(marginWidth, marginHeight, marginWidth, marginHeight)
val editText = EditText(activity).apply {
layoutParams = params
id = android.R.id.edit
inputType = InputType.TYPE_CLASS_TEXT
}
val arguments = arguments ?: throw NullPointerException()
val text = arguments.getString(ARG_TEXT)
if (!text.isNullOrEmpty())
editText.setText(text)
return AlertDialog.Builder(activity)
.setView(editText)
.setTitle(arguments.getString(ARG_TITLE))
.setPositiveButton(android.R.string.ok) { _, _ ->
listener!!.onEdited(
arguments.getInt(ARG_INDEX, -1),
arguments.getInt(ARG_ID, -1),
editText.text.toString())
}
.setNegativeButton(android.R.string.cancel, null)
.create()
}
override fun onAttach(context: Context) {
super.onAttach(context)
listener = if (parentFragment is AdBlockEditDialogListener) {
parentFragment as AdBlockEditDialogListener
} else {
activity as AdBlockEditDialogListener
}
}
override fun onDetach() {
super.onDetach()
listener = null
}
internal interface AdBlockEditDialogListener {
fun onEdited(index: Int, id: Int, text: String)
}
companion object {
private const val ARG_TITLE = "title"
private const val ARG_INDEX = "index"
private const val ARG_ID = "id"
private const val ARG_TEXT = "text"
operator fun invoke(title: String, index: Int = -1, adBlock: AdBlock? = null): AdBlockEditDialog {
return AdBlockEditDialog().apply {
arguments = Bundle().apply {
putString(ARG_TITLE, title)
putInt(ARG_INDEX, index)
if (adBlock != null) {
putInt(ARG_ID, adBlock.id)
putString(ARG_TEXT, adBlock.match)
}
}
}
}
}
}
| module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/ui/original/AdBlockEditDialog.kt | 2956395279 |
package com.orgzly.android.usecase
import com.orgzly.android.data.DataRepository
class BookSparseTreeForNote(val noteId: Long) : UseCase() {
override fun run(dataRepository: DataRepository): UseCaseResult {
dataRepository.openBookForNote(noteId, true)
return UseCaseResult()
}
} | app/src/main/java/com/orgzly/android/usecase/BookSparseTreeForNote.kt | 3806344745 |
package com.example.sqldelight.hockey.platform
import com.example.sqldelight.hockey.data.Date
@JsModule("dateformat")
external fun dateFormat(date: Date, format: String): String
actual class DateFormatHelper actual constructor(private val format: String) {
actual fun format(d: Date): String = dateFormat(d, format.replace('M', 'm'))
}
| sample/common/src/jsMain/kotlin/com/example/sqldelight/hockey/platform/DateFormatHelper.kt | 1636186331 |
package org.evomaster.core.database.extract.h2
import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType
import org.evomaster.client.java.controller.internal.db.SchemaExtractor
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
/**
* Created by arcuri82 on 01-Apr-19.
*/
class AlterTableCheckEnumTest : ExtractTestBaseH2() {
override fun getSchemaLocation() = "/sql_schema/alter_table_check_enum.sql"
@Test
fun testCreateAndExtract() {
val schema = SchemaExtractor.extract(connection)
assertNotNull(schema)
assertEquals("public", schema.name.toLowerCase())
assertEquals(DatabaseType.H2, schema.databaseType)
assertTrue(schema.tables.any { it.name == "X" })
assertEquals(10, schema.tables.first { it.name == "X" }.columns.size)
assertTrue(schema.tables.first { it.name == "X" }.columns.any { it.name == "STATUS" });
assertEquals(1, schema.tables.first { it.name == "X" }.tableCheckExpressions.size)
assertEquals("(\"STATUS\" IN('A', 'B'))", schema.tables.first { it.name == "X" }.tableCheckExpressions[0].sqlCheckExpression)
}
} | core/src/test/kotlin/org/evomaster/core/database/extract/h2/AlterTableCheckEnumTest.kt | 819185663 |
package com.gmail.blueboxware.libgdxplugin.json
import com.gmail.blueboxware.libgdxplugin.LibGDXCodeInsightFixtureTestCase
import com.intellij.testFramework.PlatformTestUtil
import java.io.File
/*
* Copyright 2019 Blue Box Ware
*
* 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.
*/
class TestStructureView : LibGDXCodeInsightFixtureTestCase() {
fun test1() {
doTest("1.lson", "1.result")
}
private fun doTest(content: String, expected: String) {
configureByFile(content)
myFixture.testStructureView { structureView ->
PlatformTestUtil.assertTreeEqual(structureView.tree, File(testDataPath + expected).readText())
}
}
override fun getBasePath() = "/filetypes/json/structureView/"
}
| src/test/kotlin/com/gmail/blueboxware/libgdxplugin/json/TestStructureView.kt | 3682835016 |
package me.proxer.library.entity.messenger
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Entity containing the results of a link check.
*
* @param isSecure If the link is not on any blacklist.
* @param link The link sent.
*/
@JsonClass(generateAdapter = true)
data class LinkCheckResponse(
@Json(name = "secure") val isSecure: Boolean,
@Json(name = "link") val link: String
)
| library/src/main/kotlin/me/proxer/library/entity/messenger/LinkCheckResponse.kt | 1073862481 |
package ru.virvar.apps.magneticBall2.blocksGenerators
import ru.virvar.apps.magneticBall2.MagneticBallLevel
import ru.virvar.apps.magneticBall2.blocks.SquareBlock
import ru.virvar.apps.magneticBall2.blocks.TriangleBlock
import ru.virvar.apps.magneticBallCore.Block
import ru.virvar.apps.magneticBallCore.IBlocksGenerator
import ru.virvar.apps.magneticBallCore.Level
import ru.virvar.apps.magneticBallCore.Point2D
import java.util.*
class OnLineBlocksGenerator(val blocksCount: Int = 20) : IBlocksGenerator {
override fun generateInitialBlocks(level: Level) {
generateBlocks(level, blocksCount)
}
private fun generateBlocks(level: Level, count: Int) {
for (i in 0..count - 1) {
if (level.freeCells.size != 0) {
val block = createRandomBlock()
val positionIndex = random.nextInt(level.freeCells.size)
val position = level.freeCells[positionIndex]
block.x = position % level.fieldSize
block.y = Math.floor((position.toDouble() / level.fieldSize)).toInt()
level.addBlock(block)
}
}
}
override fun generateBlocks(level: Level) {
val onLineFreeCells = getOnLineFreeCells(level)
while (level.blocks.size <= blocksCount) {
if (onLineFreeCells.size == 0) {
generateBlocks(level, blocksCount - level.blocks.size + 1)
} else {
val block = createRandomBlock()
val positionIndex = random.nextInt(onLineFreeCells.size)
val position = onLineFreeCells[positionIndex]
onLineFreeCells.remove(position)
block.x = position.x
block.y = position.y
level.addBlock(block)
}
}
}
private fun getOnLineFreeCells(level: Level): LinkedList<Point2D> {
val player = (level as MagneticBallLevel).player
val onLineFreeCells = LinkedList<Point2D>()
for (i in 0..level.fieldSize - 1) {
if (level.getBlock(player.x, i) == null) {
onLineFreeCells.add(Point2D(player.x, i))
}
}
for (i in 0..level.fieldSize - 1) {
if (level.getBlock(i, player.y) == null) {
onLineFreeCells.add(Point2D(i, player.y))
}
}
return onLineFreeCells
}
private fun createRandomBlock(): Block {
var block: Block? = null
var blockType = random.nextInt(2)
when (blockType) {
0 ->
block = SquareBlock()
1 -> {
val direction = random.nextInt(4)
block = TriangleBlock(TriangleBlock.ReflectionDirection.values().get(direction))
}
}
return block!!
}
}
| MagneticBallLogic/src/main/kotlin/ru/virvar/apps/magneticBall2/blocksGenerators/OnLineBlocksGenerator.kt | 132068144 |
/*
* Copyright 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.gradle.configurationcache.fingerprint
import org.gradle.api.Describable
import org.gradle.api.internal.GeneratedSubclasses.unpackType
import org.gradle.api.internal.file.FileCollectionInternal
import org.gradle.api.provider.ValueSource
import org.gradle.api.provider.ValueSourceParameters
import org.gradle.configurationcache.CheckedFingerprint
import org.gradle.configurationcache.extensions.filterKeysByPrefix
import org.gradle.configurationcache.extensions.uncheckedCast
import org.gradle.configurationcache.serialization.ReadContext
import org.gradle.internal.hash.HashCode
import org.gradle.internal.util.NumberUtil.ordinal
import org.gradle.util.Path
import java.io.File
import java.util.function.Consumer
internal
typealias InvalidationReason = String
internal
class ConfigurationCacheFingerprintChecker(private val host: Host) {
interface Host {
val gradleUserHomeDir: File
val allInitScripts: List<File>
val startParameterProperties: Map<String, Any?>
val buildStartTime: Long
val invalidateCoupledProjects: Boolean
fun gradleProperty(propertyName: String): String?
fun fingerprintOf(fileCollection: FileCollectionInternal): HashCode
fun hashCodeOf(file: File): HashCode?
fun displayNameOf(fileOrDirectory: File): String
fun instantiateValueSourceOf(obtainedValue: ObtainedValue): ValueSource<Any, ValueSourceParameters>
}
suspend fun ReadContext.checkBuildScopedFingerprint(): CheckedFingerprint {
// TODO: log some debug info
while (true) {
when (val input = read()) {
null -> break
is ConfigurationCacheFingerprint -> {
// An input that is not specific to a project. If it is out-of-date, then invalidate the whole cache entry and skip any further checks
val reason = check(input)
if (reason != null) {
return CheckedFingerprint.EntryInvalid(reason)
}
}
else -> throw IllegalStateException("Unexpected configuration cache fingerprint: $input")
}
}
return CheckedFingerprint.Valid
}
suspend fun ReadContext.checkProjectScopedFingerprint(): CheckedFingerprint {
// TODO: log some debug info
var firstReason: InvalidationReason? = null
val projects = mutableMapOf<Path, ProjectInvalidationState>()
while (true) {
when (val input = read()) {
null -> break
is ProjectSpecificFingerprint.ProjectFingerprint -> input.run {
// An input that is specific to a project. If it is out-of-date, then invalidate that project's values and continue checking values
// Don't check a value for a project that is already out-of-date
val state = projects.entryFor(input.projectPath)
if (!state.isInvalid) {
val reason = check(input.value)
if (reason != null) {
if (firstReason == null) {
firstReason = reason
}
state.invalidate()
}
}
}
is ProjectSpecificFingerprint.ProjectDependency -> {
val consumer = projects.entryFor(input.consumingProject)
val target = projects.entryFor(input.targetProject)
target.consumedBy(consumer)
}
is ProjectSpecificFingerprint.CoupledProjects -> {
if (host.invalidateCoupledProjects) {
val referrer = projects.entryFor(input.referringProject)
val target = projects.entryFor(input.targetProject)
target.consumedBy(referrer)
referrer.consumedBy(target)
}
}
else -> throw IllegalStateException("Unexpected configuration cache fingerprint: $input")
}
}
return if (firstReason == null) {
CheckedFingerprint.Valid
} else {
CheckedFingerprint.ProjectsInvalid(firstReason!!, projects.entries.filter { it.value.isInvalid }.map { it.key }.toSet())
}
}
suspend fun ReadContext.visitEntriesForProjects(reusedProjects: Set<Path>, consumer: Consumer<ProjectSpecificFingerprint>) {
while (true) {
when (val input = read()) {
null -> break
is ProjectSpecificFingerprint.ProjectFingerprint ->
if (reusedProjects.contains(input.projectPath)) {
consumer.accept(input)
}
is ProjectSpecificFingerprint.ProjectDependency ->
if (reusedProjects.contains(input.consumingProject)) {
consumer.accept(input)
}
is ProjectSpecificFingerprint.CoupledProjects ->
if (reusedProjects.contains(input.referringProject)) {
consumer.accept(input)
}
}
}
}
private
fun MutableMap<Path, ProjectInvalidationState>.entryFor(path: Path) = getOrPut(path) { ProjectInvalidationState() }
private
fun check(input: ConfigurationCacheFingerprint): InvalidationReason? {
when (input) {
is ConfigurationCacheFingerprint.WorkInputs -> input.run {
val currentFingerprint = host.fingerprintOf(fileSystemInputs)
if (currentFingerprint != fileSystemInputsFingerprint) {
// TODO: summarize what has changed (see https://github.com/gradle/configuration-cache/issues/282)
return "an input to $workDisplayName has changed"
}
}
is ConfigurationCacheFingerprint.InputFile -> input.run {
if (hasFileChanged(file, hash)) {
return "file '${displayNameOf(file)}' has changed"
}
}
is ConfigurationCacheFingerprint.ValueSource -> input.run {
val reason = checkFingerprintValueIsUpToDate(obtainedValue)
if (reason != null) return reason
}
is ConfigurationCacheFingerprint.InitScripts -> input.run {
val reason = checkInitScriptsAreUpToDate(fingerprints, host.allInitScripts)
if (reason != null) return reason
}
is ConfigurationCacheFingerprint.UndeclaredSystemProperty -> input.run {
if (System.getProperty(key) != value) {
return "system property '$key' has changed"
}
}
is ConfigurationCacheFingerprint.UndeclaredEnvironmentVariable -> input.run {
if (System.getenv(key) != value) {
return "environment variable '$key' has changed"
}
}
is ConfigurationCacheFingerprint.ChangingDependencyResolutionValue -> input.run {
if (host.buildStartTime >= expireAt) {
return reason
}
}
is ConfigurationCacheFingerprint.GradleEnvironment -> input.run {
if (host.gradleUserHomeDir != gradleUserHomeDir) {
return "Gradle user home directory has changed"
}
if (jvmFingerprint() != jvm) {
return "JVM has changed"
}
if (host.startParameterProperties != startParameterProperties) {
return "the set of Gradle properties has changed"
}
}
is ConfigurationCacheFingerprint.EnvironmentVariablesPrefixedBy -> input.run {
val current = System.getenv().filterKeysByPrefix(prefix)
if (current != snapshot) {
return "the set of environment variables prefixed by '$prefix' has changed"
}
}
is ConfigurationCacheFingerprint.SystemPropertiesPrefixedBy -> input.run {
val currentWithoutIgnored = System.getProperties().uncheckedCast<Map<String, Any>>().filterKeysByPrefix(prefix).filterKeys {
// remove properties that are known to be modified by the build logic at the moment of obtaining this, as their initial
// values doesn't matter.
snapshot[it] != ConfigurationCacheFingerprint.SystemPropertiesPrefixedBy.IGNORED
}
val snapshotWithoutIgnored = snapshot.filterValues {
// remove placeholders of modified properties to only compare relevant values.
it != ConfigurationCacheFingerprint.SystemPropertiesPrefixedBy.IGNORED
}
if (currentWithoutIgnored != snapshotWithoutIgnored) {
return "the set of system properties prefixed by '$prefix' has changed"
}
}
}
return null
}
private
fun checkInitScriptsAreUpToDate(
previous: List<ConfigurationCacheFingerprint.InputFile>,
current: List<File>
): InvalidationReason? =
when (val upToDatePrefix = countUpToDatePrefixOf(previous, current)) {
previous.size -> {
val added = current.size - upToDatePrefix
when {
added == 1 -> "init script '${displayNameOf(current[upToDatePrefix])}' has been added"
added > 1 -> "init script '${displayNameOf(current[upToDatePrefix])}' and ${added - 1} more have been added"
else -> null
}
}
current.size -> {
val removed = previous.size - upToDatePrefix
when {
removed == 1 -> "init script '${displayNameOf(previous[upToDatePrefix].file)}' has been removed"
removed > 1 -> "init script '${displayNameOf(previous[upToDatePrefix].file)}' and ${removed - 1} more have been removed"
else -> null
}
}
else -> {
when (val modifiedScript = current[upToDatePrefix]) {
previous[upToDatePrefix].file -> "init script '${displayNameOf(modifiedScript)}' has changed"
else -> "content of ${ordinal(upToDatePrefix + 1)} init script, '${displayNameOf(modifiedScript)}', has changed"
}
}
}
private
fun countUpToDatePrefixOf(
previous: List<ConfigurationCacheFingerprint.InputFile>,
current: List<File>
): Int = current.zip(previous)
.takeWhile { (initScript, fingerprint) -> isUpToDate(initScript, fingerprint.hash) }
.count()
private
fun checkFingerprintValueIsUpToDate(obtainedValue: ObtainedValue): InvalidationReason? {
val valueSource = host.instantiateValueSourceOf(obtainedValue)
if (obtainedValue.value.get() != valueSource.obtain()) {
return buildLogicInputHasChanged(valueSource)
}
return null
}
private
fun hasFileChanged(file: File, originalHash: HashCode?) =
!isUpToDate(file, originalHash)
private
fun isUpToDate(file: File, originalHash: HashCode?) =
host.hashCodeOf(file) == originalHash
private
fun displayNameOf(file: File) =
host.displayNameOf(file)
private
fun buildLogicInputHasChanged(valueSource: ValueSource<Any, ValueSourceParameters>): InvalidationReason =
(valueSource as? Describable)?.let {
it.displayName + " has changed"
} ?: "a build logic input of type '${unpackType(valueSource).simpleName}' has changed"
private
class ProjectInvalidationState {
// When true, the project is definitely invalid
// When false, validity is not known
private
var invalid = false
private
val consumedBy = mutableSetOf<ProjectInvalidationState>()
val isInvalid: Boolean
get() = invalid
fun consumedBy(consumer: ProjectInvalidationState) {
if (invalid) {
consumer.invalidate()
} else {
consumedBy.add(consumer)
}
}
fun invalidate() {
if (invalid) {
return
}
invalid = true
for (consumer in consumedBy) {
consumer.invalidate()
}
consumedBy.clear()
}
}
}
| subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/fingerprint/ConfigurationCacheFingerprintChecker.kt | 2397964203 |
/*
* Copyright 2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache
import org.gradle.api.internal.GradleInternal
import org.gradle.api.internal.SettingsInternal
import org.gradle.execution.EntryTaskSelector
import org.gradle.execution.plan.ExecutionPlan
import org.gradle.internal.build.BuildModelController
class ConfigurationCacheAwareBuildModelController(
private val model: GradleInternal,
private val delegate: BuildModelController,
private val configurationCache: BuildTreeConfigurationCache
) : BuildModelController {
override fun getLoadedSettings(): SettingsInternal {
return if (maybeLoadFromCache()) {
model.settings
} else {
delegate.loadedSettings
}
}
override fun getConfiguredModel(): GradleInternal {
return if (maybeLoadFromCache()) {
throw IllegalStateException("Cannot query configured model when model has been loaded from configuration cache.")
} else {
delegate.configuredModel
}
}
override fun prepareToScheduleTasks() {
if (!maybeLoadFromCache()) {
delegate.prepareToScheduleTasks()
} // Else, already done
}
override fun scheduleRequestedTasks(selector: EntryTaskSelector?, plan: ExecutionPlan) {
if (!maybeLoadFromCache()) {
delegate.scheduleRequestedTasks(selector, plan)
} // Else, already scheduled
}
private
fun maybeLoadFromCache(): Boolean {
return configurationCache.isLoaded
}
}
| subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/ConfigurationCacheAwareBuildModelController.kt | 3678141623 |
package org.jetbrains.exposed.sql.statements
import org.jetbrains.exposed.sql.*
import java.sql.PreparedStatement
import java.sql.ResultSet
/**
* isIgnore is supported for mysql only
*/
open class InsertStatement<Key:Any>(val table: Table, val isIgnore: Boolean = false) : UpdateBuilder<Int>(StatementType.INSERT, listOf(table)) {
open protected val flushCache = true
var generatedKey: Key? = null
infix operator fun <T:Key> get(column: Column<T>): T = generatedKey as? T ?: error("No key generated")
open protected fun generatedKeyFun(rs: ResultSet, inserted: Int) : Key? {
return table.columns.firstOrNull { it.columnType.isAutoInc }?.let { column ->
if (rs.next()) {
@Suppress("UNCHECKED_CAST")
column.columnType.valueFromDB(rs.getObject(1)) as? Key
} else null
}
}
protected fun valuesAndDefaults(): Map<Column<*>, Any?> {
val columnsWithNotNullDefault = targets.flatMap { it.columns }.filter {
(it.dbDefaultValue != null || it.defaultValueFun != null) && !it.columnType.nullable && it !in values.keys
}
return values + columnsWithNotNullDefault.map { it to (it.defaultValueFun?.invoke() ?: DefaultValueMarker) }
}
override fun prepareSQL(transaction: Transaction): String {
val builder = QueryBuilder(true)
val values = valuesAndDefaults()
val sql = if(values.isEmpty()) ""
else values.entries.joinToString(prefix = "VALUES (", postfix = ")") {
val (col, value) = it
when (value) {
is Expression<*> -> value.toSQL(builder)
DefaultValueMarker -> col.dbDefaultValue!!.toSQL(builder)
else -> builder.registerArgument(col.columnType, value)
}
}
return transaction.db.dialect.insert(isIgnore, table, values.map { it.key }, sql, transaction)
}
override fun PreparedStatement.executeInternal(transaction: Transaction): Int {
if (flushCache)
transaction.flushCache()
transaction.entityCache.removeTablesReferrers(listOf(table))
val inserted = if (arguments().count() > 1 || isAlwaysBatch) executeBatch().sum() else executeUpdate()
return inserted.apply {
generatedKeys?.let {
generatedKey = generatedKeyFun(it, this)
}
}
}
override fun prepared(transaction: Transaction, sql: String): PreparedStatement {
val autoincs = targets.flatMap { it.columns }.filter { it.columnType.isAutoInc }
return if (autoincs.isNotEmpty()) {
// http://viralpatel.net/blogs/oracle-java-jdbc-get-primary-key-insert-sql/
transaction.connection.prepareStatement(sql, autoincs.map { transaction.identity(it) }.toTypedArray())!!
} else {
transaction.connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)!!
}
}
override fun arguments() = QueryBuilder(true).run {
valuesAndDefaults().forEach {
val value = it.value
when (value) {
is Expression<*> -> value.toSQL(this)
DefaultValueMarker -> {}
else -> registerArgument(it.key.columnType, value)
}
}
if (args.isNotEmpty()) listOf(args.toList()) else emptyList()
}
}
| extra/exposed/src/main/kotlin/org/jetbrains/exposed/sql/statements/InsertStatement.kt | 3325116774 |
package com.sbg.arena.core.animation
import com.sbg.arena.core.input.ToggleWallRequest
import com.sbg.arena.core.level.Skin
import org.newdawn.slick.Graphics
import kotlin.properties.Delegates
import org.newdawn.slick.Image
import com.sbg.arena.core.level.FloorType
import org.newdawn.slick.Color
class ToggleWallAnimation(val request: ToggleWallRequest, val onAnimationFinished: () -> Unit): Animation {
private var floorSkin: Image by Delegates.notNull()
private var wallSkin: Image by Delegates.notNull()
private var current = 1F
override fun initialize(levelSkin: Skin) {
floorSkin = levelSkin.floorTile()
wallSkin = levelSkin.wallTile()
request.level.toggleFloor(request.target)
}
override fun update() {
current -= 0.02F
}
override fun render(graphics: Graphics) {
when (request.level[request.target]) {
FloorType.Floor -> wallSkin.draw(request.target.x.toFloat() * 20,
request.target.y.toFloat() * 20,
Color(1F, 1F, 1F, current))
FloorType.Wall -> floorSkin.draw(request.target.x.toFloat() * 20,
request.target.y.toFloat() * 20,
Color(1F, 1F, 1F, current))
}
}
override fun isFinished(): Boolean {
return current <= 0F
}
override fun finish() {
request.level.toggleFloor(request.target)
onAnimationFinished()
}
} | src/main/java/com/sbg/arena/core/animation/ToggleWallAnimation.kt | 1993066010 |
package org.openbase.jul.communication.mqtt
import com.hivemq.client.mqtt.MqttClient
import org.openbase.type.communication.mqtt.PrimitiveType
import org.openbase.type.communication.mqtt.RequestType
import java.util.*
import java.util.concurrent.TimeUnit
import com.google.protobuf.Any as protoAny
object Test {
@JvmStatic
fun main(args: Array<String>) {
val v: Int = 42
val asAny: Any = v
println(RequestType.Request.getDefaultInstance())
println(RequestType.Request.getDefaultInstance().descriptorForType)
val build = RequestType.Request.newBuilder().setId("ID").build()
val pack = protoAny.pack(build)
val builder = PrimitiveType.Primitive.newBuilder()
builder.int = v
builder.setInt(asAny as Int)
println("Is init ${builder.isInitialized}")
println("Is init ${builder.build().isInitialized}")
var packed = protoAny.pack(builder.build())
/*var build = PrimitiveType.Primitive.newBuilder().setInt(42).build()
println("Primitive as any: ${Any.pack(build)}")
var pack = Any.pack(build).unpack(PrimitiveType.Primitive::class.java)
println("Unpacked $pack")*/
/*val client = MqttClient.builder()
//.executorConfig(MqttClientExecutorConfig.builder().)
.identifier(UUID.randomUUID().toString())
.serverHost("broker.hivemq.com")
.useMqttVersion5()
.buildAsync()
client.connect()[1, TimeUnit.SECONDS]
println("Client connected!")
val topic = "/asdkjaflasjdhalsk/test"
val rpcServer = RPCServerImpl(client, topic)
rpcServer.activate()
val rpcRemote = RPCClientImpl(client, topic)
println("Call method...")
var get = rpcRemote.callMethod("testMethod3", String::class.java, 42).get()
println("Method returned: $get")
rpcServer.deactivate()
client.disconnect();*/
}
} | module/communication/mqtt/src/test/java/org/openbase/jul/communication/mqtt/Test.kt | 2565561391 |
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package sandbox.view
import com.almasb.fxgl.core.collection.Array
import com.almasb.fxgl.core.math.FXGLMath
import com.almasb.fxgl.core.math.FXGLMath.random
import com.almasb.fxgl.core.math.FXGLMath.randomBoolean
import javafx.geometry.Rectangle2D
/**
* Axis-aligned 2D space subdivision.
*
* @author Almas Baimagambetov ([email protected])
*/
object AASubdivision {
/**
* Subdivides given 2D space ([rect]) into maximum of n = [maxSubspaces] such that
* each subspace has width and height no less than [minSize].
*/
@JvmStatic fun divide(rect: Rectangle2D, maxSubspaces: Int, minSize: Int): Array<Rectangle2D> {
// keeps currently being processed subspaces
val grids = arrayListOf<Rectangle2D>(rect)
val result = Array<Rectangle2D>(maxSubspaces)
for (i in 1..maxSubspaces -1) {
var grid: Rectangle2D
var divisible: Pair<Boolean, Boolean>
do {
if (grids.isEmpty())
throw RuntimeException("Cannot subdivide")
grid = grids[random(0, grids.size-1)]
grids.remove(grid)
divisible = isDivisible(grid, minSize)
} while (!divisible.first && !divisible.second)
// grid is about to be subdivided, so remove from result list
result.removeValueByIdentity(grid)
var pair: Pair<Rectangle2D, Rectangle2D>
// we know at least 1 side is divisible
// if both are valid, then flip a coin
if (divisible.first && divisible.second) {
pair = if (randomBoolean()) subdivideHorizontal(grid, minSize) else subdivideVertical(grid, minSize)
} else if (divisible.first) {
// only horizontally divisible
pair = subdivideHorizontal(grid, minSize)
} else {
// only vertically divisible
pair = subdivideVertical(grid, minSize)
}
// push divided items to tmp and result list
grids.add(pair.first)
grids.add(pair.second)
result.addAll(pair.first, pair.second)
}
return result
}
private fun isDivisible(grid: Rectangle2D, minSize: Int): Pair<Boolean, Boolean> {
val horizontal = grid.width / 2 >= minSize
val vertical = grid.height / 2 >= minSize
return horizontal.to(vertical)
}
private fun subdivideVertical(grid: Rectangle2D, minSize: Int): Pair<Rectangle2D, Rectangle2D> {
val lineY = random(grid.minY.toInt() + minSize, grid.maxY.toInt() - minSize).toDouble()
return Rectangle2D(grid.minX, grid.minY, grid.width, lineY - grid.minY)
.to(Rectangle2D(grid.minX, lineY, grid.width, grid.maxY - lineY))
}
private fun subdivideHorizontal(grid: Rectangle2D, minSize: Int): Pair<Rectangle2D, Rectangle2D> {
val lineX = random(grid.minX.toInt() + minSize, grid.maxX.toInt() - minSize).toDouble()
return Rectangle2D(grid.minX, grid.minY, lineX - grid.minX, grid.height)
.to(Rectangle2D(lineX, grid.minY, grid.maxX - lineX, grid.height))
}
} | fxgl-samples/src/main/kotlin/sandbox/view/AASubdivision.kt | 1948393997 |
/*
* 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.model
import com.google.gson.annotations.SerializedName
data class MediaContent(
@SerializedName("url") val url: String,
@SerializedName("type") val type: String,
@SerializedName("medium") val medium: String
) | app/src/main/kotlin/io/shtanko/picasagallery/data/model/MediaContent.kt | 2796430283 |
package cc.redpen.intellij
import java.awt.Color
import javax.swing.DefaultCellEditor
import javax.swing.JComponent
import javax.swing.JTextField
import javax.swing.border.LineBorder
import javax.swing.text.AttributeSet
import javax.swing.text.PlainDocument
internal class SingleCharEditor : DefaultCellEditor(JTextField(SingleCharEditor.SingleCharDocument(), null, 1)) {
init {
(component as JComponent).border = LineBorder(Color.black)
}
override fun stopCellEditing(): Boolean {
return (component as JTextField).text.length == 1 && super.stopCellEditing()
}
internal class SingleCharDocument : PlainDocument() {
override fun insertString(offset: Int, str: String?, a: AttributeSet?) {
if (str != null && str.length + length == 1) super.insertString(offset, str, a)
}
}
}
| src/cc/redpen/intellij/SingleCharEditor.kt | 3192946177 |
package si.pecan.services
import org.springframework.messaging.simp.SimpMessagingTemplate
import org.springframework.stereotype.Service
import si.pecan.*
import si.pecan.dto.Message
import si.pecan.dto.toDto
import si.pecan.model.ChatRoom
import si.pecan.dto.ChatRoom as Dto
import si.pecan.model.InstantMessage
import si.pecan.model.User
import java.time.LocalDateTime
import java.util.*
import javax.transaction.Transactional
import kotlin.experimental.and
@Service
class ChatService(private val userRepository: UserRepository,
private val chatRoomRepository: ChatRoomRepository,
private val instantMessageRepository: InstantMessageRepository,
private val simpMessagingTemplate: SimpMessagingTemplate) {
@Transactional
fun getOrCreateChat(initiatorUsername: String, targetUsername: String): Dto {
val target = userRepository.findByUsername(targetUsername) ?: throw UserNotFound()
val initiator = userRepository.save(userRepository.findByUsername(initiatorUsername)?.apply {
lastActive = LocalDateTime.now()
} ?: throw UserNotFound())
val chatRoom = initiator.chatRooms.find { it.users.any { it == target } } ?: chatRoomRepository.save(ChatRoom().apply {
users = arrayListOf(initiator, target)
createdBy = initiator
})
val theDto = chatRoom.toDto()
chatRoom.users.forEach { simpMessagingTemplate.convertAndSend("/topic/rooms/${it.username}", theDto) }
return theDto
}
fun ChatRoom.toDto(): si.pecan.dto.ChatRoom {
return Dto(
this.id!!,
this.createdBy.toDto(),
this.users.find { it != this.createdBy }!!.toDto(),
this.messages.map(InstantMessage::toDto),
this.created,
if (this.messages.isEmpty()) null else this.messages.last().created
)
}
@Transactional
fun postMessage(username: String, chatId: UUID, messageContent: String): Message {
val chat = chatRoomRepository.findOne(chatId) ?: throw ChatNotFound()
val user = chat.users.find { it.username == username } ?: throw UserNotAllowedToAccessChat()
return instantMessageRepository.save(InstantMessage().apply {
room = chat
content = messageContent
postedBy = user
}).toDto().apply {
this.chatId = chatId
this.postedByUser = userRepository.save(user.apply { lastActive = LocalDateTime.now()}).toDto()
}
}
fun getAllRooms(username: String): List<Dto> = chatRoomRepository
.findChatRoomIds(username)
.map {
var msb: Long = 0
var lsb: Long = 0
assert(it.size == 16) { "data must be 16 bytes in length" }
for (i in 0..7)
msb = (msb shl 8) or (it[i].toLong() and 0xff)
for (i in 8..15)
lsb = (lsb shl 8) or (it[i].toLong() and 0xff)
UUID(msb, lsb)
}
.let { chatRoomRepository.findAll(it) }
.map { it.toDto() }
} | src/main/kotlin/si/pecan/services/ChatService.kt | 2593365014 |
package actor.proto.tests
import actor.proto.DeadLetterProcess
import actor.proto.PID
import actor.proto.ProcessNameExistException
import actor.proto.ProcessRegistry
import actor.proto.fixture.TestProcess
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertSame
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import java.util.*
class ProcessRegistryTests {
@Test
fun `given pid does not exist, add should add local pid`() {
val id = UUID.randomUUID().toString()
val p = TestProcess()
val reg = ProcessRegistry
val pid = reg.put(id, p)
assertEquals(reg.address, pid.address)
}
@Test
fun `given pid exists, add should not add local pid`() {
val id = UUID.randomUUID().toString()
val p = TestProcess()
val reg = ProcessRegistry
reg.put(id, p)
assertThrows<ProcessNameExistException> ("Should throw an exception") {
reg.put(id, p)
}
}
@Test
fun `given pid exists, get should return it`() {
val id = UUID.randomUUID().toString()
val p = TestProcess()
val reg = ProcessRegistry
val pid = reg.put(id, p)
val p2 = reg.get(pid)
assertSame(p, p2)
}
@Test
fun `given pid was removed, get should return deadLetter process`() {
val id = UUID.randomUUID().toString()
val p = TestProcess()
val reg = ProcessRegistry
val pid = reg.put(id, p)
reg.remove(pid)
val p2 = reg.get(pid)
assertSame(DeadLetterProcess, p2)
}
@Test
fun `given pid exists in host resolver, get should return it`() {
val pid = PID("abc", "def")
val p = TestProcess()
val reg = ProcessRegistry
reg.registerHostResolver { _ -> p }
val p2 = reg.get(pid)
assertSame(p, p2)
}
}
| proto-actor/src/test/kotlin/actor/proto/tests/ProcessRegistryTests.kt | 2812880587 |
package com.github.ajalt.clikt.samples.helpformat
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.context
import com.github.ajalt.clikt.output.CliktHelpFormatter
import com.github.ajalt.clikt.output.HelpFormatter
import com.github.ajalt.clikt.output.Localization
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.multiple
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.option
class ArgparseLocalization : Localization {
override fun usageTitle(): String = "usage:"
override fun optionsTitle(): String = "optional arguments:"
override fun argumentsTitle(): String = "positional arguments:"
}
class ArgparseHelpFormatter : CliktHelpFormatter(ArgparseLocalization()) {
override fun formatHelp(
prolog: String,
epilog: String,
parameters: List<HelpFormatter.ParameterHelp>,
programName: String,
) = buildString {
// argparse prints arguments before options
addUsage(parameters, programName)
addProlog(prolog)
addArguments(parameters)
addOptions(parameters)
addCommands(parameters)
addEpilog(epilog)
}
}
class Echo : CliktCommand(help = "Echo the STRING(s) to standard output") {
init {
context { helpFormatter = ArgparseHelpFormatter() }
}
val suppressNewline by option("-n", help = "do not output the trailing newline").flag()
val strings by argument(help = "the strings to echo").multiple()
override fun run() {
val message = if (strings.isEmpty()) String(System.`in`.readBytes())
else strings.joinToString(" ", postfix = if (suppressNewline) "" else "\n")
echo(message, trailingNewline = false)
}
}
fun main(args: Array<String>) = Echo().main(args)
| samples/helpformat/src/main/kotlin/com/github/ajalt/clikt/samples/helpformat/main.kt | 3842450433 |
package fr.free.nrw.commons.upload
import android.net.Uri
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import fr.free.nrw.commons.filepicker.UploadableFile
import fr.free.nrw.commons.kvstore.JsonKvStore
import fr.free.nrw.commons.location.LatLng
import fr.free.nrw.commons.nearby.Place
import fr.free.nrw.commons.repository.UploadRepository
import fr.free.nrw.commons.upload.mediaDetails.UploadMediaDetailsContract
import fr.free.nrw.commons.upload.mediaDetails.UploadMediaPresenter
import fr.free.nrw.commons.utils.ImageUtils.*
import io.github.coordinates2country.Coordinates2Country
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.schedulers.TestScheduler
import junit.framework.TestCase.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.*
import org.mockito.Mockito.verify
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
import java.util.*
/**
* The class contains unit test cases for UploadMediaPresenter
*/
@RunWith(PowerMockRunner::class)
@PrepareForTest(Coordinates2Country::class)
class UploadMediaPresenterTest {
@Mock
internal lateinit var repository: UploadRepository
@Mock
internal lateinit var view: UploadMediaDetailsContract.View
private lateinit var uploadMediaPresenter: UploadMediaPresenter
@Mock
private lateinit var uploadableFile: UploadableFile
@Mock
private lateinit var place: Place
@Mock
private lateinit var uploadItem: UploadItem
@Mock
private lateinit var imageCoordinates: ImageCoordinates
@Mock
private lateinit var uploadMediaDetails: List<UploadMediaDetail>
private lateinit var testObservableUploadItem: Observable<UploadItem>
private lateinit var testSingleImageResult: Single<Int>
private lateinit var testScheduler: TestScheduler
@Mock
private lateinit var jsonKvStore: JsonKvStore
/**
* initial setup unit test environment
*/
@Before
@Throws(Exception::class)
fun setUp() {
MockitoAnnotations.initMocks(this)
testObservableUploadItem = Observable.just(uploadItem)
testSingleImageResult = Single.just(1)
testScheduler = TestScheduler()
uploadMediaPresenter = UploadMediaPresenter(repository,
jsonKvStore,testScheduler, testScheduler)
uploadMediaPresenter.onAttachView(view)
}
/**
* unit test for method UploadMediaPresenter.receiveImage
*/
@Test
fun receiveImageTest() {
whenever(
repository.preProcessImage(
ArgumentMatchers.any(UploadableFile::class.java),
ArgumentMatchers.any(Place::class.java),
ArgumentMatchers.any(UploadMediaPresenter::class.java)
)
).thenReturn(testObservableUploadItem)
uploadMediaPresenter.receiveImage(uploadableFile, place)
verify(view).showProgress(true)
testScheduler.triggerActions()
verify(view).onImageProcessed(
ArgumentMatchers.any(UploadItem::class.java),
ArgumentMatchers.any(Place::class.java)
)
verify(view).showProgress(false)
}
/**
* unit test for method UploadMediaPresenter.verifyImageQuality (For else case)
*/
@Test
fun verifyImageQualityTest() {
whenever(repository.uploads).thenReturn(listOf(uploadItem))
whenever(repository.getImageQuality(uploadItem))
.thenReturn(testSingleImageResult)
whenever(uploadItem.imageQuality).thenReturn(0)
whenever(uploadItem.gpsCoords)
.thenReturn(imageCoordinates)
whenever(uploadItem.gpsCoords.decimalCoords)
.thenReturn("imageCoordinates")
uploadMediaPresenter.verifyImageQuality(0)
verify(view).showProgress(true)
testScheduler.triggerActions()
verify(view).showProgress(false)
}
/**
* unit test for method UploadMediaPresenter.verifyImageQuality (For if case)
*/
@Test
fun `verify ImageQuality Test while coordinates equals to null`() {
whenever(repository.uploads).thenReturn(listOf(uploadItem))
whenever(repository.getImageQuality(uploadItem))
.thenReturn(testSingleImageResult)
whenever(uploadItem.imageQuality).thenReturn(0)
whenever(uploadItem.gpsCoords)
.thenReturn(imageCoordinates)
whenever(uploadItem.gpsCoords.decimalCoords)
.thenReturn(null)
uploadMediaPresenter.verifyImageQuality(0)
testScheduler.triggerActions()
}
/**
* unit test for method UploadMediaPresenter.handleImageResult
*/
@Test
fun handleImageResult() {
//Positive case test
uploadMediaPresenter.handleImageResult(IMAGE_KEEP, uploadItem)
verify(view).onImageValidationSuccess()
//Duplicate file name
uploadMediaPresenter.handleImageResult(FILE_NAME_EXISTS, uploadItem)
verify(view).showDuplicatePicturePopup(uploadItem)
//Empty Caption test
uploadMediaPresenter.handleImageResult(EMPTY_CAPTION, uploadItem)
verify(view).showMessage(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt())
//Bad Picture test
//Empty Caption test
uploadMediaPresenter.handleImageResult(-7, uploadItem)
verify(view)?.showBadImagePopup(ArgumentMatchers.anyInt(), ArgumentMatchers.eq(uploadItem))
}
@Test
fun addSingleCaption() {
val uploadMediaDetail = UploadMediaDetail()
uploadMediaDetail.captionText = "added caption"
uploadMediaDetail.languageCode = "en"
val uploadMediaDetailList: ArrayList<UploadMediaDetail> = ArrayList()
uploadMediaDetailList.add(uploadMediaDetail)
uploadItem.setMediaDetails(uploadMediaDetailList)
Mockito.`when`(repository.getImageQuality(uploadItem)).then {
verify(view).showProgress(true)
testScheduler.triggerActions()
verify(view).showProgress(true)
verify(view).onImageValidationSuccess()
}
}
@Test
fun addMultipleCaptions() {
val uploadMediaDetail = UploadMediaDetail()
uploadMediaDetail.captionText = "added caption"
uploadMediaDetail.languageCode = "en"
uploadMediaDetail.captionText = "added caption"
uploadMediaDetail.languageCode = "eo"
uploadItem.setMediaDetails(Collections.singletonList(uploadMediaDetail))
Mockito.`when`(repository.getImageQuality(uploadItem)).then {
verify(view).showProgress(true)
testScheduler.triggerActions()
verify(view).showProgress(true)
verify(view).onImageValidationSuccess()
}
}
/**
* Test fetch image title when there was one
*/
@Test
fun fetchImageAndTitleTest() {
whenever(repository.uploads).thenReturn(listOf(uploadItem))
whenever(repository.getUploadItem(ArgumentMatchers.anyInt()))
.thenReturn(uploadItem)
whenever(uploadItem.uploadMediaDetails).thenReturn(listOf())
uploadMediaPresenter.fetchTitleAndDescription(0)
verify(view).updateMediaDetails(ArgumentMatchers.any())
}
/**
* Test bad image invalid location
*/
@Test
fun handleBadImageBaseTestInvalidLocation() {
uploadMediaPresenter.handleBadImage(8, uploadItem)
verify(view).showBadImagePopup(8, uploadItem)
}
/**
* Test bad image empty title
*/
@Test
fun handleBadImageBaseTestEmptyTitle() {
uploadMediaPresenter.handleBadImage(-3, uploadItem)
verify(view).showMessage(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt())
}
/**
* Teste show file already exists
*/
@Test
fun handleBadImageBaseTestFileNameExists() {
uploadMediaPresenter.handleBadImage(-4, uploadItem)
verify(view).showDuplicatePicturePopup(uploadItem)
}
/**
* Test show SimilarImageFragment
*/
@Test
fun showSimilarImageFragmentTest() {
val similar: ImageCoordinates = mock()
uploadMediaPresenter.showSimilarImageFragment("original", "possible", similar)
verify(view).showSimilarImageFragment("original", "possible", similar)
}
@Test
fun setCorrectCountryCodeForReceivedImage() {
val germanyAsPlace = Place(null,null, null, null, LatLng(50.1, 10.2, 1.0f), null, null, null, true)
germanyAsPlace.isMonument = true
PowerMockito.mockStatic(Coordinates2Country::class.java)
whenever(
Coordinates2Country.country(
ArgumentMatchers.eq(germanyAsPlace.getLocation().latitude),
ArgumentMatchers.eq(germanyAsPlace.getLocation().longitude)
)
).thenReturn("Germany")
val item: Observable<UploadItem> = Observable.just(UploadItem(Uri.EMPTY, null, null, germanyAsPlace, 0, null, null, null))
whenever(
repository.preProcessImage(
ArgumentMatchers.any(UploadableFile::class.java),
ArgumentMatchers.any(Place::class.java),
ArgumentMatchers.any(UploadMediaPresenter::class.java)
)
).thenReturn(item)
uploadMediaPresenter.receiveImage(uploadableFile, germanyAsPlace)
verify(view).showProgress(true)
testScheduler.triggerActions()
val captor: ArgumentCaptor<UploadItem> = ArgumentCaptor.forClass(UploadItem::class.java)
verify(view).onImageProcessed(
captor.capture(),
ArgumentMatchers.any(Place::class.java)
)
assertEquals("Exptected contry code", "de", captor.value.countryCode);
verify(view).showProgress(false)
}
}
| app/src/test/kotlin/fr/free/nrw/commons/upload/UploadMediaPresenterTest.kt | 1529702226 |
package cn.yiiguxing.plugin.translate.trans.google
import cn.yiiguxing.plugin.translate.message
import cn.yiiguxing.plugin.translate.trans.text.TranslationDocument
import cn.yiiguxing.plugin.translate.ui.StyledViewer
import cn.yiiguxing.plugin.translate.util.chunked
import cn.yiiguxing.plugin.translate.util.text.*
import com.intellij.ui.JBColor
import com.intellij.ui.scale.JBUIScale
import icons.TranslationIcons
import java.awt.Color
import javax.swing.text.*
class GoogleExamplesDocument private constructor(private val examples: List<List<CharSequence>>) : TranslationDocument {
override val text: String
get() = examples.joinToString("\n") { it.joinToString("") }
override fun applyTo(viewer: StyledViewer) {
viewer.styledDocument.apply {
initStyle()
val startOffset = length
appendExamples()
setParagraphStyle(startOffset, length - startOffset, EXAMPLE_PARAGRAPH_STYLE, false)
}
}
private fun StyledDocument.appendExamples() {
appendExample(examples.first(), false)
if (examples.size > 1) {
newLine()
val startOffset = length
val foldingAttr = SimpleAttributeSet(getStyle(EXAMPLE_FOLDING_STYLE))
StyledViewer.StyleConstants.setMouseListener(foldingAttr, createFoldingMouseListener(examples.drop(1)))
val placeholder = " " + message("title.google.document.examples.show.all", examples.size) + " "
appendString(placeholder, foldingAttr)
setParagraphStyle(startOffset, placeholder.length, EXAMPLE_FOLDING_PARAGRAPH_STYLE, false)
}
}
private fun StyledDocument.appendExample(example: List<CharSequence>, newLine: Boolean = true) {
if (newLine) {
newLine()
}
appendString(" ", ICON_QUOTE_STYLE)
appendString("\t")
for (ex in example) {
appendCharSequence(ex)
}
}
private fun createFoldingMouseListener(foldedExamples: List<List<CharSequence>>): StyledViewer.FoldingMouseListener {
return StyledViewer.FoldingMouseListener(foldedExamples) { viewer, element, _ ->
viewer.styledDocument.apply {
remove(element.startOffset - 1, element.rangeSize + 1)
val startOffset = length
examples.drop(1).forEach { appendExample(it) }
setParagraphStyle(startOffset, length - startOffset, EXAMPLE_PARAGRAPH_STYLE, true)
}
}
}
override fun toString(): String = text
companion object : TranslationDocument.Factory<GExamples?, GoogleExamplesDocument> {
private val BOLD_REGEX = Regex("<b>(.+?)</b>")
private const val EXAMPLE_PARAGRAPH_STYLE = "g_example_p_style"
private const val ICON_QUOTE_STYLE = "g_example_icon_quote_style"
private const val EXAMPLE_BOLD_STYLE = "g_example_bold_style"
private const val EXAMPLE_FOLDING_STYLE = "g_example_folding_style"
private const val EXAMPLE_FOLDING_PARAGRAPH_STYLE = "g_example_folding_ps"
override fun getDocument(input: GExamples?): GoogleExamplesDocument? {
if (input == null || input.examples.isEmpty()) {
return null
}
val examples = input.examples.asSequence()
.map { (example) ->
example.chunked(BOLD_REGEX) { StyledString(it.groupValues[1], EXAMPLE_BOLD_STYLE) }
}
.toList()
return GoogleExamplesDocument(examples)
}
private fun StyledDocument.initStyle() {
val defaultStyle = getStyle(StyleContext.DEFAULT_STYLE)
getStyleOrAdd(EXAMPLE_PARAGRAPH_STYLE, defaultStyle) { style ->
StyleConstants.setTabSet(style, TabSet(arrayOf(TabStop(JBUIScale.scale(5f)))))
StyleConstants.setForeground(style, JBColor(0x606060, 0xBBBDBF))
}
getStyleOrAdd(EXAMPLE_BOLD_STYLE, defaultStyle) { style ->
StyleConstants.setBold(style, true)
StyleConstants.setForeground(style, JBColor(0x555555, 0xC8CACC))
}
getStyleOrAdd(ICON_QUOTE_STYLE) { style ->
StyleConstants.setIcon(style, TranslationIcons.Quote)
}
getStyleOrAdd(EXAMPLE_FOLDING_STYLE, defaultStyle) { style ->
StyleConstants.setFontSize(style, getFont(style).size - 1)
StyleConstants.setForeground(style, JBColor(0x777777, 0x888888))
val background = JBColor(Color(0, 0, 0, 0x18), Color(0xFF, 0xFF, 0xFF, 0x10))
StyleConstants.setBackground(style, background)
}
getStyleOrAdd(EXAMPLE_FOLDING_PARAGRAPH_STYLE, defaultStyle) { style ->
StyleConstants.setSpaceAbove(style, JBUIScale.scale(8f))
}
}
}
} | src/main/kotlin/cn/yiiguxing/plugin/translate/trans/google/GoogleExamplesDocument.kt | 2413726510 |
package ycj.com.familyledger.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import org.jetbrains.anko.find
import ycj.com.familyledger.R
import ycj.com.familyledger.bean.LedgerBean
/**
* @author: ycj
* @date: 2017-06-14 10:53
* @version V1.0 <>
*/
class KHomeAdapter : RecyclerView.Adapter<KHomeAdapter.MyViewHolder> {
private var mContext: Context
private var dataList: ArrayList<LedgerBean>
constructor(dataList: ArrayList<LedgerBean>, context: Context) {
this.mContext = context
this.dataList = dataList
}
override fun onBindViewHolder(holder: MyViewHolder?, position: Int) {
holder!!.tvTitle.text = mContext.getString(R.string.date) + " " + dataList[position].consume_date
holder.tvContent.text = mContext.getString(R.string.cash) + " " + dataList[position].consume_money
holder.tvPhone.text = dataList[position].user_id.toString()
holder.ly.setOnClickListener {
if (listener != null) {
listener!!.onItemClickListener(position)
}
}
holder.ly.setOnLongClickListener({
if (listener != null) {
listener!!.onItemLongClickListener(position)
}
true
})
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyViewHolder {
return MyViewHolder(LayoutInflater.from(mContext).inflate(R.layout.list_item_home, parent, false))
}
override fun getItemCount(): Int {
return dataList.size
}
class MyViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
var tvTitle: TextView = itemView!!.find(R.id.t_title_home)
var tvContent: TextView = itemView!!.find(R.id.t_content_home)
var tvPhone: TextView = itemView!!.find(R.id.tv_phone_home)
var ly: LinearLayout = itemView!!.find(R.id.ly_list_item_home)
var fy: FrameLayout = itemView!!.find(R.id.fy_list_item_home)
}
private var listener: ItemClickListener? = null
fun setOnItemClickListener(listener: ItemClickListener) {
this.listener = listener
}
interface ItemClickListener {
fun onItemClickListener(position: Int)
fun onItemLongClickListener(position: Int)
}
fun addNewItem(position: Int, data: LedgerBean) {
if (position >= dataList.size) return
dataList.add(position, data)
notifyItemInserted(position)
}
fun setDatas(data: List<LedgerBean>) {
if (data.size == 0) return
dataList.clear()
dataList.addAll(data)
notifyDataSetChanged()
}
fun clearData() {
dataList.clear()
notifyDataSetChanged()
}
} | app/src/main/java/ycj/com/familyledger/adapter/KHomeAdapter.kt | 1157038169 |
package de.maibornwolff.codecharta.importer.metricgardenerimporter.json
import de.maibornwolff.codecharta.importer.metricgardenerimporter.getAttributeDescriptors
import de.maibornwolff.codecharta.importer.metricgardenerimporter.model.MetricGardenerNode
import de.maibornwolff.codecharta.importer.metricgardenerimporter.model.MetricGardenerNodes
import de.maibornwolff.codecharta.model.MutableNode
import de.maibornwolff.codecharta.model.NodeType
import org.junit.Test
import org.junit.jupiter.api.Assertions.assertEquals
internal class MetricGardenerProjectBuilderTest {
private val metricGardenerprojectBuilder: MetricGardenerProjectBuilder = MetricGardenerProjectBuilder(MetricGardenerNodes(mutableListOf(MetricGardenerNode("\\test-project\\path1\\test-project.path1.Logic\\Service\\TestService.kt",
"File",
mapOf("mcc" to 3, "functions" to 3, "classes" to 1, "lines_of_code" to 79, "comment_lines" to 32, "real_lines_of_code" to 40)), MetricGardenerNode("\\test-project\\path1\\test-project.path1.Logic\\Service\\UserLogonService.kt",
"File", mapOf("mcc" to 34, "functions" to 8, "classes" to 1, "lines_of_code" to 188, "comment_lines" to 0, "real_lines_of_code" to 155)))))
@Test
fun whenExtractFileNameFromPathThenSuccess() {
val privateExtractFileNameFromPathMethod = metricGardenerprojectBuilder.javaClass.getDeclaredMethod("extractFileNameFromPath", String::class.java)
privateExtractFileNameFromPathMethod.isAccessible = true
val fileName = privateExtractFileNameFromPathMethod.invoke(metricGardenerprojectBuilder, "\\test-project\\path1\\test-project.path1.Logic\\Service\\TestService.kt")
assertEquals("TestService.kt", fileName)
}
@Test
fun whenGenerateFileNodeThenSuccess() {
val fileNode = metricGardenerprojectBuilder.generateCodeChartaFileNode(metricGardenerprojectBuilder.metricGardenerNodes.metricGardenerNodes.elementAt(0))
val node = MutableNode("TestService.kt", NodeType.File, mapOf("mcc" to 3, "functions" to 3, "classes" to 1, "lines_of_code" to 79, "comment_lines" to 32, "real_lines_of_code" to 40), "", setOf())
assertEquals(fileNode.name, node.name)
assertEquals(fileNode.attributes, node.attributes)
}
@Test
fun `should generate project with descriptors`() {
val project = metricGardenerprojectBuilder.build()
assertEquals(project.attributeDescriptors, getAttributeDescriptors())
}
}
| analysis/import/MetricGardenerImporter/src/test/kotlin/de/maibornwolff/codecharta/importer/metricgardenerimporter/json/MetricGardenerProjectBuilderTest.kt | 1970195987 |
package com.mhp.showcase.network
import android.os.Handler
import android.util.Log
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.google.gson.Gson
import com.mhp.showcase.ShowcaseApplication
import com.mhp.showcase.network.model.ContentResponse
import com.mhp.showcase.util.Constants
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import javax.inject.Inject
/**
* Network service to get the definition of blocks for the home screen
*/
class GetArticleNetworkService {
private val tag = GetArticleNetworkService::class.java.simpleName
@Inject
internal lateinit var requestQueue: RequestQueue
@Inject
internal lateinit var gson: Gson
fun getBlocks(id: String): Observable<ContentResponse> {
return Observable.create<ContentResponse>({ it ->
this.startRequesting(e = it, id = id)
})
}
private fun startRequesting(id: String, e: ObservableEmitter<ContentResponse>) {
if (e.isDisposed) {
return
}
val jsObjRequest = JsonObjectRequest(
Request.Method.GET,
Constants.URL_ARTICLE + "-" + id + ".json", null,
Response.Listener {
val blockResponse = gson.fromJson(it.toString(), ContentResponse::class.java)
e.onNext(blockResponse)
Handler().postDelayed({ startRequesting(id, e) }, 2000)
},
Response.ErrorListener {
Log.d(tag, "Network error occurred", it)
}
)
jsObjRequest.setShouldCache(false)
requestQueue.add(jsObjRequest)
}
init {
ShowcaseApplication.graph.inject(this)
}
} | app/src/main/kotlin/com/mhp/showcase/network/GetArticleNetworkService.kt | 702975516 |
package ee.task
import ee.design.*
import ee.lang.*
object Task : Comp({ namespace("ee.task") }) {
object shared : Module() {
object TaskGroup : Entity() {
val taskFactories = prop(n.List.GT(TaskFactory))
val tasks = prop(n.List.GT(Task))
}
object Result : Values({ base(true) }) {
val action = prop()
val ok = prop { type(n.Boolean).value(true).open(true) }
val failure = prop()
val info = prop()
val error = prop { type(n.Error).nullable(true) }
val results = prop { type(n.List.GT(Result)).mutable(false) }
}
object Task : Controller() {
val name = prop()
val group = prop()
val execute = op {
p { type(lambda { p { name("line") } }).name("output") }
ret(Result)
}
}
object TaskResult : Values() {
val task = prop(Task)
val result = prop(Result)
}
object TaskFactory : Controller() {
val T = G(Task)
val name = prop()
val group = prop()
val supports = op {
p { type(n.List.GT(l.Item)).nullable(false).name("items") }
ret(n.Boolean)
}
val create = op {
p { type(n.List.GT(l.Item)).nullable(false).name("items") }
ret(n.List.GT(T))
}
}
object TaskRepository : Controller() {
val typeFactories = prop(n.List.GT(TaskFactory))
val register = op {
val V = G { type(TaskFactory).name("V") }
p { type(V).nullable(false).initByDefaultTypeValue(false).name("factory") }
}
val find = op {
val T = G { type(l.Item).name("T") }
p { type(n.List.GT(T)).initByDefaultTypeValue(false).name("items") }
ret(n.List.GT(TaskFactory))
}
}
object PathResolver : Controller() {
val home = prop(n.Path)
val itemToHome = prop(n.Map.GT(n.String, n.String))
val resolve = op {
val T = G { type(l.Item).name("T") }
p { type(T).nullable(false).initByDefaultTypeValue(false).name("addItem") }
ret(n.Path)
}
}
object TaskRegistry : Controller() {
val pathResolver = prop(PathResolver)
val register = op {
p { type(TaskRepository).name("repo") }
}
}
object ExecConfig : Values() {
val home = prop(n.Path)
val cmd = prop { type(n.List.GT(n.String)).mutable(false) }
val env = prop { type(n.Map.GT(n.String, n.String)).mutable(false) }
val filterPattern = prop { defaultValue(".*(\\.{4}|exception|error|fatal|success).*") }
val failOnError = prop { type(n.Boolean).value(false) }
val filter = prop { type(n.Boolean).value(false) }
val noConsole = prop { type(n.Boolean).value(false) }
val wait = prop { type(n.Boolean).value(true) }
val timeout = prop { type(n.Long).value(30.seconds) }
val timeoutUnit = prop { type(n.TimeUnit).value(n.TimeUnit.Seconds) }
}
}
}
| ee-task_des/src/main/kotlin/ee/task/Task.kt | 3560604403 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.homesampleapp.data
import android.content.Context
import com.google.homesampleapp.Device
import com.google.homesampleapp.Devices
import dagger.hilt.android.qualifiers.ApplicationContext
import java.io.IOException
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import timber.log.Timber
/**
* Singleton repository that updates and persists the set of devices in the homesampleapp fabric.
*/
@Singleton
class DevicesRepository @Inject constructor(@ApplicationContext context: Context) {
// The datastore managed by DevicesRepository.
private val devicesDataStore = context.devicesDataStore
// The Flow to read data from the DataStore.
val devicesFlow: Flow<Devices> =
devicesDataStore.data.catch { exception ->
// dataStore.data throws an IOException when an error is encountered when reading data
if (exception is IOException) {
Timber.e(exception, "Error reading devices.")
emit(Devices.getDefaultInstance())
} else {
throw exception
}
}
suspend fun incrementAndReturnLastDeviceId(): Long {
val newLastDeviceId = devicesFlow.first().lastDeviceId + 1
Timber.d("incrementAndReturnLastDeviceId(): newLastDeviceId [${newLastDeviceId}] ")
devicesDataStore.updateData { devices ->
devices.toBuilder().setLastDeviceId(newLastDeviceId).build()
}
return newLastDeviceId
}
suspend fun addDevice(device: Device) {
Timber.d("addDevice: device [${device}]")
devicesDataStore.updateData { devices -> devices.toBuilder().addDevices(device).build() }
}
suspend fun updateDevice(device: Device) {
Timber.d("updateDevice: device [${device}]")
val index = getIndex(device.deviceId)
devicesDataStore.updateData { devices -> devices.toBuilder().setDevices(index, device).build() }
}
suspend fun removeDevice(deviceId: Long) {
Timber.d("removeDevice: device [${deviceId}]")
val index = getIndex(deviceId)
if (index == -1) {
throw Exception("Device not found: $deviceId")
}
devicesDataStore.updateData { devicesList ->
devicesList.toBuilder().removeDevices(index).build()
}
}
suspend fun getLastDeviceId(): Long {
return devicesFlow.first().lastDeviceId
}
suspend fun getDevice(deviceId: Long): Device {
val devices = devicesFlow.first()
val index = getIndex(devices, deviceId)
if (index == -1) {
throw Exception("Device not found: $deviceId")
}
return devices.getDevices(index)
}
suspend fun getAllDevices(): Devices {
return devicesFlow.first()
}
private suspend fun getIndex(deviceId: Long): Int {
val devices = devicesFlow.first()
return getIndex(devices, deviceId)
}
private fun getIndex(devices: Devices, deviceId: Long): Int {
val devicesCount = devices.devicesCount
for (index in 0 until devicesCount) {
val device = devices.getDevices(index)
if (deviceId == device.deviceId) {
return index
}
}
return -1
}
}
| app/src/main/java/com/google/homesampleapp/data/DevicesRepository.kt | 1697653215 |
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.network
data class Connectivity(
val isConnected: Boolean = false,
val isMetered: Boolean = false,
val isWifi: Boolean = false,
val isServerAvailable: Boolean? = null
) {
companion object {
@JvmField
val DISCONNECTED = Connectivity()
@JvmField
val CONNECTED_WIFI = Connectivity(
isConnected = true,
isMetered = false,
isWifi = true,
isServerAvailable = true
)
}
}
| src/main/java/com/nextcloud/client/network/Connectivity.kt | 18597221 |
package com.gitlab.daring.fms.zabbix.agent.active
import com.gitlab.daring.fms.zabbix.agent.active.AgentResponse.Companion.Failed
import com.gitlab.daring.fms.zabbix.agent.active.AgentResponse.Companion.Success
import io.kotlintest.matchers.shouldBe
import io.kotlintest.specs.FunSpec
class AgentResponseTest : FunSpec({
test("success") {
AgentResponse(Success).success shouldBe true
AgentResponse(Failed).success shouldBe false
AgentResponse("").success shouldBe false
}
}) | zabbix/core/src/test/kotlin/com/gitlab/daring/fms/zabbix/agent/active/AgentResponseTest.kt | 1182780113 |
/**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.5.1-pre.0
* Contact: [email protected]
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.api.model
import org.openapitools.server.api.model.PipelineBranchesitempullRequestlinks
import com.google.gson.annotations.SerializedName
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
/**
*
* @param links
* @param author
* @param id
* @param title
* @param url
* @param propertyClass
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
data class PipelineBranchesitempullRequest (
val links: PipelineBranchesitempullRequestlinks? = null,
val author: kotlin.String? = null,
val id: kotlin.String? = null,
val title: kotlin.String? = null,
val url: kotlin.String? = null,
val propertyClass: kotlin.String? = null
) {
}
| clients/kotlin-vertx/generated/src/main/kotlin/org/openapitools/server/api/model/PipelineBranchesitempullRequest.kt | 4045664008 |
/**
* 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 stop entity
*
* @author Carl-Philipp Harmant
* @version 1
*/
class BusStop(
id: String,
name: String,
val description: String,
val position: Position) : Comparable<BusStop>, Parcelable, Station(id, name) {
companion object {
@JvmField
val CREATOR: Parcelable.Creator<BusStop> = object : Parcelable.Creator<BusStop> {
override fun createFromParcel(source: Parcel): BusStop {
return BusStop(source)
}
override fun newArray(size: Int): Array<BusStop?> {
return arrayOfNulls(size)
}
}
}
private constructor(source: Parcel) : this(
id = source.readString() ?: StringUtils.EMPTY,
name = source.readString() ?: StringUtils.EMPTY,
description = source.readString() ?: StringUtils.EMPTY,
position = source.readParcelable<Position>(Position::class.java.classLoader) ?: Position())
override fun toString(): String {
return "[id:$id;name:$name;description:$description;position:$position]"
}
override fun compareTo(other: BusStop): Int {
val position = other.position
val latitude = position.latitude.compareTo(position.latitude)
return if (latitude == 0) position.longitude.compareTo(position.longitude) else latitude
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(id)
dest.writeString(name)
dest.writeString(description)
dest.writeParcelable(position, flags)
}
}
| android-app/src/main/kotlin/fr/cph/chicago/core/model/BusStop.kt | 1815999193 |
package de.ph1b.audiobook.common
interface ApplicationIdProvider {
val applicationID: String
}
| common/src/main/kotlin/de/ph1b/audiobook/common/ApplicationIdProvider.kt | 2240175601 |
package shark
import org.assertj.core.api.Assertions
import org.junit.Test
import shark.LongScatterSetAssertion.Companion.assertThat
import shark.internal.hppc.HPPC.mixPhi
import shark.internal.hppc.LongScatterSet
class LongScatterSetTest {
@Test fun `new set is empty`() {
assertThat(LongScatterSet())
.isEmpty()
}
@Test fun `LongScatterSet#add() adds elements`() {
val set = LongScatterSet()
TEST_VALUES_LIST.forEach { set.add(it) }
assertThat(set)
.containsExactly(TEST_VALUES_LIST)
}
@Test fun `+= operator works as addition`() {
val set = LongScatterSet()
set += TEST_VALUE
assertThat(set)
.containsExactly(TEST_VALUE)
}
@Test fun `when adding element twice, it is only added once`() {
val set = LongScatterSet()
set.add(TEST_VALUE)
set.add(TEST_VALUE)
assertThat(set)
.containsExactly(TEST_VALUE)
}
/**
* [LongScatterSet] calculates hash for its values using [mixPhi] function.
* Inevitably, there can be collisions when two different values have same hash value;
* [LongScatterSet] should handle such collisions properly.
* There are two tests that verify adding and removing operations for values with matching hash value;
* current test verifies that values we use in those tests actually do have matching hashes.
*/
@Test fun `11 and 14_723_950_898 have same hash`() {
Assertions.assertThat(mixPhi(11))
.isEqualTo(mixPhi(14_723_950_898))
}
@Test fun `elements with equal hash can be added`() {
val set = LongScatterSet()
set.add(SAME_MIX_PHI_1)
set.add(SAME_MIX_PHI_2)
assertThat(set)
.containsExactly(listOf(SAME_MIX_PHI_1, SAME_MIX_PHI_2))
}
@Test fun `LongScatterSet#remove() removes elements`() {
val set = LongScatterSet()
TEST_VALUES_LIST.forEach { set.add(it) }
TEST_VALUES_LIST.forEach { set.remove(it) }
assertThat(set)
.isEmpty()
}
@Test fun `removing from empty set`() {
val set = LongScatterSet()
set.remove(TEST_VALUE)
assertThat(set)
.isEmpty()
}
@Test fun `elements with equal hash can be removed`() {
val set = LongScatterSet()
set.add(SAME_MIX_PHI_1)
set.add(SAME_MIX_PHI_2)
set.remove(SAME_MIX_PHI_2)
assertThat(set)
.containsExactly(SAME_MIX_PHI_1)
}
@Test fun `LongScatterSet#release() empties set`() {
val set = LongScatterSet()
set.add(TEST_VALUE)
set.release()
assertThat(set)
.isEmpty()
}
/**
* Verifies that calling [LongScatterSet.ensureCapacity] after elements has been added to set
* does not damage the data in set
*/
@Test fun `setting initial capacity after operations`() {
val set = LongScatterSet()
set.add(TEST_VALUE)
set.ensureCapacity(TEST_CAPACITY)
assertThat(set)
.containsExactly(TEST_VALUE)
}
@Test fun `adding a lot of elements causes resizing`() {
val set = LongScatterSet()
(1..100L).forEach { set.add(it) }
assertThat(set)
.containsExactly((1..100L).toList())
}
companion object {
// Values SAME_MIX_PHI_1 and SAME_MIX_PHI_2 have same hash when calculated via HHPC.mixPhi()
const val SAME_MIX_PHI_1 = 11L
const val SAME_MIX_PHI_2 = 14_723_950_898L
val TEST_VALUES_LIST = listOf(42, 0, Long.MIN_VALUE, Long.MAX_VALUE, -1)
const val TEST_VALUE = 12L
const val TEST_CAPACITY = 10
}
}
| shark-graph/src/test/java/shark/LongScatterSetTest.kt | 3639286823 |
package org.gravidence.gravifon.util
fun <T> nullableListOf(element: T?): List<T>? {
return if (element == null) {
null
} else {
listOf(element)
}
}
fun <T> firstNotEmptyOrNull(vararg collection: Collection<T>?): Collection<T>? {
return collection.firstOrNull { it?.isNotEmpty() ?: false }
}
fun <T> Iterable<T>.joinViaSpace(): String {
return joinToString(separator = " ")
} | gravifon/src/main/kotlin/org/gravidence/gravifon/util/CommonUtil.kt | 2765263308 |
package com.benny.pxerstudio.shape.draw
import android.graphics.Color
import android.graphics.Paint
import com.benny.pxerstudio.widget.PxerView
import com.benny.pxerstudio.widget.PxerView.Pxer
/**
* Created by BennyKok on 10/12/2016.
*/
class LineShape : DrawShape() {
private val p = Paint()
private val previousPxer = ArrayList<Pxer>()
private var hasInit = false
var width: Float
get() { return p.strokeWidth }
set(value) { p.strokeWidth = value }
override fun onDraw(
pxerView: PxerView,
startX: Int,
startY: Int,
endX: Int,
endY: Int
): Boolean {
if (!super.onDraw(pxerView, startX, startY, endX, endY)) {
return true
}
if (!hasInit) {
p.color = Color.YELLOW
pxerView.preview!!.eraseColor(Color.TRANSPARENT)
pxerView.previewCanvas.setBitmap(pxerView.preview)
hasInit = true
}
val layerToDraw = pxerView.pxerLayers[pxerView.currentLayer]!!.bitmap
draw(layerToDraw!!, previousPxer)
pxerView.preview!!.eraseColor(Color.TRANSPARENT)
/*
if (startX < endX) endX++ else endX--
if (startX > endX) startX++ else startX--
if (startY < endY) endY++ else endY--
if (startY > endY) startY++ else startY--
*/
pxerView.previewCanvas.drawLine(
startX.toFloat(),
startY.toFloat(),
endX.toFloat(),
endY.toFloat(),
p
)
// pxerView.preview!!.setPixel(startX, startY, pxerView.selectedColor)
// pxerView.preview!!.setPixel(endX, endY, pxerView.selectedColor)
for (i in 0 until pxerView.picWidth) {
for (y in 0 until pxerView.picHeight) {
var c = pxerView.preview!!.getPixel(i, y)
if (i == startX && y == startY || i == endX && y == endY) c = Color.YELLOW
if (c == Color.YELLOW) {
addPxerView(layerToDraw, previousPxer, i, y)
drawOnLayer(layerToDraw, pxerView, i, y)
}
}
}
pxerView.invalidate()
return true
}
override fun onDrawEnd(pxerView: PxerView) {
super.onDrawEnd(pxerView)
hasInit = false
pxerView.endDraw(previousPxer)
}
init {
p.style = Paint.Style.STROKE
p.strokeWidth = 1f
}
}
| app/src/main/java/com/benny/pxerstudio/shape/draw/LineShape.kt | 1535037899 |
/*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS 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.
*
* QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util
import android.content.Context
import android.graphics.Typeface
import androidx.core.content.res.ResourcesCompat
import com.moez.QKSMS.R
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class FontProvider @Inject constructor(context: Context) {
private var lato: Typeface? = null
private val pendingCallbacks = ArrayList<(Typeface) -> Unit>()
init {
ResourcesCompat.getFont(context, R.font.lato, object : ResourcesCompat.FontCallback() {
override fun onFontRetrievalFailed(reason: Int) {
Timber.w("Font retrieval failed: $reason")
}
override fun onFontRetrieved(typeface: Typeface) {
lato = typeface
pendingCallbacks.forEach { lato?.run(it) }
pendingCallbacks.clear()
}
}, null)
}
fun getLato(callback: (Typeface) -> Unit) {
lato?.run(callback) ?: pendingCallbacks.add(callback)
}
} | presentation/src/main/java/com/moez/QKSMS/common/util/FontProvider.kt | 1473145500 |
@file:JvmName("XpActivityManager")
package net.xpece.android.app
import android.app.ActivityManager
import android.app.Service
@Suppress("DEPRECATION")
inline fun <reified T : Service> ActivityManager.getRunningServiceInfo(): ActivityManager.RunningServiceInfo? =
getRunningServices(Integer.MAX_VALUE).firstOrNull {
T::class.java.name == it.service.className
}
| commons/src/main/java/net/xpece/android/app/ActivityManager.kt | 1298881640 |
/*
* 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.android.trackr.ui.settings
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.commitNow
import com.example.android.trackr.R
import com.example.android.trackr.databinding.SettingsFragmentBinding
import com.example.android.trackr.ui.dataBindings
class SettingsFragment : Fragment(R.layout.settings_fragment) {
private val binding by dataBindings(SettingsFragmentBinding::bind)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// We need to access binding once in order for Data Binding to bind the views.
binding.root
if (childFragmentManager.findFragmentById(R.id.preference) == null) {
childFragmentManager.commitNow {
replace(R.id.preference, SettingsPreferenceFragment())
}
}
}
}
| app/src/main/java/com/example/android/trackr/ui/settings/SettingsFragment.kt | 1703954612 |
/*
* 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.sectionedlist.stateful
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DirectionsRun
import androidx.compose.material.icons.filled.SelfImprovement
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlin.random.Random
class SectionedListStatefulScreenViewModel : ViewModel() {
private val _uiState = MutableStateFlow(
UiState(
recommendationSectionState = RecommendationSectionState.Loading,
trendingSectionState = TrendingSectionState.Loading
)
)
val uiState: StateFlow<UiState> = _uiState
init {
loadRecommendations()
loadTrending()
}
data class UiState(
val recommendationSectionState: RecommendationSectionState,
val trendingSectionState: TrendingSectionState
)
sealed class RecommendationSectionState {
object Loading : RecommendationSectionState()
data class Loaded(val list: List<Recommendation>) : RecommendationSectionState()
object Failed : RecommendationSectionState()
}
data class Recommendation(
val playlistName: String,
val icon: ImageVector
)
sealed class TrendingSectionState {
object Loading : TrendingSectionState()
data class Loaded(val list: List<Trending>) : TrendingSectionState()
object Failed : TrendingSectionState()
}
data class Trending(
val name: String,
val artist: String
)
fun loadRecommendations() {
viewModelScope.launch {
_uiState.value = _uiState.value.copy(
recommendationSectionState = RecommendationSectionState.Loading
)
// pretend it is fetching date over remote
delay(getRandomTimeInMillis())
_uiState.value = _uiState.value.copy(
recommendationSectionState = if (shouldFailToLoad()) {
RecommendationSectionState.Failed
} else {
RecommendationSectionState.Loaded(
list = listOf(
Recommendation("Running playlist", Icons.Default.DirectionsRun),
Recommendation("Focus", Icons.Default.SelfImprovement)
)
)
}
)
}
}
fun loadTrending() {
viewModelScope.launch {
_uiState.value = _uiState.value.copy(
trendingSectionState = TrendingSectionState.Loading
)
// pretend it is fetching date over remote
delay(getRandomTimeInMillis())
_uiState.value = _uiState.value.copy(
trendingSectionState = if (shouldFailToLoad()) {
TrendingSectionState.Failed
} else {
TrendingSectionState.Loaded(
list = listOf(
Trending("There'd Better Be A Mirrorball", "Arctic Monkeys"),
Trending("180 Hours", "Dudu Kanegae")
)
)
}
)
}
}
private fun shouldFailToLoad(): Boolean {
return Random.nextInt(1, 3) == 1
}
private fun getRandomTimeInMillis(): Long {
return Random.nextLong(3000, 7000)
}
}
| sample/src/main/java/com/google/android/horologist/sectionedlist/stateful/SectionedListStatefulScreenViewModel.kt | 939915969 |
package net.xpece.android.preference
import android.content.SharedPreferences
import org.threeten.bp.LocalDate
class LocalDatePreferenceDelegate(
prefs: SharedPreferences, key: String, default: LocalDate? = null) :
PrintablePreferenceDelegate<LocalDate>(prefs, key, default) {
override fun fromString(input: String) = LocalDate.parse(input)!!
}
| commons/src/main/java/net/xpece/android/preference/LocalDatePreferenceDelegate.kt | 2848896424 |
package com.androidmess.helix.common.ui.recyclerview.databinding
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
@BindingAdapter("modelData")
fun <T> RecyclerView.bindDataToRecyclerView(modelData: List<T>?) {
modelData?.let {
(adapter as? ListAdapter<T, RecyclerView.ViewHolder>)?.submitList(modelData)
}
}
| app/src/main/kotlin/com/androidmess/helix/common/ui/recyclerview/databinding/RecyclerViewExtensions.kt | 211220992 |
package com.eden.orchid.api.options.archetypes
import com.eden.common.util.EdenUtils
import com.eden.orchid.Orchid
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.OptionArchetype
import com.eden.orchid.api.options.annotations.Description
import org.json.JSONObject
import javax.inject.Inject
@Description(
value = "Configure this item with additional options merged in from `config.yml`, from the object at " + "the archetype key. Dots in the key indicate sub-objects within the site config.",
name = "Site Config"
)
class ConfigArchetype
@Inject
constructor(
private val context: OrchidContext
) : OptionArchetype {
override fun getOptions(target: Any, archetypeKey: String): Map<String, Any> {
var configOptions: Map<String, Any>? = null
val eventOptions: Map<String, Any>?
if (!EdenUtils.isEmpty(archetypeKey)) {
val contextOptions = context.query(archetypeKey)
if (EdenUtils.elementIsObject(contextOptions)) {
configOptions = (contextOptions.element as JSONObject).toMap()
}
}
val options = Orchid.Lifecycle.ArchetypeOptions(archetypeKey, target)
context.broadcast(options)
eventOptions = options.config
return EdenUtils.merge(configOptions, eventOptions)
}
}
| OrchidCore/src/main/kotlin/com/eden/orchid/api/options/archetypes/ConfigArchetype.kt | 2869107593 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.java.codeInsight.completion
import com.intellij.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase
import com.intellij.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor.M2
import org.assertj.core.api.Assertions.assertThat
class ModuleCompletionTest : LightJava9ModulesCodeInsightFixtureTestCase() {
override fun setUp() {
super.setUp()
addFile("module-info.java", "module M2 { }", M2)
}
fun testFileHeader1() = variants("<caret>", "module", "open")
fun testFileHeader2() = complete("open <caret>", "open module <caret>")
fun testModuleName() = variants("module M<caret>")
fun testStatements1() = variants("module M { <caret> }", "requires", "exports", "opens", "uses", "provides")
fun testStatements2() = complete("module M { requires X; ex<caret> }", "module M { requires X; exports <caret> }")
fun testRequires() {
variants("module M { requires <caret>", "transitive", "static", "M2", "java.base", "lib.multi.release", "lib.named")
complete("module M { requires t<caret> }", "module M { requires transitive <caret> }")
complete("module M { requires M<caret> }", "module M { requires M2;<caret> }")
}
fun testExports() {
addFile("pkg/empty/package-info.java", "package pkg.empty;")
addFile("pkg/main/C.java", "package pkg.main;\nclass C { }")
addFile("pkg/other/C.groovy", "package pkg.other\nclass C { }")
variants("module M { exports pkg.<caret> }", "main", "other")
complete("module M { exports pkg.o<caret> }", "module M { exports pkg.other;<caret> }")
}
fun testUses() {
addFile("pkg/main/MySvc.java", "package pkg.main;\npublic class MySvc { }")
addFile("pkg/main/MySvcImpl.java", "package pkg.main;\nclass MySvcImpl extends MySvc { }")
complete("module M { uses MyS<caret> }", "module M { uses pkg.main.MySvc;<caret> }")
}
fun testProvides() {
addFile("pkg/main/MySvc.java", "package pkg.main;\npublic class MySvc { }")
addFile("pkg/main/MySvcImpl.java", "package pkg.main;\nclass MySvcImpl extends MySvc { }")
complete("module M { provides MyS<caret> }", "module M { provides pkg.main.MySvc <caret> }")
complete("module M { provides pkg.main.MySvc <caret> }", "module M { provides pkg.main.MySvc with <caret> }")
complete("module M { provides pkg.main.MySvc with MSI<caret> }", "module M { provides pkg.main.MySvc with pkg.main.MySvcImpl;<caret> }")
}
//<editor-fold desc="Helpers.">
private fun complete(text: String, expected: String) {
myFixture.configureByText("module-info.java", text)
myFixture.completeBasic()
myFixture.checkResult(expected)
}
private fun variants(text: String, vararg variants: String) {
myFixture.configureByText("module-info.java", text)
val result = myFixture.completeBasic()?.map { it.lookupString }
assertThat(result).containsExactlyInAnyOrder(*variants)
}
//</editor-fold>
} | java/java-tests/testSrc/com/intellij/java/codeInsight/completion/ModuleCompletionTest.kt | 4183499959 |
package us.mikeandwan.photos.database
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import us.mikeandwan.photos.domain.models.CategoryDisplayType
import us.mikeandwan.photos.domain.models.GridThumbnailSize
@Entity(tableName = "search_preference")
data class SearchPreference(
@PrimaryKey val id: Int,
@ColumnInfo(name = "recent_query_count") val recentQueryCount: Int,
@ColumnInfo(name = "display_type") val displayType: CategoryDisplayType,
@ColumnInfo(name = "grid_thumbnail_size") val gridThumbnailSize: GridThumbnailSize
) | MaWPhotos/src/main/java/us/mikeandwan/photos/database/SearchPreference.kt | 96587221 |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.example.android.watchnextcodelab.channels
import android.content.Context
import android.support.annotation.WorkerThread
import com.example.android.watchnextcodelab.database.MockDatabase
import com.example.android.watchnextcodelab.database.SharedPreferencesDatabase
import com.example.android.watchnextcodelab.watchlist.WatchlistManager
/**
* Functions for managing the watch next row.
*/
object WatchNextAction {
private val database = MockDatabase.get()
@WorkerThread
fun watchNext(context: Context, movieId: Long) {
val movie = database.findMovieById(movieId) ?: return
val watchNextId = WatchNextTvProvider.addToWatchNextNext(context, movie)
database.updateMovieProgramId(context, movieId, watchNextProgramId = watchNextId)
}
@WorkerThread
fun addToContinueWatching(context: Context, movieId: Long, playbackPosition: Int) {
val movie = database.findMovieById(movieId) ?: return
val watchNextId = WatchNextTvProvider.addToWatchNextContinue(context, movie, playbackPosition)
database.updateMovieProgramId(context, movieId, watchNextProgramId = watchNextId)
SharedPreferencesDatabase().savePlaybackPosition(context, movie, playbackPosition)
}
@WorkerThread
fun removeFromContinueWatching(context: Context, movieId: Long) {
WatchNextTvProvider.deleteFromWatchNext(context, movieId.toString())
SharedPreferencesDatabase().deletePlaybackPosition(context, movieId.toString())
// If the user finishes watching a movie in the watch list, then remove it from the list.
WatchlistManager.get().removeMovieFromWatchlist(context, movieId)
}
@WorkerThread
fun addToWatchlist(context: Context, movieId: Long) {
WatchlistManager.get().addToWatchlist(context, movieId)
}
@WorkerThread
fun removeFromWatchlist(context: Context, movieId: Long) {
WatchlistManager.get().removeMovieFromWatchlist(context, movieId)
}
}
| step_final/src/main/java/com/example/android/watchnextcodelab/channels/WatchNextAction.kt | 1653496124 |
/*
* Copyright 2021 Peter Kenji Yamanaka
*
* 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.pyamsoft.homebutton.main
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.pyamsoft.pydroid.arch.UiViewState
import com.pyamsoft.pydroid.ui.theme.Theming
import javax.inject.Inject
internal interface MainViewState : UiViewState {
val theme: Theming.Mode
}
internal class MutableMainViewState @Inject internal constructor() : MainViewState {
override var theme by mutableStateOf(Theming.Mode.SYSTEM)
}
| app/src/main/java/com/pyamsoft/homebutton/main/MainViewState.kt | 1379265276 |
package org.jetbrains.dokka.templates
import org.jetbrains.dokka.CoreExtensions
import org.jetbrains.dokka.base.DokkaBase
import org.jetbrains.dokka.plugability.DokkaPlugin
class TestTemplatingPlugin: DokkaPlugin() {
val dokkaBase by lazy { plugin<DokkaBase>() }
val allModulesPageGeneration by extending {
(CoreExtensions.generation
providing ::TestTemplatingGeneration
override dokkaBase.singleGeneration)
}
} | plugins/templating/src/test/kotlin/org/jetbrains/dokka/templates/TestTemplatingPlugin.kt | 2087645532 |
/*
* Copyright (c) 2017 Fabio Berta
*
* 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 ch.berta.fabio.popularmovies.features.grid.vdos
import android.databinding.BaseObservable
import android.databinding.Bindable
import ch.berta.fabio.popularmovies.BR
import ch.berta.fabio.popularmovies.features.common.vdos.LoadingEmptyViewData
class GridViewData : BaseObservable(), LoadingEmptyViewData {
@get:Bindable
override var loading: Boolean = false
set(value) {
field = value
notifyPropertyChanged(BR.loading)
}
@get:Bindable
override var empty: Boolean = false
set(value) {
field = value
notifyPropertyChanged(BR.empty)
}
@get:Bindable
var refreshEnabled: Boolean = false
set(value) {
field = value
notifyPropertyChanged(BR.refreshEnabled)
}
@get:Bindable
var refreshing: Boolean = false
set(value) {
field = value
notifyPropertyChanged(BR.refreshing)
}
@get:Bindable
var loadingMore: Boolean = false
set(value) {
field = value
notifyPropertyChanged(BR.loadingMore)
}
} | app/src/main/java/ch/berta/fabio/popularmovies/features/grid/vdos/GridViewData.kt | 1524573860 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.libraryweasel.desktop
import javafx.beans.property.ReadOnlyListProperty
import javafx.beans.property.ReadOnlyObjectProperty
/**
* An instance of this interface is provided by the application and won't ever have to be implemented by plugin
* developers. Use this service to add and work with dashes.
*/
interface DashManager {
val dashes: ReadOnlyListProperty<Dash>
val selectedDashProperty: ReadOnlyObjectProperty<Dash>
fun requestSelection(dash: Dash): Boolean
fun addDash(): Dash
fun addDash(dash: Dash)
fun removeDash(dash: Dash)
fun replaceDash(oldDash: Dash, newDash: Dash)
}
| src/main/kotlin/org/libraryweasel/desktop/DashManager.kt | 1548992437 |
/*
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.home.discover
import androidx.compose.runtime.Immutable
import app.tivi.api.UiMessage
import app.tivi.data.entities.TraktUser
import app.tivi.data.resultentities.EpisodeWithSeasonWithShow
import app.tivi.data.resultentities.PopularEntryWithShow
import app.tivi.data.resultentities.RecommendedEntryWithShow
import app.tivi.data.resultentities.TrendingEntryWithShow
import app.tivi.trakt.TraktAuthState
@Immutable
internal data class DiscoverViewState(
val user: TraktUser? = null,
val authState: TraktAuthState = TraktAuthState.LOGGED_OUT,
val trendingItems: List<TrendingEntryWithShow> = emptyList(),
val trendingRefreshing: Boolean = false,
val popularItems: List<PopularEntryWithShow> = emptyList(),
val popularRefreshing: Boolean = false,
val recommendedItems: List<RecommendedEntryWithShow> = emptyList(),
val recommendedRefreshing: Boolean = false,
val nextEpisodeWithShowToWatched: EpisodeWithSeasonWithShow? = null,
val message: UiMessage? = null
) {
val refreshing: Boolean
get() = trendingRefreshing || popularRefreshing || recommendedRefreshing
companion object {
val Empty = DiscoverViewState()
}
}
| ui/discover/src/main/java/app/tivi/home/discover/DiscoverViewState.kt | 718566012 |
package io.noties.markwon.app.utils
import java.io.IOException
import java.io.InputStream
import java.util.Scanner
fun InputStream.readStringAndClose(): String {
try {
val scanner = Scanner(this).useDelimiter("\\A")
if (scanner.hasNext()) {
return scanner.next()
}
return ""
} finally {
try {
close()
} catch (e: IOException) {
// ignored
}
}
} | app-sample/src/main/java/io/noties/markwon/app/utils/InputStreamUtils.kt | 3931253399 |
package util
@Suppress("UNUSED_PARAMETER")
fun TODO(task: String, vararg references: Any?) = throw NotImplementedException("TODO: $task")
class NotImplementedException(message: String): Exception(message) | src/util/kotlinUtil.kt | 2328696677 |
/*
* Copyright (C) 2018 Saúl Díaz
*
* 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.sefford.kor.usecases
import arrow.core.Either
import arrow.effects.*
import com.sefford.common.interfaces.Postable
import com.sefford.kor.usecases.components.BackgroundPool
import com.sefford.kor.usecases.components.Error
import com.sefford.kor.usecases.components.Response
import kotlin.coroutines.experimental.CoroutineContext
/**
* Standalone use case that allows individual execution of a Single use case
*
* @author Saul Diaz <[email protected]>
*/
interface StandaloneUseCase<P, E : Error, R : Response> {
/**
* Instantiates the internal use case for execution.
*
* This is executed ad-hoc when any of the execution methods are invoked, so
* the use case is instantiated and it does not retain state.
*
* @param params Parameter configuration of the use case
*/
fun instantiate(params: P): UseCase<E, R>
/**
* Executes the use case syncronously.
*
* @param params Parameter configuration of the use case
*/
fun execute(params: P): Either<E, R> = instantiate(params).execute()
/**
* Executes the use case synchronously and outputs the
* results via a {@link Postable Postable} element.
*
* @param postable Postable element where to output the results
* @param params Parameter configuration of the use case
*
*/
fun execute(postable: Postable, params: P) = execute(params).fold({ postable.post(it) }, { postable.post(it) })
/**
* Obtains the instance of the execution and returns it in the given thread, in order to lazily execute it.
*
* @param params Parameter configuration of the use case
*/
fun defer(params: P) = defer(BackgroundPool, params)
/**
* Obtains the instance of the execution and returns it in the given thread, in order to lazily execute it.
*
* @param thread Execution context of the use case. Defaults to {@link BackgroundPool BackgroundPool}
* @param params Parameter configuration of the use case
*/
fun defer(thread: CoroutineContext = BackgroundPool, params: P) = kotlinx.coroutines.experimental.async(thread) {
execute(params)
}
/**
* Obtains the instance of the execution and returns it in the given thread, in order to lazily execute it.
*
* @param thread Execution context of the use case. Defaults to {@link BackgroundPool BackgroundPool}
* @param postable postable element where to output the results
* @param params Parameter configuration of the use case
*/
fun defer(thread: CoroutineContext = BackgroundPool, postable: Postable, params: P) = kotlinx.coroutines.experimental.async(thread) {
execute(postable, params)
}
/**
* Obtains the instance of the execution and returns it in the given thread, in order to lazily execute or combine
* it on a functional algebra
*
* @param params Parameter configuration of the use case
*/
fun asynk(params: P) = asynk(BackgroundPool, params)
/**
* Obtains the instance of the execution and returns it in the given thread, in order to lazily execute or combine
* it on a functional algebra
*
* @param thread Execution context of the use case. Defaults to {@link BackgroundPool BackgroundPool}
* @param params Parameter configuration of the use case
*/
fun asynk(thread: CoroutineContext = BackgroundPool, params: P) = defer(thread, params).k()
/**
* Obtains the instance of the execution and returns it in the given thread, in order to lazily execute or combine
* it on a functional algebra
*
* @param postable postable element where to output the results
* @param params Parameter configuration of the use case
*/
fun asynk(postable: Postable, params: P) = asynk(BackgroundPool, postable, params)
/**
* Obtains the instance of the execution and returns it in the given thread, in order to lazily execute or combine
* it on a functional algebra
*
* @param thread Execution context of the use case. Defaults to {@link BackgroundPool BackgroundPool}
* @param postable postable element where to output the results
* @param params Parameter configuration of the use case
*/
fun asynk(thread: CoroutineContext = BackgroundPool, postable: Postable, params: P) =
defer(thread, postable, params)
.k()
.runAsync { DeferredK { Unit } }
/**
* Executes the use case on a custom coroutine context and outputs the
* results.
*
* @param params Parameter configuration of the use case
*/
suspend fun async(params: P) = async(BackgroundPool, params)
/**
* Executes the use case on a custom coroutine context and outputs the
* results.
*
* @param thread Execution context of the use case
* @param params Parameter configuration of the use case
*/
suspend fun async(thread: CoroutineContext = BackgroundPool, params: P) = defer(thread, params).await()
/**
* Executes the use case the default asynchronous context {@see BackgroundPool} and outputs the
* results via a {@link Postable Postable} element.
*
* @param Postable element where to output the results
* @param params Parameter configuration of the use case
*/
fun async(postable: Postable, params: P) = async(BackgroundPool, postable, params)
/**
* Executes the use case the default asynchronous context {@see BackgroundPool} and outputs the
* results via a {@link Postable Postable} element.
*
* @param thread Execution context of the use case. Defaults to {@link BackgroundPool BackgroundPool}
* @param Postable element where to output the results
* @param params Parameter configuration of the use case
*/
fun async(thread: CoroutineContext = BackgroundPool, postable: Postable, params: P) =
asynk(BackgroundPool, postable, params)
}
| modules/kor-usecases/src/main/kotlin/com/sefford/kor/usecases/StandaloneUseCase.kt | 3811805851 |
package com.kennyc.textdrawable
import android.graphics.*
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.OvalShape
import android.graphics.drawable.shapes.RectShape
import android.graphics.drawable.shapes.RoundRectShape
import android.graphics.drawable.shapes.Shape
import androidx.annotation.ColorInt
import androidx.annotation.IntDef
class TextDrawable(
// The Shape the drawable should take
@DrawableShape val shape: Int = TextDrawable.DRAWABLE_SHAPE_RECT,
// The solid fill color of the drawable
@ColorInt var color: Int = Color.GRAY,
// The color of the text for the drawable. Will be ignored if an icon is set
@ColorInt var textColor: Int = Color.WHITE,
// The corner radius for the drawable. Will be ignored if the shape is not a DRAWABLE_SHAPE_ROUND_RECT
var cornerRadius: Float = 0F,
// The text size for the text of the drawable. Will be ignored if an icon is set
var textSize: Float = 0f,
// The desired height of the drawable
var desiredHeight: Int = -1,
// The desired width of the drawable
var desiredWidth: Int = -1,
// The border thickness of the drawable
var borderThickness: Float = 0F,
// The color of the border. Will be ignored if borderThickness is <= 0
@ColorInt var borderColor: Int = color,
// The typeface to use for the text of the drawable. Will be ignored if an icon is set
var typeFace: Typeface = Typeface.DEFAULT,
// The text to use for the drawable. Will be ignored if an icon is set
var text: String? = null,
// The icon to use for the drawable. Will override any text that may have been set
var icon: Bitmap? = null) : ShapeDrawable(getShapeDrawable(shape, cornerRadius)) {
companion object {
private const val SHADE_FACTOR = 0.9f
const val DRAWABLE_SHAPE_RECT = 0
const val DRAWABLE_SHAPE_ROUND_RECT = 1
const val DRAWABLE_SHAPE_OVAL = 2
private fun getShapeDrawable(@DrawableShape shape: Int, cornerRadius: Float): Shape {
return when (shape) {
DRAWABLE_SHAPE_ROUND_RECT -> {
val radii = floatArrayOf(cornerRadius, cornerRadius, cornerRadius, cornerRadius, cornerRadius, cornerRadius, cornerRadius, cornerRadius)
RoundRectShape(radii, null, null)
}
DRAWABLE_SHAPE_OVAL -> OvalShape()
else -> RectShape()
}
}
}
@Retention(AnnotationRetention.SOURCE)
@IntDef(DRAWABLE_SHAPE_RECT, DRAWABLE_SHAPE_ROUND_RECT, DRAWABLE_SHAPE_OVAL)
annotation class DrawableShape
private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val innerPaint = Paint()
init {
// text paint settings
text?.takeIf { !it.isBlank() }?.apply {
textPaint.color = textColor
textPaint.style = Paint.Style.FILL
textPaint.typeface = typeFace
textPaint.textAlign = Paint.Align.CENTER
textPaint.strokeWidth = borderThickness
}
if (borderThickness > 0F) {
// draw shape as color of border
// then fill shape inset by border with the normal color
paint.color = getColorForBorder()
innerPaint.style = Paint.Style.FILL
innerPaint.strokeWidth = borderThickness
innerPaint.color = color
} else {
paint.color = color
}
}
override fun onDraw(shape: Shape, canvas: Canvas, paint: Paint) {
super.onDraw(shape, canvas, paint)
val r = bounds
// draw border
if (borderThickness > 0F) {
drawInnerShape(canvas)
}
val count = canvas.save()
if (icon == null) {
canvas.translate(r.left.toFloat(), r.top.toFloat())
}
// draw text
val width = if (desiredWidth <= 0) r.width() else desiredWidth
val height = if (desiredHeight <= 0) r.height() else desiredHeight
val fontSize = if (textSize <= 0) (Math.min(width, height) / 2).toFloat() else textSize
icon?.let {
canvas.drawBitmap(it, ((width - it.width) / 2).toFloat(), ((height - it.height) / 2).toFloat(), null)
}
text?.takeIf { !it.isBlank() }?.apply {
textPaint.textSize = fontSize
canvas.drawText(this, (width / 2).toFloat(), height / 2 - (textPaint.descent() + textPaint.ascent()) / 2, textPaint)
}
canvas.restoreToCount(count)
}
override fun setAlpha(alpha: Int) {
textPaint.alpha = alpha
}
override fun setColorFilter(cf: ColorFilter?) {
textPaint.colorFilter = cf
}
override fun getOpacity(): Int {
return PixelFormat.TRANSLUCENT
}
override fun getIntrinsicWidth(): Int {
return desiredWidth
}
override fun getIntrinsicHeight(): Int {
return desiredHeight
}
/**
* Converts the [TextDrawable] to a [Bitmap]
*
* @return
*/
fun toBitmap(): Bitmap {
val bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
setBounds(0, 0, canvas.width, canvas.height)
draw(canvas)
return bitmap
}
private fun drawInnerShape(canvas: Canvas) {
val rect = RectF(bounds)
val inset = borderThickness
rect.inset(inset, inset)
when (shape) {
DRAWABLE_SHAPE_ROUND_RECT -> {
val roundRectCornerRadius = cornerRadius - inset
canvas.drawRoundRect(rect, roundRectCornerRadius, roundRectCornerRadius, innerPaint)
}
DRAWABLE_SHAPE_OVAL -> canvas.drawOval(rect, innerPaint)
else -> canvas.drawRect(rect, innerPaint)
}
}
private fun getColorForBorder(): Int {
return when (borderColor) {
color -> {
Color.rgb((SHADE_FACTOR * Color.red(color)).toInt(),
(SHADE_FACTOR * Color.green(color)).toInt(),
(SHADE_FACTOR * Color.blue(color)).toInt())
}
else -> borderColor
}
}
} | library/src/main/java/com/kennyc/textdrawable/TextDrawable.kt | 3019723577 |
package cn.cloudself.model
import org.hibernate.annotations.DynamicInsert
import javax.persistence.*
/**
* @author HerbLuo
* @version 1.0.0.d
*/
@Entity
@DynamicInsert
@Table(name = "deliver", schema = "shop")
data class DeliverEntity(
@get:Id
@get:Column(name = "id", nullable = false)
@get:GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Int = 0,
@get:Basic
@get:Column(name = "number", nullable = true, length = 64)
var number: String? = null,
@get:Basic
@get:Column(name = "name", nullable = true, length = 10)
var name: String? = null,
@get:Basic
@get:Column(name = "order_a_shop_id")
var orderAShopId: Int? = null
)
| src/main/java/cn/cloudself/model/DeliverEntity.kt | 1995800632 |
/*
* This file is generated by jOOQ.
*/
package link.kotlin.server.jooq.main.tables.daos
import java.time.LocalDateTime
import kotlin.collections.List
import link.kotlin.server.jooq.main.tables.FlywaySchemaHistory
import link.kotlin.server.jooq.main.tables.records.FlywaySchemaHistoryRecord
import org.jooq.Configuration
import org.jooq.impl.DAOImpl
/**
* This class is generated by jOOQ.
*/
@Suppress("UNCHECKED_CAST")
open class FlywaySchemaHistoryDao(configuration: Configuration?) : DAOImpl<FlywaySchemaHistoryRecord, link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory, Int>(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY, link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory::class.java, configuration) {
/**
* Create a new FlywaySchemaHistoryDao without any configuration
*/
constructor(): this(null)
override fun getId(o: link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory): Int? = o.installedRank
/**
* Fetch records that have <code>installed_rank BETWEEN lowerInclusive AND
* upperInclusive</code>
*/
fun fetchRangeOfInstalledRank(lowerInclusive: Int?, upperInclusive: Int?): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetchRange(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.INSTALLED_RANK, lowerInclusive, upperInclusive)
/**
* Fetch records that have <code>installed_rank IN (values)</code>
*/
fun fetchByInstalledRank(vararg values: Int): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetch(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.INSTALLED_RANK, *values.toTypedArray())
/**
* Fetch a unique record that has <code>installed_rank = value</code>
*/
fun fetchOneByInstalledRank(value: Int): link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory? = fetchOne(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.INSTALLED_RANK, value)
/**
* Fetch records that have <code>version BETWEEN lowerInclusive AND
* upperInclusive</code>
*/
fun fetchRangeOfVersion(lowerInclusive: String?, upperInclusive: String?): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetchRange(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.VERSION, lowerInclusive, upperInclusive)
/**
* Fetch records that have <code>version IN (values)</code>
*/
fun fetchByVersion(vararg values: String): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetch(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.VERSION, *values)
/**
* Fetch records that have <code>description BETWEEN lowerInclusive AND
* upperInclusive</code>
*/
fun fetchRangeOfDescription(lowerInclusive: String?, upperInclusive: String?): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetchRange(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.DESCRIPTION, lowerInclusive, upperInclusive)
/**
* Fetch records that have <code>description IN (values)</code>
*/
fun fetchByDescription(vararg values: String): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetch(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.DESCRIPTION, *values)
/**
* Fetch records that have <code>type BETWEEN lowerInclusive AND
* upperInclusive</code>
*/
fun fetchRangeOfType(lowerInclusive: String?, upperInclusive: String?): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetchRange(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.TYPE, lowerInclusive, upperInclusive)
/**
* Fetch records that have <code>type IN (values)</code>
*/
fun fetchByType(vararg values: String): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetch(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.TYPE, *values)
/**
* Fetch records that have <code>script BETWEEN lowerInclusive AND
* upperInclusive</code>
*/
fun fetchRangeOfScript(lowerInclusive: String?, upperInclusive: String?): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetchRange(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.SCRIPT, lowerInclusive, upperInclusive)
/**
* Fetch records that have <code>script IN (values)</code>
*/
fun fetchByScript(vararg values: String): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetch(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.SCRIPT, *values)
/**
* Fetch records that have <code>checksum BETWEEN lowerInclusive AND
* upperInclusive</code>
*/
fun fetchRangeOfChecksum(lowerInclusive: Int?, upperInclusive: Int?): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetchRange(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.CHECKSUM, lowerInclusive, upperInclusive)
/**
* Fetch records that have <code>checksum IN (values)</code>
*/
fun fetchByChecksum(vararg values: Int): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetch(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.CHECKSUM, *values.toTypedArray())
/**
* Fetch records that have <code>installed_by BETWEEN lowerInclusive AND
* upperInclusive</code>
*/
fun fetchRangeOfInstalledBy(lowerInclusive: String?, upperInclusive: String?): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetchRange(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.INSTALLED_BY, lowerInclusive, upperInclusive)
/**
* Fetch records that have <code>installed_by IN (values)</code>
*/
fun fetchByInstalledBy(vararg values: String): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetch(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.INSTALLED_BY, *values)
/**
* Fetch records that have <code>installed_on BETWEEN lowerInclusive AND
* upperInclusive</code>
*/
fun fetchRangeOfInstalledOn(lowerInclusive: LocalDateTime?, upperInclusive: LocalDateTime?): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetchRange(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.INSTALLED_ON, lowerInclusive, upperInclusive)
/**
* Fetch records that have <code>installed_on IN (values)</code>
*/
fun fetchByInstalledOn(vararg values: LocalDateTime): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetch(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.INSTALLED_ON, *values)
/**
* Fetch records that have <code>execution_time BETWEEN lowerInclusive AND
* upperInclusive</code>
*/
fun fetchRangeOfExecutionTime(lowerInclusive: Int?, upperInclusive: Int?): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetchRange(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.EXECUTION_TIME, lowerInclusive, upperInclusive)
/**
* Fetch records that have <code>execution_time IN (values)</code>
*/
fun fetchByExecutionTime(vararg values: Int): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetch(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.EXECUTION_TIME, *values.toTypedArray())
/**
* Fetch records that have <code>success BETWEEN lowerInclusive AND
* upperInclusive</code>
*/
fun fetchRangeOfSuccess(lowerInclusive: Boolean?, upperInclusive: Boolean?): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetchRange(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.SUCCESS, lowerInclusive, upperInclusive)
/**
* Fetch records that have <code>success IN (values)</code>
*/
fun fetchBySuccess(vararg values: Boolean): List<link.kotlin.server.jooq.main.tables.pojos.FlywaySchemaHistory> = fetch(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.SUCCESS, *values.toTypedArray())
}
| app-backend/src/main/kotlin/link/kotlin/server/jooq/main/tables/daos/FlywaySchemaHistoryDao.kt | 999136267 |
package com.openlattice.shuttle
import com.fasterxml.jackson.annotation.JsonProperty
import com.openlattice.client.RetrofitFactory
import com.openlattice.client.serialization.SerializationConstants
import java.util.*
data class IntegrationUpdate(
@JsonProperty(SerializationConstants.ENVIRONMENT) val environment: Optional<RetrofitFactory.Environment>,
@JsonProperty(SerializationConstants.S3_BUCKET) val s3bucket: Optional<String>,
@JsonProperty(SerializationConstants.CONTACTS) val contacts: Optional<Set<String>>,
@JsonProperty(SerializationConstants.ORGANIZATION_ID) val organizationId: Optional<UUID>,
@JsonProperty(SerializationConstants.CONNECTIONS) val maxConnections: Optional<Int>,
@JsonProperty(SerializationConstants.CALLBACK) val callbackUrls: Optional<List<String>>,
@JsonProperty(SerializationConstants.FLIGHT_PLAN_PARAMETERS) val flightPlanParameters: Optional<Map<String, FlightPlanParametersUpdate>>
) | src/main/kotlin/com/openlattice/shuttle/IntegrationUpdate.kt | 1803757271 |
/*
* Copyright (C) 2019. OpenLattice, Inc.
*
* 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/>.
*
* You can contact the owner of the copyright at [email protected]
*
*
*/
package com.openlattice.hazelcast.serializers
import com.hazelcast.nio.ObjectDataInput
import com.hazelcast.nio.ObjectDataOutput
import com.kryptnostic.rhizome.pods.hazelcast.SelfRegisteringStreamSerializer
import com.openlattice.hazelcast.StreamSerializerTypeIds
import com.openlattice.ids.IdCatchupEntryProcessor
import com.zaxxer.hikari.HikariDataSource
import org.springframework.stereotype.Component
import javax.inject.Inject
/**
*
* @author Matthew Tamayo-Rios <[email protected]>
*/
@Component
class IdCatchupEntryProcessorStreamSerializer : SelfRegisteringStreamSerializer<IdCatchupEntryProcessor> {
@Inject
private lateinit var hds: HikariDataSource
override fun getClazz(): Class<IdCatchupEntryProcessor> {
return IdCatchupEntryProcessor::class.java
}
override fun write(out: ObjectDataOutput, obj: IdCatchupEntryProcessor) {
}
override fun read(input: ObjectDataInput): IdCatchupEntryProcessor {
return IdCatchupEntryProcessor(hds)
}
override fun getTypeId(): Int {
return StreamSerializerTypeIds.ID_CATCHUP_ENTRY_PROCESSOR.ordinal
}
} | src/main/kotlin/com/openlattice/hazelcast/serializers/IdCatchupEntryProcessorStreamSerializer.kt | 859026391 |
package com.goav.netty.Handler
import com.goav.netty.Impl.ChannelHandlerImpl
import com.goav.netty.Impl.ChannelReleaseImpl
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import java.util.*
/**
* Copyright (c) 2017.
* [email protected]
*/
public class ChannelResponseHandler : ChannelInboundHandlerAdapter(), ChannelReleaseImpl {
private val mHandlerArray: ArrayList<ChannelHandlerImpl>;
init {
mHandlerArray = ArrayList<ChannelHandlerImpl>();
}
fun addChannelResponseHandler(channelHandlerImpl: ChannelHandlerImpl?) {
if (channelHandlerImpl != null) {
mHandlerArray.add(channelHandlerImpl)
}
}
/**
* dispath the message
*/
override fun channelRead(ctx: ChannelHandlerContext, msg: Any?) {
if (msg != null) {
val response = msg as ByteArray
if (mHandlerArray.any { it.channelRead(ctx, response) }) {
return
}
}
//nobody receiver
super.channelRead(ctx, msg)
}
override fun destroy() {
mHandlerArray.clear();
}
} | netty-android/src/main/java/com/goav/netty/Handler/ChannelResponseHandler.kt | 2690119503 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.