repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/KotlinUsageTypeProvider.kt | 1 | 7218 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.findUsages
import com.intellij.psi.PsiElement
import com.intellij.usages.UsageTarget
import com.intellij.usages.impl.rules.UsageType
import com.intellij.usages.impl.rules.UsageTypeProviderEx
import org.jetbrains.kotlin.idea.findUsages.KotlinUsageTypes.toUsageType
import org.jetbrains.kotlin.idea.findUsages.UsageTypeEnum.*
import org.jetbrains.kotlin.idea.references.readWriteAccess
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.resolve.references.ReferenceAccess
abstract class KotlinUsageTypeProvider : UsageTypeProviderEx {
abstract fun getUsageTypeEnumByReference(refExpr: KtReferenceExpression): UsageTypeEnum?
private fun getUsageTypeEnum(element: PsiElement?): UsageTypeEnum? {
when (element) {
is KtForExpression -> return IMPLICIT_ITERATION
is KtDestructuringDeclarationEntry -> return READ
is KtPropertyDelegate -> return PROPERTY_DELEGATION
is KtStringTemplateExpression -> return USAGE_IN_STRING_LITERAL
is KtConstructorDelegationReferenceExpression -> return CONSTRUCTOR_DELEGATION_REFERENCE
}
val refExpr = element?.getNonStrictParentOfType<KtReferenceExpression>() ?: return null
return getCommonUsageType(refExpr) ?: getUsageTypeEnumByReference(refExpr)
}
override fun getUsageType(element: PsiElement): UsageType? = getUsageType(element, UsageTarget.EMPTY_ARRAY)
override fun getUsageType(element: PsiElement?, targets: Array<out UsageTarget>): UsageType? {
val usageType = getUsageTypeEnum(element) ?: return null
return usageType.toUsageType()
}
private fun getCommonUsageType(refExpr: KtReferenceExpression): UsageTypeEnum? = when {
refExpr.getNonStrictParentOfType<KtImportDirective>() != null -> CLASS_IMPORT
refExpr.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference } != null -> CALLABLE_REFERENCE
else -> null
}
protected fun getClassUsageType(refExpr: KtReferenceExpression): UsageTypeEnum? {
if (refExpr.getNonStrictParentOfType<KtTypeProjection>() != null) return TYPE_PARAMETER
val property = refExpr.getNonStrictParentOfType<KtProperty>()
if (property != null) {
when {
property.typeReference.isAncestor(refExpr) ->
return if (property.isLocal) CLASS_LOCAL_VAR_DECLARATION else NON_LOCAL_PROPERTY_TYPE
property.receiverTypeReference.isAncestor(refExpr) ->
return EXTENSION_RECEIVER_TYPE
}
}
val function = refExpr.getNonStrictParentOfType<KtFunction>()
if (function != null) {
when {
function.typeReference.isAncestor(refExpr) ->
return FUNCTION_RETURN_TYPE
function.receiverTypeReference.isAncestor(refExpr) ->
return EXTENSION_RECEIVER_TYPE
}
}
return when {
refExpr.getParentOfTypeAndBranch<KtTypeParameter> { extendsBound } != null || refExpr.getParentOfTypeAndBranch<KtTypeConstraint> { boundTypeReference } != null -> TYPE_CONSTRAINT
refExpr is KtSuperTypeListEntry || refExpr.getParentOfTypeAndBranch<KtSuperTypeListEntry> { typeReference } != null -> SUPER_TYPE
refExpr.getParentOfTypeAndBranch<KtParameter> { typeReference } != null -> VALUE_PARAMETER_TYPE
refExpr.getParentOfTypeAndBranch<KtIsExpression> { typeReference } != null || refExpr.getParentOfTypeAndBranch<KtWhenConditionIsPattern> { typeReference } != null -> IS
with(refExpr.getParentOfTypeAndBranch<KtBinaryExpressionWithTypeRHS> { right }) {
val opType = this?.operationReference?.getReferencedNameElementType()
opType == org.jetbrains.kotlin.lexer.KtTokens.AS_KEYWORD || opType == org.jetbrains.kotlin.lexer.KtTokens.AS_SAFE
} -> CLASS_CAST_TO
with(refExpr.getNonStrictParentOfType<KtDotQualifiedExpression>()) {
when {
this == null -> {
false
}
receiverExpression == refExpr -> {
true
}
else -> {
selectorExpression == refExpr
&& getParentOfTypeAndBranch<KtDotQualifiedExpression>(strict = true) { receiverExpression } != null
}
}
} -> CLASS_OBJECT_ACCESS
refExpr.getParentOfTypeAndBranch<KtSuperExpression> { superTypeQualifier } != null -> SUPER_TYPE_QUALIFIER
refExpr.getParentOfTypeAndBranch<KtTypeAlias> { getTypeReference() } != null -> TYPE_ALIAS
else -> null
}
}
protected fun getVariableUsageType(refExpr: KtReferenceExpression): UsageTypeEnum {
if (refExpr.getParentOfTypeAndBranch<KtDelegatedSuperTypeEntry> { delegateExpression } != null) return DELEGATE
if (refExpr.parent is KtValueArgumentName) return NAMED_ARGUMENT
val dotQualifiedExpression = refExpr.getNonStrictParentOfType<KtDotQualifiedExpression>()
if (dotQualifiedExpression != null) {
val parent = dotQualifiedExpression.parent
when {
dotQualifiedExpression.receiverExpression.isAncestor(refExpr) ->
return RECEIVER
parent is KtDotQualifiedExpression && parent.receiverExpression.isAncestor(refExpr) ->
return RECEIVER
}
}
return when (refExpr.readWriteAccess(useResolveForReadWrite = true)) {
ReferenceAccess.READ -> READ
ReferenceAccess.WRITE, ReferenceAccess.READ_WRITE -> WRITE
}
}
protected fun getPackageUsageType(refExpr: KtReferenceExpression): UsageTypeEnum? = when {
refExpr.getNonStrictParentOfType<KtPackageDirective>() != null -> PACKAGE_DIRECTIVE
refExpr.getNonStrictParentOfType<KtQualifiedExpression>() != null -> PACKAGE_MEMBER_ACCESS
else -> getClassUsageType(refExpr)
}
}
enum class UsageTypeEnum {
TYPE_CONSTRAINT,
VALUE_PARAMETER_TYPE,
NON_LOCAL_PROPERTY_TYPE,
FUNCTION_RETURN_TYPE,
SUPER_TYPE,
IS,
CLASS_OBJECT_ACCESS,
COMPANION_OBJECT_ACCESS,
EXTENSION_RECEIVER_TYPE,
SUPER_TYPE_QUALIFIER,
TYPE_ALIAS,
FUNCTION_CALL,
IMPLICIT_GET,
IMPLICIT_SET,
IMPLICIT_INVOKE,
IMPLICIT_ITERATION,
PROPERTY_DELEGATION,
RECEIVER,
DELEGATE,
PACKAGE_DIRECTIVE,
PACKAGE_MEMBER_ACCESS,
CALLABLE_REFERENCE,
READ,
WRITE,
CLASS_IMPORT,
CLASS_LOCAL_VAR_DECLARATION,
TYPE_PARAMETER,
CLASS_CAST_TO,
ANNOTATION,
CLASS_NEW_OPERATOR,
NAMED_ARGUMENT,
USAGE_IN_STRING_LITERAL,
CONSTRUCTOR_DELEGATION_REFERENCE,
}
| apache-2.0 | dd6275ac3edaaf09ae82eeab9fc6587c | 38.659341 | 190 | 0.675949 | 5.639063 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/stories/viewer/text/StoryTextPostPreviewFragment.kt | 1 | 3592 | package org.thoughtcrime.securesms.stories.viewer.text
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import org.signal.core.util.DimensionUnit
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.linkpreview.LinkPreview
import org.thoughtcrime.securesms.mediapreview.MediaPreviewFragment
import org.thoughtcrime.securesms.stories.StoryTextPostView
import org.thoughtcrime.securesms.stories.viewer.page.StoryPost
import org.thoughtcrime.securesms.util.CommunicationActions
import org.thoughtcrime.securesms.util.FragmentDialogs.displayInDialogAboveAnchor
import org.thoughtcrime.securesms.util.fragments.requireListener
class StoryTextPostPreviewFragment : Fragment(R.layout.stories_text_post_preview_fragment) {
companion object {
private const val STORY_ID = "STORY_ID"
fun create(content: StoryPost.Content.TextContent): Fragment {
return StoryTextPostPreviewFragment().apply {
arguments = Bundle().apply {
putParcelable(MediaPreviewFragment.DATA_URI, content.uri)
putLong(STORY_ID, content.recordId)
}
}
}
}
private val viewModel: StoryTextPostViewModel by viewModels(
factoryProducer = {
StoryTextPostViewModel.Factory(requireArguments().getLong(STORY_ID), StoryTextPostRepository())
}
)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val storyTextPostView: StoryTextPostView = view.findViewById(R.id.story_text_post)
viewModel.state.observe(viewLifecycleOwner) { state ->
when (state.loadState) {
StoryTextPostState.LoadState.INIT -> Unit
StoryTextPostState.LoadState.LOADED -> {
storyTextPostView.bindFromStoryTextPost(state.storyTextPost!!)
storyTextPostView.bindLinkPreview(state.linkPreview)
if (state.linkPreview != null) {
storyTextPostView.setLinkPreviewClickListener {
showLinkPreviewTooltip(it, state.linkPreview)
}
} else {
storyTextPostView.setLinkPreviewClickListener(null)
}
}
StoryTextPostState.LoadState.FAILED -> {
requireListener<MediaPreviewFragment.Events>().mediaNotAvailable()
}
}
if (state.typeface != null) {
storyTextPostView.setTypeface(state.typeface)
}
if (state.typeface != null && state.loadState == StoryTextPostState.LoadState.LOADED) {
requireListener<MediaPreviewFragment.Events>().onMediaReady()
}
}
}
@SuppressLint("AlertDialogBuilderUsage")
private fun showLinkPreviewTooltip(view: View, linkPreview: LinkPreview) {
requireListener<Callback>().setIsDisplayingLinkPreviewTooltip(true)
val contentView = LayoutInflater.from(requireContext()).inflate(R.layout.stories_link_popup, null, false)
contentView.findViewById<TextView>(R.id.url).text = linkPreview.url
contentView.setOnClickListener {
CommunicationActions.openBrowserLink(requireContext(), linkPreview.url)
}
contentView.measure(
View.MeasureSpec.makeMeasureSpec(DimensionUnit.DP.toPixels(275f).toInt(), View.MeasureSpec.EXACTLY),
0
)
contentView.layout(0, 0, contentView.measuredWidth, contentView.measuredHeight)
displayInDialogAboveAnchor(view, contentView, windowDim = 0f)
}
interface Callback {
fun setIsDisplayingLinkPreviewTooltip(isDisplayingLinkPreviewTooltip: Boolean)
}
}
| gpl-3.0 | 2bb67c9324c11260c78acdde0e0ff9e5 | 35.653061 | 109 | 0.745824 | 4.827957 | false | false | false | false |
helloworld1/FreeOTPPlus | app/src/main/java/org/fedorahosted/freeotp/ui/DeleteActivity.kt | 1 | 1936 | package org.fedorahosted.freeotp.ui
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import org.fedorahosted.freeotp.R
import org.fedorahosted.freeotp.data.OtpTokenDatabase
import org.fedorahosted.freeotp.databinding.DeleteBinding
import org.fedorahosted.freeotp.util.setTokenImage
import javax.inject.Inject
@AndroidEntryPoint
class DeleteActivity : AppCompatActivity() {
@Inject lateinit var otpTokenDatabase: OtpTokenDatabase
private lateinit var binding: DeleteBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DeleteBinding.inflate(layoutInflater)
setContentView(binding.root)
lifecycleScope.launch {
val tokenId = intent.getLongExtra(EXTRA_TOKEN_ID, 0L)
if (tokenId == 0L) {
return@launch
}
binding.cancel.setOnClickListener {
finish()
}
binding.delete.setOnClickListener {
lifecycleScope.launch {
otpTokenDatabase.otpTokenDao().deleteById(tokenId)
setResult(RESULT_OK)
}
}
otpTokenDatabase.otpTokenDao().get(tokenId).collect { token ->
if (token == null) {
finish()
return@collect
}
(findViewById<View>(R.id.issuer) as TextView).text = token.issuer
(findViewById<View>(R.id.label) as TextView).text = token.label
binding.imageView.setTokenImage(token)
}
}
}
companion object {
const val EXTRA_TOKEN_ID = "token_id"
}
}
| apache-2.0 | 629d7053d13c824057aea6690ecf3da8 | 29.730159 | 81 | 0.644112 | 4.756757 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-plugins/ktor-server-status-pages/jvmAndNix/src/io/ktor/server/plugins/statuspages/StatusPages.kt | 1 | 5243 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.plugins.statuspages
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.server.application.*
import io.ktor.server.application.hooks.*
import io.ktor.server.logging.*
import io.ktor.server.request.*
import io.ktor.util.*
import io.ktor.util.logging.*
import io.ktor.util.reflect.*
import kotlin.jvm.*
import kotlin.reflect.*
private val LOGGER = KtorSimpleLogger("io.ktor.server.plugins.statuspages.StatusPages")
/**
* Specifies how the exception should be handled.
*/
public typealias HandlerFunction = suspend (call: ApplicationCall, cause: Throwable) -> Unit
/**
* A plugin that handles exceptions and status codes. Useful to configure default error pages.
*/
public val StatusPages: ApplicationPlugin<StatusPagesConfig> = createApplicationPlugin(
"StatusPages",
::StatusPagesConfig
) {
val statusPageMarker = AttributeKey<Unit>("StatusPagesTriggered")
val exceptions = HashMap(pluginConfig.exceptions)
val statuses = HashMap(pluginConfig.statuses)
fun findHandlerByValue(cause: Throwable): HandlerFunction? {
val keys = exceptions.keys.filter { cause.instanceOf(it) }
if (keys.isEmpty()) return null
if (keys.size == 1) {
return exceptions[keys.single()]
}
val key = selectNearestParentClass(cause, keys)
return exceptions[key]
}
on(ResponseBodyReadyForSend) { call, content ->
if (call.attributes.contains(statusPageMarker)) return@on
val status = content.status ?: call.response.status()
if (status == null) {
LOGGER.trace("No status code found for call: ${call.request.uri}")
return@on
}
val handler = statuses[status]
if (handler == null) {
LOGGER.trace("No handler found for status code $status for call: ${call.request.uri}")
return@on
}
call.attributes.put(statusPageMarker, Unit)
try {
LOGGER.trace("Executing $handler for status code $status for call: ${call.request.uri}")
handler(call, content, status)
} catch (cause: Throwable) {
LOGGER.trace(
"Exception $cause while executing $handler for status code $status for call: ${call.request.uri}"
)
call.attributes.remove(statusPageMarker)
throw cause
}
}
on(CallFailed) { call, cause ->
if (call.attributes.contains(statusPageMarker)) return@on
LOGGER.trace("Call ${call.request.uri} failed with cause $cause")
val handler = findHandlerByValue(cause)
if (handler == null) {
LOGGER.trace("No handler found for exception: $cause for call ${call.request.uri}")
throw cause
}
call.attributes.put(statusPageMarker, Unit)
call.application.mdcProvider.withMDCBlock(call) {
LOGGER.trace("Executing $handler for exception $cause for call ${call.request.uri}")
handler(call, cause)
}
}
}
/**
* A [StatusPages] plugin configuration.
*/
@KtorDsl
public class StatusPagesConfig {
/**
* Provides access to exception handlers of the exception class.
*/
public val exceptions: MutableMap<KClass<*>, HandlerFunction> = mutableMapOf()
/**
* Provides access to status handlers based on a status code.
*/
public val statuses: MutableMap<HttpStatusCode,
suspend (call: ApplicationCall, content: OutgoingContent, code: HttpStatusCode) -> Unit> =
mutableMapOf()
/**
* Register an exception [handler] for the exception type [T] and its children.
*/
public inline fun <reified T : Throwable> exception(
noinline handler: suspend (call: ApplicationCall, cause: T) -> Unit
): Unit = exception(T::class, handler)
/**
* Register an exception [handler] for the exception class [klass] and its children.
*/
public fun <T : Throwable> exception(
klass: KClass<T>,
handler: suspend (call: ApplicationCall, T) -> Unit
) {
@Suppress("UNCHECKED_CAST")
val cast = handler as suspend (ApplicationCall, Throwable) -> Unit
exceptions[klass] = cast
}
/**
* Register a status [handler] for the [status] code.
*/
public fun status(
vararg status: HttpStatusCode,
handler: suspend (ApplicationCall, HttpStatusCode) -> Unit
) {
status.forEach {
statuses[it] = { call, _, code -> handler(call, code) }
}
}
/**
* Register a status [handler] for the [status] code.
*/
@JvmName("statusWithContext")
public fun status(
vararg status: HttpStatusCode,
handler: suspend StatusContext.(HttpStatusCode) -> Unit
) {
status.forEach {
statuses[it] = { call, content, code -> handler(StatusContext(call, content), code) }
}
}
/**
* A context for [status] config method.
*/
public class StatusContext(
public val call: ApplicationCall,
public val content: OutgoingContent
)
}
| apache-2.0 | f25c5707fd045d73f5164292d93afdb0 | 30.584337 | 118 | 0.637612 | 4.365529 | false | false | false | false |
dahlstrom-g/intellij-community | platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/vfu.kt | 2 | 6744 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
interface VFUEntity : WorkspaceEntity {
val data: String
val fileProperty: VirtualFileUrl
//region generated code
//@formatter:off
@GeneratedCodeApiVersion(1)
interface Builder: VFUEntity, ModifiableWorkspaceEntity<VFUEntity>, ObjBuilder<VFUEntity> {
override var data: String
override var entitySource: EntitySource
override var fileProperty: VirtualFileUrl
}
companion object: Type<VFUEntity, Builder>() {
operator fun invoke(data: String, entitySource: EntitySource, fileProperty: VirtualFileUrl, init: (Builder.() -> Unit)? = null): VFUEntity {
val builder = builder()
builder.data = data
builder.entitySource = entitySource
builder.fileProperty = fileProperty
init?.invoke(builder)
return builder
}
}
//@formatter:on
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: VFUEntity, modification: VFUEntity.Builder.() -> Unit) = modifyEntity(VFUEntity.Builder::class.java, entity, modification)
//endregion
interface VFUWithTwoPropertiesEntity : WorkspaceEntity {
val data: String
val fileProperty: VirtualFileUrl
val secondFileProperty: VirtualFileUrl
//region generated code
//@formatter:off
@GeneratedCodeApiVersion(1)
interface Builder: VFUWithTwoPropertiesEntity, ModifiableWorkspaceEntity<VFUWithTwoPropertiesEntity>, ObjBuilder<VFUWithTwoPropertiesEntity> {
override var data: String
override var entitySource: EntitySource
override var fileProperty: VirtualFileUrl
override var secondFileProperty: VirtualFileUrl
}
companion object: Type<VFUWithTwoPropertiesEntity, Builder>() {
operator fun invoke(data: String, entitySource: EntitySource, fileProperty: VirtualFileUrl, secondFileProperty: VirtualFileUrl, init: (Builder.() -> Unit)? = null): VFUWithTwoPropertiesEntity {
val builder = builder()
builder.data = data
builder.entitySource = entitySource
builder.fileProperty = fileProperty
builder.secondFileProperty = secondFileProperty
init?.invoke(builder)
return builder
}
}
//@formatter:on
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: VFUWithTwoPropertiesEntity, modification: VFUWithTwoPropertiesEntity.Builder.() -> Unit) = modifyEntity(VFUWithTwoPropertiesEntity.Builder::class.java, entity, modification)
//endregion
interface NullableVFUEntity : WorkspaceEntity {
val data: String
val fileProperty: VirtualFileUrl?
//region generated code
//@formatter:off
@GeneratedCodeApiVersion(1)
interface Builder: NullableVFUEntity, ModifiableWorkspaceEntity<NullableVFUEntity>, ObjBuilder<NullableVFUEntity> {
override var data: String
override var entitySource: EntitySource
override var fileProperty: VirtualFileUrl?
}
companion object: Type<NullableVFUEntity, Builder>() {
operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): NullableVFUEntity {
val builder = builder()
builder.data = data
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//@formatter:on
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: NullableVFUEntity, modification: NullableVFUEntity.Builder.() -> Unit) = modifyEntity(NullableVFUEntity.Builder::class.java, entity, modification)
//endregion
interface ListVFUEntity : WorkspaceEntity {
val data: String
val fileProperty: List<VirtualFileUrl>
//region generated code
//@formatter:off
@GeneratedCodeApiVersion(1)
interface Builder: ListVFUEntity, ModifiableWorkspaceEntity<ListVFUEntity>, ObjBuilder<ListVFUEntity> {
override var data: String
override var entitySource: EntitySource
override var fileProperty: List<VirtualFileUrl>
}
companion object: Type<ListVFUEntity, Builder>() {
operator fun invoke(data: String, entitySource: EntitySource, fileProperty: List<VirtualFileUrl>, init: (Builder.() -> Unit)? = null): ListVFUEntity {
val builder = builder()
builder.data = data
builder.entitySource = entitySource
builder.fileProperty = fileProperty
init?.invoke(builder)
return builder
}
}
//@formatter:on
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ListVFUEntity, modification: ListVFUEntity.Builder.() -> Unit) = modifyEntity(ListVFUEntity.Builder::class.java, entity, modification)
//endregion
fun MutableEntityStorage.addVFUEntity(
data: String,
fileUrl: String,
virtualFileManager: VirtualFileUrlManager,
source: EntitySource = SampleEntitySource("test")
): VFUEntity {
val vfuEntity = VFUEntity(data, source, virtualFileManager.fromUrl(fileUrl))
this.addEntity(vfuEntity)
return vfuEntity
}
fun MutableEntityStorage.addVFU2Entity(
data: String,
fileUrl: String,
secondFileUrl: String,
virtualFileManager: VirtualFileUrlManager,
source: EntitySource = SampleEntitySource("test")
): VFUWithTwoPropertiesEntity {
val vfuWithTwoPropertiesEntity = VFUWithTwoPropertiesEntity(data, source, virtualFileManager.fromUrl(fileUrl), virtualFileManager.fromUrl(secondFileUrl))
this.addEntity(vfuWithTwoPropertiesEntity)
return vfuWithTwoPropertiesEntity
}
fun MutableEntityStorage.addNullableVFUEntity(
data: String,
fileUrl: String?,
virtualFileManager: VirtualFileUrlManager,
source: EntitySource = SampleEntitySource("test")
): NullableVFUEntity {
val nullableVFUEntity = NullableVFUEntity(data, source) {
this.fileProperty = fileUrl?.let { virtualFileManager.fromUrl(it) }
}
this.addEntity(nullableVFUEntity)
return nullableVFUEntity
}
fun MutableEntityStorage.addListVFUEntity(
data: String,
fileUrl: List<String>,
virtualFileManager: VirtualFileUrlManager,
source: EntitySource = SampleEntitySource("test")
): ListVFUEntity {
val listVFUEntity = ListVFUEntity(data, source, fileUrl.map { virtualFileManager.fromUrl(it) })
this.addEntity(listVFUEntity)
return listVFUEntity
}
| apache-2.0 | 4c6474c26a1ea22603d03e646cf2a351 | 34.494737 | 219 | 0.755783 | 5.390887 | false | false | false | false |
komu/scratch | src/main/kotlin/gitstats/PlotLocOverTime.kt | 1 | 3299 | package gitstats
import jetbrains.letsPlot.export.ggsave
import jetbrains.letsPlot.geom.geom_line
import jetbrains.letsPlot.ggplot
import jetbrains.letsPlot.label.ggtitle
import jetbrains.letsPlot.lets_plot
import jetbrains.letsPlot.scale.scale_x_datetime
import jetbrains.letsPlot.scale.scale_y_continuous
import org.eclipse.jgit.lib.*
import org.eclipse.jgit.revwalk.RevTree
import org.eclipse.jgit.revwalk.RevWalk
import org.eclipse.jgit.storage.file.FileRepositoryBuilder
import org.eclipse.jgit.treewalk.TreeWalk
import java.io.File
import java.time.Duration
import java.time.Instant
import kotlin.system.measureTimeMillis
fun main() {
dumpRepoStats("/Users/komu/src/evident/raudikko/.git", "Raudikko", "raudikko-stats.png")
dumpRepoStats("/Users/komu/src/evident/dalesbred/.git", "Dalesbred", "dalesbred-stats.png")
dumpRepoStats("/Users/komu/src/evident/finnpilot/pilotweb/.git", "Pilotweb", "pilotweb-stats.png")
}
private fun dumpRepoStats(repo: String, title: String, file: String) {
val ms = measureTimeMillis {
val stats = RepoAnalyzer(repo).analyze()
val data = mapOf(
"times" to stats.map { it.commitTime },
"lines" to stats.map { it.lines }
)
val p = ggplot(data) +
ggtitle(title) +
geom_line { x = "times"; y = "lines" } +
scale_y_continuous("", limits = 0 to null) +
scale_x_datetime("")
ggsave(p, file)
}
println("analyzed $repo in $ms ms")
}
private class CommitStats(val commitTime: Instant, val lines: Int)
private class RepoAnalyzer(dir: String) {
private val repo = FileRepositoryBuilder().setGitDir(File(dir)).build()
private val lineCountCache = mutableMapOf<ObjectId, Int>()
fun analyze(): List<CommitStats> {
val walk = RevWalk(repo)
val resolve = repo.resolve(repo.branch)
walk.markStart(walk.parseCommit(resolve))
val result = mutableListOf<CommitStats>()
val periodBetween = Duration.ofDays(60)
var previousTime = Instant.MAX
for (commit in walk) {
val time = Instant.ofEpochSecond(commit.commitTime.toLong())
if (Duration.between(time, previousTime) > periodBetween) {
result += CommitStats(time, treeSize(commit.tree))
previousTime = time
}
commit.disposeBody()
}
walk.dispose()
return result
}
private fun treeSize(tree: RevTree): Int {
val walk = TreeWalk(repo)
walk.reset(tree)
walk.isRecursive = true
var lines = 0
while (walk.next())
if (validFile(walk.nameString))
lines += repo.objectDatabase.objectSize(walk.getObjectId(0))
walk.close()
return lines
}
private fun validFile(name: String) =
name.endsWith(".kt") ||
name.endsWith(".java") ||
name.endsWith(".js") ||
name.endsWith(".ts") ||
name.endsWith(".m") ||
name.endsWith(".h") ||
name.endsWith(".swift")
private fun ObjectDatabase.objectSize(id: ObjectId): Int =
lineCountCache.getOrPut(id) { open(id).bytes.count { it == '\n'.toByte() } }
}
| mit | 9de9108bca93506d4e23e86c0b08ed86 | 30.419048 | 102 | 0.627766 | 3.913405 | false | false | false | false |
theapache64/Mock-API | src/com/theah64/mock_api/utils/MarkDownUtils.kt | 1 | 3430 | package com.theah64.mock_api.utils
import com.theah64.webengine.utils.Request
import java.lang.StringBuilder
import java.util.regex.Pattern
class MarkDownUtils {
companion object {
const val TABLE_HEAD_REGEX = "<thead>.+(<tr>.+<\\/tr>).+<\\/thead>"
const val TABLE_BODY_REGEX = "<tbody>.+(<tr>.+<\\/tr>).+<\\/tbody>"
fun toMarkDownTable(_tableData: String): String {
var tableData = _tableData
tableData = tableData.replace("\n", "")
tableData = tableData.replace(Regex("\\s+"), " ")
// getting headers
val headers = getHeadings(tableData)
// Getting rows
val rows = getRows(tableData)
if (headers != null) {
val sBuilder = StringBuilder("|")
val lineBuilder = StringBuilder("|")
// Adding headers
for (header in headers) {
sBuilder.append(header).append("|")
lineBuilder.append(get('-', header.length - 1)).append("|")
}
sBuilder.append("\n").append(lineBuilder).append("\n")
rows?.let { tableRows ->
for (row in tableRows) {
sBuilder.append("|")
for (value in row) {
sBuilder.append(value).append("|")
}
sBuilder.append("\n")
}
}
return sBuilder.toString()
} else {
throw Request.RequestException("Invalid table data, couldn't get table header data")
}
}
private fun get(char: Char, length: Int): Any {
val sb = StringBuilder()
for (i in 0..length) {
sb.append(char)
}
return sb.toString()
}
fun getRows(tableData: String): List<List<String>>? {
var headings = mutableListOf<List<String>>()
val pattern = Pattern.compile(TABLE_BODY_REGEX)
val matcher = pattern.matcher(tableData)
if (matcher.find()) {
var tBody = matcher.group(0)
tBody = tBody.replace(Regex("(<\\s*tbody>|</\\s*tbody>)"), "")
tBody.split("<tr>")
.filter { row -> row.trim().isNotEmpty() }
.map { row ->
val tds = row.split("<td>")
.filter { td -> td.trim().isNotEmpty() }
.map { td -> td.replace(Regex("(</td>|</tr>)"), "").trim() }
headings.add(tds)
}
}
return headings
}
private fun getHeadings(tableData: String): List<String>? {
var headings: List<String>? = null
val pattern = Pattern.compile(TABLE_HEAD_REGEX)
val matcher = pattern.matcher(tableData)
if (matcher.find()) {
var trHead = matcher.group(1)
trHead = trHead.replace(Regex("(<\\s*tr\\s*>|<\\s*th\\s*>|</\\s*tr\\s*>)"), "")
headings = trHead.split("</th>")
.map { value -> value.trim() }
.filter { value -> value.isNotEmpty() }
}
return headings
}
}
} | apache-2.0 | f07f87a3291b448e1e7eae0ea41221d2 | 33.656566 | 100 | 0.45102 | 4.685792 | false | false | false | false |
ThePreviousOne/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/updater/UpdateDownloaderService.kt | 1 | 5809 | package eu.kanade.tachiyomi.data.updater
import android.app.IntentService
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.support.v4.app.NotificationCompat
import eu.kanade.tachiyomi.Constants.NOTIFICATION_UPDATER_ID
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.network.GET
import eu.kanade.tachiyomi.data.network.NetworkHelper
import eu.kanade.tachiyomi.data.network.ProgressListener
import eu.kanade.tachiyomi.data.network.newCallWithProgress
import eu.kanade.tachiyomi.util.notificationManager
import eu.kanade.tachiyomi.util.saveTo
import timber.log.Timber
import uy.kohesive.injekt.injectLazy
import java.io.File
class UpdateDownloaderService : IntentService(UpdateDownloaderService::class.java.name) {
companion object {
/**
* Download url.
*/
const val EXTRA_DOWNLOAD_URL = "eu.kanade.APP_DOWNLOAD_URL"
/**
* Downloads a new update and let the user install the new version from a notification.
* @param context the application context.
* @param url the url to the new update.
*/
fun downloadUpdate(context: Context, url: String) {
val intent = Intent(context, UpdateDownloaderService::class.java).apply {
putExtra(EXTRA_DOWNLOAD_URL, url)
}
context.startService(intent)
}
/**
* Prompt user with apk install intent
* @param context context
* @param file file of apk that is installed
*/
fun installAPK(context: Context, file: File) {
// Prompt install interface
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive")
// Without this flag android returned a intent error!
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
context.startActivity(intent)
}
}
/**
* Network helper
*/
private val network: NetworkHelper by injectLazy()
override fun onHandleIntent(intent: Intent?) {
if (intent == null) return
val url = intent.getStringExtra(EXTRA_DOWNLOAD_URL) ?: return
downloadApk(url)
}
fun downloadApk(url: String) {
val progressNotification = NotificationCompat.Builder(this)
progressNotification.update {
setContentTitle(getString(R.string.app_name))
setContentText(getString(R.string.update_check_notification_download_in_progress))
setSmallIcon(android.R.drawable.stat_sys_download)
setOngoing(true)
}
// Progress of the download
var savedProgress = 0
val progressListener = object : ProgressListener {
override fun update(bytesRead: Long, contentLength: Long, done: Boolean) {
val progress = (100 * bytesRead / contentLength).toInt()
if (progress > savedProgress) {
savedProgress = progress
progressNotification.update { setProgress(100, progress, false) }
}
}
}
// Reference the context for later usage inside apply blocks.
val ctx = this
try {
// Download the new update.
val response = network.client.newCallWithProgress(GET(url), progressListener).execute()
// File where the apk will be saved
val apkFile = File(externalCacheDir, "update.apk")
if (response.isSuccessful) {
response.body().source().saveTo(apkFile)
} else {
response.close()
throw Exception("Unsuccessful response")
}
val installIntent = UpdateNotificationReceiver.installApkIntent(ctx, apkFile.absolutePath)
// Prompt the user to install the new update.
NotificationCompat.Builder(this).update {
setContentTitle(getString(R.string.app_name))
setContentText(getString(R.string.update_check_notification_download_complete))
setSmallIcon(android.R.drawable.stat_sys_download_done)
// Install action
setContentIntent(installIntent)
addAction(R.drawable.ic_system_update_grey_24dp_img,
getString(R.string.action_install),
installIntent)
// Cancel action
addAction(R.drawable.ic_clear_grey_24dp_img,
getString(R.string.action_cancel),
UpdateNotificationReceiver.cancelNotificationIntent(ctx))
}
} catch (error: Exception) {
Timber.e(error)
// Prompt the user to retry the download.
NotificationCompat.Builder(this).update {
setContentTitle(getString(R.string.app_name))
setContentText(getString(R.string.update_check_notification_download_error))
setSmallIcon(android.R.drawable.stat_sys_download_done)
// Retry action
addAction(R.drawable.ic_refresh_grey_24dp_img,
getString(R.string.action_retry),
UpdateNotificationReceiver.downloadApkIntent(ctx, url))
// Cancel action
addAction(R.drawable.ic_clear_grey_24dp_img,
getString(R.string.action_cancel),
UpdateNotificationReceiver.cancelNotificationIntent(ctx))
}
}
}
fun NotificationCompat.Builder.update(block: NotificationCompat.Builder.() -> Unit) {
block()
notificationManager.notify(NOTIFICATION_UPDATER_ID, build())
}
} | apache-2.0 | 6b0df59a81d8b0806cbc4a0ce47e245d | 37.223684 | 102 | 0.616285 | 4.99055 | false | false | false | false |
btkelly/gnag-website | src/main/kotlin/watch/gnag/website/models/github/PageLinks.kt | 1 | 2649 | package watch.gnag.website.models.github
import org.springframework.web.reactive.function.client.ClientResponse
import java.net.MalformedURLException
@Suppress("LoopWithTooManyJumpStatements", "multiline-if-else")
class PageLinks(headers: ClientResponse.Headers) {
companion object {
private const val DELIM_LINKS = ","
private const val DELIM_LINK_PARAM = ";"
private const val HEADER_LINK = "Link"
private const val META_REL = "rel"
private const val META_LAST = "last"
private const val META_NEXT = "next"
private const val META_FIRST = "first"
private const val META_PREV = "prev"
}
var first: PageLink? = null
var last: PageLink? = null
var next: PageLink? = null
var prev: PageLink? = null
init {
val linkHeader = headers.header(HEADER_LINK).firstOrNull()
linkHeader?.let {
val links = linkHeader.split(DELIM_LINKS.toRegex())
.dropLastWhile { it.isEmpty() }
.toTypedArray()
for (link in links) {
val segments = link.split(DELIM_LINK_PARAM.toRegex())
.dropLastWhile { it.isEmpty() }
.toTypedArray()
if (segments.size < 2) continue
var linkPart = segments[0].trim { it <= ' ' }
if (!linkPart.startsWith("<") || !linkPart.endsWith(">"))
continue
linkPart = linkPart.substring(1, linkPart.length - 1)
for (i in 1 until segments.size) {
val rel = segments[i].trim { it <= ' ' }
.split("=".toRegex())
.dropLastWhile { it.isEmpty() }
.toTypedArray()
if (rel.size < 2 || META_REL != rel[0]) continue
var relValue = rel[1]
if (relValue.startsWith("\"") && relValue.endsWith("\""))
relValue = relValue.substring(1, relValue.length - 1)
try {
if (META_FIRST == relValue) first =
PageLink(linkPart, relValue) else if (META_LAST == relValue) last =
PageLink(linkPart, relValue) else if (META_NEXT == relValue) next =
PageLink(linkPart, relValue) else if (META_PREV == relValue) prev =
PageLink(linkPart, relValue)
} catch (e: MalformedURLException) {
e.printStackTrace()
}
}
}
}
}
}
| apache-2.0 | f408afac711704ec4a3002185276aea6 | 34.797297 | 95 | 0.510759 | 4.614983 | false | false | false | false |
DreierF/MyTargets | shared/src/main/java/de/dreier/mytargets/shared/utils/RoundedAvatarDrawable.kt | 1 | 1891 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.shared.utils
import android.graphics.*
import android.graphics.drawable.Drawable
/**
* A Drawable that draws an oval with given [Bitmap]
*/
class RoundedAvatarDrawable(bitmap: Bitmap) : Drawable() {
private val mPaint: Paint = Paint()
private val mRectF: RectF = RectF()
private val mBitmapWidth: Int = bitmap.width
private val mBitmapHeight: Int = bitmap.height
init {
mPaint.isAntiAlias = true
mPaint.shader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
}
override fun draw(canvas: Canvas) {
canvas.drawOval(mRectF, mPaint)
}
override fun onBoundsChange(bounds: Rect) {
super.onBoundsChange(bounds)
mRectF.set(bounds)
}
override fun setAlpha(alpha: Int) {
if (mPaint.alpha != alpha) {
mPaint.alpha = alpha
invalidateSelf()
}
}
override fun setColorFilter(cf: ColorFilter?) {
mPaint.colorFilter = cf
}
override fun getOpacity(): Int {
return PixelFormat.TRANSLUCENT
}
override fun getIntrinsicWidth(): Int {
return mBitmapWidth
}
override fun getIntrinsicHeight(): Int {
return mBitmapHeight
}
override fun setFilterBitmap(filter: Boolean) {
mPaint.isFilterBitmap = filter
invalidateSelf()
}
}
| gpl-2.0 | b112bc28e7c5951c0d0b575b40979de8 | 25.633803 | 90 | 0.67266 | 4.545673 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/web/vo/graduate/design/project/GraduationDesignProjectUpdateVo.kt | 1 | 704 | package top.zbeboy.isy.web.vo.graduate.design.project
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
/**
* Created by zbeboy 2018-01-22 .
**/
open class GraduationDesignProjectUpdateVo {
@NotNull
@Size(max = 64)
var graduationDesignPlanId: String? = null
@NotNull
@Size(max = 64)
var graduationDesignReleaseId: String? = null
@NotNull
@Size(max = 100)
var scheduling: String? = null
@NotNull
@Size(max = 100)
var supervisionTime: String? = null
@NotNull
@Size(max = 150)
var guideContent: String? = null
@Size(max = 100)
var note: String? = null
@NotNull
var schoolroomId: Int? = null
} | mit | ef58f3bc5a63c05d95401e548c4a8280 | 23.310345 | 53 | 0.669034 | 3.724868 | false | false | false | false |
opst-miyatay/LightCalendarView | library/src/main/kotlin/jp/co/recruit_mp/android/lightcalendarview/WeekDayView.kt | 1 | 2326 | /*
* Copyright (C) 2016 RECRUIT MARKETING PARTNERS CO., LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.co.recruit_mp.android.lightcalendarview
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.support.v4.view.ViewCompat
import java.util.*
/**
* 曜日のラベルを表示する {@link CellView}
* Created by masayuki-recruit on 8/19/16.
*/
class WeekDayView(context: Context, settings: CalendarSettings, var weekDay: WeekDay) : CellView(context, settings) {
val text: String = weekDay.getShortLabel(context, settings.locale)
private val textPaint: Paint = settings.weekDayView.defaultTextPaint(weekDay)
private var baseX: Float = 0f
private var baseY: Float = 0f
private val observer = Observer { observable, any ->
updateMetrics()
ViewCompat.postInvalidateOnAnimation(this@WeekDayView)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
settings.weekDayView.addObserver(observer)
}
override fun onDetachedFromWindow() {
settings.weekDayView.deleteObserver(observer)
super.onDetachedFromWindow()
}
private fun updateMetrics() {
val fm = textPaint.fontMetrics
val textWidth = textPaint.measureText(text)
val textHeight = fm.descent - fm.ascent
baseX = centerX - textWidth / 2
baseY = centerY + textHeight / 2 - fm.descent
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
updateMetrics()
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawText(text, baseX, baseY, textPaint)
}
override fun toString(): String = "WeekDayView($weekDay)"
}
| apache-2.0 | 8f9924c76f3b60b80a2c024f17dba205 | 30.561644 | 117 | 0.700955 | 4.181488 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/search/declarationsSearch/overridersSearchUtils.kt | 3 | 6884 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.search.declarationsSearch
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.OverridingMethodsSearch
import com.intellij.util.Processor
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.kotlin.asJava.classes.KtFakeLightMethod
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.isOverridable
import org.jetbrains.kotlin.idea.base.util.excludeKotlinSources
import org.jetbrains.kotlin.idea.base.util.useScope
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.core.getDeepestSuperDeclarations
import org.jetbrains.kotlin.idea.core.getDirectlyOverriddenDeclarations
import org.jetbrains.kotlin.idea.refactoring.resolveToExpectedDescriptorIfPossible
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.getTypeSubstitution
import org.jetbrains.kotlin.idea.util.toSubstitutor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.util.findCallableMemberBySignature
fun forEachKotlinOverride(
ktClass: KtClass,
members: List<KtNamedDeclaration>,
scope: SearchScope,
searchDeeply: Boolean,
processor: (superMember: PsiElement, overridingMember: PsiElement) -> Boolean
): Boolean {
val baseClassDescriptor = runReadAction { ktClass.unsafeResolveToDescriptor() as ClassDescriptor }
val baseDescriptors =
runReadAction { members.mapNotNull { it.unsafeResolveToDescriptor() as? CallableMemberDescriptor }.filter { it.isOverridable } }
if (baseDescriptors.isEmpty()) return true
HierarchySearchRequest(ktClass, scope, searchDeeply).searchInheritors().forEach(Processor { psiClass ->
val inheritor = psiClass.unwrapped as? KtClassOrObject ?: return@Processor true
runReadAction {
val inheritorDescriptor = inheritor.unsafeResolveToDescriptor() as ClassDescriptor
val substitutor = getTypeSubstitution(baseClassDescriptor.defaultType, inheritorDescriptor.defaultType)?.toSubstitutor()
?: return@runReadAction true
baseDescriptors.forEach { baseDescriptor ->
val superMember = baseDescriptor.source.getPsi()!!
val overridingDescriptor = (baseDescriptor.substitute(substitutor) as? CallableMemberDescriptor)?.let { memberDescriptor ->
inheritorDescriptor.findCallableMemberBySignature(memberDescriptor)
}
val overridingMember = overridingDescriptor?.source?.getPsi()
if (overridingMember != null) {
if (!processor(superMember, overridingMember)) return@runReadAction false
}
}
true
}
})
return true
}
fun PsiMethod.forEachOverridingMethod(
scope: SearchScope = runReadAction { useScope() },
processor: (PsiMethod) -> Boolean
): Boolean {
if (this !is KtFakeLightMethod) {
if (!OverridingMethodsSearch.search(
/* method = */ this,
/* scope = */ runReadAction { scope.excludeKotlinSources(project) },
/* checkDeep = */ true,
).forEach(Processor { processor(it) })
) return false
}
val ktMember = this.unwrapped as? KtNamedDeclaration ?: return true
val ktClass = runReadAction { ktMember.containingClassOrObject as? KtClass } ?: return true
return forEachKotlinOverride(ktClass, listOf(ktMember), scope, searchDeeply = true) { _, overrider ->
val lightMethods = runReadAction { overrider.toPossiblyFakeLightMethods().distinctBy { it.unwrapped } }
lightMethods.all { processor(it) }
}
}
fun findDeepestSuperMethodsNoWrapping(method: PsiElement): List<PsiElement> {
return when (val element = method.unwrapped) {
is PsiMethod -> element.findDeepestSuperMethods().toList()
is KtCallableDeclaration -> {
val descriptor = element.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return emptyList()
descriptor.getDeepestSuperDeclarations(false).mapNotNull {
it.source.getPsi() ?: DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, it)
}
}
else -> emptyList()
}
}
fun findSuperDescriptors(declaration: KtDeclaration, descriptor: DeclarationDescriptor): Sequence<DeclarationDescriptor> {
val sequenceOfExpectedDescriptor = declaration.takeIf { it.hasActualModifier() }
?.resolveToExpectedDescriptorIfPossible()
?.let { sequenceOf(it) }
.orEmpty()
val superDescriptors = findSuperDescriptors(descriptor)
return if (superDescriptors == null) sequenceOfExpectedDescriptor else superDescriptors + sequenceOfExpectedDescriptor
}
private fun findSuperDescriptors(descriptor: DeclarationDescriptor): Sequence<DeclarationDescriptor>? {
val superDescriptors: Collection<DeclarationDescriptor> = when (descriptor) {
is ClassDescriptor -> {
val supertypes = descriptor.typeConstructor.supertypes
val superclasses = supertypes.mapNotNull { type ->
type.constructor.declarationDescriptor as? ClassDescriptor
}
ContainerUtil.removeDuplicates(superclasses)
superclasses
}
is CallableMemberDescriptor -> descriptor.getDirectlyOverriddenDeclarations()
else -> return null
}
return superDescriptors.asSequence().filterNot { it is ClassDescriptor && KotlinBuiltIns.isAny(it) }
}
fun findSuperMethodsNoWrapping(method: PsiElement): List<PsiElement> {
return when (val element = method.unwrapped) {
is PsiMethod -> element.findSuperMethods().toList()
is KtCallableDeclaration -> {
val descriptor = element.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return emptyList()
descriptor.getDirectlyOverriddenDeclarations().mapNotNull {
it.source.getPsi() ?: DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, it)
}
}
else -> emptyList()
}
}
| apache-2.0 | 56d4a2346043dd213c7c30a0145fa23b | 44.589404 | 139 | 0.734021 | 5.610432 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/demo2_0_0/TAB_OBJECT_LAYOUT.kt | 2 | 26187 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.snapshots.demo2_0_0
import org.apache.causeway.client.kroviz.snapshots.Response
object TAB_OBJECT_LAYOUT : Response(){
override val url = "http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/object-layout"
override val str = """{
"row": [
{
"cols": [
{
"col": {
"domainObject": {
"named": null,
"describedAs": null,
"plural": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/element",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object\""
},
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"namedEscaped": null
},
"action": [
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/action",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/actions/clearHints",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
},
"id": "clearHints",
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"hidden": null,
"namedEscaped": null,
"position": null,
"promptStyle": null,
"redirect": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/action",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/actions/downloadLayoutXml",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
},
"id": "downloadLayoutXml",
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"hidden": null,
"namedEscaped": null,
"position": null,
"promptStyle": null,
"redirect": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/action",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/actions/openRestApi",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
},
"id": "openRestApi",
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"hidden": null,
"namedEscaped": null,
"position": null,
"promptStyle": null,
"redirect": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/action",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/actions/rebuildMetamodel",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
},
"id": "rebuildMetamodel",
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"hidden": null,
"namedEscaped": null,
"position": null,
"promptStyle": null,
"redirect": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/action",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/actions/doHideField",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
},
"id": "doHideField",
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"hidden": null,
"namedEscaped": null,
"position": null,
"promptStyle": null,
"redirect": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/action",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/actions/doShowField",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
},
"id": "doShowField",
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"hidden": null,
"namedEscaped": null,
"position": null,
"promptStyle": null,
"redirect": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/action",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/actions/downloadMetaModelXml",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
},
"id": "downloadMetaModelXml",
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"hidden": null,
"namedEscaped": null,
"position": null,
"promptStyle": null,
"redirect": null
}
],
"metadataError": null,
"cssClass": null,
"size": null,
"id": null,
"span": 12,
"unreferencedActions": true,
"unreferencedCollections": null
}
}
],
"metadataError": null,
"cssClass": null,
"id": null
},
{
"cols": [
{
"col": {
"domainObject": null,
"tabGroup": [
{
"tab": [
{
"name": "Tab 1",
"row": [
{
"cols": [
{
"col": {
"domainObject": null,
"fieldSet": [
{
"name": "Hideable Field",
"property": [
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/property",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/properties/field1",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\""
},
"id": "field1",
"cssClass": null,
"hidden": null,
"labelPosition": null,
"multiLine": null,
"namedEscaped": null,
"promptStyle": null,
"renderDay": null,
"typicalLength": null,
"repainting": null,
"unchanging": null
}
],
"metadataError": null,
"id": "fs1",
"unreferencedActions": null,
"unreferencedProperties": null
}
],
"metadataError": null,
"cssClass": null,
"size": null,
"id": null,
"span": 12,
"unreferencedActions": null,
"unreferencedCollections": null
}
}
],
"metadataError": null,
"cssClass": null,
"id": null
}
],
"cssClass": null
},
{
"name": "Tab 2",
"row": [
{
"cols": [
{
"col": {
"domainObject": null,
"fieldSet": [
{
"name": null,
"property": [
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/property",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/properties/field2",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\""
},
"id": "field2",
"cssClass": null,
"hidden": null,
"labelPosition": null,
"multiLine": null,
"namedEscaped": null,
"promptStyle": null,
"renderDay": null,
"typicalLength": null,
"repainting": null,
"unchanging": null
}
],
"metadataError": null,
"id": "fs2",
"unreferencedActions": null,
"unreferencedProperties": null
}
],
"metadataError": null,
"cssClass": null,
"size": null,
"id": null,
"span": 12,
"unreferencedActions": null,
"unreferencedCollections": null
}
}
],
"metadataError": null,
"cssClass": null,
"id": null
}
],
"cssClass": null
}
],
"metadataError": null,
"cssClass": null,
"unreferencedCollections": null,
"collapseIfOne": null
}
],
"metadataError": null,
"cssClass": null,
"size": null,
"id": null,
"span": 6,
"unreferencedActions": null,
"unreferencedCollections": null
}
},
{
"col": {
"domainObject": null,
"fieldSet": [
{
"name": "Description",
"property": [
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/property",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/properties/description",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\""
},
"id": "description",
"cssClass": null,
"hidden": null,
"labelPosition": "NONE",
"multiLine": null,
"namedEscaped": null,
"promptStyle": null,
"renderDay": null,
"typicalLength": null,
"repainting": null,
"unchanging": null
}
],
"metadataError": null,
"id": "description",
"unreferencedActions": null,
"unreferencedProperties": true
}
],
"metadataError": null,
"cssClass": null,
"size": null,
"id": null,
"span": 6,
"unreferencedActions": null,
"unreferencedCollections": true
}
}
],
"metadataError": null,
"cssClass": null,
"id": null
}
],
"cssClass": null
}
"""
}
| apache-2.0 | 382420241f79192ca351cfb34e3d392d | 63.659259 | 368 | 0.320693 | 6.148626 | false | false | false | false |
google/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/vcsToolWindowFactories.kt | 1 | 4072 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vcs.changes.ui
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.ToolWindowEmptyStateAction.rebuildContentUi
import com.intellij.ide.impl.isTrusted
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.COMMIT_TOOLWINDOW_ID
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowEx
import com.intellij.util.ui.StatusText
private class ChangeViewToolWindowFactory : VcsToolWindowFactory() {
private val shouldShowWithoutActiveVcs = Registry.get("vcs.empty.toolwindow.show")
override fun init(window: ToolWindow) {
super.init(window)
window.setAdditionalGearActions(ActionManager.getInstance().getAction("LocalChangesView.GearActions") as ActionGroup)
}
override fun setEmptyState(project: Project, state: StatusText) {
setChangesViewEmptyState(state, project)
}
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
super.createToolWindowContent(project, toolWindow)
if (toolWindow.contentManager.isEmpty) {
// to show id label
rebuildContentUi(toolWindow)
}
}
override fun updateState(toolWindow: ToolWindow) {
super.updateState(toolWindow)
toolWindow.stripeTitle = ProjectLevelVcsManager.getInstance(toolWindow.project).allActiveVcss.singleOrNull()?.displayName
?: IdeBundle.message("toolwindow.stripe.Version_Control")
}
override fun isAvailable(project: Project) = project.isTrusted() && showWithoutActiveVcs(project)
private fun showWithoutActiveVcs(project: Project): Boolean {
return shouldShowWithoutActiveVcs.asBoolean() || ProjectLevelVcsManager.getInstance(project).hasAnyMappings()
}
}
private class CommitToolWindowFactory : VcsToolWindowFactory() {
override fun init(window: ToolWindow) {
super.init(window)
window.setAdditionalGearActions(ActionManager.getInstance().getAction("CommitView.GearActions") as ActionGroup)
hideIdLabelIfNotEmptyState(window)
}
override fun setEmptyState(project: Project, state: StatusText) {
setCommitViewEmptyState(state, project)
}
override fun isAvailable(project: Project): Boolean {
return ProjectLevelVcsManager.getInstance(project).hasAnyMappings() &&
ChangesViewContentManager.isCommitToolWindowShown(project) &&
project.isTrusted()
}
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
super.createToolWindowContent(project, toolWindow)
// to show id label
if (toolWindow.contentManager.isEmpty) {
rebuildContentUi(toolWindow)
}
}
}
internal class SwitchToCommitDialogHint(toolWindow: ToolWindowEx, toolbar: ActionToolbar) : ChangesViewContentManagerListener {
private val actionToolbarTooltip =
ActionToolbarGotItTooltip("changes.view.toolwindow", message("switch.to.commit.dialog.hint.text"),
toolWindow.disposable, toolbar, gearButtonOrToolbar)
init {
toolWindow.project.messageBus.connect(actionToolbarTooltip.tooltipDisposable).subscribe(ChangesViewContentManagerListener.TOPIC, this)
}
override fun toolWindowMappingChanged() = actionToolbarTooltip.hideHint(true)
companion object {
fun install(project: Project) {
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(COMMIT_TOOLWINDOW_ID) as? ToolWindowEx ?: return
val toolbar = toolWindow.decorator.headerToolbar ?: return
SwitchToCommitDialogHint(toolWindow, toolbar)
}
}
}
| apache-2.0 | 38f2c4538da7e79e558f027e5d8394ca | 38.533981 | 138 | 0.78168 | 4.813239 | false | false | false | false |
indianpoptart/RadioControl | RadioControl/app/src/main/java/com/nikhilparanjape/radiocontrol/listeners/CustomPhoneStateListener.kt | 1 | 4042 | package com.nikhilparanjape.radiocontrol.listeners
/**
* Created by admin on 3/4/2017.
*
* @author Nikhil Paranjape
*
*
*/
import android.content.Context
import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager
import android.util.Log
import com.nikhilparanjape.radiocontrol.utilities.Utilities
class CustomPhoneStateListener(private val context: Context) : PhoneStateListener() { //Context for making a Toast if applicable
//Root commands which disable cell only
//private var airCmd = arrayOf("su", "settings put global airplane_mode_radios \"cell\"", "content update --uri content://settings/global --bind value:s:'cell' --where \"name='airplane_mode_radios'\"", "settings put global airplane_mode_on 1", "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state true")
//runs command to disable airplane mode on wifi loss, while restoring previous airplane settings
//private val airOffCmd2 = arrayOf("su", "settings put global airplane_mode_on 0", "am broadcast -a android.intent.action.AIRPLANE_MODE --ez state false", "settings put global airplane_mode_radios \"cell,bluetooth,nfc,wimax\"", "content update --uri content://settings/global --bind value:s:'cell,bluetooth,nfc,wimax' --where \"name='airplane_mode_radios'\"")
/** Moved to Companion Object
// private var lastState = TelephonyManager.CALL_STATE_IDLE // We assume the last state of the phone call is idle for now
// private var isIncoming: Boolean = false // Boolean for if there is an incoming call
**/
@Deprecated("Deprecated in Java")
override fun onCallStateChanged(state: Int, phoneNumber: String?) {
super.onCallStateChanged(state, "1") // Do not pull phone number for privacy
val prefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(context) // General Shared Prefs for the whole app
Log.d(TAG, "PhoneCall State $state")
Log.d(TAG, "Last-State $lastState")
if (lastState == state) {
//No change, debounce extras
return
}
when (state) {
TelephonyManager.CALL_STATE_RINGING -> {
isIncoming = true // If the phone is ringing, set isIncoming to true
}
TelephonyManager.CALL_STATE_OFFHOOK -> {
//when Off hook i.e in call
//doThingChangeNameLater()
Log.d(TAG,"Outgoing Call Starting")
isIncoming = false // Phone is no longer ringing, it was picked up, set isIncoming to false
lastState = state
Utilities.enableNetworks(context, prefs)
}
TelephonyManager.CALL_STATE_IDLE -> {
when {
lastState == TelephonyManager.CALL_STATE_RINGING -> {
// When phone is idle and the last state was ringing do nothing for now
}
isIncoming -> {
// When there
}
else -> {
Log.d(TAG, "Job Time")
// Utilities.scheduleJob(context)
Utilities.disableNetworks(prefs, context)
}
}
}
}// when Idle i.e no call
lastState = state
// Toast.makeText(context, "Phone state Idle", Toast.LENGTH_LONG).show();
// Toast.makeText(context, "Phone state Off hook", Toast.LENGTH_LONG).show();
// when Ringing
// Toast.makeText(context, "Phone state Ringing", Toast.LENGTH_LONG).show();
}
companion object {
private const val TAG = "RadioControl-phoneSL"
private var lastState = TelephonyManager.CALL_STATE_IDLE // We assume the last state of the phone call is idle for now
private var isIncoming: Boolean = false // Boolean for if there is an incoming call
}
} | gpl-3.0 | 1c4aae909ef95f0f095f455b9eede7e1 | 48.55 | 364 | 0.609104 | 4.716453 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertBinaryExpressionWithDemorgansLawIntention.kt | 1 | 4901 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.idea.inspections.ReplaceNegatedIsEmptyWithIsNotEmptyInspection.Companion.invertSelectorFunction
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.KtPsiUtil.deparenthesize
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.typeUtil.isBoolean
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class ConvertBinaryExpressionWithDemorgansLawIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>(
KtBinaryExpression::class.java,
KotlinBundle.lazyMessage("demorgan.law")
) {
override fun isApplicableTo(element: KtBinaryExpression): Boolean {
val expr = element.topmostBinaryExpression()
setTextGetter(
when (expr.operationToken) {
KtTokens.ANDAND -> KotlinBundle.lazyMessage("replace.with2")
KtTokens.OROR -> KotlinBundle.lazyMessage("replace.with")
else -> return false
}
)
return splitBooleanSequence(expr) != null
}
override fun applyTo(element: KtBinaryExpression, editor: Editor?) = applyTo(element)
companion object {
fun convertIfPossible(element: KtBinaryExpression) {
val expr = element.topmostBinaryExpression()
if (splitBooleanSequence(expr) == null) return
applyTo(element)
}
private fun KtBinaryExpression.topmostBinaryExpression(): KtBinaryExpression =
parentsWithSelf.takeWhile { it is KtBinaryExpression }.last() as KtBinaryExpression
private fun applyTo(element: KtBinaryExpression) {
val expr = element.topmostBinaryExpression()
val operatorText = when (expr.operationToken) {
KtTokens.ANDAND -> KtTokens.OROR.value
KtTokens.OROR -> KtTokens.ANDAND.value
else -> throw IllegalArgumentException()
}
val context by lazy { expr.analyze(BodyResolveMode.PARTIAL) }
val operands = splitBooleanSequence(expr) { context }?.asReversed() ?: return
val newExpression = KtPsiFactory(expr.project).buildExpression {
val negatedOperands = operands.map {
it.safeAs<KtQualifiedExpression>()?.invertSelectorFunction(context) ?: it.negate()
}
appendExpressions(negatedOperands, separator = operatorText)
}
val grandParentPrefix = expr.parent.parent as? KtPrefixExpression
val negated = expr.parent is KtParenthesizedExpression &&
grandParentPrefix?.operationReference?.getReferencedNameElementType() == KtTokens.EXCL
if (negated) {
grandParentPrefix?.replace(newExpression)
} else {
expr.replace(newExpression.negate())
}
}
private fun splitBooleanSequence(expression: KtBinaryExpression, contextProvider: (() -> BindingContext)? = null): List<KtExpression>? {
val result = ArrayList<KtExpression>()
val firstOperator = expression.operationToken
var remainingExpression: KtExpression = expression
while (true) {
if (remainingExpression !is KtBinaryExpression) break
if (deparenthesize(remainingExpression.left) is KtStatementExpression ||
deparenthesize(remainingExpression.right) is KtStatementExpression
) return null
val operation = remainingExpression.operationToken
if (operation != KtTokens.ANDAND && operation != KtTokens.OROR) break
if (operation != firstOperator) return null //Boolean sequence must be homogenous
result.add(remainingExpression.right ?: return null)
remainingExpression = remainingExpression.left ?: return null
}
result.add(remainingExpression)
val context = contextProvider?.invoke() ?: expression.analyze(BodyResolveMode.PARTIAL)
if (!expression.left.isBoolean(context) || !expression.right.isBoolean(context)) return null
return result
}
private fun KtExpression?.isBoolean(context: BindingContext) = this != null && context.getType(this)?.isBoolean() == true
}
}
| apache-2.0 | fbfd242054614d765f7c814ffca55c08 | 48.505051 | 144 | 0.683126 | 5.569318 | false | false | false | false |
mikepenz/Android-Iconics | iconics-core/src/main/java/com/mikepenz/iconics/context/InternalLayoutInflater.kt | 1 | 8269 | /*
* Copyright 2020 Mike Penz
*
* 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.mikepenz.iconics.context
import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import org.xmlpull.v1.XmlPullParser
import java.lang.reflect.Field
/**
* Base created by Christopher Jenkins
* https://github.com/chrisjenx/Calligraphy
*/
@Deprecated(message = "Use the IconicsImageView or IconicsTextView instead")
internal class InternalLayoutInflater : LayoutInflater {
// Reflection Hax
private var isSetPrivateFactory = false
private var constructorArgs: Field? = null
protected constructor(context: Context) : super(context) {
setUpLayoutFactories(false)
}
constructor(
original: LayoutInflater,
newContext: Context,
cloned: Boolean
) : super(original, newContext) {
setUpLayoutFactories(cloned)
}
override fun cloneInContext(newContext: Context): LayoutInflater {
return InternalLayoutInflater(this, newContext, true)
}
@Throws(ClassNotFoundException::class)
override fun onCreateView(name: String, attrs: AttributeSet): View? {
var view: View? = null
classPrefixList.forEach { runCatching { view = createView(name, it, attrs) } }
// In this case we want to let the base class take a crack at it.
if (view == null) {
view = super.onCreateView(name, attrs)
}
return view?.let { IconicsFactory.onViewCreated(it, it.context, attrs) }
}
@Throws(ClassNotFoundException::class)
override fun onCreateView(parent: View?, name: String, attrs: AttributeSet): View? {
val view = super.onCreateView(parent, name, attrs)
return IconicsFactory.onViewCreated(view, context, attrs)
}
// ===
// Wrapping goodies
// ===
override fun inflate(parser: XmlPullParser, root: ViewGroup?, attachToRoot: Boolean): View {
setPrivateFactoryInternal()
return super.inflate(parser, root, attachToRoot)
}
/**
* We don't want to unnecessary create/set our factories if there are none there. We try to be
* as lazy as possible.
*/
private fun setUpLayoutFactories(cloned: Boolean) {
if (cloned) {
return
}
if (factory2 != null && factory2 !is InternalLayoutInflater.WrapperFactory2) {
// Sets both Factory/Factory2
factory2 = factory2
}
}
override fun setFactory(factory: LayoutInflater.Factory) {
// Only set our factory and wrap calls to the Factory trying to be set!
if (factory !is InternalLayoutInflater.WrapperFactory) {
super.setFactory(InternalLayoutInflater.WrapperFactory(factory))
} else {
super.setFactory(factory)
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
override fun setFactory2(factory2: LayoutInflater.Factory2) {
// Only set our factory and wrap calls to the Factory2 trying to be set!
if (factory2 !is InternalLayoutInflater.WrapperFactory2) {
super.setFactory2(InternalLayoutInflater.WrapperFactory2(factory2))
} else {
super.setFactory2(factory2)
}
}
private fun setPrivateFactoryInternal() {
// Already tried to set the factory.
if (isSetPrivateFactory) {
return
}
// Skip if not attached to an activity.
if (context !is LayoutInflater.Factory2) {
isSetPrivateFactory = true
return
}
val setPrivateFactoryMethod = ReflectionUtils.getMethod(
LayoutInflater::class.java,
"setPrivateFactory"
)
if (setPrivateFactoryMethod != null) {
ReflectionUtils.invokeMethod(
this,
setPrivateFactoryMethod,
PrivateWrapperFactory2(
context as LayoutInflater.Factory2,
this
)
)
}
isSetPrivateFactory = true
}
private fun createCustomViewInternal(
view: View?,
name: String,
viewContext: Context,
attrs: AttributeSet
): View? {
var createdView = view
if (createdView == null && name.contains('.')) {
if (constructorArgs == null) {
constructorArgs = ReflectionUtils.getField(
LayoutInflater::class.java,
"mConstructorArgs"
)
}
val constructorArgs = this.constructorArgs ?: return null
@Suppress("UNCHECKED_CAST")
val constArgs = ReflectionUtils.getValue(constructorArgs, this) as Array<Any>
val lastContext = constArgs[0]
// The LayoutInflater actually finds out the correct context to use. We just need to set
// it on the mConstructor for the internal method.
// Set the constructor ars up for the createView, not sure why we can't pass these in.
constArgs[0] = viewContext
ReflectionUtils.setValue(constructorArgs, this, constArgs)
runCatching { createdView = createView(name, null, attrs) }
constArgs[0] = lastContext
ReflectionUtils.setValue(constructorArgs, this, constArgs)
}
return createdView
}
// ===
// Wrapper Factories for Pre/Post HC
// ===
/** Factory 1 is the first port of call for LayoutInflation */
private class WrapperFactory(
private val factory: LayoutInflater.Factory
) : LayoutInflater.Factory {
override fun onCreateView(name: String, context: Context, attrs: AttributeSet): View? {
val view = factory.onCreateView(name, context, attrs)
return IconicsFactory.onViewCreated(view, context, attrs)
}
}
/** Factory 2 is the second port of call for LayoutInflation */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private open class WrapperFactory2(
protected val factory2: LayoutInflater.Factory2
) : LayoutInflater.Factory2 {
override fun onCreateView(name: String, context: Context, attrs: AttributeSet): View? {
val view = factory2.onCreateView(name, context, attrs)
return IconicsFactory.onViewCreated(view, context, attrs)
}
override fun onCreateView(
parent: View?,
name: String,
context: Context,
attrs: AttributeSet
): View? {
val view = factory2.onCreateView(parent, name, context, attrs)
return IconicsFactory.onViewCreated(view, context, attrs)
}
}
/**
* Private factory is step three for Activity Inflation, this is what is attached to the
* Activity on HC+ devices.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private class PrivateWrapperFactory2(
factory2: LayoutInflater.Factory2,
private val inflater: InternalLayoutInflater
) : InternalLayoutInflater.WrapperFactory2(factory2) {
override fun onCreateView(
parent: View?,
name: String,
context: Context,
attrs: AttributeSet
): View? {
val view = factory2.onCreateView(parent, name, context, attrs)
val customView = inflater.createCustomViewInternal(view, name, context, attrs)
return IconicsFactory.onViewCreated(customView, context, attrs)
}
}
companion object {
private val classPrefixList = arrayOf("android.widget.", "android.webkit.")
}
} | apache-2.0 | c936bfdeff39ca3c09f4ac3a759f12a1 | 33.458333 | 100 | 0.639013 | 4.87559 | false | false | false | false |
allotria/intellij-community | python/testSrc/com/jetbrains/python/PyLineBreakpointTypeTest.kt | 2 | 2723 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.util.TextRange
import com.jetbrains.python.codeInsight.typing.PyTypeShed
import com.jetbrains.python.codeInsight.userSkeletons.PyUserSkeletonsUtil.getUserSkeletonsDirectory
import com.jetbrains.python.debugger.PyLineBreakpointType
import com.jetbrains.python.fixtures.PyTestCase
class PyLineBreakpointTypeTest : PyTestCase() {
// PY-16932
fun testPutAtUserSkeleton() {
val skeletonsDir = getUserSkeletonsDirectory()
val pythonFile = skeletonsDir!!.findFileByRelativePath("nose/tools/__init__.py")
val line = 13
val document = FileDocumentManager.getInstance().getDocument(pythonFile!!)
val range = TextRange.create(document!!.getLineStartOffset(line), document.getLineEndOffset(line))
assertEquals(" pass", document.getText(range))
assertFalse(PyLineBreakpointType().canPutAt(pythonFile, line, myFixture.project))
}
// PY-16932
fun testPutAtSkeleton() {
runWithAdditionalFileInSkeletonDir("my_mod.py", "class A:\n def method(self):\n print(\"ok\")") { pythonFile ->
val line = 2
val document = FileDocumentManager.getInstance().getDocument(pythonFile)
val range = TextRange.create(document!!.getLineStartOffset(line), document.getLineEndOffset(line))
assertEquals(" print(\"ok\")", document.getText(range))
assertFalse(PyLineBreakpointType().canPutAt(pythonFile, line, myFixture.project))
}
}
// PY-16932
fun testPutAtPythonStub() {
val pythonFile = PyTypeShed.directory!!.findFileByRelativePath("stdlib/@python2/__builtin__.pyi")
val line = 55
val document = FileDocumentManager.getInstance().getDocument(pythonFile!!)
val range = TextRange.create(document!!.getLineStartOffset(line), document.getLineEndOffset(line))
assertEquals("_T = TypeVar(\"_T\")", document.getText(range))
assertFalse(PyLineBreakpointType().canPutAt(pythonFile, line, myFixture.project))
}
fun testCorrect() {
val pythonFile = myFixture.configureByText(PythonFileType.INSTANCE, "def foo():\n" +
" print(1)").virtualFile
val line = 1
val document = FileDocumentManager.getInstance().getDocument(pythonFile!!)
val range = TextRange.create(document!!.getLineStartOffset(line), document.getLineEndOffset(line))
assertEquals(" print(1)", document.getText(range))
assertTrue(PyLineBreakpointType().canPutAt(pythonFile, line, myFixture.project))
}
}
| apache-2.0 | fbc134064cd77bbf0bfe2e367e158832 | 42.919355 | 140 | 0.72567 | 4.576471 | false | true | false | false |
Skatteetaten/boober | src/test/kotlin/no/skatteetaten/aurora/boober/feature/DatabaseFeatureTest.kt | 1 | 17768 | package no.skatteetaten.aurora.boober.feature
import java.util.UUID
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.boot.web.client.RestTemplateBuilder
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import assertk.Assert
import assertk.assertThat
import assertk.assertions.contains
import assertk.assertions.hasSize
import assertk.assertions.isEmpty
import assertk.assertions.isEqualTo
import assertk.assertions.isInstanceOf
import assertk.assertions.isSuccess
import io.fabric8.kubernetes.api.model.Secret
import io.fabric8.openshift.api.model.DeploymentConfig
import io.mockk.every
import io.mockk.mockk
import no.skatteetaten.aurora.boober.controller.security.User
import no.skatteetaten.aurora.boober.facade.json
import no.skatteetaten.aurora.boober.model.AuroraConfigFile
import no.skatteetaten.aurora.boober.model.AuroraResource
import no.skatteetaten.aurora.boober.model.openshift.ApplicationDeployment
import no.skatteetaten.aurora.boober.service.UserDetailsProvider
import no.skatteetaten.aurora.boober.service.resourceprovisioning.DatabaseSchemaInstance
import no.skatteetaten.aurora.boober.service.resourceprovisioning.DatabaseSchemaProvisioner
import no.skatteetaten.aurora.boober.service.resourceprovisioning.DbApiEnvelope
import no.skatteetaten.aurora.boober.service.resourceprovisioning.DbhRestTemplateWrapper
import no.skatteetaten.aurora.boober.service.resourceprovisioning.DbhSchema
import no.skatteetaten.aurora.boober.service.resourceprovisioning.DbhUser
import no.skatteetaten.aurora.boober.service.resourceprovisioning.RestorableSchema
import no.skatteetaten.aurora.boober.utils.AbstractFeatureTest
import no.skatteetaten.aurora.boober.utils.addIfNotNull
import no.skatteetaten.aurora.boober.utils.singleApplicationError
import no.skatteetaten.aurora.boober.utils.singleApplicationErrorResult
import no.skatteetaten.aurora.mockmvc.extensions.mockwebserver.HttpMock
import no.skatteetaten.aurora.mockmvc.extensions.mockwebserver.httpMockServer
import okhttp3.mockwebserver.MockResponse
class DatabaseFeatureTest : AbstractFeatureTest() {
val provisioner = DatabaseSchemaProvisioner(
DbhRestTemplateWrapper(RestTemplateBuilder().build(), "http://localhost:5000", 0),
jacksonObjectMapper()
)
override val feature: Feature
get() = DatabaseFeature(provisioner, userDetailsProvider, "utv")
val userDetailsProvider: UserDetailsProvider = mockk()
@BeforeEach
fun setupMock() {
every { userDetailsProvider.getAuthenticatedUser() } returns User("username", "token")
}
@AfterEach
fun clearMocks() {
HttpMock.clearAllHttpMocks()
}
@Test
fun `create database secret`() {
httpMockServer(5000) {
rule {
json(DbApiEnvelope("ok", listOf(schema)))
}
}
val (adResource, dcResource, secretResource) = generateResources(
"""{
"database" : true
}""",
resources = mutableSetOf(createEmptyApplicationDeployment(), createEmptyDeploymentConfig())
)
assertThat(dcResource).auroraDatabaseMounted(listOf(secretResource))
assertThat(adResource).auroraDatabaseIdsAdded(listOf(secretResource))
}
@Test
fun `should get error if schema with id does not exist`() {
httpMockServer(5000) {
rule {
json(DbApiEnvelope<DbhSchema>("ok", emptyList()))
}
}
assertThat {
createAuroraDeploymentContext(
"""{
"database" : {
"simple" : "123456"
}
}"""
)
}.singleApplicationErrorResult("Could not find schema")
}
@Test
fun `should get error if schema with generate false does not exist`() {
httpMockServer(5000) {
rule {
json(DbApiEnvelope<DbhSchema>("ok", emptyList()))
}
}
assertThat {
createAuroraDeploymentContext(
"""{
"database" : {
"foo" : {
"generate" : false
}
}
}"""
)
}.singleApplicationErrorResult("Could not find schema")
}
@Test
fun `create database secret with instance defaults`() {
httpMockServer(5000) {
rule {
json(DbApiEnvelope("ok", listOf(schema)))
}
}
val (adResource, dcResource, secretResource) = generateResources(
"""{
"database" : true,
"databaseDefaults" : {
"tryReuse" : true,
"flavor" : "POSTGRES_MANAGED",
"generate" : false,
"instance" : {
"name" : "corrusant",
"fallback" : true,
"labels" : {
"type" : "ytelse"
}
}
}
}""",
resources = mutableSetOf(createEmptyApplicationDeployment(), createEmptyDeploymentConfig())
)
assertThat(dcResource).auroraDatabaseMounted(listOf(secretResource))
assertThat(adResource).auroraDatabaseIdsAdded(listOf(secretResource))
}
@Test
fun `create database secret from id`() {
httpMockServer(5000) {
rule {
json(DbApiEnvelope("ok", listOf(schema)))
}
}
val (adResource, dcResource, secretResource) = generateResources(
"""{
"database" : {
"simple" : "123456"
}
}""",
resources = mutableSetOf(createEmptyApplicationDeployment(), createEmptyDeploymentConfig())
)
assertThat(dcResource).auroraDatabaseMounted(listOf(secretResource))
assertThat(adResource).auroraDatabaseIdsAdded(listOf(secretResource))
}
@Test
fun `should get error if schema with id is not in the selected affiliation`() {
val uuid = UUID.randomUUID()
httpMockServer(5000) {
rule {
json(DbApiEnvelope("ok", listOf(createDbhSchema(uuid))))
}
}
assertThat {
generateResources(
"""{
"database" : {
"simple" : "$uuid"
}
}""",
resources = mutableSetOf(createEmptyApplicationDeployment(), createEmptyDeploymentConfig()),
files = listOf(
AuroraConfigFile(
"about.json",
"""{
"schemaVersion": "v1",
"type": "deploy",
"cluster": "utv",
"affiliation": "aurora"
}"""
)
)
)
}.singleApplicationError("Schema with id=$uuid is located in the affiliation=paas, current affiliation=aurora. Using schema with id across affiliations is not allowed")
}
@Test
fun `ignore false database`() {
val result = generateResources(
"""{
"database" : false
}"""
)
assertThat(result).isEmpty()
}
@Test
fun `ignore false databases`() {
val result = generateResources(
"""{
"database" : {
"foo" : false,
"bar" : "false"
}
}"""
)
assertThat(result).isEmpty()
}
@Test
fun `Should not run full validation when cluster is not same as boober cluster`() {
assertThat {
createAuroraDeploymentContext(
""" {
"databaseDefaults": {
"generate": false
},
"cluster": "notsamecluster",
"database": true
}
""".trimIndent()
)
}.isSuccess()
}
@Test
fun `create two database secret with auto`() {
httpMockServer(5000) {
rule {
json(DbApiEnvelope("ok", listOf(schema)))
}
}
val (adResource, dcResource, fooDatabase, barDatabase) = generateResources(
"""{
"database" : {
"foo" : "auto",
"bar" : "auto"
}
}""",
createdResources = 2,
resources = mutableSetOf(createEmptyApplicationDeployment(), createEmptyDeploymentConfig())
)
assertThat(dcResource).auroraDatabaseMounted(listOf(fooDatabase, barDatabase))
assertThat(adResource).auroraDatabaseIdsAdded(listOf(fooDatabase, barDatabase))
}
@Test
fun `create two database secret`() {
httpMockServer(5000) {
rule {
json(DbApiEnvelope("ok", listOf(schema)))
}
}
val (adResource, dcResource, fooDatabase, barDatabase) = generateResources(
"""{
"database" : {
"foo" : {
"enabled" : true,
"tryReuse" : true
},
"bar" : {
"enabled" : true
}
}
}""",
createdResources = 2,
resources = mutableSetOf(createEmptyApplicationDeployment(), createEmptyDeploymentConfig())
)
assertThat(dcResource).auroraDatabaseMounted(listOf(fooDatabase, barDatabase))
assertThat(adResource).auroraDatabaseIdsAdded(listOf(fooDatabase, barDatabase))
}
@Test
fun `get two dbs with tryReuse as default and generate disabled`() {
val barSchema = createRestorableSchema()
val fooSchema = createRestorableSchema()
httpMockServer(5000) {
rule({
path!!.contains("/schema/") && method == "GET"
}) {
json(DbApiEnvelope("ok", emptyList<Any>()))
}
rule({
path!!.contains("/restorableSchema/") && method == "GET" && path!!.contains(barSchema.databaseSchema.id)
}) {
json(DbApiEnvelope("ok", listOf(barSchema)))
}
rule({
path!!.contains("/restorableSchema/") && method == "GET"
}) {
json(DbApiEnvelope("ok", listOf(fooSchema)))
}
}
assertThat {
createAuroraDeploymentContext(
"""{
"database" : {
"foo": {
"enabled": true
},
"bar": {
"id": "${barSchema.databaseSchema.id}"
}
},
"databaseDefaults" : {
"tryReuse" : true,
"flavor" : "POSTGRES_MANAGED",
"generate" : false
}
}"""
)
}.isSuccess()
}
@Test
fun `create database ignore disabled`() {
httpMockServer(5000) {
rule {
json(DbApiEnvelope("ok", listOf(schema)))
}
}
val (adResource, dcResource, fooDatabase) = generateResources(
"""{
"database" : {
"foo" : {
"enabled" : true
},
"bar" : {
"enabled" : false
}
}
}""",
resources = mutableSetOf(createEmptyApplicationDeployment(), createEmptyDeploymentConfig())
)
assertThat(dcResource).auroraDatabaseMounted(listOf(fooDatabase))
assertThat(adResource).auroraDatabaseIdsAdded(listOf(fooDatabase))
}
@Test
fun `when ignoreMissingSchema is true do not fail validation or generate resource when generate is false and schema is not found`() {
httpMockServer(5000) {
rule({ method == "GET" }) {
MockResponse()
.setResponseCode(404)
}
}
val res = generateResources(
"""{
"databaseDefaults": {
"generate": false,
"tryReuse": true,
"ignoreMissingSchema": true
},
"database": {
"foo": {
"enabled": true
},
"bar": {
"enabled": true
}
}
}"""
)
assertThat(res).isEmpty()
}
@Test
fun `when ignoreMissingSchema is true and generate is false then it should generate resource if schema is found`() {
httpMockServer(5000) {
rule({ method == "GET" && path!!.contains("foo") }) {
json(DbApiEnvelope("ok", listOf(schema)))
}
rule({ method == "GET" }) {
MockResponse()
.setResponseCode(404)
}
}
val res = generateResources(
"""{
"databaseDefaults": {
"generate": false,
"tryReuse": true,
"ignoreMissingSchema": true
},
"database": {
"foo": {
"enabled": true
},
"bar": {
"enabled": true
}
}
}"""
)
assertThat(res).hasSize(1)
}
@Test
fun `fail when generate is false and schema is missing when overriding ignoreMissingSchema`() {
httpMockServer(5000) {
rule({ method == "GET" }) {
MockResponse()
.setResponseCode(404)
}
}
assertThat {
generateResources(
"""{
"databaseDefaults": {
"generate": false,
"ignoreMissingSchema": true
},
"database": {
"foo": {
"enabled": true
},
"bar": {
"enabled": true,
"ignoreMissingSchema": false
}
}
}"""
)
}.singleApplicationError("Could not find schema with name=bar")
}
fun Assert<AuroraResource>.auroraDatabaseIdsAdded(
databases: List<AuroraResource>
): Assert<AuroraResource> = transform { actual ->
assertThat(actual).auroraResourceModifiedByThisFeatureWithComment("Added databaseId")
val ad = actual.resource as ApplicationDeployment
val expectedDbId = ad.spec.databases
databases.forEach {
val secret = it.resource as Secret
assertThat(expectedDbId, "contains dbh id").contains(secret.metadata.labels["dbhId"])
}
actual
}
fun Assert<AuroraResource>.auroraDatabaseMounted(
databases: List<AuroraResource>
): Assert<AuroraResource> = transform { actual ->
assertThat(actual.resource).isInstanceOf(DeploymentConfig::class.java)
assertThat(actual).auroraResourceModifiedByThisFeatureWithComment("Added env vars, volume mount, volume")
val dc = actual.resource as DeploymentConfig
val podSpec = dc.spec.template.spec
val container = podSpec.containers[0]
val firstEnv = databases.firstOrNull()?.let {
val name = if ("${dc.metadata.name}-db" != it.resource.metadata.name) {
it.resource.metadata.name.removePrefix("${dc.metadata.name}-")
} else {
it.resource.metadata.name
}
createDbEnv(name, "db")
}
val dbEnv = databases.flatMap {
val name = if ("${dc.metadata.name}-db" != it.resource.metadata.name) {
it.resource.metadata.name.removePrefix("${dc.metadata.name}-")
} else {
it.resource.metadata.name
}
createDbEnv(name)
}.addIfNotNull(firstEnv).toMap()
databases.forEachIndexed { index, it ->
assertThat(it).auroraResourceCreatedByThisFeature()
val secret = it.resource as Secret
assertThat(secret.data.keys.toList())
.isEqualTo(listOf("db.properties", "id", "info", "jdbcurl", "name"))
val volume = podSpec.volumes[index]
val volumeMount = container.volumeMounts[index]
val volumeMountName = volumeMount.name
assertThat(volume.name).isEqualTo(volumeMountName)
assertThat(volume.secret.secretName).isEqualTo(it.resource.metadata.name)
}
val env: Map<String, String> = container.env.associate { it.name to it.value }
assertThat(dbEnv, "Env vars").isEqualTo(env)
actual
}
}
fun createRestorableSchema(id: UUID = UUID.randomUUID()) =
RestorableSchema(setToCooldownAt = 0L, deleteAfter = 0L, databaseSchema = createDbhSchema(id))
fun createDbhSchema(
id: UUID = UUID.randomUUID(),
jdbcUrl: String = "foo/bar/baz",
databaseInstance: DatabaseSchemaInstance = DatabaseSchemaInstance(1512, "localhost")
) =
DbhSchema(
id = id.toString(),
type = "SCHEMA",
databaseInstance = databaseInstance,
jdbcUrl = jdbcUrl,
labels = mapOf(
"affiliation" to "paas",
"name" to "myApp"
),
users = listOf(DbhUser("username", "password", type = "SCHEMA"))
)
val schema = createDbhSchema()
| apache-2.0 | 933176512069e8d9a602fdafa8a44441 | 31.246824 | 176 | 0.539284 | 5.171129 | false | false | false | false |
ursjoss/sipamato | core/core-web/src/main/java/ch/difty/scipamato/core/web/paper/SearchOrderChangeEvent.kt | 2 | 2302 | package ch.difty.scipamato.core.web.paper
import org.apache.wicket.ajax.AjaxRequestTarget
/**
* The event indicates that there were changes in the search order deriving from
* the [SearchOrderPanel] that will or may affect other child components
* of the parent page container holding the [SearchOrderPanel].
*
*
* There are a couple of special options that can be achieved with the event:
*
*
* * if the excluded id is set, the sink will be requested to handle that id
* an treat it as an excluded id.
* * if the newSearchOrderRequested flag is set, the sink will need to take
* care of creating a new SearchOrder and set it as the model.
*
*
* @author u.joss
*/
class SearchOrderChangeEvent(val target: AjaxRequestTarget) {
var excludedId: Long? = null
private set
var droppedConditionId: Long? = null
private set
var isNewSearchOrderRequested = false
private set
fun withExcludedPaperId(excludedId: Long): SearchOrderChangeEvent {
this.excludedId = excludedId
droppedConditionId = null
isNewSearchOrderRequested = false
return this
}
fun withDroppedConditionId(id: Long?): SearchOrderChangeEvent {
droppedConditionId = id
excludedId = null
isNewSearchOrderRequested = false
return this
}
fun requestingNewSearchOrder(): SearchOrderChangeEvent {
isNewSearchOrderRequested = true
droppedConditionId = null
excludedId = null
return this
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as SearchOrderChangeEvent
if (target != other.target) return false
if (excludedId != other.excludedId) return false
if (droppedConditionId != other.droppedConditionId) return false
if (isNewSearchOrderRequested != other.isNewSearchOrderRequested) return false
return true
}
override fun hashCode(): Int {
var result = target.hashCode()
result = 31 * result + (excludedId?.hashCode() ?: 0)
result = 31 * result + (droppedConditionId?.hashCode() ?: 0)
result = 31 * result + isNewSearchOrderRequested.hashCode()
return result
}
}
| gpl-3.0 | f952c99cce144fffdf00336ee06622f9 | 30.534247 | 86 | 0.67854 | 4.688391 | false | false | false | false |
matrix-org/matrix-android-sdk | matrix-sdk-crypto/src/main/java/org/matrix/androidsdk/crypto/rest/model/crypto/KeyVerificationAccept.kt | 1 | 3845 | /*
* Copyright 2019 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.matrix.androidsdk.crypto.rest.model.crypto
import com.google.gson.annotations.SerializedName
import org.matrix.androidsdk.core.Log
import org.matrix.androidsdk.crypto.verification.SASVerificationTransaction
/**
* Sent by Bob to accept a verification from a previously sent m.key.verification.start message.
*/
class KeyVerificationAccept : SendToDeviceObject {
/**
* string to identify the transaction.
* This string must be unique for the pair of users performing verification for the duration that the transaction is valid.
* Alice’s device should record this ID and use it in future messages in this transaction.
*/
@JvmField
@SerializedName("transaction_id")
var transactionID: String? = null
/**
* The key agreement protocol that Bob’s device has selected to use, out of the list proposed by Alice’s device
*/
@JvmField
@SerializedName("key_agreement_protocol")
var keyAgreementProtocol: String? = null
/**
* The hash algorithm that Bob’s device has selected to use, out of the list proposed by Alice’s device
*/
@JvmField
var hash: String? = null
/**
* The message authentication code that Bob’s device has selected to use, out of the list proposed by Alice’s device
*/
@JvmField
@SerializedName("message_authentication_code")
var messageAuthenticationCode: String? = null
/**
* An array of short authentication string methods that Bob’s client (and Bob) understands. Must be a subset of the list proposed by Alice’s device
*/
@JvmField
@SerializedName("short_authentication_string")
var shortAuthenticationStrings: List<String>? = null
/**
* The hash (encoded as unpadded base64) of the concatenation of the device’s ephemeral public key (QB, encoded as unpadded base64)
* and the canonical JSON representation of the m.key.verification.start message.
*/
@JvmField
var commitment: String? = null
fun isValid(): Boolean {
if (transactionID.isNullOrBlank()
|| keyAgreementProtocol.isNullOrBlank()
|| hash.isNullOrBlank()
|| commitment.isNullOrBlank()
|| messageAuthenticationCode.isNullOrBlank()
|| shortAuthenticationStrings.isNullOrEmpty()) {
Log.e(SASVerificationTransaction.LOG_TAG, "## received invalid verification request")
return false
}
return true
}
companion object {
fun create(tid: String,
keyAgreementProtocol: String,
hash: String,
commitment: String,
messageAuthenticationCode: String,
shortAuthenticationStrings: List<String>): KeyVerificationAccept {
return KeyVerificationAccept().apply {
this.transactionID = tid
this.keyAgreementProtocol = keyAgreementProtocol
this.hash = hash
this.commitment = commitment
this.messageAuthenticationCode = messageAuthenticationCode
this.shortAuthenticationStrings = shortAuthenticationStrings
}
}
}
}
| apache-2.0 | 5114e440905fc0549b782d43027a48de | 36.5 | 152 | 0.671111 | 4.948254 | false | false | false | false |
spring-projects/spring-framework | spring-test/src/main/kotlin/org/springframework/test/web/reactive/server/WebTestClientExtensions.kt | 1 | 3487 | /*
* Copyright 2002-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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.reactive.server
import kotlinx.coroutines.flow.Flow
import org.reactivestreams.Publisher
import org.springframework.core.ParameterizedTypeReference
import org.springframework.test.web.reactive.server.WebTestClient.*
/**
* Extension for [RequestBodySpec.body] providing a variant without explicit class
* parameter thanks to Kotlin reified type parameters.
*
* @author Sebastien Deleuze
* @since 5.0
*/
inline fun <reified T : Any, S : Publisher<T>> RequestBodySpec.body(publisher: S): RequestHeadersSpec<*>
= body(publisher, object : ParameterizedTypeReference<T>() {})
/**
* Extension for [RequestBodySpec.body] providing a `body<T>(Any)` variant
* leveraging Kotlin reified type parameters. This extension is not subject to type
* erasure and retains actual generic type arguments.
* @param producer the producer to write to the request. This must be a
* [Publisher] or another producer adaptable to a
* [Publisher] via [org.springframework.core.ReactiveAdapterRegistry]
* @param T the type of the elements contained in the producer
* @author Sebastien Deleuze
* @since 5.2
*/
inline fun <reified T : Any> RequestBodySpec.body(producer: Any): RequestHeadersSpec<*>
= body(producer, object : ParameterizedTypeReference<T>() {})
/**
* Extension for [RequestBodySpec.body] providing a `body(Flow<T>)` variant
* leveraging Kotlin reified type parameters. This extension is not subject to type
* erasure and retains actual generic type arguments.
* @param flow the [Flow] to write to the request
* @param T the type of the elements contained in the publisher
* @author Sebastien Deleuze
* @since 5.2
*/
inline fun <reified T : Any> RequestBodySpec.body(flow: Flow<T>): RequestHeadersSpec<*> =
body(flow, object : ParameterizedTypeReference<T>() {})
/**
* Extension for [ResponseSpec.expectBody] providing an `expectBody<Foo>()` variant
* leveraging Kotlin reified type parameters. This extension is not subject ot type
* erasure and retains actual generic type arguments.
*
* @author Sebastien Deleuze
* @author Arjen Poutsma
* @since 5.0
*/
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
inline fun <reified B : Any> ResponseSpec.expectBody(): BodySpec<B, *> =
expectBody(object : ParameterizedTypeReference<B>() {})
/**
* Extension for [ResponseSpec.expectBodyList] providing a `expectBodyList<Foo>()` variant.
*
* @author Sebastien Deleuze
* @since 5.0
*/
inline fun <reified E : Any> ResponseSpec.expectBodyList(): ListBodySpec<E> =
expectBodyList(object : ParameterizedTypeReference<E>() {})
/**
* Extension for [ResponseSpec.returnResult] providing a `returnResult<Foo>()` variant.
*
* @author Sebastien Deleuze
* @since 5.0
*/
inline fun <reified T : Any> ResponseSpec.returnResult(): FluxExchangeResult<T> =
returnResult(object : ParameterizedTypeReference<T>() {})
| apache-2.0 | 25414af2f2be7ed21d0a2f950881adbe | 38.179775 | 104 | 0.746487 | 4.116883 | false | false | false | false |
takke/cpustats | app/src/main/java/jp/takke/cpustats/C.kt | 1 | 1044 | package jp.takke.cpustats
object C {
const val LOG_NAME = "CpuStats"
// Preference keys
const val PREF_KEY_START_ON_BOOT = "StartOnBoot"
const val PREF_KEY_UPDATE_INTERVAL_SEC = "UpdateIntervalSec"
const val PREF_DEFAULT_UPDATE_INTERVAL_SEC = 5
const val PREF_KEY_SHOW_FREQUENCY_NOTIFICATION = "ShowFrequencyNotification"
const val PREF_KEY_SHOW_USAGE_NOTIFICATION = "ShowUsageNotification"
// 初期Alarmの遅延時間[ms]
const val ALARM_STARTUP_DELAY_MSEC = 1000
// Service維持のためのAlarmの更新間隔[ms]
const val ALARM_INTERVAL_MSEC = 60 * 1000
// CPU使用率通知のアイコンモード
const val PREF_KEY_CORE_DISTRIBUTION_MODE = "CoreDistributionMode"
const val CORE_DISTRIBUTION_MODE_2ICONS = 0 // 最大2アイコン(デフォルト)
const val CORE_DISTRIBUTION_MODE_1ICON_UNSORTED = 1 // 1アイコン+非ソート
const val CORE_DISTRIBUTION_MODE_1ICON_SORTED = 2 // 1アイコン+ソート
const val READ_BUFFER_SIZE = 1024
}
| apache-2.0 | 2ce226c75184ca9abb74433a27a1ca0d | 31.068966 | 80 | 0.706452 | 3.152542 | false | false | false | false |
zdary/intellij-community | plugins/ide-features-trainer/src/training/learn/lesson/general/navigation/DeclarationAndUsagesLesson.kt | 1 | 5346 | // 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 training.learn.lesson.general.navigation
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.openapi.actionSystem.impl.ActionMenuItem
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.impl.content.BaseLabel
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.ui.UIBundle
import com.intellij.ui.table.JBTable
import training.dsl.LessonContext
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.dsl.TaskRuntimeContext
import training.dsl.checkToolWindowState
import training.dsl.closeAllFindTabs
import training.learn.LearnBundle
import training.learn.LessonsBundle
import training.learn.course.KLesson
abstract class DeclarationAndUsagesLesson
: KLesson("Declaration and usages", LessonsBundle.message("declaration.and.usages.lesson.name")) {
abstract fun LessonContext.setInitialPosition()
abstract override val existedFile: String
override val lessonContent: LessonContext.() -> Unit
get() = {
setInitialPosition()
prepareRuntimeTask {
val focusManager = IdeFocusManager.getInstance(project)
if (focusManager.focusOwner != editor.contentComponent) {
focusManager.requestFocus(editor.contentComponent, true)
}
}
task("GotoDeclaration") {
text(LessonsBundle.message("declaration.and.usages.jump.to.declaration", action(it)))
trigger(it, { state() }) { before, _ ->
before != null && !isInsidePsi(before.target.navigationElement, before.position)
}
restoreIfModifiedOrMoved()
test { actions(it) }
}
task("GotoDeclaration") {
text(LessonsBundle.message("declaration.and.usages.show.usages", action(it)))
trigger(it, { state() }) l@{ before, now ->
if (before == null || now == null) {
return@l false
}
val navigationElement = before.target.navigationElement
return@l navigationElement == now.target.navigationElement &&
isInsidePsi(navigationElement, before.position) &&
!isInsidePsi(navigationElement, now.position)
}
restoreIfModifiedOrMoved()
test {
actions(it)
ideFrame {
waitComponent(JBTable::class.java, "ShowUsagesTable")
invokeActionViaShortcut("ENTER")
}
}
}
task("FindUsages") {
before {
closeAllFindTabs()
}
text(LessonsBundle.message("declaration.and.usages.find.usages", action(it)))
triggerByUiComponentAndHighlight { ui: BaseLabel ->
ui.text?.contains(LearnBundle.message("usages.tab.name")) ?: false
}
restoreIfModifiedOrMoved()
test {
actions(it)
}
}
val pinTabText = UIBundle.message("tabbed.pane.pin.tab.action.name")
task {
test {
ideFrame {
previous.ui?.let { usagesTab -> jComponent(usagesTab).rightClick() }
}
}
triggerByUiComponentAndHighlight(highlightInside = false) { ui: ActionMenuItem ->
ui.text?.contains(pinTabText) ?: false
}
restoreByUi()
text(LessonsBundle.message("declaration.and.usages.pin.motivation", strong(UIBundle.message("tool.window.name.find"))))
text(LessonsBundle.message("declaration.and.usages.right.click.tab", strong(LearnBundle.message("usages.tab.name"))))
}
task("PinToolwindowTab") {
trigger(it)
restoreByUi()
text(LessonsBundle.message("declaration.and.usages.select.pin.item", strong(pinTabText)))
test {
ideFrame {
jComponent(previous.ui!!).click()
}
}
}
task("HideActiveWindow") {
text(LessonsBundle.message("declaration.and.usages.hide.view", action(it)))
checkToolWindowState("Find", false)
test { actions(it) }
}
actionTask("ActivateFindToolWindow") {
LessonsBundle.message("declaration.and.usages.open.find.view",
action(it), strong(UIBundle.message("tool.window.name.find")))
}
}
private fun TaskRuntimeContext.state(): MyInfo? {
val flags = TargetElementUtil.ELEMENT_NAME_ACCEPTED or TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED
val currentEditor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null
val target = TargetElementUtil.findTargetElement(currentEditor, flags) ?: return null
val file = PsiDocumentManager.getInstance(project).getPsiFile(currentEditor.document) ?: return null
val position = MyPosition(file,
currentEditor.caretModel.offset)
return MyInfo(target, position)
}
private fun isInsidePsi(psi: PsiElement, position: MyPosition): Boolean {
return psi.containingFile == position.file && psi.textRange.contains(position.offset)
}
private data class MyInfo(val target: PsiElement, val position: MyPosition)
private data class MyPosition(val file: PsiFile, val offset: Int)
}
| apache-2.0 | 596937bab03bfbf08057b15ea75b7c96 | 36.125 | 140 | 0.676019 | 4.803235 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/main/kotlin/com/vrem/wifianalyzer/MainReload.kt | 1 | 2531 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer
import com.vrem.wifianalyzer.settings.Settings
import com.vrem.wifianalyzer.settings.ThemeStyle
import com.vrem.wifianalyzer.wifi.accesspoint.ConnectionViewType
import java.util.*
class MainReload(settings: Settings) {
var themeStyle: ThemeStyle
private set
var connectionViewType: ConnectionViewType
private set
var languageLocale: Locale
private set
fun shouldReload(settings: Settings): Boolean =
themeChanged(settings) || connectionViewTypeChanged(settings) || languageChanged(settings)
private fun connectionViewTypeChanged(settings: Settings): Boolean {
val currentConnectionViewType = settings.connectionViewType()
val connectionViewTypeChanged = connectionViewType != currentConnectionViewType
if (connectionViewTypeChanged) {
connectionViewType = currentConnectionViewType
}
return connectionViewTypeChanged
}
private fun themeChanged(settings: Settings): Boolean {
val settingThemeStyle = settings.themeStyle()
val themeChanged = themeStyle != settingThemeStyle
if (themeChanged) {
themeStyle = settingThemeStyle
}
return themeChanged
}
private fun languageChanged(settings: Settings): Boolean {
val settingLanguageLocale = settings.languageLocale()
val languageLocaleChanged = languageLocale != settingLanguageLocale
if (languageLocaleChanged) {
languageLocale = settingLanguageLocale
}
return languageLocaleChanged
}
init {
themeStyle = settings.themeStyle()
connectionViewType = settings.connectionViewType()
languageLocale = settings.languageLocale()
}
} | gpl-3.0 | 543c0cefd6225300e2e987a7e715b665 | 36.235294 | 102 | 0.723034 | 5.133874 | false | false | false | false |
JuliusKunze/kotlin-native | tools/kotlin-native-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/KonanCompileConfig.kt | 1 | 5481 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.gradle.plugin
import org.gradle.api.Task
import org.gradle.api.file.FileCollection
import org.gradle.api.internal.project.ProjectInternal
import org.gradle.internal.reflect.Instantiator
import org.jetbrains.kotlin.gradle.plugin.tasks.*
import org.jetbrains.kotlin.konan.target.KonanTarget
import java.io.File
abstract class KonanCompileConfig<T: KonanCompileTask>(name: String,
type: Class<T>,
project: ProjectInternal,
instantiator: Instantiator)
: KonanBuildingConfig<T>(name, type, project, instantiator), KonanCompileSpec {
protected abstract val typeForDescription: String
override fun generateTaskDescription(task: T) =
"Build the Kotlin/Native $typeForDescription '${task.name}' for target '${task.konanTarget}'"
override fun generateAggregateTaskDescription(task: Task) =
"Build the Kotlin/Native $typeForDescription '${task.name}' for all supported and declared targets"
override fun generateHostTaskDescription(task: Task, hostTarget: KonanTarget) =
"Build the Kotlin/Native $typeForDescription '${task.name}' for current host"
override fun srcDir(dir: Any) = forEach { it.srcDir(dir) }
override fun srcFiles(vararg files: Any) = forEach { it.srcFiles(*files) }
override fun srcFiles(files: Collection<Any>) = forEach { it.srcFiles(files) }
override fun nativeLibrary(lib: Any) = forEach { it.nativeLibrary(lib) }
override fun nativeLibraries(vararg libs: Any) = forEach { it.nativeLibraries(*libs) }
override fun nativeLibraries(libs: FileCollection) = forEach { it.nativeLibraries(libs) }
override fun linkerOpts(values: List<String>) = forEach { it.linkerOpts(values) }
override fun linkerOpts(vararg values: String) = forEach { it.linkerOpts(*values) }
override fun enableDebug(flag: Boolean) = forEach { it.enableDebug(flag) }
override fun noStdLib(flag: Boolean) = forEach { it.noStdLib(flag) }
override fun noMain(flag: Boolean) = forEach { it.noMain(flag) }
override fun enableOptimizations(flag: Boolean) = forEach { it.enableOptimizations(flag) }
override fun enableAssertions(flag: Boolean) = forEach { it.enableAssertions(flag) }
override fun entryPoint(entryPoint: String) = forEach { it.entryPoint(entryPoint) }
override fun measureTime(flag: Boolean) = forEach { it.measureTime(flag) }
}
open class KonanProgram(name: String, project: ProjectInternal, instantiator: Instantiator)
: KonanCompileConfig<KonanCompileProgramTask>(name, KonanCompileProgramTask::class.java, project, instantiator) {
override val typeForDescription: String
get() = "executable"
override val defaultBaseDir: File
get() = project.konanBinBaseDir
}
open class KonanDynamic(name: String, project: ProjectInternal, instantiator: Instantiator)
: KonanCompileConfig<KonanCompileDynamicTask>(name, KonanCompileDynamicTask::class.java, project, instantiator) {
override val typeForDescription: String
get() = "dynamic library"
override val defaultBaseDir: File
get() = project.konanBinBaseDir
}
open class KonanFramework(name: String, project: ProjectInternal, instantiator: Instantiator)
: KonanCompileConfig<KonanCompileFrameworkTask>(name, KonanCompileFrameworkTask::class.java, project, instantiator) {
override val typeForDescription: String
get() = "framework"
override val defaultBaseDir: File
get() = project.konanBinBaseDir
}
open class KonanLibrary(name: String, project: ProjectInternal, instantiator: Instantiator)
: KonanCompileConfig<KonanCompileLibraryTask>(name, KonanCompileLibraryTask::class.java, project, instantiator) {
override val typeForDescription: String
get() = "library"
override val defaultBaseDir: File
get() = project.konanLibsBaseDir
}
open class KonanBitcode(name: String, project: ProjectInternal, instantiator: Instantiator)
: KonanCompileConfig<KonanCompileBitcodeTask>(name, KonanCompileBitcodeTask::class.java, project, instantiator) {
override val typeForDescription: String
get() = "bitcode"
override fun generateTaskDescription(task: KonanCompileBitcodeTask) =
"Generates bitcode for the artifact '${task.name}' and target '${task.konanTarget}'"
override fun generateAggregateTaskDescription(task: Task) =
"Generates bitcode for the artifact '${task.name}' for all supported and declared targets'"
override fun generateHostTaskDescription(task: Task, hostTarget: KonanTarget) =
"Generates bitcode for the artifact '${task.name}' for current host"
override val defaultBaseDir: File
get() = project.konanBitcodeBaseDir
} | apache-2.0 | 36738bee864733c279546644ed7e931f | 43.934426 | 121 | 0.722496 | 4.761946 | false | true | false | false |
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/ndrei/teslacorelib/compatibility/ItemStackUtil.kt | 1 | 4557 | package net.ndrei.teslacorelib.compatibility
import com.google.common.collect.Lists
import net.minecraft.item.ItemStack
import net.minecraftforge.items.IItemHandler
import net.minecraftforge.items.ItemHandlerHelper
import net.ndrei.teslacorelib.utils.copyWithSize
import net.ndrei.teslacorelib.utils.equalsIgnoreSize
/**
* Created by CF on 2017-06-28.
*/
@Suppress("unused")
object ItemStackUtil {
@Deprecated("This was for the stupid 1.10 / 1.11 compatibility. Stop using it!", ReplaceWith("ItemStack::isEmpty"))
fun isEmpty(stack: ItemStack?): Boolean = (stack == null) || stack.isEmpty || (stack.count == 0)
@Deprecated("This was for the stupid 1.10 / 1.11 compatibility. Stop using it!", ReplaceWith("ItemStack::grow"))
fun grow(stack: ItemStack, amount: Int) = stack.grow(amount)
@Deprecated("This was for the stupid 1.10 / 1.11 compatibility. Stop using it!", ReplaceWith("ItemStack::shrink"))
fun shrink(stack: ItemStack, amount: Int) = stack.shrink(amount)
@Deprecated("This was for the stupid 1.10 / 1.11 compatibility. Stop using it!", ReplaceWith("ItemStack::count"))
fun getSize(stack: ItemStack): Int = if (ItemStackUtil.isEmpty(stack)) 0 else stack.count
@Deprecated("This was for the stupid 1.10 / 1.11 compatibility. Stop using it!", ReplaceWith("ItemStack::count"))
fun setSize(stack: ItemStack, size: Int) { stack.count = size; }
fun copyWithSize(stack: ItemStack, size: Int): ItemStack {
val result = stack.copy()
result.count = size
return result
}
@Deprecated("This was for the stupid 1.10 / 1.11 compatibility. Stop using it!", ReplaceWith("ItemStack.EMPTY"))
val emptyStack: ItemStack
get() = ItemStack.EMPTY
fun getCombinedInventory(handler: IItemHandler): List<ItemStack> {
val list = Lists.newArrayList<ItemStack>()
for (i in 0 until handler.slots) {
val stack = handler.getStackInSlot(i)
if (stack.isEmpty) {
continue
}
val match: ItemStack? = list.firstOrNull { it.equalsIgnoreSize(stack) }
if (match == null) {
list.add(stack.copy())
} else {
match.count = match.count + stack.count
}
}
return list
}
fun extractFromCombinedInventory(handler: IItemHandler, stack: ItemStack, amount: Int, simulate: Boolean = false): Int {
if (stack.isEmpty) {
return 0
}
val result = stack.copyWithSize(amount)
var taken = 0
for (i in 0 until handler.slots) {
val temp = handler.getStackInSlot(i)
if (temp.isEmpty || !temp.equalsIgnoreSize(stack)) {
continue
}
val takenStack = handler.extractItem(i, Math.min(result.count, temp.count), simulate)
taken += takenStack.count
result.shrink(takenStack.count)
if (result.isEmpty) {
break
}
}
return taken
}
fun insertItemInExistingStacks(dest: IItemHandler?, stack: ItemStack, simulate: Boolean): ItemStack {
var remaining = stack
if ((dest == null) || remaining.isEmpty)
return ItemStack.EMPTY
for (i in 0 until dest.slots) {
if (dest.getStackInSlot(i).isEmpty) {
continue
}
remaining = dest.insertItem(i, remaining, simulate)
if (remaining.isEmpty) {
return ItemStack.EMPTY
}
}
return remaining
}
fun insertItems(dest: IItemHandler, stack: ItemStack, simulate: Boolean): ItemStack {
val remaining = ItemStackUtil.insertItemInExistingStacks(dest, stack, simulate)
return if (remaining.isEmpty) ItemStack.EMPTY
else ItemHandlerHelper.insertItem(dest, remaining, simulate)
}
fun areEqualIgnoreSize(a: ItemStack, b: ItemStack) =
if (a.isEmpty && b.isEmpty)
true
else if (a.isEmpty != b.isEmpty)
false
else {
val x = ItemStackUtil.copyWithSize(a, b.count)
ItemStack.areItemStacksEqualUsingNBTShareTag(x, b)
}
fun areEqualIgnoreSizeAndNBT(a: ItemStack, b: ItemStack) =
if (a.isEmpty && b.isEmpty)
true
else if (a.isEmpty != b.isEmpty)
false
else {
val x = ItemStackUtil.copyWithSize(a, b.count)
ItemStack.areItemStacksEqual(x, b)
}
}
| mit | 845dea7a5bd4d1428d818fb9d26890e4 | 35.456 | 124 | 0.613123 | 4.437196 | false | false | false | false |
JoachimR/Bible2net | app/src/main/java/de/reiss/bible2net/theword/main/content/TheWordViewModel.kt | 1 | 1717 | package de.reiss.bible2net.theword.main.content
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import de.reiss.bible2net.theword.architecture.AsyncLoad
import de.reiss.bible2net.theword.architecture.AsyncLoadStatus
import de.reiss.bible2net.theword.model.Note
import de.reiss.bible2net.theword.model.TheWord
import java.util.Date
open class TheWordViewModel(private val repository: TheWordRepository) : ViewModel() {
private val theWordLiveData: MutableLiveData<AsyncLoad<TheWord>> = MutableLiveData()
private val noteLiveData: MutableLiveData<AsyncLoad<Note>> = MutableLiveData()
open fun theWordLiveData() = theWordLiveData
open fun noteLiveData() = noteLiveData
open fun loadTheWord(date: Date) {
repository.getTheWordFor(date, theWordLiveData())
}
open fun loadNote(date: Date) {
repository.getNoteFor(date, noteLiveData())
}
fun theWord() = theWordLiveData().value?.data
fun note() = noteLiveData().value?.data
fun isLoadingTheWord() = theWordLiveData().value?.loadStatus == AsyncLoadStatus.LOADING
fun isErrorForTheWord() = theWordLiveData().value?.loadStatus == AsyncLoadStatus.ERROR
fun isSuccessForTheWord() = theWordLiveData().value?.loadStatus == AsyncLoadStatus.SUCCESS
fun isLoadingNote() = noteLiveData().value?.loadStatus == AsyncLoadStatus.LOADING
class Factory(private val repository: TheWordRepository) :
ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return TheWordViewModel(repository) as T
}
}
}
| gpl-3.0 | 1b03f153f7ffa55c7d751e59bdab90b8 | 36.326087 | 94 | 0.746651 | 4.678474 | false | false | false | false |
smmribeiro/intellij-community | plugins/gradle/java/src/service/resolve/GradleGroovyProperty.kt | 2 | 2336 | // 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 org.jetbrains.plugins.gradle.service.resolve
import com.intellij.codeInsight.javadoc.JavaDocInfoGeneratorFactory
import com.intellij.icons.AllIcons
import com.intellij.ide.presentation.Presentation
import com.intellij.openapi.util.Key
import com.intellij.psi.OriginInfoAwareElement
import com.intellij.psi.PsiElement
import com.intellij.util.lazyPub
import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings.GradleProp
import org.jetbrains.plugins.gradle.util.GradleDocumentationBundle
import org.jetbrains.plugins.groovy.dsl.holders.NonCodeMembersHolder
import org.jetbrains.plugins.groovy.lang.resolve.api.LazyTypeProperty
import javax.swing.Icon
@Presentation(typeName = "Gradle Property")
class GradleGroovyProperty(
private val myProperty: GradleProp,
context: PsiElement
) : LazyTypeProperty(myProperty.name, myProperty.typeFqn, context),
OriginInfoAwareElement {
override fun getIcon(flags: Int): Icon? = AllIcons.Nodes.Property
override fun getOriginInfo(): String? = "via ext"
private val doc by lazyPub {
val value = myProperty.value
val result = StringBuilder()
result.append("<PRE>")
JavaDocInfoGeneratorFactory.create(context.project, null).generateType(result, propertyType, context, true)
result.append(" " + myProperty.name)
val hasInitializer = !value.isNullOrBlank()
if (hasInitializer) {
result.append(" = ")
val longString = value.toString().length > 100
if (longString) {
result.append("<blockquote>")
}
result.append(value)
if (longString) {
result.append("</blockquote>")
}
}
result.append("</PRE>")
if (hasInitializer) {
result.append("<br><b>" + GradleDocumentationBundle.message("gradle.documentation.groovy.initial.value.got.during.last.import") + "</b>")
}
result.toString()
}
override fun <T : Any?> getUserData(key: Key<T>): T? {
if (key == NonCodeMembersHolder.DOCUMENTATION) {
@Suppress("UNCHECKED_CAST")
return doc as T
}
return super.getUserData(key)
}
override fun toString(): String = GradleDocumentationBundle.message("gradle.documentation.groovy.gradle.property", name)
}
| apache-2.0 | 3e1cada273733e141c002e9db9038342 | 36.677419 | 143 | 0.739298 | 4.171429 | false | false | false | false |
smmribeiro/intellij-community | platform/configuration-store-impl/src/schemeManager/SchemeManagerBase.kt | 7 | 1875 | // 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 com.intellij.configurationStore.schemeManager
import com.intellij.openapi.options.Scheme
import com.intellij.openapi.options.SchemeManager
import com.intellij.openapi.options.SchemeProcessor
abstract class SchemeManagerBase<T: Scheme, in MUTABLE_SCHEME : T>(internal val processor: SchemeProcessor<T, MUTABLE_SCHEME>) : SchemeManager<T>() {
/**
* Schemes can be lazy loaded, so, client should be able to set current scheme by name, not only by instance.
*/
@Volatile
internal var currentPendingSchemeName: String? = null
override var activeScheme: T? = null
internal set
override var currentSchemeName: String?
get() = activeScheme?.let { processor.getSchemeKey(it) } ?: currentPendingSchemeName
set(schemeName) = setCurrentSchemeName(schemeName, true)
internal fun processPendingCurrentSchemeName(newScheme: T): Boolean {
if (processor.getSchemeKey(newScheme) == currentPendingSchemeName) {
setCurrent(newScheme, false)
return true
}
return false
}
override fun setCurrent(scheme: T?, notify: Boolean, processChangeSynchronously: Boolean) {
currentPendingSchemeName = null
val oldCurrent = activeScheme
activeScheme = scheme
if (notify && oldCurrent !== scheme) {
processor.onCurrentSchemeSwitched(oldCurrent, scheme, processChangeSynchronously)
}
}
override fun setCurrentSchemeName(schemeName: String?, notify: Boolean) {
currentPendingSchemeName = schemeName
val scheme = schemeName?.let { findSchemeByName(it) }
// don't set current scheme if no scheme by name - pending resolution (see currentSchemeName field comment)
if (scheme != null || schemeName == null) {
setCurrent(scheme, notify)
}
}
} | apache-2.0 | 4910ee87cc49271608a29f5ada394e05 | 37.285714 | 149 | 0.741867 | 4.573171 | false | false | false | false |
alibaba/p3c | idea-plugin/p3c-common/src/main/kotlin/com/alibaba/smartfox/idea/common/util/PluginVersions.kt | 2 | 1857 | /*
* Copyright 1999-2017 Alibaba Group.
*
* 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.alibaba.smartfox.idea.common.util
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.cl.PluginClassLoader
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.extensions.PluginId
/**
* @author caikang
*/
object PluginVersions {
val baseVersion141 = 141
val baseVersion143 = 143
val baseVersion145 = 145
val baseVersion162 = 162
val baseVersion163 = 163
val baseVersion171 = 171
val pluginId: PluginId = (javaClass.classLoader as PluginClassLoader).pluginId
val pluginDescriptor: IdeaPluginDescriptor = PluginManager.getPlugin(pluginId)!!
/**
* 获取当前安装的 plugin版本
*/
val pluginVersion: String
get() = pluginDescriptor.version
/**
* 获取当前使用的IDE版本
*/
val ideVersion: String
get() {
val applicationInfo = ApplicationInfo.getInstance()
return applicationInfo.fullVersion + "_" + applicationInfo.build
}
val baseVersion: Int
get() {
val applicationInfo = ApplicationInfo.getInstance()
return applicationInfo.build.baselineVersion
}
}
| apache-2.0 | 29fd267be0c567ba242e666fa97e4d08 | 29.864407 | 84 | 0.711148 | 4.72987 | false | false | false | false |
JetBrains/kotlin-native | runtime/src/main/kotlin/kotlin/collections/HashMap.kt | 1 | 23754 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package kotlin.collections
import kotlin.native.concurrent.isFrozen
actual class HashMap<K, V> private constructor(
private var keysArray: Array<K>,
private var valuesArray: Array<V>?, // allocated only when actually used, always null in pure HashSet
private var presenceArray: IntArray,
private var hashArray: IntArray,
private var maxProbeDistance: Int,
private var length: Int
) : MutableMap<K, V> {
private var hashShift: Int = computeShift(hashSize)
private var _size: Int = 0
override actual val size: Int
get() = _size
private var keysView: HashMapKeys<K>? = null
private var valuesView: HashMapValues<V>? = null
private var entriesView: HashMapEntrySet<K, V>? = null
private var isReadOnly: Boolean = false
// ---------------------------- functions ----------------------------
actual constructor() : this(INITIAL_CAPACITY)
actual constructor(initialCapacity: Int) : this(
arrayOfUninitializedElements(initialCapacity),
null,
IntArray(initialCapacity),
IntArray(computeHashSize(initialCapacity)),
INITIAL_MAX_PROBE_DISTANCE,
0)
actual constructor(original: Map<out K, V>) : this(original.size) {
putAll(original)
}
// This implementation doesn't use a loadFactor, this constructor is used for compatibility with common stdlib
actual constructor(initialCapacity: Int, loadFactor: Float) : this(initialCapacity)
@PublishedApi
internal fun build(): Map<K, V> {
checkIsMutable()
isReadOnly = true
return this
}
override actual fun isEmpty(): Boolean = _size == 0
override actual fun containsKey(key: K): Boolean = findKey(key) >= 0
override actual fun containsValue(value: V): Boolean = findValue(value) >= 0
override actual operator fun get(key: K): V? {
val index = findKey(key)
if (index < 0) return null
return valuesArray!![index]
}
override actual fun put(key: K, value: V): V? {
checkIsMutable()
val index = addKey(key)
val valuesArray = allocateValuesArray()
if (index < 0) {
val oldValue = valuesArray[-index - 1]
valuesArray[-index - 1] = value
return oldValue
} else {
valuesArray[index] = value
return null
}
}
override actual fun putAll(from: Map<out K, V>) {
checkIsMutable()
putAllEntries(from.entries)
}
override actual fun remove(key: K): V? {
val index = removeKey(key) // mutability gets checked here
if (index < 0) return null
val valuesArray = valuesArray!!
val oldValue = valuesArray[index]
valuesArray.resetAt(index)
return oldValue
}
override actual fun clear() {
checkIsMutable()
// O(length) implementation for hashArray cleanup
for (i in 0..length - 1) {
val hash = presenceArray[i]
if (hash >= 0) {
hashArray[hash] = 0
presenceArray[i] = TOMBSTONE
}
}
keysArray.resetRange(0, length)
valuesArray?.resetRange(0, length)
_size = 0
length = 0
}
override actual val keys: MutableSet<K> get() {
val cur = keysView
return if (cur == null) {
val new = HashMapKeys(this)
if (!isFrozen)
keysView = new
new
} else cur
}
override actual val values: MutableCollection<V> get() {
val cur = valuesView
return if (cur == null) {
val new = HashMapValues(this)
if (!isFrozen)
valuesView = new
new
} else cur
}
override actual val entries: MutableSet<MutableMap.MutableEntry<K, V>> get() {
val cur = entriesView
return if (cur == null) {
val new = HashMapEntrySet(this)
if (!isFrozen)
entriesView = new
return new
} else cur
}
override fun equals(other: Any?): Boolean {
return other === this ||
(other is Map<*, *>) &&
contentEquals(other)
}
override fun hashCode(): Int {
var result = 0
val it = entriesIterator()
while (it.hasNext()) {
result += it.nextHashCode()
}
return result
}
override fun toString(): String {
val sb = StringBuilder(2 + _size * 3)
sb.append("{")
var i = 0
val it = entriesIterator()
while (it.hasNext()) {
if (i > 0) sb.append(", ")
it.nextAppendString(sb)
i++
}
sb.append("}")
return sb.toString()
}
// ---------------------------- private ----------------------------
private val capacity: Int get() = keysArray.size
private val hashSize: Int get() = hashArray.size
internal fun checkIsMutable() {
if (isReadOnly) throw UnsupportedOperationException()
}
private fun ensureExtraCapacity(n: Int) {
ensureCapacity(length + n)
}
private fun ensureCapacity(capacity: Int) {
if (capacity > this.capacity) {
var newSize = this.capacity * 3 / 2
if (capacity > newSize) newSize = capacity
keysArray = keysArray.copyOfUninitializedElements(newSize)
valuesArray = valuesArray?.copyOfUninitializedElements(newSize)
presenceArray = presenceArray.copyOf(newSize)
val newHashSize = computeHashSize(newSize)
if (newHashSize > hashSize) rehash(newHashSize)
} else if (length + capacity - _size > this.capacity) {
rehash(hashSize)
}
}
private fun allocateValuesArray(): Array<V> {
val curValuesArray = valuesArray
if (curValuesArray != null) return curValuesArray
val newValuesArray = arrayOfUninitializedElements<V>(capacity)
valuesArray = newValuesArray
return newValuesArray
}
// Null-check for escaping extra boxing for non-nullable keys.
private fun hash(key: K) = if (key == null) 0 else (key.hashCode() * MAGIC) ushr hashShift
private fun compact() {
var i = 0
var j = 0
val valuesArray = valuesArray
while (i < length) {
if (presenceArray[i] >= 0) {
keysArray[j] = keysArray[i]
if (valuesArray != null) valuesArray[j] = valuesArray[i]
j++
}
i++
}
keysArray.resetRange(j, length)
valuesArray?.resetRange(j, length)
length = j
//check(length == size) { "Internal invariant violated during compact: length=$length != size=$size" }
}
private fun rehash(newHashSize: Int) {
if (length > _size) compact()
if (newHashSize != hashSize) {
hashArray = IntArray(newHashSize)
hashShift = computeShift(newHashSize)
} else {
hashArray.fill(0, 0, hashSize)
}
var i = 0
while (i < length) {
if (!putRehash(i++)) {
throw IllegalStateException("This cannot happen with fixed magic multiplier and grow-only hash array. " +
"Have object hashCodes changed?")
}
}
}
private fun putRehash(i: Int): Boolean {
var hash = hash(keysArray[i])
var probesLeft = maxProbeDistance
while (true) {
val index = hashArray[hash]
if (index == 0) {
hashArray[hash] = i + 1
presenceArray[i] = hash
return true
}
if (--probesLeft < 0) return false
if (hash-- == 0) hash = hashSize - 1
}
}
private fun findKey(key: K): Int {
var hash = hash(key)
var probesLeft = maxProbeDistance
while (true) {
val index = hashArray[hash]
if (index == 0) return TOMBSTONE
if (index > 0 && keysArray[index - 1] == key) return index - 1
if (--probesLeft < 0) return TOMBSTONE
if (hash-- == 0) hash = hashSize - 1
}
}
private fun findValue(value: V): Int {
var i = length
while (--i >= 0) {
if (presenceArray[i] >= 0 && valuesArray!![i] == value)
return i
}
return TOMBSTONE
}
internal fun addKey(key: K): Int {
checkIsMutable()
retry@ while (true) {
var hash = hash(key)
// put is allowed to grow maxProbeDistance with some limits (resize hash on reaching limits)
val tentativeMaxProbeDistance = (maxProbeDistance * 2).coerceAtMost(hashSize / 2)
var probeDistance = 0
while (true) {
val index = hashArray[hash]
if (index <= 0) { // claim or reuse hash slot
if (length >= capacity) {
ensureExtraCapacity(1)
continue@retry
}
val putIndex = length++
keysArray[putIndex] = key
presenceArray[putIndex] = hash
hashArray[hash] = putIndex + 1
_size++
if (probeDistance > maxProbeDistance) maxProbeDistance = probeDistance
return putIndex
}
if (keysArray[index - 1] == key) {
return -index
}
if (++probeDistance > tentativeMaxProbeDistance) {
rehash(hashSize * 2) // cannot find room even with extra "tentativeMaxProbeDistance" -- grow hash
continue@retry
}
if (hash-- == 0) hash = hashSize - 1
}
}
}
internal fun removeKey(key: K): Int {
checkIsMutable()
val index = findKey(key)
if (index < 0) return TOMBSTONE
removeKeyAt(index)
return index
}
private fun removeKeyAt(index: Int) {
keysArray.resetAt(index)
removeHashAt(presenceArray[index])
presenceArray[index] = TOMBSTONE
_size--
}
private fun removeHashAt(removedHash: Int) {
var hash = removedHash
var hole = removedHash // will try to patch the hole in hash array
var probeDistance = 0
var patchAttemptsLeft = (maxProbeDistance * 2).coerceAtMost(hashSize / 2) // don't spend too much effort
while (true) {
if (hash-- == 0) hash = hashSize - 1
if (++probeDistance > maxProbeDistance) {
// too far away -- can release the hole, bad case will not happen
hashArray[hole] = 0
return
}
val index = hashArray[hash]
if (index == 0) {
// end of chain -- can release the hole, bad case will not happen
hashArray[hole] = 0
return
}
if (index < 0) {
// TOMBSTONE FOUND
// - <--- [ TS ] ------ [hole] ---> +
// \------------/
// probeDistance
// move tombstone into the hole
hashArray[hole] = TOMBSTONE
hole = hash
probeDistance = 0
} else {
val otherHash = hash(keysArray[index - 1])
// Bad case:
// - <--- [hash] ------ [hole] ------ [otherHash] ---> +
// \------------/
// probeDistance
if ((otherHash - hash) and (hashSize - 1) >= probeDistance) {
// move otherHash into the hole, move the hole
hashArray[hole] = index
presenceArray[index - 1] = hole
hole = hash
probeDistance = 0
}
}
// check how long we're patching holes
if (--patchAttemptsLeft < 0) {
// just place tombstone into the hole
hashArray[hole] = TOMBSTONE
return
}
}
}
internal fun containsEntry(entry: Map.Entry<K, V>): Boolean {
val index = findKey(entry.key)
if (index < 0) return false
return valuesArray!![index] == entry.value
}
internal fun getEntry(entry: Map.Entry<K, V>): MutableMap.MutableEntry<K, V>? {
val index = findKey(entry.key)
return if (index < 0 || valuesArray!![index] != entry.value) {
null
} else {
EntryRef(this, index)
}
}
internal fun getKey(key: K): K? {
val index = findKey(key)
return if (index >= 0) {
keysArray[index]!!
} else {
null
}
}
private fun contentEquals(other: Map<*, *>): Boolean = _size == other.size && containsAllEntries(other.entries)
internal fun containsAllEntries(m: Collection<*>): Boolean {
val it = m.iterator()
while (it.hasNext()) {
val entry = it.next()
try {
@Suppress("UNCHECKED_CAST") // todo: get rid of unchecked cast here somehow
if (entry == null || !containsEntry(entry as Map.Entry<K, V>))
return false
} catch (e: ClassCastException) {
return false
}
}
return true
}
private fun putEntry(entry: Map.Entry<K, V>): Boolean {
val index = addKey(entry.key)
val valuesArray = allocateValuesArray()
if (index >= 0) {
valuesArray[index] = entry.value
return true
}
val oldValue = valuesArray[-index - 1]
if (entry.value != oldValue) {
valuesArray[-index - 1] = entry.value
return true
}
return false
}
private fun putAllEntries(from: Collection<Map.Entry<K, V>>): Boolean {
if (from.isEmpty()) return false
ensureExtraCapacity(from.size)
val it = from.iterator()
var updated = false
while (it.hasNext()) {
if (putEntry(it.next()))
updated = true
}
return updated
}
internal fun removeEntry(entry: Map.Entry<K, V>): Boolean {
checkIsMutable()
val index = findKey(entry.key)
if (index < 0) return false
if (valuesArray!![index] != entry.value) return false
removeKeyAt(index)
return true
}
internal fun removeValue(element: V): Boolean {
checkIsMutable()
val index = findValue(element)
if (index < 0) return false
removeKeyAt(index)
return true
}
internal fun keysIterator() = KeysItr(this)
internal fun valuesIterator() = ValuesItr(this)
internal fun entriesIterator() = EntriesItr(this)
@kotlin.native.internal.CanBePrecreated
private companion object {
private const val MAGIC = -1640531527 // 2654435769L.toInt(), golden ratio
private const val INITIAL_CAPACITY = 8
private const val INITIAL_MAX_PROBE_DISTANCE = 2
private const val TOMBSTONE = -1
@OptIn(ExperimentalStdlibApi::class)
private fun computeHashSize(capacity: Int): Int = (capacity.coerceAtLeast(1) * 3).takeHighestOneBit()
@OptIn(ExperimentalStdlibApi::class)
private fun computeShift(hashSize: Int): Int = hashSize.countLeadingZeroBits() + 1
}
internal open class Itr<K, V>(
internal val map: HashMap<K, V>
) {
internal var index = 0
internal var lastIndex: Int = -1
init {
initNext()
}
internal fun initNext() {
while (index < map.length && map.presenceArray[index] < 0)
index++
}
fun hasNext(): Boolean = index < map.length
fun remove() {
map.checkIsMutable()
map.removeKeyAt(lastIndex)
lastIndex = -1
}
}
internal class KeysItr<K, V>(map: HashMap<K, V>) : Itr<K, V>(map), MutableIterator<K> {
override fun next(): K {
if (index >= map.length) throw NoSuchElementException()
lastIndex = index++
val result = map.keysArray[lastIndex]
initNext()
return result
}
}
internal class ValuesItr<K, V>(map: HashMap<K, V>) : Itr<K, V>(map), MutableIterator<V> {
override fun next(): V {
if (index >= map.length) throw NoSuchElementException()
lastIndex = index++
val result = map.valuesArray!![lastIndex]
initNext()
return result
}
}
internal class EntriesItr<K, V>(map: HashMap<K, V>) : Itr<K, V>(map),
MutableIterator<MutableMap.MutableEntry<K, V>> {
override fun next(): EntryRef<K, V> {
if (index >= map.length) throw NoSuchElementException()
lastIndex = index++
val result = EntryRef(map, lastIndex)
initNext()
return result
}
internal fun nextHashCode(): Int {
if (index >= map.length) throw NoSuchElementException()
lastIndex = index++
val result = map.keysArray[lastIndex].hashCode() xor map.valuesArray!![lastIndex].hashCode()
initNext()
return result
}
fun nextAppendString(sb: StringBuilder) {
if (index >= map.length) throw NoSuchElementException()
lastIndex = index++
val key = map.keysArray[lastIndex]
if (key == map) sb.append("(this Map)") else sb.append(key)
sb.append('=')
val value = map.valuesArray!![lastIndex]
if (value == map) sb.append("(this Map)") else sb.append(value)
initNext()
}
}
internal class EntryRef<K, V>(
private val map: HashMap<K, V>,
private val index: Int
) : MutableMap.MutableEntry<K, V> {
override val key: K
get() = map.keysArray[index]
override val value: V
get() = map.valuesArray!![index]
override fun setValue(newValue: V): V {
map.checkIsMutable()
val valuesArray = map.allocateValuesArray()
val oldValue = valuesArray[index]
valuesArray[index] = newValue
return oldValue
}
override fun equals(other: Any?): Boolean =
other is Map.Entry<*, *> &&
other.key == key &&
other.value == value
override fun hashCode(): Int = key.hashCode() xor value.hashCode()
override fun toString(): String = "$key=$value"
}
}
internal class HashMapKeys<E> internal constructor(
private val backing: HashMap<E, *>
) : MutableSet<E>, kotlin.native.internal.KonanSet<E>, AbstractMutableSet<E>() {
override val size: Int get() = backing.size
override fun isEmpty(): Boolean = backing.isEmpty()
override fun contains(element: E): Boolean = backing.containsKey(element)
override fun getElement(element: E): E? = backing.getKey(element)
override fun clear() = backing.clear()
override fun add(element: E): Boolean = throw UnsupportedOperationException()
override fun addAll(elements: Collection<E>): Boolean = throw UnsupportedOperationException()
override fun remove(element: E): Boolean = backing.removeKey(element) >= 0
override fun iterator(): MutableIterator<E> = backing.keysIterator()
override fun removeAll(elements: Collection<E>): Boolean {
backing.checkIsMutable()
return super.removeAll(elements)
}
override fun retainAll(elements: Collection<E>): Boolean {
backing.checkIsMutable()
return super.retainAll(elements)
}
}
internal class HashMapValues<V> internal constructor(
val backing: HashMap<*, V>
) : MutableCollection<V>, AbstractMutableCollection<V>() {
override val size: Int get() = backing.size
override fun isEmpty(): Boolean = backing.isEmpty()
override fun contains(element: V): Boolean = backing.containsValue(element)
override fun add(element: V): Boolean = throw UnsupportedOperationException()
override fun addAll(elements: Collection<V>): Boolean = throw UnsupportedOperationException()
override fun clear() = backing.clear()
override fun iterator(): MutableIterator<V> = backing.valuesIterator()
override fun remove(element: V): Boolean = backing.removeValue(element)
override fun removeAll(elements: Collection<V>): Boolean {
backing.checkIsMutable()
return super.removeAll(elements)
}
override fun retainAll(elements: Collection<V>): Boolean {
backing.checkIsMutable()
return super.retainAll(elements)
}
}
/**
* Note: intermediate class with [E] `: Map.Entry<K, V>` is required to support
* [contains] for values that are [Map.Entry] but not [MutableMap.MutableEntry],
* and probably same for other functions.
* This is important because an instance of this class can be used as a result of [Map.entries],
* which should support [contains] for [Map.Entry].
* For example, this happens when upcasting [MutableMap] to [Map].
*
* The compiler enables special type-safe barriers to methods like [contains], which has [UnsafeVariance].
* Changing type from [MutableMap.MutableEntry] to [E] makes the compiler generate barriers checking that
* argument `is` [E] (so technically `is` [Map.Entry]) instead of `is` [MutableMap.MutableEntry].
*
* See also [KT-42248](https://youtrack.jetbrains.com/issue/KT-42428).
*/
internal abstract class HashMapEntrySetBase<K, V, E : Map.Entry<K, V>> internal constructor(
val backing: HashMap<K, V>
) : MutableSet<E>, kotlin.native.internal.KonanSet<E>, AbstractMutableSet<E>() {
override val size: Int get() = backing.size
override fun isEmpty(): Boolean = backing.isEmpty()
override fun contains(element: E): Boolean = backing.containsEntry(element)
override fun getElement(element: E): E? = getEntry(element)
protected abstract fun getEntry(element: Map.Entry<K, V>): E?
override fun clear() = backing.clear()
override fun add(element: E): Boolean = throw UnsupportedOperationException()
override fun addAll(elements: Collection<E>): Boolean = throw UnsupportedOperationException()
override fun remove(element: E): Boolean = backing.removeEntry(element)
override fun containsAll(elements: Collection<E>): Boolean = backing.containsAllEntries(elements)
override fun removeAll(elements: Collection<E>): Boolean {
backing.checkIsMutable()
return super.removeAll(elements)
}
override fun retainAll(elements: Collection<E>): Boolean {
backing.checkIsMutable()
return super.retainAll(elements)
}
}
internal class HashMapEntrySet<K, V> internal constructor(
backing: HashMap<K, V>
) : HashMapEntrySetBase<K, V, MutableMap.MutableEntry<K, V>>(backing) {
override fun getEntry(element: Map.Entry<K, V>): MutableMap.MutableEntry<K, V>? = backing.getEntry(element)
override fun iterator(): MutableIterator<MutableMap.MutableEntry<K, V>> = backing.entriesIterator()
}
// This hash map keeps insertion order.
actual typealias LinkedHashMap<K, V> = HashMap<K, V> | apache-2.0 | 430f339dd245e814f1ed776bbc8506ee | 33.780381 | 121 | 0.566978 | 4.542742 | false | false | false | false |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/ui/filters/FilterChip.kt | 3 | 2449 | /*
* Copyright 2020 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
*
* 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.samples.apps.iosched.ui.filters
import android.graphics.Color
import com.google.samples.apps.iosched.R
import com.google.samples.apps.iosched.model.Tag
import com.google.samples.apps.iosched.model.filters.Filter
import com.google.samples.apps.iosched.model.filters.Filter.DateFilter
import com.google.samples.apps.iosched.model.filters.Filter.MyScheduleFilter
import com.google.samples.apps.iosched.model.filters.Filter.TagFilter
import com.google.samples.apps.iosched.shared.util.TimeUtils
/** Wrapper model for showing [Filter] as a chip in the UI. */
data class FilterChip(
val filter: Filter,
val isSelected: Boolean,
val categoryLabel: Int = 0,
val color: Int = Color.parseColor("#4768fd"), // @color/indigo
val selectedTextColor: Int = Color.WHITE,
val textResId: Int = 0,
val text: String = ""
)
fun Filter.asChip(isSelected: Boolean): FilterChip = when (this) {
is TagFilter -> FilterChip(
filter = this,
isSelected = isSelected,
color = tag.color,
text = tag.displayName,
selectedTextColor = tag.fontColor ?: Color.TRANSPARENT,
categoryLabel = tag.filterCategoryLabel()
)
is DateFilter -> FilterChip(
filter = this,
isSelected = isSelected,
textResId = TimeUtils.getShortLabelResForDay(day),
categoryLabel = R.string.category_heading_dates
)
MyScheduleFilter -> FilterChip(
filter = this,
isSelected = isSelected,
textResId = R.string.my_events,
categoryLabel = R.string.category_heading_dates
)
}
private fun Tag.filterCategoryLabel(): Int = when (this.category) {
Tag.CATEGORY_TYPE -> R.string.category_heading_types
Tag.CATEGORY_TOPIC -> R.string.category_heading_tracks
Tag.CATEGORY_LEVEL -> R.string.category_heading_levels
else -> 0
}
| apache-2.0 | 8df3da5120a13d4856d4d12a3637ae2c | 35.552239 | 76 | 0.713761 | 4.008183 | false | false | false | false |
JetBrains/intellij-community | plugins/git4idea/src/git4idea/checkin/GitSkipHooksCommitHandlerFactory.kt | 1 | 2922 | // 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 git4idea.checkin
import com.intellij.openapi.util.Key
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.changes.CommitContext
import com.intellij.openapi.vcs.changes.LocalChangeList
import com.intellij.openapi.vcs.checkin.CheckinChangeListSpecificComponent
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vcs.checkin.CheckinHandlerFactory
import com.intellij.openapi.vcs.ui.RefreshableOnComponent
import com.intellij.util.ui.JBUI
import com.intellij.vcs.commit.CommitSessionCollector
import com.intellij.vcs.commit.CommitSessionCounterUsagesCollector.CommitOption
import com.intellij.vcs.commit.commitProperty
import git4idea.GitVcs
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import javax.swing.JCheckBox
import javax.swing.JComponent
private val IS_SKIP_HOOKS_KEY = Key.create<Boolean>("Git.Commit.IsSkipHooks")
internal var CommitContext.isSkipHooks: Boolean by commitProperty(IS_SKIP_HOOKS_KEY)
class GitSkipHooksCommitHandlerFactory : CheckinHandlerFactory() {
override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler {
if (!panel.vcsIsAffected(GitVcs.NAME)) return CheckinHandler.DUMMY
return GitSkipHooksCommitHandler(panel, commitContext)
}
}
private class GitSkipHooksCommitHandler(
private val panel: CheckinProjectPanel,
private val commitContext: CommitContext
) : CheckinHandler() {
override fun getBeforeCheckinConfigurationPanel() = GitSkipHooksConfigurationPanel(panel, commitContext)
}
private class GitSkipHooksConfigurationPanel(
private val panel: CheckinProjectPanel,
private val commitContext: CommitContext
) : RefreshableOnComponent,
CheckinChangeListSpecificComponent {
private val repositoryManager get() = GitRepositoryManager.getInstance(panel.project)
private val runHooks = JCheckBox(GitBundle.message("checkbox.run.git.hooks")).apply {
isSelected = true
toolTipText = GitBundle.message("tooltip.run.git.hooks")
addActionListener {
CommitSessionCollector.getInstance(panel.project).logCommitOptionToggled(CommitOption.RUN_HOOKS, isSelected)
}
}
override fun getComponent(): JComponent = JBUI.Panels.simplePanel(runHooks)
private fun refreshAvailability() {
runHooks.isVisible = repositoryManager.repositories.any { it.hasCommitHooks() }
}
override fun onChangeListSelected(list: LocalChangeList) {
refreshAvailability()
}
override fun saveState() {
commitContext.isSkipHooks = runHooks.isVisible && !runHooks.isSelected
}
override fun restoreState() {
refreshAvailability()
}
private fun GitRepository.hasCommitHooks() = info.hooksInfo.areCommitHooksAvailable
}
| apache-2.0 | 397e5c629ed855dbaaddfbbd1c48fa19 | 37.447368 | 140 | 0.813142 | 4.544323 | false | false | false | false |
androidx/androidx | benchmark/gradle-plugin/src/main/kotlin/androidx/benchmark/gradle/BenchmarkReportTask.kt | 3 | 5380 | /*
* 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.benchmark.gradle
import java.io.File
import org.gradle.api.DefaultTask
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.StopExecutionException
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.property
import org.gradle.work.DisableCachingByDefault
@Suppress("UnstableApiUsage")
@DisableCachingByDefault(because = "Benchmark measurements are performed each task execution.")
open class BenchmarkReportTask : DefaultTask() {
private val benchmarkReportDir: File
init {
group = "Android"
description = "Run benchmarks found in the current project and output reports to the " +
"benchmark_reports folder under the project's build directory."
benchmarkReportDir = File(
"${project.buildDir}/outputs", "connected_android_test_additional_output"
)
outputs.dir(benchmarkReportDir)
// This task should mirror the upToDate behavior of connectedAndroidTest as we always want
// this task to run after connectedAndroidTest is run to pull the most recent benchmark
// report data, even when tests are triggered multiple times in a row without source
// changes.
outputs.upToDateWhen { false }
}
@Input
val adbPath: Property<String> = project.objects.property()
@TaskAction
fun exec() {
// Fetch reports from all available devices as the default behaviour of connectedAndroidTest
// is to run on all available devices.
getReportsForDevices(Adb(adbPath.get(), logger))
}
private fun getReportsForDevices(adb: Adb) {
if (benchmarkReportDir.exists()) {
benchmarkReportDir.deleteRecursively()
}
benchmarkReportDir.mkdirs()
val deviceIds = adb.execSync("devices -l").stdout
.split("\n")
.drop(1)
.filter { !it.contains("unauthorized") }
.map { it.split(Regex("\\s+")).first().trim() }
.filter { !it.isBlank() }
for (deviceId in deviceIds) {
val dataDir = getReportDirForDevice(adb, deviceId)
if (dataDir.isBlank()) {
throw StopExecutionException("Failed to find benchmark report on device: $deviceId")
}
val outDir = File(benchmarkReportDir, deviceId)
outDir.mkdirs()
getReportsForDevice(adb, outDir, dataDir, deviceId)
logger.info(
"Benchmark",
"Benchmark report files generated at ${benchmarkReportDir.absolutePath}"
)
}
}
private fun getReportsForDevice(
adb: Adb,
benchmarkReportDir: File,
dataDir: String,
deviceId: String
) {
adb.execSync("shell ls $dataDir", deviceId)
.stdout
.split("\n")
.map { it.trim() }
.filter { it.matches(Regex(".*benchmarkData[.](?:xml|json)$")) }
.forEach {
val src = "$dataDir/$it"
adb.execSync("pull $src $benchmarkReportDir/$it", deviceId)
adb.execSync("shell rm $src", deviceId)
}
}
/**
* Query for test runner user's Download dir on shared public external storage via content
* provider APIs.
*
* This folder is typically accessed in Android code via
* Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
*/
private fun getReportDirForDevice(adb: Adb, deviceId: String): String {
val cmd = "shell content query --uri content://media/external/file --projection _data"
// With Android >= 10 `LIKE` is no longer supported when specifying a `WHERE` clause so we
// need to manually filter the output here.
// Note that stdout of the above command is of the form:
// Row: 0 _data=/storage/emulated
// Row: 1 _data=/storage/emulated/0
// Row: 2 _data=/storage/emulated/0/Music
// Row: 3 _data=/storage/emulated/0/Podcasts
// Row: 4 _data=/storage/emulated/0/Ringtones
// Row: 5 _data=/storage/emulated/0/Alarms
// Row: 5 _data=/storage/emulated/0/Download
// etc
// There are 2 filters: the first filters all the rows ending with `Download`, while
// the second excludes app-scoped shared external storage.
return adb.execSync(cmd, deviceId).stdout
.split("\n")
.filter { it.matches(regex = Regex(".*/Download")) }
.first { !it.matches(regex = Regex(".*files/Download")) }
.trim()
.split(Regex("\\s+"))
.last()
.split("=")
.last()
.trim()
}
}
| apache-2.0 | b85b7c9f3cdb4e634bd508467c9de403 | 36.622378 | 100 | 0.628625 | 4.543919 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database/src/main/kotlin/com/onyx/diskmap/data/Header.kt | 1 | 1446 | package com.onyx.diskmap.data
import com.onyx.buffer.BufferStream
import com.onyx.buffer.BufferStreamable
import com.onyx.exception.BufferingException
import java.util.concurrent.atomic.AtomicLong
/**
* Created by timothy.osborn on 3/21/15.
*
* This class is to represent the starting place for a structure implementation. This is serialized first
*
*/
class Header : BufferStreamable {
var firstNode: Long = 0
var position: Long = 0
var recordCount: AtomicLong = AtomicLong(0)
/**
* Override equals key to compare all values
*
* @param other Object to compare against
* @return Whether the header = the parameter value
*/
override fun equals(other: Any?): Boolean = other is Header && position == other.position
/**
* Add hash code for use within maps to help identify
*
* @return hash code of the header position
*/
override fun hashCode(): Int = position.hashCode()
@Throws(BufferingException::class)
override fun read(buffer: BufferStream) {
firstNode = buffer.long
recordCount = AtomicLong(buffer.long)
position = buffer.long
}
@Throws(BufferingException::class)
override fun write(buffer: BufferStream) {
buffer.putLong(firstNode)
buffer.putLong(recordCount.get())
buffer.putLong(position)
}
companion object {
const val HEADER_SIZE = java.lang.Long.BYTES * 3
}
}
| agpl-3.0 | 519d1e4c60a22ddbe1f4e80344b76e0c | 26.283019 | 106 | 0.67704 | 4.342342 | false | false | false | false |
GunoH/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralSettingsWatcher.kt | 7 | 2512 | // 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 org.jetbrains.idea.maven.project
import com.intellij.openapi.Disposable
import com.intellij.openapi.externalSystem.autoimport.changes.AsyncFilesChangesListener.Companion.subscribeOnVirtualFilesChanges
import com.intellij.openapi.externalSystem.autoimport.changes.FilesChangesListener
import com.intellij.openapi.externalSystem.autoimport.settings.ReadAsyncSupplier
import com.intellij.openapi.util.io.FileUtil
import org.jetbrains.idea.maven.buildtool.MavenImportSpec
import org.jetbrains.idea.maven.server.MavenDistributionsCache
import java.util.concurrent.ExecutorService
class MavenGeneralSettingsWatcher private constructor(
private val manager: MavenProjectsManager,
private val watcher: MavenProjectsManagerWatcher,
backgroundExecutor: ExecutorService,
parentDisposable: Disposable
) {
private val generalSettings get() = manager.generalSettings
private val embeddersManager get() = manager.embeddersManager
private val settingsFiles: Set<String>
get() = collectSettingsFiles().map { FileUtil.toCanonicalPath(it) }.toSet()
private fun collectSettingsFiles() = sequence {
generalSettings.effectiveUserSettingsIoFile?.path?.let { yield(it) }
generalSettings.effectiveGlobalSettingsIoFile?.path?.let { yield(it) }
}
private fun fireSettingsChange() {
embeddersManager.reset()
MavenDistributionsCache.getInstance(manager.project).cleanCaches()
watcher.scheduleUpdateAll(MavenImportSpec.IMPLICIT_IMPORT)
}
private fun fireSettingsXmlChange() {
generalSettings.changed()
// fireSettingsChange() will be called indirectly by pathsChanged listener on GeneralSettings object
}
init {
generalSettings.addListener(::fireSettingsChange, parentDisposable)
val filesProvider = ReadAsyncSupplier.Builder(::settingsFiles)
.coalesceBy(this)
.build(backgroundExecutor)
subscribeOnVirtualFilesChanges(false, filesProvider, object : FilesChangesListener {
override fun apply() = fireSettingsXmlChange()
}, parentDisposable)
}
companion object {
@JvmStatic
fun registerGeneralSettingsWatcher(
manager: MavenProjectsManager,
watcher: MavenProjectsManagerWatcher,
backgroundExecutor: ExecutorService,
parentDisposable: Disposable
) {
MavenGeneralSettingsWatcher(manager, watcher, backgroundExecutor, parentDisposable)
}
}
}
| apache-2.0 | 860be3b817d6de3cd556f7fdb98616c4 | 38.873016 | 140 | 0.792994 | 5.168724 | false | false | false | false |
prof18/RSS-Parser | rssparser/src/main/java/com/prof/rssparser/caching/CacheDatabase.kt | 1 | 1172 | package com.prof.rssparser.caching
import android.content.Context
import androidx.room.AutoMigration
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(
entities = [CachedFeed::class],
version = 2,
autoMigrations = [
AutoMigration(from = 1, to = 2)
]
)
internal abstract class CacheDatabase : RoomDatabase() {
abstract fun cachedFeedDao(): CachedFeedDao
companion object {
private var INSTANCE: CacheDatabase? = null
private val lock = Any()
fun getInstance(context: Context): CacheDatabase {
if (INSTANCE == null) {
synchronized(lock) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(
context.applicationContext,
CacheDatabase::class.java,
"rssparsercache.db"
).fallbackToDestructiveMigration().build()
}
return INSTANCE as CacheDatabase
}
}
return INSTANCE as CacheDatabase
}
}
}
| apache-2.0 | f7355210bc8793933073150bd6e0aa9c | 29.051282 | 66 | 0.561433 | 5.351598 | false | false | false | false |
monarezio/PathFinder | app/src/main/java/net/zdendukmonarezio/pathfinder/domain/game/model/board/GameBoard.kt | 1 | 1395 | package net.zdendukmonarezio.pathfinder.domain.game.model.board
import net.zdendukmonarezio.pathfinder.domain.common.extensions.set
import net.zdendukmonarezio.pathfinder.domain.game.model.utils.Coordinate
import net.zdendukmonarezio.pathfinder.domain.game.model.utils.Field
/**
* Created by monarezio on 23/04/2017.
*/
data class GameBoard private constructor(private val fields: List<List<Field>>) : Board{
override fun find(field: Field): Coordinate {
val y = fields.indexOfFirst { i -> i.contains(field) }
val x = if(y == -1) -1
else fields[y].indexOfFirst { i -> i == field }
return Coordinate(x, y)
}
override fun set(x: Int, y: Int, field: Field): Board = GameBoard(fields.set(y, fields[y].set(x, field)))
override fun set(coordinate: Coordinate, field: Field): Board = set(coordinate.x, coordinate.y, field)
override fun getFields(): List<List<Field>> = fields
override fun getField(coord: Coordinate): Field = getFields()[coord.y][coord.x]
override fun getRows(): Int = fields[0].size
override fun getColumns(): Int = fields.size
companion object {
fun createBoard(fields: List<List<Field>>): Board = GameBoard(fields)
fun createEmpty(rows: Int, columns: Int) = GameBoard(
IntRange(0, rows).map { i -> IntRange(0, columns).map { i -> Field.AIR } }
)
}
} | apache-2.0 | 43c24a4c61d248cb0cfa653185a0856d | 35.736842 | 109 | 0.671685 | 3.680739 | false | false | false | false |
flicus/vertx-telegram-bot-api | kotlin/src/main/kotlin/kt/schors/vertx/telegram/bot/example/Main.kt | 1 | 530 | package kt.schors.vertx.telegram.bot.example
import io.vertx.core.DeploymentOptions
import io.vertx.core.Vertx
import io.vertx.core.VertxOptions
fun main(args: Array<String>) {
var options = VertxOptions().setWorkerPoolSize(40)
val vertx = Vertx.vertx(options)
// val vertx = Vertx.vertx(VertxOptions(workerPoolSize = 40))
var deploymentOptions = DeploymentOptions().setInstances(1)
// vertx.deployVerticle(TestBot(), DeploymentOptions(instances = 1))
vertx.deployVerticle(TestBot(), deploymentOptions)
}
| mit | 82a2b96aef6f627fda5411db18bcdcb4 | 34.333333 | 71 | 0.760377 | 3.897059 | false | true | false | false |
everis-innolab/interledger-ledger | src/main/java/com/everis/everledger/handlers/AccountHandlers.kt | 1 | 6734 | package com.everis.everledger.handlers
import com.everis.everledger.AccessRoll
import com.everis.everledger.AuthInfo
import com.everis.everledger.util.Config
import com.everis.everledger.ifaces.account.IfaceAccount
import com.everis.everledger.impl.SimpleAccount
import com.everis.everledger.impl.manager.SimpleAccountManager
import com.everis.everledger.util.AuthManager
import com.everis.everledger.util.ConversionUtil
import com.everis.everledger.util.ILPExceptionSupport
import com.everis.everledger.util.JsonObjectBuilder
import io.netty.handler.codec.http.HttpResponseStatus
import io.vertx.core.http.HttpMethod
import io.vertx.core.json.JsonArray
import io.vertx.core.json.JsonObject
import io.vertx.ext.web.RoutingContext
import org.javamoney.moneta.Money
import org.slf4j.LoggerFactory
private val PARAM_ID = "id"
private val PARAM_NAME = "name"
private val PARAM_BALANCE = "balance"
private val PARAM_MIN_ALLOWED_BALANCE = "minimum_allowed_balance"
private val PARAM_PASSWORD = "password"
private fun accountToJsonObject(account: IfaceAccount, isAuthenticated: Boolean): JsonObject {
// TODO:(0) Move to JSON Support?
val build = JsonObjectBuilder.create()
.put("id", Config.publicURL.toString()+"/accounts/"+account.id)
.put("name", account.authInfo.login)
// .put("ledger", Config.publicURL.toString())
if (isAuthenticated) {
build
.put("balance", account.balanceAsString)
// .put("connector", "??????" /* TODO:(?) Recheck */)
.put("is_disabled", account.isDisabled)
.put("minimum_allowed_balance", account.ilpMinimumAllowedBalance.number.toString())
}
return build.get()
}
class AccountsHandler
private constructor() : RestEndpointHandler(
arrayOf(HttpMethod.GET, HttpMethod.PUT, HttpMethod.POST), arrayOf("accounts/:" + PARAM_ID)) {
override fun handleGet(context: RoutingContext) {
val ai = AuthManager.authenticate(context, true)
// private fun getAccountName(context: RoutingContext): String {
// val accountName =
// throw ILPExceptionSupport.createILPBadRequestException(PARAM_NAME + "not provided")
// }
// return accountName
// }
val data_id = ConversionUtil.parseNonEmptyString(context.request().getParam(PARAM_ID))
val isAuthenticated = ai.roll == AccessRoll.ADMIN || ai.id == data_id
val account = SimpleAccountManager.getAccountById(data_id)
val result = accountToJsonObject(account, isAuthenticated)
response(context, HttpResponseStatus.OK, result)
}
override fun handlePut(context: RoutingContext) {
log.debug("Handing put account")
AuthManager.authenticate(context)
val id = ConversionUtil.parseNonEmptyString(context.request().getParam(PARAM_ID))
val exists = SimpleAccountManager.hasAccount(id)
val data = RestEndpointHandler.getBodyAsJson(context)
val data_id01 = data.getString(PARAM_ID)
val data_id01_offset = data_id01.lastIndexOf('/')
val data_id = if (data_id01_offset >= 0) data_id01.substring(data_id01_offset+1) else data_id01
if (id != data_id) {
throw ILPExceptionSupport.createILPBadRequestException(
"id in body '$data_id' doesn't match account id '$id' in URL")
}
// TODO:(0) Check data_id is valid (for example valid Ethereum address)
val data_name: String = data.getString(PARAM_NAME)
?: throw ILPExceptionSupport.createILPBadRequestException("id not provided")
var data_password = data.getString(PARAM_PASSWORD) ?:
if (exists) AuthManager.getUsers()[data_name]!!.pass
else throw ILPExceptionSupport.createILPBadRequestException("password not provided for id:" + data_id)
if (exists && !data_name.equals(data_name, ignoreCase = true)) {
throw ILPExceptionSupport.createILPBadRequestException()
}
log.info("Put data: {} to account {}", data, data_name)
var sMinAllowVal: String? = data.getString(PARAM_MIN_ALLOWED_BALANCE)
if (sMinAllowVal == null) sMinAllowVal = "0" // TODO:(1) Arbitrary value. Use Config....
sMinAllowVal = sMinAllowVal.toLowerCase().replace("infinity", "1000000000000000") // TODO:(0) Arbitrary value. Use Config...
val minAllowedBalance = ConversionUtil.toNumber(sMinAllowVal)
val balance = if (data.containsKey(PARAM_BALANCE))
ConversionUtil.toNumber(data.getValue(PARAM_BALANCE))
else
ConversionUtil.toNumber("0")
val ai = AuthInfo(data_id, data_name, data_password, AccessRoll.USER )
val account = SimpleAccount(
data_id,
Money.of(balance, Config.ledgerCurrencyCode),
Money.of(minAllowedBalance, Config.ledgerCurrencyCode),
false, ai )
SimpleAccountManager.store(account, true /*update if already exists*/)
AuthManager.setUser(ai)
// if(data.containsKey(PARAM_DISABLED)) {
// ((SimpleLedgerAccount)account).setDisabled(data.getBoolean(PARAM_DISABLED, false));
// }
response(context,
if (exists) HttpResponseStatus.OK else HttpResponseStatus.CREATED,
accountToJsonObject(account, true) )
}
override fun handlePost(context: RoutingContext) {
handlePut(context)
}
companion object {
private val log = LoggerFactory.getLogger(AccountsHandler::class.java)
fun create(): AccountsHandler {
return AccountsHandler()
}
}
}
class AccountsListHandler private constructor() :
RestEndpointHandler(arrayOf(HttpMethod.GET), arrayOf("accounts")) {
override fun handleGet(context: RoutingContext) {
val ai = AuthManager.authenticate(context)
if (!ai.isAdmin) {
throw ILPExceptionSupport.createILPForbiddenException()
}
val request = RestEndpointHandler.getBodyAsJson(context)
val page = request.getInteger("page", 1)!!
val pageSize = request.getInteger("pageSize", 10)!!
val response : JsonArray = JsonArray()
for (account in SimpleAccountManager.getAccounts(page, pageSize)) {
response.add(accountToJsonObject(account, true))
}
context.response()
.putHeader("content-type", "application/json; charset=utf-8") //TODO create decorator
.end(response.encode())
}
companion object {
private val log = LoggerFactory.getLogger(AccountsListHandler::class.java)
fun create(): AccountsListHandler = AccountsListHandler()
}
} | apache-2.0 | 97ae88ad8734136b58ca1bd3cc4daa51 | 40.067073 | 132 | 0.674042 | 4.253948 | false | false | false | false |
AlmasB/Zephyria | src/main/kotlin/com/almasb/zeph/item/Item.kt | 1 | 3999 | package com.almasb.zeph.item
import com.almasb.zeph.Config.MAX_ESSENCES
import com.almasb.zeph.Config.MAX_ITEM_REFINE_LEVEL
import com.almasb.zeph.Description
import com.almasb.zeph.character.CharacterEntity
import com.almasb.zeph.combat.Essence
import com.almasb.zeph.combat.GameMath
import com.almasb.zeph.combat.Rune
import com.almasb.zeph.ui.TooltipTextFlow
import javafx.beans.property.SimpleIntegerProperty
import javafx.beans.property.SimpleStringProperty
import javafx.collections.FXCollections
import javafx.scene.text.TextFlow
enum class ItemLevel constructor(
val bonus: Int,
val refineChanceReduction: Int,
val maxRunes: Int) {
// refinement chance 100/90/80/70/60
NORMAL(3, 10, 2),
// refinement chance 100/85/70/55/40
UNIQUE(5, 15, 3),
// refinement chance 100/80/60/40/20
EPIC(10, 20, 4)
}
/**
* Currently the subtypes are only: EquipItem (Weapon/Armor), UsableItem, MiscItem.
*
* @author Almas Baimagambetov ([email protected])
*/
sealed class Item(val description: Description) {
/**
* A property populated with dynamic description.
* Typically a combination of static + runtime info, such as
* actual weapon damage, actual armor rating, etc.
*/
val dynamicDescription = SimpleStringProperty(description.name + "\n" + description.description)
val dynamicTextFlow: TextFlow = TooltipTextFlow(description)
}
/**
* Subtypes are only: Weapon, Armor.
*/
sealed class EquipItem(
description: Description,
val itemLevel: ItemLevel,
dataRunes: List<Rune>,
dataEssences: List<Essence>
) : Item(description) {
val runes = FXCollections.observableArrayList(dataRunes)
val essences = FXCollections.observableArrayList(dataEssences)
var equippedCharacter: CharacterEntity? = null
val refineLevel = SimpleIntegerProperty(0)
/**
* @return whether rune addition succeeded
*/
fun addRune(rune: Rune): Boolean {
if (runes.size >= itemLevel.maxRunes)
return false
equippedCharacter?.let {
onUnEquip(it)
}
runes += rune
equippedCharacter?.let {
onEquip(it)
}
return true
}
fun removeRune(rune: Rune) {
equippedCharacter?.let {
onUnEquip(it)
}
runes -= rune
equippedCharacter?.let {
onEquip(it)
}
}
/**
* @return whether essence addition succeeded
*/
fun addEssence(essence: Essence): Boolean {
if (essences.size >= MAX_ESSENCES)
return false
equippedCharacter?.let {
onUnEquip(it)
}
essences += essence
equippedCharacter?.let {
onEquip(it)
}
return true
}
fun removeEssence(essence: Essence) {
equippedCharacter?.let {
onUnEquip(it)
}
essences -= essence
equippedCharacter?.let {
onEquip(it)
}
}
open fun onEquip(char: CharacterEntity) {
equippedCharacter = char
runes.forEach { char.addBonus(it.attribute, it.bonus) }
essences.forEach { char.addBonus(it.stat, it.bonus) }
}
open fun onUnEquip(char: CharacterEntity) {
equippedCharacter = null
runes.forEach { char.addBonus(it.attribute, -it.bonus) }
essences.forEach { char.addBonus(it.stat, -it.bonus) }
}
/**
* @return true if refine succeeded
*/
fun refine(): Boolean {
if (refineLevel.value >= MAX_ITEM_REFINE_LEVEL)
return false
if (GameMath.checkChance(100 - refineLevel.value * itemLevel.refineChanceReduction)) {
refineLevel.value++
return true
}
if (refineLevel.value > 0) {
refineLevel.value--
}
return false
}
}
/**
* Marks a class that stores item data.
*/
interface ItemData {
val description: Description
} | gpl-2.0 | 91f18949c66f0be2d1a85569488a62f9 | 22.952096 | 100 | 0.629407 | 4.003003 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/command/character/unhide/CharacterUnhideProfileCommand.kt | 1 | 2723 | /*
* Copyright 2016 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.characters.bukkit.command.character.unhide
import com.rpkit.characters.bukkit.RPKCharactersBukkit
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
/**
* Character unhide profile command.
* Unhides character's profile.
*/
class CharacterUnhideProfileCommand(private val plugin: RPKCharactersBukkit): CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean {
if (sender is Player) {
if (sender.hasPermission("rpkit.characters.command.character.unhide.profile")) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender)
if (minecraftProfile != null) {
val character = characterProvider.getActiveCharacter(minecraftProfile)
if (character != null) {
character.isProfileHidden = false
characterProvider.updateCharacter(character)
sender.sendMessage(plugin.messages["character-unhide-profile-valid"])
character.showCharacterCard(minecraftProfile)
} else {
sender.sendMessage(plugin.messages["no-character"])
}
} else {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
}
} else {
sender.sendMessage(plugin.messages["no-permission-character-unhide-profile"])
}
} else {
sender.sendMessage(plugin.messages["not-from-console"])
}
return true
}
} | apache-2.0 | 395b2e46b47d49be9fc71166d4b9bcb1 | 43.655738 | 128 | 0.677929 | 5.216475 | false | false | false | false |
Litote/kmongo | kmongo-annotation-processor/target/generated-sources/kapt/test/org/litote/kmongo/issue/RecordCollectionImpl1_.kt | 1 | 3634 | package org.litote.kmongo.issue
import java.time.Month
import java.time.Year
import kotlin.Long
import kotlin.String
import kotlin.Suppress
import kotlin.collections.Collection
import kotlin.collections.List
import kotlin.collections.Map
import kotlin.reflect.KProperty1
import org.litote.kmongo.property.KCollectionPropertyPath
import org.litote.kmongo.property.KCollectionSimplePropertyPath
import org.litote.kmongo.property.KMapPropertyPath
import org.litote.kmongo.property.KPropertyPath
private val ___id: KProperty1<RecordCollectionImpl1, Long?>
get() = RecordCollectionImpl1::_id
private val __Year: KProperty1<RecordCollectionImpl1, Year?>
get() = RecordCollectionImpl1::year
private val __Month: KProperty1<RecordCollectionImpl1, Month?>
get() = RecordCollectionImpl1::month
private val __Records: KProperty1<RecordCollectionImpl1, List<out Record1?>?>
get() = RecordCollectionImpl1::records
class RecordCollectionImpl1_<T>(previous: KPropertyPath<T, *>?, property: KProperty1<*,
RecordCollectionImpl1?>) : KPropertyPath<T, RecordCollectionImpl1?>(previous,property) {
val _id: KPropertyPath<T, Long?>
get() = KPropertyPath(this,___id)
val year: KPropertyPath<T, Year?>
get() = KPropertyPath(this,__Year)
val month: KPropertyPath<T, Month?>
get() = KPropertyPath(this,__Month)
val records: KCollectionSimplePropertyPath<T, out Record1??>
get() = KCollectionSimplePropertyPath(this,RecordCollectionImpl1::records)
companion object {
val _id: KProperty1<RecordCollectionImpl1, Long?>
get() = ___id
val Year: KProperty1<RecordCollectionImpl1, Year?>
get() = __Year
val Month: KProperty1<RecordCollectionImpl1, Month?>
get() = __Month
val Records: KCollectionSimplePropertyPath<RecordCollectionImpl1, out Record1??>
get() = KCollectionSimplePropertyPath(null, __Records)}
}
class RecordCollectionImpl1_Col<T>(previous: KPropertyPath<T, *>?, property: KProperty1<*,
Collection<RecordCollectionImpl1>?>) : KCollectionPropertyPath<T, RecordCollectionImpl1?,
RecordCollectionImpl1_<T>>(previous,property) {
val _id: KPropertyPath<T, Long?>
get() = KPropertyPath(this,___id)
val year: KPropertyPath<T, Year?>
get() = KPropertyPath(this,__Year)
val month: KPropertyPath<T, Month?>
get() = KPropertyPath(this,__Month)
val records: KCollectionSimplePropertyPath<T, out Record1??>
get() = KCollectionSimplePropertyPath(this,RecordCollectionImpl1::records)
@Suppress("UNCHECKED_CAST")
override fun memberWithAdditionalPath(additionalPath: String): RecordCollectionImpl1_<T> =
RecordCollectionImpl1_(this, customProperty(this, additionalPath))}
class RecordCollectionImpl1_Map<T, K>(previous: KPropertyPath<T, *>?, property: KProperty1<*, Map<K,
RecordCollectionImpl1>?>) : KMapPropertyPath<T, K, RecordCollectionImpl1?,
RecordCollectionImpl1_<T>>(previous,property) {
val _id: KPropertyPath<T, Long?>
get() = KPropertyPath(this,___id)
val year: KPropertyPath<T, Year?>
get() = KPropertyPath(this,__Year)
val month: KPropertyPath<T, Month?>
get() = KPropertyPath(this,__Month)
val records: KCollectionSimplePropertyPath<T, out Record1??>
get() = KCollectionSimplePropertyPath(this,RecordCollectionImpl1::records)
@Suppress("UNCHECKED_CAST")
override fun memberWithAdditionalPath(additionalPath: String): RecordCollectionImpl1_<T> =
RecordCollectionImpl1_(this, customProperty(this, additionalPath))}
| apache-2.0 | 4d93749e5d7f3cc96c606ea771407422 | 41.255814 | 100 | 0.719042 | 4.153143 | false | false | false | false |
SoulBeaver/Arena--7DRL- | src/main/java/com/sbg/arena/core/animation/ShootAnimation.kt | 1 | 2419 | package com.sbg.arena.core.animation
import org.newdawn.slick.Graphics
import com.sbg.arena.core.level.Skin
import com.sbg.arena.core.input.ShootRequest
import kotlin.properties.Delegates
import org.newdawn.slick.Image
import com.sbg.arena.core.geom.Point
import org.apache.logging.log4j.LogManager
import com.sbg.arena.core.Direction
class ShootAnimation(val request: ShootRequest, val onAnimationFinished: () -> Unit): Animation {
private val logger = LogManager.getLogger(javaClass<ShootAnimation>())!!
var shootSkin: Image by Delegates.notNull()
var start: Point by Delegates.notNull()
var targets: Map<Direction, Point> by Delegates.notNull()
var shots: MutableMap<Direction, Point> by Delegates.notNull()
override fun initialize(levelSkin: Skin) {
shootSkin = levelSkin.shootTile()
start = request.start.let { Point(it.x * 20, it.y * 20) }
targets = hashMapOf(Direction.North to request.targets[Direction.North]!!.let { Point(it.x * 20, it.y * 20) },
Direction.East to request.targets[Direction.East]!!.let { Point(it.x * 20, it.y * 20) },
Direction.South to request.targets[Direction.South]!!.let { Point(it.x * 20, it.y * 20) },
Direction.West to request.targets[Direction.West]!!.let { Point(it.x * 20, it.y * 20) })
shots = hashMapOf(Direction.North to start,
Direction.East to start,
Direction.South to start,
Direction.West to start)
}
override fun update() {
shots.entrySet().filter { it.getValue() == targets[it.getKey()] } forEach { shots.remove(it.getKey()) }
for ((direction, shot) in shots.entrySet())
shots[direction] = update(direction, shot)
}
private fun update(direction: Direction, shot: Point): Point {
return when (direction) {
Direction.North -> Point(shot.x, shot.y - 5)
Direction.South -> Point(shot.x, shot.y + 5)
Direction.West -> Point(shot.x - 5, shot.y)
Direction.East -> Point(shot.x + 5, shot.y)
}
}
override fun render(graphics: Graphics) {
shots.values().forEach { shootSkin.draw(it.x.toFloat(), it.y.toFloat()) }
}
override fun isFinished() = shots.isEmpty()
override fun finish() = onAnimationFinished()
} | apache-2.0 | 652eb5d7b661b7e2d8ee86bf809371ad | 40.724138 | 118 | 0.627532 | 3.926948 | false | false | false | false |
AdamLuisSean/Picasa-Gallery-Android | app/src/main/kotlin/io/shtanko/picasagallery/ui/util/AndroidUtils.kt | 1 | 2405 | /*
* 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.ui.util
import android.graphics.Matrix
import android.graphics.Matrix.ScaleToFit.FILL
import android.graphics.Point
import android.graphics.RectF
import io.shtanko.picasagallery.PicasaApplication
object AndroidUtils {
var statusBarHeight = 0
var displaySize = Point()
var density = 1f
fun setRectToRect(
matrix: Matrix,
src: RectF,
dst: RectF,
rotation: Int,
align: Matrix.ScaleToFit
) {
val tx: Float
var sx: Float
val ty: Float
var sy: Float
if (rotation == 90 || rotation == 270) {
sx = dst.height() / src.width()
sy = dst.width() / src.height()
} else {
sx = dst.width() / src.width()
sy = dst.height() / src.height()
}
if (align != FILL) {
if (sx > sy) {
sx = sy
} else {
sy = sx
}
}
tx = -src.left * sx
ty = -src.top * sy
matrix.setTranslate(dst.left, dst.top)
if (rotation == 90) {
matrix.preRotate(90f)
matrix.preTranslate(0f, -dst.width())
} else if (rotation == 180) {
matrix.preRotate(180f)
matrix.preTranslate(-dst.width(), -dst.height())
} else if (rotation == 270) {
matrix.preRotate(270f)
matrix.preTranslate(-dst.height(), 0f)
}
matrix.preScale(sx, sy)
matrix.preTranslate(tx, ty)
}
fun dp(value: Float): Int {
return if (value == 0f) {
0
} else Math.ceil((density * value).toDouble()).toInt()
}
fun runOnUIThread(runnable: Runnable) {
runOnUIThread(runnable, 0)
}
private fun runOnUIThread(
runnable: Runnable,
delay: Long
) {
if (delay == 0.toLong()) {
PicasaApplication.applicationHandler.post(runnable)
} else {
PicasaApplication.applicationHandler.postDelayed(runnable, delay)
}
}
} | apache-2.0 | 301f68df6c16035534c2bbc598715ea8 | 24.0625 | 75 | 0.640748 | 3.67737 | false | false | false | false |
summerlly/Quiet | app/src/main/java/tech/summerly/quiet/data/preference/impl/ILocalMusicScannerSetting.kt | 1 | 3151 | /*
* MIT License
*
* Copyright (c) 2017 YangBin
*
* 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 tech.summerly.quiet.data.preference.impl
import android.content.Context
import tech.summerly.quiet.AppContext
import tech.summerly.quiet.data.preference.LocalMusicScannerSetting
import tech.summerly.quiet.extensions.edit
/**
* author : Summer
* date : 2017/10/20
*/
object ILocalMusicScannerSetting : LocalMusicScannerSetting {
private const val NAME = "preference_local_music_scanner"
private const val KEY_IS_FILTER_BY_DURATION = "isFilterByDuration"
private const val KEY_LIMIT_DURATION = "limitDuration"
private const val KEY_FILTER_FOLDERS = "filterFolders"
private const val DEFAULT_LIMIT_DURATION = 1000 * 30
private val preference by lazy {
AppContext.instance.getSharedPreferences(NAME, Context.MODE_PRIVATE)
}
fun setFilterByDuration(filter: Boolean) {
preference.edit {
putBoolean(KEY_IS_FILTER_BY_DURATION, filter)
}
}
override fun isFilterByDuration(): Boolean {
return preference.getBoolean(KEY_IS_FILTER_BY_DURATION, true)
}
fun setLimitDuration(duration: Int) {
preference.edit {
putInt(KEY_LIMIT_DURATION, duration)
}
}
override fun getLimitDuration(): Int {
return preference.getInt(KEY_LIMIT_DURATION, DEFAULT_LIMIT_DURATION)
}
fun addFilterFolder(folderPath: String) {
preference.edit {
val folders = preference.getStringSet(KEY_FILTER_FOLDERS, null) ?: HashSet<String>()
folders.add(folderPath)
putStringSet(KEY_FILTER_FOLDERS, folders)
}
}
fun removeFilterFolderByPath(folderPath: String) {
preference.edit {
val folders = preference.getStringSet(KEY_FILTER_FOLDERS, null) ?: HashSet<String>()
folders.remove(folderPath)
putStringSet(KEY_FILTER_FOLDERS, folders)
}
}
override fun getAllFilterFolder(): Set<String> {
return preference.getStringSet(KEY_FILTER_FOLDERS, null) ?: emptySet()
}
}
| gpl-2.0 | 6d6ef9c5a73cc369cfa235e6ff5ee5e5 | 32.521277 | 96 | 0.707077 | 4.376389 | false | false | false | false |
elect86/modern-jogl-examples | src/main/kotlin/glNext/tut03/vertPositionOffset.kt | 2 | 2639 | package glNext.tut03
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL.*
import com.jogamp.opengl.GL3
import glNext.*
import glm.glm
import glm.vec._2.Vec2
import main.framework.Framework
import uno.buffer.destroyBuffers
import uno.buffer.floatBufferOf
import uno.buffer.intBufferBig
import uno.glsl.programOf
/**
* Created by elect on 21/02/17.
*/
fun main(args: Array<String>) {
VertPositionOffset_Next().setup("Tutorial 03 - Shader Position Offset")
}
class VertPositionOffset_Next : Framework() {
var theProgram = 0
var offsetLocation = 0
val positionBufferObject = intBufferBig(1)
val vao = intBufferBig(1)
val vertexPositions = floatBufferOf(
+0.25f, +0.25f, 0.0f, 1.0f,
+0.25f, -0.25f, 0.0f, 1.0f,
-0.25f, -0.25f, 0.0f, 1.0f)
var startingTime = 0L
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
initializeVertexBuffer(gl)
glGenVertexArray(vao)
glBindVertexArray(vao)
startingTime = System.currentTimeMillis()
}
fun initializeProgram(gl: GL3) = with(gl) {
theProgram = programOf(gl, javaClass, "tut03", "position-offset.vert", "standard.frag")
withProgram(theProgram) { offsetLocation = "offset".location }
}
fun initializeVertexBuffer(gl: GL3) =
gl.initArrayBuffer(positionBufferObject) { data(vertexPositions, GL_STATIC_DRAW) }
override fun display(gl: GL3) = with(gl) {
val offset = Vec2(0f)
computePositionOffsets(offset)
clear { color(0, 0, 0, 1) }
usingProgram(theProgram) {
offsetLocation.vec2 = offset
withVertexLayout(positionBufferObject, glf.pos4) { glDrawArrays(3) }
}
}
fun computePositionOffsets(offset: Vec2) {
val loopDuration = 5.0f
val scale = glm.PIf * 2f / loopDuration
val elapsedTime = (System.currentTimeMillis() - startingTime) / 1_000f
val currTimeThroughLoop = elapsedTime % loopDuration
offset.x = glm.cos(currTimeThroughLoop * scale) * .5f
offset.y = glm.sin(currTimeThroughLoop * scale) * .5f
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
glViewport(w, h)
}
override fun end(gl: GL3) = with(gl) {
glDeleteProgram(theProgram)
glDeleteBuffer(positionBufferObject)
glDeleteVertexArray(vao)
destroyBuffers(positionBufferObject, vao, vertexPositions)
}
override fun keyPressed(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
}
}
} | mit | 71b034be07c869090fcc846106aaccea | 24.631068 | 95 | 0.644562 | 3.903846 | false | false | false | false |
android/user-interface-samples | People/app/src/main/java/com/example/android/people/data/ChatRepository.kt | 1 | 4852 | /*
* Copyright (C) 2019 The Android Open Source Project
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.people.data
import android.content.Context
import android.net.Uri
import androidx.annotation.MainThread
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import java.util.concurrent.Executor
import java.util.concurrent.Executors
interface ChatRepository {
fun getContacts(): LiveData<List<Contact>>
fun findContact(id: Long): LiveData<Contact?>
fun findMessages(id: Long): LiveData<List<Message>>
fun sendMessage(id: Long, text: String, photoUri: Uri?, photoMimeType: String?)
fun updateNotification(id: Long)
fun activateChat(id: Long)
fun deactivateChat(id: Long)
fun showAsBubble(id: Long)
fun canBubble(id: Long): Boolean
}
class DefaultChatRepository internal constructor(
private val notificationHelper: NotificationHelper,
private val executor: Executor
) : ChatRepository {
companion object {
private var instance: DefaultChatRepository? = null
fun getInstance(context: Context): DefaultChatRepository {
return instance ?: synchronized(this) {
instance ?: DefaultChatRepository(
NotificationHelper(context),
Executors.newFixedThreadPool(4)
).also {
instance = it
}
}
}
}
private var currentChat: Long = 0L
private val chats = Contact.CONTACTS.map { contact ->
contact.id to Chat(contact)
}.toMap()
init {
notificationHelper.setUpNotificationChannels()
}
@MainThread
override fun getContacts(): LiveData<List<Contact>> {
return MutableLiveData<List<Contact>>().apply {
postValue(Contact.CONTACTS)
}
}
@MainThread
override fun findContact(id: Long): LiveData<Contact?> {
return MutableLiveData<Contact>().apply {
postValue(Contact.CONTACTS.find { it.id == id })
}
}
@MainThread
override fun findMessages(id: Long): LiveData<List<Message>> {
val chat = chats.getValue(id)
return object : LiveData<List<Message>>() {
private val listener = { messages: List<Message> ->
postValue(messages)
}
override fun onActive() {
value = chat.messages
chat.addListener(listener)
}
override fun onInactive() {
chat.removeListener(listener)
}
}
}
@MainThread
override fun sendMessage(id: Long, text: String, photoUri: Uri?, photoMimeType: String?) {
val chat = chats.getValue(id)
chat.addMessage(Message.Builder().apply {
sender = 0L // User
this.text = text
timestamp = System.currentTimeMillis()
this.photo = photoUri
this.photoMimeType = photoMimeType
})
executor.execute {
// The animal is typing...
Thread.sleep(5000L)
// Receive a reply.
chat.addMessage(chat.contact.reply(text))
// Show notification if the chat is not on the foreground.
if (chat.contact.id != currentChat) {
notificationHelper.showNotification(chat, false)
}
}
}
override fun updateNotification(id: Long) {
val chat = chats.getValue(id)
notificationHelper.showNotification(chat, false, true)
}
override fun activateChat(id: Long) {
val chat = chats.getValue(id)
currentChat = id
val isPrepopulatedMsgs =
chat.messages.size == 2 && chat.messages[0] != null && chat.messages[1] != null
notificationHelper.updateNotification(chat, id, isPrepopulatedMsgs)
}
override fun deactivateChat(id: Long) {
if (currentChat == id) {
currentChat = 0
}
}
override fun showAsBubble(id: Long) {
val chat = chats.getValue(id)
executor.execute {
notificationHelper.showNotification(chat, true)
}
}
override fun canBubble(id: Long): Boolean {
val chat = chats.getValue(id)
return notificationHelper.canBubble(chat.contact)
}
}
| apache-2.0 | fbedea065b22b2636698842e06e8f293 | 30.506494 | 94 | 0.624691 | 4.719844 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/economy/declarations/SonhosCommand.kt | 1 | 2201 | package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.declarations
import net.perfectdreams.loritta.common.locale.LanguageManager
import net.perfectdreams.loritta.i18n.I18nKeysData
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.common.commands.CommandCategory
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandDeclarationWrapper
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.SonhosExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.pay.PayExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.sonhosrank.SonhosRankExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.transactions.TransactionsExecutor
import net.perfectdreams.loritta.common.utils.TodoFixThisData
class SonhosCommand(languageManager: LanguageManager) : CinnamonSlashCommandDeclarationWrapper(languageManager) {
companion object {
val I18N_PREFIX = I18nKeysData.Commands.Command.Sonhos
val CATEGORY_I18N_PREFIX = I18nKeysData.Commands.Category.Economy
val SONHOS_I18N_PREFIX = I18nKeysData.Commands.Command.Sonhosatm
val SONHOS_RANK_I18N_PREFIX = I18nKeysData.Commands.Command.Sonhosrank
val PAY_I18N_PREFIX = I18nKeysData.Commands.Command.Pay
val TRANSACTIONS_I18N_PREFIX = I18nKeysData.Commands.Command.Transactions
}
override fun declaration() = slashCommand(I18N_PREFIX.Label, CommandCategory.ECONOMY, CATEGORY_I18N_PREFIX.RootCommandDescription) {
subcommand(SONHOS_I18N_PREFIX.Label, SONHOS_I18N_PREFIX.Description) {
executor = { SonhosExecutor(it) }
}
subcommand(PAY_I18N_PREFIX.Label, PAY_I18N_PREFIX.Description) {
executor = { PayExecutor(it) }
}
subcommand(SONHOS_RANK_I18N_PREFIX.Label, SONHOS_RANK_I18N_PREFIX.Description) {
executor = { SonhosRankExecutor(it) }
}
subcommand(TRANSACTIONS_I18N_PREFIX.Label, TRANSACTIONS_I18N_PREFIX.Description) {
executor = { TransactionsExecutor(it) }
}
}
} | agpl-3.0 | c9cc465f4d159512c0dff2a020cbcd9e | 52.707317 | 136 | 0.780554 | 4.106343 | false | false | false | false |
jitsi/jibri | src/test/kotlin/org/jitsi/jibri/service/impl/SipGatewayJibriServiceTest.kt | 1 | 7647 | /*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.jibri.service.impl
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.shouldBe
import io.kotest.matchers.types.shouldBeInstanceOf
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.Runs
import io.mockk.verify
import org.jitsi.jibri.CallUrlInfo
import org.jitsi.jibri.config.XmppCredentials
import org.jitsi.jibri.error.JibriError
import org.jitsi.jibri.helpers.SeleniumMockHelper
import org.jitsi.jibri.helpers.createFinalizeProcessMock
import org.jitsi.jibri.selenium.CallParams
import org.jitsi.jibri.selenium.FailedToJoinCall
import org.jitsi.jibri.sipgateway.SipClientParams
import org.jitsi.jibri.sipgateway.pjsua.PjsuaClient
import org.jitsi.jibri.sipgateway.pjsua.util.RemoteSipClientBusy
import org.jitsi.jibri.status.ComponentState
import org.jitsi.jibri.util.ProcessFactory
internal class SipGatewayJibriServiceTest : ShouldSpec() {
override fun isolationMode(): IsolationMode = IsolationMode.InstancePerLeaf
private val callParams = CallParams(
CallUrlInfo("baseUrl", "callName"),
"[email protected]"
)
private val callLoginParams = XmppCredentials(
domain = "domain",
username = "username",
password = "password"
)
private val sipClientParams = SipClientParams(
"[email protected]",
"sipusername",
true
)
private val sipGatewayServiceParams = SipGatewayServiceParams(
callParams,
callLoginParams,
sipClientParams
)
private val seleniumMockHelper = SeleniumMockHelper()
private val pjsuaClientMockHelper = PjsuaClientMockHelper()
private val processFactory: ProcessFactory = mockk()
private val statusUpdates = mutableListOf<ComponentState>()
private val sipGatewayJibriService =
SipGatewayJibriService(
sipGatewayServiceParams,
seleniumMockHelper.mock,
pjsuaClientMockHelper.mock,
processFactory
).also {
it.addStatusHandler(statusUpdates::add)
}
init {
context("starting a sip gateway service") {
sipGatewayJibriService.start()
should("have selenium join the call") {
verify { seleniumMockHelper.mock.joinCall(any(), any()) }
}
context("and selenium joins the call successfully") {
seleniumMockHelper.startSuccessfully()
should("start pjsua") {
verify { pjsuaClientMockHelper.mock.start() }
}
should("add sip metadata to presence") {
verify { seleniumMockHelper.mock.addToPresence("sip_address", "sip:[email protected]") }
verify { seleniumMockHelper.mock.sendPresence() }
}
context("and the pjsua starts successfully") {
pjsuaClientMockHelper.startSuccessfully()
should("publish that it's running") {
statusUpdates shouldHaveSize 1
val status = statusUpdates.first()
status shouldBe ComponentState.Running
}
}
context("but pjsua fails to start") {
pjsuaClientMockHelper.error(RemoteSipClientBusy)
should("publish an error") {
statusUpdates shouldHaveSize 1
val status = statusUpdates.first()
status.shouldBeInstanceOf<ComponentState.Error>()
}
}
}
context("but joining the call fails") {
seleniumMockHelper.error(FailedToJoinCall)
should("publish an error") {
statusUpdates shouldHaveSize 1
val status = statusUpdates.first()
status.shouldBeInstanceOf<ComponentState.Error>()
}
}
}
context("stopping a service which has successfully started") {
// First get the service in a 'successful start' state.
sipGatewayJibriService.start()
seleniumMockHelper.startSuccessfully()
pjsuaClientMockHelper.startSuccessfully()
// Validate that it started
statusUpdates shouldHaveSize 1
val status = statusUpdates.first()
status shouldBe ComponentState.Running
// Stop the service
val finalizeProcessMock = createFinalizeProcessMock(true)
every {
processFactory.createProcess(eq(listOf("/opt/jitsi/jibri/finalize_sip.sh")), any(), any(), any())
} returns finalizeProcessMock
sipGatewayJibriService.stop()
should("tell selenium to leave the call") {
verify { seleniumMockHelper.mock.leaveCallAndQuitBrowser() }
}
should("run the finalize command") {
finalizeProcessMock.start()
}
}
context("stopping a service which has successfully started, but finalize script fails") {
// First get the service in a 'successful start' state.
sipGatewayJibriService.start()
seleniumMockHelper.startSuccessfully()
pjsuaClientMockHelper.startSuccessfully()
// Validate that it started
statusUpdates shouldHaveSize 1
val status = statusUpdates.first()
status shouldBe ComponentState.Running
// Stop the service
val finalizeProcessMock = createFinalizeProcessMock(false)
every {
processFactory.createProcess(eq(listOf("/opt/jitsi/jibri/finalize_sip.sh")), any(), any(), any())
} returns finalizeProcessMock
sipGatewayJibriService.stop()
should("tell selenium to leave the call") {
verify { seleniumMockHelper.mock.leaveCallAndQuitBrowser() }
}
should("run the finalize command") {
finalizeProcessMock.start()
finalizeProcessMock.waitFor()
}
}
}
}
private class PjsuaClientMockHelper() {
private val eventHandlers = mutableListOf<(ComponentState) -> Boolean>()
val mock: PjsuaClient = mockk(relaxed = true) {
every { addTemporaryHandler(capture(eventHandlers)) } just Runs
every { addStatusHandler(captureLambda()) } answers {
// This behavior mimics what's done in StatusPublisher#addStatusHandler
eventHandlers.add {
lambda<(ComponentState) -> Unit>().captured(it)
true
}
}
}
fun startSuccessfully() {
eventHandlers.forEach { it(ComponentState.Running) }
}
fun error(error: JibriError) {
eventHandlers.forEach { it(ComponentState.Error(error)) }
}
}
| apache-2.0 | f813a68b361c9f5c929fe63b502f45b3 | 36.485294 | 113 | 0.628351 | 4.818526 | false | false | false | false |
nsk-mironov/smuggler | smuggler-plugin/src/main/java/com/joom/smuggler/plugin/SmugglerTransform.kt | 1 | 5964 | package com.joom.smuggler.plugin
import com.android.build.api.transform.QualifiedContent
import com.android.build.api.transform.QualifiedContent.DefaultContentType
import com.android.build.api.transform.QualifiedContent.Scope
import com.android.build.api.transform.Transform
import com.android.build.api.transform.TransformInvocation
import com.joom.smuggler.compiler.SmugglerCompiler
import com.joom.smuggler.plugin.utils.TransformSet
import com.joom.smuggler.plugin.utils.TransformUnit
import com.joom.smuggler.plugin.utils.copyInputsToOutputs
import com.joom.smuggler.plugin.utils.getClasspath
import java.io.File
import java.util.EnumSet
class SmugglerTransform(
private val extension: SmugglerExtension,
private val configuration: SmugglerConfiguration
) : Transform() {
override fun transform(invocation: TransformInvocation) {
val transformSet = computePreparedTransformSet(invocation)
val adapters = computeClasspathForAdapters(transformSet, invocation)
SmugglerCompiler.create(transformSet.getClasspath(), adapters).use { compiler ->
computeTransformUnitGroups(transformSet)
.filter { it.containsModifiedUnits() }
.forEach { transformGroup ->
if (invocation.isIncremental) {
compiler.cleanup(transformGroup.output)
}
transformGroup.units.forEach { transformUnit ->
if (transformUnit.changes.status != TransformUnit.Status.REMOVED) {
compiler.compile(transformUnit.input, transformUnit.output)
}
}
}
if (configuration.verifyNoUnprocessedClasses) {
verifyNoUnprocessedClasses(invocation, compiler)
}
}
}
override fun getScopes(): MutableSet<Scope> {
return configuration.scopes.toTransformScope().toMutableSet()
}
override fun getReferencedScopes(): MutableSet<Scope> {
return configuration.referencedScopes.toTransformScope().toMutableSet()
}
override fun getInputTypes(): Set<QualifiedContent.ContentType> {
return EnumSet.of(
DefaultContentType.CLASSES
)
}
override fun getParameterInputs(): Map<String, Any> {
return mapOf(
"cacheable" to extension.cacheable,
"incremental" to extension.incremental,
"version" to BuildConfig.VERSION,
"hash" to BuildConfig.GIT_HASH,
"bootClasspath" to extension.bootClasspath
.map { it.absolutePath }
.sorted()
.joinToString()
)
}
override fun getName(): String {
return "smuggler"
}
override fun isIncremental(): Boolean {
return extension.incremental
}
override fun isCacheable(): Boolean {
return extension.cacheable
}
private fun verifyNoUnprocessedClasses(invocation: TransformInvocation, compiler: SmugglerCompiler) {
val referencedFiles = computeClasspathForUnprocessedCandidates(invocation)
val unprocessedClasses = compiler.findUnprocessedClasses(referencedFiles)
if (unprocessedClasses.isNotEmpty()) {
throw IllegalStateException(buildString {
appendLine("Found ${unprocessedClasses.size} unprocessed AutoParcelable classes.")
appendLine("Most likely you have a module that transitively depends on Smuggler Runtime, but doesn't apply Smuggler Plugin.")
appendLine("The full list of unprocessed classes:")
for (name in unprocessedClasses) {
appendLine(" - $name")
}
})
}
}
private fun computeClasspathForUnprocessedCandidates(invocation: TransformInvocation): Collection<File> {
val transformSet = TransformSet.create(invocation, emptyList())
val classpath = transformSet.getClasspath().toSet()
val scopes = setOf(Scope.SUB_PROJECTS)
val contents = ArrayList<QualifiedContent>()
val result = ArrayList<File>()
for (input in invocation.referencedInputs) {
contents.addAll(input.directoryInputs)
contents.addAll(input.jarInputs)
}
for (content in contents) {
if (scopes.any { it in content.scopes } && content.file in classpath) {
result += content.file
}
}
return result
}
private fun computeClasspathForAdapters(
transformSet: TransformSet,
transformInvocation: TransformInvocation
): Collection<File> {
val classpath = transformSet.getClasspath().toSet()
val scopes = setOf(Scope.PROJECT, Scope.SUB_PROJECTS)
val contents = ArrayList<QualifiedContent>()
val result = ArrayList<File>()
for (input in transformInvocation.referencedInputs) {
contents.addAll(input.directoryInputs)
contents.addAll(input.jarInputs)
}
for (input in transformInvocation.inputs) {
contents.addAll(input.directoryInputs)
contents.addAll(input.jarInputs)
}
for (content in contents) {
if (scopes.any { it in content.scopes } && content.file in classpath) {
result += content.file
}
}
return result
}
private fun computePreparedTransformSet(transformInvocation: TransformInvocation): TransformSet {
val transformSet = TransformSet.create(transformInvocation, extension.bootClasspath)
if (!transformInvocation.isIncremental) {
transformInvocation.outputProvider.deleteAll()
}
transformSet.copyInputsToOutputs()
return transformSet
}
private fun computeTransformUnitGroups(transformSet: TransformSet): List<TransformUnitGroup> {
return transformSet.units
.groupBy { it.output }
.map { TransformUnitGroup(it.key, it.value) }
}
private fun TransformUnitGroup.containsModifiedUnits(): Boolean {
return units.any { unit ->
when (unit.changes.status) {
TransformUnit.Status.UNKNOWN -> true
TransformUnit.Status.ADDED -> true
TransformUnit.Status.CHANGED -> true
TransformUnit.Status.REMOVED -> true
TransformUnit.Status.UNCHANGED -> false
}
}
}
private data class TransformUnitGroup(
val output: File,
val units: List<TransformUnit>
)
}
| mit | e5952af58f723ae3934d794ae8e6a7e2 | 31.237838 | 133 | 0.716968 | 4.601852 | false | false | false | false |
actioninja/BurningSun | src/main/kotlin/actioninja/burningsun/BurningSun.kt | 1 | 2051 | package actioninja.burningsun
import actioninja.burningsun.item.ItemRegistry
import actioninja.burningsun.item.LootManager
import actioninja.burningsun.item.RecipeManager
import actioninja.burningsun.potion.PotionRegistry
import net.minecraftforge.common.MinecraftForge
import net.minecraftforge.fml.common.Loader
import net.minecraftforge.fml.common.Mod
import net.minecraftforge.fml.common.event.FMLInitializationEvent
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent
import net.minecraftforge.fml.relauncher.Side
import net.minecraftforge.fml.relauncher.SideOnly
import org.apache.logging.log4j.LogManager
/**
* Created by actioninja on 5/1/17.
*/
@Mod(modid = BurningSun.MODID, name = "Burning Sun", version = BurningSun.VERSION, modLanguageAdapter = "net.shadowfacts.forgelin.KotlinAdapter", dependencies = "required-after:forgelin@[1.3.1,);")
object BurningSun
{
const val MODID = "burningsun"
const val VERSION = "@VERSION@"
var log = LogManager.getLogger(MODID)
@Mod.EventHandler
fun preInit(event:FMLPreInitializationEvent)
{
BurningSunConfig.preInit(event.suggestedConfigurationFile)
MinecraftForge.EVENT_BUS.register(BurningSunEventHandler())
PotionRegistry.init()
ItemRegistry.initCommon()
if (Loader.isModLoaded("baubles") && BurningSunConfig.baublesIntegrationEnabled)
MinecraftForge.EVENT_BUS.register(LootManager())
}
@Mod.EventHandler
@SideOnly(Side.CLIENT)
fun preInitClient(event:FMLPreInitializationEvent)
{
ItemRegistry.initClient()
BurningSunConfig.preInitClient()
}
@Mod.EventHandler
fun init(event:FMLInitializationEvent)
{
if (Loader.isModLoaded("baubles") && BurningSunConfig.baublesIntegrationEnabled)
RecipeManager.initRecipes()
}
fun prependModId(string:String):String
{
return MODID + ":" + string
}
fun debugLog(string:String)
{
if (BurningSunConfig.debugLogging)
log.info(string)
}
} | gpl-3.0 | 33e44c25018da779fff688af29a95fb3 | 30.569231 | 197 | 0.740127 | 4.021569 | false | true | false | false |
JavaEden/OrchidCore | OrchidCore/src/main/kotlin/com/eden/orchid/impl/generators/SitemapGenerator.kt | 1 | 3939 | package com.eden.orchid.impl.generators
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.generators.OrchidCollection
import com.eden.orchid.api.generators.OrchidGenerator
import com.eden.orchid.api.options.annotations.BooleanDefault
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.theme.pages.OrchidPage
import java.util.ArrayList
import java.util.stream.Stream
import javax.inject.Inject
@Description(value = "Generate a sitemap and `robots.txt` for automatic SEO.", name = "Sitemap and Robots.txt")
class SitemapGenerator @Inject
constructor(context: OrchidContext) : OrchidGenerator(context,
GENERATOR_KEY, OrchidGenerator.PRIORITY_LATE + 1) {
@Option
@BooleanDefault(true)
@Description("Whether to generate sitemaps.")
var useSitemaps: Boolean = true
@Option
@BooleanDefault(true)
@Description("Whether to generate a robots.txt, which includes a link to the sitemap.")
var useRobots: Boolean = true
override fun startIndexing(): List<OrchidPage>? {
return null
}
override fun startGeneration(pages: Stream<out OrchidPage>) {
generateSitemapFiles()
}
private fun generateSitemapFiles() {
var sitemapIndex: SitemapIndexPage? = null
if (useSitemaps) {
val mappedIndex = context.internalIndex.allIndexedPages
val sitemapPages = ArrayList<SitemapPage>()
// Render an page for each generator's individual index
mappedIndex.keys.forEach { key ->
val pages = mappedIndex[key]?.allPages
val page = SitemapPage(context, key, pages)
sitemapPages.add(page)
context.renderRaw(page)
}
// Render an index of all indices, so individual index pages can be found
sitemapIndex = SitemapIndexPage(context, sitemapPages)
context.renderRaw(sitemapIndex)
}
if (useRobots) {
// Render the robots.txt
val robotsPage = RobotsPage(context, sitemapIndex)
context.renderRaw(robotsPage)
}
}
override fun getCollections(): List<OrchidCollection<*>>? {
return null
}
@Description(value = "The sitemap for a section of your site, grouped by generator.", name = "Sitemap")
class SitemapPage internal constructor(context: OrchidContext, key: String, val entries: List<OrchidPage>?) :
OrchidPage(context.getResourceEntry("sitemap.xml.peb"), "sitemap", "Sitemap") {
init {
this.reference.fileName = "sitemap-$key"
this.reference.path = ""
this.reference.outputExtension = "xml"
this.reference.isUsePrettyUrl = false
}
}
@Description(value = "The root sitemap, with links to all individual sitemaps.", name = "Sitemap Index")
class SitemapIndexPage internal constructor(context: OrchidContext, val sitemaps: List<SitemapPage>) :
OrchidPage(context.getResourceEntry("sitemapIndex.xml.peb"), "sitemapIndex", "Sitemap Index") {
init {
this.reference.fileName = "sitemap"
this.reference.path = ""
this.reference.outputExtension = "xml"
this.reference.isUsePrettyUrl = false
}
}
@Description(value = "Your site's robots.txt file, for directing web crawlers.", name = "Robots.txt")
class RobotsPage internal constructor(context: OrchidContext, val sitemap: SitemapIndexPage?) :
OrchidPage(context.getResourceEntry("robots.txt.peb"), "robots", "Robots") {
init {
this.reference.fileName = "robots"
this.reference.path = ""
this.reference.outputExtension = "txt"
this.reference.isUsePrettyUrl = false
}
}
companion object {
val GENERATOR_KEY = "sitemap"
}
}
| mit | fe28621914f9344ef3f8bfeba29f305b | 36.875 | 113 | 0.663874 | 4.538018 | false | false | false | false |
xfournet/intellij-community | java/java-impl/src/com/intellij/lang/java/request/createFieldFromUsage.kt | 1 | 4818 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("CreateFieldFromUsage")
package com.intellij.lang.java.request
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFieldFromUsageFix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.java.actions.toJavaClassOrNull
import com.intellij.lang.jvm.JvmClass
import com.intellij.lang.jvm.JvmClassKind
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.actions.CreateFieldRequest
import com.intellij.lang.jvm.actions.EP_NAME
import com.intellij.lang.jvm.actions.groupActionsByType
import com.intellij.psi.*
import com.intellij.psi.util.PsiUtil.resolveClassInClassTypeOnly
import com.intellij.psi.util.parentOfType
fun generateActions(ref: PsiReferenceExpression): List<IntentionAction> {
if (!checkReference(ref)) return emptyList()
val fieldRequests = CreateFieldRequests(ref).collectRequests()
val extensions = EP_NAME.extensions
return fieldRequests.flatMap { (clazz, request) ->
extensions.flatMap { ext ->
ext.createAddFieldActions(clazz, request)
}
}.groupActionsByType()
}
private fun checkReference(ref: PsiReferenceExpression): Boolean {
if (ref.referenceName == null) return false
if (ref.parent is PsiMethodCallExpression) return false
return true
}
private class CreateFieldRequests(val myRef: PsiReferenceExpression) {
private val requests = LinkedHashMap<JvmClass, CreateFieldRequest>()
fun collectRequests(): Map<JvmClass, CreateFieldRequest> {
doCollectRequests()
return requests
}
private fun doCollectRequests() {
val qualifier = myRef.qualifierExpression
if (qualifier != null) {
val instanceClass = resolveClassInClassTypeOnly(qualifier.type)
if (instanceClass != null) {
processHierarchy(instanceClass)
}
else {
val staticClass = (qualifier as? PsiJavaCodeReferenceElement)?.resolve() as? PsiClass
if (staticClass != null) {
processClass(staticClass, true)
}
}
}
else {
val baseClass = extractBaseClassFromSwitchStatement()
if (baseClass != null) {
processHierarchy(baseClass)
}
else {
processOuterAndImported()
}
}
}
private fun extractBaseClassFromSwitchStatement(): PsiClass? {
val parent = myRef.parent as? PsiSwitchLabelStatement ?: return null
val switchStatement = parent.parentOfType<PsiSwitchStatement>() ?: return null
return resolveClassInClassTypeOnly(switchStatement.expression?.type)
}
private fun processHierarchy(baseClass: PsiClass) {
for (clazz in hierarchy(baseClass)) {
processClass(clazz, false)
}
}
private fun processOuterAndImported() {
val inStaticContext = myRef.isInStaticContext()
for (outerClass in collectOuterClasses(myRef)) {
processClass(outerClass, inStaticContext)
}
for (imported in collectOnDemandImported(myRef)) {
processClass(imported, true)
}
}
private fun processClass(target: JvmClass, staticContext: Boolean) {
if (!staticContext && target.classKind in STATIC_ONLY) return
val modifiers = mutableSetOf<JvmModifier>()
if (staticContext) {
modifiers += JvmModifier.STATIC
}
if (shouldCreateFinalField(myRef, target)) {
modifiers += JvmModifier.FINAL
}
val ownerClass = myRef.parentOfType<PsiClass>()
val visibility = computeVisibility(myRef.project, ownerClass, target)
if (visibility != null) {
modifiers += visibility
}
val request = CreateFieldFromJavaUsageRequest(
modifiers = modifiers,
reference = myRef,
useAnchor = target.toJavaClassOrNull() == ownerClass,
constant = false
)
requests[target] = request
}
}
private val STATIC_ONLY = arrayOf(JvmClassKind.INTERFACE, JvmClassKind.ANNOTATION)
/**
* Given unresolved unqualified reference,
* this reference could be resolved into static member if some class which has it's members imported.
*
* @return list of classes from static on demand imports.
*/
private fun collectOnDemandImported(place: PsiElement): List<JvmClass> {
val containingFile = place.containingFile as? PsiJavaFile ?: return emptyList()
val importList = containingFile.importList ?: return emptyList()
val onDemandImports = importList.importStaticStatements.filter { it.isOnDemand }
if (onDemandImports.isEmpty()) return emptyList()
return onDemandImports.mapNotNull { it.resolveTargetClass() }
}
private fun shouldCreateFinalField(ref: PsiReferenceExpression, targetClass: JvmClass): Boolean {
val javaClass = targetClass.toJavaClassOrNull() ?: return false
return CreateFieldFromUsageFix.shouldCreateFinalMember(ref, javaClass)
}
| apache-2.0 | 6c73f1be23c17a7adf824f3c0f22778a | 33.170213 | 140 | 0.740141 | 4.718903 | false | false | false | false |
AerisG222/maw_photos_android | MaWPhotos/src/main/java/us/mikeandwan/photos/di/NotificationModule.kt | 1 | 2709 | package us.mikeandwan.photos.di
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.graphics.Color
import android.media.AudioAttributes
import android.media.RingtoneManager
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import us.mikeandwan.photos.R
import us.mikeandwan.photos.utils.NOTIFICATION_CHANNEL_ID_NEW_CATEGORIES
import us.mikeandwan.photos.utils.NOTIFICATION_CHANNEL_ID_UPLOAD_FILES
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class NotificationModule {
@Provides
@Singleton
fun provideNotificationManager(app: Application): NotificationManager {
val notificationManager = app.getSystemService(Application.NOTIFICATION_SERVICE) as NotificationManager
addNewCategoriesNotificationChannel(app, notificationManager)
addUploadNotificationChannel(app, notificationManager)
return notificationManager
}
private fun addNewCategoriesNotificationChannel(
app: Application,
notificationManager: NotificationManager
) {
val name = app.getString(R.string.channel_name_new_categories)
val description = app.getString(R.string.channel_description_new_categories)
createChannel(notificationManager, name, description, NOTIFICATION_CHANNEL_ID_NEW_CATEGORIES)
}
private fun addUploadNotificationChannel(
app: Application,
notificationManager: NotificationManager
) {
val name = app.getString(R.string.channel_name_upload)
val description = app.getString(R.string.channel_description_upload)
createChannel(notificationManager, name, description, NOTIFICATION_CHANNEL_ID_UPLOAD_FILES)
}
private fun createChannel(
notificationManager: NotificationManager,
name: String,
description: String,
channelId: String
) {
val audioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build()
val channel = NotificationChannel(
channelId,
name,
NotificationManager.IMPORTANCE_DEFAULT
)
channel.description = description
channel.enableLights(true)
channel.enableVibration(true)
channel.vibrationPattern = longArrayOf(300, 300)
channel.lightColor = Color.argb(255, 75, 0, 130)
channel.setSound(
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION),
audioAttributes
)
notificationManager.createNotificationChannel(channel)
}
} | mit | c6841cd0fb297c4629934e3d5b9467ff | 32.875 | 111 | 0.731635 | 5.280702 | false | false | false | false |
google/ksp | gradle-plugin/src/main/kotlin/com/google/devtools/ksp/gradle/model/builder/KspModelBuilder.kt | 1 | 1539 | /*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.gradle.model.builder
import com.google.devtools.ksp.gradle.KspExtension
import com.google.devtools.ksp.gradle.model.Ksp
import com.google.devtools.ksp.gradle.model.impl.KspImpl
import org.gradle.api.Project
import org.gradle.tooling.provider.model.ToolingModelBuilder
/**
* [ToolingModelBuilder] for [Ksp] models.
* This model builder is registered for Kotlin All Open sub-plugin.
*/
class KspModelBuilder : ToolingModelBuilder {
override fun canBuild(modelName: String): Boolean {
return modelName == Ksp::class.java.name
}
override fun buildAll(modelName: String, project: Project): Any? {
if (modelName == Ksp::class.java.name) {
val extension = project.extensions.getByType(KspExtension::class.java)
return KspImpl(project.name)
}
return null
}
}
| apache-2.0 | 863d456b22b8a4c2bf8962b6378f1982 | 34.790698 | 85 | 0.733593 | 4.126005 | false | false | false | false |
mmorihiro/larger-circle | core/src/mmorihiro/matchland/view/ImageLoader.kt | 2 | 782 | package mmorihiro.matchland.view
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.scenes.scene2d.ui.Image
import ktx.assets.asset
class ImageLoader(private val size: Int, filePath: String) {
private val sheet = asset<Texture>(filePath)
private val tiles: Array<Array<TextureRegion>> =
TextureRegion.split(sheet, size, size)
fun load(position: Pair<Int, Int>): MyImage {
val (x, y) = position
return MyImage(Image(tiles[x][y]), x to y)
}
fun loadRandom(): MyImage {
val row = sheet.width / size
val col = sheet.height / size
return load(MathUtils.random(col - 1) to MathUtils.random(row - 1))
}
} | apache-2.0 | e25828518289f32781ec591757662c49 | 30.32 | 75 | 0.686701 | 3.741627 | false | false | false | false |
quarkusio/quarkus | integration-tests/mongodb-panache-kotlin/src/main/kotlin/io/quarkus/it/mongodb/panache/person/resources/PersonEntityResource.kt | 1 | 2527 | package io.quarkus.it.mongodb.panache.person.resources
import com.mongodb.ReadPreference
import io.quarkus.it.mongodb.panache.person.PersonEntity
import io.quarkus.it.mongodb.panache.person.PersonName
import io.quarkus.it.mongodb.panache.person.Status
import io.quarkus.panache.common.Sort
import java.net.URI
import javax.ws.rs.DELETE
import javax.ws.rs.GET
import javax.ws.rs.PATCH
import javax.ws.rs.POST
import javax.ws.rs.PUT
import javax.ws.rs.Path
import javax.ws.rs.PathParam
import javax.ws.rs.QueryParam
import javax.ws.rs.core.Response
@Path("/persons/entity")
class PersonEntityResource {
@GET
fun getPersons(@QueryParam("sort") sort: String?): List<PersonEntity> =
sort?.let { PersonEntity.listAll(Sort.ascending(sort)) }
?: PersonEntity.listAll()
@GET
@Path("/search/{name}")
fun searchPersons(@PathParam("name") name: String): Set<PersonName> {
return PersonEntity.find("lastname = ?1 and status = ?2", name, Status.ALIVE)
.project(PersonName::class.java)
.withReadPreference(ReadPreference.primaryPreferred())
.list()
.toSet()
}
@POST
fun addPerson(person: PersonEntity): Response {
person.persist()
return Response.created(URI.create("/persons/entity/${person.id}")).build()
}
@POST
@Path("/multiple")
fun addPersons(persons: List<PersonEntity>) {
PersonEntity.persist(persons)
}
@PUT
fun updatePerson(person: PersonEntity): Response {
person.update()
return Response.accepted().build()
}
// PATCH is not correct here but it allows to test persistOrUpdate without a specific subpath
@PATCH
fun upsertPerson(person: PersonEntity): Response {
person.persistOrUpdate()
return Response.accepted().build()
}
@DELETE
@Path("/{id}")
fun deletePerson(@PathParam("id") id: String) {
PersonEntity.deleteById(id.toLong())
}
@GET
@Path("/{id}")
fun getPerson(@PathParam("id") id: String) = PersonEntity.findById(id.toLong())
@GET
@Path("/count")
fun countAll(): Long = PersonEntity.count()
@DELETE
fun deleteAll() {
PersonEntity.deleteAll()
}
@POST
@Path("/rename")
fun rename(@QueryParam("previousName") previousName: String, @QueryParam("newName") newName: String): Response {
PersonEntity.update("lastname", newName)
.where("lastname", previousName)
return Response.ok().build()
}
}
| apache-2.0 | 60bc5c68d5b960ffe5809da44de84ebc | 28.045977 | 116 | 0.661654 | 3.985804 | false | false | false | false |
MyDogTom/detekt | detekt-sample-extensions/src/test/kotlin/io/gitlab/arturbosch/detekt/sample/extensions/processors/QualifiedNameProcessorTest.kt | 1 | 1778 | package io.gitlab.arturbosch.detekt.sample.extensions.processors
import io.gitlab.arturbosch.detekt.api.Detektion
import io.gitlab.arturbosch.detekt.api.Finding
import io.gitlab.arturbosch.detekt.api.Notification
import io.gitlab.arturbosch.detekt.api.ProjectMetric
import io.gitlab.arturbosch.detekt.test.compileContentForTest
import org.assertj.core.api.Assertions
import org.jetbrains.kotlin.com.intellij.openapi.util.Key
import org.jetbrains.kotlin.com.intellij.util.keyFMap.KeyFMap
import org.junit.jupiter.api.Test
/**
* @author Artur Bosch
*/
internal class QualifiedNameProcessorTest {
@Test
fun fqNamesOfTestFiles() {
val ktFile = compileContentForTest(code)
val processor = QualifiedNameProcessor()
processor.onProcess(ktFile)
processor.onFinish(listOf(ktFile), result)
val data = result.getData(FQ_NAMES_KEY)
Assertions.assertThat(data).contains(
"io.gitlab.arturbosch.detekt.sample.Foo",
"io.gitlab.arturbosch.detekt.sample.Bar",
"io.gitlab.arturbosch.detekt.sample.Bla")
}
}
val result = object : Detektion {
override val findings: Map<String, List<Finding>> = mapOf()
override val notifications: Collection<Notification> = listOf()
override val metrics: Collection<ProjectMetric> = listOf()
private var userData = KeyFMap.EMPTY_MAP
override fun <V> getData(key: Key<V>): V? = userData.get(key)
override fun <V> addData(key: Key<V>, value: V) {
userData = userData.plus(key, value)
}
override fun add(notification: Notification) {
throw UnsupportedOperationException("not implemented")
}
override fun add(projectMetric: ProjectMetric) {
throw UnsupportedOperationException("not implemented")
}
}
val code = """
package io.gitlab.arturbosch.detekt.sample
class Foo {}
object Bar {}
interface Bla {}
"""
| apache-2.0 | 6ab522ff7056158db99286963addcb7f | 27.677419 | 64 | 0.767154 | 3.584677 | false | true | false | false |
square/moshi | moshi/src/main/java16/com/squareup/moshi/RecordJsonAdapter.kt | 1 | 5782 | /*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.squareup.moshi
import com.squareup.moshi.internal.jsonAnnotations
import com.squareup.moshi.internal.jsonName
import com.squareup.moshi.internal.knownNotNull
import com.squareup.moshi.internal.missingProperty
import com.squareup.moshi.internal.resolve
import com.squareup.moshi.internal.rethrowCause
import java.lang.invoke.MethodHandle
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType.methodType
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.ParameterizedType
import java.lang.reflect.RecordComponent
import java.lang.reflect.Type
/**
* A [JsonAdapter] that supports Java `record` classes via reflection.
*
* **NOTE:** Java records require JDK 16 or higher.
*/
internal class RecordJsonAdapter<T>(
private val constructor: MethodHandle,
private val targetClass: String,
componentBindings: Map<String, ComponentBinding<Any>>
) : JsonAdapter<T>() {
data class ComponentBinding<T>(
val componentName: String,
val jsonName: String,
val adapter: JsonAdapter<T>,
val accessor: MethodHandle
)
private val componentBindingsArray = componentBindings.values.toTypedArray()
private val options = JsonReader.Options.of(*componentBindings.keys.toTypedArray())
override fun fromJson(reader: JsonReader): T? {
val resultsArray = arrayOfNulls<Any>(componentBindingsArray.size)
reader.beginObject()
while (reader.hasNext()) {
val index = reader.selectName(options)
if (index == -1) {
reader.skipName()
reader.skipValue()
continue
}
resultsArray[index] = componentBindingsArray[index].adapter.fromJson(reader)
}
reader.endObject()
return try {
@Suppress("UNCHECKED_CAST")
constructor.invokeWithArguments(*resultsArray) as T
} catch (e: InvocationTargetException) {
throw e.rethrowCause()
} catch (e: Throwable) {
// Don't throw a fatal error if it's just an absent primitive.
for (i in componentBindingsArray.indices) {
if (resultsArray[i] == null && componentBindingsArray[i].accessor.type().returnType().isPrimitive) {
throw missingProperty(
propertyName = componentBindingsArray[i].componentName,
jsonName = componentBindingsArray[i].jsonName,
reader = reader
)
}
}
throw AssertionError(e)
}
}
override fun toJson(writer: JsonWriter, value: T?) {
writer.beginObject()
for (binding in componentBindingsArray) {
writer.name(binding.jsonName)
val componentValue = try {
binding.accessor.invoke(value)
} catch (e: InvocationTargetException) {
throw e.rethrowCause()
} catch (e: Throwable) {
throw AssertionError(e)
}
binding.adapter.toJson(writer, componentValue)
}
writer.endObject()
}
override fun toString() = "JsonAdapter($targetClass)"
companion object Factory : JsonAdapter.Factory {
private val VOID_CLASS = knownNotNull(Void::class.javaPrimitiveType)
override fun create(type: Type, annotations: Set<Annotation>, moshi: Moshi): JsonAdapter<*>? {
if (annotations.isNotEmpty()) {
return null
}
if (type !is Class<*> && type !is ParameterizedType) {
return null
}
val rawType = type.rawType
if (!rawType.isRecord) {
return null
}
val components = rawType.recordComponents
val bindings = LinkedHashMap<String, ComponentBinding<Any>>()
val lookup = MethodHandles.lookup()
val componentRawTypes = Array<Class<*>>(components.size) { i ->
val component = components[i]
val componentBinding =
createComponentBinding(type, rawType, moshi, lookup, component)
val replaced = bindings.put(componentBinding.jsonName, componentBinding)
if (replaced != null) {
throw IllegalArgumentException(
"Conflicting components:\n ${replaced.componentName}\n ${componentBinding.componentName}"
)
}
component.type
}
val constructor = try {
lookup.findConstructor(rawType, methodType(VOID_CLASS, componentRawTypes))
} catch (e: NoSuchMethodException) {
throw AssertionError(e)
} catch (e: IllegalAccessException) {
throw AssertionError(e)
}
return RecordJsonAdapter<Any>(constructor, rawType.simpleName, bindings).nullSafe()
}
private fun createComponentBinding(
type: Type,
rawType: Class<*>,
moshi: Moshi,
lookup: MethodHandles.Lookup,
component: RecordComponent
): ComponentBinding<Any> {
val componentName = component.name
val jsonName = component.jsonName(componentName)
val componentType = component.genericType.resolve(type, rawType)
val qualifiers = component.jsonAnnotations
val adapter = moshi.adapter<Any>(componentType, qualifiers)
val accessor = try {
lookup.unreflect(component.accessor)
} catch (e: IllegalAccessException) {
throw AssertionError(e)
}
return ComponentBinding(componentName, jsonName, adapter, accessor)
}
}
}
| apache-2.0 | 2b46649b90ddd3e9e1eca56ab8445a60 | 31.852273 | 108 | 0.687997 | 4.58525 | false | false | false | false |
http4k/http4k | http4k-jsonrpc/src/main/kotlin/org/http4k/jsonrpc/ErrorMessage.kt | 1 | 793 | package org.http4k.jsonrpc
import org.http4k.format.Json
open class ErrorMessage(val code: Int, val message: String) {
open fun <NODE> data(json: Json<NODE>): NODE? = null
operator fun <NODE> invoke(json: Json<NODE>): NODE = json {
val fields = listOf("code" to number(code), "message" to string(message))
val data = data(json)
json.obj(data?.let { fields + ("data" to it) } ?: fields)
}
companion object {
val InvalidRequest = ErrorMessage(-32600, "Invalid Request")
val MethodNotFound = ErrorMessage(-32601, "Method not found")
val InvalidParams = ErrorMessage(-32602, "Invalid params")
val InternalError = ErrorMessage(-32603, "Internal error")
val ParseError = ErrorMessage(-32700, "Parse error")
}
}
| apache-2.0 | b8d1195ee42a4f7fa5411e7bd481a318 | 36.761905 | 81 | 0.650694 | 3.887255 | false | false | false | false |
jpmoreto/play-with-robots | android/lib/src/main/java/jpm/lib/graph/graphs/WeightedSpaceGraph.kt | 1 | 4584 | package jpm.lib.graph.graphs
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet
import jpm.lib.math.DoubleVector2D
import java.util.*
/**
* Created by jm on 22/03/17.
*
*/
object WeightedSpaceGraph {
class Node(val p1: DoubleVector2D, val p2: DoubleVector2D, val middlePoint: DoubleVector2D): WeightedGraphAbs.Node<Node,Arc> {
override fun setVisited(isVisited: Boolean) {
visited_ = isVisited
}
override fun getVisited(): Boolean = visited_
override fun getMinCost(): Double = minCost_
override fun setMinCost(cost: Double) {
minCost_ = cost
}
override fun setMinCostArc(arc: Arc) {
minCostArc_ = arc
}
override fun getMinCostToEndNode(): Double = minCostToEndNode_
val arcs = ObjectOpenHashSet<Arc>(53)
var visited_ = false
var minCost_: Double = Double.POSITIVE_INFINITY
var minCostArc_: Arc? = null
var minCostToEndNode_: Double = 0.0
override fun reset(endNode: Node) {
minCost_ = Double.POSITIVE_INFINITY
minCostArc_ = null
visited_ = false
minCostToEndNode_ = (middlePoint - endNode.middlePoint).length()
}
override fun add(arc: Arc): Node {
arcs.add(arc)
return this
}
fun from(): Node? {
if(minCostArc_ == null) return null
return minCostArc_!!.startNode
}
override fun toString(): String {
val from = if(minCostArc_ != null) minCostArc_!!.startNode.middlePoint else ""
return "Node(name='$middlePoint', visited=$visited_, from=$from, minCost=$minCost_, totalCost=${minCost_ + minCostToEndNode_})"
}
}
class Arc(startNode: Node, endNode: Node, weight: Double) : WeightedGraphAbs.Arc<Node,Arc>(startNode,endNode,weight) {
init {
startNode.add(this)
}
override fun weight() = weight
override fun equals(other: Any?): Boolean {
if(other is Arc) {
return startNode === other.startNode && endNode == other.endNode
}
return false
}
override fun hashCode(): Int
= startNode.hashCode().xor(endNode.hashCode())
override fun toString(): String
= "Arc(startNode=$startNode, endNode=$endNode, weight=$weight)"
}
/*
object ArcComparator: Comparator<Arc> {
override fun compare(a0: Arc, a1: Arc): Int {
return NodeComparator.compare(a0.endNode,a1.endNode)
}
}
*/
object NodeComparator: Comparator<Node> {
override fun compare(a0: Node, a1: Node): Int
= DoubleVector2DComparator.compare(a0.middlePoint,a1.middlePoint)
}
private object DoubleVector2DComparator : Comparator<DoubleVector2D> {
override fun compare(p0: DoubleVector2D, p1: DoubleVector2D): Int {
if(p0.x < p1.x - 1E-20) return -1
if(p0.x > p1.x + 1E-20) return 1
if(p0.y < p1.y - 1E-20) return -1
if(p0.y > p1.y + 1E-20) return 1
return 0
}
}
class Graph: WeightedGraphAbs.Graph<Graph,Node,Arc> {
val nodes = TreeMap<DoubleVector2D,Node>(DoubleVector2DComparator)
var startNode: Node? = null
var endNode: Node? = null
operator fun get(nodeName: DoubleVector2D): Node? = nodes[nodeName]
override fun nodes(): Set<Node> {
return nodes.map { it.value }.toSet()
}
override fun startNodes(): Set<Node> {
return if(startNode != null) setOf(startNode!!) else setOf<Node>()
}
override fun endNodes(): Set<Node> {
return if(endNode != null) setOf(endNode!!) else setOf<Node>()
}
override fun add(node: Node): Graph {
nodes.put(node.middlePoint,node)
return this
}
override fun add(arc: Arc): Graph {
add(arc.startNode)
add(arc.endNode)
return this
}
override fun startAdd(node: Node): Graph {
startNode = node
return this
}
override fun endAdd(node: Node): Graph {
endNode = node
return this
}
override fun outArcs(node: Node): Set<Arc> = node.arcs
override fun inArcs(node: Node): Set<Arc> = node.arcs
override fun toString(): String {
return "Graph(nodes=${nodes().sortedBy { it.middlePoint }})"
}
}
} | mit | 5ff164e9ebf84669ba3d6c51804306bf | 28.203822 | 139 | 0.572426 | 4.20165 | false | false | false | false |
moltendorf/IntelliDoors | src/main/kotlin/net/moltendorf/bukkit/intellidoors/CanonicalSet.kt | 1 | 288 | package net.moltendorf.bukkit.intellidoors
import java.util.*
class CanonicalSet<T> {
private val map = HashMap<T, T>()
operator fun get(key : T) : T {
val cached = map[key]
return if (cached == null) {
map[key] = key
key
} else {
cached
}
}
}
| mit | fb4ae07cef8c60ddc1e721e4749e90c2 | 15 | 42 | 0.576389 | 3.164835 | false | false | false | false |
openMF/android-client | mifosng-android/src/main/java/com/mifos/mifosxdroid/online/loanaccount/LoanAccountFragment.kt | 1 | 29195 | /*
* This project is licensed under the open source MPL V2.
* See https://github.com/openMF/android-client/blob/master/LICENSE.md
*/
package com.mifos.mifosxdroid.online.loanaccount
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import android.widget.AdapterView.OnItemSelectedListener
import androidx.fragment.app.DialogFragment
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.mifos.mifosxdroid.R
import com.mifos.mifosxdroid.core.MifosBaseActivity
import com.mifos.mifosxdroid.core.ProgressableDialogFragment
import com.mifos.mifosxdroid.core.util.Toaster
import com.mifos.mifosxdroid.online.datatablelistfragment.DataTableListFragment
import com.mifos.mifosxdroid.uihelpers.MFDatePicker
import com.mifos.mifosxdroid.uihelpers.MFDatePicker.OnDatePickListener
import com.mifos.objects.accounts.loan.Loans
import com.mifos.objects.organisation.LoanProducts
import com.mifos.objects.templates.loans.LoanTemplate
import com.mifos.objects.templates.loans.RepaymentFrequencyDaysOfWeekTypeOptions
import com.mifos.objects.templates.loans.RepaymentFrequencyNthDayTypeOptions
import com.mifos.services.data.LoansPayload
import com.mifos.utils.Constants
import com.mifos.utils.DateHelper
import com.mifos.utils.FragmentConstants
import java.util.*
import javax.inject.Inject
import kotlin.properties.Delegates
/**
* Created by nellyk on 1/22/2016.
*
*
* Use this Fragment to Create and/or Update loan
*/
class LoanAccountFragment : ProgressableDialogFragment(), OnDatePickListener, LoanAccountMvpView, OnItemSelectedListener {
val LOG_TAG = javaClass.simpleName
lateinit var rootView: View
@kotlin.jvm.JvmField
@BindView(R.id.sp_lproduct)
var spLoanProduct: Spinner? = null
@kotlin.jvm.JvmField
@BindView(R.id.sp_loan_purpose)
var spLoanPurpose: Spinner? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_submittedon_date)
var tvSubmittedOnDate: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.et_client_external_id)
var etClientExternalId: EditText? = null
@kotlin.jvm.JvmField
@BindView(R.id.et_principal)
var etPrincipal: EditText? = null
@kotlin.jvm.JvmField
@BindView(R.id.sp_linking_options)
var spLinkingOptions: Spinner? = null
@kotlin.jvm.JvmField
@BindView(R.id.et_loanterm)
var etLoanTerm: EditText? = null
@kotlin.jvm.JvmField
@BindView(R.id.et_numberofrepayments)
var etNumberOfRepayments: EditText? = null
@kotlin.jvm.JvmField
@BindView(R.id.et_repaidevery)
var etRepaidEvery: EditText? = null
@kotlin.jvm.JvmField
@BindView(R.id.sp_payment_periods)
var spPaymentPeriods: Spinner? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_repaid_nthfreq_label_on)
var tvRepaidNthFreqLabelOn: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.sp_repayment_freq_nth_day)
var spRepaymentFreqNthDay: Spinner? = null
@kotlin.jvm.JvmField
@BindView(R.id.sp_loan_term_periods)
var spLoanTermFrequencyType: Spinner? = null
@kotlin.jvm.JvmField
@BindView(R.id.sp_repayment_freq_day_of_week)
var spRepaymentFreqDayOfWeek: Spinner? = null
@kotlin.jvm.JvmField
@BindView(R.id.et_nominal_interest_rate)
var etNominalInterestRate: EditText? = null
@kotlin.jvm.JvmField
@BindView(R.id.tv_nominal_rate_year_month)
var tvNominalRatePerYearMonth: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.sp_amortization)
var spAmortization: Spinner? = null
@kotlin.jvm.JvmField
@BindView(R.id.sp_interestcalculationperiod)
var spInterestCalculationPeriod: Spinner? = null
@kotlin.jvm.JvmField
@BindView(R.id.sp_repaymentstrategy)
var spRepaymentStrategy: Spinner? = null
@kotlin.jvm.JvmField
@BindView(R.id.sp_interest_type)
var spInterestType: Spinner? = null
@kotlin.jvm.JvmField
@BindView(R.id.sp_loan_officer)
var spLoanOfficer: Spinner? = null
@kotlin.jvm.JvmField
@BindView(R.id.sp_fund)
var spFund: Spinner? = null
@BindView(R.id.cb_calculateinterest)
lateinit var cbCalculateInterest: CheckBox
@kotlin.jvm.JvmField
@BindView(R.id.tv_disbursementon_date)
var tvDisbursementOnDate: TextView? = null
@kotlin.jvm.JvmField
@BindView(R.id.btn_loan_submit)
var btnLoanSubmit: Button? = null
@kotlin.jvm.JvmField
@Inject
var mLoanAccountPresenter: LoanAccountPresenter? = null
var submissionDate: String? = null
var disbursementDate: String? = null
private var hasDataTables = false
private var mfDatePicker: DialogFragment? = null
private var productId = 0
private var clientId = 0
private var loanPurposeId = 0
private var loanTermFrequency = 0
private val loanTermFrequencyType = 0
private var termFrequency: Int? = null
private var repaymentEvery: Int? = null
private var transactionProcessingStrategyId = 0
private var amortizationTypeId = 0
private var interestCalculationPeriodTypeId = 0
private var fundId by Delegates.notNull<Int>()
private var loanOfficerId = 0
private var interestTypeId = 0
private var repaymentFrequencyNthDayType: Int? = null
private var repaymentFrequencyDayOfWeek: Int? = null
private var interestRatePerPeriod: Double? = null
private var linkAccountId: Int? = null
private var isDisbursebemntDate = false
private var isSubmissionDate = false
var mLoanProducts: List<LoanProducts> = ArrayList()
var mRepaymentFrequencyNthDayTypeOptions: List<RepaymentFrequencyNthDayTypeOptions> = ArrayList()
var mRepaymentFrequencyDaysOfWeekTypeOptions: List<RepaymentFrequencyDaysOfWeekTypeOptions> = ArrayList()
var mLoanTemplate = LoanTemplate()
var mListLoanProducts: MutableList<String> = ArrayList()
var mListLoanPurposeOptions: MutableList<String> = ArrayList()
var mListAccountLinkingOptions: MutableList<String> = ArrayList()
var mListAmortizationTypeOptions: MutableList<String> = ArrayList()
var mListInterestCalculationPeriodTypeOptions: MutableList<String> = ArrayList()
var mListTransactionProcessingStrategyOptions: MutableList<String> = ArrayList()
var mListTermFrequencyTypeOptions: MutableList<String> = ArrayList()
var mListLoanTermFrequencyTypeOptions: MutableList<String> = ArrayList()
var mListRepaymentFrequencyNthDayTypeOptions: MutableList<String> = ArrayList()
var mListRepaymentFrequencyDayOfWeekTypeOptions: MutableList<String> = ArrayList()
var mListLoanFundOptions: MutableList<String> = ArrayList()
var mListLoanOfficerOptions: MutableList<String> = ArrayList()
var mListInterestTypeOptions: MutableList<String> = ArrayList()
var mLoanProductAdapter: ArrayAdapter<String>? = null
var mLoanPurposeOptionsAdapter: ArrayAdapter<String>? = null
var mAccountLinkingOptionsAdapter: ArrayAdapter<String>? = null
var mAmortizationTypeOptionsAdapter: ArrayAdapter<String>? = null
var mInterestCalculationPeriodTypeOptionsAdapter: ArrayAdapter<String>? = null
var mTransactionProcessingStrategyOptionsAdapter: ArrayAdapter<String>? = null
var mTermFrequencyTypeOptionsAdapter: ArrayAdapter<String>? = null
var mLoanTermFrequencyTypeAdapter: ArrayAdapter<String>? = null
var mRepaymentFrequencyNthDayTypeOptionsAdapter: ArrayAdapter<String>? = null
var mRepaymentFrequencyDayOfWeekTypeOptionsAdapter: ArrayAdapter<String>? = null
var mLoanFundOptionsAdapter: ArrayAdapter<String>? = null
var mLoanOfficerOptionsAdapter: ArrayAdapter<String>? = null
var mInterestTypeOptionsAdapter: ArrayAdapter<String>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments != null) clientId = requireArguments().getInt(Constants.CLIENT_ID)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
activity?.actionBar?.setDisplayHomeAsUpEnabled(true)
rootView = inflater.inflate(R.layout.fragment_add_loan, null)
(activity as MifosBaseActivity?)!!.activityComponent.inject(this)
ButterKnife.bind(this, rootView)
mLoanAccountPresenter!!.attachView(this)
inflateSubmissionDate()
inflateDisbursementDate()
inflateLoansProductSpinner()
disbursementDate = tvDisbursementOnDate!!.text.toString()
submissionDate = tvSubmittedOnDate!!.text.toString()
submissionDate = DateHelper.getDateAsStringUsedForCollectionSheetPayload(submissionDate).replace("-", " ")
disbursementDate = DateHelper.getDateAsStringUsedForCollectionSheetPayload(disbursementDate).replace("-", " ")
inflateSpinners()
return rootView
}
@OnClick(R.id.btn_loan_submit)
fun submit() {
val loansPayload = LoansPayload()
loansPayload.isAllowPartialPeriodInterestCalcualtion = cbCalculateInterest
.isChecked()
loansPayload.amortizationType = amortizationTypeId
loansPayload.clientId = clientId
loansPayload.dateFormat = "dd MMMM yyyy"
loansPayload.expectedDisbursementDate = disbursementDate
loansPayload.interestCalculationPeriodType = interestCalculationPeriodTypeId
loansPayload.loanType = "individual"
loansPayload.locale = "en"
loansPayload.numberOfRepayments = etNumberOfRepayments!!.editableText
.toString()
loansPayload.principal = etPrincipal!!.editableText.toString()
loansPayload.productId = productId
loansPayload.repaymentEvery = etRepaidEvery!!.editableText.toString()
loansPayload.submittedOnDate = submissionDate
loansPayload.loanPurposeId = loanPurposeId
loansPayload.loanTermFrequency = etLoanTerm!!.editableText.toString().toInt()
loansPayload.loanTermFrequencyType = loanTermFrequency
//loanTermFrequencyType and repaymentFrequencyType should be the same.
loansPayload.repaymentFrequencyType = loanTermFrequency
loansPayload.repaymentFrequencyDayOfWeekType = if (repaymentFrequencyDayOfWeek != null) repaymentFrequencyDayOfWeek else null
loansPayload.repaymentFrequencyNthDayType = if (repaymentFrequencyNthDayType != null) repaymentFrequencyNthDayType else null
loansPayload.transactionProcessingStrategyId = transactionProcessingStrategyId
loansPayload.fundId = fundId!!
loansPayload.interestType = interestTypeId
loansPayload.loanOfficerId = loanOfficerId
loansPayload.linkAccountId = linkAccountId
interestRatePerPeriod =
etNominalInterestRate!!.editableText.toString().toDouble()
loansPayload.interestRatePerPeriod = interestRatePerPeriod
if (hasDataTables) {
val fragment = DataTableListFragment.newInstance(
mLoanTemplate.dataTables,
loansPayload, Constants.CLIENT_LOAN)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.DATA_TABLE_LIST)
fragmentTransaction.replace(R.id.container, fragment).commit()
} else {
initiateLoanCreation(loansPayload)
}
}
override fun onDatePicked(date: String) {
if (isSubmissionDate) {
tvSubmittedOnDate!!.text = date
submissionDate = date
isSubmissionDate = false
}
if (isDisbursebemntDate) {
tvDisbursementOnDate!!.text = date
disbursementDate = date
isDisbursebemntDate = false
}
}
private fun inflateSpinners() {
//Inflating the LoanProducts Spinner
mLoanProductAdapter = ArrayAdapter(requireActivity(), android.R.layout.simple_spinner_item,
mListLoanProducts)
mLoanProductAdapter!!.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spLoanProduct!!.adapter = mLoanProductAdapter
spLoanProduct!!.onItemSelectedListener = this
//Inflating the LoanPurposeOptions
mLoanPurposeOptionsAdapter = ArrayAdapter(requireActivity(), android.R.layout.simple_spinner_item,
mListLoanPurposeOptions)
mLoanPurposeOptionsAdapter!!.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spLoanPurpose!!.adapter = mLoanPurposeOptionsAdapter
spLoanPurpose!!.onItemSelectedListener = this
//Inflating Linking Options
mAccountLinkingOptionsAdapter = ArrayAdapter(requireActivity(),
android.R.layout.simple_spinner_item, mListAccountLinkingOptions)
mAccountLinkingOptionsAdapter!!.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spLinkingOptions!!.adapter = mAccountLinkingOptionsAdapter
spLinkingOptions!!.onItemSelectedListener = this
//Inflating AmortizationTypeOptions Spinner
mAmortizationTypeOptionsAdapter = ArrayAdapter(requireActivity(),
android.R.layout.simple_spinner_item, mListAmortizationTypeOptions)
mAmortizationTypeOptionsAdapter!!.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item)
spAmortization!!.adapter = mAmortizationTypeOptionsAdapter
spAmortization!!.onItemSelectedListener = this
//Inflating InterestCalculationPeriodTypeOptions Spinner
mInterestCalculationPeriodTypeOptionsAdapter = ArrayAdapter(requireActivity(),
android.R.layout.simple_spinner_item, mListInterestCalculationPeriodTypeOptions)
mInterestCalculationPeriodTypeOptionsAdapter!!.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item)
spInterestCalculationPeriod!!.adapter = mInterestCalculationPeriodTypeOptionsAdapter
spInterestCalculationPeriod!!.onItemSelectedListener = this
//Inflate TransactionProcessingStrategyOptions Spinner
mTransactionProcessingStrategyOptionsAdapter = ArrayAdapter(requireActivity(),
android.R.layout.simple_spinner_item, mListTransactionProcessingStrategyOptions)
mTransactionProcessingStrategyOptionsAdapter!!.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item)
spRepaymentStrategy!!.adapter = mTransactionProcessingStrategyOptionsAdapter
spRepaymentStrategy!!.onItemSelectedListener = this
//Inflate TermFrequencyTypeOptionsAdapter Spinner
mTermFrequencyTypeOptionsAdapter = ArrayAdapter(requireActivity(),
android.R.layout.simple_spinner_item, mListTermFrequencyTypeOptions)
mTermFrequencyTypeOptionsAdapter!!.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item)
spPaymentPeriods!!.adapter = mTermFrequencyTypeOptionsAdapter
spPaymentPeriods!!.onItemSelectedListener = this
//Inflate LoanTerm Frequency Type adapter
mLoanTermFrequencyTypeAdapter = ArrayAdapter(requireActivity(),
android.R.layout.simple_spinner_item, mListLoanTermFrequencyTypeOptions)
mLoanTermFrequencyTypeAdapter!!.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item)
spLoanTermFrequencyType!!.adapter = mLoanTermFrequencyTypeAdapter
spLoanTermFrequencyType!!.onItemSelectedListener = this
//Inflate FondOptions Spinner
mLoanFundOptionsAdapter = ArrayAdapter(requireActivity(),
android.R.layout.simple_spinner_item, mListLoanFundOptions)
mLoanFundOptionsAdapter!!.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spFund!!.adapter = mLoanFundOptionsAdapter
spFund!!.onItemSelectedListener = this
//Inflating LoanOfficerOptions Spinner
mLoanOfficerOptionsAdapter = ArrayAdapter(requireActivity(),
android.R.layout.simple_spinner_item, mListLoanOfficerOptions)
mLoanOfficerOptionsAdapter!!.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spLoanOfficer!!.adapter = mLoanOfficerOptionsAdapter
spLoanOfficer!!.onItemSelectedListener = this
//Inflating InterestTypeOptions Spinner
mInterestTypeOptionsAdapter = ArrayAdapter(requireActivity(),
android.R.layout.simple_spinner_item, mListInterestTypeOptions)
mInterestTypeOptionsAdapter!!.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spInterestType!!.adapter = mInterestTypeOptionsAdapter
spInterestType!!.onItemSelectedListener = this
}
private fun inflateRepaidMonthSpinners() {
mRepaymentFrequencyNthDayTypeOptionsAdapter = ArrayAdapter(
requireActivity(), android.R.layout.simple_spinner_item,
mListRepaymentFrequencyNthDayTypeOptions)
mRepaymentFrequencyNthDayTypeOptionsAdapter!!
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spRepaymentFreqNthDay!!.adapter = mRepaymentFrequencyNthDayTypeOptionsAdapter
spRepaymentFreqNthDay!!.onItemSelectedListener = this
mRepaymentFrequencyDayOfWeekTypeOptionsAdapter = ArrayAdapter(
requireActivity(), android.R.layout.simple_spinner_item,
mListRepaymentFrequencyDayOfWeekTypeOptions)
mRepaymentFrequencyDayOfWeekTypeOptionsAdapter!!
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spRepaymentFreqDayOfWeek!!.adapter = mRepaymentFrequencyDayOfWeekTypeOptionsAdapter
spRepaymentFreqDayOfWeek!!.onItemSelectedListener = this
spRepaymentFreqNthDay!!.setSelection(mListRepaymentFrequencyNthDayTypeOptions.size - 1)
spRepaymentFreqDayOfWeek!!.setSelection(
mListRepaymentFrequencyDayOfWeekTypeOptions.size - 1)
}
private fun inflateLoansProductSpinner() {
mLoanAccountPresenter!!.loadAllLoans()
}
private fun inflateLoanPurposeSpinner() {
mLoanAccountPresenter!!.loadLoanAccountTemplate(clientId, productId)
}
private fun initiateLoanCreation(loansPayload: LoansPayload) {
mLoanAccountPresenter!!.createLoansAccount(loansPayload)
}
fun inflateSubmissionDate() {
mfDatePicker = MFDatePicker.newInsance(this)
tvSubmittedOnDate!!.text = MFDatePicker.getDatePickedAsString()
}
@OnClick(R.id.tv_submittedon_date)
fun setTvSubmittedOnDate() {
isSubmissionDate = true
mfDatePicker!!.show(requireActivity().supportFragmentManager, FragmentConstants.DFRAG_DATE_PICKER)
}
fun inflateDisbursementDate() {
mfDatePicker = MFDatePicker.newInsance(this)
tvDisbursementOnDate!!.text = MFDatePicker.getDatePickedAsString()
}
@OnClick(R.id.tv_disbursementon_date)
fun setTvDisbursementOnDate() {
isDisbursebemntDate = true
mfDatePicker!!.show(requireActivity().supportFragmentManager, FragmentConstants.DFRAG_DATE_PICKER)
}
override fun showAllLoan(loans: List<LoanProducts>) {
mLoanProducts = loans
mListLoanProducts.clear()
for (loanProducts in mLoanProducts) {
mListLoanProducts.add(loanProducts.name)
}
mLoanProductAdapter!!.notifyDataSetChanged()
}
override fun showLoanAccountTemplate(loanTemplate: LoanTemplate) {
mLoanTemplate = loanTemplate
hasDataTables = mLoanTemplate.dataTables.size > 0
mListRepaymentFrequencyNthDayTypeOptions.clear()
mRepaymentFrequencyNthDayTypeOptions = mLoanTemplate
.repaymentFrequencyNthDayTypeOptions
for (options in mRepaymentFrequencyNthDayTypeOptions) {
mListRepaymentFrequencyNthDayTypeOptions.add(options.value)
}
mListRepaymentFrequencyNthDayTypeOptions.add(
resources.getString(R.string.select_week_hint))
mListRepaymentFrequencyDayOfWeekTypeOptions.clear()
mRepaymentFrequencyDaysOfWeekTypeOptions = mLoanTemplate
.repaymentFrequencyDaysOfWeekTypeOptions
for (options in mRepaymentFrequencyDaysOfWeekTypeOptions) {
mListRepaymentFrequencyDayOfWeekTypeOptions.add(options.value)
}
mListRepaymentFrequencyDayOfWeekTypeOptions.add(
resources.getString(R.string.select_day_hint))
mListLoanPurposeOptions.clear()
for (loanPurposeOptions in mLoanTemplate.loanPurposeOptions) {
mListLoanPurposeOptions.add(loanPurposeOptions.name)
}
mLoanPurposeOptionsAdapter!!.notifyDataSetChanged()
mListAccountLinkingOptions.clear()
for (options in mLoanTemplate.accountLinkingOptions) {
mListAccountLinkingOptions.add(options.productName)
}
mListAccountLinkingOptions.add(
resources.getString(R.string.select_linkage_account_hint))
mAccountLinkingOptionsAdapter!!.notifyDataSetChanged()
mListAmortizationTypeOptions.clear()
for (amortizationTypeOptions in mLoanTemplate.amortizationTypeOptions) {
mListAmortizationTypeOptions.add(amortizationTypeOptions.value)
}
mAmortizationTypeOptionsAdapter!!.notifyDataSetChanged()
mListInterestCalculationPeriodTypeOptions.clear()
for (interestCalculationPeriodType in mLoanTemplate
.interestCalculationPeriodTypeOptions) {
mListInterestCalculationPeriodTypeOptions.add(interestCalculationPeriodType.value)
}
mInterestCalculationPeriodTypeOptionsAdapter!!.notifyDataSetChanged()
mListTransactionProcessingStrategyOptions.clear()
for (transactionProcessingStrategyOptions in mLoanTemplate.transactionProcessingStrategyOptions) {
mListTransactionProcessingStrategyOptions.add(transactionProcessingStrategyOptions
.name)
}
mTransactionProcessingStrategyOptionsAdapter!!.notifyDataSetChanged()
mListTermFrequencyTypeOptions.clear()
for (termFrequencyTypeOptions in mLoanTemplate.termFrequencyTypeOptions) {
mListTermFrequencyTypeOptions.add(termFrequencyTypeOptions.value)
}
mTermFrequencyTypeOptionsAdapter!!.notifyDataSetChanged()
mListLoanTermFrequencyTypeOptions.clear()
for (termFrequencyTypeOptions in mLoanTemplate.termFrequencyTypeOptions) {
mListLoanTermFrequencyTypeOptions.add(termFrequencyTypeOptions.value)
}
mLoanTermFrequencyTypeAdapter!!.notifyDataSetChanged()
mListLoanFundOptions.clear()
for (fundOptions in mLoanTemplate.fundOptions) {
mListLoanFundOptions.add(fundOptions.name)
}
mLoanFundOptionsAdapter!!.notifyDataSetChanged()
mListLoanOfficerOptions.clear()
for (loanOfficerOptions in mLoanTemplate.loanOfficerOptions) {
mListLoanOfficerOptions.add(loanOfficerOptions.displayName)
}
mLoanOfficerOptionsAdapter!!.notifyDataSetChanged()
mListInterestTypeOptions.clear()
for (interestTypeOptions in mLoanTemplate.interestTypeOptions) {
mListInterestTypeOptions.add(interestTypeOptions.value)
}
mInterestTypeOptionsAdapter!!.notifyDataSetChanged()
showDefaultValues()
}
override fun showLoanAccountCreatedSuccessfully(loans: Loans?) {
Toast.makeText(activity, R.string.loan_creation_success, Toast.LENGTH_LONG).show()
requireActivity().supportFragmentManager.popBackStackImmediate()
}
override fun showMessage(messageId: Int) {
Toaster.show(rootView, messageId)
}
override fun showFetchingError(s: String?) {
Toaster.show(rootView, s)
}
override fun showProgressbar(show: Boolean) {
showProgress(show)
}
override fun onDetach() {
super.onDetach()
}
override fun onDestroyView() {
super.onDestroyView()
mLoanAccountPresenter!!.detachView()
}
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
when (parent.id) {
R.id.sp_lproduct -> {
productId = mLoanProducts[position].id
inflateLoanPurposeSpinner()
}
R.id.sp_loan_purpose -> loanPurposeId = mLoanTemplate.loanPurposeOptions[position].id
R.id.sp_amortization -> amortizationTypeId = mLoanTemplate.amortizationTypeOptions[position].id
R.id.sp_interestcalculationperiod -> interestCalculationPeriodTypeId = mLoanTemplate
.interestCalculationPeriodTypeOptions[position].id
R.id.sp_repaymentstrategy -> transactionProcessingStrategyId = mLoanTemplate
.transactionProcessingStrategyOptions[position].id
R.id.sp_payment_periods -> {
loanTermFrequency = mLoanTemplate.termFrequencyTypeOptions[position]
.id
spLoanTermFrequencyType!!.setSelection(loanTermFrequency)
if (loanTermFrequency == 2) {
// Show and inflate Nth day and week spinners
showHideRepaidMonthSpinners(View.VISIBLE)
inflateRepaidMonthSpinners()
} else {
showHideRepaidMonthSpinners(View.GONE)
}
}
R.id.sp_loan_term_periods -> {
loanTermFrequency = mLoanTemplate.termFrequencyTypeOptions[position]
.id
spPaymentPeriods!!.setSelection(loanTermFrequency)
if (loanTermFrequency == 2) {
// Show and inflate Nth day and week spinners
showHideRepaidMonthSpinners(View.VISIBLE)
inflateRepaidMonthSpinners()
} else {
showHideRepaidMonthSpinners(View.GONE)
}
}
R.id.sp_repayment_freq_nth_day -> repaymentFrequencyNthDayType = if (mListRepaymentFrequencyNthDayTypeOptions[position]
== resources.getString(R.string.select_week_hint)) {
null
} else {
mLoanTemplate
.repaymentFrequencyNthDayTypeOptions[position].id
}
R.id.sp_repayment_freq_day_of_week -> repaymentFrequencyDayOfWeek = if (mListRepaymentFrequencyDayOfWeekTypeOptions[position]
== resources.getString(R.string.select_day_hint)) {
null
} else {
mLoanTemplate
.repaymentFrequencyDaysOfWeekTypeOptions[position].id
}
R.id.sp_fund -> fundId = mLoanTemplate.fundOptions[position].id
R.id.sp_loan_officer -> loanOfficerId = mLoanTemplate.loanOfficerOptions[position].id
R.id.sp_interest_type -> interestTypeId = mLoanTemplate.interestTypeOptions[position].id
R.id.sp_linking_options -> linkAccountId = if (mListAccountLinkingOptions[position]
== resources.getString(R.string.select_linkage_account_hint)) {
null
} else {
mLoanTemplate.accountLinkingOptions[position].id
}
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
private fun showHideRepaidMonthSpinners(visibility: Int) {
spRepaymentFreqNthDay!!.visibility = visibility
spRepaymentFreqDayOfWeek!!.visibility = visibility
tvRepaidNthFreqLabelOn!!.visibility = visibility
}
private fun showDefaultValues() {
interestRatePerPeriod = mLoanTemplate.interestRatePerPeriod
loanTermFrequency = mLoanTemplate.termPeriodFrequencyType.id
termFrequency = mLoanTemplate.termFrequency
etPrincipal!!.setText(mLoanTemplate.principal.toString())
etNumberOfRepayments!!.setText(mLoanTemplate.numberOfRepayments.toString())
tvNominalRatePerYearMonth
?.setText(mLoanTemplate.interestRateFrequencyType.value)
etNominalInterestRate!!.setText(mLoanTemplate.interestRatePerPeriod.toString())
etLoanTerm!!.setText(termFrequency.toString())
if (mLoanTemplate.repaymentEvery != null) {
repaymentEvery = mLoanTemplate.repaymentEvery
etRepaidEvery!!.setText(repaymentEvery.toString())
}
if (mLoanTemplate.fundId != null) {
fundId = mLoanTemplate.fundId
spFund!!.setSelection(mLoanTemplate.getFundNameFromId(fundId))
}
spLinkingOptions!!.setSelection(mListAccountLinkingOptions.size)
}
companion object {
@kotlin.jvm.JvmStatic
fun newInstance(clientId: Int): LoanAccountFragment {
val loanAccountFragment = LoanAccountFragment()
val args = Bundle()
args.putInt(Constants.CLIENT_ID, clientId)
loanAccountFragment.arguments = args
return loanAccountFragment
}
}
} | mpl-2.0 | 4571974c8ff8b0d99d17a6b826982856 | 45.050473 | 137 | 0.717486 | 4.840822 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/elementfilter/filters/HasTagLike.kt | 1 | 741 | package de.westnordost.streetcomplete.data.elementfilter.filters
import de.westnordost.streetcomplete.data.elementfilter.quoteIfNecessary
import de.westnordost.streetcomplete.data.osm.mapdata.Element
/** ~key(word)? ~ val(ue)? */
class HasTagLike(val key: String, val value: String) : ElementFilter {
private val keyRegex = RegexOrSet.from(key)
private val valueRegex = RegexOrSet.from(value)
override fun toOverpassQLString() =
"[" + "~" + "^($key)$".quoteIfNecessary() + " ~ " + "^($value)$".quoteIfNecessary() + "]"
override fun toString() = toOverpassQLString()
override fun matches(obj: Element?) =
obj?.tags?.entries?.find { keyRegex.matches(it.key) && valueRegex.matches(it.value) } != null
}
| gpl-3.0 | f88969a99958a3819411667c179c4afb | 40.166667 | 101 | 0.699055 | 3.983871 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | example/src/main/java/org/wordpress/android/fluxc/example/ui/products/WooProductAttributeFragment.kt | 2 | 12557 | package org.wordpress.android.fluxc.example.ui.products
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_woo_product_attribute.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.wordpress.android.fluxc.example.R
import org.wordpress.android.fluxc.example.prependToLog
import org.wordpress.android.fluxc.example.ui.StoreSelectingFragment
import org.wordpress.android.fluxc.example.utils.showSingleLineDialog
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.attribute.WCGlobalAttributeModel
import org.wordpress.android.fluxc.model.attribute.terms.WCAttributeTermModel
import org.wordpress.android.fluxc.store.WCGlobalAttributeStore
import javax.inject.Inject
class WooProductAttributeFragment : StoreSelectingFragment() {
@Inject internal lateinit var wcAttributesStore: WCGlobalAttributeStore
private val coroutineScope = CoroutineScope(Dispatchers.Main)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
inflater.inflate(R.layout.fragment_woo_product_attribute, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fetch_product_attributes.setOnClickListener { onFetchAttributesListClicked() }
fetch_product_attributes_from_db.setOnClickListener { onFetchCachedAttributesListClicked() }
create_product_attributes.setOnClickListener { onCreateAttributeButtonClicked() }
delete_product_attributes.setOnClickListener { onDeleteAttributeButtonClicked() }
update_product_attributes.setOnClickListener { onUpdateAttributeButtonClicked() }
fetch_product_single_attribute.setOnClickListener { onFetchAttributeButtonClicked() }
fetch_term_for_attribute.setOnClickListener { onFetchAttributeTermsButtonClicked() }
create_term_for_attribute.setOnClickListener { onCreateAttributeTermButtonClicked() }
}
@Suppress("TooGenericExceptionCaught")
private fun onCreateAttributeButtonClicked() {
try {
showSingleLineDialog(
activity,
"Enter the attribute name you want to create:"
) { editText ->
coroutineScope.launch {
takeAsyncRequestWithValidSite {
wcAttributesStore.createAttribute(it, editText.text.toString())
}?.apply {
model?.let { logSingleAttributeResponse(it) }
?.let { prependToLog("========== Attribute Created =========") }
?: takeIf { isError }?.let {
prependToLog("Failed to create Attribute. Error: ${error.message}")
}
} ?: prependToLog("Failed to create Attribute. Error: Unknown")
}
}
} catch (ex: Exception) {
prependToLog("Couldn't create Attributes. Error: ${ex.message}")
}
}
@Suppress("TooGenericExceptionCaught")
private fun onDeleteAttributeButtonClicked() {
try {
showSingleLineDialog(
activity,
"Enter the attribute ID you want to remove:"
) { editText ->
coroutineScope.launch {
takeAsyncRequestWithValidSite {
wcAttributesStore.deleteAttribute(
it,
editText.text.toString().toLongOrNull() ?: 0
)
}?.apply {
model?.let { logSingleAttributeResponse(it) }
?.let { prependToLog("========== Attribute Deleted =========") }
?: takeIf { isError }?.let {
prependToLog("Failed to delete Attribute. Error: ${error.message}")
}
} ?: prependToLog("Failed to delete Attribute. Error: Unknown")
}
}
} catch (ex: Exception) {
prependToLog("Couldn't create Attributes. Error: ${ex.message}")
}
}
@Suppress("TooGenericExceptionCaught")
private fun onUpdateAttributeButtonClicked() {
try {
showSingleLineDialog(
activity,
"Enter the attribute ID you want to update:"
) { attributeIdEditText ->
showSingleLineDialog(
activity,
"Enter the attribute new name:"
) { attributeNameEditText ->
coroutineScope.launch {
takeAsyncRequestWithValidSite {
wcAttributesStore.updateAttribute(
it,
attributeIdEditText.text.toString().toLongOrNull() ?: 0,
attributeNameEditText.text.toString()
)
}?.apply {
model?.let { logSingleAttributeResponse(it) }
?.let { prependToLog("========== Attribute Updated =========") }
?: takeIf { isError }?.let {
prependToLog("Failed to update Attribute. Error: ${error.message}")
}
} ?: prependToLog("Failed to update Attribute. Error: Unknown")
}
}
}
} catch (ex: Exception) {
prependToLog("Couldn't create Attributes. Error: ${ex.message}")
}
}
@Suppress("TooGenericExceptionCaught")
private fun onFetchAttributeButtonClicked() {
try {
showSingleLineDialog(
activity,
"Enter the attribute ID you want to remove:"
) { editText ->
coroutineScope.launch {
takeAsyncRequestWithValidSite {
wcAttributesStore.fetchAttribute(
it,
editText.text.toString().toLongOrNull() ?: 0
)
}?.apply {
model?.let { logSingleAttributeResponse(it) }
?.let { prependToLog("========== Attribute Fetched =========") }
?: takeIf { isError }?.let {
prependToLog("Failed to delete Attribute. Error: ${error.message}")
}
} ?: prependToLog("Failed to delete Attribute. Error: Unknown")
}
}
} catch (ex: Exception) {
prependToLog("Couldn't create Attributes. Error: ${ex.message}")
}
}
@Suppress("TooGenericExceptionCaught")
private fun onFetchAttributeTermsButtonClicked() {
try {
showSingleLineDialog(
activity,
"Enter the attribute ID you want to fetch terms:"
) { editText ->
coroutineScope.launch {
takeAsyncRequestWithValidSite {
wcAttributesStore.fetchAttributeTerms(
it,
editText.text.toString().toLongOrNull() ?: 0
)
}?.apply {
model?.forEach {
logSingleAttributeTermResponse(it) }
?.let { prependToLog("========== Attribute Terms Fetched =========") }
?: takeIf { isError }?.let {
prependToLog("Failed to fetch Terms. Error: ${error.message}")
}
} ?: prependToLog("Failed to fetch Terms. Error: Unknown")
}
}
} catch (ex: Exception) {
prependToLog("Couldn't create Attributes. Error: ${ex.message}")
}
}
@Suppress("TooGenericExceptionCaught")
private fun onCreateAttributeTermButtonClicked() {
try {
showSingleLineDialog(
activity,
"Enter the attribute ID you want to add terms:"
) { attributeIdEditText ->
showSingleLineDialog(
activity,
"Enter the term name you want to create:"
) { termEditText ->
coroutineScope.launch {
takeAsyncRequestWithValidSite {
wcAttributesStore.createOptionValueForAttribute(
it,
attributeIdEditText.text.toString().toLongOrNull() ?: 0,
termEditText.text.toString()
)
}?.apply {
model?.let { logSingleAttributeResponse(it) }
?.let { prependToLog("========== Attribute Term Created =========") }
?: takeIf { isError }?.let {
prependToLog("Failed to delete Attribute. Error: ${error.message}")
}
} ?: prependToLog("Failed to create Attribute Term. Error: Unknown")
}
}
}
} catch (ex: Exception) {
prependToLog("Couldn't create Attribute Term. Error: ${ex.message}")
}
}
@Suppress("TooGenericExceptionCaught")
private fun onFetchAttributesListClicked() = coroutineScope.launch {
try {
takeAsyncRequestWithValidSite {
wcAttributesStore.fetchStoreAttributes(it)
}
?.model
?.let { logAttributeListResponse(it) }
} catch (ex: Exception) {
prependToLog("Couldn't fetch Products Attributes. Error: ${ex.message}")
}
}
@Suppress("TooGenericExceptionCaught")
private fun onFetchCachedAttributesListClicked() = coroutineScope.launch {
try {
takeAsyncRequestWithValidSite {
wcAttributesStore.loadCachedStoreAttributes(it)
}
?.model
?.let { logAttributeListResponse(it) }
} catch (ex: Exception) {
prependToLog("Couldn't fetch Products Attributes. Error: ${ex.message}")
}
}
private fun logSingleAttributeResponse(response: WCGlobalAttributeModel) {
response.let {
response.terms
?.filterNotNull()
?.forEachIndexed { index, wcAttributeTermModel ->
logSingleAttributeTermResponse(wcAttributeTermModel, index)
}
prependToLog(" Attribute slug: ${it.slug.ifEmpty { "Slug not available" }}")
prependToLog(" Attribute type: ${it.type.ifEmpty { "Type not available" }}")
prependToLog(" Attribute name: ${it.name.ifEmpty { "Attribute name not available" }}")
prependToLog(" Attribute remote id: ${it.remoteId}")
prependToLog(" --------- Attribute ---------")
}
}
private fun logSingleAttributeTermResponse(response: WCAttributeTermModel, termIndex: Int? = null) {
response.let {
prependToLog(" Term name: ${it.name}")
prependToLog(" Term id: ${it.remoteId}")
prependToLog(" --------- Attribute Term ${termIndex ?: ""} ---------")
}
}
private fun logAttributeListResponse(model: List<WCGlobalAttributeModel>) {
model.forEach(::logSingleAttributeResponse)
prependToLog("========== Full Site Attribute list =========")
}
private suspend inline fun <T> takeAsyncRequestWithValidSite(crossinline action: suspend (SiteModel) -> T) =
selectedSite?.let {
withContext(Dispatchers.Default) {
action(it)
}
}
}
| gpl-2.0 | 72cfec64f8107949e1293025bec552bb | 44.661818 | 115 | 0.52624 | 6.110462 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/registry/type/recipe/LanternRecipeRegistry.kt | 1 | 2097 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.registry.type.recipe
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.registry.MutableCatalogTypeRegistry
import org.lanternpowered.api.registry.RecipeRegistry
import org.lanternpowered.api.registry.mutableCatalogTypeRegistry
import org.lanternpowered.api.util.optional.asOptional
import org.lanternpowered.api.world.World
import org.spongepowered.api.item.inventory.Inventory
import org.spongepowered.api.item.inventory.ItemStackSnapshot
import org.spongepowered.api.item.recipe.Recipe
import org.spongepowered.api.item.recipe.RecipeType
import org.spongepowered.api.item.recipe.cooking.CookingRecipe
import java.util.Optional
object LanternRecipeRegistry : RecipeRegistry, MutableCatalogTypeRegistry<Recipe> by mutableCatalogTypeRegistry() {
@Suppress("UNCHECKED_CAST")
override fun <T : Recipe> getAllOfType(type: RecipeType<T>): Collection<T> =
this.all.filter { recipe -> recipe.type == type } as Collection<T>
override fun getByKey(key: NamespacedKey): Optional<Recipe> = this[key].asOptional()
override fun getAll(): Collection<Recipe> = this.all
override fun findMatchingRecipe(inventory: Inventory, world: World): Optional<Recipe> {
TODO("Not yet implemented")
}
override fun <T : Recipe> findMatchingRecipe(type: RecipeType<T>, inventory: Inventory, world: World): Optional<T> {
TODO("Not yet implemented")
}
override fun <T : Recipe> findByResult(type: RecipeType<T>, result: ItemStackSnapshot): MutableCollection<T> {
TODO("Not yet implemented")
}
override fun <T : CookingRecipe> findCookingRecipe(type: RecipeType<T>, ingredient: ItemStackSnapshot): Optional<T> {
TODO("Not yet implemented")
}
}
| mit | 66ef05a10e0951094aca27a8052e1f92 | 40.94 | 121 | 0.755842 | 4.160714 | false | false | false | false |
callstack-io/react-native-material-palette | android/src/main/java/io/callstack/react_native_material_palette/MaterialPaletteModule.kt | 1 | 7344 | package io.callstack.react_native_material_palette
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.provider.MediaStore
import android.support.v7.graphics.Palette
import android.support.v7.graphics.Target
import com.facebook.common.executors.CallerThreadExecutor
import com.facebook.common.internal.Closeables
import com.facebook.common.references.CloseableReference
import com.facebook.datasource.BaseDataSubscriber
import com.facebook.datasource.DataSource
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.imagepipeline.common.ImageDecodeOptions
import com.facebook.imagepipeline.memory.PooledByteBuffer
import com.facebook.imagepipeline.memory.PooledByteBufferInputStream
import com.facebook.imagepipeline.request.ImageRequest.RequestLevel
import com.facebook.imagepipeline.request.ImageRequestBuilder
import com.facebook.react.bridge.*
import java.io.IOException
class MaterialPaletteModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
private val REACT_NAME = "MaterialPalette"
private val ERR_INVALID_URI = "ERR_INVALID_URI"
private val ERR_DOWNLOAD = "ERR_DOWNLOAD"
override fun getName(): String {
return REACT_NAME
}
private lateinit var palette: Palette
fun throwExceptionWrongColor() {
throw RuntimeException("The color provided is not valid. It must be one of types 'muted', " +
"'vibrant', 'darkMuted', 'darkVibrant', 'lightMuted' or 'lightVibrant")
}
fun getHexColor(rgbInt: Int): String = String.format("#%06X", 0xFFFFFF and rgbInt)
fun targetMap(target: String): Target? {
return when(target) {
"muted" -> Target.MUTED
"vibrant" -> Target.VIBRANT
"darkMuted" -> Target.DARK_MUTED
"darkVibrant" -> Target.DARK_VIBRANT
"lightMuted" -> Target.LIGHT_MUTED
"lightVibrant" -> Target.LIGHT_VIBRANT
else -> {
null
}
}
}
fun getSwatchProperties(swatch: Palette.Swatch?): WritableMap {
val swatchMap = Arguments.createMap()
val population = swatch?.population ?: 0
val bodyTextColor = swatch?.bodyTextColor ?: 0
val titleTextColor = swatch?.titleTextColor ?: 0
val rgbColor = swatch?.rgb ?: 0
swatchMap.putInt("population", population)
swatchMap.putString("color", getHexColor(rgbColor))
swatchMap.putString("bodyTextColor", getHexColor(bodyTextColor))
swatchMap.putString("titleTextColor", getHexColor(titleTextColor))
return swatchMap
}
fun getSwatch(color: String): WritableMap {
var targetSwatch: Palette.Swatch? = Palette.Swatch(0, 0)
when(color) {
"muted" -> targetSwatch = palette.mutedSwatch
"vibrant" -> targetSwatch = palette.vibrantSwatch
"darkMuted" -> targetSwatch = palette.darkMutedSwatch
"darkVibrant" -> targetSwatch = palette.darkVibrantSwatch
"lightMuted" -> targetSwatch = palette.lightMutedSwatch
"lightVibrant" -> targetSwatch = palette.lightVibrantSwatch
else -> {
throwExceptionWrongColor()
}
}
return getSwatchProperties(targetSwatch)
}
fun getPalettesFromImage(image: Bitmap, options: ReadableMap, callback: (result: WritableMap) -> Unit) {
val region = options.getMap("region")
val top = region.getInt("top")
val right = region.getInt("right")
val bottom = region.getInt("bottom")
val left = region.getInt("left")
val maxColorCount = options.getInt("maximumColorCount")
val types = options.getArray("type")
var builder: Palette.Builder = Palette.from(image).maximumColorCount(maxColorCount)
if (left != 0 || top != 0 || right != 0 || bottom != 0) {
builder = builder.setRegion(left, top, right, bottom)
}
for (t in Array(types.size(), { i -> targetMap(types.getString(i))})) {
if (t != null) {
builder = builder.addTarget(t)
} else {
throwExceptionWrongColor()
}
}
builder.generate({ p: Palette ->
palette = p
val returnMap = Arguments.createMap()
val targets: Array<String> = Array(types.size(), { i -> types.getString(i)})
for (t in targets) {
returnMap.putMap(t, getSwatch(t))
}
callback(returnMap)
})
}
@ReactMethod
fun createMaterialPalette(source: ReadableMap, options: ReadableMap, promise: Promise) {
val uri: Uri
try {
uri = Uri.parse(source.getString("uri"))
} catch(error: IOException) {
promise.reject(ERR_INVALID_URI, "The URI provided is not valid")
return
}
if (uri.scheme == "http" || uri.scheme == "https") {
val decodeOptions = ImageDecodeOptions.newBuilder()
.build()
val imageRequest = ImageRequestBuilder
.newBuilderWithSource(uri)
.setImageDecodeOptions(decodeOptions)
.setLowestPermittedRequestLevel(RequestLevel.FULL_FETCH)
.build()
val imagePipeline = Fresco.getImagePipeline()
val dataSource = imagePipeline.fetchEncodedImage(imageRequest, reactApplicationContext)
val dataSubscriber = object: BaseDataSubscriber<CloseableReference<PooledByteBuffer>>() {
override fun onNewResultImpl(dataSource: DataSource<CloseableReference<PooledByteBuffer>>) {
if (!dataSource.isFinished) {
return
}
val result = dataSource.result
if (result == null) {
promise.reject(ERR_DOWNLOAD, "Failed to download image")
return
}
val inputStream = PooledByteBufferInputStream(result.get())
try {
val bitmap = BitmapFactory.decodeStream(inputStream)
getPalettesFromImage(bitmap, options, {
result ->
promise.resolve(result)
})
} catch (e: Exception) {
promise.reject(e)
} finally {
Closeables.closeQuietly(inputStream)
}
}
override fun onFailureImpl(dataSource: DataSource<CloseableReference<PooledByteBuffer>>) {
promise.reject(dataSource.failureCause)
}
}
dataSource.subscribe(dataSubscriber, CallerThreadExecutor.getInstance())
} else {
try {
val bitmap = MediaStore.Images.Media.getBitmap(reactApplicationContext.contentResolver, uri)
getPalettesFromImage(bitmap, options, {
result ->
promise.resolve(result)
})
} catch (e: Exception) {
promise.reject(e)
}
}
}
}
| mit | 2e4dc47e718b7bed6de46ab087675952 | 37.051813 | 111 | 0.600763 | 4.935484 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/intentions/LatexMoveSelectionToFileIntention.kt | 1 | 3188 | package nl.hannahsten.texifyidea.intentions
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import nl.hannahsten.texifyidea.ui.CreateFileDialog
import nl.hannahsten.texifyidea.util.files.createFile
import nl.hannahsten.texifyidea.util.files.findRootFile
import nl.hannahsten.texifyidea.util.files.isLatexFile
import nl.hannahsten.texifyidea.util.removeIndents
import org.intellij.lang.annotations.Language
import java.io.File
/**
* @author Hannah Schellekens
*/
open class LatexMoveSelectionToFileIntention : TexifyIntentionBase("Move selection contents to separate file") {
companion object {
private const val minimumSelectionLength = 24
}
override fun startInWriteAction() = false
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
if (editor == null || file == null || !file.isLatexFile()) {
return false
}
val selectionSize = selectionOffsets(editor).sumOf { (start, end): Pair<Int, Int> -> end - start }
return selectionSize >= minimumSelectionLength
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (editor == null || file == null) {
return
}
// Ask the user for a new file name.
val offsets = selectionOffsets(editor)
val document = editor.document
// Display a dialog to ask for the location and name of the new file.
val filePath = CreateFileDialog(file.containingDirectory?.virtualFile?.canonicalPath, "")
.newFileFullPath ?: return
// Find text.
val text = StringBuilder()
for ((start, end) in offsets) {
val selected = document.getText(TextRange(start, end)).trimEnd().removeIndents()
text.append(selected)
}
// Manage paths/file names.
@Language("RegExp")
// Note that we do not override the user-specified filename to be LaTeX-like.
// Path of virtual file always contains '/' as file separators.
val root = file.findRootFile().containingDirectory?.virtualFile?.canonicalPath
// Execute write actions.
runWriteAction {
val createdFile = createFile("$filePath.tex", text.toString())
for ((start, end) in offsets.reversed()) {
document.deleteString(start, end)
}
// The path of the created file contains the system's file separators, whereas the path of the root
// (virtual file) always contains '/' as file separators.
val fileNameRelativeToRoot = createdFile.absolutePath
.replace(File.separator, "/")
.replace("$root/", "")
document.insertString(offsets.first().first, "\\input{${fileNameRelativeToRoot.dropLast(4)}}")
}
}
private fun selectionOffsets(editor: Editor): List<Pair<Int, Int>> {
return editor.caretModel.allCarets
.map { Pair(it.selectionStart, it.selectionEnd) }
}
} | mit | 03c1021231af754c155261a6906c0105 | 36.964286 | 112 | 0.664366 | 4.765321 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/inspections/latex/probablebugs/LatexFileNotFoundInspection.kt | 1 | 5917 | package nl.hannahsten.texifyidea.inspections.latex.probablebugs
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import nl.hannahsten.texifyidea.inspections.InsightGroup
import nl.hannahsten.texifyidea.inspections.TexifyInspectionBase
import nl.hannahsten.texifyidea.lang.magic.MagicCommentScope
import nl.hannahsten.texifyidea.psi.LatexCommands
import nl.hannahsten.texifyidea.reference.InputFileReference
import nl.hannahsten.texifyidea.ui.CreateFileDialog
import nl.hannahsten.texifyidea.util.*
import nl.hannahsten.texifyidea.util.files.commandsInFile
import nl.hannahsten.texifyidea.util.files.createFile
import nl.hannahsten.texifyidea.util.files.findRootFile
import nl.hannahsten.texifyidea.util.files.getFileExtension
import nl.hannahsten.texifyidea.util.magic.CommandMagic
import java.io.File
import java.util.*
/**
* @author Hannah Schellekens
*/
open class LatexFileNotFoundInspection : TexifyInspectionBase() {
override val inspectionGroup = InsightGroup.LATEX
override val inspectionId = "FileNotFound"
override val outerSuppressionScopes = EnumSet.of(MagicCommentScope.GROUP)!!
override fun getDisplayName() = "File not found"
override fun inspectFile(file: PsiFile, manager: InspectionManager, isOntheFly: Boolean): MutableList<ProblemDescriptor> {
val descriptors = descriptorList()
// Get commands of this file.
val commands = file.commandsInFile()
// Loop through commands of file
for (command in commands) {
// Don't resolve references in command definitions, as in \cite{#1} the #1 is not a reference
if (command.parent.parentsOfType(LatexCommands::class).any { it.name in CommandMagic.commandDefinitionsAndRedefinitions }) {
continue
}
val referencesList = command.references.filterIsInstance<InputFileReference>()
for (reference in referencesList) {
if (reference.resolve() == null) {
createQuickFixes(reference, descriptors, manager, isOntheFly)
}
}
}
return descriptors
}
private fun createQuickFixes(reference: InputFileReference, descriptors: MutableList<ProblemDescriptor>, manager: InspectionManager, isOntheFly: Boolean) {
val fileName = reference.key
val extensions = reference.extensions
// CTAN packages are no targets of the InputFileReference, so we check them here and don't show a warning if a CTAN package is included
if (extensions.contains("sty")) {
val ctanPackages = PackageUtils.CTAN_PACKAGE_NAMES.map { it.lowercase(Locale.getDefault()) }
if (reference.key.lowercase(Locale.getDefault()) in ctanPackages) return
}
val fixes = mutableListOf<LocalQuickFix>()
// Create quick fixes for all extensions
extensions.forEach {
fixes.add(CreateNewFileWithDialogQuickFix(fileName, it, reference))
}
// Find expected extension
val extension = if (fileName.getFileExtension().isNotEmpty()) {
fileName.getFileExtension()
}
else {
reference.defaultExtension
}
descriptors.add(
manager.createProblemDescriptor(
reference.element,
reference.rangeInElement,
"File '${fileName.appendExtension(extension)}' not found",
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOntheFly,
*(fixes.toTypedArray())
)
)
}
/**
* Create a new file.
*
* @param filePath Path relative to the root file parent.
*/
class CreateNewFileWithDialogQuickFix(private val filePath: String, private val extension: String, private val reference: InputFileReference) : LocalQuickFix {
override fun getFamilyName() = "Create file ${filePath.appendExtension(extension)}"
override fun startInWriteAction() = false
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val cmd = descriptor.psiElement
val file = cmd.containingFile ?: return
val root = file.findRootFile().containingDirectory?.virtualFile?.canonicalPath ?: return
// Display a dialog to ask for the location and name of the new file.
// By default, all inclusion paths are relative to the main file
val newFilePath = CreateFileDialog(file.findRootFile().containingDirectory?.virtualFile?.canonicalPath, filePath.formatAsFilePath())
.newFileFullPath ?: return
runWriteAction {
val expandedFilePath = expandCommandsOnce(newFilePath, file.project, file) ?: newFilePath
createFile("$expandedFilePath.$extension", "")
// Update LaTeX command parameter with chosen filename.
// We can safely add the extension since illegal extensions are removed later.
// We add the extension for consistency with the file name auto completion, which also adds the extension.
var fileNameRelativeToRoot = "$newFilePath.$extension"
.replace(File.separator, "/")
.replace("$root/", "")
val command = (cmd as? LatexCommands)?.name
if (command in CommandMagic.illegalExtensions) {
CommandMagic.illegalExtensions[command]?.forEach { fileNameRelativeToRoot = fileNameRelativeToRoot.replace(it, "") }
}
reference.handleElementRename(fileNameRelativeToRoot, false)
}
}
}
}
| mit | e4e9e051e1f084770dcd79fcf9e9555e | 41.568345 | 163 | 0.680074 | 5.316262 | false | false | false | false |
i7c/cfm | server/recorder/src/main/kotlin/org/rliz/cfm/recorder/user/data/User.kt | 1 | 1313 | package org.rliz.cfm.recorder.user.data
import org.rliz.cfm.recorder.common.data.AbstractModel
import java.util.UUID
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.EnumType
import javax.persistence.Enumerated
import javax.persistence.Index
import javax.persistence.Table
import javax.persistence.UniqueConstraint
@Entity
@Table(
name = "cfm_user",
uniqueConstraints = arrayOf(
UniqueConstraint(
name = "UC_User_name",
columnNames = arrayOf("name")
)
),
indexes = arrayOf(
Index(
name = "IX_User_uuid",
columnList = "uuid",
unique = true
)
)
)
class User : AbstractModel {
@Column(length = 128, nullable = false)
var name: String? = null
@Column(length = 128, nullable = false)
var password: String? = null
@Enumerated(value = EnumType.STRING)
var state: UserState? = null
var systemUser: Boolean = false
constructor() : super()
constructor(
uuid: UUID,
name: String,
password: String,
state: UserState,
systemUser: Boolean
) : super(uuid) {
this.name = name
this.password = password
this.state = state
this.systemUser = systemUser
}
}
| gpl-3.0 | 0d7c698482f50ebced3aebece8f3dd21 | 22.035088 | 54 | 0.626809 | 4.155063 | false | false | false | false |
Devexperts/usages | idea-plugin/src/main/kotlin/com/devexperts/usages/idea/UsagesTree.kt | 1 | 11329 | /**
* Copyright (C) 2017 Devexperts LLC
*
* 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/gpl-3.0.html>.
*/
package com.devexperts.usages.idea
import com.devexperts.usages.api.MemberType
import com.devexperts.usages.api.MemberType.FIELD
import com.devexperts.usages.api.MemberType.METHOD
import com.devexperts.usages.api.MemberUsage
import com.intellij.ui.ColoredTreeCellRenderer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.TreeSpeedSearch
import com.intellij.ui.speedSearch.SpeedSearchUtil
import com.intellij.ui.treeStructure.SimpleTree
import com.intellij.util.PlatformIcons
import com.intellij.util.ui.tree.TreeUtil
import javax.swing.JTree
import javax.swing.event.TreeExpansionEvent
import javax.swing.event.TreeExpansionListener
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.DefaultTreeModel
import javax.swing.tree.TreePath
class UsagesTree(model: UsagesTreeModel) : SimpleTree(model) {
init {
// On expand action if node has one child, expand it too (recursively)
addTreeExpansionListener(object : TreeExpansionListener {
override fun treeExpanded(event: TreeExpansionEvent) {
var node = (event.path.lastPathComponent ?: return) as DefaultMutableTreeNode
while (node.childCount == 1)
node = node.getChildAt(0) as DefaultMutableTreeNode
expandPath(TreePath(node))
}
override fun treeCollapsed(event: TreeExpansionEvent?) {}
})
// Set custom cell renderer
setCellRenderer(UsagesTreeCellRenderer())
// Install additional actions
TreeUtil.installActions(this)
TreeSpeedSearch(this) // todo does not highlight text, fix it
// Do not show [SyntheticRootNode]
isRootVisible = false
}
/**
* Expands the beginning of the tree to show the first usage
*/
fun expandFirstUsage(): TreePath {
var node = model.root as DefaultMutableTreeNode
while (!node.isLeaf) {
node = node.firstChild as DefaultMutableTreeNode
expandPath(TreePath(node.path))
}
return TreePath(node)
}
}
/**
* Model for work with [UsagesTree] with the specified rendering [strategy]
*/
class UsagesTreeModel(val strategy: GroupingStrategy) : DefaultTreeModel(SyntheticRootNode()) {
val rootNode = getRoot() as Node
fun addUsages(usages: List<MemberUsage>) {
usages.forEach { usage ->
var curNode = rootNode
strategy.groupingOrder.forEach { nodeType ->
val key = nodeType.key(usage)
if (key != null) {
val rank = strategy.getRank(nodeType)
curNode = curNode.getOrCreate(rank, key, nodeType, usage, this)
curNode.usageCount++
}
}
}
reload()
}
/**
* Notify that [child] node has been inserted into [parent] one by the specified [index]
*/
fun fireNodeInserted(parent: Node, child: Node, index: Int) = fireTreeNodesInserted(
this, parent.path, intArrayOf(index), arrayOf(child))
}
/**
* Describes node types in [UsagesTree] and its rendering characteristics
*/
enum class NodeType(
/**
* Returns key for ordering nodes with the same rank.
* Returns `false` if this [NodeType] does not support the specified usage.
*/
val key: (MemberUsage) -> String?,
/**
* Renders the specified node
*/
val renderFunc: (node: UsageGroupNode, renderer: UsagesTreeCellRenderer, usage: MemberUsage) -> Unit
) {
ROOT(key = { "" }, renderFunc = { node, renderer, _ ->
renderer.append("Found usages", com.intellij.ui.SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES)
renderer.appendUsagesCount(node = node, bold = true)
}),
// SEARCHED_FILE, todo add it
SEARCHED_PACKAGE(key = { it.member.packageName() }, renderFunc = { node, renderer, usage ->
renderer.icon = PlatformIcons.PACKAGE_ICON
renderer.append(usage.member.packageName())
renderer.appendUsagesCount(node = node, bold = false)
}),
SEARCHED_CLASS(key = { classKey(it) }, renderFunc = { node, renderer, usage ->
renderer.icon = PlatformIcons.CLASS_ICON
renderer.append(usage.member.simpleClassName())
renderer.appendUsagesCount(node = node, bold = false)
}),
SEARCHED_CLASS_MEMBER(key = { classMemberKey(it) }, renderFunc = { node, renderer, usage ->
renderer.icon = when (usage.member.type) {
METHOD -> PlatformIcons.METHOD_ICON
FIELD -> PlatformIcons.FIELD_ICON
else -> throw IllegalStateException()
}
renderer.append(usage.member.simpleMemberName())
renderer.appendUsagesCount(node = node, bold = false)
}),
ARTIFACT(key = { it.location.artifact.toString() }, renderFunc = { node, renderer, usage ->
renderer.icon = PlatformIcons.LIBRARY_ICON
renderer.append(usage.location.artifact.toString())
renderer.appendUsagesCount(node = node, bold = false)
}),
USAGE_KIND(key = { it.usageKind.ordinal.toString() }, renderFunc = { node, renderer, usage ->
renderer.append(usage.usageKind.description)
renderer.appendUsagesCount(node = node, bold = false)
}),
TARGET_FILE(key = { it.location.file }, renderFunc = { node, renderer, usage ->
renderer.icon = PlatformIcons.FILE_ICON
renderer.append(usage.location.file.toString())
renderer.appendUsagesCount(node = node, bold = false)
}),
TARGET_PACKAGE(key = { it.location.member.packageName() }, renderFunc = { node, renderer, usage ->
renderer.icon = PlatformIcons.PACKAGE_ICON
renderer.append(usage.location.member.packageName())
renderer.appendUsagesCount(node = node, bold = false)
}),
TARGET_CLASS(key = { classKey(it) }, renderFunc = { node, renderer, usage ->
renderer.icon = PlatformIcons.CLASS_ICON
renderer.append(usage.member.simpleClassName())
renderer.appendUsagesCount(node = node, bold = false)
}),
TARGET_CLASS_MEMBER(key = { classMemberKey(it) }, renderFunc = { node, renderer, usage ->
renderer.icon = when (usage.member.type) {
METHOD -> PlatformIcons.METHOD_ICON
FIELD -> PlatformIcons.FIELD_ICON
else -> throw IllegalStateException()
}
renderer.append(usage.member.simpleMemberName())
renderer.appendUsagesCount(node = node, bold = false)
}),
TARGET_LINE(key = { "${it.location.file} ${it.location.lineNumber}" }, renderFunc = { node, renderer, usage ->
renderer.append(usage.location.lineNumber.toString(), com.intellij.ui.SimpleTextAttributes.GRAY_ATTRIBUTES)
renderer.append(" ")
renderer.append(usage.location.file.toString())
renderer.appendUsagesCount(node = node, bold = false)
}) // should be leaf always
}
/**
* Creates key for classes.
* Returns `null` if the searched element is package.
*/
private fun classKey(usage: MemberUsage): String? {
return if (usage.member.type == MemberType.PACKAGE) null else usage.member.className()
}
/**
* Creates key for class member (field or method).
* Returns `null` if the searched element is not one of them.
*/
private fun classMemberKey(usage: MemberUsage) = when (usage.member.type) {
FIELD, METHOD -> usage.member.simpleName()
else -> null
}
abstract class Node : DefaultMutableTreeNode() {
var usageCount: Int = 0
private var textForSearch: String? = null
fun getOrCreate(rank: Int, key: String, type: NodeType, usage: MemberUsage, treeModel: UsagesTreeModel): UsageGroupNode {
// Find index with first child (child_rank, child_key) >= (rank, key)
// ATTENTION! BINARY SEARCH HERE!
var l = -1
var r = childCount
while (l + 1 < r) {
val m = (l + r) / 2
val mChild = getChildAt(m) as UsageGroupNode
val less = mChild.rank < rank || (mChild.rank == rank && mChild.key < key)
if (less) l = m else r = m
}
// children[r] >= searched
// If found child has searched rank and key, return it
print("${children().toList().map { it as UsageGroupNode }.map { "(${it.key} ${it.rank})" }} $r ")
val insertIndex = r
if (insertIndex < childCount) {
val child = getChildAt(insertIndex) as UsageGroupNode
if (child.rank == rank && child.key == key) {
println(" FOUND")
return child
}
}
// Create new node and insert
val newNode = UsageGroupNode(type, rank, key, usage)
insert(newNode, insertIndex)
treeModel.fireNodeInserted(this, newNode, insertIndex)
println(children().toList().map { it as UsageGroupNode }.map { "(${it.key} ${it.rank})" })
return newNode
}
fun render(renderer: UsagesTreeCellRenderer) {
renderImpl(renderer)
textForSearch = renderer.toString()
}
abstract fun renderImpl(renderer: UsagesTreeCellRenderer)
override fun getUserObject() = this
override fun toString(): String {
return textForSearch ?: super.toString()
}
}
class UsageGroupNode(val type: NodeType, val rank: Int, val key: String, val representativeUsage: MemberUsage) : Node() {
override fun renderImpl(renderer: UsagesTreeCellRenderer) = type.renderFunc(this, renderer, representativeUsage)
override fun toString(): String {
return type.key(representativeUsage)!!
}
}
class SyntheticRootNode : Node() {
override fun renderImpl(renderer: UsagesTreeCellRenderer) {
// This node is synthetic and should not be shown, do nothing
}
}
/**
* Renders [UsagesTree] nodes, delegates rendering to [UsageGroupNode]s
*/
class UsagesTreeCellRenderer : ColoredTreeCellRenderer() {
override fun customizeCellRenderer(tree: JTree, node: Any, selected: Boolean, expanded: Boolean,
leaf: Boolean, row: Int, hasFocus: Boolean) {
if (node is UsageGroupNode)
node.render(this)
else
append(node.toString())
SpeedSearchUtil.applySpeedSearchHighlighting(tree, this, true, mySelected)
}
fun appendUsagesCount(node: UsageGroupNode, bold: Boolean) {
val msg = " ${node.usageCount} ${(if (node.usageCount == 1) "usage" else "usages")}"
val attributes = if (bold) SimpleTextAttributes.GRAYED_BOLD_ATTRIBUTES
else SimpleTextAttributes.GRAYED_ATTRIBUTES
this.append(msg, attributes)
}
} | gpl-3.0 | 39f1e6e45481f711f548e67a048eecd5 | 38.615385 | 125 | 0.653809 | 4.399612 | false | false | false | false |
vsouhrada/kotlin-anko-demo | app/src/main/kotlin/com/vsouhrada/kotlin/android/anko/fibo/function/signin/login/presenter/LoginPresenter.kt | 1 | 2314 | package com.vsouhrada.kotlin.android.anko.fibo.function.signin.login.presenter
import com.chibatching.kotpref.blockingBulk
import com.hannesdorfmann.mosby.mvp.MvpBasePresenter
import com.vsouhrada.apps.fibo.core.db.bl.IUserBL
import com.vsouhrada.kotlin.android.anko.fibo.function.drawer.DrawerActivity
import com.vsouhrada.kotlin.android.anko.fibo.core.session.ISessionManager
import com.vsouhrada.kotlin.android.anko.fibo.core.session.model.UserInfoPrefModel
import com.vsouhrada.kotlin.android.anko.fibo.function.signin.login.model.AuthCredentials
import com.vsouhrada.kotlin.android.anko.fibo.function.signin.login.view.ILoginViewPresenter
import com.vsouhrada.kotlin.android.anko.fibo.function.signin.login.view.LoginView
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.uiThread
import javax.inject.Inject
/**
* @author vsouhrada
* @since 0.1.0
*/
class LoginPresenter @Inject constructor(val userBL: IUserBL, val sessionManager: ISessionManager)
: MvpBasePresenter<LoginView>(), ILoginViewPresenter {
//private var subscriber: Subscriber<UserDO>? = null
fun showLoginForm() {
view?.showLoginForm()
}
override fun doLogin(credentials: AuthCredentials) {
if (isViewAttached) {
view?.showLoading()
}
//cancelSubscription()
doAsync {
val user = userBL.getUser(credentials)
uiThread {
if (isViewAttached) {
if (user != null) {
sessionManager.putUserOnSession(user)
if (credentials.rememberMe) {
UserInfoPrefModel.blockingBulk { userId = user.id }
} else {
UserInfoPrefModel.blockingBulk { userId = -1 }
}
view?.loginSuccessful()
view?.ankoView?.startActivity<DrawerActivity>()
view?.ankoView?.owner?.finish()
} else {
view?.showError()
}
}
}
}
}
// /**
// * Cancels any previous callback
// */
// private fun cancelSubscription() {
// if (subscriber != null && !subscriber.isUnsubscribed()) {
// subscriber.unsubscribe()
// }
// }
//
// override fun detachView(retainInstance: Boolean) {
// super.detachView(retainInstance)
// if (!retainInstance) {
// cancelSubscription()
// }
// }
} | apache-2.0 | c8c0e05b4fb0f0e9663402ef6fdef400 | 29.866667 | 98 | 0.687554 | 4.059649 | false | false | false | false |
gumil/basamto | data/src/main/kotlin/io/github/gumil/data/model/Comment.kt | 1 | 1984 | /*
* The MIT License (MIT)
*
* Copyright 2017 Miguel Panelo
*
* 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.github.gumil.data.model
import com.squareup.moshi.Json
data class Comment(
override val id: String,
override val name: String,
override val subreddit: String,
override val author: String,
override val created: Long,
@Json(name = "created_utc")
override val createdUtc: Long,
val body: String,
@Json(name = "body_html")
val bodyHtml: String,
val controversiality: Int,
val depth: Int,
@Json(name = "link_id")
val linkId: String,
@Json(name = "parent_id")
val parentId: String,
val replies: Thing?,
@Json(name = "subreddit_id")
val subredditId: String,
override val gilded: Int,
override val score: Int,
override val ups: Int
) : Submission | mit | d0d4b1534e2fbf72afe4e73c4db8b81d | 29.075758 | 81 | 0.681956 | 4.379691 | false | false | false | false |
misaochan/apps-android-commons | app/src/main/java/fr/free/nrw/commons/upload/categories/UploadCategoryAdapterDelegates.kt | 3 | 797 | package fr.free.nrw.commons.upload.categories
import com.hannesdorfmann.adapterdelegates4.dsl.adapterDelegateLayoutContainer
import fr.free.nrw.commons.R
import fr.free.nrw.commons.category.CategoryItem
import kotlinx.android.synthetic.main.layout_upload_categories_item.*
fun uploadCategoryDelegate(onCategoryClicked: (CategoryItem) -> Unit) =
adapterDelegateLayoutContainer<CategoryItem, CategoryItem>(R.layout.layout_upload_categories_item) {
containerView.setOnClickListener {
item.isSelected = !item.isSelected
uploadCategoryCheckbox.isChecked = item.isSelected
onCategoryClicked(item)
}
bind {
uploadCategoryCheckbox.isChecked = item.isSelected
uploadCategoryCheckbox.text = item.name
}
}
| apache-2.0 | a8154b39cb7ef93a4c2c82f42079189a | 40.947368 | 104 | 0.739021 | 4.744048 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/ingestion/support/FilterHelper.kt | 1 | 567 | package net.nemerosa.ontrack.extension.github.ingestion.support
object FilterHelper {
fun includes(name: String, includes: String, excludes: String): Boolean {
val includesRegex = includes.toRegex(RegexOption.IGNORE_CASE)
val excludesRegex = excludes.takeIf { it.isNotBlank() }?.toRegex(RegexOption.IGNORE_CASE)
return includesRegex.matches(name) && (excludesRegex == null || !excludesRegex.matches(name))
}
fun excludes(name: String, includes: String, excludes: String): Boolean =
!includes(name, includes, excludes)
} | mit | c414b34b49500fe365794938e6de7f6a | 39.571429 | 101 | 0.717813 | 4.295455 | false | false | false | false |
liceoArzignano/app_bold | app/src/main/kotlin/it/liceoarzignano/bold/utils/ContentUtils.kt | 1 | 4212 | package it.liceoarzignano.bold.utils
import android.content.Context
import android.content.res.Resources
import com.firebase.jobdispatcher.*
import it.liceoarzignano.bold.R
import it.liceoarzignano.bold.events.EventsHandler
import it.liceoarzignano.bold.events.EventsJobUtils
import it.liceoarzignano.bold.marks.MarksHandler
import it.liceoarzignano.bold.settings.AppPrefs
import java.util.*
object ContentUtils {
fun getAverageElements(context: Context, filter: Int): Array<String> {
val handler = MarksHandler.getInstance(context)
val list = handler.getFilteredMarks("", filter)
val elements = ArrayList<String>()
for (item in list) {
if (!elements.contains(item.subject)) {
elements.add(item.subject)
}
}
return elements.toTypedArray()
}
fun eventCategoryToString(context: Context, category: Int): String =
when (category) {
0 -> context.getString(R.string.events_test)
1 -> context.getString(R.string.event_school)
2 -> context.getString(R.string.event_birthday)
3 -> context.getString(R.string.event_homework)
4 -> context.getString(R.string.event_reminder)
5 -> context.getString(R.string.event_meeting)
else -> context.getString(R.string.event_other)
}
fun getTomorrowInfo(context: Context): String {
val res = context.resources
var content = ""
val categories = intArrayOf(0 /* test */, 0 /* atSchool */,
0 /* bday */, 0 /* homeworks */,
0 /* reminder */, 0 /* meeting */,
0 /* others */)
val messages = intArrayOf(R.plurals.notification_test, R.plurals.notification_school,
R.plurals.notification_birthday, R.plurals.notification_homework,
R.plurals.notification_reminder, R.plurals.notification_meeting,
R.plurals.notification_other)
val handler = EventsHandler.getInstance(context)
val events = handler.tomorrow
if (events.isEmpty()) {
return ""
}
// Get data
for (event in events) {
categories[event.category]++
}
// Build message
categories.indices
.asSequence()
.filter { categories[it] > 0 }
.forEach { content = eventInfoBuilder(res, content, categories[it], messages[it]) }
content += " " + res.getString(R.string.notification_message_end)
return content
}
private fun eventInfoBuilder(res: Resources, orig: String, size: Int, id: Int): String {
val message =
if (orig.isEmpty())
res.getQuantityString(R.plurals.notification_message_first, size, size)
else
orig + res.getQuantityString(R.plurals.notification_message_half, size, size)
return message + " " + res.getQuantityString(id, size, size)
}
fun makeEventNotification(context: Context) {
val calendar = Calendar.getInstance()
val hr = calendar.get(Calendar.HOUR_OF_DAY)
var userPreference = 21
val prefs = AppPrefs(context)
if (!prefs.get(AppPrefs.KEY_NOTIF_EVENT, true)) {
return
}
when (prefs.get(AppPrefs.KEY_NOTIF_EVENT_TIME, "2")) {
"0" -> userPreference = 6
"1" -> userPreference = 15
}
val time =
(if (hr >= userPreference)
hr - userPreference + 1
else
24 + userPreference - hr) * 60 * 60
val dispatcher = FirebaseJobDispatcher(GooglePlayDriver(context))
val job = dispatcher.newJobBuilder()
.setService(EventsJobUtils::class.java)
.setTag("Bold_EventsJob")
.setLifetime(Lifetime.FOREVER)
.setTrigger(Trigger.executionWindow(time, time + 120))
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
.setReplaceCurrent(false)
.build()
dispatcher.mustSchedule(job)
}
}
| lgpl-3.0 | 326be7cf51fd5eabcfb089e6f00c4208 | 34.1 | 99 | 0.588082 | 4.558442 | false | false | false | false |
aglne/mycollab | mycollab-services/src/main/java/com/mycollab/module/project/domain/criteria/ComponentSearchCriteria.kt | 3 | 1188 | /**
* Copyright © MyCollab
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.module.project.domain.criteria
import com.mycollab.db.arguments.NumberSearchField
import com.mycollab.db.arguments.SearchCriteria
import com.mycollab.db.arguments.StringSearchField
class ComponentSearchCriteria : SearchCriteria() {
var projectId: NumberSearchField? = null
var componentName: StringSearchField? = null
var id: NumberSearchField? = null
var status: StringSearchField? = null
var userlead: StringSearchField? = null
}
| agpl-3.0 | 7456a58a5385c5e5e826d1013c93125f | 38.566667 | 81 | 0.759899 | 4.396296 | false | false | false | false |
scana/ok-gradle | plugin/src/test/java/me/scana/okgradle/data/BintrayRepositoryTest.kt | 1 | 4926 | package me.scana.okgradle.data
import com.google.gson.GsonBuilder
import me.scana.okgradle.data.repository.*
import org.junit.Assert.assertEquals
import org.junit.Test
import kotlin.test.assertNull
import kotlin.test.assertTrue
@Suppress("MemberVisibilityCanPrivate")
class BintrayRepositoryTest {
val mockOkHttpClient = MockOkHttpClient()
val networkClient = NetworkClient(mockOkHttpClient.instance())
val gson = GsonBuilder().create()
val repository = BintrayRepository(networkClient, gson)
@Test
fun `builds proper query`() {
repository.search("my_awesome_query").blockingGet()
val request = mockOkHttpClient.recentRequest()
assertEquals(
"GET",
request?.method
)
assertEquals(
"https://api.bintray.com/search/packages/maven?a=*my_awesome_query*&repo=jcenter&repo=bintray",
request?.url?.toString()
)
}
@Test
fun `returns empty result on empty query`() {
val result = repository.search("").blockingGet() as SearchResult.Success
assertNull(result.suggestion)
assertTrue(result.artifacts.isEmpty())
}
@Test
fun `searches and parses results - artifact id with version`() {
mockOkHttpClient.returnsJson(
"""
[{
"name": "commons-io:commons-io",
"repo": "jcenter",
"owner": "bintray",
"desc": null,
"system_ids": [
"commons-io:commons-io"
],
"versions": [
"2.4",
"2.3",
"2.2",
"2.1",
"2.0.1",
"2.0",
"1.4-backport-IO-168",
"1.4",
"1.3.2",
"1.3.1",
"1.3",
"1.2",
"1.1",
"1.0",
"0.1",
"20030203.000550",
"2.6",
"2.5"
],
"latest_version": "2.4"
},
{
"name": "org.carlspring.commons:commons-io",
"repo": "jcenter",
"owner": "bintray",
"desc": null,
"system_ids": [
"org.carlspring.commons:commons-io"
],
"versions": [
"1.1",
"1.0"
],
"latest_version": "1.1"
},
{
"name": "org.clojars.amit:commons-io",
"repo": "jcenter",
"owner": "bintray",
"desc": null,
"system_ids": [
"org.clojars.amit:commons-io"
],
"versions": [
"1.4.0"
],
"latest_version": "1.4.0"
},
{
"name": "org.kie.commons:kieora-commons-io",
"repo": "jcenter",
"owner": "bintray",
"desc": null,
"system_ids": [
"org.kie.commons:kieora-commons-io"
],
"versions": [
"6.0.0.CR3",
"6.0.0.Beta4",
"6.0.0.Beta5",
"6.0.0.CR2",
"6.0.0.Beta2",
"6.0.0.Beta1",
"6.0.0.Alpha9",
"6.0.0.CR1",
"6.0.0.CR5",
"6.0.0.CR4-Pre1",
"6.0.0.Beta3",
"6.0.0.CR4"
],
"latest_version": "6.0.0.CR3"
}]
""".trimIndent()
)
val result = repository.search("commons-io").blockingGet() as SearchResult.Success
assertNull(result.suggestion)
assertEquals(4, result.artifacts.size)
val artifact = result.artifacts[0]
assertEquals("2.4", artifact.version)
assertEquals("commons-io", artifact.groupId)
assertEquals("commons-io", artifact.name)
}
} | apache-2.0 | e43e59c16d94c89618c9898806a513c3 | 34.446043 | 111 | 0.358709 | 5.001015 | false | true | false | false |
ibaton/3House | mobile/src/main/java/treehou/se/habit/core/db/model/WidgetDB.kt | 1 | 1656 | package treehou.se.habit.core.db.model
import io.realm.annotations.Ignore
class WidgetDB /*extends RealmObject*/ {
var widgetId: String? = null
var type: String? = null
var icon: String? = null
get() = if (field == null || field == "none" || field == "image" || field == "") null else field
var label: String? = null
get() = if (field != null) field else ""
// Used for charts
var period: String? = null
var service: String? = null
var minValue = 0
var maxValue = 100
/*public RealmList<MappingDB> getMapping() {
return mapping;
}
public void setMapping(RealmList<MappingDB> mapping) {
this.mapping = mapping;
}*/
var step = 1f
/*public RealmList<WidgetDB> getWidget() {
return widget;
}*/
var url: String? = null
var item: ItemDB? = null
/*private RealmList<WidgetDB> widget;*/
//private RealmList<MappingDB> mapping;
/*public void setWidget(RealmList<WidgetDB> widget) {
this.widget = widget;
}*/
@Ignore
var linkedPage: LinkedPageDB? = null
companion object {
val TAG = "WidgetFactory"
// TODO convert to enum
val TYPE_DUMMY = "Dummy"
val TYPE_FRAME = "Frame"
val TYPE_SWITCH = "Switch"
val TYPE_COLORPICKER = "Colorpicker"
val TYPE_SELECTION = "Selection"
val TYPE_CHART = "Chart"
val TYPE_IMAGE = "Image"
val TYPE_VIDEO = "Video"
val TYPE_WEB = "Webview"
val TYPE_TEXT = "Text"
val TYPE_SLIDER = "Slider"
val TYPE_GROUP = "Group"
val TYPE_SETPOINT = "Setpoint"
}
}
| epl-1.0 | 61f70f2205e1604055a4c9cb7f1fb171 | 24.476923 | 104 | 0.585145 | 3.933492 | false | false | false | false |
whoww/SneakPeek | app/src/main/java/de/sneakpeek/adapter/ActorsAdapter.kt | 1 | 1300 | package de.sneakpeek.adapter
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import de.sneakpeek.R
import de.sneakpeek.data.MovieInfoCast
class ActorsAdapter(private var cast: List<MovieInfoCast>) : RecyclerView.Adapter<ActorsAdapter.MovieViewHolder>() {
fun addAll(cast: List<MovieInfoCast>) {
this.cast = cast
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.layout_detail_actor_list_element, parent, false)
return MovieViewHolder(itemView)
}
override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
val actor = cast[position]
holder.name.text = actor.name
holder.character.text = actor.character
}
override fun getItemCount(): Int {
return cast.size
}
class MovieViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var character: TextView = itemView.findViewById(R.id.actor_list_item_character) as TextView
var name: TextView = itemView.findViewById(R.id.actor_list_item_name) as TextView
}
}
| mit | 00fbfbd599c27e97a801027fa2613ca0 | 33.210526 | 124 | 0.731538 | 4.290429 | false | false | false | false |
HedvigInsurance/bot-service | src/main/java/com/hedvig/botService/chat/ConversationFactoryImpl.kt | 1 | 4775 | package com.hedvig.botService.chat
import com.google.i18n.phonenumbers.PhoneNumberUtil
import com.hedvig.botService.chat.house.HouseOnboardingConversation
import com.hedvig.botService.enteties.UserContext
import com.hedvig.botService.serviceIntegration.claimsService.ClaimsService
import com.hedvig.botService.serviceIntegration.lookupService.LookupService
import com.hedvig.botService.serviceIntegration.memberService.MemberService
import com.hedvig.botService.serviceIntegration.productPricing.ProductPricingService
import com.hedvig.botService.serviceIntegration.underwriter.Underwriter
import com.hedvig.botService.services.triggerService.TriggerService
import com.hedvig.libs.translations.Translations
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.ApplicationEventPublisher
import org.springframework.stereotype.Component
@Component
class ConversationFactoryImpl(
private val memberService: MemberService,
private val lookupService: LookupService,
private val underwriter: Underwriter,
private val productPricingService: ProductPricingService,
private val triggerService: TriggerService,
private val eventPublisher: ApplicationEventPublisher,
private val claimsService: ClaimsService,
private val statusBuilder: StatusBuilder,
private val translations: Translations,
@Value("\${hedvig.waitlist.length}") private val queuePos: Int?,
@Value("\${hedvig.appleUser.email}") private val appleUserEmail: String,
@Value("\${hedvig.appleUser.password}") private val appleUserPwd: String,
private val phoneNumberUtil: PhoneNumberUtil
) : ConversationFactory {
private val log = LoggerFactory.getLogger(ConversationFactoryImpl::class.java)
override fun createConversation(conversationClass: Class<*>, userContext: UserContext): Conversation {
if (conversationClass == CharityConversation::class.java) {
return CharityConversation(this, memberService, productPricingService, eventPublisher, translations, userContext)
}
if (conversationClass == ClaimsConversation::class.java) {
return ClaimsConversation(
eventPublisher,
claimsService,
productPricingService,
this,
memberService,
translations,
userContext
)
}
if (conversationClass == MainConversation::class.java) {
return MainConversation(this, eventPublisher, translations, userContext)
}
if (conversationClass == OnboardingConversationDevi::class.java) {
val onboardingConversationDevi = OnboardingConversationDevi(
memberService,
underwriter,
eventPublisher,
this,
translations,
appleUserEmail,
appleUserPwd,
phoneNumberUtil,
userContext
)
onboardingConversationDevi.queuePos = queuePos
return onboardingConversationDevi
}
if (conversationClass == HouseOnboardingConversation::class.java) {
val houseOnboardingConversation = HouseOnboardingConversation(
memberService, lookupService, eventPublisher, this, translations, userContext
)
houseOnboardingConversation.queuePos = queuePos
return houseOnboardingConversation
}
if (conversationClass == TrustlyConversation::class.java) {
return TrustlyConversation(triggerService, eventPublisher, translations, userContext)
}
if (conversationClass == FreeChatConversation::class.java) {
return FreeChatConversation(statusBuilder, eventPublisher, productPricingService, translations, userContext)
}
if (conversationClass == CallMeConversation::class.java) {
return CallMeConversation(eventPublisher, translations, userContext)
}
return if (conversationClass == MemberSourceConversation::class.java) {
MemberSourceConversation(eventPublisher, translations, userContext)
} else throw RuntimeException("Failed to create conversation")
}
override fun createConversation(conversationClassName: String, userContext: UserContext): Conversation {
try {
val concreteClass = Class.forName(conversationClassName)
return createConversation(concreteClass, userContext)
} catch (ex: ClassNotFoundException) {
log.error("Could not create conversation for classname: {}", conversationClassName, ex)
}
throw RuntimeException("Failed to create conversation")
}
}
| agpl-3.0 | d74b1341893c931a557ec946f401d795 | 42.409091 | 125 | 0.712461 | 5.565268 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-Coroutines/src/main/kotlin/reactvice/04_RxSubject_BroadcastChannel.kt | 2 | 3612 | package reactvice
import io.reactivex.subjects.BehaviorSubject
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.rx2.consumeEach
//RxJava 有个概念叫做 Subject,它会向它所有的订阅者广播数据。而协程里相对应的概念叫做 BroadcastChannel。
// Rx 中有着各种各样的 Subject,其中 BehaviorSubject 是用来管理状态的:
fun main1() {
val subject = BehaviorSubject.create<String>()
subject.onNext("one")
subject.onNext("two") // updates the state of BehaviorSubject, "one" value is lost
// now subscribe to this subject and print everything
subject.subscribe(System.out::println)
subject.onNext("three")
subject.onNext("four")
}
//你也可以在协程中订阅 subject,就像其他任意一个 reactive stream 一样。
//在这里,我们使用 Unconfined 上下文,通过它启动的订阅协程表现方式与 Rx 中的订阅一样。这也意味着启动的这个协程也会在同样的线程中立即执行。
@ExperimentalCoroutinesApi
fun main2() = runBlocking<Unit> {
val subject = BehaviorSubject.create<String>()
subject.onNext("one")
subject.onNext("two")
// now launch a coroutine to print everything
GlobalScope.launch(Dispatchers.Unconfined) { // launch coroutine in unconfined context
subject.consumeEach { println(it) }
}
subject.onNext("three")
subject.onNext("four")
}
//协程的优势在于很容易合并 UI 线程的更新操作。一个典型的 UI 程序不需要响应每一个状态变化,只有最近的状态才是有效的。
// 一旦 UI 线程空闲,一连串的状态更新只需要反映到 UI 上一次。下面的例子中,我们会使用主线程的上下文启动消费者协程来模拟这种情况,
// 可以使用 yield 函数来模拟一系列更新的中断,释放主线程:
fun main3() = runBlocking<Unit> {
val subject = BehaviorSubject.create<String>()
subject.onNext("one")
subject.onNext("two")
// now launch a coroutine to print the most recent update
launch { // use the context of the main thread for a coroutine
subject.consumeEach { println(it) }
}
subject.onNext("three")
subject.onNext("four")
yield() // yield the main thread to the launched coroutine <--- HERE
subject.onComplete() // now complete subject's sequence to cancel consumer, too
}
//如果纯用协程来,对应的实现是 ConflatedBroadcastChannel,它通过协程的 channel 直接提供了相同的逻辑,不再需要 reactive steam 桥接。
//BroadcastChannel 的另一个实现是 ArrayBroadcastChannel ,只要相关的订阅打开着,他就会把每一个事件传递给每一个订阅者。他与 Rx 中的 PublishSubject 类似。
// ArrayBroadcastChannel 构造函数的 capacity 参数指定了缓冲区的大小,这个缓冲区放置的是生产者等待接收者接收时可以先发送的数据个数。
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
fun main() = runBlocking<Unit> {
val broadcast = ConflatedBroadcastChannel<String>()
broadcast.offer("one")
broadcast.offer("two")
// now launch a coroutine to print the most recent update
launch { // use the context of the main thread for a coroutine
broadcast.consumeEach { println(it) }
}
broadcast.offer("three")
broadcast.offer("four")
yield() // yield the main thread to the launched coroutine
broadcast.close() // now close broadcast channel to cancel consumer, too
} | apache-2.0 | c3682960c59f2a6f079ac4a712d8b55e | 39.042857 | 107 | 0.748751 | 3.412911 | false | false | false | false |
RocketChat/Rocket.Chat.Android.Lily | app/src/main/java/chat/rocket/android/webview/oauth/ui/OauthWebViewActivity.kt | 2 | 5245 | package chat.rocket.android.webview.oauth.ui
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.webkit.CookieManager
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.core.net.toUri
import chat.rocket.android.R
import chat.rocket.android.util.extensions.decodeUrl
import chat.rocket.android.util.extensions.toJsonObject
import kotlinx.android.synthetic.main.activity_web_view.*
import kotlinx.android.synthetic.main.app_bar.*
import org.json.JSONObject
fun Context.oauthWebViewIntent(webPageUrl: String, state: String): Intent {
return Intent(this, OauthWebViewActivity::class.java).apply {
putExtra(INTENT_WEB_PAGE_URL, webPageUrl)
putExtra(INTENT_STATE, state)
}
}
private const val INTENT_WEB_PAGE_URL = "web_page_url"
private const val INTENT_STATE = "state"
private const val JSON_CREDENTIAL_TOKEN = "credentialToken"
private const val JSON_CREDENTIAL_SECRET = "credentialSecret"
const val INTENT_OAUTH_CREDENTIAL_TOKEN = "credential_token"
const val INTENT_OAUTH_CREDENTIAL_SECRET = "credential_secret"
// Shows a WebView to the user authenticate with its OAuth credential.
class OauthWebViewActivity : AppCompatActivity() {
private lateinit var webPageUrl: String
private lateinit var state: String
private var isWebViewSetUp: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_web_view)
webPageUrl = intent.getStringExtra(INTENT_WEB_PAGE_URL)
requireNotNull(webPageUrl) { "no web_page_url provided in Intent extras" }
state = intent.getStringExtra(INTENT_STATE)
requireNotNull(state) { "no state provided in Intent extras" }
// Ensures that the cookies is always removed when opening the webview.
CookieManager.getInstance().removeAllCookies(null)
setupToolbar()
}
override fun onResume() {
super.onResume()
if (!isWebViewSetUp) {
setupWebView()
isWebViewSetUp = true
}
}
override fun onBackPressed() {
if (web_view.canGoBack()) {
web_view.goBack()
} else {
closeView()
}
}
private fun setupToolbar() {
with(toolbar) {
title = getString(R.string.title_authentication)
setNavigationIcon(R.drawable.ic_close_white_24dp)
setNavigationOnClickListener { closeView() }
}
}
@SuppressLint("SetJavaScriptEnabled")
private fun setupWebView() {
with(web_view.settings) {
javaScriptEnabled = true
domStorageEnabled = true
// TODO Remove this workaround that is required to make Google OAuth to work. We should use Custom Tabs instead. See https://github.com/RocketChat/Rocket.Chat.Android/issues/968
if (webPageUrl.contains("google")) {
userAgentString =
"Mozilla/5.0 (Linux; Android 4.1.1; Galaxy Nexus Build/JRO03C) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/43.0.2357.65 Mobile Safari/535.19"
}
}
web_view.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
if (url.contains(JSON_CREDENTIAL_TOKEN) && url.contains(JSON_CREDENTIAL_SECRET)) {
if (isStateValid(url)) {
val jsonResult = url.decodeUrl()
.substringAfter("#")
.toJsonObject()
val credentialToken = getCredentialToken(jsonResult)
val credentialSecret = getCredentialSecret(jsonResult)
if (credentialToken.isNotEmpty() && credentialSecret.isNotEmpty()) {
closeView(Activity.RESULT_OK, credentialToken, credentialSecret)
}
}
}
view_loading.hide()
}
}
web_view.loadUrl(webPageUrl)
}
// If the states matches, then try to get the code, otherwise the request was created by a third party and the process should be aborted.
private fun isStateValid(url: String): Boolean =
url.substringBefore("#").toUri().getQueryParameter(INTENT_STATE) == state
private fun getCredentialToken(json: JSONObject): String =
json.optString(JSON_CREDENTIAL_TOKEN)
private fun getCredentialSecret(json: JSONObject): String =
json.optString(JSON_CREDENTIAL_SECRET)
private fun closeView(
activityResult: Int = Activity.RESULT_CANCELED,
credentialToken: String? = null,
credentialSecret: String? = null
) {
setResult(
activityResult,
Intent().putExtra(INTENT_OAUTH_CREDENTIAL_TOKEN, credentialToken).putExtra(
INTENT_OAUTH_CREDENTIAL_SECRET,
credentialSecret
)
)
finish()
overridePendingTransition(R.anim.hold, R.anim.slide_down)
}
} | mit | 21dc61cc5942cf945fcfd0db0601b91a | 37.859259 | 189 | 0.652812 | 4.691413 | false | false | false | false |
panpf/sketch | sketch/src/main/java/com/github/panpf/sketch/util/DrawableUtils.kt | 1 | 2544 | /*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.util
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Bitmap.Config.ARGB_8888
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
import androidx.annotation.WorkerThread
import androidx.core.graphics.component1
import androidx.core.graphics.component2
import androidx.core.graphics.component3
import androidx.core.graphics.component4
import com.github.panpf.sketch.cache.BitmapPool
import com.github.panpf.sketch.decode.internal.getOrCreate
import com.github.panpf.sketch.drawable.internal.CrossfadeDrawable
/**
* Find the last child [Drawable] from the specified Drawable
*/
@SuppressLint("RestrictedApi")
fun Drawable.getLastChildDrawable(): Drawable? {
return when (val drawable = this) {
is CrossfadeDrawable -> {
drawable.end?.getLastChildDrawable()
}
is LayerDrawable -> {
val layerCount = drawable.numberOfLayers.takeIf { it > 0 } ?: return null
drawable.getDrawable(layerCount - 1).getLastChildDrawable()
}
else -> drawable
}
}
/**
* Drawable into new Bitmap. Each time a new bitmap is drawn
*/
@WorkerThread
internal fun Drawable.toNewBitmap(
bitmapPool: BitmapPool,
disallowReuseBitmap: Boolean,
preferredConfig: Bitmap.Config? = null
): Bitmap {
val (oldLeft, oldTop, oldRight, oldBottom) = bounds
setBounds(0, 0, intrinsicWidth, intrinsicHeight)
val config = preferredConfig ?: ARGB_8888
val bitmap: Bitmap = bitmapPool.getOrCreate(
width = intrinsicWidth,
height = intrinsicHeight,
config = config,
disallowReuseBitmap = disallowReuseBitmap,
caller = "toNewBitmap"
)
val canvas = Canvas(bitmap)
draw(canvas)
setBounds(oldLeft, oldTop, oldRight, oldBottom) // restore bounds
return bitmap
} | apache-2.0 | 9a598ac09c01340e0a0952137d57f638 | 32.933333 | 85 | 0.732704 | 4.416667 | false | true | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/support/AccountManagerSupport.kt | 1 | 3261 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util.support
import android.accounts.*
import android.app.Activity
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.support.annotation.RequiresApi
import java.io.IOException
import java.util.concurrent.TimeUnit
fun AccountManager.removeAccountSupport(
account: Account,
activity: Activity? = null,
callback: AccountManagerCallback<Bundle>? = null,
handler: Handler? = null
): AccountManagerFuture<Bundle> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
return AccountManagerSupportL.removeAccount(this, account, activity, callback, handler)
}
@Suppress("DEPRECATION")
val future = this.removeAccount(account, { future ->
callback?.run(BooleanToBundleAccountManagerFuture(future))
}, handler)
return BooleanToBundleAccountManagerFuture(future)
}
object AccountManagerSupportL {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
internal fun removeAccount(
am: AccountManager, account: Account,
activity: Activity?,
callback: AccountManagerCallback<Bundle>?,
handler: Handler?
): AccountManagerFuture<Bundle> {
return am.removeAccount(account, activity, callback, handler)
}
}
private class BooleanToBundleAccountManagerFuture internal constructor(private val future: AccountManagerFuture<Boolean>) : AccountManagerFuture<Bundle> {
override fun cancel(mayInterruptIfRunning: Boolean): Boolean {
return future.cancel(mayInterruptIfRunning)
}
override fun isCancelled(): Boolean {
return future.isCancelled
}
override fun isDone(): Boolean {
return future.isDone
}
@Throws(OperationCanceledException::class, IOException::class, AuthenticatorException::class)
override fun getResult(): Bundle {
val result = Bundle()
result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, future.result)
return result
}
@Throws(OperationCanceledException::class, IOException::class, AuthenticatorException::class)
override fun getResult(timeout: Long, unit: TimeUnit): Bundle {
val result = Bundle()
result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, future.getResult(timeout, unit))
return result
}
} | gpl-3.0 | 2b9bb8652d5fc75ffa3fa71a14386e8f | 34.456522 | 154 | 0.718185 | 4.51662 | false | false | false | false |
stripe/stripe-android | payments-core/src/test/java/com/stripe/android/FraudDetectionDataParamsUtilsTest.kt | 1 | 4019 | package com.stripe.android
import com.google.common.truth.Truth.assertThat
import com.stripe.android.model.CardParamsFixtures
import com.stripe.android.model.ConfirmPaymentIntentParams
import com.stripe.android.model.ConfirmStripeIntentParams.Companion.PARAM_PAYMENT_METHOD_DATA
import com.stripe.android.model.PaymentMethodCreateParamsFixtures
import com.stripe.android.model.SourceParams
import com.stripe.android.networking.FraudDetectionDataParamsUtils
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import kotlin.test.Test
@RunWith(RobolectricTestRunner::class)
class FraudDetectionDataParamsUtilsTest {
private val fraudDetectionDataParamsUtils = FraudDetectionDataParamsUtils()
@Test
fun addUidParamsToPaymentIntent_withSource_addsParamsAtRightLevel() {
val updatedParams = fraudDetectionDataParamsUtils.addFraudDetectionData(
params = mapOf(
ConfirmPaymentIntentParams.PARAM_SOURCE_DATA to
SourceParams.createCardParams(CardParamsFixtures.DEFAULT).toParamMap()
),
fraudDetectionData = FRAUD_DETECTION_DATA
)
assertThat(updatedParams[ConfirmPaymentIntentParams.PARAM_SOURCE_DATA])
.isEqualTo(
mapOf(
"type" to "card",
"owner" to mapOf(
"address" to mapOf(
"city" to "San Francisco",
"country" to "US",
"line1" to "123 Market St",
"line2" to "#345",
"postal_code" to "94107",
"state" to "CA"
),
"name" to "Jenny Rosen"
),
"card" to mapOf(
"number" to CardNumberFixtures.VISA_NO_SPACES,
"exp_month" to 12,
"exp_year" to 2025,
"cvc" to "123"
),
"metadata" to mapOf("fruit" to "orange"),
"muid" to FRAUD_DETECTION_DATA.muid,
"guid" to FRAUD_DETECTION_DATA.guid,
"sid" to FRAUD_DETECTION_DATA.sid
)
)
}
@Test
fun addUidParamsToPaymentIntent_withPaymentMethodParams_addsUidAtRightLevel() {
val updatedParams = fraudDetectionDataParamsUtils.addFraudDetectionData(
params = mapOf(
PARAM_PAYMENT_METHOD_DATA to
PaymentMethodCreateParamsFixtures.DEFAULT_CARD.toParamMap()
),
fraudDetectionData = FRAUD_DETECTION_DATA
)
assertThat(updatedParams[PARAM_PAYMENT_METHOD_DATA])
.isEqualTo(
mapOf(
"type" to "card",
"billing_details" to mapOf(
"address" to mapOf(
"city" to "San Francisco",
"country" to "US",
"line1" to "1234 Main St",
"state" to "CA",
"postal_code" to "94111"
),
"email" to "[email protected]",
"name" to "Jenny Rosen",
"phone" to "1-800-555-1234"
),
"card" to mapOf(
"number" to CardNumberFixtures.VISA_NO_SPACES,
"exp_month" to 1,
"exp_year" to 2024,
"cvc" to "111"
),
"muid" to FRAUD_DETECTION_DATA.muid,
"guid" to FRAUD_DETECTION_DATA.guid,
"sid" to FRAUD_DETECTION_DATA.sid
)
)
}
private companion object {
private val FRAUD_DETECTION_DATA = FraudDetectionDataFixtures.create()
}
}
| mit | 564306407a2dce20e7a8f6511c151693 | 39.59596 | 93 | 0.515302 | 4.919217 | false | true | false | false |
paulofernando/localchat | app/src/main/kotlin/site/paulo/localchat/data/model/firebase/NearbyUser.kt | 1 | 432 | package site.paulo.localchat.data.model.firebase
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class NearbyUser(
val lastGeoUpdate: Long = 0,
val name: String = "",
val email: String = "",
val age: Long = 0L,
val pic: String = "") : Parcelable {
fun getSummarizedUser(): SummarizedUser {
return SummarizedUser(this.name, this.pic)
}
} | apache-2.0 | 08271b62522fa610d32dabbcf605bd8a | 24.470588 | 50 | 0.650463 | 3.891892 | false | false | false | false |
mvarnagiris/expensius | app/src/main/kotlin/com/mvcoding/expensius/feature/DragAndDropTouchHelperCallback.kt | 1 | 2335 | /*
* Copyright (C) 2016 Mantas Varnagiris.
*
* 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.
*/
package com.mvcoding.expensius.feature
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.support.v7.widget.helper.ItemTouchHelper.DOWN
import android.support.v7.widget.helper.ItemTouchHelper.UP
import rx.subjects.PublishSubject
class DragAndDropTouchHelperCallback(
private val adapter: BaseAdapter<*, *>,
private val itemMovedSubject: PublishSubject<ItemMoved>,
private val canDropOver: (RecyclerView.ViewHolder, RecyclerView.ViewHolder) -> Boolean = { current, target -> true }) :
ItemTouchHelper.SimpleCallback(UP or DOWN, 0) {
private var fromPosition: Int = -1
private var toPosition: Int = -1
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
if (fromPosition == -1) {
fromPosition = viewHolder.adapterPosition
}
toPosition = target.adapterPosition
adapter.moveItem(viewHolder.adapterPosition, toPosition)
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, position: Int) {
}
override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
super.onSelectedChanged(viewHolder, actionState)
if (actionState == ItemTouchHelper.ACTION_STATE_IDLE) {
itemMovedSubject.onNext(ItemMoved(fromPosition, toPosition))
fromPosition = -1
toPosition = -1
}
}
override fun canDropOver(recyclerView: RecyclerView, current: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
return canDropOver(current, target)
}
data class ItemMoved(val fromPosition: Int, val toPosition: Int)
} | gpl-3.0 | dc8f74c10a464955579ce34b1ccb6e0a | 39.275862 | 134 | 0.72848 | 4.814433 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/cargo/RustfmtWatcher.kt | 2 | 4689 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo
import com.intellij.execution.ExecutionException
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManagerListener
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.guessProjectForFile
import com.intellij.util.DocumentUtil
import com.intellij.util.containers.ContainerUtil
import org.rust.cargo.project.model.CargoProject
import org.rust.cargo.project.model.cargoProjects
import org.rust.cargo.project.settings.rustfmtSettings
import org.rust.cargo.project.settings.toolchain
import org.rust.cargo.runconfig.command.workingDirectory
import org.rust.cargo.toolchain.tools.Rustfmt
import org.rust.cargo.toolchain.tools.Rustup.Companion.checkNeedInstallRustfmt
import org.rust.cargo.toolchain.tools.rustfmt
import org.rust.lang.core.psi.isNotRustFile
import org.rust.openapiext.checkIsDispatchThread
import org.rust.openapiext.virtualFile
@Service
class RustfmtWatcher {
private val documentsToReformatLater: MutableSet<Document> = ContainerUtil.newConcurrentSet()
private var isSuppressed: Boolean = false
fun withoutReformatting(action: () -> Unit) {
val oldStatus = isSuppressed
try {
isSuppressed = true
action()
} finally {
isSuppressed = oldStatus
}
}
fun reformatDocumentLater(document: Document): Boolean {
val file = document.virtualFile ?: return false
if (file.isNotRustFile) return false
val project = guessProjectForFile(file) ?: return false
if (!project.rustfmtSettings.state.runRustfmtOnSave) return false
return documentsToReformatLater.add(document)
}
class RustfmtListener : FileDocumentManagerListener {
override fun beforeAllDocumentsSaving() {
val documentsToReformatLater = getInstanceIfCreated()?.documentsToReformatLater
?: return
val documentsToReformat = documentsToReformatLater.toList()
documentsToReformatLater.clear()
for ((cargoProject, documents) in documentsToReformat.groupBy(::findCargoProject)) {
if (cargoProject == null) continue
if (DumbService.isDumb(cargoProject.project)) {
documentsToReformatLater += documents
} else {
reformatDocuments(cargoProject, documents)
}
}
}
override fun beforeDocumentSaving(document: Document) {
val isSuppressed = getInstanceIfCreated()?.isSuppressed == true
if (!isSuppressed) {
val cargoProject = findCargoProject(document) ?: return
if (DumbService.isDumb(cargoProject.project)) {
getInstance().reformatDocumentLater(document)
} else {
reformatDocuments(cargoProject, listOf(document))
}
}
}
override fun unsavedDocumentsDropped() {
getInstanceIfCreated()?.documentsToReformatLater?.clear()
}
}
companion object {
fun getInstance(): RustfmtWatcher = service()
private fun getInstanceIfCreated(): RustfmtWatcher? = serviceIfCreated()
private fun findCargoProject(document: Document): CargoProject? {
val file = document.virtualFile ?: return null
val project = guessProjectForFile(file) ?: return null
return project.cargoProjects.findProjectForFile(file)
}
private fun reformatDocuments(cargoProject: CargoProject, documents: List<Document>) {
val project = cargoProject.project
if (!project.rustfmtSettings.state.runRustfmtOnSave) return
val rustfmt = project.toolchain?.rustfmt() ?: return
if (checkNeedInstallRustfmt(cargoProject.project, cargoProject.workingDirectory)) return
documents.forEach { rustfmt.reformatDocument(cargoProject, it) }
}
@Throws(ExecutionException::class)
private fun Rustfmt.reformatDocument(cargoProject: CargoProject, document: Document) {
checkIsDispatchThread()
if (!document.isWritable) return
val formattedText = reformatDocumentTextOrNull(cargoProject, document) ?: return
DocumentUtil.writeInRunUndoTransparentAction { document.setText(formattedText) }
}
}
}
| mit | cf707b193bd4f94cffb2aba385d44326 | 39.076923 | 100 | 0.691619 | 5.147091 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/data/local/implementation/RealmContentLocalRepository.kt | 1 | 2622 | package com.habitrpg.android.habitica.data.local.implementation
import com.habitrpg.android.habitica.data.local.ContentLocalRepository
import com.habitrpg.android.habitica.extensions.skipNull
import com.habitrpg.android.habitica.models.ContentResult
import com.habitrpg.android.habitica.models.WorldState
import com.habitrpg.android.habitica.models.inventory.Quest
import com.habitrpg.android.habitica.models.social.Group
import hu.akarnokd.rxjava3.bridge.RxJavaBridge
import io.reactivex.rxjava3.core.Flowable
import io.realm.Realm
open class RealmContentLocalRepository(realm: Realm) : RealmBaseLocalRepository(realm), ContentLocalRepository {
override fun saveContent(contentResult: ContentResult) {
executeTransactionAsync { realm1 ->
contentResult.potion?.let { realm1.insertOrUpdate(it) }
contentResult.armoire?.let { realm1.insertOrUpdate(it) }
contentResult.gear?.flat?.let { realm1.insertOrUpdate(it) }
realm1.insertOrUpdate(contentResult.quests)
realm1.insertOrUpdate(contentResult.eggs)
realm1.insertOrUpdate(contentResult.food)
realm1.insertOrUpdate(contentResult.hatchingPotions)
realm1.insertOrUpdate(contentResult.special)
realm1.insertOrUpdate(contentResult.pets)
realm1.insertOrUpdate(contentResult.mounts)
realm1.insertOrUpdate(contentResult.spells)
realm1.insertOrUpdate(contentResult.special)
realm1.insertOrUpdate(contentResult.appearances)
realm1.insertOrUpdate(contentResult.backgrounds)
realm1.insertOrUpdate(contentResult.faq)
}
}
override fun getWorldState(): Flowable<WorldState> {
return RxJavaBridge.toV3Flowable(
realm.where(WorldState::class.java)
.findAll()
.asFlowable()
.filter { it.isLoaded && it.size > 0 }
.map { it.first() }
)
.skipNull()
}
override fun saveWorldState(worldState: WorldState) {
val tavern = getUnmanagedCopy(
realm.where(Group::class.java)
.equalTo("id", Group.TAVERN_ID)
.findFirst() ?: Group()
)
if (!tavern.isManaged) {
tavern.id = Group.TAVERN_ID
}
if (tavern.quest == null) {
tavern.quest = Quest()
}
tavern.quest?.active = worldState.worldBossActive
tavern.quest?.key = worldState.worldBossKey
tavern.quest?.progress = worldState.progress
save(tavern)
save(worldState)
}
}
| gpl-3.0 | 4ca6597fc6cdc1acdabd834c507adba8 | 38.134328 | 112 | 0.668192 | 4.348259 | false | false | false | false |
RSDT/Japp16 | app/src/main/java/nl/rsdt/japp/jotial/data/structures/area348/VosInfo.kt | 1 | 10519 | package nl.rsdt.japp.jotial.data.structures.area348
import android.graphics.Color
import android.os.Parcel
import android.os.Parcelable
import android.util.Log
import com.google.gson.Gson
import com.google.gson.JsonParseException
import com.google.gson.annotations.SerializedName
import com.google.gson.stream.JsonReader
import nl.rsdt.japp.R
import nl.rsdt.japp.application.JappPreferences
import nl.rsdt.japp.jotial.maps.sighting.SightingIcon
import org.acra.ktx.sendWithAcra
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 20-10-2015
* Class that servers as deserialization object for the VosInfo.
*/
class VosInfo
/**
* Initializes a new instance of VosInfo from the parcel.
*
* @param in The parcel where the instance should be created from.
*/
protected constructor(`in`: Parcel) : BaseInfo(`in`), Parcelable {
@SerializedName("datetime")
/**
* The dateTime the vosInfo was created.
*/
val datetime: String?
@SerializedName("team")
/**
* The team of the VosInfo as a char.
*/
val team: String?
@SerializedName("team_naam")
/**
* The team of the VosInfo as a whole name.
*/
val teamName: String?
@SerializedName("opmerking")
/**
* A extra of the VosInfo.
*/
val note: String?
@SerializedName("extra")
/**
* The user of the VosInfo.
*/
val extra: String?
@SerializedName("hint_nr")
/**
* The hint number of the VosInfo.
*/
val hintNr: Int
@SerializedName("icon")
/**
* The icon of the VosInfo.
*/
var icon: Int = 0
val associatedDrawable: Int
get() = VosInfo.getAssociatedDrawable(this)
val associatedColor: Int
get() = VosInfo.getAssociatedColor(this)
init {
datetime = `in`.readString()
team = `in`.readString()
teamName = `in`.readString()
note = `in`.readString()
extra = `in`.readString()
hintNr = `in`.readInt()
icon = `in`.readInt()
}
fun getAssociatedColor(alpha: Int): Int {
return VosInfo.getAssociatedColor(this, alpha)
}
override fun writeToParcel(dest: Parcel, flags: Int) {
super.writeToParcel(dest, flags)
dest.writeString(datetime)
dest.writeString(team)
dest.writeString(teamName)
dest.writeString(note)
dest.writeString(extra)
dest.writeInt(hintNr)
dest.writeInt(icon)
}
override fun describeContents(): Int {
return 0
}
companion object {
val CREATOR: Parcelable.Creator<VosInfo> = object : Parcelable.Creator<VosInfo> {
override fun createFromParcel(`in`: Parcel): VosInfo {
return VosInfo(`in`)
}
override fun newArray(size: Int): Array<VosInfo?> {
return arrayOfNulls(size)
}
}
/**
* Deserializes a VosInfo from JSON.
*
* @param json The JSON where the VosInfo should be deserialized from.
* @return The VosInfo deserialized from the JSON.
*/
fun fromJson(json: String): VosInfo? {
try {
val jsonReader = JsonReader(java.io.StringReader(json))
jsonReader.isLenient = true
return Gson().fromJson<VosInfo>(jsonReader, VosInfo::class.java)
} catch (e: JsonParseException) {
Log.e("VosInfo", e.message, e)
e.sendWithAcra()
}
return null
}
/**
* Deserializes a VosInfo array from JSON.
*
* @param json The JSON where the array should be deserialized from.
* @return The array of VosInfo deserialized from the JSON.
*/
fun fromJsonArray(json: String): Array<VosInfo>? {
try {
val jsonReader = JsonReader(java.io.StringReader(json))
jsonReader.isLenient = true
return Gson().fromJson<Array<VosInfo>>(jsonReader, Array<VosInfo>::class.java)
} catch (e: JsonParseException) {
Log.e("VosInfo", e.message, e)
e.sendWithAcra()
}
return null
}
/**
* Gets the Drawable associated with the given VosInfo.
*
* @param info The VosInfo to get the associated icon from.
* @return A int pointing to the associated drawable.
*/
fun getAssociatedDrawable(info: VosInfo): Int {
val color = MetaColorInfo.ColorNameInfo.DeelgebiedColor.valueOf(JappPreferences.getColorName(info.team?:"x"))
return when (info.icon) {
SightingIcon.DEFAULT -> when (color) {
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Groen -> R.drawable.vos_groen_2
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Rood -> R.drawable.vos_rood_2
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Paars -> R.drawable.vos_paars_2
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Oranje -> R.drawable.vos_oranje_2
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Blauw -> R.drawable.vos_blauw_2
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Zwart -> R.drawable.vos_zwart_2
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Turquoise -> R.drawable.vos_turquoise_2
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Onbekend -> R.drawable.vos_zwart_2
}
SightingIcon.HUNT -> when (color) {
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Groen -> R.drawable.vos_groen_4
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Rood -> R.drawable.vos_rood_4
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Paars -> R.drawable.vos_paars_4
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Oranje -> R.drawable.vos_oranje_4
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Blauw -> R.drawable.vos_blauw_4
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Zwart -> R.drawable.vos_zwart_4
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Turquoise -> R.drawable.vos_turquoise_4
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Onbekend -> R.drawable.vos_zwart_4
}
SightingIcon.SPOT -> when (color) {
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Groen -> R.drawable.vos_groen_3
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Rood -> R.drawable.vos_rood_3
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Paars -> R.drawable.vos_paars_3
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Oranje -> R.drawable.vos_oranje_3
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Blauw -> R.drawable.vos_blauw_3
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Zwart -> R.drawable.vos_zwart_3
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Turquoise -> R.drawable.vos_turquoise_3
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Onbekend -> R.drawable.vos_zwart_3
}
SightingIcon.LAST_LOCATION -> when (color) {
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Groen -> R.drawable.vos_groen_1
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Rood -> R.drawable.vos_rood_1
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Paars -> R.drawable.vos_paars_1
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Oranje -> R.drawable.vos_oranje_1
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Blauw -> R.drawable.vos_blauw_1
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Zwart -> R.drawable.vos_zwart_1
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Turquoise -> R.drawable.vos_turquoise_1
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Onbekend -> R.drawable.vos_zwart_1
}
else -> when (color) {
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Groen -> R.drawable.vos_groen_2
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Rood -> R.drawable.vos_rood_2
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Paars -> R.drawable.vos_paars_2
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Oranje -> R.drawable.vos_oranje_2
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Blauw -> R.drawable.vos_blauw_2
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Zwart -> R.drawable.vos_zwart_2
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Turquoise -> R.drawable.vos_turquoise_2
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Onbekend -> R.drawable.vos_zwart_2
}
}
}
fun getAssociatedColor(info: VosInfo): Int {
return getAssociatedColor(info.team)
}
fun getAssociatedColor(info: VosInfo, alpha: Int): Int {
return getAssociatedColor(info.team, alpha)
}
@JvmOverloads
fun getAssociatedColor(team: String?, alpha: Int = 255): Int {
val color = MetaColorInfo.ColorNameInfo.DeelgebiedColor.valueOf(JappPreferences.getColorName(team?:"x"))
when (color) {
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Rood -> return Color.argb(alpha, 255, 0, 0)
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Groen -> return Color.argb(alpha, 0, 255, 0)
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Blauw -> return Color.argb(alpha, 0, 0, 255)
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Turquoise -> return Color.argb(alpha, 0, 255, 255)
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Paars -> return Color.argb(alpha, 255, 0, 255)
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Oranje -> return Color.argb(alpha, 255, 162, 0)
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Zwart -> return Color.argb(alpha, 0, 0, 0)
MetaColorInfo.ColorNameInfo.DeelgebiedColor.Onbekend -> return Color.WHITE
else -> return Color.WHITE
}
}
}
}
| apache-2.0 | a79b640135533e02cb42b70759eddb13 | 41.415323 | 121 | 0.611465 | 4.212655 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/FirstActivity.kt | 1 | 11295 | /*
* Copyright (C) 2017 yvolk (Yuri Volkov), http://yurivolkov.com
*
* 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.andstatus.app
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.AndroidRuntimeException
import androidx.appcompat.app.AppCompatActivity
import org.andstatus.app.context.MyContext
import org.andstatus.app.context.MyContextHolder
import org.andstatus.app.context.MyContextState
import org.andstatus.app.context.MyLocale
import org.andstatus.app.context.MyPreferences
import org.andstatus.app.context.MySettingsGroup
import org.andstatus.app.data.DbUtils
import org.andstatus.app.os.UiThreadExecutor
import org.andstatus.app.timeline.TimelineActivity
import org.andstatus.app.util.Identifiable
import org.andstatus.app.util.Identified
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.SharedPreferencesUtil
import org.andstatus.app.util.TriState
import java.util.concurrent.CompletableFuture
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import java.util.function.BiConsumer
/** Activity to be started, when Application is not initialised yet (or needs re-initialization).
* It allows to avoid "Application not responding" errors.
* It is transparent and shows progress indicator only, launches next activity after application initialization.
*/
class FirstActivity(
private val identifiable: Identifiable = Identified(FirstActivity::class)
) : AppCompatActivity(), Identifiable by identifiable {
enum class NeedToStart {
HELP, CHANGELOG, OTHER
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
try {
if (isFirstrun.compareAndSet(true, false)) {
MyLocale.onAttachBaseContext(this)
}
setContentView(R.layout.loading)
} catch (e: Throwable) {
MyLog.w(this, "Couldn't setContentView", e)
}
parseNewIntent(intent)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
parseNewIntent(intent)
}
private fun parseNewIntent(intent: Intent?) {
when (MyAction.fromIntent(intent)) {
MyAction.INITIALIZE_APP -> MyContextHolder.myContextHolder.initialize(this)
.whenSuccessAsync({ myContext: MyContext? -> finish() }, UiThreadExecutor.INSTANCE)
MyAction.SET_DEFAULT_VALUES -> {
setDefaultValuesOnUiThread(this)
finish()
}
MyAction.CLOSE_ALL_ACTIVITIES -> finish()
else -> if ( MyContextHolder.myContextHolder.getFuture().isReady() || MyContextHolder.myContextHolder.getNow().state == MyContextState.UPGRADING) {
startNextActivitySync( MyContextHolder.myContextHolder.getNow(), intent)
finish()
} else {
MyContextHolder.myContextHolder.initialize(this)
.with { future: CompletableFuture<MyContext> ->
future.whenCompleteAsync(startNextActivity, UiThreadExecutor.INSTANCE)
}
}
}
}
private val startNextActivity: BiConsumer<MyContext?, Throwable?> = BiConsumer { myContext: MyContext?, throwable: Throwable? ->
var launched = false
if (myContext != null && myContext.isReady && !myContext.isExpired) {
try {
startNextActivitySync(myContext, intent)
launched = true
} catch (e: AndroidRuntimeException) {
MyLog.w(instanceTag, "Launching next activity from firstActivity", e)
} catch (e: SecurityException) {
MyLog.d(instanceTag, "Launching activity", e)
}
}
if (!launched) {
HelpActivity.startMe(
if (myContext == null) MyContextHolder.myContextHolder.getNow().context else myContext.context,
true, HelpActivity.PAGE_LOGO)
}
finish()
}
private fun startNextActivitySync(myContext: MyContext, myIntent: Intent?) {
when (needToStartNext(this, myContext)) {
NeedToStart.HELP -> HelpActivity.startMe(this, true, HelpActivity.PAGE_LOGO)
NeedToStart.CHANGELOG -> HelpActivity.startMe(this, true, HelpActivity.PAGE_CHANGELOG)
else -> {
val intent = Intent(this, TimelineActivity::class.java)
if (myIntent != null) {
val action = myIntent.action
if (!action.isNullOrEmpty()) {
intent.action = action
}
val data = myIntent.data
if (data != null) {
intent.data = data
}
val extras = myIntent.extras
if (extras != null) {
intent.putExtras(extras)
}
}
startActivity(intent)
}
}
}
companion object {
private val SET_DEFAULT_VALUES: String = "setDefaultValues"
private val resultOfSettingDefaults: AtomicReference<TriState> = AtomicReference(TriState.UNKNOWN)
var isFirstrun: AtomicBoolean = AtomicBoolean(true)
/**
* Based on http://stackoverflow.com/questions/14001963/finish-all-activities-at-a-time
*/
fun closeAllActivities(context: Context) {
context.startActivity(MyAction.CLOSE_ALL_ACTIVITIES.newIntent()
.setClass(context, FirstActivity::class.java)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK + Intent.FLAG_ACTIVITY_NEW_TASK)
)
}
fun goHome(activity: MyActivity) {
try {
MyLog.v(activity.instanceTag) { "goHome"}
startApp(activity)
} catch (e: Exception) {
MyLog.v(activity.instanceTag, "goHome", e)
MyContextHolder.myContextHolder.thenStartApp()
}
}
fun startApp(myContext: MyContext) {
myContext.context.let { startApp(it) }
}
private fun startApp(context: Context) {
MyLog.i(context, "startApp")
val intent = Intent(context, FirstActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
}
fun needToStartNext(context: Context, myContext: MyContext): NeedToStart {
if (!myContext.isReady) {
MyLog.i(context, "Context is not ready: " + myContext.toString())
return NeedToStart.HELP
} else if (myContext.accounts.isEmpty) {
MyLog.i(context, "No AndStatus Accounts yet")
return NeedToStart.HELP
}
return if (myContext.isReady && checkAndUpdateLastOpenedAppVersion(context, false)) {
NeedToStart.CHANGELOG
} else NeedToStart.OTHER
}
/**
* @return true if we opened previous version
*/
fun checkAndUpdateLastOpenedAppVersion(context: Context, update: Boolean): Boolean {
var changed = false
val versionCodeLast = SharedPreferencesUtil.getLong(MyPreferences.KEY_VERSION_CODE_LAST)
val pm = context.getPackageManager()
val pi: PackageInfo?
try {
pi = pm.getPackageInfo(context.getPackageName(), 0)
val versionCode = pi.versionCode
if (versionCodeLast < versionCode) {
// Even if the Actor will see only the first page of the Help activity,
// count this as showing the Change Log
MyLog.v(FirstActivity::class
) {
("Last opened version=" + versionCodeLast
+ ", current is " + versionCode
+ if (update) ", updating" else "")
}
changed = true
if (update && MyContextHolder.myContextHolder.getNow().isReady) {
SharedPreferencesUtil.putLong(MyPreferences.KEY_VERSION_CODE_LAST, versionCode.toLong())
}
}
} catch (e: PackageManager.NameNotFoundException) {
MyLog.e(FirstActivity::class, "Unable to obtain package information", e)
}
return changed
}
fun startMeAsync(context: Context, myAction: MyAction) {
val intent = Intent(context, FirstActivity::class.java)
intent.action = myAction.action
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
/** @return success
*/
fun setDefaultValues(context: Context?): Boolean {
if (context == null) {
MyLog.e(FirstActivity::class, SET_DEFAULT_VALUES + " no context")
return false
}
synchronized(resultOfSettingDefaults) {
resultOfSettingDefaults.set(TriState.UNKNOWN)
try {
if (context is Activity) {
context.runOnUiThread(Runnable { setDefaultValuesOnUiThread(context) })
} else {
startMeAsync(context, MyAction.SET_DEFAULT_VALUES)
}
for (i in 0..99) {
DbUtils.waitMs(FirstActivity::class, 50)
if (resultOfSettingDefaults.get().known) break
}
} catch (e: Exception) {
MyLog.e(FirstActivity::class, "$SET_DEFAULT_VALUES error:${e.message} \n${MyLog.getStackTrace(e)}")
}
}
return resultOfSettingDefaults.get().toBoolean(false)
}
private fun setDefaultValuesOnUiThread(activity: Activity) {
try {
MyLog.i(activity, SET_DEFAULT_VALUES + " started")
MySettingsGroup.setDefaultValues(activity)
resultOfSettingDefaults.set(TriState.TRUE)
MyLog.i(activity, SET_DEFAULT_VALUES + " completed")
return
} catch (e: Exception) {
MyLog.w(activity, "$SET_DEFAULT_VALUES error:${e.message} \n${MyLog.getStackTrace(e)}")
}
resultOfSettingDefaults.set(TriState.FALSE)
}
}
}
| apache-2.0 | e16bab92d227b5105ab271ad0711527c | 41.303371 | 160 | 0.596724 | 5.01777 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/codeInsight/inspection/GlobalNameCanbeLocal.kt | 2 | 2827 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.codeInsight.inspection
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.tang.intellij.lua.psi.*
import com.tang.intellij.lua.search.SearchContext
class GlobalNameCanbeLocal : LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object : LuaVisitor() {
override fun visitNameExpr(o: LuaNameExpr) {
val stat = o.assignStat
if (stat != null && o.moduleName == null) {
val name = o.name
val resolve = resolveInFile(name, o, SearchContext.get(o.project))
if (resolve == null) {
val scope = GlobalSearchScope.allScope(o.project)
val searchScope = scope.intersectWith(GlobalSearchScope.notScope(GlobalSearchScope.fileScope(o.containingFile)))
val query = ReferencesSearch.search(o, searchScope)
var canLocal = query.findFirst() == null
if (canLocal) {
canLocal = o.reference?.resolve() == null
}
if (canLocal) {
holder.registerProblem(o, "Global name \"$name\" can be local", object : LocalQuickFix {
override fun getFamilyName() = "Append \"local\""
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = LuaElementFactory.createWith(project, "local ${stat.text}")
stat.replace(element)
}
})
}
}
}
}
}
}
} | apache-2.0 | 45c08c005616d28659a7c06ca021a613 | 45.360656 | 136 | 0.60665 | 5.177656 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/market/MarketService.kt | 1 | 38805 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.market
import com.vk.api.sdk.requests.VKRequest
import com.vk.dto.common.id.UserId
import com.vk.sdk.api.GsonHolder
import com.vk.sdk.api.NewApiRequest
import com.vk.sdk.api.base.dto.BaseBoolInt
import com.vk.sdk.api.base.dto.BaseOkResponse
import com.vk.sdk.api.market.dto.MarketAddAlbumResponse
import com.vk.sdk.api.market.dto.MarketAddResponse
import com.vk.sdk.api.market.dto.MarketEditOrderPaymentStatus
import com.vk.sdk.api.market.dto.MarketGetAlbumByIdResponse
import com.vk.sdk.api.market.dto.MarketGetAlbumsResponse
import com.vk.sdk.api.market.dto.MarketGetByIdExtendedResponse
import com.vk.sdk.api.market.dto.MarketGetByIdResponse
import com.vk.sdk.api.market.dto.MarketGetCategoriesResponse
import com.vk.sdk.api.market.dto.MarketGetCommentsResponse
import com.vk.sdk.api.market.dto.MarketGetCommentsSort
import com.vk.sdk.api.market.dto.MarketGetExtendedResponse
import com.vk.sdk.api.market.dto.MarketGetGroupOrdersResponse
import com.vk.sdk.api.market.dto.MarketGetOrderByIdResponse
import com.vk.sdk.api.market.dto.MarketGetOrderItemsResponse
import com.vk.sdk.api.market.dto.MarketGetOrdersExtendedResponse
import com.vk.sdk.api.market.dto.MarketGetOrdersResponse
import com.vk.sdk.api.market.dto.MarketGetResponse
import com.vk.sdk.api.market.dto.MarketReportCommentReason
import com.vk.sdk.api.market.dto.MarketReportReason
import com.vk.sdk.api.market.dto.MarketSearchExtendedResponse
import com.vk.sdk.api.market.dto.MarketSearchExtendedRev
import com.vk.sdk.api.market.dto.MarketSearchExtendedSort
import com.vk.sdk.api.market.dto.MarketSearchItemsSortBy
import com.vk.sdk.api.market.dto.MarketSearchItemsSortDirection
import com.vk.sdk.api.market.dto.MarketSearchResponse
import com.vk.sdk.api.market.dto.MarketSearchRev
import com.vk.sdk.api.market.dto.MarketSearchSort
import com.vk.sdk.api.users.dto.UsersFields
import kotlin.Boolean
import kotlin.Float
import kotlin.Int
import kotlin.String
import kotlin.collections.List
class MarketService {
/**
* Ads a new item to the market.
*
* @param ownerId - ID of an item owner community.
* @param name - Item name.
* @param description - Item description.
* @param categoryId - Item category ID.
* @param price - Item price.
* @param oldPrice
* @param deleted - Item status ('1' - deleted, '0' - not deleted).
* @param mainPhotoId - Cover photo ID.
* @param photoIds - IDs of additional photos.
* @param url - Url for button in market item.
* @param dimensionWidth
* @param dimensionHeight
* @param dimensionLength
* @param weight
* @param sku
* @return [VKRequest] with [MarketAddResponse]
*/
fun marketAdd(
ownerId: UserId,
name: String,
description: String,
categoryId: Int,
price: Float? = null,
oldPrice: Float? = null,
deleted: Boolean? = null,
mainPhotoId: Int? = null,
photoIds: List<Int>? = null,
url: String? = null,
dimensionWidth: Int? = null,
dimensionHeight: Int? = null,
dimensionLength: Int? = null,
weight: Int? = null,
sku: String? = null
): VKRequest<MarketAddResponse> = NewApiRequest("market.add") {
GsonHolder.gson.fromJson(it, MarketAddResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("name", name, minLength = 4, maxLength = 100)
addParam("description", description, minLength = 10)
addParam("category_id", categoryId, min = 0)
price?.let { addParam("price", it, min = 0.0) }
oldPrice?.let { addParam("old_price", it, min = 0.01) }
deleted?.let { addParam("deleted", it) }
mainPhotoId?.let { addParam("main_photo_id", it, min = 0) }
photoIds?.let { addParam("photo_ids", it) }
url?.let { addParam("url", it, minLength = 0, maxLength = 320) }
dimensionWidth?.let { addParam("dimension_width", it, min = 0, max = 100000) }
dimensionHeight?.let { addParam("dimension_height", it, min = 0, max = 100000) }
dimensionLength?.let { addParam("dimension_length", it, min = 0, max = 100000) }
weight?.let { addParam("weight", it, min = 0, max = 100000000) }
sku?.let { addParam("sku", it, maxLength = 50) }
}
/**
* Creates new collection of items
*
* @param ownerId - ID of an item owner community.
* @param title - Collection title.
* @param photoId - Cover photo ID.
* @param mainAlbum - Set as main ('1' - set, '0' - no).
* @param isHidden - Set as hidden
* @return [VKRequest] with [MarketAddAlbumResponse]
*/
fun marketAddAlbum(
ownerId: UserId,
title: String,
photoId: Int? = null,
mainAlbum: Boolean? = null,
isHidden: Boolean? = null
): VKRequest<MarketAddAlbumResponse> = NewApiRequest("market.addAlbum") {
GsonHolder.gson.fromJson(it, MarketAddAlbumResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("title", title, maxLength = 128)
photoId?.let { addParam("photo_id", it, min = 0) }
mainAlbum?.let { addParam("main_album", it) }
isHidden?.let { addParam("is_hidden", it) }
}
/**
* Adds an item to one or multiple collections.
*
* @param ownerId - ID of an item owner community.
* @param itemIds
* @param albumIds - Collections IDs to add item to.
* @return [VKRequest] with [BaseOkResponse]
*/
fun marketAddToAlbum(
ownerId: UserId,
itemIds: List<Int>,
albumIds: List<Int>
): VKRequest<BaseOkResponse> = NewApiRequest("market.addToAlbum") {
GsonHolder.gson.fromJson(it, BaseOkResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("item_ids", itemIds)
addParam("album_ids", albumIds)
}
/**
* Creates a new comment for an item.
*
* @param ownerId - ID of an item owner community.
* @param itemId - Item ID.
* @param message - Comment text (required if 'attachments' parameter is not specified)
* @param attachments - Comma-separated list of objects attached to a comment. The field is
* submitted the following way_ , "'<owner_id>_<media_id>,<owner_id>_<media_id>'", , '' - media
* attachment type_ "'photo' - photo, 'video' - video, 'audio' - audio, 'doc' - document", ,
* '<owner_id>' - media owner id, '<media_id>' - media attachment id, , For example_
* "photo100172_166443618,photo66748_265827614",
* @param fromGroup - '1' - comment will be published on behalf of a community, '0' - on behalf
* of a user (by default).
* @param replyToComment - ID of a comment to reply with current comment to.
* @param stickerId - Sticker ID.
* @param guid - Random value to avoid resending one comment.
* @return [VKRequest] with [Int]
*/
fun marketCreateComment(
ownerId: UserId,
itemId: Int,
message: String? = null,
attachments: List<String>? = null,
fromGroup: Boolean? = null,
replyToComment: Int? = null,
stickerId: Int? = null,
guid: String? = null
): VKRequest<Int> = NewApiRequest("market.createComment") {
GsonHolder.gson.fromJson(it, Int::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("item_id", itemId, min = 0)
message?.let { addParam("message", it) }
attachments?.let { addParam("attachments", it) }
fromGroup?.let { addParam("from_group", it) }
replyToComment?.let { addParam("reply_to_comment", it, min = 0) }
stickerId?.let { addParam("sticker_id", it, min = 0) }
guid?.let { addParam("guid", it) }
}
/**
* Deletes an item.
*
* @param ownerId - ID of an item owner community.
* @param itemId - Item ID.
* @return [VKRequest] with [BaseOkResponse]
*/
fun marketDelete(ownerId: UserId, itemId: Int): VKRequest<BaseOkResponse> =
NewApiRequest("market.delete") {
GsonHolder.gson.fromJson(it, BaseOkResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("item_id", itemId, min = 0)
}
/**
* Deletes a collection of items.
*
* @param ownerId - ID of an collection owner community.
* @param albumId - Collection ID.
* @return [VKRequest] with [BaseOkResponse]
*/
fun marketDeleteAlbum(ownerId: UserId, albumId: Int): VKRequest<BaseOkResponse> =
NewApiRequest("market.deleteAlbum") {
GsonHolder.gson.fromJson(it, BaseOkResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("album_id", albumId, min = 0)
}
/**
* Deletes an item's comment
*
* @param ownerId - identifier of an item owner community, "Note that community id in the
* 'owner_id' parameter should be negative number. For example 'owner_id'=-1 matches the
* [vk.com/apiclub|VK API] community "
* @param commentId - comment id
* @return [VKRequest] with [BaseBoolInt]
*/
fun marketDeleteComment(ownerId: UserId, commentId: Int): VKRequest<BaseBoolInt> =
NewApiRequest("market.deleteComment") {
GsonHolder.gson.fromJson(it, BaseBoolInt::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("comment_id", commentId, min = 0)
}
/**
* Edits an item.
*
* @param ownerId - ID of an item owner community.
* @param itemId - Item ID.
* @param name - Item name.
* @param description - Item description.
* @param categoryId - Item category ID.
* @param price - Item price.
* @param deleted - Item status ('1' - deleted, '0' - not deleted).
* @param mainPhotoId - Cover photo ID.
* @param photoIds - IDs of additional photos.
* @param url - Url for button in market item.
* @return [VKRequest] with [BaseOkResponse]
*/
fun marketEdit(
ownerId: UserId,
itemId: Int,
name: String,
description: String,
categoryId: Int,
price: Float? = null,
deleted: Boolean? = null,
mainPhotoId: Int? = null,
photoIds: List<Int>? = null,
url: String? = null
): VKRequest<BaseOkResponse> = NewApiRequest("market.edit") {
GsonHolder.gson.fromJson(it, BaseOkResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("item_id", itemId, min = 0)
addParam("name", name, minLength = 4, maxLength = 100)
addParam("description", description, minLength = 10)
addParam("category_id", categoryId, min = 0)
price?.let { addParam("price", it, min = 0.0) }
deleted?.let { addParam("deleted", it) }
mainPhotoId?.let { addParam("main_photo_id", it, min = 0) }
photoIds?.let { addParam("photo_ids", it) }
url?.let { addParam("url", it, minLength = 0, maxLength = 320) }
}
/**
* Edits a collection of items
*
* @param ownerId - ID of an collection owner community.
* @param albumId - Collection ID.
* @param title - Collection title.
* @param photoId - Cover photo id
* @param mainAlbum - Set as main ('1' - set, '0' - no).
* @param isHidden - Set as hidden
* @return [VKRequest] with [BaseOkResponse]
*/
fun marketEditAlbum(
ownerId: UserId,
albumId: Int,
title: String,
photoId: Int? = null,
mainAlbum: Boolean? = null,
isHidden: Boolean? = null
): VKRequest<BaseOkResponse> = NewApiRequest("market.editAlbum") {
GsonHolder.gson.fromJson(it, BaseOkResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("album_id", albumId, min = 0)
addParam("title", title, maxLength = 128)
photoId?.let { addParam("photo_id", it, min = 0) }
mainAlbum?.let { addParam("main_album", it) }
isHidden?.let { addParam("is_hidden", it) }
}
/**
* Chages item comment's text
*
* @param ownerId - ID of an item owner community.
* @param commentId - Comment ID.
* @param message - New comment text (required if 'attachments' are not specified), , 2048
* symbols maximum.
* @param attachments - Comma-separated list of objects attached to a comment. The field is
* submitted the following way_ , "'<owner_id>_<media_id>,<owner_id>_<media_id>'", , '' - media
* attachment type_ "'photo' - photo, 'video' - video, 'audio' - audio, 'doc' - document", ,
* '<owner_id>' - media owner id, '<media_id>' - media attachment id, , For example_
* "photo100172_166443618,photo66748_265827614",
* @return [VKRequest] with [BaseOkResponse]
*/
fun marketEditComment(
ownerId: UserId,
commentId: Int,
message: String? = null,
attachments: List<String>? = null
): VKRequest<BaseOkResponse> = NewApiRequest("market.editComment") {
GsonHolder.gson.fromJson(it, BaseOkResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("comment_id", commentId, min = 0)
message?.let { addParam("message", it) }
attachments?.let { addParam("attachments", it) }
}
/**
* Edit order
*
* @param userId
* @param orderId
* @param merchantComment
* @param status
* @param trackNumber
* @param paymentStatus
* @param deliveryPrice
* @param width
* @param length
* @param height
* @param weight
* @return [VKRequest] with [BaseOkResponse]
*/
fun marketEditOrder(
userId: UserId,
orderId: Int,
merchantComment: String? = null,
status: Int? = null,
trackNumber: String? = null,
paymentStatus: MarketEditOrderPaymentStatus? = null,
deliveryPrice: Int? = null,
width: Int? = null,
length: Int? = null,
height: Int? = null,
weight: Int? = null
): VKRequest<BaseOkResponse> = NewApiRequest("market.editOrder") {
GsonHolder.gson.fromJson(it, BaseOkResponse::class.java)
}
.apply {
addParam("user_id", userId, min = 1)
addParam("order_id", orderId, min = 0)
merchantComment?.let { addParam("merchant_comment", it, maxLength = 800) }
status?.let { addParam("status", it, min = 0) }
trackNumber?.let { addParam("track_number", it, maxLength = 60) }
paymentStatus?.let { addParam("payment_status", it.value) }
deliveryPrice?.let { addParam("delivery_price", it, min = 0) }
width?.let { addParam("width", it, min = 0, max = 100000) }
length?.let { addParam("length", it, min = 0, max = 100000) }
height?.let { addParam("height", it, min = 0, max = 100000) }
weight?.let { addParam("weight", it, min = 0, max = 100000000) }
}
/**
* Returns items list for a community.
*
* @param ownerId - ID of an item owner community, "Note that community id in the 'owner_id'
* parameter should be negative number. For example 'owner_id'=-1 matches the [vk.com/apiclub|VK
* API] community "
* @param albumId
* @param count - Number of items to return.
* @param offset - Offset needed to return a specific subset of results.
* @param dateFrom - Items update date from (format_ yyyy-mm-dd)
* @param dateTo - Items update date to (format_ yyyy-mm-dd)
* @param needVariants - Add variants to response if exist
* @param withDisabled - Add disabled items to response
* @return [VKRequest] with [MarketGetResponse]
*/
fun marketGet(
ownerId: UserId,
albumId: Int? = null,
count: Int? = null,
offset: Int? = null,
dateFrom: String? = null,
dateTo: String? = null,
needVariants: Boolean? = null,
withDisabled: Boolean? = null
): VKRequest<MarketGetResponse> = NewApiRequest("market.get") {
GsonHolder.gson.fromJson(it, MarketGetResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
albumId?.let { addParam("album_id", it, min = 0) }
count?.let { addParam("count", it, min = 0, max = 200) }
offset?.let { addParam("offset", it, min = 0) }
dateFrom?.let { addParam("date_from", it) }
dateTo?.let { addParam("date_to", it) }
needVariants?.let { addParam("need_variants", it) }
withDisabled?.let { addParam("with_disabled", it) }
}
/**
* Returns items list for a community.
*
* @param ownerId - ID of an item owner community, "Note that community id in the 'owner_id'
* parameter should be negative number. For example 'owner_id'=-1 matches the [vk.com/apiclub|VK
* API] community "
* @param albumId
* @param count - Number of items to return.
* @param offset - Offset needed to return a specific subset of results.
* @param dateFrom - Items update date from (format_ yyyy-mm-dd)
* @param dateTo - Items update date to (format_ yyyy-mm-dd)
* @param needVariants - Add variants to response if exist
* @param withDisabled - Add disabled items to response
* @return [VKRequest] with [MarketGetExtendedResponse]
*/
fun marketGetExtended(
ownerId: UserId,
albumId: Int? = null,
count: Int? = null,
offset: Int? = null,
dateFrom: String? = null,
dateTo: String? = null,
needVariants: Boolean? = null,
withDisabled: Boolean? = null
): VKRequest<MarketGetExtendedResponse> = NewApiRequest("market.get") {
GsonHolder.gson.fromJson(it, MarketGetExtendedResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
albumId?.let { addParam("album_id", it, min = 0) }
count?.let { addParam("count", it, min = 0, max = 200) }
offset?.let { addParam("offset", it, min = 0) }
addParam("extended", true)
dateFrom?.let { addParam("date_from", it) }
dateTo?.let { addParam("date_to", it) }
needVariants?.let { addParam("need_variants", it) }
withDisabled?.let { addParam("with_disabled", it) }
}
/**
* Returns items album's data
*
* @param ownerId - identifier of an album owner community, "Note that community id in the
* 'owner_id' parameter should be negative number. For example 'owner_id'=-1 matches the
* [vk.com/apiclub|VK API] community "
* @param albumIds - collections identifiers to obtain data from
* @return [VKRequest] with [MarketGetAlbumByIdResponse]
*/
fun marketGetAlbumById(ownerId: UserId, albumIds: List<Int>):
VKRequest<MarketGetAlbumByIdResponse> = NewApiRequest("market.getAlbumById") {
GsonHolder.gson.fromJson(it, MarketGetAlbumByIdResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("album_ids", albumIds)
}
/**
* Returns community's market collections list.
*
* @param ownerId - ID of an items owner community.
* @param offset - Offset needed to return a specific subset of results.
* @param count - Number of items to return.
* @return [VKRequest] with [MarketGetAlbumsResponse]
*/
fun marketGetAlbums(
ownerId: UserId,
offset: Int? = null,
count: Int? = null
): VKRequest<MarketGetAlbumsResponse> = NewApiRequest("market.getAlbums") {
GsonHolder.gson.fromJson(it, MarketGetAlbumsResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
offset?.let { addParam("offset", it, min = 0) }
count?.let { addParam("count", it, min = 0, max = 100) }
}
/**
* Returns information about market items by their ids.
*
* @param itemIds - Comma-separated ids list_ {user id}_{item id}. If an item belongs to a
* community -{community id} is used. " 'Videos' value example_ ,
* '-4363_136089719,13245770_137352259'"
* @return [VKRequest] with [MarketGetByIdResponse]
*/
fun marketGetById(itemIds: List<String>): VKRequest<MarketGetByIdResponse> =
NewApiRequest("market.getById") {
GsonHolder.gson.fromJson(it, MarketGetByIdResponse::class.java)
}
.apply {
addParam("item_ids", itemIds)
}
/**
* Returns information about market items by their ids.
*
* @param itemIds - Comma-separated ids list_ {user id}_{item id}. If an item belongs to a
* community -{community id} is used. " 'Videos' value example_ ,
* '-4363_136089719,13245770_137352259'"
* @return [VKRequest] with [MarketGetByIdExtendedResponse]
*/
fun marketGetByIdExtended(itemIds: List<String>): VKRequest<MarketGetByIdExtendedResponse> =
NewApiRequest("market.getById") {
GsonHolder.gson.fromJson(it, MarketGetByIdExtendedResponse::class.java)
}
.apply {
addParam("item_ids", itemIds)
addParam("extended", true)
}
/**
* Returns a list of market categories.
*
* @param count - Number of results to return.
* @param offset - Offset needed to return a specific subset of results.
* @return [VKRequest] with [MarketGetCategoriesResponse]
*/
fun marketGetCategories(count: Int? = null, offset: Int? = null):
VKRequest<MarketGetCategoriesResponse> = NewApiRequest("market.getCategories") {
GsonHolder.gson.fromJson(it, MarketGetCategoriesResponse::class.java)
}
.apply {
count?.let { addParam("count", it, min = 0, max = 1000) }
offset?.let { addParam("offset", it, min = 0) }
}
/**
* Returns comments list for an item.
*
* @param ownerId - ID of an item owner community
* @param itemId - Item ID.
* @param needLikes - '1' - to return likes info.
* @param startCommentId - ID of a comment to start a list from (details below).
* @param offset
* @param count - Number of results to return.
* @param sort - Sort order ('asc' - from old to new, 'desc' - from new to old)
* @param fields - List of additional profile fields to return. See the
* [vk.com/dev/fields|details]
* @return [VKRequest] with [MarketGetCommentsResponse]
*/
fun marketGetComments(
ownerId: UserId,
itemId: Int,
needLikes: Boolean? = null,
startCommentId: Int? = null,
offset: Int? = null,
count: Int? = null,
sort: MarketGetCommentsSort? = null,
fields: List<UsersFields>? = null
): VKRequest<MarketGetCommentsResponse> = NewApiRequest("market.getComments") {
GsonHolder.gson.fromJson(it, MarketGetCommentsResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("item_id", itemId, min = 0)
needLikes?.let { addParam("need_likes", it) }
startCommentId?.let { addParam("start_comment_id", it, min = 0) }
offset?.let { addParam("offset", it, min = 0) }
count?.let { addParam("count", it, min = 0, max = 100) }
sort?.let { addParam("sort", it.value) }
val fieldsJsonConverted = fields?.map {
it.value
}
fieldsJsonConverted?.let { addParam("fields", it) }
}
/**
* Get market orders
*
* @param groupId
* @param offset
* @param count
* @return [VKRequest] with [MarketGetGroupOrdersResponse]
*/
fun marketGetGroupOrders(
groupId: UserId,
offset: Int? = null,
count: Int? = null
): VKRequest<MarketGetGroupOrdersResponse> = NewApiRequest("market.getGroupOrders") {
GsonHolder.gson.fromJson(it, MarketGetGroupOrdersResponse::class.java)
}
.apply {
addParam("group_id", groupId, min = 1)
offset?.let { addParam("offset", it, min = 0) }
count?.let { addParam("count", it, min = 1, max = 50) }
}
/**
* Get order
*
* @param orderId
* @param userId
* @return [VKRequest] with [MarketGetOrderByIdResponse]
*/
fun marketGetOrderById(orderId: Int, userId: UserId? = null):
VKRequest<MarketGetOrderByIdResponse> = NewApiRequest("market.getOrderById") {
GsonHolder.gson.fromJson(it, MarketGetOrderByIdResponse::class.java)
}
.apply {
addParam("order_id", orderId, min = 0)
userId?.let { addParam("user_id", it, min = 0) }
}
/**
* Get market items in the order
*
* @param orderId
* @param userId
* @param offset
* @param count
* @return [VKRequest] with [MarketGetOrderItemsResponse]
*/
fun marketGetOrderItems(
orderId: Int,
userId: UserId? = null,
offset: Int? = null,
count: Int? = null
): VKRequest<MarketGetOrderItemsResponse> = NewApiRequest("market.getOrderItems") {
GsonHolder.gson.fromJson(it, MarketGetOrderItemsResponse::class.java)
}
.apply {
addParam("order_id", orderId, min = 0)
userId?.let { addParam("user_id", it, min = 0) }
offset?.let { addParam("offset", it, min = 0) }
count?.let { addParam("count", it, min = 0) }
}
/**
* @param offset
* @param count
* @param dateFrom - Orders status updated date from (format_ yyyy-mm-dd)
* @param dateTo - Orders status updated date to (format_ yyyy-mm-dd)
* @return [VKRequest] with [MarketGetOrdersResponse]
*/
fun marketGetOrders(
offset: Int? = null,
count: Int? = null,
dateFrom: String? = null,
dateTo: String? = null
): VKRequest<MarketGetOrdersResponse> = NewApiRequest("market.getOrders") {
GsonHolder.gson.fromJson(it, MarketGetOrdersResponse::class.java)
}
.apply {
offset?.let { addParam("offset", it, min = 0) }
count?.let { addParam("count", it, min = 0, max = 10) }
dateFrom?.let { addParam("date_from", it) }
dateTo?.let { addParam("date_to", it) }
}
/**
* @param offset
* @param count
* @param dateFrom - Orders status updated date from (format_ yyyy-mm-dd)
* @param dateTo - Orders status updated date to (format_ yyyy-mm-dd)
* @return [VKRequest] with [MarketGetOrdersExtendedResponse]
*/
fun marketGetOrdersExtended(
offset: Int? = null,
count: Int? = null,
dateFrom: String? = null,
dateTo: String? = null
): VKRequest<MarketGetOrdersExtendedResponse> = NewApiRequest("market.getOrders") {
GsonHolder.gson.fromJson(it, MarketGetOrdersExtendedResponse::class.java)
}
.apply {
offset?.let { addParam("offset", it, min = 0) }
count?.let { addParam("count", it, min = 0, max = 10) }
addParam("extended", true)
dateFrom?.let { addParam("date_from", it) }
dateTo?.let { addParam("date_to", it) }
}
/**
* Removes an item from one or multiple collections.
*
* @param ownerId - ID of an item owner community.
* @param itemId - Item ID.
* @param albumIds - Collections IDs to remove item from.
* @return [VKRequest] with [BaseOkResponse]
*/
fun marketRemoveFromAlbum(
ownerId: UserId,
itemId: Int,
albumIds: List<Int>
): VKRequest<BaseOkResponse> = NewApiRequest("market.removeFromAlbum") {
GsonHolder.gson.fromJson(it, BaseOkResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("item_id", itemId, min = 0)
addParam("album_ids", albumIds)
}
/**
* Reorders the collections list.
*
* @param ownerId - ID of an item owner community.
* @param albumId - Collection ID.
* @param before - ID of a collection to place current collection before it.
* @param after - ID of a collection to place current collection after it.
* @return [VKRequest] with [BaseOkResponse]
*/
fun marketReorderAlbums(
ownerId: UserId,
albumId: Int,
before: Int? = null,
after: Int? = null
): VKRequest<BaseOkResponse> = NewApiRequest("market.reorderAlbums") {
GsonHolder.gson.fromJson(it, BaseOkResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("album_id", albumId)
before?.let { addParam("before", it, min = 0) }
after?.let { addParam("after", it, min = 0) }
}
/**
* Changes item place in a collection.
*
* @param ownerId - ID of an item owner community.
* @param itemId - Item ID.
* @param albumId - ID of a collection to reorder items in. Set 0 to reorder full items list.
* @param before - ID of an item to place current item before it.
* @param after - ID of an item to place current item after it.
* @return [VKRequest] with [BaseOkResponse]
*/
fun marketReorderItems(
ownerId: UserId,
itemId: Int,
albumId: Int? = null,
before: Int? = null,
after: Int? = null
): VKRequest<BaseOkResponse> = NewApiRequest("market.reorderItems") {
GsonHolder.gson.fromJson(it, BaseOkResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("item_id", itemId, min = 0)
albumId?.let { addParam("album_id", it) }
before?.let { addParam("before", it, min = 0) }
after?.let { addParam("after", it, min = 0) }
}
/**
* Sends a complaint to the item.
*
* @param ownerId - ID of an item owner community.
* @param itemId - Item ID.
* @param reason - Complaint reason. Possible values_ *'0' - spam,, *'1' - child porn,, *'2' -
* extremism,, *'3' - violence,, *'4' - drugs propaganda,, *'5' - adult materials,, *'6' - insult.
* @return [VKRequest] with [BaseOkResponse]
*/
fun marketReport(
ownerId: UserId,
itemId: Int,
reason: MarketReportReason? = null
): VKRequest<BaseOkResponse> = NewApiRequest("market.report") {
GsonHolder.gson.fromJson(it, BaseOkResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("item_id", itemId, min = 0)
reason?.let { addParam("reason", it.value) }
}
/**
* Sends a complaint to the item's comment.
*
* @param ownerId - ID of an item owner community.
* @param commentId - Comment ID.
* @param reason - Complaint reason. Possible values_ *'0' - spam,, *'1' - child porn,, *'2' -
* extremism,, *'3' - violence,, *'4' - drugs propaganda,, *'5' - adult materials,, *'6' - insult.
* @return [VKRequest] with [BaseOkResponse]
*/
fun marketReportComment(
ownerId: UserId,
commentId: Int,
reason: MarketReportCommentReason
): VKRequest<BaseOkResponse> = NewApiRequest("market.reportComment") {
GsonHolder.gson.fromJson(it, BaseOkResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("comment_id", commentId, min = 0)
addParam("reason", reason.value)
}
/**
* Restores recently deleted item
*
* @param ownerId - ID of an item owner community.
* @param itemId - Deleted item ID.
* @return [VKRequest] with [BaseOkResponse]
*/
fun marketRestore(ownerId: UserId, itemId: Int): VKRequest<BaseOkResponse> =
NewApiRequest("market.restore") {
GsonHolder.gson.fromJson(it, BaseOkResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("item_id", itemId, min = 0)
}
/**
* Restores a recently deleted comment
*
* @param ownerId - identifier of an item owner community, "Note that community id in the
* 'owner_id' parameter should be negative number. For example 'owner_id'=-1 matches the
* [vk.com/apiclub|VK API] community "
* @param commentId - deleted comment id
* @return [VKRequest] with [BaseBoolInt]
*/
fun marketRestoreComment(ownerId: UserId, commentId: Int): VKRequest<BaseBoolInt> =
NewApiRequest("market.restoreComment") {
GsonHolder.gson.fromJson(it, BaseBoolInt::class.java)
}
.apply {
addParam("owner_id", ownerId)
addParam("comment_id", commentId, min = 0)
}
/**
* Searches market items in a community's catalog
*
* @param ownerId - ID of an items owner community.
* @param albumId
* @param q - Search query, for example "pink slippers".
* @param priceFrom - Minimum item price value.
* @param priceTo - Maximum item price value.
* @param sort
* @param rev - '0' - do not use reverse order, '1' - use reverse order
* @param offset - Offset needed to return a specific subset of results.
* @param count - Number of items to return.
* @param status
* @param needVariants - Add variants to response if exist
* @return [VKRequest] with [MarketSearchResponse]
*/
fun marketSearch(
ownerId: UserId,
albumId: Int? = null,
q: String? = null,
priceFrom: Int? = null,
priceTo: Int? = null,
sort: MarketSearchSort? = null,
rev: MarketSearchRev? = null,
offset: Int? = null,
count: Int? = null,
status: List<Int>? = null,
needVariants: Boolean? = null
): VKRequest<MarketSearchResponse> = NewApiRequest("market.search") {
GsonHolder.gson.fromJson(it, MarketSearchResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
albumId?.let { addParam("album_id", it, min = 0) }
q?.let { addParam("q", it) }
priceFrom?.let { addParam("price_from", it, min = 0) }
priceTo?.let { addParam("price_to", it, min = 0) }
sort?.let { addParam("sort", it.value) }
rev?.let { addParam("rev", it.value) }
offset?.let { addParam("offset", it, min = 0) }
count?.let { addParam("count", it, min = 0, max = 200) }
status?.let { addParam("status", it) }
needVariants?.let { addParam("need_variants", it) }
}
/**
* Searches market items in a community's catalog
*
* @param ownerId - ID of an items owner community.
* @param albumId
* @param q - Search query, for example "pink slippers".
* @param priceFrom - Minimum item price value.
* @param priceTo - Maximum item price value.
* @param sort
* @param rev - '0' - do not use reverse order, '1' - use reverse order
* @param offset - Offset needed to return a specific subset of results.
* @param count - Number of items to return.
* @param status
* @param needVariants - Add variants to response if exist
* @return [VKRequest] with [MarketSearchExtendedResponse]
*/
fun marketSearchExtended(
ownerId: UserId,
albumId: Int? = null,
q: String? = null,
priceFrom: Int? = null,
priceTo: Int? = null,
sort: MarketSearchExtendedSort? = null,
rev: MarketSearchExtendedRev? = null,
offset: Int? = null,
count: Int? = null,
status: List<Int>? = null,
needVariants: Boolean? = null
): VKRequest<MarketSearchExtendedResponse> = NewApiRequest("market.search") {
GsonHolder.gson.fromJson(it, MarketSearchExtendedResponse::class.java)
}
.apply {
addParam("owner_id", ownerId)
albumId?.let { addParam("album_id", it, min = 0) }
q?.let { addParam("q", it) }
priceFrom?.let { addParam("price_from", it, min = 0) }
priceTo?.let { addParam("price_to", it, min = 0) }
sort?.let { addParam("sort", it.value) }
rev?.let { addParam("rev", it.value) }
offset?.let { addParam("offset", it, min = 0) }
count?.let { addParam("count", it, min = 0, max = 200) }
addParam("extended", true)
status?.let { addParam("status", it) }
needVariants?.let { addParam("need_variants", it) }
}
/**
* @param q
* @param offset
* @param count
* @param categoryId
* @param priceFrom
* @param priceTo
* @param sortBy
* @param sortDirection
* @param country
* @param city
* @return [VKRequest] with [MarketSearchResponse]
*/
fun marketSearchItems(
q: String,
offset: Int? = null,
count: Int? = null,
categoryId: Int? = null,
priceFrom: Int? = null,
priceTo: Int? = null,
sortBy: MarketSearchItemsSortBy? = null,
sortDirection: MarketSearchItemsSortDirection? = null,
country: Int? = null,
city: Int? = null
): VKRequest<MarketSearchResponse> = NewApiRequest("market.searchItems") {
GsonHolder.gson.fromJson(it, MarketSearchResponse::class.java)
}
.apply {
addParam("q", q)
offset?.let { addParam("offset", it) }
count?.let { addParam("count", it, min = 0, max = 300) }
categoryId?.let { addParam("category_id", it, min = 0) }
priceFrom?.let { addParam("price_from", it, min = 0) }
priceTo?.let { addParam("price_to", it, min = 0) }
sortBy?.let { addParam("sort_by", it.value) }
sortDirection?.let { addParam("sort_direction", it.value) }
country?.let { addParam("country", it, min = 0) }
city?.let { addParam("city", it, min = 0) }
}
}
| mit | c4d5ece1fdc4a890c67132b1cfff0d83 | 37.650398 | 102 | 0.613168 | 3.856972 | false | false | false | false |
inorichi/tachiyomi-extensions | src/es/tmohentai/src/eu/kanade/tachiyomi/extension/es/tmohentai/TMOHentaiUrlActivity.kt | 1 | 1251 | package eu.kanade.tachiyomi.extension.es.tmohentai
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.util.Log
import kotlin.system.exitProcess
/**
* Springboard that accepts https://tmohentai.com/contents/:id intents and redirects them to
* the main Tachiyomi process.
*/
class TMOHentaiUrlActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val pathSegments = intent?.data?.pathSegments
if (pathSegments != null && pathSegments.size > 1) {
val id = pathSegments[1]
val mainIntent = Intent().apply {
action = "eu.kanade.tachiyomi.SEARCH"
putExtra("query", "${TMOHentai.PREFIX_ID_SEARCH}$id")
putExtra("filter", packageName)
}
try {
startActivity(mainIntent)
} catch (e: ActivityNotFoundException) {
Log.e("TMOHentaiUrlActivity", e.toString())
}
} else {
Log.e("TMOHentaiUrlActivity", "could not parse uri from intent $intent")
}
finish()
exitProcess(0)
}
}
| apache-2.0 | f8325f3f97e83722ac1d6f9941c9455c | 30.275 | 92 | 0.629097 | 4.703008 | false | false | false | false |
googleads/googleads-mobile-android-examples | kotlin/admob/AppOpenExample/app/src/main/java/com/google/android/gms/example/appopenexample/SplashActivity.kt | 2 | 2382 | package com.google.android.gms.example.appopenexample
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
/**
* Number of seconds to count down before showing the app open ad. This simulates the time needed
* to load the app.
*/
private const val COUNTER_TIME = 5L
private const val LOG_TAG = "SplashActivity"
/** Splash Activity that inflates splash activity xml. */
class SplashActivity : AppCompatActivity() {
private var secondsRemaining: Long = 0L
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
// Create a timer so the SplashActivity will be displayed for a fixed amount of time.
createTimer(COUNTER_TIME)
}
/**
* Create the countdown timer, which counts down to zero and show the app open ad.
*
* @param seconds the number of seconds that the timer counts down from
*/
private fun createTimer(seconds: Long) {
val counterTextView: TextView = findViewById(R.id.timer)
val countDownTimer: CountDownTimer = object : CountDownTimer(seconds * 1000, 1000) {
override fun onTick(millisUntilFinished: Long) {
secondsRemaining = millisUntilFinished / 1000 + 1
counterTextView.text = "App is done loading in: $secondsRemaining"
}
override fun onFinish() {
secondsRemaining = 0
counterTextView.text = "Done."
val application = application as? MyApplication
// If the application is not an instance of MyApplication, log an error message and
// start the MainActivity without showing the app open ad.
if (application == null) {
Log.e(LOG_TAG, "Failed to cast application to MyApplication.")
startMainActivity()
return
}
// Show the app open ad.
application.showAdIfAvailable(
this@SplashActivity,
object : MyApplication.OnShowAdCompleteListener {
override fun onShowAdComplete() {
startMainActivity()
}
})
}
}
countDownTimer.start()
}
/** Start the MainActivity. */
fun startMainActivity() {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
}
| apache-2.0 | 22301316876f94c71df7c8501a49d1a1 | 30.342105 | 97 | 0.686818 | 4.735586 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/other/generic/adapter/EqualSpacingItemDecoration.kt | 1 | 658 | package de.tum.`in`.tumcampusapp.component.other.generic.adapter
import android.graphics.Rect
import androidx.recyclerview.widget.RecyclerView
import android.view.View
class EqualSpacingItemDecoration(private val spacing: Int) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val position = parent.getChildViewHolder(view).adapterPosition
val itemCount = state.itemCount
outRect.left = spacing
outRect.right = spacing
outRect.top = spacing
outRect.bottom = if (position == itemCount - 1) spacing else 0
}
}
| gpl-3.0 | 1e0e1975556d07e789d308a143cc71d4 | 35.555556 | 109 | 0.735562 | 4.733813 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.