repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mdanielwork/intellij-community | plugins/editorconfig/src/org/editorconfig/language/codeinsight/linemarker/EditorConfigOverriddenKeyLineMarkerProvider.kt | 4 | 2589 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.editorconfig.language.codeinsight.linemarker
import com.intellij.codeHighlighting.Pass
import com.intellij.codeInsight.daemon.LineMarkerInfo
import com.intellij.codeInsight.daemon.LineMarkerProvider
import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator
import com.intellij.icons.AllIcons
import com.intellij.ide.util.DefaultPsiElementCellRenderer
import com.intellij.openapi.editor.markup.GutterIconRenderer
import com.intellij.psi.PsiElement
import org.editorconfig.language.messages.EditorConfigBundle
import org.editorconfig.language.psi.EditorConfigFlatOptionKey
import java.awt.event.MouseEvent
class EditorConfigOverriddenKeyLineMarkerProvider : LineMarkerProvider {
override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? = null
override fun collectSlowLineMarkers(elements: List<PsiElement>, result: MutableCollection<LineMarkerInfo<PsiElement>>) {
for (element in elements) {
if (element !is EditorConfigFlatOptionKey) continue
val identifier = element.firstChild ?: continue
if (identifier.firstChild != null) continue
val reference = element.reference
val children = reference
.findChildren()
.toTypedArray()
if (children.isEmpty()) continue
val marker = LineMarkerInfo(
identifier,
identifier.textRange,
AllIcons.Gutter.OverridenMethod,
Pass.LINE_MARKERS,
createTooltipProvider(children),
createNavigationHandler(children, element),
GutterIconRenderer.Alignment.RIGHT
)
result.add(marker)
}
}
private fun createNavigationHandler(children: Array<EditorConfigFlatOptionKey>, optionKey: EditorConfigFlatOptionKey) =
{ event: MouseEvent, _: PsiElement ->
val title = EditorConfigBundle["message.overridden.title"]
val findUsagesTitle = EditorConfigBundle.get("message.overridden.find-usages-title", optionKey.text, optionKey.declarationSite)
val renderer = DefaultPsiElementCellRenderer()
PsiElementListNavigator.openTargets(event, children, title, findUsagesTitle, renderer)
}
private fun createTooltipProvider(children: Array<EditorConfigFlatOptionKey>): (PsiElement) -> String = {
if (children.size == 1) {
val site = children.single().declarationSite
EditorConfigBundle.get("message.overridden.element", site)
}
else {
EditorConfigBundle["message.overridden.multiple"]
}
}
}
| apache-2.0 | d198e332de648eba3baa2796f2700fc6 | 41.442623 | 140 | 0.761298 | 5.076471 | false | true | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/dalatlaptop/ux/adapters/RelatedProductsRecyclerAdapter.kt | 1 | 3558 | package com.tungnui.dalatlaptop.ux.adapters
import android.graphics.Paint
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.tungnui.dalatlaptop.models.Product
import java.util.ArrayList
import com.tungnui.dalatlaptop.R
import com.tungnui.dalatlaptop.views.ResizableImageViewHeight
import com.tungnui.dalatlaptop.utils.getFeaturedImage
import com.tungnui.dalatlaptop.utils.inflate
import com.tungnui.dalatlaptop.utils.loadImg
import kotlinx.android.synthetic.main.list_item_recommended_products.view.*
class RelatedProductsRecyclerAdapter(val listener: (Product)->Unit) : RecyclerView.Adapter<RelatedProductsRecyclerAdapter.ViewHolder>() {
private val relatedProducts: MutableList<Product>
init {
relatedProducts = ArrayList()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RelatedProductsRecyclerAdapter.ViewHolder {
return ViewHolder(parent.inflate(R.layout.list_item_recommended_products))
}
override fun onBindViewHolder(holder: RelatedProductsRecyclerAdapter.ViewHolder, position: Int) {
holder.blind(relatedProducts[position],listener)
}
private fun getItem(position: Int): Product? {
return relatedProducts[position]
}
override fun getItemCount(): Int {
return relatedProducts.size
}
fun add(position: Int, product: Product) {
relatedProducts.add(position, product)
notifyItemInserted(position)
}
fun addProducts(items:List<Product>){
relatedProducts.addAll(items)
notifyDataSetChanged()
}
fun addLast(product: Product) {
relatedProducts.add(relatedProducts.size, product)
notifyItemInserted(relatedProducts.size)
}
class ViewHolder(v: View) : RecyclerView.ViewHolder(v) {
internal var position: Int = 0
fun blind(item:Product,listener: (Product) -> Unit)=with(itemView){
(list_item_recommended_products_image as ResizableImageViewHeight).loadImg(item.images?.getFeaturedImage()?.src)
list_item_recommended_products_name.text = item.name
val pr = item.price
val dis = item.salePrice
if (pr == dis) {
list_item_recommended_products_price.visibility = View.VISIBLE
list_item_recommended_products_discount.visibility = View.GONE
list_item_recommended_products_price.setText(item.priceHtml)
//list_item_recommended_products_price.paintFlags = item
list_item_recommended_products_price.setTextColor(ContextCompat.getColor(context, R.color.textPrimary))
} else {
list_item_recommended_products_price.visibility = View.VISIBLE
list_item_recommended_products_discount.visibility = View.VISIBLE
list_item_recommended_products_price.setText(item.priceHtml)
list_item_recommended_products_price.paintFlags = Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG
list_item_recommended_products_price.setTextColor(ContextCompat.getColor(context, R.color.textSecondary))
list_item_recommended_products_discount.setText(item.salePrice)
}
setOnClickListener { listener(item) }
}
fun setPosition(position: Int) {
this.position = position
}
}
}
| mit | 3dd0948559166e4b1c1d5b240a52bafe | 40.372093 | 137 | 0.686903 | 4.756684 | false | false | false | false |
openium/auvergne-webcams-droid | app/src/main/java/fr/openium/auvergnewebcams/utils/DateUtils.kt | 1 | 1148 | package fr.openium.auvergnewebcams.utils
import android.content.Context
import fr.openium.auvergnewebcams.R
import timber.log.Timber
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by Openium on 19/02/2019.
*/
class DateUtils(context: Context) {
companion object {
const val DELAY_VALUE_BEFORE_OUTDATED = 2 * 24 * 60 * 60 * 1000L
}
private var dateFullFormat: SimpleDateFormat =
SimpleDateFormat(context.getString(R.string.date_full_format), Locale.getDefault())
private var dateFormatGMT: SimpleDateFormat =
SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US).apply { timeZone = TimeZone.getTimeZone("GMT") }
fun getDateInFullFormat(date: Long): String = dateFullFormat.format(Date(date))
fun isUpToDate(lastUpdateTime: Long?): Boolean {
val time = lastUpdateTime ?: 0L
return if (time == 0L) true else System.currentTimeMillis() - time <= DELAY_VALUE_BEFORE_OUTDATED
}
fun parseDateGMT(date: String): Long? = try {
dateFormatGMT.parse(date)?.time
} catch (e: Exception) {
Timber.e(e, "date $date")
null
}
} | mit | 6aa1d7a46a948560984d139b484f3bbf | 30.916667 | 116 | 0.686411 | 3.986111 | false | false | false | false |
mctoyama/PixelServer | src/main/kotlin/org/pixelndice/table/pixelserver/connection/main/Context.kt | 1 | 2241 | package org.pixelndice.table.pixelserver.connection.main
import com.google.common.eventbus.Subscribe
import org.apache.logging.log4j.LogManager
import java.net.InetAddress
import java.time.Instant
import org.pixelndice.table.pixelprotocol.*
import org.pixelndice.table.pixelserver.Bus
import org.pixelndice.table.pixelserver.connection.main.state04hostgame.State07LobbyUnreachable
import org.pixelndice.table.pixelserver.connection.main.state04hostgame.State08LobbyReachable
import org.pixelndice.table.pixelserverhibernate.Account
import org.pixelndice.table.pixelserverhibernate.Game
private val logger = LogManager.getLogger(Context::class.java)
class Context(address: InetAddress) {
val h = BusHandler()
var state: State = State00Start()
var channel: Channel = Channel(address)
var account: Account = Account()
var game: Game? = null
init {
Bus.register(h)
}
fun process() {
try {
// sending keep alive before state processing
if (Instant.now().isAfter(channel.instant.plusSeconds(keepaliveSeconds))) {
logger.trace("Sending keep-alive")
val resp = Protobuf.Packet.newBuilder()
val tkKeepAlive = Protobuf.Keepalive.newBuilder()
resp.setKeepalive(tkKeepAlive)
channel.packet = resp.build()
}
// state processing
state.process(this)
} catch (e: ChannelCanceledException) {
logger.trace("Channel in invalid state. Waiting to be disposed.")
}
}
inner class BusHandler{
@Subscribe
fun handleLobbyReachable(ev: Bus.LobbyReachable){
if( [email protected](ev.game.gm)){
[email protected] = ev.game
[email protected] = State08LobbyReachable()
}
}
@Subscribe
fun handleLobbyUnreachable(ev: Bus.LobbyUnreachable){
if( [email protected](ev.ping.gm)){
[email protected] = State07LobbyUnreachable()
}
}
}
companion object Connection {
// keep alive interval in seconds
var keepaliveSeconds: Long = 60L
}
}
| bsd-2-clause | aa72b5eac8094c8d27c933de5b93ad7f | 25.678571 | 95 | 0.651495 | 4.554878 | false | false | false | false |
zanata/zanata-platform | server/services/src/test/java/org/zanata/arquillian/ArquillianUtil.kt | 1 | 4197 | package org.zanata.arquillian
import org.jboss.shrinkwrap.api.asset.ClassAsset
import org.jboss.shrinkwrap.api.asset.StringAsset
import org.jboss.shrinkwrap.api.container.ClassContainer
import org.jboss.shrinkwrap.api.container.ResourceContainer
import org.jboss.shrinkwrap.api.spec.WebArchive
import org.jboss.shrinkwrap.descriptor.api.Descriptor
import org.jboss.shrinkwrap.impl.base.path.BasicPath
import org.slf4j.LoggerFactory
/**
* This object contains extension methods for Arquillian ClassContainer
* (including WebArchive).
* @author Sean Flanigan <a href="mailto:[email protected]">[email protected]</a>
*/
object ArquillianUtil {
private val log = LoggerFactory.getLogger(ArquillianUtil::class.java)
private val TOP_PACKAGE = "org.zanata"
private fun inAZanataPackage(className: String): Boolean = className.startsWith(TOP_PACKAGE)
val IN_ZANATA: ClassNameFilter = ArquillianUtil::inAZanataPackage
private fun notInPlatform(className: String): Boolean {
// TODO listing the packages which will be provided by the platform is a losing battle
val blacklist = arrayOf("org.jboss", "org.hibernate", "java", "com.sun", "sun", "org.w3c", "org.xml", "org.codehaus.jackson", "org.apache.log4j", "org.wildfly", "org.picket", "org.infinispan")
// return !(className.startsWith("org.jboss") || className.startsWith("org.hibernate") || className.startsWith("java") || className.startsWith("com.sun") || className.startsWith("sun") || className.startsWith("org.w3c") || className.startsWith("org.xml") || className.startsWith("org.codehaus.jackson") || className.startsWith("org.apache.log4j") || className.startsWith("org.wildfly") || className.startsWith("org.picket") || className.startsWith("org.infinispan"))
blacklist.forEach {
if (className.startsWith(it)) return false
}
return true
}
val NOT_IN_PLATFORM: ClassNameFilter = ArquillianUtil::notInPlatform
@JvmOverloads
@JvmStatic
fun <T: ClassContainer<T>> T.addClassesWithSupertypes(vararg classes: Class<*>, filter: ClassNameFilter = IN_ZANATA): T {
classes
.filter { filter(it.name) }
.forEach { clazz ->
addClass(clazz)
clazz.superclass?.let { addClassesWithSupertypes(it, filter = filter) }
clazz.interfaces.forEach { addClassesWithSupertypes(it, filter = filter) }
}
return this
}
/**
* ClassContainer extension method which can add a list of classes and
* the transitive set of classes they reference (based on analysis of
* byte code). This includes supertypes, annotations, fields, method
* signature types and method bodies.
*/
@JvmOverloads
@JvmStatic
fun <T: ClassContainer<T>> T.addClassesWithDependencies(classes: List<Class<*>>, filter: ClassNameFilter = IN_ZANATA): T {
val allClasses = findAllClassDependencyChains(classes, filter = filter) //.toTypedArray()
log.info("Adding classes with dependencies: {} ({} total)", classes, allClasses.size)
// uncomment if you want to see the classes and how they were referenced
// allClasses.values.forEach{
// println(it.reverse().map { it.simpleName }.joinToString("/"))
// }
allClasses.keys.forEach { clazz ->
val asset = ClassAsset(clazz)
val filename = clazz.name.replace('.','/')
addAsResource(asset, BasicPath("$filename.class"))
}
return this
}
@JvmStatic
fun <T: ResourceContainer<T>> T.addPersistenceConfig(): T {
addAsResource("arquillian/persistence.xml", "META-INF/persistence.xml")
addAsResource("META-INF/orm.xml")
addAsResource("import.sql")
return this
}
@JvmStatic
fun WebArchive.addWebInfXml(xmlDescriptor: Descriptor): WebArchive {
// contents of XML file
val stringAsset = StringAsset(xmlDescriptor.exportAsString())
// eg beans.xml, jboss-deployment-structure.xml:
val path = xmlDescriptor.descriptorName
addAsWebInfResource(stringAsset, path)
return this
}
}
| lgpl-2.1 | 9265c8243c294ad33f1db395b55558fe | 45.633333 | 473 | 0.681439 | 4.24368 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/web/vo/internship/regulate/InternshipRegulateVo.kt | 1 | 985 | package top.zbeboy.isy.web.vo.internship.regulate
import java.sql.Date
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
/**
* Created by zbeboy 2017-12-29 .
**/
open class InternshipRegulateVo {
var internshipRegulateId: String? = null
@NotNull
@Size(max = 30)
var studentName: String? = null
@NotNull
@Size(max = 20)
var studentNumber: String? = null
@NotNull
@Size(max = 15)
var studentTel: String? = null
@NotNull
@Size(max = 200)
var internshipContent: String? = null
@NotNull
@Size(max = 200)
var internshipProgress: String? = null
@NotNull
@Size(max = 20)
var reportWay: String? = null
@NotNull
var reportDate: Date? = null
var schoolGuidanceTeacher: String? = null
var tliy = "无"
@NotNull
var studentId: Int? = null
@NotNull
@Size(max = 64)
var internshipReleaseId: String? = null
@NotNull
var staffId: Int? = null
} | mit | 68ef07be971a2824bce874b29fa5b095 | 23 | 49 | 0.652085 | 3.627306 | false | false | false | false |
georocket/georocket | src/main/kotlin/io/georocket/index/generic/BoundingBoxIndexerFactory.kt | 1 | 3734 | package io.georocket.index.generic
import io.georocket.constants.ConfigConstants
import io.georocket.index.DatabaseIndex
import io.georocket.index.Indexer
import io.georocket.index.IndexerFactory
import io.georocket.index.geojson.GeoJsonBoundingBoxIndexer
import io.georocket.index.xml.XMLBoundingBoxIndexer
import io.georocket.query.GeoIntersects
import io.georocket.query.IndexQuery
import io.georocket.query.QueryCompiler.MatchPriority
import io.georocket.query.QueryPart
import io.georocket.query.StringQueryPart
import io.georocket.util.CoordinateTransformer
import io.georocket.util.JsonStreamEvent
import io.georocket.util.StreamEvent
import io.georocket.util.XMLStreamEvent
import io.vertx.core.Vertx
import io.vertx.kotlin.core.json.jsonArrayOf
import io.vertx.kotlin.core.json.jsonObjectOf
import org.geotools.referencing.CRS
/**
* Base class for factories creating indexers that manage bounding boxes
* @author Michel Kraemer
*/
class BoundingBoxIndexerFactory : IndexerFactory {
companion object {
private const val FLOAT_REGEX = "[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"
private const val COMMA_REGEX = "\\s*,\\s*"
private const val CODE_PREFIX = "([a-zA-Z]+:\\d+:)?"
private val BBOX_REGEX = (CODE_PREFIX + FLOAT_REGEX + COMMA_REGEX +
FLOAT_REGEX + COMMA_REGEX + FLOAT_REGEX + COMMA_REGEX + FLOAT_REGEX).toRegex()
}
val defaultCrs: String?
/**
* Default constructor
*/
constructor() {
defaultCrs = Vertx.currentContext()
?.config()
?.getString(ConfigConstants.QUERY_DEFAULT_CRS)
}
/**
* Construct a new instance with an explicit defaultCrs
*/
constructor(defaultCrs: String?) {
this.defaultCrs = defaultCrs
}
@Suppress("UNCHECKED_CAST")
override fun <T : StreamEvent> createIndexer(eventType: Class<T>): Indexer<T>? {
if (eventType.isAssignableFrom(XMLStreamEvent::class.java)) {
return XMLBoundingBoxIndexer() as Indexer<T>
} else if (eventType.isAssignableFrom(JsonStreamEvent::class.java)) {
return GeoJsonBoundingBoxIndexer() as Indexer<T>
}
return null
}
override fun getQueryPriority(queryPart: QueryPart): MatchPriority {
return when (queryPart) {
is StringQueryPart -> if (BBOX_REGEX.matches(queryPart.value)) {
MatchPriority.ONLY
} else {
MatchPriority.NONE
}
else -> MatchPriority.NONE
}
}
override fun compileQuery(queryPart: QueryPart): IndexQuery? {
if (queryPart !is StringQueryPart) {
return null
}
val index = queryPart.value.lastIndexOf(':')
val (crsCode, co) = if (index > 0) {
queryPart.value.substring(0, index) to queryPart.value.substring(index + 1)
} else {
null to queryPart.value
}
val crs = if (crsCode != null) {
CRS.decode(crsCode)
} else if (defaultCrs != null) {
CoordinateTransformer.decode(defaultCrs)
} else {
null
}
var points = co.split(",").map { it.trim().toDouble() }.toDoubleArray()
if (crs != null) {
val transformer = CoordinateTransformer(crs)
points = transformer.transform(points, 2)!!
}
val minX = points[0]
val minY = points[1]
val maxX = points[2]
val maxY = points[3]
return GeoIntersects(
"bbox", jsonObjectOf(
"type" to "Polygon",
"coordinates" to jsonArrayOf(
jsonArrayOf(
jsonArrayOf(minX, minY),
jsonArrayOf(maxX, minY),
jsonArrayOf(maxX, maxY),
jsonArrayOf(minX, maxY),
jsonArrayOf(minX, minY)
)
)
)
)
}
override fun getDatabaseIndexes(indexedFields: List<String>): List<DatabaseIndex> = listOf(
DatabaseIndex.Geo("bbox", "bbox_geo")
)
}
| apache-2.0 | 29388adcc7d01cfe06d6749da9b7b930 | 28.634921 | 93 | 0.676754 | 4.067538 | false | false | false | false |
paplorinc/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/HintUtils.kt | 3 | 1903 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hints
import com.intellij.codeInsight.hints.filtering.MatcherConstructor
import com.intellij.lang.Language
import com.intellij.lang.LanguageExtensionPoint
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.util.text.StringUtil
import java.util.*
import java.util.stream.Collectors
fun getHintProviders(): List<Pair<Language, InlayParameterHintsProvider>> {
val name = ExtensionPointName<LanguageExtensionPoint<InlayParameterHintsProvider>>("com.intellij.codeInsight.parameterNameHints")
val languages = name.extensionList.map { it.language }
return languages
.mapNotNull { Language.findLanguageByID(it) }
.map { it to InlayParameterHintsExtension.forLanguage(it) }
}
fun getBlackListInvalidLineNumbers(text: String): List<Int> {
val rules = StringUtil.split(text, "\n", true, false)
return rules
.mapIndexedNotNull { index, s -> index to s }
.filter { it.second.isNotEmpty() }
.map { it.first to MatcherConstructor.createMatcher(it.second) }
.filter { it.second == null }
.map { it.first }
}
fun getLanguageForSettingKey(language: Language): Language {
val supportedLanguages = getBaseLanguagesWithProviders()
var languageForSettings: Language? = language
while (languageForSettings != null && !supportedLanguages.contains(languageForSettings)) {
languageForSettings = languageForSettings.baseLanguage
}
if (languageForSettings == null) languageForSettings = language
return languageForSettings
}
fun getBaseLanguagesWithProviders(): List<Language> {
return getHintProviders()
.stream()
.map { (first) -> first }
.sorted(Comparator.comparing<Language, String> { l -> l.displayName })
.collect(Collectors.toList())
} | apache-2.0 | e42daf633d826e7577055a2d8c83e5e0 | 38.666667 | 140 | 0.76721 | 4.52019 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeFunctionLiteralReturnTypeFix.kt | 1 | 7432 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.findParentOfType
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.util.getParentResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getValueArgumentForExpression
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import java.util.*
class ChangeFunctionLiteralReturnTypeFix(
functionLiteralExpression: KtLambdaExpression,
type: KotlinType
) : KotlinQuickFixAction<KtLambdaExpression>(functionLiteralExpression) {
private val typePresentation = IdeDescriptorRenderers.SOURCE_CODE_TYPES_WITH_SHORT_NAMES.renderType(type)
private val typeSourceCode = IdeDescriptorRenderers.SOURCE_CODE_TYPES.renderType(type)
private val functionLiteralReturnTypeRef: KtTypeReference?
get() = element?.functionLiteral?.typeReference
private val appropriateQuickFix = createAppropriateQuickFix(functionLiteralExpression, type)
private fun createAppropriateQuickFix(functionLiteralExpression: KtLambdaExpression, type: KotlinType): IntentionAction? {
val context = functionLiteralExpression.analyze()
val functionLiteralType = context.getType(functionLiteralExpression) ?: return null
val builtIns = functionLiteralType.constructor.builtIns
val functionClass = builtIns.getFunction(functionLiteralType.arguments.size - 1)
val functionClassTypeParameters = LinkedList<KotlinType>()
for (typeProjection in functionLiteralType.arguments) {
functionClassTypeParameters.add(typeProjection.type)
}
// Replacing return type:
functionClassTypeParameters.removeAt(functionClassTypeParameters.size - 1)
functionClassTypeParameters.add(type)
val eventualFunctionLiteralType = TypeUtils.substituteParameters(functionClass, functionClassTypeParameters)
val correspondingProperty = PsiTreeUtil.getParentOfType(functionLiteralExpression, KtProperty::class.java)
if (correspondingProperty != null &&
correspondingProperty.delegate == null &&
correspondingProperty.initializer?.let { QuickFixBranchUtil.canEvaluateTo(it, functionLiteralExpression) } != false
) {
val correspondingPropertyTypeRef = correspondingProperty.typeReference
val propertyType = context.get(BindingContext.TYPE, correspondingPropertyTypeRef)
return if (propertyType != null && !KotlinTypeChecker.DEFAULT.isSubtypeOf(eventualFunctionLiteralType, propertyType))
ChangeVariableTypeFix(correspondingProperty, eventualFunctionLiteralType)
else
null
}
val resolvedCall = functionLiteralExpression.getParentResolvedCall(context, true)
if (resolvedCall != null) {
val valueArgument = resolvedCall.call.getValueArgumentForExpression(functionLiteralExpression)
val correspondingParameter = resolvedCall.getParameterForArgument(valueArgument)
if (correspondingParameter != null && correspondingParameter.overriddenDescriptors.size <= 1) {
val project = functionLiteralExpression.project
val correspondingParameterDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, correspondingParameter)
if (correspondingParameterDeclaration is KtParameter) {
val correspondingParameterTypeRef = correspondingParameterDeclaration.typeReference
val parameterType = context.get(BindingContext.TYPE, correspondingParameterTypeRef)
return if (parameterType != null && !KotlinTypeChecker.DEFAULT.isSubtypeOf(eventualFunctionLiteralType, parameterType))
ChangeParameterTypeFix(correspondingParameterDeclaration, eventualFunctionLiteralType)
else
null
}
}
}
val parentFunction = PsiTreeUtil.getParentOfType(functionLiteralExpression, KtFunction::class.java, true)
return if (parentFunction != null && QuickFixBranchUtil.canFunctionOrGetterReturnExpression(parentFunction, functionLiteralExpression)) {
val parentFunctionReturnTypeRef = parentFunction.typeReference
val parentFunctionReturnType = context.get(BindingContext.TYPE, parentFunctionReturnTypeRef)
if (parentFunctionReturnType != null && !KotlinTypeChecker.DEFAULT
.isSubtypeOf(eventualFunctionLiteralType, parentFunctionReturnType)
)
ChangeCallableReturnTypeFix.ForEnclosing(parentFunction, eventualFunctionLiteralType)
else
null
} else
null
}
override fun getText() = appropriateQuickFix?.text ?: KotlinBundle.message("fix.change.return.type.lambda", typePresentation)
override fun getFamilyName() = KotlinBundle.message("fix.change.return.type.family")
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean =
functionLiteralReturnTypeRef != null || appropriateQuickFix != null && appropriateQuickFix.isAvailable(
project,
editor!!,
file
)
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
ApplicationManager.getApplication().runWriteAction {
functionLiteralReturnTypeRef?.let {
val newTypeRef = it.replace(KtPsiFactory(project).createType(typeSourceCode)) as KtTypeReference
ShortenReferences.DEFAULT.process(newTypeRef)
}
}
if (appropriateQuickFix != null && appropriateQuickFix.isAvailable(project, editor!!, file)) {
appropriateQuickFix.invoke(project, editor, file)
}
}
override fun startInWriteAction(): Boolean {
return appropriateQuickFix == null || appropriateQuickFix.startInWriteAction()
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val functionLiteralExpression = diagnostic.psiElement.findParentOfType<KtLambdaExpression>(strict = false) ?: return null
return ChangeFunctionLiteralReturnTypeFix(functionLiteralExpression, functionLiteralExpression.builtIns.unitType)
}
}
}
| apache-2.0 | 02b6b619dd79a1d44d9bf88814e9c613 | 54.462687 | 145 | 0.745022 | 6.137077 | false | false | false | false |
java-graphics/assimp | src/main/kotlin/assimp/ParsingUtils.kt | 2 | 4622 | package assimp
import glm_.b
import glm_.c
import glm_.mat4x4.Mat4
import java.io.DataInputStream
import java.io.InputStream
import java.nio.ByteBuffer
/**
* Created by elect on 15/11/2016.
*/
var ByteBuffer.pos
get() = position()
set(value) {
position(value)
}
fun String.trimNUL(): String {
val nulIdx = indexOf(NUL)
return if (nulIdx != -1) substring(0, nulIdx)
else this
}
fun ByteBuffer.skipSpaces(): Boolean {
var value = this[position()]
while (value == SP.b || value == HT.b) {
get()
value = this[position()]
}
return !value.isLineEnd
}
fun ByteBuffer.skipLine(): Boolean {
var value = this[position()]
while (value != CR.b && value != LF.b && value != NUL.b) {
get()
value = this[position()]
}
// files are opened in binary mode. Ergo there are both NL and CR
while (value == CR.b || value == LF.b) {
get()
value = this[position()]
}
return value != 0.b
}
fun ByteBuffer.skipSpacesAndLineEnd(): Boolean {
var value = this[position()]
while (value == SP.b || value == HT.b || value == CR.b || value == LF.b) {
get()
// check if we are at the end of file, e.g: ply
if (remaining() > 0) value = this[position()]
else return true
}
return value != 0.b
}
fun ByteBuffer.nextWord(): String {
skipSpaces()
val bytes = ArrayList<Byte>()
while (!this[position()].isSpaceOrNewLine) bytes.add(get())
return String(bytes.toByteArray())
}
fun ByteBuffer.restOfLine(): String {
val bytes = ArrayList<Byte>()
while (!this[position()].isLineEnd) bytes.add(get())
return String(bytes.toByteArray())
}
fun ByteBuffer.consumeNUL() {
while (get(pos).c == NUL) get()
}
val Byte.isLineEnd get() = this == CR.b || this == LF.b || this == NUL.b || this == FF.b
val Char.isLineEnd get () = this == CR || this == LF || this == NUL || this == FF
val Byte.isSpaceOrNewLine get() = isSpace || isLineEnd
val Char.isSpaceOrNewLine get() = isSpace || isLineEnd
val Char.isNewLine get() = this == LF
val Byte.isSpace get() = this == SP.b || this == HT.b
val Char.isSpace get() = this == SP || this == HT
infix fun ByteBuffer.startsWith(string: String) = string.all { get() == it.b }
val Char.isNumeric get() = if (isDigit()) true else (this == '-' || this == '+')
// http://www.aivosto.com/vbtips/control-characters.html
/** Null */
val NUL = '\u0000'
/** Start of Heading — TC1 Transmission control character 1 */
val SOH = '\u0001'
/** Start of Text — TC2 Transmission control character 2 */
val STX = '\u0002'
/** End of Text — TC3 Transmission control character 3 */
val ETX = '\u0003'
/** End of Transmission — TC4 Transmission control character 4 */
val EOT = '\u0004'
/** Enquiry — TC5 Transmission control character 5 */
val ENQ = '\u0005'
/** Acknowledge — TC6 Transmission control character 6 */
val ACK = '\u0006'
/** Bell */
val BEL = '\u0007'
/** Backspace — FE0 Format effector 0 */
val BS = '\u0008'
/** Horizontal Tabulation — FE1 Format effector 1 (Character Tabulation) */
val HT = '\u0009'
/** Line Feed — FE2 Format effector 2 */
val LF = '\u000A'
/** Vertical Tabulation — FE3 Format effector 3 (Line Tabulation) */
val VT = '\u000B'
/** Form Feed — FE4 Format effector 4 */
val FF = '\u000C'
/** Carriage Return — FE5 Format effector 5 */
val CR = '\u000D'
/** Shift Out — LS1 Locking-Shift One */
val SO = '\u000E'
/** Shift In — LS0 Locking-Shift Zero */
val SI = '\u000D'
/** Data Link Escape — TC7 Transmission control character 7 */
val DLE = '\u0010'
/** Device Control 1 — XON */
val DC1 = '\u0011'
/** Device Control 2 */
val DC2 = '\u0012'
/** Device Control 3 — XOFF */
val DC3 = '\u0013'
/** Device Control 4 (Stop) */
val DC4 = '\u0014'
/** Negative Acknowledge — TC8 Transmission control character 8 */
val NAK = '\u0015'
/** Synchronous Idle — TC9 Transmission control character 9 */
val SYN = '\u0016'
/** End of Transmission Block — TC10 Transmission control character 10 */
val ETB = '\u0017'
/** Cancel */
val CAN = '\u0018'
/** End of Medium */
val EM = '\u0019'
/** Substitute */
val SUB = '\u001A'
/** Escape */
val ESC = '\u001B'
/** File Separator — IS4 Information separator 4 */
val FS = '\u001C'
/** Group Separator — IS3 Information separator 3 */
val GS = '\u001D'
/** Record Separator — IS2 Information separator 2 */
val RS = '\u001E'
/** Unit Separator — IS1 Information separator 1 */
val US = '\u001F'
/** Space */
val SP = '\u0020'
/** Delete */
val DEL = '\u007F' | bsd-3-clause | 88e61c29d36095ee7695c8d900113dbb | 27.240741 | 88 | 0.618059 | 3.295389 | false | false | false | false |
youdonghai/intellij-community | platform/configuration-store-impl/testSrc/TemplateSchemeTest.kt | 1 | 1491 | package com.intellij.configurationStore
import com.intellij.codeInsight.template.impl.TemplateSettings
import com.intellij.testFramework.rules.InMemoryFsRule
import com.intellij.testFramework.ProjectRule
import com.intellij.util.io.readText
import com.intellij.util.io.write
import org.assertj.core.api.Assertions.assertThat
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
class TemplateSchemeTest {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule()
}
@JvmField
@Rule
val fsRule = InMemoryFsRule()
// https://youtrack.jetbrains.com/issue/IDEA-155623#comment=27-1721029
@Test fun `do not remove unknown context`() {
val schemeFile = fsRule.fs.getPath("templates/Groovy.xml")
val schemeManagerFactory = SchemeManagerFactoryBase.TestSchemeManagerFactory(fsRule.fs.getPath(""))
val schemeData = """
<templateSet group="Groovy">
<template name="serr" value="System.err.println("$\END$")dwed" description="Prints a string to System.errwefwe" toReformat="true" toShortenFQNames="true" deactivated="true">
<context>
<option name="__DO_NOT_DELETE_ME__" value="true" />
<option name="GROOVY_STATEMENT" value="false" />
</context>
</template>
</templateSet>""".trimIndent()
schemeFile.write(schemeData)
TemplateSettings(schemeManagerFactory)
schemeManagerFactory.save()
assertThat(schemeFile.readText()).isEqualTo(schemeData)
}
} | apache-2.0 | 90d112aee40cd24d66b4536ca0cdd002 | 32.909091 | 189 | 0.735077 | 4.223796 | false | true | false | false |
heitorcolangelo/kappuccino | kappuccino/src/main/kotlin/br/com/concretesolutions/kappuccino/matchers/drawable/DrawableMatcher.kt | 1 | 1409 | package br.com.concretesolutions.kappuccino.matchers.drawable
import android.graphics.drawable.Drawable
import android.view.View
import br.com.concretesolutions.kappuccino.utils.getBitmap
import br.com.concretesolutions.kappuccino.utils.getDrawable
import br.com.concretesolutions.kappuccino.utils.getResourceName
import org.hamcrest.Description
import org.hamcrest.TypeSafeMatcher
open class DrawableMatcher(private val drawableId: Int) : TypeSafeMatcher<View>(View::class.java) {
private var resourceName: String? = null
protected var drawable: Drawable? = null
override fun matchesSafely(target: View): Boolean {
if (drawable == null) return drawableId < 0
val currentDrawable = drawable
resourceName = getResourceName(target.context, drawableId)
val expectedDrawable = getDrawable(target.context, drawableId) ?: return false
val currentBitmap = getBitmap(currentDrawable!!)
val expectedBitmap = getBitmap(expectedDrawable)
return currentBitmap.sameAs(expectedBitmap)
}
override fun describeTo(description: Description?) {
description?.appendText("with drawable from resource id: ")
description?.appendValue(drawableId)
if (resourceName != null) {
description?.appendText("[")
description?.appendText(resourceName)
description?.appendText("]")
}
}
}
| apache-2.0 | 44e13fc6d8ab7ad253fb8095301712cf | 36.078947 | 99 | 0.729595 | 5.199262 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/course_list/ui/delegate/CoursePropertiesDelegate.kt | 1 | 3417 | package org.stepik.android.view.course_list.ui.delegate
import android.view.View
import android.view.ViewGroup
import androidx.core.view.children
import androidx.core.view.isVisible
import kotlinx.android.synthetic.main.item_course.view.*
import kotlinx.android.synthetic.main.layout_course_properties.view.*
import org.stepic.droid.R
import org.stepic.droid.util.TextUtil
import org.stepik.android.domain.course.model.CourseStats
import org.stepik.android.domain.course.model.EnrollmentState
import org.stepik.android.domain.course_list.model.CourseListItem
import org.stepik.android.domain.user_courses.model.UserCourse
import org.stepik.android.model.Course
import ru.nobird.app.core.model.safeCast
import java.util.Locale
class CoursePropertiesDelegate(
root: View,
private val view: ViewGroup
) {
private val learnersCountImage = view.learnersCountImage
private val learnersCountText = view.learnersCountText
private val courseRatingImage = view.courseRatingImage
private val courseRatingText = view.courseRatingText
private val courseCertificateImage = view.courseCertificateImage
private val courseCertificateText = view.courseCertificateText
private val courseArchiveImage = view.courseArchiveImage
private val courseArchiveText = view.courseArchiveText
private val courseFavoriteImage = root.courseListFavorite
private val courseWishlistImage = root.courseListWishlist
fun setStats(courseListItem: CourseListItem.Data) {
setLearnersCount(courseListItem.course.learnersCount, courseListItem.course.enrollment > 0L)
setRating(courseListItem.courseStats)
setCertificate(courseListItem.course)
setUserCourse(courseListItem.courseStats.enrollmentState.safeCast<EnrollmentState.Enrolled>()?.userCourse)
setWishlist(courseListItem.course.enrollment > 0L, courseListItem.course.isInWishlist)
view.isVisible = view.children.any(View::isVisible)
}
private fun setLearnersCount(learnersCount: Long, isEnrolled: Boolean) {
val needShowLearners = learnersCount > 0 && !isEnrolled
if (needShowLearners) {
learnersCountText.text = TextUtil.formatNumbers(learnersCount)
}
learnersCountImage.isVisible = needShowLearners
learnersCountText.isVisible = needShowLearners
}
private fun setRating(courseStats: CourseStats) {
val needShow = courseStats.review > 0
if (needShow) {
courseRatingText.text = String.format(Locale.ROOT, view.resources.getString(R.string.course_rating_value), courseStats.review)
}
courseRatingImage.isVisible = needShow
courseRatingText.isVisible = needShow
}
private fun setCertificate(course: Course) {
val isEnrolled = course.enrollment > 0L
val needShow = course.withCertificate && !isEnrolled
courseCertificateImage.isVisible = needShow
courseCertificateText.isVisible = needShow
}
private fun setUserCourse(userCourse: UserCourse?) {
courseFavoriteImage.isVisible = userCourse?.isFavorite == true
val isArchived = userCourse?.isArchived == true
courseArchiveImage.isVisible = isArchived
courseArchiveText.isVisible = isArchived
}
private fun setWishlist(isEnrolled: Boolean, isWishlisted: Boolean) {
courseWishlistImage.isVisible = !isEnrolled && isWishlisted
}
} | apache-2.0 | defc4967a796b4981fe7742c2b55a24a | 39.690476 | 138 | 0.759438 | 4.687243 | false | false | false | false |
Skatteetaten/boober | src/test/kotlin/no/skatteetaten/aurora/boober/feature/JavaDeployFeatureTest.kt | 1 | 4757 | package no.skatteetaten.aurora.boober.feature
import org.junit.jupiter.api.Test
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isSuccess
import no.skatteetaten.aurora.boober.model.ApplicationDeploymentRef
import no.skatteetaten.aurora.boober.model.openshift.ApplicationDeployment
import no.skatteetaten.aurora.boober.utils.AbstractFeatureTest
import no.skatteetaten.aurora.boober.utils.singleApplicationErrorResult
class JavaDeployFeatureTest : AbstractFeatureTest() {
override val feature: Feature
get() = JavaDeployFeature("docker.registry")
@Test
fun `should generate resource for java application`() {
val (adResource, dcResource, serviceResource, isResource) = generateResources(
"""{
"version" : "SNAPSHOT-feature_FOO_1001_FIX_STUPID_STUFF_20190402.113042-26-b1.18.1-wingnut8-1.3.0",
"groupId" : "org.test"
}""",
resource = createEmptyApplicationDeployment(),
createdResources = 3
)
assertThat(adResource).auroraResourceModifiedByThisFeatureWithComment("Added application name and id")
val ad = adResource.resource as ApplicationDeployment
assertThat(ad.spec.applicationId).isEqualTo("665c8f8518c18e8fc6b28a458496ce19bf9e7645")
assertThat(ad.spec.applicationName).isEqualTo("simple")
assertThat(dcResource).auroraResourceCreatedByThisFeature().auroraResourceMatchesFile("dc.json")
assertThat(serviceResource).auroraResourceCreatedByThisFeature().auroraResourceMatchesFile("service.json")
assertThat(isResource).auroraResourceCreatedByThisFeature().auroraResourceMatchesFile("is.json")
}
@Test
fun `should generate resource for java application with adaptions`() {
val (adResource, dcResource, serviceResource, isResource) = generateResources(
"""{
"artifactId" : "simple",
"version" : "1",
"groupId" : "org.test",
"readiness" : {
"path" : "/health"
},
"liveness" : true,
"serviceAccount" : "hero",
"deployStrategy" : {
"type" : "recreate"
},
"prometheus" : false
}""",
resource = createEmptyApplicationDeployment(),
createdResources = 3
)
assertThat(adResource).auroraResourceModifiedByThisFeatureWithComment("Added application name and id")
val ad = adResource.resource as ApplicationDeployment
assertThat(ad.spec.applicationId).isEqualTo("665c8f8518c18e8fc6b28a458496ce19bf9e7645")
assertThat(ad.spec.applicationName).isEqualTo("simple")
assertThat(dcResource).auroraResourceCreatedByThisFeature().auroraResourceMatchesFile("dc-expanded.json")
assertThat(serviceResource).auroraResourceCreatedByThisFeature()
.auroraResourceMatchesFile("service-no-prometheus.json")
assertThat(isResource).auroraResourceCreatedByThisFeature().auroraResourceMatchesFile("is-1.json")
}
@Test
fun `fileName can be long if both artifactId and name exist`() {
assertThat {
createCustomAuroraDeploymentContext(
ApplicationDeploymentRef("utv", "this-name-is-stupid-stupid-stupidly-long-for-no-reason"),
"about.json" to FEATURE_ABOUT,
"this-name-is-stupid-stupid-stupidly-long-for-no-reason.json" to """{ "groupId" : "org.test" }""",
"utv/about.json" to "{}",
"utv/this-name-is-stupid-stupid-stupidly-long-for-no-reason.json" to
"""{ "name" : "foo", "artifactId" : "foo", "version" : "1" }"""
)
}.isSuccess()
}
@Test
fun `Fails when application name is too long and artifactId blank`() {
assertThat {
createCustomAuroraDeploymentContext(
ApplicationDeploymentRef("utv", "this-name-is-stupid-stupid-stupidly-long-for-no-reason"),
"about.json" to FEATURE_ABOUT,
"this-name-is-stupid-stupid-stupidly-long-for-no-reason.json" to """{ "groupId" : "org.test" }""",
"utv/about.json" to "{}",
"utv/this-name-is-stupid-stupid-stupidly-long-for-no-reason.json" to
"""{ "name" : "foo", "version" : "1" }"""
)
}.singleApplicationErrorResult("ArtifactId must be set and be shorter then 50 characters")
}
@Test
fun `Fails when envFile does not start with about`() {
assertThat {
createAuroraDeploymentContext(
"""{
"envFile" : "foo.json"
}"""
)
}.singleApplicationErrorResult("envFile must start with about")
}
}
| apache-2.0 | 9648d1446e3b5cb13abe251bdeec6bf6 | 42.245455 | 114 | 0.647887 | 4.636452 | false | true | false | false |
allotria/intellij-community | plugins/markdown/src/org/intellij/plugins/markdown/extensions/jcef/mermaid/MermaidCodeGeneratingProviderExtension.kt | 3 | 5188 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.extensions.jcef.mermaid
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.ColorUtil
import com.intellij.util.io.DigestUtil
import org.intellij.markdown.ast.ASTNode
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.extensions.MarkdownCodeFenceCacheableProvider
import org.intellij.plugins.markdown.extensions.MarkdownExtensionWithExternalFiles
import org.intellij.plugins.markdown.extensions.jcef.MarkdownJCEFPreviewExtension
import org.intellij.plugins.markdown.ui.preview.ResourceProvider
import org.intellij.plugins.markdown.ui.preview.html.MarkdownCodeFencePluginCacheCollector
import org.intellij.plugins.markdown.ui.preview.html.MarkdownUtil
import java.io.File
import java.nio.file.Paths
internal class MermaidCodeGeneratingProviderExtension(
collector: MarkdownCodeFencePluginCacheCollector? = null
) : MarkdownCodeFenceCacheableProvider(collector),
MarkdownJCEFPreviewExtension,
MarkdownExtensionWithExternalFiles,
ResourceProvider
{
override val scripts: List<String> = listOf(
MAIN_SCRIPT_FILENAME,
THEME_DEFINITION_FILENAME,
"mermaid/bootstrap.js",
)
override val styles: List<String> = listOf("mermaid/mermaid.css")
override val events: Map<String, (String) -> Unit> =
mapOf("storeMermaidFile" to this::storeFileEvent)
override fun isApplicable(language: String) = isEnabled && isAvailable && language == "mermaid"
override fun generateHtml(language: String, raw: String, node: ASTNode): String {
val hash = MarkdownUtil.md5(raw, "") + determineTheme()
val key = getUniqueFile("mermaid", hash, "svg").toFile()
return if (key.exists()) {
"<img src=\"${key.toURI()}\"/>"
} else createRawContentElement(hash, raw)
}
fun store(key: String, content: ByteArray) {
val actualKey = getUniqueFile("mermaid", key, "svg").toFile()
FileUtil.createParentDirs(actualKey)
actualKey.outputStream().buffered().use {
it.write(content)
}
collector?.addAliveCachedFile(this, actualKey)
}
override fun onLAFChanged() = Unit
override val displayName: String =
MarkdownBundle.message("markdown.extensions.mermaid.display.name")
override val id: String = "MermaidLanguageExtension"
override val description: String = MarkdownBundle.message("markdown.extensions.mermaid.description")
override val downloadLink: String = DOWNLOAD_URL
override val downloadFilename: String = "mermaid.js"
private val actualFile
get() = Paths.get(directory.toString(), "mermaid", downloadFilename).toFile()
private fun isDistributionChecksumValid(): Boolean {
val got = StringUtil.toHexString(DigestUtil.md5().digest(actualFile.readBytes()))
return got == CHECKSUM
}
override val isAvailable: Boolean
get() = actualFile.exists() && isDistributionChecksumValid()
override fun afterDownload(): Boolean {
val sourceFile = File(directory, downloadFilename)
sourceFile.copyTo(actualFile, overwrite = true)
return sourceFile.delete()
}
override fun canProvide(resourceName: String): Boolean {
return resourceName in scripts || resourceName in styles
}
private fun determineTheme(): String {
val registryValue = Registry.stringValue("markdown.mermaid.theme")
if (registryValue == "follow-ide") {
val scheme = EditorColorsManager.getInstance().globalScheme
return if (ColorUtil.isDark(scheme.defaultBackground)) "dark" else "default"
}
return registryValue
}
override fun loadResource(resourceName: String): ResourceProvider.Resource? {
return when (resourceName) {
MAIN_SCRIPT_FILENAME -> ResourceProvider.loadExternalResource(File(directory, resourceName))
THEME_DEFINITION_FILENAME -> ResourceProvider.Resource("window.mermaidTheme = '${determineTheme()}';".toByteArray())
else -> ResourceProvider.loadInternalResource(this::class.java, resourceName)
}
}
override val resourceProvider: ResourceProvider = this
private fun escapeContent(content: String): String {
return content.replace("<", "<").replace(">", ">")
}
private fun createRawContentElement(hash: String, content: String): String {
return "<div class=\"mermaid\" cache-id=\"$hash\" id=\"$hash\">${escapeContent(content)}</div>"
}
private fun storeFileEvent(data: String) {
if (data.isEmpty()) {
return
}
val key = data.substring(0, data.indexOf(';'))
val content = data.substring(data.indexOf(';') + 1)
store(key, content.toByteArray())
}
companion object {
private const val MAIN_SCRIPT_FILENAME = "mermaid/mermaid.js"
private const val THEME_DEFINITION_FILENAME = "mermaid/themeDefinition.js"
private const val DOWNLOAD_URL = "https://unpkg.com/[email protected]/dist/mermaid.js"
private const val CHECKSUM = "352791299c7f42ee02e774da58bead4a"
}
}
| apache-2.0 | 8c9935a22650da133700e1f4f42b7b5a | 37.716418 | 140 | 0.747494 | 4.392887 | false | false | false | false |
zdary/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenWslUtil.kt | 1 | 14761 | // Copyright 2000-2021 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.utils
import com.intellij.execution.wsl.WSLCommandLineOptions
import com.intellij.execution.wsl.WSLDistribution
import com.intellij.execution.wsl.WslPath
import com.intellij.notification.Notification
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.components.service
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.projectRoots.JdkFinder
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil
import com.intellij.openapi.projectRoots.impl.jdkDownloader.JdkInstaller
import com.intellij.openapi.projectRoots.impl.jdkDownloader.JdkListDownloader
import com.intellij.openapi.projectRoots.impl.jdkDownloader.JdkPredicate
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.roots.ex.ProjectRootManagerEx
import com.intellij.openapi.roots.ui.configuration.ProjectStructureConfigurable
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.navigation.Place
import com.intellij.util.text.VersionComparatorUtil
import org.jetbrains.idea.maven.execution.SyncBundle
import org.jetbrains.idea.maven.project.MavenProjectBundle
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.server.MavenDistributionsCache
import org.jetbrains.idea.maven.server.MavenServerManager
import org.jetbrains.idea.maven.server.WslMavenDistribution
import java.io.File
import java.util.function.Function
import java.util.function.Supplier
import javax.swing.event.HyperlinkEvent
internal object MavenWslUtil : MavenUtil() {
@JvmStatic
fun getPropertiesFromMavenOpts(distribution: WSLDistribution): Map<String, String> {
return parseMavenProperties(distribution.getEnvironmentVariable("MAVEN_OPTS"))
}
@JvmStatic
fun getWslDistribution(project: Project): WSLDistribution {
val basePath = project.basePath ?: throw IllegalArgumentException("Project $project with null base path")
return WslPath.getDistributionByWindowsUncPath(basePath)
?: throw IllegalArgumentException("Distribution for path $basePath not found, check your WSL installation")
}
@JvmStatic
fun tryGetWslDistribution(project: Project): WSLDistribution? {
return project.basePath?.let { WslPath.getDistributionByWindowsUncPath(it) }
}
@JvmStatic
fun tryGetWslDistributionForPath(path: String?): WSLDistribution? {
return path?.let { WslPath.getDistributionByWindowsUncPath(it)}
}
/**
* return file in windows-style ("\\wsl$\distrib-name\home\user\.m2\settings.xml")
*/
@JvmStatic
fun WSLDistribution.resolveUserSettingsFile(overriddenUserSettingsFile: String?): File {
if (isEmptyOrSpaces(overriddenUserSettingsFile)) {
return File(resolveM2Dir(), SETTINGS_XML)
}
else {
return File(overriddenUserSettingsFile)
}
}
/**
* return file in windows-style ("\\wsl$\distrib-name\home\user\.m2\settings.xml")
*/
@JvmStatic
fun WSLDistribution.resolveGlobalSettingsFile(overriddenMavenHome: String?): File? {
val directory = this.resolveMavenHomeDirectory(overriddenMavenHome) ?: return null
return File(File(directory, CONF_DIR), SETTINGS_XML)
}
@JvmStatic
fun WSLDistribution.resolveM2Dir(): File {
return this.getWindowsFile(File(this.environment["HOME"], DOT_M2_DIR))!!
}
/**
* return file in windows-style ("\\wsl$\distrib-name\home\user\.m2\settings.xml")
*/
@JvmStatic
fun WSLDistribution.resolveMavenHomeDirectory(overrideMavenHome: String?): File? {
MavenLog.LOG.debug("resolving maven home on WSL with override = \"${overrideMavenHome}\"")
if (overrideMavenHome != null) {
if (overrideMavenHome == MavenServerManager.BUNDLED_MAVEN_3) {
return MavenDistributionsCache.resolveEmbeddedMavenHome().mavenHome
}
val home = File(overrideMavenHome)
if (isValidMavenHome(home)) {
MavenLog.LOG.debug("resolved maven home as ${overrideMavenHome}")
return home
}
else {
MavenLog.LOG.debug("Maven home ${overrideMavenHome} on WSL is invalid")
return null
}
}
val m2home = this.environment[ENV_M2_HOME]
if (m2home != null && !isEmptyOrSpaces(m2home)) {
val homeFromEnv = this.getWindowsPath(m2home)?.let(::File)
if (isValidMavenHome(homeFromEnv)) {
MavenLog.LOG.debug("resolved maven home using \$M2_HOME as ${homeFromEnv}")
return homeFromEnv
}
else {
MavenLog.LOG.debug("Maven home using \$M2_HOME is invalid")
return null
}
}
var home = this.getWindowsPath("/usr/share/maven")?.let(::File)
if (isValidMavenHome(home)) {
MavenLog.LOG.debug("Maven home found at /usr/share/maven")
return home
}
home = this.getWindowsPath("/usr/share/maven2")?.let(::File)
if (isValidMavenHome(home)) {
MavenLog.LOG.debug("Maven home found at /usr/share/maven2")
return home
}
val options = WSLCommandLineOptions()
.setExecuteCommandInLoginShell(true)
.setShellPath(this.shellPath)
val processOutput = this.executeOnWsl(listOf("which", "mvn"), options, 10000, null)
if (processOutput.exitCode == 0) {
val path = processOutput.stdout.lines().find { it.isNotEmpty() }?.let(this::resolveSymlink)?.let(this::getWindowsPath)?.let(::File)
if (path != null) {
return path
}
}
MavenLog.LOG.debug("mvn not found in \$PATH")
MavenLog.LOG.debug("Maven home not found on ${this.presentableName}")
return null
}
/**
* return file in windows style
*/
@JvmStatic
fun WSLDistribution.resolveLocalRepository(overriddenLocalRepository: String?,
overriddenMavenHome: String?,
overriddenUserSettingsFile: String?): File {
if (overriddenLocalRepository != null && !isEmptyOrSpaces(overriddenLocalRepository)) {
return File(overriddenLocalRepository)
}
return doResolveLocalRepository(this.resolveUserSettingsFile(overriddenUserSettingsFile),
this.resolveGlobalSettingsFile(overriddenMavenHome))?.let { this.getWindowsFile(it) }
?: File(this.resolveM2Dir(), REPOSITORY_DIR)
}
@JvmStatic
internal fun WSLDistribution.getDefaultMavenDistribution(overriddenMavenHome: String? = null): WslMavenDistribution? {
val file = this.resolveMavenHomeDirectory(overriddenMavenHome) ?: return null
val wslFile = this.getWslPath(file.path) ?: return null
return WslMavenDistribution(this, wslFile, "default")
}
@JvmStatic
fun getJdkPath(wslDistribution: WSLDistribution): String? {
return wslDistribution.getEnvironmentVariable("JDK_HOME")
}
@JvmStatic
fun WSLDistribution.getWindowsFile(wslFile: File): File? {
return FileUtil.toSystemIndependentName(wslFile.path).let(this::getWindowsPath)?.let(::File)
}
@JvmStatic
fun WSLDistribution.getWslFile(windowsFile: File): File? {
return windowsFile.path.let(this::getWslPath)?.let(::File)
}
@JvmStatic
fun <T> resolveWslAware(project: Project?, ordinary: Supplier<T>, wsl: Function<WSLDistribution, T>): T {
if (project == null && ApplicationManager.getApplication().isUnitTestMode) {
MavenLog.LOG.error("resolveWslAware: Project is null")
}
val wslDistribution = project?.let { tryGetWslDistribution(it) } ?: return ordinary.get()
return wsl.apply(wslDistribution)
}
@JvmStatic
fun useWslMaven(project: Project): Boolean {
val projectWslDistr = tryGetWslDistribution(project) ?: return false
val jdkWslDistr = tryGetWslDistributionForPath(ProjectRootManager.getInstance(project).projectSdk?.homePath) ?: return false
return jdkWslDistr.id == projectWslDistr.id
}
@JvmStatic
fun sameDistributions(first: WSLDistribution?, second: WSLDistribution?): Boolean {
return first?.id == second?.id
}
@JvmStatic
fun restartMavenConnectorsIfJdkIncorrect(project: Project) {
ProgressManager.getInstance().runProcessWithProgressSynchronously(
{
val projectWslDistr = tryGetWslDistribution(project)
var needReset = false
MavenServerManager.getInstance().allConnectors.forEach {
if (it.project == project) {
val jdkWslDistr = tryGetWslDistributionForPath(it.jdk.homePath)
if ((projectWslDistr != null && it.supportType != "WSL") || !sameDistributions(projectWslDistr, jdkWslDistr)) {
needReset = true
it.shutdown(true)
}
}
}
if (!needReset) {
MavenProjectsManager.getInstance(project).embeddersManager.reset()
}
}, SyncBundle.message("maven.sync.restarting"), false, project)
}
@JvmStatic
fun checkWslJdkAndShowNotification(project: Project?) {
val projectWslDistr = tryGetWslDistribution(project!!)
val sdk = ProjectRootManager.getInstance(project).projectSdk
if (sdk == null) return;
val jdkWslDistr = tryGetWslDistributionForPath(sdk.homePath)
val FIX_STR = "FIX"
val OPEN_STR = "OPEN"
if (sameDistributions(projectWslDistr, jdkWslDistr)) return
val listener = object : NotificationListener {
override fun hyperlinkUpdate(notification: Notification, event: HyperlinkEvent) {
if (event.description == OPEN_STR) {
val configurable = ProjectStructureConfigurable.getInstance(
project)
ShowSettingsUtil.getInstance().editConfigurable(project, configurable) {
val place = Place().putPath(
ProjectStructureConfigurable.CATEGORY, configurable.projectConfig)
configurable.navigateTo(place, true)
}
}
else {
if (trySetUpExistingJdk(project, projectWslDistr, notification)) return
ApplicationManager.getApplication().invokeLater {
findOrDownloadNewJdk(project, projectWslDistr, sdk, notification, this)
}
}
}
}
if (projectWslDistr != null && jdkWslDistr == null) {
Notifications.Bus.notify(Notification(MAVEN_NOTIFICATION_GROUP, MavenProjectBundle.message("wsl.windows.jdk.used.for.wsl"),
MavenProjectBundle.message("wsl.windows.jdk.used.for.wsl.descr", OPEN_STR, FIX_STR),
NotificationType.WARNING,
listener), project)
}
else if (projectWslDistr == null && jdkWslDistr != null) {
Notifications.Bus.notify(Notification(MAVEN_NOTIFICATION_GROUP, MavenProjectBundle.message("wsl.wsl.jdk.used.for.windows"),
MavenProjectBundle.message("wsl.wsl.jdk.used.for.windows.descr", OPEN_STR, FIX_STR),
NotificationType.WARNING,
listener), project)
}
else if (projectWslDistr != null && jdkWslDistr != null) {
Notifications.Bus.notify(Notification(MAVEN_NOTIFICATION_GROUP, MavenProjectBundle.message("wsl.different.wsl.jdk.used"),
MavenProjectBundle.message("wsl.different.wsl.jdk.used.descr", OPEN_STR, FIX_STR),
NotificationType.WARNING,
listener), project)
}
}
private fun trySetUpExistingJdk(project: Project, projectWslDistr: WSLDistribution?, notification: Notification): Boolean {
val sdk = service<ProjectJdkTable>().allJdks.filter {
sameDistributions(projectWslDistr, it.homePath?.let(WslPath::getDistributionByWindowsUncPath))
}.maxWithOrNull(compareBy(VersionComparatorUtil.COMPARATOR) { it.versionString })
if (sdk == null) return false;
WriteAction.runAndWait<RuntimeException> {
ProjectRootManagerEx.getInstance(project).projectSdk = sdk
notification.hideBalloon()
}
return true
}
private fun findOrDownloadNewJdk(project: Project, projectWslDistr: WSLDistribution?, sdk: Sdk, notification: Notification, listener: NotificationListener) {
val jdkTask = object : Task.Backgroundable(null, MavenProjectBundle.message("wsl.jdk.searching"), false) {
override fun run(indicator: ProgressIndicator) {
val sdkPath = service<JdkFinder>().suggestHomePaths().filter {
sameDistributions(projectWslDistr, WslPath.getDistributionByWindowsUncPath(it))
}.firstOrNull()
if (sdkPath != null) {
WriteAction.runAndWait<RuntimeException> {
val jdkName = SdkConfigurationUtil.createUniqueSdkName(JavaSdk.getInstance(), sdkPath,
ProjectJdkTable.getInstance().allJdks.toList())
val newJdk = JavaSdk.getInstance().createJdk(jdkName, sdkPath)
ProjectJdkTable.getInstance().addJdk(newJdk)
ProjectRootManagerEx.getInstance(project).projectSdk = newJdk
notification.hideBalloon()
}
return
}
val installer = JdkInstaller.getInstance()
val jdkPredicate = when {
projectWslDistr != null -> JdkPredicate.forWSL()
else -> JdkPredicate.default()
}
val model = JdkListDownloader.getInstance().downloadModelForJdkInstaller(indicator, jdkPredicate)
if (model.isEmpty()) {
Notifications.Bus.notify(Notification(MAVEN_NOTIFICATION_GROUP, MavenProjectBundle.message("maven.wsl.jdk.fix.failed"),
MavenProjectBundle.message("maven.wsl.jdk.fix.failed.descr"),
NotificationType.ERROR, listener), project)
}
else {
val homeDir = installer.defaultInstallDir(model[0], projectWslDistr)
val request = installer.prepareJdkInstallation(model[0], homeDir)
installer.installJdk(request, indicator, project)
notification.hideBalloon()
}
}
}
ProgressManager.getInstance().run(jdkTask)
}
}
| apache-2.0 | d6dd96116c086e257e9d3696a0134e5c | 42.414706 | 159 | 0.69582 | 4.920333 | false | false | false | false |
zdary/intellij-community | platform/lang-impl/src/com/intellij/ui/tabs/FileColorModelStorageManager.kt | 4 | 1304 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.tabs
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import com.intellij.ui.FileColorManager
import org.jdom.Element
@Service
internal abstract class FileColorModelStorageManager(private val project: Project) : PersistentStateComponent<Element> {
protected abstract val perUser: Boolean
private fun getFileColorManager() = FileColorManager.getInstance(project) as FileColorManagerImpl
override fun getState(): Element {
return getFileColorManager().uninitializedModel.save(!perUser)
}
override fun loadState(state: Element) {
getFileColorManager().uninitializedModel.load(state, !perUser)
}
}
@State(name = "SharedFileColors", storages = [Storage("fileColors.xml")])
internal class PerTeamFileColorModelStorageManager(project: Project) : FileColorModelStorageManager(project) {
override val perUser: Boolean
get() = false
}
@State(name = "FileColors", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)])
internal class PerUserFileColorModelStorageManager(project: Project) : FileColorModelStorageManager(project) {
override val perUser: Boolean
get() = true
} | apache-2.0 | 9db343c52adf5f03906ad8f6da26271e | 37.382353 | 140 | 0.789877 | 4.4811 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/main/kotlin/com/vrem/wifianalyzer/wifi/timegraph/TimeGraphView.kt | 1 | 3657 | /*
* 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.wifi.timegraph
import android.view.View
import com.jjoe64.graphview.GraphView
import com.vrem.annotation.OpenClass
import com.vrem.wifianalyzer.MainContext
import com.vrem.wifianalyzer.R
import com.vrem.wifianalyzer.settings.Settings
import com.vrem.wifianalyzer.settings.ThemeStyle
import com.vrem.wifianalyzer.wifi.band.WiFiBand
import com.vrem.wifianalyzer.wifi.graphutils.GraphViewBuilder
import com.vrem.wifianalyzer.wifi.graphutils.GraphViewNotifier
import com.vrem.wifianalyzer.wifi.graphutils.GraphViewWrapper
import com.vrem.wifianalyzer.wifi.model.WiFiData
import com.vrem.wifianalyzer.wifi.predicate.Predicate
import com.vrem.wifianalyzer.wifi.predicate.makeOtherPredicate
private const val NUM_X_TIME = 21
internal fun makeGraphView(mainContext: MainContext, graphMaximumY: Int, themeStyle: ThemeStyle): GraphView =
GraphViewBuilder(NUM_X_TIME, graphMaximumY, themeStyle, false)
.setLabelFormatter(TimeAxisLabel())
.setVerticalTitle(mainContext.resources.getString(R.string.graph_axis_y))
.setHorizontalTitle(mainContext.resources.getString(R.string.graph_time_axis_x))
.build(mainContext.context)
internal fun makeGraphViewWrapper(): GraphViewWrapper {
val settings = MainContext.INSTANCE.settings
val themeStyle = settings.themeStyle()
val configuration = MainContext.INSTANCE.configuration
val graphView = makeGraphView(MainContext.INSTANCE, settings.graphMaximumY(), themeStyle)
val graphViewWrapper = GraphViewWrapper(graphView, settings.timeGraphLegend(), themeStyle)
configuration.size = graphViewWrapper.size(graphViewWrapper.calculateGraphType())
graphViewWrapper.setViewport()
return graphViewWrapper
}
@OpenClass
internal class TimeGraphView(private val wiFiBand: WiFiBand,
private val dataManager: DataManager = DataManager(),
private val graphViewWrapper: GraphViewWrapper = makeGraphViewWrapper())
: GraphViewNotifier {
override fun update(wiFiData: WiFiData) {
val predicate = predicate(MainContext.INSTANCE.settings)
val wiFiDetails = wiFiData.wiFiDetails(predicate, MainContext.INSTANCE.settings.sortBy())
val newSeries = dataManager.addSeriesData(graphViewWrapper, wiFiDetails, MainContext.INSTANCE.settings.graphMaximumY())
graphViewWrapper.removeSeries(newSeries)
graphViewWrapper.updateLegend(MainContext.INSTANCE.settings.timeGraphLegend())
graphViewWrapper.visibility(if (selected()) View.VISIBLE else View.GONE)
}
fun predicate(settings: Settings): Predicate = makeOtherPredicate(settings)
private fun selected(): Boolean {
return wiFiBand == MainContext.INSTANCE.settings.wiFiBand()
}
override fun graphView(): GraphView {
return graphViewWrapper.graphView
}
} | gpl-3.0 | ec8ec3a31d37a897bab7a5b0f63845f2 | 44.725 | 127 | 0.761553 | 4.71871 | false | false | false | false |
grover-ws-1/http4k | http4k-core/src/test/kotlin/org/http4k/lens/helpers.kt | 1 | 4814 | package org.http4k.lens
import com.natpryce.hamkrest.MatchResult
import com.natpryce.hamkrest.Matcher
import com.natpryce.hamkrest.absent
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.throws
import org.http4k.core.Status
import org.http4k.lens.ParamMeta.StringParam
object BiDiLensContract {
val spec = BiDiLensSpec("location", StringParam, LensGet { _: String, str: String ->
if (str.isBlank()) emptyList() else listOf(str)
},
LensSet { _: String, values: List<String>, str: String -> values.fold(str, { memo, next -> memo + next }) })
fun <IN, T> checkContract(spec: BiDiLensSpec<IN, String, T>, tValue: T, validValue: IN, nullValue: IN, invalidValue: IN, s: IN, modifiedValue: IN, listModifiedValue: IN) {
//synonym methods
assertThat(spec.required("hello").extract(validValue), equalTo(tValue))
assertThat(spec.required("hello").inject(tValue, s), equalTo(modifiedValue))
val optionalLens = spec.optional("hello")
assertThat(optionalLens(validValue), equalTo(tValue))
assertThat(optionalLens.extract(validValue), equalTo(tValue))
assertThat((spec.map { it.toString() }.optional("hello"))(validValue), equalTo(tValue.toString()))
assertThat(optionalLens(nullValue), absent())
assertThat({ optionalLens(invalidValue) }, throws(lensFailureWith(optionalLens.invalid())))
assertThat(optionalLens(tValue, s), equalTo(modifiedValue))
val optionalMultiLens = spec.multi.optional("hello")
assertThat(optionalMultiLens(validValue), equalTo(listOf(tValue)))
assertThat((spec.map { it.toString() }.multi.optional("hello"))(validValue), equalTo(listOf(tValue.toString())))
assertThat(optionalMultiLens(nullValue), absent())
assertThat({ optionalMultiLens(invalidValue) }, throws(lensFailureWith(optionalLens.invalid())))
assertThat(optionalMultiLens(listOf(tValue, tValue), s), equalTo(listModifiedValue))
val requiredLens = spec.required("hello")
assertThat(requiredLens(validValue), equalTo(tValue))
assertThat((spec.map { it.toString() }.required("hello"))(validValue), equalTo(tValue.toString()))
assertThat({ requiredLens(nullValue) }, throws(lensFailureWith(requiredLens.missing())))
assertThat({ requiredLens(invalidValue) }, throws(lensFailureWith(requiredLens.invalid())))
assertThat(requiredLens(tValue, s), equalTo(modifiedValue))
val requiredMultiLens = spec.multi.required("hello")
assertThat(requiredMultiLens(validValue), equalTo(listOf(tValue)))
assertThat((spec.map { it.toString() }.multi.required("hello"))(validValue), equalTo(listOf(tValue.toString())))
assertThat({ requiredMultiLens(nullValue) }, throws(lensFailureWith(requiredLens.missing())))
assertThat({ requiredMultiLens(invalidValue) }, throws(lensFailureWith(requiredLens.invalid())))
assertThat(requiredMultiLens(listOf(tValue, tValue), s), equalTo(listModifiedValue))
val defaultedLens = spec.defaulted("hello", tValue)
assertThat(defaultedLens(validValue), equalTo(tValue))
assertThat((spec.map { it.toString() }.defaulted("hello", "world"))(validValue), equalTo(tValue.toString()))
assertThat(defaultedLens(nullValue), equalTo(tValue))
assertThat({ defaultedLens(invalidValue) }, throws(lensFailureWith(defaultedLens.invalid())))
assertThat(defaultedLens(tValue, s), equalTo(modifiedValue))
val defaultedMultiLens = spec.multi.defaulted("hello", listOf(tValue))
assertThat(defaultedMultiLens(validValue), equalTo(listOf(tValue)))
assertThat((spec.map { it.toString() }.multi.defaulted("hello", listOf(tValue.toString())))(validValue), equalTo(listOf(tValue.toString())))
assertThat(defaultedMultiLens(nullValue), equalTo(listOf(tValue)))
assertThat({ defaultedMultiLens(invalidValue) }, throws(lensFailureWith(defaultedMultiLens.invalid())))
assertThat(defaultedMultiLens(listOf(tValue, tValue), s), equalTo(listModifiedValue))
}
}
data class MyCustomBodyType(val value: String)
fun lensFailureWith(vararg failures: Failure, status: Status = Status.BAD_REQUEST) = object : Matcher<LensFailure> {
private val expectedList = failures.toList()
override val description: String = "LensFailure with status $status and failures $expectedList"
override fun invoke(actual: LensFailure): MatchResult =
if (actual.failures != expectedList) {
MatchResult.Mismatch("\n${actual.failures}\ninstead of \n$expectedList")
} else if (actual.status != status) {
MatchResult.Mismatch("${actual.status}\ninstead of $status")
} else
MatchResult.Match
}
| apache-2.0 | e7e398bda3af886e96e07421a61b0ff5 | 57.707317 | 175 | 0.713544 | 4.705767 | false | false | false | false |
leafclick/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ignore/actions/IgnoreFileActionGroup.kt | 1 | 6134 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.ignore.actions
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.VcsRoot
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.actions.ScheduleForAdditionAction
import com.intellij.openapi.vcs.changes.ignore.lang.IgnoreFileType
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.FileTypeIndex
import com.intellij.psi.search.ProjectScope
import com.intellij.vcsUtil.VcsImplUtil
import com.intellij.vcsUtil.VcsUtil
import kotlin.streams.toList
open class IgnoreFileActionGroup(private val ignoreFileType: IgnoreFileType) :
ActionGroup(
message("vcs.add.to.ignore.file.action.group.text", ignoreFileType.ignoreLanguage.filename),
message("vcs.add.to.ignore.file.action.group.description", ignoreFileType.ignoreLanguage.filename),
ignoreFileType.icon
), DumbAware {
private var actions: Collection<AnAction> = emptyList()
override fun update(e: AnActionEvent) {
val selectedFiles = getSelectedFiles(e)
val presentation = e.presentation
val project = e.getData(CommonDataKeys.PROJECT)
if (project == null) {
presentation.isVisible = false
return
}
val unversionedFiles = ScheduleForAdditionAction.getUnversionedFiles(e, project).toList()
if (unversionedFiles.isEmpty()) {
presentation.isVisible = false
return
}
val ignoreFiles =
filterSelectedFiles(project, selectedFiles).map { findSuitableIgnoreFiles(project, it) }.filterNot(Collection<*>::isEmpty)
val resultedIgnoreFiles = ignoreFiles.flatten().toHashSet()
for (files in ignoreFiles) {
resultedIgnoreFiles.retainAll(files) //only take ignore files which is suitable for all selected files
}
val additionalActions = createAdditionalActions(project, selectedFiles, unversionedFiles)
if (resultedIgnoreFiles.isNotEmpty()) {
actions = resultedIgnoreFiles.toActions(project, additionalActions.size)
}
else {
actions = listOfNotNull(createNewIgnoreFileAction(project, selectedFiles))
}
if (additionalActions.isNotEmpty()) {
actions += additionalActions
}
isPopup = actions.size > 1
presentation.isVisible = actions.isNotEmpty()
}
protected open fun createAdditionalActions(project: Project,
selectedFiles: List<VirtualFile>,
unversionedFiles: List<VirtualFile>): List<AnAction> = emptyList()
override fun canBePerformed(context: DataContext) = actions.size == 1
override fun actionPerformed(e: AnActionEvent) {
actions.firstOrNull()?.actionPerformed(e)
}
override fun getChildren(e: AnActionEvent?) = actions.toTypedArray()
private fun filterSelectedFiles(project: Project, files: List<VirtualFile>) =
files.filter { file ->
VcsUtil.isFileUnderVcs(project, VcsUtil.getFilePath(file)) && !ChangeListManager.getInstance(project).isIgnoredFile(file)
}
private fun findSuitableIgnoreFiles(project: Project, file: VirtualFile): Collection<VirtualFile> {
val fileParent = file.parent
return FileTypeIndex.getFiles(ignoreFileType, ProjectScope.getProjectScope(project))
.filter {
fileParent == it.parent || fileParent != null && it.parent != null && VfsUtil.isAncestor(it.parent, fileParent, false)
}
}
private fun Collection<VirtualFile>.toActions(project: Project, additionalActionsSize: Int): Collection<AnAction> {
val projectDir = project.guessProjectDir()
return map { file ->
IgnoreFileAction(file).apply {
templatePresentation.apply {
icon = ignoreFileType.icon
text = file.toTextRepresentation(project, projectDir, [email protected] + additionalActionsSize)
}
}
}
}
private fun createNewIgnoreFileAction(project: Project, selectedFiles: List<VirtualFile>): AnAction? {
val filename = ignoreFileType.ignoreLanguage.filename
val (rootVcs, commonIgnoreFileRoot) = selectedFiles.getCommonIgnoreFileRoot(project) ?: return null
if (rootVcs == null) return null
if (commonIgnoreFileRoot.findChild(filename) != null) return null
val ignoredFileContentProvider = VcsImplUtil.findIgnoredFileContentProvider(rootVcs) ?: return null
if (ignoredFileContentProvider.fileName != filename) return null
return CreateNewIgnoreFileAction(filename, commonIgnoreFileRoot).apply {
templatePresentation.apply {
icon = ignoreFileType.icon
text = message("vcs.add.to.ignore.file.action.group.text", filename)
}
}
}
private fun VirtualFile.toTextRepresentation(project: Project, projectDir: VirtualFile?, size: Int): String {
if (size == 1) return message("vcs.add.to.ignore.file.action.group.text", ignoreFileType.ignoreLanguage.filename)
val projectRootOrVcsRoot = projectDir ?: VcsUtil.getVcsRootFor(project, this) ?: return name
return VfsUtil.getRelativePath(this, projectRootOrVcsRoot) ?: name
}
private fun Collection<VirtualFile>.getCommonIgnoreFileRoot(project: Project): VcsRoot? {
val vcsManager = ProjectLevelVcsManager.getInstance(project)
val first = firstOrNull() ?: return null
val commonVcsRoot = vcsManager.getVcsRootObjectFor(first) ?: return null
if (first == commonVcsRoot.path) return null //trying to ignore vcs root itself
val haveCommonRoot = asSequence().drop(1).all {
it != commonVcsRoot && vcsManager.getVcsRootObjectFor(it) == commonVcsRoot
}
return if (haveCommonRoot) commonVcsRoot else null
}
private operator fun VcsRoot.component1() = vcs
private operator fun VcsRoot.component2() = path
}
| apache-2.0 | 9d96b6661d73cc54536068dc37f69c49 | 41.013699 | 140 | 0.743397 | 4.769829 | false | false | false | false |
Xenoage/Zong | core/src/com/xenoage/zong/core/text/FormattedTextSymbol.kt | 1 | 1802 | package com.xenoage.zong.core.text
import com.xenoage.utils.Pt
import com.xenoage.utils.color.Color
import com.xenoage.utils.font.TextMetrics
import com.xenoage.utils.pxToMm_1_1
import com.xenoage.zong.symbols.Symbol
/**
* Musical [Symbol] within a formatted text.
*/
class FormattedTextSymbol(
val symbol: Symbol,
/** The size of the symbol in pt (relative to the ascent
* height defined in the symbol */
val size: Pt,
val color: Color
) : FormattedTextElement {
override val style: FormattedTextStyle = FormattedTextStyle(color = color)
val scaling: Float
/** The horizontal offset of the symbol, which must be added so that
* the symbol is left-aligned). */
val offsetX: Float
/** Measurements, with only ascent and width set. The other values are 0. */
override val metrics: TextMetrics
init {
//compute scaling
this.scaling = computeScaling(symbol, size)
//compute ascent and width
val ascent = symbol.ascentHeight * this.scaling //TODO: right?
val width = (symbol.rightBorder - symbol.leftBorder) * this.scaling
this.metrics = TextMetrics(ascent, 0f, 0f, width)
//horizontal offset: align symbol to the left side
this.offsetX = -symbol.leftBorder * this.scaling
}
override val length: Int
get() = 1
/** Returns the Unicode Object Replacement character, `\ufffc`. */
override val text: String
get() = "\ufffc"
override fun toString(): String =
"[symbol ${symbol.id}]"
companion object {
/**
* Computes and returns the scaling factor that is needed to draw
* the given symbol fitting to the given font size.
*/
private fun computeScaling(symbol: Symbol, size: Pt): Float =
//TODO: 0.65f is a constant that defines that the ascent has 65% of the complete hight
size * pxToMm_1_1 / symbol.ascentHeight * 0.65f
}
}
| agpl-3.0 | 1c0d3b3d443e6f512fcd2fd0578e831e | 28.064516 | 89 | 0.716426 | 3.547244 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-api/src/main/kotlin/org/nd4j/samediff/frameworkimport/rule/attribute/SizeThresholdIntArrayIntIndexRule.kt | 1 | 3755 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.rule.attribute
import org.nd4j.ir.OpNamespace
import org.nd4j.samediff.frameworkimport.context.MappingContext
import org.nd4j.samediff.frameworkimport.lookupIndexForArgDescriptor
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
abstract class SizeThresholdIntArrayIntIndexRule<
GRAPH_DEF: GeneratedMessageV3,
OP_DEF_TYPE: GeneratedMessageV3,
NODE_TYPE: GeneratedMessageV3,
ATTR_DEF : GeneratedMessageV3,
ATTR_VALUE_TYPE : GeneratedMessageV3,
TENSOR_TYPE : GeneratedMessageV3, DATA_TYPE>(mappingNamesToPerform: Map<String, String>,
transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>>):
BaseAttributeExtractionRule<GRAPH_DEF, OP_DEF_TYPE, NODE_TYPE, ATTR_DEF, ATTR_VALUE_TYPE, TENSOR_TYPE, DATA_TYPE>
(name = "sizethresholdarrayint", mappingNamesToPerform = mappingNamesToPerform, transformerArgs = transformerArgs) where DATA_TYPE: ProtocolMessageEnum {
override fun convertAttributes(mappingCtx: MappingContext<GRAPH_DEF, NODE_TYPE, OP_DEF_TYPE, TENSOR_TYPE, ATTR_DEF, ATTR_VALUE_TYPE, DATA_TYPE>): List<OpNamespace.ArgDescriptor> {
val ret = ArrayList<OpNamespace.ArgDescriptor>()
for((k, v) in mappingNamesToPerform()) {
val descriptorForName = transformerArgs[k]
val inputArr = mappingCtx.irAttributeValueForNode(v).listIntValue()
val index = descriptorForName!![0].int32Value
val sizeThreshold = descriptorForName!![1].int64Value
val fallbackIndex = descriptorForName!![2].stringValue
val descriptorBuilder = OpNamespace.ArgDescriptor.newBuilder()
descriptorBuilder.name = v
descriptorBuilder.argType = OpNamespace.ArgDescriptor.ArgType.INT64
if(inputArr.size < sizeThreshold) {
descriptorBuilder.int64Value = inputArr[fallbackIndex.toInt()]
} else {
descriptorBuilder.int64Value = inputArr[index]
}
descriptorBuilder.argIndex = lookupIndexForArgDescriptor(
argDescriptorName = k,
opDescriptorName = mappingCtx.nd4jOpName(),
argDescriptorType = OpNamespace.ArgDescriptor.ArgType.INT64
)
ret.add(descriptorBuilder.build())
}
return ret
}
override fun acceptsInputType(argDescriptorType: AttributeValueType): Boolean {
return argDescriptorType == AttributeValueType.INT ||
argDescriptorType == AttributeValueType.STRING
}
override fun outputsType(argDescriptorType: List<OpNamespace.ArgDescriptor.ArgType>): Boolean {
return argDescriptorType.contains(OpNamespace.ArgDescriptor.ArgType.INT64)
}
} | apache-2.0 | 8e4e458fef9754dbc07597ab9453ca66 | 45.95 | 183 | 0.668975 | 4.908497 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/buildSystem/BuildSystemPlugin.kt | 1 | 10267 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem
import kotlinx.collections.immutable.toImmutableList
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.PipelineTask
import org.jetbrains.kotlin.tools.projectWizard.core.entity.properties.Property
import org.jetbrains.kotlin.tools.projectWizard.core.entity.ValidationResult
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSetting
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingDefaultValue
import org.jetbrains.kotlin.tools.projectWizard.core.service.BuildSystemAvailabilityWizardService
import org.jetbrains.kotlin.tools.projectWizard.core.service.FileSystemWizardService
import org.jetbrains.kotlin.tools.projectWizard.core.service.ProjectImportingWizardService
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.*
import org.jetbrains.kotlin.tools.projectWizard.library.MavenArtifact
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.KotlinPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ProjectKind
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.BuildFilePrinter
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.printBuildFile
import org.jetbrains.kotlin.tools.projectWizard.plugins.projectPath
import org.jetbrains.kotlin.tools.projectWizard.plugins.templates.TemplatesPlugin
import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.DefaultRepository
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Repository
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.updateBuildFiles
abstract class BuildSystemPlugin(context: Context) : Plugin(context) {
override val path = pluginPath
companion object : PluginSettingsOwner() {
override val pluginPath = "buildSystem"
val type by enumSetting<BuildSystemType>(
KotlinNewProjectWizardBundle.message("plugin.buildsystem.setting.type"),
GenerationPhase.FIRST_STEP,
) {
fun Reader.isBuildSystemAvailable(type: BuildSystemType): Boolean =
service<BuildSystemAvailabilityWizardService>().isAvailable(type)
isSavable = true
values = BuildSystemType.ALL_BY_PRIORITY.toImmutableList()
defaultValue = SettingDefaultValue.Dynamic {
values.firstOrNull { isBuildSystemAvailable(it) }
}
filter = { _, type -> isBuildSystemAvailable(type) }
validate { buildSystemType ->
val projectKind = KotlinPlugin.projectKind.notRequiredSettingValue ?: ProjectKind.Multiplatform
if (buildSystemType in projectKind.supportedBuildSystems && isBuildSystemAvailable(buildSystemType)) {
ValidationResult.OK
} else {
ValidationResult.ValidationError(
KotlinNewProjectWizardBundle.message(
"plugin.buildsystem.setting.type.error.wrong.project.kind",
projectKind.shortName.capitalize(),
buildSystemType.fullText
)
)
}
}
tooltipText = KotlinNewProjectWizardBundle.message("plugin.buildsystem.setting.type.tooltip")
}
val buildSystemData by property<List<BuildSystemData>>(emptyList())
val buildFiles by listProperty<BuildFileIR>()
val pluginRepositoreis by listProperty<Repository>()
val takeRepositoriesFromDependencies by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runBefore(createModules)
runAfter(TemplatesPlugin.postApplyTemplatesToModules)
withAction {
updateBuildFiles { buildFile ->
val dependenciesOfModule = buildList<LibraryDependencyIR> {
buildFile.modules.modules.forEach { module ->
if (module is SingleplatformModuleIR) module.sourcesets.forEach { sourceset ->
+sourceset.irs.filterIsInstance<LibraryDependencyIR>()
}
+module.irs.filterIsInstance<LibraryDependencyIR>()
}
}
val repositoriesToAdd = dependenciesOfModule.mapNotNull { dependency ->
dependency.artifact.safeAs<MavenArtifact>()?.repository?.let(::RepositoryIR)
}
buildFile.withIrs(repositoriesToAdd).asSuccess()
}
}
}
val createModules by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runAfter(StructurePlugin.createProjectDir)
withAction {
val fileSystem = service<FileSystemWizardService>()
val data = buildSystemData.propertyValue.first { it.type == buildSystemType }
val buildFileData = data.buildFileData ?: return@withAction UNIT_SUCCESS
buildFiles.propertyValue.mapSequenceIgnore { buildFile ->
fileSystem.createFile(
buildFile.directoryPath / buildFileData.buildFileName,
buildFileData.createPrinter().printBuildFile { buildFile.render(this) }
)
}
}
}
val importProject by pipelineTask(GenerationPhase.PROJECT_IMPORT) {
runAfter(createModules)
withAction {
val data = buildSystemData.propertyValue.first { it.type == buildSystemType }
service<ProjectImportingWizardService> { service -> service.isSuitableFor(data.type) }
.importProject(this, StructurePlugin.projectPath.settingValue, allIRModules, buildSystemType)
}
}
}
override val settings: List<PluginSetting<*, *>> = listOf(
type,
)
override val pipelineTasks: List<PipelineTask> = listOf(
takeRepositoriesFromDependencies,
createModules,
importProject,
)
override val properties: List<Property<*>> = listOf(
buildSystemData,
buildFiles,
pluginRepositoreis
)
}
fun Reader.getPluginRepositoriesWithDefaultOnes(): List<Repository> {
val allRepositories = BuildSystemPlugin.pluginRepositoreis.propertyValue + buildSystemType.getDefaultPluginRepositories()
return allRepositories.filterOutOnlyDefaultPluginRepositories(buildSystemType)
}
private fun List<Repository>.filterOutOnlyDefaultPluginRepositories(buildSystem: BuildSystemType): List<Repository> {
val isAllDefault = all { it.isDefaultPluginRepository(buildSystem) }
return if (isAllDefault) emptyList() else this
}
private fun Repository.isDefaultPluginRepository(buildSystem: BuildSystemType) =
this in buildSystem.getDefaultPluginRepositories()
fun PluginSettingsOwner.addBuildSystemData(data: BuildSystemData) = pipelineTask(GenerationPhase.PREPARE) {
runBefore(BuildSystemPlugin.createModules)
withAction {
BuildSystemPlugin.buildSystemData.addValues(data)
}
}
data class BuildSystemData(
val type: BuildSystemType,
val buildFileData: BuildFileData?
)
data class BuildFileData(
val createPrinter: () -> BuildFilePrinter,
@NonNls val buildFileName: String
)
enum class BuildSystemType(
@Nls override val text: String,
@NonNls val id: String, // used for FUS, should never be changed
val fullText: String = text
) : DisplayableSettingItem {
GradleKotlinDsl(
text = KotlinNewProjectWizardBundle.message("buildsystem.type.gradle.kotlin"),
id = "gradleKotlin"
),
GradleGroovyDsl(
text = KotlinNewProjectWizardBundle.message("buildsystem.type.gradle.groovy"),
id = "gradleGroovy"
),
Jps(
text = KotlinNewProjectWizardBundle.message("buildsystem.type.intellij"),
id = "jps",
fullText = KotlinNewProjectWizardBundle.message("buildsystem.type.intellij.full")
),
Maven(
text = KotlinNewProjectWizardBundle.message("buildsystem.type.maven"),
id = "maven"
);
override val greyText: String?
get() = null
companion object {
val ALL_GRADLE = setOf(GradleKotlinDsl, GradleGroovyDsl)
val ALL_BY_PRIORITY = setOf(GradleKotlinDsl, GradleGroovyDsl, Maven, Jps)
}
}
val BuildSystemType.isGradle
get() = this == BuildSystemType.GradleGroovyDsl
|| this == BuildSystemType.GradleKotlinDsl
val Reader.allIRModules
get() = BuildSystemPlugin.buildFiles.propertyValue.flatMap { buildFile ->
buildFile.modules.modules
}
val Writer.allModulesPaths
get() = BuildSystemPlugin.buildFiles.propertyValue.flatMap { buildFile ->
val paths = when (val structure = buildFile.modules) {
is MultiplatformModulesStructureIR -> listOf(buildFile.directoryPath)
else -> structure.modules.map { it.path }
}
paths.mapNotNull { path ->
projectPath.relativize(path)
.takeIf { it.toString().isNotBlank() }
?.toList()
?.takeIf { it.isNotEmpty() }
}
}
fun BuildSystemType.getDefaultPluginRepositories(): List<DefaultRepository> = when (this) {
BuildSystemType.GradleKotlinDsl, BuildSystemType.GradleGroovyDsl -> listOf(DefaultRepository.GRADLE_PLUGIN_PORTAL)
BuildSystemType.Maven -> listOf(DefaultRepository.MAVEN_CENTRAL)
BuildSystemType.Jps -> emptyList()
}
val Reader.buildSystemType: BuildSystemType
get() = BuildSystemPlugin.type.settingValue
| apache-2.0 | c96b6db81faccde82b9fef56eb254fa7 | 42.876068 | 158 | 0.695627 | 5.493312 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/formatter/CommentInFunctionLiteral.kt | 13 | 784 | fun test(some: (Int) -> Int) {
}
fun foo() {
test() {
// Some comment
it
}
test() {
// val a = 42
}
test() {
/*
val a = 42
*/
}
test() {
/*
val a = 42
*/
}
test() {
// val a = 42
val b = 44
}
}
val s = Shadow { -> // wdwd
val a = 42
}
val s2 = Shadow { // wdwd
val a = 42
}
val s3 = Shadow(fun() { // wdwd
val a = 42
})
val s4 = Shadow(fun() { /* s */
val a = 42
})
val s5 = Shadow { ->
// wdwd
val a = 42
}
val s6 = Shadow {
// wdwd
val a = 42
}
val s7 = Shadow(fun() {
// wdwd
val a = 42
})
val s8 = Shadow(fun() {
// wdwd
val a = 42
})
val s9 = Shadow { -> /* s */
val a = 42
}
class Shadow(callback: () -> Unit)
| apache-2.0 | 806256e5e40b7e8e22a53b672f5557f4 | 9.888889 | 34 | 0.38648 | 2.780142 | false | true | false | false |
smmribeiro/intellij-community | plugins/gradle/java/src/execution/test/runner/AbstractGradleTestRunConfigurationProducer.kt | 7 | 7680 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.execution.test.runner
import com.intellij.execution.JavaRunConfigurationExtensionManager
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.ConfigurationFromContext
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.plugins.gradle.execution.test.runner.TestTasksChooser.Companion.contextWithLocationName
import org.jetbrains.plugins.gradle.service.execution.GradleRunConfiguration
import org.jetbrains.plugins.gradle.util.GradleCommandLine.Companion.parse
import org.jetbrains.plugins.gradle.util.GradleCommandLine.TasksAndArguments
import org.jetbrains.plugins.gradle.util.TasksToRun
import org.jetbrains.plugins.gradle.util.createTestWildcardFilter
import java.util.*
import java.util.function.Consumer
abstract class AbstractGradleTestRunConfigurationProducer<E : PsiElement, Ex : PsiElement> : GradleTestRunConfigurationProducer() {
protected abstract fun getElement(context: ConfigurationContext): E?
protected abstract fun getLocationName(context: ConfigurationContext, element: E): String
protected abstract fun suggestConfigurationName(context: ConfigurationContext, element: E, chosenElements: List<Ex>): String
protected abstract fun chooseSourceElements(context: ConfigurationContext, element: E, onElementsChosen: Consumer<List<Ex>>)
private fun chooseSourceElements(context: ConfigurationContext, element: E, onElementsChosen: (List<Ex>) -> Unit) {
chooseSourceElements(context, element, Consumer { onElementsChosen(it) })
}
protected abstract fun getAllTestsTaskToRun(context: ConfigurationContext, element: E, chosenElements: List<Ex>): List<TestTasksToRun>
private fun getAllTasksAndArguments(context: ConfigurationContext, element: E, chosenElements: List<Ex>): List<TasksAndArguments> {
return getAllTestsTaskToRun(context, element, chosenElements)
.map { it.toTasksAndArguments() }
}
override fun doSetupConfigurationFromContext(
configuration: GradleRunConfiguration,
context: ConfigurationContext,
sourceElement: Ref<PsiElement>
): Boolean {
val project = context.project ?: return false
val module = context.module ?: return false
val externalProjectPath = resolveProjectPath(module) ?: return false
val location = context.location ?: return false
val element = getElement(context) ?: return false
val allTasksAndArguments = getAllTasksAndArguments(context, element, emptyList())
val tasksAndArguments = allTasksAndArguments.firstOrNull() ?: return false
sourceElement.set(element)
configuration.name = suggestConfigurationName(context, element, emptyList())
setUniqueNameIfNeeded(project, configuration)
configuration.settings.externalProjectPath = externalProjectPath
configuration.settings.taskNames = tasksAndArguments.toList()
configuration.settings.scriptParameters = ""
JavaRunConfigurationExtensionManager.instance.extendCreatedConfiguration(configuration, location)
return true
}
override fun doIsConfigurationFromContext(
configuration: GradleRunConfiguration,
context: ConfigurationContext
): Boolean {
val module = context.module ?: return false
val externalProjectPath = resolveProjectPath(module) ?: return false
val element = getElement(context) ?: return false
val allTasksAndArguments = getAllTasksAndArguments(context, element, emptyList())
val tasksAndArguments = configuration.commandLine.tasksAndArguments.toList()
return externalProjectPath == configuration.settings.externalProjectPath &&
tasksAndArguments.isNotEmpty() && allTasksAndArguments.isNotEmpty() &&
isConsistedFrom(tasksAndArguments, allTasksAndArguments.map { it.toList() })
}
override fun onFirstRun(configuration: ConfigurationFromContext, context: ConfigurationContext, startRunnable: Runnable) {
val project = context.project
val element = getElement(context)
if (project == null || element == null) {
LOG.warn("Cannot extract configuration data from context, uses raw run configuration")
super.onFirstRun(configuration, context, startRunnable)
return
}
val runConfiguration = configuration.configuration as GradleRunConfiguration
val dataContext = contextWithLocationName(context.dataContext, getLocationName(context, element))
chooseSourceElements(context, element) { elements ->
val allTestsToRun = getAllTestsTaskToRun(context, element, elements)
.groupBy { it.tasksToRun.testName }
.mapValues { it.value }
testTasksChooser.chooseTestTasks(project, dataContext, allTestsToRun) { chosenTestsToRun ->
val chosenTasksAndArguments = chosenTestsToRun.flatten()
.groupBy { it.tasksToRun }
.mapValues { it.value.map(TestTasksToRun::testFilter).toSet() }
.map { createTasksAndArguments(it.key, it.value) }
runConfiguration.name = suggestConfigurationName(context, element, elements)
setUniqueNameIfNeeded(project, runConfiguration)
runConfiguration.settings.taskNames = chosenTasksAndArguments.flatMap { it.toList() }
runConfiguration.settings.scriptParameters = if (chosenTasksAndArguments.size > 1) "--continue" else ""
super.onFirstRun(configuration, context, startRunnable)
}
}
}
/**
* Checks that [list] can be represented by sequence from all or part of [subLists].
*
* For example:
*
* `[1, 2, 3, 4] is not consisted from [1, 2]`
*
* `[1, 2, 3, 4] is consisted from [1, 2] and [3, 4]`
*
* `[1, 2, 3, 4] is consisted from [1, 2], [3, 4] and [1, 2, 3]`
*
* `[1, 2, 3, 4] is not consisted from [1, 2, 3] and [3, 4]`
*/
private fun isConsistedFrom(list: List<String>, subLists: List<List<String>>): Boolean {
val reducer = ArrayList(list)
val sortedTiles = subLists.sortedByDescending { it.size }
for (tile in sortedTiles) {
val size = tile.size
val index = indexOfSubList(reducer, tile)
if (index >= 0) {
val subReducer = reducer.subList(index, index + size)
subReducer.clear()
subReducer.add(null)
}
}
return ContainerUtil.and(reducer) { it == null }
}
private fun indexOfSubList(list: List<String>, subList: List<String>): Int {
for (i in list.indices) {
if (i + subList.size <= list.size) {
var hasSubList = true
for (j in subList.indices) {
if (list[i + j] != subList[j]) {
hasSubList = false
break
}
}
if (hasSubList) {
return i
}
}
}
return -1
}
private fun createTasksAndArguments(tasksToRun: TasksToRun, testFilters: Collection<String>): TasksAndArguments {
val commandLineBuilder = StringJoiner(" ")
for (task in tasksToRun) {
commandLineBuilder.add(task.escapeIfNeeded())
}
if (createTestWildcardFilter() !in testFilters) {
for (testFilter in testFilters) {
if (StringUtil.isNotEmpty(testFilter)) {
commandLineBuilder.add(testFilter)
}
}
}
val commandLine = commandLineBuilder.toString()
return parse(commandLine).tasksAndArguments
}
fun TestTasksToRun.toTasksAndArguments() = createTasksAndArguments(tasksToRun, listOf(testFilter))
class TestTasksToRun(val tasksToRun: TasksToRun, val testFilter: String)
} | apache-2.0 | a1927a3b817020a84438ff817808077c | 43.143678 | 158 | 0.734115 | 4.791017 | false | true | false | false |
jguerinet/Suitcase | dialog/src/main/java/ContextExt.kt | 2 | 4904 | /*
* Copyright 2016-2019 Julien Guerinet
*
* 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.guerinet.suitcase.dialog
import android.content.Context
import androidx.annotation.StringRes
import com.afollestad.materialdialogs.DialogCallback
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.list.listItems
import com.afollestad.materialdialogs.list.listItemsMultiChoice
import com.afollestad.materialdialogs.list.listItemsSingleChoice
/**
* Context extensions relating to dialogs
* @author Julien Guerinet
* @since 2.5.0
*/
/* DIALOGS */
/**
* Displays and returns a dialog with a [title] and a [message]. Takes an [init] block to add any other buttons
*/
fun Context.showDialog(
@StringRes title: Int = 0,
@StringRes message: Int = 0,
init: (MaterialDialog.() -> Unit)? = null
) = MaterialDialog(this).show {
build(title, message)
init?.invoke(this)
}
/**
* Displays and returns a dialog with a [title] and a [message]. Takes an [init] block to add any other buttons
*/
fun Context.showDialog(
@StringRes title: Int = 0,
message: String? = null,
init: (MaterialDialog.() -> Unit)? = null
) = MaterialDialog(this).show {
build(title, message)
init?.invoke(this)
}
/* NEUTRAL */
/**
* Displays and returns a dialog with one button. This dialog can have a [title], a [message],
* a [button] text (defaults to the Android OK), and a button [listener].
*/
fun Context.neutralDialog(
@StringRes title: Int = 0,
@StringRes message: Int = 0,
@StringRes button: Int = android.R.string.ok,
listener: DialogCallback? = null
) = showDialog(title, message) {
positiveButton(button, click = listener)
}
/**
* Displays and returns a dialog with one button. This dialog can have a [title], a [message],
* a [button] text (defaults to the Android OK), and a button [listener]
*/
fun Context.neutralDialog(
@StringRes title: Int = 0,
message: String? = null,
@StringRes button: Int = android.R.string.ok,
listener: DialogCallback? = null
) = showDialog(title, message) {
positiveButton(button, click = listener)
}
/* LISTS DIALOGS */
/**
* Displays and returns a dialog with a single choice list of [choices] to choose from.
* Dialog may have a [title] and may show radio buttons depending on [showRadioButtons].
* A [currentChoice] can be given (-1 if none, defaults to -1). When a choice is selected,
* [onChoiceSelected] is called
*/
fun Context.singleListDialog(
choices: List<String>,
@StringRes title: Int = -1,
currentChoice: Int = -1,
showRadioButtons: Boolean = true,
onChoiceSelected: (position: Int) -> Unit
) = MaterialDialog(this).show {
build(title)
if (showRadioButtons) {
listItemsSingleChoice(items = choices, initialSelection = currentChoice) { _, index, _ ->
onChoiceSelected(index)
}
} else {
listItems(items = choices) { _, index, _ ->
onChoiceSelected(index)
}
}
}
/**
* Displays and returns a dialog with a multiple choice list of [choices] to choose from.
* Dialog may have a [title] and has one [button] (text defaults to the Android OK). A list of
* [selectedItems] can be given (defaults to an empty list). When the user has clicked on the
* button, [onChoicesSelected] is called with the list of selected choices.
*/
fun Context.multiListDialog(
choices: List<String>,
@StringRes title: Int = -1,
@StringRes button: Int = android.R.string.ok,
selectedItems: IntArray = intArrayOf(),
onChoicesSelected: (positions: IntArray) -> Unit
) = MaterialDialog(this).show {
build(title)
listItemsMultiChoice(items = choices, initialSelection = selectedItems) { _, indices, _ ->
onChoicesSelected(indices)
}
positiveButton(button)
}
/**
* Begins the construction of a [MaterialDialog] with an optional [title] and [message]
*/
private fun MaterialDialog.build(
@StringRes title: Int,
@StringRes message: Int = 0
) {
if (title != 0) {
title(title)
}
if (message != 0) {
message(message)
}
}
/**
* Begins the construction of a [MaterialDialog] with an optional [title] and [message]
*/
private fun MaterialDialog.build(
@StringRes title: Int,
message: String?
) {
build(title)
message?.let { message(text = message) }
}
| apache-2.0 | ec061f7735969f6dbf5709f0152eb226 | 29.65 | 111 | 0.68699 | 3.910686 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/demo2_0_0/OBJECT_LAYOUT.kt | 2 | 21531 | /*
* 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 OBJECT_LAYOUT: Response(){
override val url = "http://localhost:8080/restful/objects/demo.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/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.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==",
"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.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/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.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/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.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/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.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/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.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/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,
"fieldSet": [
{
"name": "Editable",
"property": [
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/property",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/properties/string",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\""
},
"id": "string",
"cssClass": null,
"hidden": null,
"labelPosition": null,
"multiLine": null,
"namedEscaped": null,
"promptStyle": null,
"renderDay": null,
"typicalLength": null,
"repainting": null,
"unchanging": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/property",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/properties/stringMultiline",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\""
},
"id": "stringMultiline",
"cssClass": null,
"hidden": null,
"labelPosition": null,
"multiLine": null,
"namedEscaped": null,
"promptStyle": null,
"renderDay": null,
"typicalLength": null,
"repainting": null,
"unchanging": null
}
],
"metadataError": null,
"id": "editable",
"unreferencedActions": null,
"unreferencedProperties": null
},
{
"name": "Readonly",
"property": [
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/property",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/properties/stringReadonly",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\""
},
"id": "stringReadonly",
"cssClass": null,
"hidden": null,
"labelPosition": null,
"multiLine": null,
"namedEscaped": null,
"promptStyle": null,
"renderDay": null,
"typicalLength": null,
"repainting": null,
"unchanging": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/property",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/properties/stringMultilineReadonly",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\""
},
"id": "stringMultilineReadonly",
"cssClass": null,
"hidden": null,
"labelPosition": null,
"multiLine": null,
"namedEscaped": null,
"promptStyle": null,
"renderDay": null,
"typicalLength": null,
"repainting": null,
"unchanging": null
}
],
"metadataError": null,
"id": "readonly",
"unreferencedActions": null,
"unreferencedProperties": true
}
],
"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.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/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": "More than one column with 'unreferencedProperties' attribute set",
"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 | fa33076b033e530a342eae3fa919a7c8 | 61.228324 | 410 | 0.407552 | 6.538415 | false | false | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/EmptyUpdatableIndex.kt | 1 | 2392 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.indexing
import com.intellij.openapi.util.Computable
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.Processor
import com.intellij.util.indexing.impl.AbstractUpdateData
import com.intellij.util.indexing.snapshot.EmptyValueContainer
import java.lang.UnsupportedOperationException
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReadWriteLock
import java.util.concurrent.locks.ReentrantReadWriteLock
class EmptyUpdatableIndex<Key, Value, Input> : UpdatableIndex<Key, Value, Input> {
private var lock = ReentrantReadWriteLock()
@Throws(StorageException::class)
override fun processAllKeys(processor: Processor<in Key>,
scope: GlobalSearchScope,
idFilter: IdFilter?): Boolean {
return false
}
override fun getLock(): ReadWriteLock = lock
@Throws(StorageException::class)
override fun getIndexedFileData(fileId: Int): Map<Key, Value> = emptyMap()
override fun setIndexedStateForFile(fileId: Int, file: IndexedFile) = Unit
override fun resetIndexedStateForFile(fileId: Int) {}
override fun isIndexedStateForFile(fileId: Int, file: IndexedFile): Boolean = false
override fun getModificationStamp(): Long = 0
override fun removeTransientDataForFile(inputId: Int) = Unit
override fun removeTransientDataForKeys(inputId: Int, keys: Collection<Key>) = Unit
override fun getExtension(): IndexExtension<Key, Value, Input> = throw UnsupportedOperationException()
@Throws(StorageException::class)
override fun updateWithMap(updateData: AbstractUpdateData<Key, Value>) = Unit
override fun setBufferingEnabled(enabled: Boolean) = Unit
override fun cleanupMemoryStorage() = Unit
override fun cleanupForNextTest() = Unit
@Throws(StorageException::class)
override fun getData(key: Key): ValueContainer<Value> {
@Suppress("UNCHECKED_CAST")
return EmptyValueContainer as ValueContainer<Value>
}
override fun update(inputId: Int, content: Input?): Computable<Boolean> = throw UnsupportedOperationException()
@Throws(StorageException::class)
override fun flush() {
}
@Throws(StorageException::class)
override fun clear() {
}
override fun dispose() {}
} | apache-2.0 | 879258c8aec1178ffb70686f3921300d | 37.596774 | 140 | 0.76296 | 4.582375 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/classLiteralAndTypeArgsRuntime.kt | 4 | 390 | // "Replace usages of 'myJavaClass(): Class<T>' in whole project" "true"
// WITH_RUNTIME
@Deprecated("", ReplaceWith("T::class.java"))
inline fun <reified T: Any> myJavaClass(): Class<T> = T::class.java
fun foo() {
val v1 = <caret>myJavaClass<List<*>>()
val v2 = myJavaClass<List<String>>()
val v3 = myJavaClass<Array<String>>()
val v4 = myJavaClass<java.util.Random>()
}
| apache-2.0 | d68b19d543afe5ffb4f9784c1cad8ce3 | 31.5 | 72 | 0.648718 | 3.25 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/injection/src/org/jetbrains/kotlin/idea/injection/KotlinLanguageInjectionSupport.kt | 1 | 10390 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.injection
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.lang.Language
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiTreeUtil.getDeepestLast
import com.intellij.util.Consumer
import com.intellij.util.Processor
import org.intellij.plugins.intelliLang.Configuration
import org.intellij.plugins.intelliLang.inject.*
import org.intellij.plugins.intelliLang.inject.config.BaseInjection
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.patterns.KotlinPatterns
import org.jetbrains.kotlin.idea.util.addAnnotation
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.findAnnotation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.psi.psiUtil.startOffset
@NonNls
val KOTLIN_SUPPORT_ID = "kotlin"
class KotlinLanguageInjectionSupport : AbstractLanguageInjectionSupport() {
override fun getId(): String = KOTLIN_SUPPORT_ID
override fun createAddActions(project: Project?, consumer: Consumer<in BaseInjection>?): Array<AnAction> {
return super.createAddActions(project, consumer).apply {
forEach {
it.templatePresentation.icon = KotlinFileType.INSTANCE.icon
}
}
}
override fun getPatternClasses() = arrayOf(KotlinPatterns::class.java)
override fun isApplicableTo(host: PsiLanguageInjectionHost?) = host is KtElement
override fun useDefaultInjector(host: PsiLanguageInjectionHost?): Boolean = false
override fun addInjectionInPlace(language: Language?, host: PsiLanguageInjectionHost?): Boolean {
if (language == null || host == null) return false
val configuration = Configuration.getProjectInstance(host.project).advancedConfiguration
if (!configuration.isSourceModificationAllowed) {
// It's not allowed to modify code without explicit permission. Postpone adding @Inject or comment till it granted.
host.putUserData(InjectLanguageAction.FIX_KEY, Processor { fixHost: PsiLanguageInjectionHost? ->
fixHost != null && addInjectionInstructionInCode(language, fixHost)
})
return false
}
if (!addInjectionInstructionInCode(language, host)) {
return false
}
TemporaryPlacesRegistry.getInstance(host.project).addHostWithUndo(host, InjectedLanguage.create(language.id))
return true
}
override fun removeInjectionInPlace(psiElement: PsiLanguageInjectionHost?): Boolean {
if (psiElement == null || psiElement !is KtElement) return false
val project = psiElement.getProject()
val injectInstructions = listOfNotNull(
findAnnotationInjection(psiElement),
findInjectionComment(psiElement)
)
TemporaryPlacesRegistry.getInstance(project).removeHostWithUndo(project, psiElement)
project.executeWriteCommand(KotlinJvmBundle.message("command.action.remove.injection.in.code.instructions")) {
injectInstructions.forEach(PsiElement::delete)
}
return true
}
override fun findCommentInjection(host: PsiElement, commentRef: Ref<in PsiElement>?): BaseInjection? {
// Do not inject through CommentLanguageInjector, because it injects as simple injection.
// We need to behave special for interpolated strings.
return null
}
fun findCommentInjection(host: KtElement): BaseInjection? {
return InjectorUtils.findCommentInjection(host, "", null)
}
private fun findInjectionComment(host: KtElement): PsiComment? {
val commentRef = Ref.create<PsiElement>(null)
InjectorUtils.findCommentInjection(host, "", commentRef) ?: return null
return commentRef.get() as? PsiComment
}
internal fun findAnnotationInjectionLanguageId(host: KtElement): InjectionInfo? {
val annotationEntry = findAnnotationInjection(host) ?: return null
val extractLanguageFromInjectAnnotation = extractLanguageFromInjectAnnotation(annotationEntry) ?: return null
val prefix = extractStringArgumentByName(annotationEntry, "prefix")
val suffix = extractStringArgumentByName(annotationEntry, "suffix")
return InjectionInfo(extractLanguageFromInjectAnnotation, prefix, suffix)
}
}
private fun extractStringArgumentByName(annotationEntry: KtAnnotationEntry, name: String): String? {
val namedArgument: ValueArgument =
annotationEntry.valueArguments.firstOrNull { it.getArgumentName()?.asName?.asString() == name } ?: return null
return extractStringValue(namedArgument)
}
private fun extractLanguageFromInjectAnnotation(annotationEntry: KtAnnotationEntry): String? {
val firstArgument: ValueArgument = annotationEntry.valueArguments.firstOrNull() ?: return null
return extractStringValue(firstArgument)
}
private fun extractStringValue(valueArgument: ValueArgument): String? {
val firstStringArgument = valueArgument.getArgumentExpression() as? KtStringTemplateExpression ?: return null
val firstStringEntry = firstStringArgument.entries.singleOrNull() ?: return null
return firstStringEntry.text
}
private fun findAnnotationInjection(host: KtElement): KtAnnotationEntry? {
val modifierListOwner = findElementToInjectWithAnnotation(host) ?: return null
val modifierList = modifierListOwner.modifierList ?: return null
// Host can't be before annotation
if (host.startOffset < modifierList.endOffset) return null
return modifierListOwner.findAnnotation(FqName(AnnotationUtil.LANGUAGE))
}
private fun canInjectWithAnnotation(host: PsiElement): Boolean {
val module = ModuleUtilCore.findModuleForPsiElement(host) ?: return false
val javaPsiFacade = JavaPsiFacade.getInstance(module.project)
return javaPsiFacade.findClass(AnnotationUtil.LANGUAGE, GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module)) != null
}
private fun findElementToInjectWithAnnotation(host: KtElement): KtModifierListOwner? = PsiTreeUtil.getParentOfType(
host,
KtModifierListOwner::class.java,
false, /* strict */
KtBlockExpression::class.java, KtParameterList::class.java, KtTypeParameterList::class.java /* Stop at */
)
private fun findElementToInjectWithComment(host: KtElement): KtExpression? {
val parentBlockExpression = PsiTreeUtil.getParentOfType(
host,
KtBlockExpression::class.java,
true, /* strict */
KtDeclaration::class.java /* Stop at */
) ?: return null
return parentBlockExpression.statements.firstOrNull { statement ->
PsiTreeUtil.isAncestor(statement, host, false) && checkIsValidPlaceForInjectionWithLineComment(statement, host)
}
}
private fun addInjectionInstructionInCode(language: Language, host: PsiLanguageInjectionHost): Boolean {
val ktHost = host as? KtElement ?: return false
val project = ktHost.project
// Find the place where injection can be stated with annotation or comment
val modifierListOwner = findElementToInjectWithAnnotation(ktHost)
if (modifierListOwner != null && canInjectWithAnnotation(ktHost)) {
project.executeWriteCommand(KotlinJvmBundle.message("command.action.add.injection.annotation")) {
modifierListOwner.addAnnotation(FqName(AnnotationUtil.LANGUAGE), "\"${language.id}\"")
}
return true
}
// Find the place where injection can be done with one-line comment
val commentBeforeAnchor: PsiElement =
modifierListOwner?.firstNonCommentChild() ?: findElementToInjectWithComment(ktHost) ?: return false
val psiFactory = KtPsiFactory(project)
val injectComment = psiFactory.createComment("//language=" + language.id)
project.executeWriteCommand(KotlinJvmBundle.message("command.action.add.injection.comment")) {
commentBeforeAnchor.parent.addBefore(injectComment, commentBeforeAnchor)
}
return true
}
// Inspired with InjectorUtils.findCommentInjection()
private fun checkIsValidPlaceForInjectionWithLineComment(statement: KtExpression, host: KtElement): Boolean {
// make sure comment is close enough and ...
val statementStartOffset = statement.startOffset
val hostStart = host.startOffset
if (hostStart < statementStartOffset || hostStart - statementStartOffset > 120) {
return false
}
if (hostStart - statementStartOffset > 2) {
// ... there's no non-empty valid host in between comment and e2
if (prevWalker(host, statement).asSequence().takeWhile { it != null }.any {
it is PsiLanguageInjectionHost && it.isValidHost && !StringUtil.isEmptyOrSpaces(it.text)
}
) return false
}
return true
}
private fun PsiElement.firstNonCommentChild(): PsiElement? =
firstChild.siblings().dropWhile { it is PsiComment || it is PsiWhiteSpace }.firstOrNull()
// Based on InjectorUtils.prevWalker
private fun prevWalker(element: PsiElement, scope: PsiElement): Iterator<PsiElement?> {
return object : Iterator<PsiElement?> {
private var e: PsiElement? = element
override fun hasNext(): Boolean = true
override fun next(): PsiElement? {
val current = e
if (current == null || current === scope) return null
val prev = current.prevSibling
e = if (prev != null) {
getDeepestLast(prev)
} else {
val parent = current.parent
if (parent === scope || parent is PsiFile) null else parent
}
return e
}
}
}
| apache-2.0 | bdbc5e3ccb52da5a0e456c27853d4314 | 40.726908 | 158 | 0.737247 | 5.35567 | false | false | false | false |
jwren/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/dependency/analyzer/AbstractDependencyAnalyzerAction.kt | 1 | 1599 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.dependency.analyzer
import com.intellij.openapi.actionSystem.AnActionEvent
abstract class AbstractDependencyAnalyzerAction<Data> : DependencyAnalyzerAction() {
abstract fun getSelectedData(e: AnActionEvent): Data?
abstract fun getExternalProjectPath(e: AnActionEvent, selectedData: Data): String?
abstract fun getDependencyData(e: AnActionEvent, selectedData: Data): DependencyAnalyzerDependency.Data?
abstract fun getDependencyScope(e: AnActionEvent, selectedData: Data): DependencyAnalyzerDependency.Scope?
override fun isEnabledAndVisible(e: AnActionEvent): Boolean {
val selectedData = getSelectedData(e) ?: return false
return getExternalProjectPath(e, selectedData) != null
}
override fun setSelectedState(view: DependencyAnalyzerView, e: AnActionEvent) {
val selectedData = getSelectedData(e) ?: return
val externalProjectPath = getExternalProjectPath(e, selectedData) ?: return
val dependencyData = getDependencyData(e, selectedData)
val dependencyScope = getDependencyScope(e, selectedData)
if (dependencyData != null && dependencyScope != null) {
view.setSelectedDependency(externalProjectPath, dependencyData, dependencyScope)
}
else if (dependencyData != null) {
view.setSelectedDependency(externalProjectPath, dependencyData)
}
else {
view.setSelectedExternalProject(externalProjectPath)
}
}
} | apache-2.0 | 4902f7303054501194615f9279b37dcd | 43.444444 | 158 | 0.778612 | 5.125 | false | false | false | false |
androidx/androidx | metrics/metrics-performance/src/main/java/androidx/metrics/performance/JankStatsApi31Impl.kt | 3 | 2566 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.metrics.performance
import android.view.FrameMetrics
import android.view.View
import android.view.Window
import androidx.annotation.RequiresApi
@RequiresApi(31)
internal class JankStatsApi31Impl(
jankStats: JankStats,
view: View,
window: Window
) : JankStatsApi26Impl(jankStats, view, window) {
// Reuse the same frameData on every frame to avoid allocating per-frame objects
val frameData = FrameDataApi31(0, 0, 0, 0, 0, false, stateInfo)
override fun getFrameData(
startTime: Long,
expectedDuration: Long,
frameMetrics: FrameMetrics
): FrameDataApi31 {
val uiDuration = frameMetrics.getMetric(FrameMetrics.UNKNOWN_DELAY_DURATION) +
frameMetrics.getMetric(FrameMetrics.INPUT_HANDLING_DURATION) +
frameMetrics.getMetric(FrameMetrics.ANIMATION_DURATION) +
frameMetrics.getMetric(FrameMetrics.LAYOUT_MEASURE_DURATION) +
frameMetrics.getMetric(FrameMetrics.DRAW_DURATION) +
frameMetrics.getMetric(FrameMetrics.SYNC_DURATION)
prevEnd = startTime + uiDuration
metricsStateHolder.state?.getIntervalStates(startTime, prevEnd, stateInfo)
val isJank = uiDuration > expectedDuration
val totalDuration = frameMetrics.getMetric(FrameMetrics.TOTAL_DURATION)
// SWAP is counted for both CPU and GPU metrics, so add it back in after subtracting GPU
val cpuDuration = totalDuration -
frameMetrics.getMetric(FrameMetrics.GPU_DURATION) +
frameMetrics.getMetric(FrameMetrics.SWAP_BUFFERS_DURATION)
val overrun = totalDuration -
frameMetrics.getMetric(FrameMetrics.DEADLINE)
frameData.update(startTime, uiDuration, cpuDuration, totalDuration, overrun, isJank)
return frameData
}
override fun getExpectedFrameDuration(metrics: FrameMetrics): Long {
return metrics.getMetric(FrameMetrics.DEADLINE)
}
} | apache-2.0 | 448a6ed619cac8e5ab966a536dc9cf7b | 40.403226 | 96 | 0.726033 | 4.716912 | false | false | false | false |
androidx/androidx | navigation/navigation-fragment/src/androidTest/java/androidx/navigation/fragment/DialogFragmentNavigatorDestinationBuilderTest.kt | 3 | 5134 | /*
* 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.navigation.fragment
import androidx.fragment.app.DialogFragment
import androidx.navigation.contains
import androidx.navigation.createGraph
import androidx.navigation.get
import androidx.test.annotation.UiThreadTest
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertWithMessage
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@SmallTest
@RunWith(AndroidJUnit4::class)
class DialogFragmentNavigatorDestinationBuilderTest {
@Suppress("DEPRECATION")
@get:Rule
val activityRule = androidx.test.rule.ActivityTestRule<TestActivity>(TestActivity::class.java)
private val fragmentManager get() = activityRule.activity.supportFragmentManager
@Suppress("DEPRECATION")
@UiThreadTest
@Test fun fragment() {
val navHostFragment = NavHostFragment()
fragmentManager.beginTransaction()
.add(android.R.id.content, navHostFragment)
.commitNow()
val graph = navHostFragment.createGraph(startDestination = DESTINATION_ID) {
dialog<BuilderTestDialogFragment>(DESTINATION_ID)
}
assertWithMessage("Destination should be added to the graph")
.that(DESTINATION_ID in graph)
.isTrue()
assertWithMessage("DialogFragment class should be set to BuilderTestDialogFragment")
.that((graph[DESTINATION_ID] as DialogFragmentNavigator.Destination).className)
.isEqualTo(BuilderTestDialogFragment::class.java.name)
}
@Suppress("DEPRECATION")
@UiThreadTest
@Test fun fragmentWithBody() {
val navHostFragment = NavHostFragment()
fragmentManager.beginTransaction()
.add(android.R.id.content, navHostFragment)
.commitNow()
val graph = navHostFragment.createGraph(startDestination = DESTINATION_ID) {
dialog<BuilderTestDialogFragment>(DESTINATION_ID) {
label = LABEL
}
}
assertWithMessage("Destination should be added to the graph")
.that(DESTINATION_ID in graph)
.isTrue()
assertWithMessage("DialogFragment class should be set to BuilderTestDialogFragment")
.that((graph[DESTINATION_ID] as DialogFragmentNavigator.Destination).className)
.isEqualTo(BuilderTestDialogFragment::class.java.name)
assertWithMessage("DialogFragment should have label set")
.that(graph[DESTINATION_ID].label)
.isEqualTo(LABEL)
}
@UiThreadTest
@Test fun fragmentRoute() {
val navHostFragment = NavHostFragment()
fragmentManager.beginTransaction()
.add(android.R.id.content, navHostFragment)
.commitNow()
val graph = navHostFragment.createGraph(startDestination = DESTINATION_ROUTE) {
dialog<BuilderTestDialogFragment>(DESTINATION_ROUTE)
}
assertWithMessage("Destination should be added to the graph")
.that(DESTINATION_ROUTE in graph)
.isTrue()
assertWithMessage("DialogFragment class should be set to BuilderTestDialogFragment")
.that((graph[DESTINATION_ROUTE] as DialogFragmentNavigator.Destination).className)
.isEqualTo(BuilderTestDialogFragment::class.java.name)
}
@UiThreadTest
@Test fun fragmentWithBodyRoute() {
val navHostFragment = NavHostFragment()
fragmentManager.beginTransaction()
.add(android.R.id.content, navHostFragment)
.commitNow()
val graph = navHostFragment.createGraph(startDestination = DESTINATION_ROUTE) {
dialog<BuilderTestDialogFragment>(DESTINATION_ROUTE) {
label = LABEL
}
}
assertWithMessage("Destination should be added to the graph")
.that(DESTINATION_ROUTE in graph)
.isTrue()
assertWithMessage("DialogFragment class should be set to BuilderTestDialogFragment")
.that((graph[DESTINATION_ROUTE] as DialogFragmentNavigator.Destination).className)
.isEqualTo(BuilderTestDialogFragment::class.java.name)
assertWithMessage("DialogFragment should have label set")
.that(graph[DESTINATION_ROUTE].label)
.isEqualTo(LABEL)
}
}
private const val DESTINATION_ID = 1
private const val DESTINATION_ROUTE = "destination"
private const val LABEL = "Test"
class BuilderTestDialogFragment : DialogFragment()
| apache-2.0 | 51bc4a7a8de619b194cabf21c093dfac | 40.739837 | 98 | 0.698675 | 5.331256 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/core/TypesWithOperatorDetector.kt | 4 | 6349 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.core
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.utils.collectFunctions
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeSubstitutor
import org.jetbrains.kotlin.types.typeUtil.TypeNullability
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.util.isValidOperator
import org.jetbrains.kotlin.utils.addIfNotNull
import java.util.*
abstract class TypesWithOperatorDetector(
private val name: Name,
private val scope: LexicalScope,
private val indicesHelper: KotlinIndicesHelper?
) {
protected abstract fun checkIsSuitableByType(
operator: FunctionDescriptor,
freeTypeParams: Collection<TypeParameterDescriptor>
): TypeSubstitutor?
private val cache = HashMap<FuzzyType, Pair<FunctionDescriptor, TypeSubstitutor>?>()
val extensionOperators: Collection<FunctionDescriptor> by lazy {
val result = ArrayList<FunctionDescriptor>()
val extensionsFromScope = scope
.collectFunctions(name, NoLookupLocation.FROM_IDE)
.filter { it.extensionReceiverParameter != null }
result.addSuitableOperators(extensionsFromScope)
indicesHelper?.getTopLevelExtensionOperatorsByName(name.asString())?.let { result.addSuitableOperators(it) }
result.distinctBy { it.original }
}
val classesWithMemberOperators: Collection<ClassDescriptor> by lazy {
if (indicesHelper == null) return@lazy emptyList<ClassDescriptor>()
val operators = ArrayList<FunctionDescriptor>().addSuitableOperators(indicesHelper.getMemberOperatorsByName(name.asString()))
operators.map { it.containingDeclaration as ClassDescriptor }.distinct()
}
private fun MutableCollection<FunctionDescriptor>.addSuitableOperators(functions: Collection<FunctionDescriptor>): MutableCollection<FunctionDescriptor> {
for (function in functions) {
if (!function.isValidOperator()) continue
var freeParameters = function.typeParameters
val containingClass = function.containingDeclaration as? ClassDescriptor
if (containingClass != null) {
freeParameters += containingClass.typeConstructor.parameters
}
val substitutor = checkIsSuitableByType(function, freeParameters) ?: continue
addIfNotNull(function.substitute(substitutor))
}
return this
}
fun findOperator(type: FuzzyType): Pair<FunctionDescriptor, TypeSubstitutor>? = if (cache.containsKey(type)) {
cache[type]
} else {
val result = findOperatorNoCache(type)
cache[type] = result
result
}
private fun findOperatorNoCache(type: FuzzyType): Pair<FunctionDescriptor, TypeSubstitutor>? {
if (type.nullability() != TypeNullability.NULLABLE) {
for (memberFunction in type.type.memberScope.getContributedFunctions(name, NoLookupLocation.FROM_IDE)) {
if (memberFunction.isValidOperator()) {
val substitutor = checkIsSuitableByType(memberFunction, type.freeParameters) ?: continue
val substituted = memberFunction.substitute(substitutor) ?: continue
return substituted to substitutor
}
}
}
for (operator in extensionOperators) {
val substitutor = type.checkIsSubtypeOf(operator.fuzzyExtensionReceiverType()!!) ?: continue
val substituted = operator.substitute(substitutor) ?: continue
return substituted to substitutor
}
return null
}
}
class TypesWithContainsDetector(
scope: LexicalScope,
indicesHelper: KotlinIndicesHelper?,
private val argumentType: KotlinType
) : TypesWithOperatorDetector(OperatorNameConventions.CONTAINS, scope, indicesHelper) {
override fun checkIsSuitableByType(
operator: FunctionDescriptor,
freeTypeParams: Collection<TypeParameterDescriptor>
): TypeSubstitutor? {
val parameter = operator.valueParameters.single()
val fuzzyParameterType = parameter.type.toFuzzyType(operator.typeParameters + freeTypeParams)
return fuzzyParameterType.checkIsSuperTypeOf(argumentType)
}
}
class TypesWithGetValueDetector(
scope: LexicalScope,
indicesHelper: KotlinIndicesHelper?,
private val propertyOwnerType: FuzzyType,
private val propertyType: FuzzyType?
) : TypesWithOperatorDetector(OperatorNameConventions.GET_VALUE, scope, indicesHelper) {
override fun checkIsSuitableByType(
operator: FunctionDescriptor,
freeTypeParams: Collection<TypeParameterDescriptor>
): TypeSubstitutor? {
val paramType = operator.valueParameters.first().type.toFuzzyType(freeTypeParams)
val substitutor = paramType.checkIsSuperTypeOf(propertyOwnerType) ?: return null
if (propertyType == null) return substitutor
val fuzzyReturnType = operator.returnType?.toFuzzyType(freeTypeParams) ?: return null
val substitutorFromPropertyType = fuzzyReturnType.checkIsSubtypeOf(propertyType) ?: return null
return substitutor.combineIfNoConflicts(substitutorFromPropertyType, freeTypeParams)
}
}
class TypesWithSetValueDetector(
scope: LexicalScope,
indicesHelper: KotlinIndicesHelper?,
private val propertyOwnerType: FuzzyType
) : TypesWithOperatorDetector(OperatorNameConventions.SET_VALUE, scope, indicesHelper) {
override fun checkIsSuitableByType(
operator: FunctionDescriptor,
freeTypeParams: Collection<TypeParameterDescriptor>
): TypeSubstitutor? {
val paramType = operator.valueParameters.first().type.toFuzzyType(freeTypeParams)
return paramType.checkIsSuperTypeOf(propertyOwnerType)
}
} | apache-2.0 | 5e967e80a044355f63c2cfaae83e71d5 | 41.905405 | 158 | 0.738226 | 5.673816 | false | false | false | false |
GunoH/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/ProjectModuleOperationProvider.kt | 3 | 6279 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.jetbrains.packagesearch.intellij.plugin.extensibility
import com.intellij.buildsystem.model.DeclaredDependency
import com.intellij.buildsystem.model.OperationFailure
import com.intellij.buildsystem.model.OperationItem
import com.intellij.buildsystem.model.unified.UnifiedDependency
import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.jetbrains.packagesearch.intellij.plugin.intentions.PackageSearchDependencyUpgradeQuickFix
import com.jetbrains.packagesearch.intellij.plugin.util.asCoroutine
/**
* Extension point that allows to modify the dependencies of a specific project.
*/
@Deprecated(
"Use async version. Either AsyncProjectModuleOperationProvider or CoroutineProjectModuleOperationProvider." +
" Remember to change the extension point type in the xml",
ReplaceWith(
"ProjectAsyncModuleOperationProvider",
"com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectAsyncModuleOperationProvider"
),
DeprecationLevel.WARNING
)
interface ProjectModuleOperationProvider {
companion object {
private val EP_NAME = "com.intellij.packagesearch.projectModuleOperationProvider"
private val extensionPointName
get() = ExtensionPointName.create<ProjectModuleOperationProvider>(EP_NAME)
internal val extensions
get() = extensionPointName.extensions.map { it.asCoroutine() }
}
/**
* Returns whether the implementation of the interface uses the shared "packages update available"
* inspection and quickfix. This is `false` by default; override this property and return `true`
* to opt in to [PackageUpdateInspection].
*
* @return `true` opt in to [PackageUpdateInspection], false otherwise.
* @see PackageUpdateInspection
* @see PackageSearchDependencyUpgradeQuickFix
*/
fun usesSharedPackageUpdateInspection(): Boolean = false
/**
* Checks if current implementation has support in the given [project] for the current [psiFile].
* @return `true` if the [project] and [psiFile] are supported.
*/
fun hasSupportFor(project: Project, psiFile: PsiFile?): Boolean
/**
* Checks if current implementation has support in the given [projectModuleType].
* @return `true` if the [projectModuleType] is supported.
*/
fun hasSupportFor(projectModuleType: ProjectModuleType): Boolean
/**
* Adds a dependency to the given [module] using [operationMetadata].
* @return A list containing all failures encountered during the operation. If the list is empty, the operation was successful.
*/
fun addDependencyToModule(
operationMetadata: DependencyOperationMetadata,
module: ProjectModule
): Collection<OperationFailure<out OperationItem>> = emptyList()
/**
* Removes a dependency from the given [module] using [operationMetadata].
* @return A list containing all failures encountered during the operation. If the list is empty, the operation was successful.
*/
fun removeDependencyFromModule(
operationMetadata: DependencyOperationMetadata,
module: ProjectModule
): Collection<OperationFailure<out OperationItem>> = emptyList()
/**
* Modify a dependency in the given [module] using [operationMetadata].
* @return A list containing all failures encountered during the operation. If the list is empty, the operation was successful.
*/
fun updateDependencyInModule(
operationMetadata: DependencyOperationMetadata,
module: ProjectModule
): Collection<OperationFailure<out OperationItem>> = emptyList()
/**
* Lists all dependencies declared in the given [module]. A declared dependency
* have to be explicitly written in the build file.
* @return A [Collection]<[UnifiedDependency]> found in the project.
*/
fun declaredDependenciesInModule(
module: ProjectModule
): Collection<DeclaredDependency> = emptyList()
/**
* Lists all resolved dependencies in the given [module].
* @return A [Collection]<[UnifiedDependency]> found in the project.
*/
fun resolvedDependenciesInModule(
module: ProjectModule,
scopes: Set<String> = emptySet()
): Collection<UnifiedDependency> = emptyList()
/**
* Adds the [repository] to the given [module].
* @return A list containing all failures encountered during the operation. If the list is empty, the operation was successful.
*/
fun addRepositoryToModule(
repository: UnifiedDependencyRepository,
module: ProjectModule
): Collection<OperationFailure<out OperationItem>> = emptyList()
/**
* Removes the [repository] from the given [module].
* @return A list containing all failures encountered during the operation. If the list is empty, the operation was successful.
*/
fun removeRepositoryFromModule(
repository: UnifiedDependencyRepository,
module: ProjectModule
): Collection<OperationFailure<out OperationItem>> = emptyList()
/**
* Lists all repositories in the given [module].
* @return A [Collection]<[UnifiedDependencyRepository]> found the project.
*/
fun listRepositoriesInModule(
module: ProjectModule
): Collection<UnifiedDependencyRepository> = emptyList()
}
| apache-2.0 | 25972d57eb2cafd9dc4887b927e4d673 | 41.14094 | 131 | 0.712852 | 5.488636 | false | false | false | false |
kivensolo/UiUsingListView | module-Demo/src/main/java/com/zeke/demo/jetpack/paging/PagingDemoActivity.kt | 1 | 1799 | package com.zeke.demo.jetpack.paging
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.kingz.base.BaseVMActivity
import com.zeke.demo.R
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
/**
* author: King.Z <br>
* date: 2021/8/22 21:13 <br>
* description: <br>
*/
class PagingDemoActivity : BaseVMActivity() {
lateinit var pagingAdapter: PagingDemoAdapter
override val viewModel: UserInfoViewModel by lazy {
UserInfoViewModel(ReqresApiService.getApiService())
}
override fun getContentLayout(): Int = R.layout.activity_paging_demo
override fun initView(savedInstanceState: Bundle?) {
super.initView(savedInstanceState)
pagingAdapter = PagingDemoAdapter().apply {
// 列表加载时回调
addLoadStateListener {
if (it.refresh == LoadState.Loading) {
// show progress view
} else {
//hide progress view
}
}
//withLoadStateHeaderAndFooter{ }
// .withLoadStateFooter
}
findViewById<RecyclerView>(R.id.content_recycler).apply {
layoutManager = LinearLayoutManager(this@PagingDemoActivity)
adapter = pagingAdapter
}
}
override fun initData(savedInstanceState: Bundle?) {
lifecycleScope.launch {
try {
viewModel.listData.collect {
pagingAdapter.submitData(it)
}
} catch (e: Throwable) {
println("Exception from the flow: $e")
}
}
}
} | gpl-2.0 | dd326c856121fa4897e2447ae41e13b6 | 28.766667 | 72 | 0.62521 | 4.811321 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/entity/settings/SettingBuilder.kt | 1 | 2039 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.core.entity.settings
import org.jetbrains.kotlin.tools.projectWizard.core.Reader
import org.jetbrains.kotlin.tools.projectWizard.core.entity.SettingValidator
import org.jetbrains.kotlin.tools.projectWizard.core.entity.ValidationResult
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settingValidator
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
abstract class SettingBuilder<V : Any, T : SettingType<V>>(
private val path: String,
private val title: String,
private val neededAtPhase: GenerationPhase
) {
var isAvailable: Reader.() -> Boolean = { true }
open var defaultValue: SettingDefaultValue<V>? = null
var validateOnProjectCreation = true
var isSavable: Boolean = false
var isRequired: Boolean? = null
var description: String? = null
fun value(value: V) = SettingDefaultValue.Value(value)
fun dynamic(getter: Reader.(SettingReference<V, SettingType<V>>) -> V?) =
SettingDefaultValue.Dynamic(getter)
protected var validator =
SettingValidator<V> { ValidationResult.OK }
fun validate(validator: SettingValidator<V>) {
this.validator = this.validator and validator
}
fun validate(validator: Reader.(V) -> ValidationResult) {
this.validator = this.validator and settingValidator(
validator
)
}
abstract val type: T
fun buildInternal() = InternalSetting(
path = path,
title = title,
description = description,
defaultValue = defaultValue,
isAvailable = isAvailable,
isRequired = isRequired ?: (defaultValue == null),
isSavable = isSavable,
neededAtPhase = neededAtPhase,
validator = validator,
validateOnProjectCreation = validateOnProjectCreation,
type = type
)
} | apache-2.0 | 1312e078d40dea732fc504650457f79e | 34.172414 | 158 | 0.710152 | 4.687356 | false | false | false | false |
JetBrains/kotlin-native | tools/benchmarks/shared/src/main/kotlin/report/json/JsonElement.kt | 4 | 11329 | /*
* Copyright 2010-2018 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.report.json
/**
* Class representing single JSON element.
* Can be [JsonPrimitive], [JsonArray] or [JsonObject].
*
* [JsonElement.toString] properly prints JSON tree as valid JSON, taking into
* account quoted values and primitives
*/
sealed class JsonElement {
/**
* Convenience method to get current element as [JsonPrimitive]
* @throws JsonElementTypeMismatchException is current element is not a [JsonPrimitive]
*/
open val primitive: JsonPrimitive
get() = error("JsonLiteral")
/**
* Convenience method to get current element as [JsonObject]
* @throws JsonElementTypeMismatchException is current element is not a [JsonObject]
*/
open val jsonObject: JsonObject
get() = error("JsonObject")
/**
* Convenience method to get current element as [JsonArray]
* @throws JsonElementTypeMismatchException is current element is not a [JsonArray]
*/
open val jsonArray: JsonArray
get() = error("JsonArray")
/**
* Convenience method to get current element as [JsonNull]
* @throws JsonElementTypeMismatchException is current element is not a [JsonNull]
*/
open val jsonNull: JsonNull
get() = error("JsonPrimitive")
/**
* Checks whether current element is [JsonNull]
*/
val isNull: Boolean
get() = this === JsonNull
private fun error(element: String): Nothing =
throw JsonElementTypeMismatchException(this::class.toString(), element)
}
/**
* Class representing JSON primitive value. Can be either [JsonLiteral] or [JsonNull].
*/
sealed class JsonPrimitive : JsonElement() {
/**
* Content of given element without quotes. For [JsonNull] this methods returns `"null"`
*/
abstract val content: String
/**
* Content of the given element without quotes or `null` if current element is [JsonNull]
*/
abstract val contentOrNull: String?
@Suppress("LeakingThis")
final override val primitive: JsonPrimitive = this
/**
* Returns content of current element as int
* @throws NumberFormatException if current element is not a valid representation of number
*/
val int: Int get() = content.toInt()
/**
* Returns content of current element as int or `null` if current element is not a valid representation of number
**/
val intOrNull: Int? get() = content.toIntOrNull()
/**
* Returns content of current element as long
* @throws NumberFormatException if current element is not a valid representation of number
*/
val long: Long get() = content.toLong()
/**
* Returns content of current element as long or `null` if current element is not a valid representation of number
*/
val longOrNull: Long? get() = content.toLongOrNull()
/**
* Returns content of current element as double
* @throws NumberFormatException if current element is not a valid representation of number
*/
val double: Double get() = content.toDouble()
/**
* Returns content of current element as double or `null` if current element is not a valid representation of number
*/
val doubleOrNull: Double? get() = content.toDoubleOrNull()
/**
* Returns content of current element as float
* @throws NumberFormatException if current element is not a valid representation of number
*/
val float: Float get() = content.toFloat()
/**
* Returns content of current element as float or `null` if current element is not a valid representation of number
*/
val floatOrNull: Float? get() = content.toFloatOrNull()
/**
* Returns content of current element as boolean
* @throws IllegalStateException if current element doesn't represent boolean
*/
val boolean: Boolean get() = content.toBooleanStrict()
/**
* Returns content of current element as boolean or `null` if current element is not a valid representation of boolean
*/
val booleanOrNull: Boolean? get() = content.toBooleanStrictOrNull()
override fun toString() = content
}
/**
* Class representing JSON literals: numbers, booleans and string.
* Strings are always quoted.
*/
data class JsonLiteral internal constructor(
private val body: Any,
private val isString: Boolean
) : JsonPrimitive() {
override val content = body.toString()
override val contentOrNull: String = content
/**
* Creates number literal
*/
constructor(number: Number) : this(number, false)
/**
* Creates boolean literal
*/
constructor(boolean: Boolean) : this(boolean, false)
/**
* Creates quoted string literal
*/
constructor(string: String) : this(string, true)
override fun toString() =
if (isString) buildString { printQuoted(content) }
else content
fun unquoted() = content
}
/**
* Class representing JSON `null` value
*/
object JsonNull : JsonPrimitive() {
override val jsonNull: JsonNull = this
override val content: String = "null"
override val contentOrNull: String? = null
}
/**
* Class representing JSON object, consisting of name-value pairs, where value is arbitrary [JsonElement]
*/
data class JsonObject(val content: Map<String, JsonElement>) : JsonElement(), Map<String, JsonElement> by content {
override val jsonObject: JsonObject = this
/**
* Returns [JsonElement] associated with given [key]
* @throws NoSuchElementException if element is not present
*/
override fun get(key: String): JsonElement = content[key] ?: throw NoSuchElementException("Element $key is missing")
/**
* Returns [JsonElement] associated with given [key] or `null` if element is not present
*/
fun getOrNull(key: String): JsonElement? = content[key]
/**
* Returns [JsonPrimitive] associated with given [key]
*
* @throws NoSuchElementException if element is not present
* @throws JsonElementTypeMismatchException if element is present, but has invalid type
*/
fun getPrimitive(key: String): JsonPrimitive = get(key) as? JsonPrimitive
?: unexpectedJson(key, "JsonPrimitive")
/**
* Returns [JsonObject] associated with given [key]
*
* @throws NoSuchElementException if element is not present
* @throws JsonElementTypeMismatchException if element is present, but has invalid type
*/
fun getObject(key: String): JsonObject = get(key) as? JsonObject
?: unexpectedJson(key, "JsonObject")
/**
* Returns [JsonArray] associated with given [key]
*
* @throws NoSuchElementException if element is not present
* @throws JsonElementTypeMismatchException if element is present, but has invalid type
*/
fun getArray(key: String): JsonArray = get(key) as? JsonArray
?: unexpectedJson(key, "JsonArray")
/**
* Returns [JsonPrimitive] associated with given [key] or `null` if element
* is not present or has different type
*/
fun getPrimitiveOrNull(key: String): JsonPrimitive? = content[key] as? JsonPrimitive
/**
* Returns [JsonObject] associated with given [key] or `null` if element
* is not present or has different type
*/
fun getObjectOrNull(key: String): JsonObject? = content[key] as? JsonObject
/**
* Returns [JsonArray] associated with given [key] or `null` if element
* is not present or has different type
*/
fun getArrayOrNull(key: String): JsonArray? = content[key] as? JsonArray
/**
* Returns [J] associated with given [key]
*
* @throws NoSuchElementException if element is not present
* @throws JsonElementTypeMismatchException if element is present, but has invalid type
*/
inline fun <reified J : JsonElement> getAs(key: String): J = get(key) as? J
?: unexpectedJson(key, J::class.toString())
/**
* Returns [J] associated with given [key] or `null` if element
* is not present or has different type
*/
inline fun <reified J : JsonElement> lookup(key: String): J? = content[key] as? J
override fun toString(): String {
return content.entries.joinToString(
prefix = "{",
postfix = "}",
transform = {(k, v) -> """"$k": $v"""}
)
}
}
data class JsonArray(val content: List<JsonElement>) : JsonElement(), List<JsonElement> by content {
override val jsonArray: JsonArray = this
/**
* Returns [index]-th element of an array as [JsonPrimitive]
* @throws JsonElementTypeMismatchException if element has invalid type
*/
fun getPrimitive(index: Int) = content[index] as? JsonPrimitive
?: unexpectedJson("at $index", "JsonPrimitive")
/**
* Returns [index]-th element of an array as [JsonObject]
* @throws JsonElementTypeMismatchException if element has invalid type
*/
fun getObject(index: Int) = content[index] as? JsonObject
?: unexpectedJson("at $index", "JsonObject")
/**
* Returns [index]-th element of an array as [JsonArray]
* @throws JsonElementTypeMismatchException if element has invalid type
*/
fun getArray(index: Int) = content[index] as? JsonArray
?: unexpectedJson("at $index", "JsonArray")
/**
* Returns [index]-th element of an array as [JsonPrimitive] or `null` if element is missing or has different type
*/
fun getPrimitiveOrNull(index: Int) = content.getOrNull(index) as? JsonPrimitive
/**
* Returns [index]-th element of an array as [JsonObject] or `null` if element is missing or has different type
*/
fun getObjectOrNull(index: Int) = content.getOrNull(index) as? JsonObject
/**
* Returns [index]-th element of an array as [JsonArray] or `null` if element is missing or has different type
*/
fun getArrayOrNull(index: Int) = content.getOrNull(index) as? JsonArray
/**
* Returns [index]-th element of an array as [J]
* @throws JsonElementTypeMismatchException if element has invalid type
*/
inline fun <reified J : JsonElement> getAs(index: Int): J = content[index] as? J
?: unexpectedJson("at $index", J::class.toString())
/**
* Returns [index]-th element of an array as [J] or `null` if element is missing or has different type
*/
inline fun <reified J : JsonElement> getAsOrNull(index: Int): J? = content.getOrNull(index) as? J
override fun toString() = content.joinToString(prefix = "[", postfix = "]")
}
fun unexpectedJson(key: String, expected: String): Nothing =
throw JsonElementTypeMismatchException(key, expected) | apache-2.0 | 84489a115ef40a56da0e7ce3cc0ce390 | 33.542683 | 122 | 0.668373 | 4.752097 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/sequence/exec/KotlinTraceTestCase.kt | 3 | 6859 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.test.sequence.exec
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.impl.OutputChecker
import com.intellij.debugger.streams.lib.LibrarySupportProvider
import com.intellij.debugger.streams.psi.DebuggerPositionResolver
import com.intellij.debugger.streams.psi.impl.DebuggerPositionResolverImpl
import com.intellij.debugger.streams.trace.*
import com.intellij.debugger.streams.trace.impl.TraceResultInterpreterImpl
import com.intellij.debugger.streams.wrapper.StreamChain
import com.intellij.debugger.streams.wrapper.StreamChainBuilder
import com.intellij.execution.process.ProcessOutputTypes
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.Computable
import com.intellij.xdebugger.XDebugSessionListener
import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinDebuggerCaches
import org.jetbrains.kotlin.idea.debugger.test.KotlinDescriptorTestCaseWithStepping
import org.jetbrains.kotlin.idea.debugger.test.TestFiles
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferences
import java.util.concurrent.atomic.AtomicBoolean
abstract class KotlinTraceTestCase : KotlinDescriptorTestCaseWithStepping() {
private companion object {
val DEFAULT_CHAIN_SELECTOR = ChainSelector.byIndex(0)
}
private lateinit var traceChecker: StreamTraceChecker
override fun initOutputChecker(): OutputChecker {
traceChecker = StreamTraceChecker(this)
return super.initOutputChecker()
}
abstract val librarySupportProvider: LibrarySupportProvider
override fun doMultiFileTest(files: TestFiles, preferences: DebuggerPreferences) {
// Sequence expressions are verbose. Disable expression logging for sequence debugger
KotlinDebuggerCaches.LOG_COMPILATIONS = false
val session = debuggerSession.xDebugSession ?: kotlin.test.fail("XDebugSession is null")
assertNotNull(session)
val completed = AtomicBoolean(false)
val positionResolver = getPositionResolver()
val chainBuilder = getChainBuilder()
val resultInterpreter = getResultInterpreter()
val expressionBuilder = getExpressionBuilder()
val chainSelector = DEFAULT_CHAIN_SELECTOR
session.addSessionListener(object : XDebugSessionListener {
override fun sessionPaused() {
if (completed.getAndSet(true)) {
resume()
return
}
try {
sessionPausedImpl()
} catch (t: Throwable) {
println("Exception caught: $t, ${t.message}", ProcessOutputTypes.SYSTEM)
t.printStackTrace()
resume()
}
}
private fun sessionPausedImpl() {
printContext(debugProcess.debuggerContext)
val chain = ApplicationManager.getApplication().runReadAction(
Computable<StreamChain> {
val elementAtBreakpoint = positionResolver.getNearestElementToBreakpoint(session)
val chains = if (elementAtBreakpoint == null) null else chainBuilder.build(elementAtBreakpoint)
if (chains.isNullOrEmpty()) null else chainSelector.select(chains)
})
if (chain == null) {
complete(null, null, null, FailureReason.CHAIN_CONSTRUCTION)
return
}
EvaluateExpressionTracer(session, expressionBuilder, resultInterpreter).trace(chain, object : TracingCallback {
override fun evaluated(result: TracingResult, context: EvaluationContextImpl) {
complete(chain, result, null, null)
}
override fun evaluationFailed(traceExpression: String, message: String) {
complete(chain, null, message, FailureReason.EVALUATION)
}
override fun compilationFailed(traceExpression: String, message: String) {
complete(chain, null, message, FailureReason.COMPILATION)
}
})
}
private fun complete(chain: StreamChain?, result: TracingResult?, error: String?, errorReason: FailureReason?) {
try {
if (error != null) {
assertNotNull(errorReason)
assertNotNull(chain)
throw AssertionError(error)
} else {
assertNull(errorReason)
handleSuccess(chain, result)
}
} catch (t: Throwable) {
println("Exception caught: " + t + ", " + t.message, ProcessOutputTypes.SYSTEM)
} finally {
resume()
}
}
private fun resume() {
ApplicationManager.getApplication().invokeLater { session.resume() }
}
}, testRootDisposable)
}
private fun getPositionResolver(): DebuggerPositionResolver {
return DebuggerPositionResolverImpl()
}
protected fun handleSuccess(chain: StreamChain?, result: TracingResult?) {
kotlin.test.assertNotNull(chain)
kotlin.test.assertNotNull(result)
println(chain.text, ProcessOutputTypes.SYSTEM)
val trace = result.trace
traceChecker.checkChain(trace)
val resolvedTrace = result.resolve(librarySupportProvider.librarySupport.resolverFactory)
traceChecker.checkResolvedChain(resolvedTrace)
}
private fun getResultInterpreter(): TraceResultInterpreter {
return TraceResultInterpreterImpl(librarySupportProvider.librarySupport.interpreterFactory)
}
private fun getChainBuilder(): StreamChainBuilder {
return librarySupportProvider.chainBuilder
}
private fun getExpressionBuilder(): TraceExpressionBuilder {
return librarySupportProvider.getExpressionBuilder(project)
}
protected enum class FailureReason {
COMPILATION, EVALUATION, CHAIN_CONSTRUCTION
}
@FunctionalInterface
protected interface ChainSelector {
fun select(chains: List<StreamChain>): StreamChain
companion object {
fun byIndex(index: Int): ChainSelector {
return object : ChainSelector {
override fun select(chains: List<StreamChain>): StreamChain = chains[index]
}
}
}
}
} | apache-2.0 | 96a2d7b2e079e4b82b9e430e501e6549 | 40.077844 | 158 | 0.649949 | 5.640625 | false | true | false | false |
jwren/intellij-community | plugins/ide-features-trainer/src/training/learn/lesson/general/navigation/SearchEverywhereLesson.kt | 5 | 6227 | // 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.ide.actions.searcheverywhere.SearchEverywhereManagerImpl
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereUI
import com.intellij.openapi.actionSystem.impl.ActionButtonWithText
import com.intellij.openapi.editor.impl.EditorComponentImpl
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.psi.search.EverythingGlobalScope
import com.intellij.psi.search.ProjectScope
import com.intellij.ui.components.fields.ExtendableTextField
import com.intellij.util.ui.UIUtil
import training.dsl.*
import training.dsl.LessonUtil.adjustPopupPosition
import training.dsl.LessonUtil.restorePopupPosition
import training.learn.LessonsBundle
import training.learn.course.KLesson
import training.learn.course.LessonType
import training.util.LessonEndInfo
import training.util.isToStringContains
import java.awt.Point
import java.awt.event.KeyEvent
import javax.swing.JList
abstract class SearchEverywhereLesson : KLesson("Search everywhere", LessonsBundle.message("search.everywhere.lesson.name")) {
abstract override val sampleFilePath: String?
abstract val resultFileName: String
override val lessonType: LessonType = LessonType.PROJECT
private val requiredClassName = "QuadraticEquationsSolver"
private var backupPopupLocation: Point? = null
override val lessonContent: LessonContext.() -> Unit = {
sdkConfigurationTasks()
task("SearchEverywhere") {
triggerAndBorderHighlight().component { ui: ExtendableTextField ->
UIUtil.getParentOfType(SearchEverywhereUI::class.java, ui) != null
}
text(LessonsBundle.message("search.everywhere.invoke.search.everywhere", LessonUtil.actionName(it),
LessonUtil.rawKeyStroke(KeyEvent.VK_SHIFT)))
test { actions(it) }
}
task("que") {
before {
if (backupPopupLocation == null) {
backupPopupLocation = adjustPopupPosition(SearchEverywhereManagerImpl.LOCATION_SETTINGS_KEY)
}
}
text(LessonsBundle.message("search.everywhere.type.prefixes", strong("quadratic"), strong("equation"), code(it)))
stateCheck { checkWordInSearch(it) }
restoreByUi()
test {
Thread.sleep(500)
type(it)
}
}
task {
triggerAndBorderHighlight().listItem { item ->
if (item is PsiNameIdentifierOwner)
item.name == requiredClassName
else item.isToStringContains(requiredClassName)
}
restoreByUi()
}
task {
text(LessonsBundle.message("search.everywhere.navigate.to.class", code(requiredClassName), LessonUtil.rawEnter()))
stateCheck {
FileEditorManager.getInstance(project).selectedEditor?.file?.name.equals(resultFileName)
}
restoreByUi()
test {
Thread.sleep(500) // wait items loading
val jList = previous.ui as? JList<*> ?: error("No list")
val itemIndex = LessonUtil.findItem(jList) { item ->
if (item is PsiNameIdentifierOwner)
item.name == requiredClassName
else item.isToStringContains(requiredClassName)
} ?: error("No item")
ideFrame {
jListFixture(jList).clickItem(itemIndex)
}
}
}
actionTask("GotoClass") {
LessonsBundle.message("search.everywhere.goto.class", action(it))
}
task("bufre") {
text(LessonsBundle.message("search.everywhere.type.class.name", code(it)))
stateCheck { checkWordInSearch(it) }
restoreAfterStateBecomeFalse { !checkInsideSearchEverywhere() }
test { type(it) }
}
task(EverythingGlobalScope.getNameText()) {
text(LessonsBundle.message("search.everywhere.use.all.places",
strong(ProjectScope.getProjectFilesScopeName()), strong(it)))
triggerAndFullHighlight().component { _: ActionButtonWithText -> true }
triggerUI().component { button: ActionButtonWithText ->
button.accessibleContext.accessibleName == it
}
showWarning(LessonsBundle.message("search.everywhere.class.popup.closed.warning.message", action("GotoClass"))) {
!checkInsideSearchEverywhere() && focusOwner !is JList<*>
}
test {
invokeActionViaShortcut("ALT P")
}
}
task("QuickJavaDoc") {
text(LessonsBundle.message("search.everywhere.quick.documentation", action(it)))
triggerOnQuickDocumentationPopup()
restoreByUi()
test { actions(it) }
}
task {
text(LessonsBundle.message("search.everywhere.close.documentation.popup", LessonUtil.rawKeyStroke(KeyEvent.VK_ESCAPE)))
stateCheck { previous.ui?.isShowing != true }
test { invokeActionViaShortcut("ENTER") }
}
task {
text(LessonsBundle.message("search.everywhere.finish", action("GotoSymbol"), action("GotoFile")))
}
if (TaskTestContext.inTestMode) task {
stateCheck { focusOwner is EditorComponentImpl }
test {
invokeActionViaShortcut("ESCAPE")
invokeActionViaShortcut("ESCAPE")
}
}
epilogue()
}
override fun onLessonEnd(project: Project, lessonEndInfo: LessonEndInfo) {
restorePopupPosition(project, SearchEverywhereManagerImpl.LOCATION_SETTINGS_KEY, backupPopupLocation)
backupPopupLocation = null
}
open fun LessonContext.epilogue() = Unit
private fun TaskRuntimeContext.checkWordInSearch(expected: String): Boolean =
(focusOwner as? ExtendableTextField)?.text?.equals(expected, ignoreCase = true) == true
private fun TaskRuntimeContext.checkInsideSearchEverywhere(): Boolean {
return UIUtil.getParentOfType(SearchEverywhereUI::class.java, focusOwner) != null
}
override val suitableTips = listOf("SearchEverywhere", "GoToClass", "search_everywhere_general")
override val helpLinks: Map<String, String> get() = mapOf(
Pair(LessonsBundle.message("help.search.everywhere"),
LessonUtil.getHelpLink("searching-everywhere.html")),
)
} | apache-2.0 | 2558aaf2088bd197f191440fb125a0bf | 35.852071 | 140 | 0.712863 | 5.025827 | false | true | false | false |
GunoH/intellij-community | plugins/gitlab/src/org/jetbrains/plugins/gitlab/mergerequest/ui/GitLabToolWindowTabController.kt | 1 | 5967 | // 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.plugins.gitlab.mergerequest.ui
import com.intellij.collaboration.async.collectScoped
import com.intellij.collaboration.messages.CollaborationToolsBundle
import com.intellij.collaboration.ui.CollaborationToolsUIUtil
import com.intellij.collaboration.ui.CollaborationToolsUIUtil.isDefault
import com.intellij.collaboration.ui.util.bindDisabled
import com.intellij.collaboration.ui.util.bindVisibility
import com.intellij.collaboration.util.URIUtil
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.content.Content
import git4idea.remote.hosting.ui.RepositoryAndAccountSelectorComponentFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.jetbrains.plugins.gitlab.api.GitLabApiManager
import org.jetbrains.plugins.gitlab.api.GitLabProjectCoordinates
import org.jetbrains.plugins.gitlab.authentication.GitLabLoginUtil
import org.jetbrains.plugins.gitlab.authentication.accounts.GitLabAccountManager
import org.jetbrains.plugins.gitlab.authentication.ui.GitLabAccountsDetailsProvider
import org.jetbrains.plugins.gitlab.mergerequest.ui.GitLabToolWindowTabViewModel.NestedViewModel
import org.jetbrains.plugins.gitlab.mergerequest.ui.list.GitLabMergeRequestsPanelFactory
import org.jetbrains.plugins.gitlab.util.GitLabBundle
import org.jetbrains.plugins.gitlab.util.GitLabProjectMapping
import java.awt.BorderLayout
import java.awt.event.ActionEvent
import javax.swing.*
internal class GitLabToolWindowTabController(private val project: Project,
scope: CoroutineScope,
tabVm: GitLabToolWindowTabViewModel,
private val content: Content) {
init {
scope.launch {
tabVm.nestedViewModelState.collectScoped { scope, vm ->
content.displayName = GitLabBundle.message("title.merge.requests")
val component = when (vm) {
is NestedViewModel.Selectors -> createSelectorsComponent(scope, vm)
is NestedViewModel.MergeRequests -> createMergeRequestsComponent(scope, vm)
}
CollaborationToolsUIUtil.setComponentPreservingFocus(content, component)
}
}
}
private fun createSelectorsComponent(scope: CoroutineScope, vm: NestedViewModel.Selectors): JComponent {
val accountsDetailsProvider = GitLabAccountsDetailsProvider(scope) {
// TODO: separate loader
service<GitLabAccountManager>().findCredentials(it)?.let(service<GitLabApiManager>()::getClient)
}
val selectorVm = vm.selectorVm
val selectors = RepositoryAndAccountSelectorComponentFactory(selectorVm).create(
scope = scope,
repoNamer = { mapping ->
val allProjects = vm.selectorVm.repositoriesState.value.map { it.repository }
getProjectDisplayName(allProjects, mapping.repository)
},
detailsProvider = accountsDetailsProvider,
accountsPopupActionsSupplier = { createPopupLoginActions(selectorVm, it) },
credsMissingText = GitLabBundle.message("account.token.missing"),
submitActionText = GitLabBundle.message("view.merge.requests.button"),
loginButtons = createLoginButtons(scope, selectorVm)
)
scope.launch {
selectorVm.loginRequestsFlow.collect { req ->
val account = req.account
if (account == null) {
val (newAccount, token) = GitLabLoginUtil.logInViaToken(project, selectors, req.repo.repository.serverPath) { server, name ->
req.accounts.none { it.server == server || it.name == name }
} ?: return@collect
req.login(newAccount, token)
}
else {
val token = GitLabLoginUtil.updateToken(project, selectors, account) { server, name ->
req.accounts.none { it.server == server || it.name == name }
} ?: return@collect
req.login(account, token)
}
}
}
return JPanel(BorderLayout()).apply {
add(selectors, BorderLayout.NORTH)
}
}
private fun createMergeRequestsComponent(scope: CoroutineScope, vm: NestedViewModel.MergeRequests): JComponent =
GitLabMergeRequestsPanelFactory().create(scope, vm.listVm)
private fun createLoginButtons(scope: CoroutineScope, vm: GitLabRepositoryAndAccountSelectorViewModel)
: List<JButton> {
return listOf(
JButton(CollaborationToolsBundle.message("login.button")).apply {
isDefault = true
isOpaque = false
addActionListener {
vm.requestTokenLogin(false, true)
}
bindDisabled(scope, vm.busyState)
bindVisibility(scope, vm.tokenLoginAvailableState)
}
)
}
private fun createPopupLoginActions(vm: GitLabRepositoryAndAccountSelectorViewModel, mapping: GitLabProjectMapping?): List<Action> {
if (mapping == null) return emptyList()
return listOf(object : AbstractAction(CollaborationToolsBundle.message("login.button")) {
override fun actionPerformed(e: ActionEvent?) {
vm.requestTokenLogin(true, false)
}
})
}
private fun getProjectDisplayName(allProjects: List<GitLabProjectCoordinates>, project: GitLabProjectCoordinates): @NlsSafe String {
val showServer = needToShowServer(allProjects)
val builder = StringBuilder()
if (showServer) builder.append(URIUtil.toStringWithoutScheme(project.serverPath.toURI())).append("/")
builder.append(project.projectPath.owner).append("/")
builder.append(project.projectPath.name)
return builder.toString()
}
private fun needToShowServer(projects: List<GitLabProjectCoordinates>): Boolean {
if (projects.size <= 1) return false
val firstServer = projects.first().serverPath
return projects.any { it.serverPath != firstServer }
}
} | apache-2.0 | 459198b835573c83e519960cc446a69e | 42.562044 | 135 | 0.734372 | 4.812097 | false | false | false | false |
PhoenixDevTeam/Phoenix-for-VK | app/src/main/java/biz/dealnote/messenger/model/PeerUpdate.kt | 1 | 468 | package biz.dealnote.messenger.model
class PeerUpdate(val accountId: Int, val peerId: Int) {
var readIn: Read? = null
var readOut: Read? = null
var lastMessage: LastMessage? = null
var unread: Unread? = null
var pin: Pin? = null
var title: Title? = null
class Read (val messageId: Int)
class Unread(val count: Int)
class LastMessage(val messageId: Int)
class Pin(val pinned: Message?)
class Title(val title: String?)
} | gpl-3.0 | fd51a5b0a951f9b163b6f709691ce2ed | 22.45 | 55 | 0.666667 | 3.714286 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/utils/CommonUtils.kt | 1 | 2608 | /*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* 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.zwq65.unity.utils
import android.app.ProgressDialog
import android.content.Context
import android.content.pm.ApplicationInfo
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import com.zwq65.unity.R
import java.io.File
/**
* ================================================
*
* Created by NIRVANA on 2017/01/27
* Contact with <[email protected]>
* ================================================
*/
object CommonUtils {
val imageStorePath: String
get() {
var path: String = if (getSdCardIsEnable()) {
getSdCardPath()
} else {
getDataAbsolutePath()
}
path = path + "Unity" + File.separator + "image" + File.separator
return path
}
fun showLoadingDialog(context: Context): ProgressDialog {
val progressDialog = ProgressDialog(context)
progressDialog.show()
if (progressDialog.window != null) {
progressDialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
}
progressDialog.setContentView(R.layout.progress_dialog)
progressDialog.isIndeterminate = true
progressDialog.setCancelable(false)
progressDialog.setCanceledOnTouchOutside(false)
return progressDialog
}
/**
* 判断当前应用是否是debug状态
*/
fun isApkInDebug(context: Context): Boolean {
return try {
val info = context.applicationInfo
info.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
} catch (e: Exception) {
false
}
}
/**
* 用于取得recycleView当前最大的position以判断是否许需要加载
*
* @param lastPositions recycleView底部的position数组
* @return 最大的position
*/
fun findMax(lastPositions: IntArray): Int {
return lastPositions.max() ?: lastPositions[0]
}
}
| apache-2.0 | 756c82779de026b521725bad7982c145 | 29.142857 | 91 | 0.628752 | 4.612022 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/variables/types/SelectType.kt | 1 | 3491 | package ch.rmy.android.http_shortcuts.variables.types
import android.content.Context
import ch.rmy.android.framework.extensions.addOrRemove
import ch.rmy.android.framework.extensions.runFor
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.dagger.ApplicationComponent
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableRepository
import ch.rmy.android.http_shortcuts.data.models.VariableModel
import ch.rmy.android.http_shortcuts.extensions.showOrElse
import ch.rmy.android.http_shortcuts.utils.ActivityProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import javax.inject.Inject
import kotlin.coroutines.resume
class SelectType : BaseVariableType() {
@Inject
lateinit var variablesRepository: VariableRepository
@Inject
lateinit var activityProvider: ActivityProvider
override fun inject(applicationComponent: ApplicationComponent) {
applicationComponent.inject(this)
}
override suspend fun resolveValue(context: Context, variable: VariableModel): String {
val value = withContext(Dispatchers.Main) {
suspendCancellableCoroutine<String> { continuation ->
createDialogBuilder(activityProvider.getActivity(), variable, continuation)
.run {
if (isMultiSelect(variable)) {
val selectedOptions = mutableListOf<String>()
runFor(variable.options!!) { option ->
checkBoxItem(name = option.labelOrValue, checked = { option.id in selectedOptions }) { isChecked ->
selectedOptions.addOrRemove(option.id, isChecked)
}
}
.positive(R.string.dialog_ok) {
continuation.resume(
selectedOptions
.mapNotNull { optionId ->
variable.options!!.find { it.id == optionId }
}
.joinToString(getSeparator(variable)) { option ->
option.value
}
)
}
} else {
runFor(variable.options!!) { option ->
item(name = option.labelOrValue) {
continuation.resume(option.value)
}
}
}
}
.showOrElse {
continuation.cancel()
}
}
}
if (variable.rememberValue) {
variablesRepository.setVariableValue(variable.id, value)
}
return value
}
companion object {
const val KEY_MULTI_SELECT = "multi_select"
const val KEY_SEPARATOR = "separator"
fun isMultiSelect(variable: VariableModel) =
variable.dataForType[KEY_MULTI_SELECT]?.toBoolean() ?: false
fun getSeparator(variable: VariableModel) =
variable.dataForType[KEY_SEPARATOR] ?: ","
}
}
| mit | 7ecf5ee335d9ffb6046b837ef823a60d | 41.573171 | 131 | 0.536522 | 6.071304 | false | false | false | false |
breadwallet/breadwallet-android | app-core/src/main/java/com/breadwallet/tools/crypto/CryptoHelper.kt | 1 | 4433 | /**
* BreadWallet
*
* Created by Mihail Gutan <[email protected]> on 11/28/16.
* Copyright (c) 2016 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.tools.crypto
import android.text.format.DateUtils
import com.breadwallet.crypto.Coder
import com.breadwallet.crypto.Hasher
import com.breadwallet.crypto.Key
import com.breadwallet.crypto.Signer
import java.nio.ByteBuffer
import java.nio.ByteOrder
@Suppress("TooManyFunctions")
object CryptoHelper {
private const val NONCE_SIZE = 12
private val base58: Coder by lazy {
Coder.createForAlgorithm(Coder.Algorithm.BASE58)
}
private val sha256: Hasher by lazy {
Hasher.createForAlgorithm(Hasher.Algorithm.SHA256)
}
private val sha256_2: Hasher by lazy {
Hasher.createForAlgorithm(Hasher.Algorithm.SHA256_2)
}
private val md5: Hasher by lazy {
Hasher.createForAlgorithm(Hasher.Algorithm.MD5)
}
private val keccak256: Hasher by lazy {
Hasher.createForAlgorithm(Hasher.Algorithm.KECCAK256)
}
private val compact: Signer by lazy {
Signer.createForAlgorithm(Signer.Algorithm.COMPACT)
}
private val jose: Signer by lazy {
Signer.createForAlgorithm(Signer.Algorithm.BASIC_JOSE)
}
private val basicDer: Signer by lazy {
Signer.createForAlgorithm(Signer.Algorithm.BASIC_DER)
}
private val hex: Coder by lazy {
Coder.createForAlgorithm(Coder.Algorithm.HEX)
}
@JvmStatic
fun hexEncode(data: ByteArray): String {
return hex.encode(data).or("")
}
@JvmStatic
fun hexDecode(data: String): ByteArray? {
return hex.decode(data).orNull()
}
fun signCompact(data: ByteArray, key: Key): ByteArray {
return compact.sign(data, key).or(byteArrayOf())
}
fun signJose(data: ByteArray, key: Key): ByteArray {
return jose.sign(data, key).or(byteArrayOf())
}
fun signBasicDer(data: ByteArray, key: Key): ByteArray {
return basicDer.sign(data, key).or(byteArrayOf())
}
fun base58Encode(data: ByteArray): String {
return base58.encode(data).or("")
}
fun base58Decode(data: String): ByteArray {
return base58.decode(data).or(byteArrayOf())
}
@JvmStatic
fun base58ofSha256(toEncode: ByteArray): String {
val sha256First = sha256(toEncode)
return base58.encode(sha256First).or("")
}
@JvmStatic
fun doubleSha256(data: ByteArray): ByteArray? {
return sha256_2.hash(data).orNull()
}
@JvmStatic
fun sha256(data: ByteArray?): ByteArray? {
return sha256.hash(data).orNull()
}
@JvmStatic
fun md5(data: ByteArray): ByteArray? {
return md5.hash(data).orNull()
}
fun keccak256(data: ByteArray): ByteArray? {
return keccak256.hash(data).orNull()
}
/**
* generate a nonce using microseconds-since-epoch
*/
@JvmStatic
@Suppress("MagicNumber")
fun generateRandomNonce(): ByteArray {
val nonce = ByteArray(NONCE_SIZE)
val buffer = ByteBuffer.allocate(8)
val t = System.nanoTime() / DateUtils.SECOND_IN_MILLIS
buffer.order(ByteOrder.LITTLE_ENDIAN)
buffer.putLong(t)
val byteTime = buffer.array()
System.arraycopy(byteTime, 0, nonce, 4, byteTime.size)
return nonce
}
}
| mit | 75864ded71082a82e60b42baaae9e01f | 29.156463 | 80 | 0.685766 | 4.162441 | false | false | false | false |
dscoppelletti/spaceship | lib/src/main/kotlin/it/scoppelletti/spaceship/widget/DefaultExceptionItem.kt | 1 | 2441 | /*
* Copyright (C) 2018 Dario Scoppelletti, <http://www.scoppelletti.it/>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("JoinDeclarationAndAssignment", "RedundantVisibilityModifier")
package it.scoppelletti.spaceship.widget
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import it.scoppelletti.spaceship.R
import it.scoppelletti.spaceship.toMessage
import kotlinx.parcelize.Parcelize
/**
* Default implementation of the `ExceptionItem` interface.
*
* @since 1.0.0
*
* @property className Name of the exception class.
* @property message Message.
*/
@Parcelize
public data class DefaultExceptionItem(
public val className: String,
public val message: String,
override val adapter: ExceptionAdapter<*>
) : ExceptionItem
/**
* Default implementation of the `ExceptionAdapter` interface.
*
* @since 1.0.0
*/
@Parcelize
public class DefaultExceptionAdapter : ExceptionAdapter<DefaultExceptionItem> {
override fun getView(ex: DefaultExceptionItem, parent: ViewGroup): View {
val itemView: View
val inflater: LayoutInflater
var textView: TextView
inflater = LayoutInflater.from(parent.context)
itemView = inflater.inflate(R.layout.it_scoppelletti_exception, parent,
false)
textView = itemView.findViewById(R.id.txtClass)
textView.text = ex.className
textView = itemView.findViewById(R.id.txtMessage)
textView.text = ex.message
return itemView
}
}
/**
* Default implementation of the `ExceptionMapper` interface.
*
* @since 1.0.0
*/
public class DefaultExceptionMapperHandler : ExceptionMapperHandler<Throwable> {
override fun map(ex: Throwable) : ExceptionItem =
DefaultExceptionItem(ex.javaClass.name,
ex.toMessage(), DefaultExceptionAdapter())
}
| apache-2.0 | 81a508f00b75f18c00fcc2d5579f40b3 | 29.135802 | 80 | 0.722245 | 4.390288 | false | false | false | false |
quran/quran_android | app/src/main/java/com/quran/labs/androidquran/util/AudioUtils.kt | 2 | 7953 | package com.quran.labs.androidquran.util
import android.content.Context
import android.content.Intent
import androidx.annotation.VisibleForTesting
import com.quran.data.core.QuranInfo
import com.quran.data.model.SuraAyah
import com.quran.data.model.audio.Qari
import com.quran.labs.androidquran.common.audio.model.QariItem
import com.quran.labs.androidquran.common.audio.util.QariUtil
import com.quran.labs.androidquran.service.AudioService
import java.io.File
import java.util.Locale
import javax.inject.Inject
import timber.log.Timber
class AudioUtils @Inject constructor(
private val quranInfo: QuranInfo,
private val quranFileUtils: QuranFileUtils,
private val qariUtil: QariUtil
) {
private val totalPages = quranInfo.numberOfPages
internal object LookAheadAmount {
const val PAGE = 1
const val SURA = 2
const val JUZ = 3
// make sure to update these when a lookup type is added
const val MIN = 1
const val MAX = 3
}
/**
* Get a list of QariItem representing the qaris to show
*
* This removes gapped qaris that have a gapless alternative if
* no files are downloaded for that qari.
*
* This list sorts gapless qaris before gapped qaris, with each
* set being alphabetically sorted.
*/
fun getQariList(context: Context): List<QariItem> {
return qariUtil.getQariList(context)
.filter {
it.isGapless || (it.hasGaplessAlternative && !haveAnyFiles(it.path))
}
.sortedWith { lhs, rhs ->
if (lhs.isGapless != rhs.isGapless) {
if (lhs.isGapless) -1 else 1
} else {
lhs.name.compareTo(rhs.name)
}
}
}
private fun haveAnyFiles(path: String): Boolean {
val basePath = quranFileUtils.audioFileDirectory()
val file = File(basePath, path)
return file.isDirectory && file.list()?.isNotEmpty() ?: false
}
fun getQariUrl(qari: Qari): String {
return qari.url + if (qari.isGapless) {
"%03d$AUDIO_EXTENSION"
} else {
"%03d%03d$AUDIO_EXTENSION"
}
}
fun getQariUrl(item: QariItem): String {
return item.url + if (item.isGapless) {
"%03d$AUDIO_EXTENSION"
} else {
"%03d%03d$AUDIO_EXTENSION"
}
}
fun getLocalQariUrl(item: QariItem): String? {
val rootDirectory = quranFileUtils.audioFileDirectory()
return if (rootDirectory == null) null else rootDirectory + item.path
}
fun getLocalQariUri(item: QariItem): String? {
val rootDirectory = quranFileUtils.audioFileDirectory()
return if (rootDirectory == null) null else
rootDirectory + item.path + File.separator + if (item.isGapless) {
"%03d$AUDIO_EXTENSION"
} else {
"%d" + File.separator + "%d" + AUDIO_EXTENSION
}
}
fun getQariDatabasePathIfGapless(item: QariItem): String? {
var databaseName = item.databaseName
if (databaseName != null) {
val path = getLocalQariUrl(item)
if (path != null) {
databaseName = path + File.separator + databaseName + DB_EXTENSION
}
}
return databaseName
}
fun getLastAyahToPlay(
startAyah: SuraAyah,
currentPage: Int,
mode: Int,
isDualPageVisible: Boolean
): SuraAyah? {
val page =
if (isDualPageVisible &&
mode == LookAheadAmount.PAGE &&
currentPage % 2 == 1
) {
// if we download page by page and we are currently in tablet mode
// and playing from the right page, get the left page as well.
currentPage + 1
} else {
currentPage
}
var pageLastSura = 114
var pageLastAyah = 6
// page < 0 - intentional, because nextPageAyah looks up the ayah on the next page
if (page > totalPages || page < 0) {
return null
}
if (mode == LookAheadAmount.SURA) {
val sura = startAyah.sura
val lastAyah = quranInfo.getNumberOfAyahs(sura)
if (lastAyah == -1) {
return null
}
return SuraAyah(sura, lastAyah)
} else if (mode == LookAheadAmount.JUZ) {
val juz = quranInfo.getJuzFromPage(page)
if (juz == 30) {
return SuraAyah(114, 6)
} else if (juz in 1..29) {
val endJuz = quranInfo.getQuarterByIndex(juz * 8)
if (pageLastSura > endJuz.sura) {
// ex between jathiya and a7qaf
return getQuarterForNextJuz(juz)
} else if (pageLastSura == endJuz.sura && pageLastAyah > endJuz.ayah) {
// ex surat al anfal
return getQuarterForNextJuz(juz)
}
return SuraAyah(endJuz.sura, endJuz.ayah)
}
} else {
val range = quranInfo.getVerseRangeForPage(page)
pageLastSura = range.endingSura
pageLastAyah = range.endingAyah
}
// page mode (fallback also from errors above)
return SuraAyah(pageLastSura, pageLastAyah)
}
private fun getQuarterForNextJuz(currentJuz: Int): SuraAyah {
return if (currentJuz < 29) {
val juz = quranInfo.getQuarterByIndex((currentJuz + 1) * 8)
SuraAyah(juz.sura, juz.ayah)
} else {
// if we're currently at the 29th juz', just return the end of the 30th.
SuraAyah(114, 6)
}
}
fun shouldDownloadBasmallah(
baseDirectory: String,
start: SuraAyah,
end: SuraAyah,
isGapless: Boolean
): Boolean {
if (isGapless) {
return false
}
if (baseDirectory.isNotEmpty()) {
var f = File(baseDirectory)
if (f.exists()) {
val filename = 1.toString() + File.separator + 1 + AUDIO_EXTENSION
f = File(baseDirectory + File.separator + filename)
if (f.exists()) {
Timber.d("already have basmalla...")
return false
}
} else {
f.mkdirs()
}
}
return doesRequireBasmallah(start, end)
}
@VisibleForTesting
fun doesRequireBasmallah(minAyah: SuraAyah, maxAyah: SuraAyah): Boolean {
Timber.d("seeing if need basmalla...")
for (i in minAyah.sura..maxAyah.sura) {
val firstAyah: Int = if (i == minAyah.sura) {
minAyah.ayah
} else {
1
}
if (firstAyah == 1 && i != 1 && i != 9) {
return true
}
}
return false
}
fun haveAllFiles(
baseUrl: String,
path: String,
start: SuraAyah,
end: SuraAyah,
isGapless: Boolean
): Boolean {
if (path.isEmpty()) {
return false
}
var f = File(path)
if (!f.exists()) {
f.mkdirs()
return false
}
val startSura = start.sura
val startAyah = start.ayah
val endSura = end.sura
val endAyah = end.ayah
if (endSura < startSura || endSura == startSura && endAyah < startAyah) {
throw IllegalStateException(
"End isn't larger than the start: $startSura:$startAyah to $endSura:$endAyah"
)
}
for (i in startSura..endSura) {
val lastAyah = if (i == endSura) {
endAyah
} else {
quranInfo.getNumberOfAyahs(i)
}
val firstAyah = if (i == startSura) {
startAyah
} else {
1
}
if (isGapless) {
if (i == endSura && endAyah == 0) {
continue
}
val fileName = String.format(Locale.US, baseUrl, i)
Timber.d("gapless, checking if we have %s", fileName)
f = File(fileName)
if (!f.exists()) {
return false
}
continue
}
Timber.d("not gapless, checking each ayah...")
for (j in firstAyah..lastAyah) {
val filename = i.toString() + File.separator + j + AUDIO_EXTENSION
f = File(path + File.separator + filename)
if (!f.exists()) {
return false
}
}
}
return true
}
fun getAudioIntent(context: Context, action: String): Intent {
return Intent(context, AudioService::class.java).apply {
setAction(action)
}
}
companion object {
const val ZIP_EXTENSION = ".zip"
const val AUDIO_EXTENSION = ".mp3"
private const val DB_EXTENSION = ".db"
}
}
| gpl-3.0 | f641cfae28a9e800c2bd998fc02e7e85 | 25.598662 | 86 | 0.615868 | 4.022762 | false | false | false | false |
duftler/clouddriver | clouddriver-saga/src/main/kotlin/com/netflix/spinnaker/clouddriver/saga/models/Saga.kt | 1 | 5292 | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.clouddriver.saga.models
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.google.common.annotations.VisibleForTesting
import com.netflix.spinnaker.clouddriver.saga.SagaCommand
import com.netflix.spinnaker.clouddriver.saga.SagaCommandCompleted
import com.netflix.spinnaker.clouddriver.saga.SagaCompleted
import com.netflix.spinnaker.clouddriver.saga.SagaEvent
import com.netflix.spinnaker.clouddriver.saga.SagaLogAppended
import com.netflix.spinnaker.clouddriver.saga.SagaRollbackStarted
import com.netflix.spinnaker.clouddriver.saga.exceptions.SagaStateIntegrationException
import com.netflix.spinnaker.clouddriver.saga.exceptions.SagaSystemException
import com.netflix.spinnaker.kork.annotations.Beta
import org.slf4j.LoggerFactory
/**
* The primary domain model of the Saga framework.
*
* @param name The name of the Saga type. This should be shared across all same-type Sagas (e.g. aws deploys)
* @param id The Saga instance ID
* @param sequence An internal counter used for tracking a Saga's position in an event log
*/
@Beta
class Saga(
val name: String,
val id: String,
private var sequence: Long = 0
) {
constructor(name: String, id: String) : this(name, id, 0)
private val log by lazy { LoggerFactory.getLogger(javaClass) }
private val events: MutableList<SagaEvent> = mutableListOf()
private val pendingEvents: MutableList<SagaEvent> = mutableListOf()
internal fun complete(success: Boolean = true) {
addEvent(SagaCompleted(success))
}
fun isComplete(): Boolean = events.filterIsInstance<SagaCompleted>().isNotEmpty()
fun isCompensating(): Boolean = events.filterIsInstance<SagaRollbackStarted>().isNotEmpty()
fun getVersion(): Long {
return events.map { it.getMetadata().originatingVersion }.max()?.let { it + 1 } ?: 0
}
fun addEvent(event: SagaEvent) {
this.pendingEvents.add(event)
}
@Suppress("UNCHECKED_CAST")
fun <T : SagaEvent> getEvent(clazz: Class<T>): T {
return events.reversed()
.filter { clazz.isAssignableFrom(it.javaClass) }
.let {
when (it.size) {
0 -> throw SagaStateIntegrationException.typeNotFound(clazz, this)
1 -> it.first() as T
else -> throw SagaStateIntegrationException.tooManyResults(clazz, this)
}
}
}
@Suppress("UNCHECKED_CAST")
fun <T : SagaEvent> getEvent(clazz: Class<T>, reducer: (List<T>) -> T): T {
return events.reversed()
.filter { clazz.isAssignableFrom(it.javaClass) }
.let {
when (it.size) {
0 -> throw SagaStateIntegrationException.typeNotFound(clazz, this)
1 -> it.first()
else -> reducer(it as List<T>)
} as T
}
}
internal fun completed(command: Class<SagaCommand>): Boolean {
return getEvents().filterIsInstance<SagaCommandCompleted>().any { it.matches(command) }
}
internal fun getNextCommand(requiredCommand: Class<SagaCommand>): SagaCommand? {
return getEvents()
.filterIsInstance<SagaCommand>()
.filterNot { completed(it.javaClass) }
.firstOrNull { requiredCommand.isAssignableFrom(it.javaClass) }
}
internal fun hasUnappliedCommands(): Boolean {
return getEvents().plus(pendingEvents)
.filterIsInstance<SagaCommand>()
.filterNot { completed(it.javaClass) }
.any()
}
@VisibleForTesting
fun addEventForTest(event: SagaEvent) {
this.events.add(event)
}
internal fun hydrateEvents(events: List<SagaEvent>) {
if (this.events.isEmpty()) {
this.events.addAll(events)
}
}
fun getSequence(): Long = sequence
internal fun setSequence(appliedEventVersion: Long) {
if (sequence > appliedEventVersion) {
throw SagaSystemException("Attempted to set Saga sequence to an event version in the past " +
"(current: $sequence, applying: $appliedEventVersion)")
}
sequence = appliedEventVersion
}
@JsonIgnoreProperties("saga")
fun getEvents(): List<SagaEvent> {
return events.toList()
}
@JsonIgnore
@VisibleForTesting
fun getPendingEvents(flush: Boolean = true): List<SagaEvent> {
val pending = mutableListOf<SagaEvent>()
pending.addAll(pendingEvents)
if (flush) {
pendingEvents.clear()
}
return pending.toList()
}
fun log(message: String) {
addEvent(SagaLogAppended(
SagaLogAppended.Message(message, null),
null
))
}
fun log(message: String, vararg replacements: Any?) {
log(String.format(message, *replacements))
}
fun getLogs(): List<String> {
return events.filterIsInstance<SagaLogAppended>().mapNotNull { it.message.user }
}
}
| apache-2.0 | 5450383771b1a00d693c0475bad6b862 | 31.268293 | 109 | 0.713341 | 4.271186 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/impact/impactinfocollection/MutatedGeneWithContext.kt | 1 | 1309 | package org.evomaster.core.search.impact.impactinfocollection
import org.evomaster.core.search.gene.Gene
/**
* this can be used to represent a mutated gene in detail, including
* @property current gene after mutation
* @property previous gene before mutation
* @property action refers to an action which contains the gene
* @property position indicates where the gene located in a view of an individual, e.g., index of action
* @property actionLocalId indicates the local id of the action
* @property isDynamicAction indicates whether the action belongs to [Individual.seeDynamicMainActions]
*/
class MutatedGeneWithContext (
val current : Gene,
val action : String = NO_ACTION,
val position : Int? = null,
val actionLocalId : String = NO_ACTION,
val isDynamicAction: Boolean = false,
val previous : Gene?,
val numOfMutatedGene: Int = 1
){
companion object{
const val NO_ACTION = "NONE"
}
fun mainPosition(current: Gene, previous: Gene?, numOfMutatedGene: Int) : MutatedGeneWithContext{
return MutatedGeneWithContext(current = current, previous = previous,action = this.action, position = this.position, actionLocalId = actionLocalId, isDynamicAction = isDynamicAction, numOfMutatedGene = numOfMutatedGene)
}
} | lgpl-3.0 | fa5638461e79ec888b1a9c1fecef3329 | 42.666667 | 227 | 0.729565 | 4.742754 | false | false | false | false |
Yorxxx/played-next-kotlin | app/src/test/java/com/piticlistudio/playednext/data/repository/datasource/room/platform/RoomGamePlatformRepositoryImplTest.kt | 1 | 7521 | package com.piticlistudio.playednext.data.repository.datasource.room.platform
import com.nhaarman.mockito_kotlin.*
import com.piticlistudio.playednext.data.entity.mapper.datasources.platform.RoomPlatformMapper
import com.piticlistudio.playednext.domain.model.Platform
import com.piticlistudio.playednext.test.factory.PlatformFactory.Factory.makePlatform
import com.piticlistudio.playednext.test.factory.PlatformFactory.Factory.makeRoomPlatform
import io.reactivex.Flowable
import io.reactivex.Single
import io.reactivex.observers.TestObserver
import io.reactivex.subscribers.TestSubscriber
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
internal class RoomGamePlatformRepositoryImplTest {
@Nested
@DisplayName("Given a RoomGamePlatformRepositoryImpl instance")
inner class Instance {
private lateinit var repository: RoomGamePlatformRepositoryImpl
private val dao: RoomGamePlatformService = mock()
private val mapper: RoomPlatformMapper = mock()
@BeforeEach
internal fun setUp() {
reset(dao, mapper)
repository = RoomGamePlatformRepositoryImpl(dao, mapper)
}
@Nested
@DisplayName("When we call load")
inner class LoadCalled {
private var observer: TestSubscriber<Platform>? = null
private val source = makeRoomPlatform()
private val result = makePlatform()
@BeforeEach
internal fun setUp() {
whenever(dao.find(10)).thenReturn(Flowable.just(source))
whenever(mapper.mapFromDataLayer(source)).thenReturn(result)
observer = repository.load(10).test()
}
@Test
@DisplayName("Then should request dao service")
fun shouldRequestRepository() {
verify(dao).find(10)
}
@Test
@DisplayName("Then should map response")
fun shouldMap() {
verify(mapper).mapFromDataLayer(source)
}
@Test
@DisplayName("Then should emit without errors")
fun withoutErrors() {
assertNotNull(observer)
observer?.apply {
assertNoErrors()
assertComplete()
assertValueCount(1)
assertValue(result)
}
}
}
@Nested
@DisplayName("When we call loadForGame")
inner class LoadForGameCalled {
private var observer: TestSubscriber<List<Platform>>? = null
private val source = makeRoomPlatform()
private val result = makePlatform()
@BeforeEach
internal fun setUp() {
whenever(dao.findForGame(10)).thenReturn(Flowable.just(listOf(source)))
whenever(mapper.mapFromDataLayer(source)).thenReturn(result)
observer = repository.loadForGame(10).test()
}
@Test
@DisplayName("Then should request dao service")
fun shouldRequestRepository() {
verify(dao).findForGame(10)
}
@Test
@DisplayName("Then should map response")
fun shouldMap() {
verify(mapper).mapFromDataLayer(source)
}
@Test
@DisplayName("Then should emit without errors")
fun withoutErrors() {
assertNotNull(observer)
observer?.apply {
assertNoErrors()
assertComplete()
assertValueCount(1)
assertValue { it.size == 1 && it.contains(result) }
}
}
}
@Nested
@DisplayName("When we call saveForGame")
inner class SaveForGameCalled {
private var observer: TestObserver<Void>? = null
private val source = makePlatform()
private val result = makeRoomPlatform()
@BeforeEach
internal fun setUp() {
whenever(mapper.mapIntoDataLayerModel(source)).thenReturn(result)
whenever(dao.insert(result)).thenReturn(10)
whenever(dao.insertGamePlatform(any())).thenReturn(10)
observer = repository.saveForGame(10, source).test()
}
@Test
@DisplayName("Then should save company")
fun shouldSaveCompany() {
verify(dao).insert(result)
}
@Test
@DisplayName("Then should save relation")
fun shouldRequestDao() {
verify(dao).insertGamePlatform(com.nhaarman.mockito_kotlin.check {
assertEquals(it.platformId, source.id)
assertEquals(it.gameId, 10)
})
}
@Test
@DisplayName("Then should emit without errors")
fun withoutErrors() {
assertNotNull(observer)
observer?.apply {
assertNoErrors()
assertComplete()
assertNoValues()
}
}
@Nested
@DisplayName("And Room fails to save platform")
inner class RoomFail {
@BeforeEach
internal fun setUp() {
reset(dao, mapper)
whenever(dao.insert(result)).thenReturn(-1)
observer = repository.saveForGame(10, source).test()
}
@Test
@DisplayName("Then should emit error")
fun emitsError() {
assertNotNull(observer)
observer?.apply {
assertNoValues()
assertError(PlatformSaveException::class.java)
assertNotComplete()
}
}
@Test
@DisplayName("Then should not save RoomGameGenre")
fun shouldNotSaveGameDeveloper() {
verify(dao, never()).insertGamePlatform(any())
}
}
@Nested
@DisplayName("And Room fails to save gamePlatform")
inner class RoomPlatformFail {
@BeforeEach
internal fun setUp() {
reset(dao)
whenever(dao.insert(result)).thenReturn(10)
whenever(dao.insertGamePlatform(any())).thenReturn(-1)
observer = repository.saveForGame(10, source).test()
}
@Test
@DisplayName("Then should emit error")
fun emitsError() {
assertNotNull(observer)
observer?.apply {
assertNoValues()
assertError(GamePlatformSaveException::class.java)
assertNotComplete()
}
}
@Test
@DisplayName("Then should have saved platform")
fun shouldHaveSavedCompany() {
verify(dao).insert(result)
}
}
}
}
} | mit | 4216d5c0590fa45ea403e7440e368625 | 33.347032 | 94 | 0.53929 | 5.871194 | false | true | false | false |
google-developer-training/basic-android-kotlin-compose-training-mars-photos | app/src/main/java/com/example/marsphotos/ui/theme/Theme.kt | 1 | 1513 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.marsphotos.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
private val DarkColorPalette = darkColors(
primary = Purple200,
primaryVariant = Purple700,
secondary = Teal200
)
private val LightColorPalette = lightColors(
primary = Purple500,
primaryVariant = Purple700,
secondary = Teal200
)
@Composable
fun MarsPhotosTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
}
| apache-2.0 | 2542883cd01a287d32d5a67c57ee42d4 | 28.096154 | 75 | 0.724389 | 4.52994 | false | false | false | false |
kaltura/playkit-android | playkit/src/main/java/com/kaltura/playkit/plugins/playback/PlaybackUtils.kt | 1 | 2361 | package com.kaltura.playkit.plugins.playback
import com.kaltura.playkit.PKRequestParams
import com.kaltura.playkit.PlayKitManager
import com.kaltura.playkit.Utils
class PlaybackUtils {
companion object {
@JvmStatic
fun getPKRequestParams(requestParams: PKRequestParams,
playSessionId: String?, applicationName: String?,
httpHeaders: Map<String?, String?>?): PKRequestParams {
val url = requestParams.url
url?.let {
it.path?.let { path ->
if (path.contains("/playManifest/")) {
var alt = url.buildUpon()
.appendQueryParameter("clientTag", PlayKitManager.CLIENT_TAG)
.appendQueryParameter("playSessionId", playSessionId).build()
if (!applicationName.isNullOrEmpty()) {
alt = alt.buildUpon().appendQueryParameter("referrer", Utils.toBase64(applicationName.toByteArray())).build()
}
val lastPathSegment = requestParams.url.lastPathSegment
if (!lastPathSegment.isNullOrEmpty() && lastPathSegment.endsWith(".wvm")) {
// in old android device it will not play wvc if url is not ended in wvm
alt = alt.buildUpon().appendQueryParameter("name", lastPathSegment).build()
}
setCustomHeaders(requestParams, httpHeaders)
return PKRequestParams(alt, requestParams.headers)
}
}
}
setCustomHeaders(requestParams, httpHeaders)
return requestParams
}
private fun setCustomHeaders(requestParams: PKRequestParams, httpHeaders: Map<String?, String?>?) {
httpHeaders?.let { header ->
if (header.isNotEmpty()) {
header.forEach { (key, value) ->
key?.let { requestKey ->
value?.let { requestValue ->
requestParams.headers[requestKey] = requestValue
}
}
}
}
}
}
}
}
| agpl-3.0 | e00b77e1d1dc7e7199b11377f140a19e | 41.927273 | 137 | 0.506989 | 6.229551 | false | false | false | false |
sunghwanJo/workshop-jb | src/ii_collections/_21_Partition_.kt | 1 | 660 | package ii_collections
fun example8() {
val numbers = listOf(1, 3, -4, 2, -11)
// The details (how multi-assignment works) will be explained later in the 'Conventions' task
val (positive, negative) = numbers.partition { it > 0 }
positive == listOf(1, 3, 2)
negative == listOf(-4, -11)
}
fun Shop.getCustomersWithMoreUndeliveredOrdersThanDelivered(): Set<Customer> {
// Return customers who have more undelivered orders than delivered
return customers.filter {
val (deliveredCustomer, undeliveredCustomer) = it.orders.partition { it.isDelivered }
undeliveredCustomer.size > deliveredCustomer.size
}.toSet()
}
| mit | 93bcb1bcbfa061e03ef6349094043406 | 33.736842 | 97 | 0.698485 | 4.099379 | false | false | false | false |
Edward608/RxBinding | rxbinding-kotlin/src/main/kotlin/com/jakewharton/rxbinding2/widget/RxSeekBar.kt | 2 | 1676 | @file:Suppress(
names = "NOTHING_TO_INLINE"
)
package com.jakewharton.rxbinding2.widget
import android.widget.SeekBar
import com.jakewharton.rxbinding2.InitialValueObservable
import kotlin.Int
import kotlin.Suppress
/**
* Create an observable of progress value changes on `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Note:* A value will be emitted immediately on subscribe.
*/
inline fun SeekBar.changes(): InitialValueObservable<Int> = RxSeekBar.changes(this)
/**
* Create an observable of progress value changes on `view` that were made only from the
* user.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Note:* A value will be emitted immediately on subscribe.
*/
inline fun SeekBar.userChanges(): InitialValueObservable<Int> = RxSeekBar.userChanges(this)
/**
* Create an observable of progress value changes on `view` that were made only from the
* system.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Note:* A value will be emitted immediately on subscribe.
*/
inline fun SeekBar.systemChanges(): InitialValueObservable<Int> = RxSeekBar.systemChanges(this)
/**
* Create an observable of progress change events for `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Note:* A value will be emitted immediately on subscribe.
*/
inline fun SeekBar.changeEvents(): InitialValueObservable<SeekBarChangeEvent> = RxSeekBar.changeEvents(this)
| apache-2.0 | ba826242dbddf53c4e7556e4ee6075c6 | 31.230769 | 108 | 0.749403 | 4.19 | false | false | false | false |
arcao/Geocaching4Locus | geocaching-api/src/main/java/com/arcao/geocaching4locus/data/api/util/ReferenceCode.kt | 1 | 4374 | package com.arcao.geocaching4locus.data.api.util
import java.util.Locale
/**
* Helper functions to convert string reference code to numeric reference id and vice versa.
*/
object ReferenceCode {
private const val BASE_31_CHARS = "0123456789ABCDEFGHJKMNPQRTVWXYZ"
// = (16 * 31 * 31 * 31) - (16 * 16 * 16 * 16)
private const val REFERENCE_CODE_BASE31_MAGIC_NUMBER: Long = 411120
const val GEOCACHE_PREFIX = "GC"
private const val REFERENCE_CODE_BASE16_MAX: Long = 0xFFFF
private const val BASE_31 = 31
private const val BASE_16 = 16
/**
* Convert a base 31 number containing chars 0123456789ABCDEFGHJKMNPQRTVWXYZ
* to numeric value.
*
* @param input base 31 number
* @return numeric value
* @throws IllegalArgumentException If input contains illegal chars
*/
fun base31Decode(input: String): Long {
var result: Long = 0
for (ch in input.toCharArray()) {
result *= BASE_31
val index = BASE_31_CHARS.indexOf(ch, ignoreCase = true)
if (index == -1) {
throw IllegalArgumentException("Only chars $BASE_31_CHARS are supported.")
}
result += index.toLong()
}
return result
}
/**
* Convert a numeric value to base 31 number using chars
* 0123456789ABCDEFGHJKMNPQRTVWXYZ.
*
* @param input numeric value
* @return base 31 number
*/
fun base31Encode(input: Long): String {
var temp = input
val sb = StringBuilder()
while (temp != 0L) {
sb.append(BASE_31_CHARS[(temp % BASE_31).toInt()])
temp /= BASE_31
}
return sb.reverse().toString()
}
/**
* Convert reference code `ppXXX` to numeric reference id.
*
* The algorithm respects following rules used for reference code:
*
* * `pp0 - ppFFFF` - value after `pp` prefix is a hexadecimal number
* * `ppG000 - ...` = value after `pp` is a base 31 number minus magic constant
* `411120 = (16 * 31 * 31 * 31 - 16 * 16 * 16 * 16)`
*
* @param referenceCode cache code including GC prefix
* @return reference id
* @throws IllegalArgumentException reference code contains invalid characters
*/
fun toId(referenceCode: String): Long {
val referenceCodeNorm = referenceCode.uppercase(Locale.US)
if (referenceCodeNorm.length < 3) {
throw IllegalArgumentException("Reference code is too short.")
}
// remove prefix
val code = referenceCodeNorm.substring(2)
// 0 - FFFF = base16; G000 - ... = base 31
return if (code.length <= 4 && code[0] < 'G') {
try {
code.toLong(BASE_16)
} catch (e: NumberFormatException) {
throw IllegalArgumentException("Only chars $BASE_31_CHARS are supported.")
}
} else {
base31Decode(code) - REFERENCE_CODE_BASE31_MAGIC_NUMBER
}
}
/**
* Convert a numeric id to reference code `ppXXX`. The algorithm respects
* rules for generating reference code.
*
* @param prefix the reference code prefix `pp`
* @param id reference id
* @return reference code including prefix
* @see .toId
*/
fun toReferenceCode(prefix: String = GEOCACHE_PREFIX, id: Long): String {
val sb = StringBuilder()
// append GC prefix
sb.append(prefix)
if (id <= REFERENCE_CODE_BASE16_MAX) { // 0 - FFFF
sb.append(id.toString(BASE_16).uppercase(Locale.US))
} else { // G000 - ...
sb.append(base31Encode(id + REFERENCE_CODE_BASE31_MAGIC_NUMBER))
}
return sb.toString()
}
/**
* Returns true if the reference code is valid. The algorithm respects
* rules for reference code.
*
* @param referenceCode reference code
* @return true if reference code is valid, otherwise false
* @see .toId
*/
fun isReferenceCodeValid(referenceCode: String, prefix: String? = null): Boolean {
try {
if (prefix != null && !referenceCode.startsWith(prefix, ignoreCase = true))
return false
return toId(referenceCode) >= 0
} catch (e: IllegalArgumentException) {
return false
}
}
}
| gpl-3.0 | 091a97b1143af464a19012f19a770176 | 30.695652 | 92 | 0.593736 | 4.292444 | false | false | false | false |
GoogleCloudPlatform/kotlin-samples | getting-started/android-with-appengine/backend/src/main/kotlin/com/google/cloud/kotlin/emojify/EmojifyController.kt | 1 | 7370 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.kotlin.emojify
import com.google.cloud.storage.Bucket
import com.google.cloud.storage.Storage
import com.google.cloud.vision.v1.Likelihood
import com.google.cloud.vision.v1.FaceAnnotation
import com.google.cloud.vision.v1.AnnotateImageRequest
import com.google.cloud.vision.v1.ImageAnnotatorClient
import com.google.cloud.vision.v1.ImageSource
import com.google.cloud.vision.v1.Image
import com.google.cloud.vision.v1.Feature
import com.google.cloud.vision.v1.Feature.Type
import org.springframework.http.HttpStatus
import org.springframework.beans.factory.annotation.Value
import org.springframework.core.io.ClassPathResource
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.awt.Polygon
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.nio.channels.Channels
import javax.imageio.ImageIO
import java.util.logging.Logger
enum class Emoji {
JOY, ANGER, SURPRISE, SORROW, NONE
}
val errorMessage = mapOf(
100 to "Other",
101 to "Slashes are intentionally forbidden in objectName.",
102 to "storage.bucket.name is missing in application.properties.",
103 to "Blob specified doesn't exist in bucket.",
104 to "blob ContentType is null.",
105 to "Size of responsesList is not 1.",
106 to "objectName is null.",
107 to "We couldn't detect faces in your image."
)
// Returns best emoji based on detected emotions likelihoods
fun bestEmoji(annotation: FaceAnnotation): Emoji {
val emotionsLikelihood = listOf(Likelihood.VERY_LIKELY, Likelihood.LIKELY, Likelihood.POSSIBLE)
val emotions = mapOf(
Emoji.JOY to annotation.joyLikelihood,
Emoji.ANGER to annotation.angerLikelihood,
Emoji.SURPRISE to annotation.surpriseLikelihood,
Emoji.SORROW to annotation.sorrowLikelihood
)
for (likelihood in emotionsLikelihood) { // In this order: VERY_LIKELY, LIKELY, POSSIBLE
for (emotion in emotions) { // In this order: JOY, ANGER, SURPRISE, SORROW (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map-of.html)
if (emotion.value == likelihood) return emotion.key // Returns emotion corresponding to likelihood
}
}
return Emoji.NONE
}
data class EmojifyResponse(
val objectPath: String? = null,
val emojifiedUrl: String? = null,
val statusCode: HttpStatus = HttpStatus.OK,
val errorCode: Int? = null,
val errorMessage: String? = null
)
@RestController
class EmojifyController(@Value("\${storage.bucket.name}") val bucketName: String, val storage: Storage, val vision: ImageAnnotatorClient) {
companion object {
val log: Logger = Logger.getLogger(EmojifyController::class.java.name)
}
val emojiBufferedImage = mapOf(
Emoji.JOY to retrieveEmoji("joy.png"),
Emoji.ANGER to retrieveEmoji("anger.png"),
Emoji.SURPRISE to retrieveEmoji("surprise.png"),
Emoji.SORROW to retrieveEmoji("sorrow.png"),
Emoji.NONE to retrieveEmoji("none.png")
)
private final fun retrieveEmoji(name: String): BufferedImage {
return ImageIO.read(ClassPathResource("emojis/$name").inputStream)
}
fun streamFromGCS(blobName: String): BufferedImage {
val strm: InputStream = Channels.newInputStream(storage.reader(bucketName, blobName))
return ImageIO.read(strm)
}
fun errorResponse(statusCode: HttpStatus, errorCode: Int = 100, msg: String? = null): EmojifyResponse {
val err = msg ?: errorMessage[errorCode]
log.severe(err)
return EmojifyResponse(statusCode = statusCode, errorCode = errorCode, errorMessage = err)
}
@GetMapping("/emojify")
fun emojify(@RequestParam(value = "objectName") objectName: String): EmojifyResponse {
if (objectName.isEmpty()) return errorResponse(HttpStatus.BAD_REQUEST, 106)
if (objectName.contains('/')) return errorResponse(HttpStatus.BAD_REQUEST, 101)
val bucket = storage.get(bucketName) ?: return errorResponse(HttpStatus.INTERNAL_SERVER_ERROR, 102)
val publicUrl: String =
"https://storage.googleapis.com/$bucketName/emojified/emojified-$objectName" // api response
val blob = bucket.get(objectName) ?: return errorResponse(HttpStatus.BAD_REQUEST, 103)
val imgType = blob.contentType?.substringAfter('/') ?: return errorResponse(HttpStatus.BAD_REQUEST, 104)
// Setting up image annotation request
val source = ImageSource.newBuilder().setGcsImageUri("gs://$bucketName/$objectName").build()
val img = Image.newBuilder().setSource(source).build()
val feat = Feature.newBuilder().setMaxResults(100).setType(Type.FACE_DETECTION).build()
val request = AnnotateImageRequest.newBuilder()
.addFeatures(feat)
.setImage(img)
.build()
// Calls vision api on above image annotation requests
val response = vision.batchAnnotateImages(listOf(request))
if (response.responsesList.size != 1) return errorResponse(HttpStatus.INTERNAL_SERVER_ERROR, 105)
val resp = response.responsesList[0]
if (resp.hasError()) return errorResponse(HttpStatus.INTERNAL_SERVER_ERROR, 100, resp.error.message)
// Writing source image to InputStream
val imgBuff = streamFromGCS(objectName)
val gfx = imgBuff.createGraphics()
if (resp.faceAnnotationsList.size == 0) return errorResponse(HttpStatus.BAD_REQUEST, 107)
for (annotation in resp.faceAnnotationsList) {
val imgEmoji = emojiBufferedImage[bestEmoji(annotation)]
val poly = Polygon()
for (vertex in annotation.fdBoundingPoly.verticesList) {
poly.addPoint(vertex.x, vertex.y)
}
val height = poly.ypoints[2] - poly.ypoints[0]
val width = poly.xpoints[1] - poly.xpoints[0]
// Draws emoji on detected face
gfx.drawImage(imgEmoji, poly.xpoints[0], poly.ypoints[1], height, width, null)
}
// Writing emojified image to OutputStream
val outputStream = ByteArrayOutputStream()
ImageIO.write(imgBuff, imgType, outputStream)
// Uploading emojified image to GCS and making it public
bucket.create(
"emojified/emojified-$objectName",
outputStream.toByteArray(),
Bucket.BlobTargetOption.predefinedAcl(Storage.PredefinedAcl.PUBLIC_READ)
)
// Everything went well!
return EmojifyResponse(
objectPath = "emojified/emojified-$objectName",
emojifiedUrl = publicUrl
)
}
} | apache-2.0 | 3d4f854cc6c5593e3701f3be1e4ab47d | 40.880682 | 160 | 0.70787 | 4.3404 | false | false | false | false |
CPRTeam/CCIP-Android | app/src/main/java/app/opass/ccip/ui/PuzzleFragment.kt | 1 | 4412 | package app.opass.ccip.ui
import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.*
import android.webkit.PermissionRequest
import android.webkit.WebSettings
import android.widget.FrameLayout
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import app.opass.ccip.R
import app.opass.ccip.network.webclient.OfficialWebViewClient
import app.opass.ccip.network.webclient.WebChromeViewClient
import app.opass.ccip.util.CryptoUtil
import app.opass.ccip.util.PreferenceUtil
import kotlinx.android.synthetic.main.fragment_web.*
class PuzzleFragment : Fragment() {
companion object {
private const val URL_NO_NETWORK = "file:///android_asset/no_network.html"
private const val EXTRA_URL = "EXTRA_URL"
fun newInstance(url: String): PuzzleFragment = PuzzleFragment().apply {
arguments = Bundle().apply { putString(EXTRA_URL, url) }
}
}
private lateinit var mActivity: MainActivity
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
mActivity = requireActivity() as MainActivity
return inflater.inflate(R.layout.fragment_web, container, false)
}
@SuppressLint("SetJavaScriptEnabled")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<FrameLayout>(R.id.webview_wrapper)
.setOnApplyWindowInsetsListener { v, insets ->
v.updatePadding(bottom = insets.systemWindowInsetBottom)
insets
}
webView.webViewClient = OfficialWebViewClient()
webView.webChromeClient = WebChromeViewClient(progressBar, fun (request) {
if (!request!!.resources.contains(PermissionRequest.RESOURCE_VIDEO_CAPTURE)) request.deny()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Android M Permission check
if (mActivity.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.CAMERA), 2)
request.deny()
} else {
request.grant(request.resources)
}
} else {
request.grant(request.resources)
}
})
if (PreferenceUtil.getToken(mActivity) != null) {
webView.loadUrl(
requireArguments().getString(EXTRA_URL)!!
.replace(
"{public_token}",
CryptoUtil.toPublicToken(PreferenceUtil.getToken(mActivity)) ?: ""
)
)
} else {
webView.loadUrl("data:text/html, <div>Please login</div>")
}
val settings = webView.settings
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
if (Build.VERSION.SDK_INT >= 21) {
settings.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (permissions.contains(Manifest.permission.CAMERA) && grantResults.contains(PackageManager.PERMISSION_GRANTED)) {
webView.reload()
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
mActivity.menuInflater.inflate(R.menu.puzzle, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.share -> {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_SUBJECT, resources.getText(R.string.puzzle_share_subject))
intent.putExtra(Intent.EXTRA_TEXT, webView.url)
mActivity.startActivity(Intent.createChooser(intent, resources.getText(R.string.share)))
}
}
return true
}
}
| gpl-3.0 | a708f3d63af698ef7d3eb7a1e4cacd26 | 37.034483 | 123 | 0.651405 | 4.946188 | false | false | false | false |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/appointment/model.kt | 1 | 1345 | package at.cpickl.gadsu.appointment
import at.cpickl.gadsu.persistence.Persistable
import at.cpickl.gadsu.service.HasId
import com.google.common.collect.ComparisonChain
import com.google.common.collect.Ordering
import org.joda.time.DateTime
data class Appointment(
override val id: String?,
val clientId: String,
// title, as shown as summary in gcal
val created: DateTime,
val start: DateTime,
val end: DateTime,
val note: String,
val gcalId: String?,
val gcalUrl: String?
) : Comparable<Appointment>, HasId, Persistable {
companion object {
fun insertPrototype(clientId: String, start: DateTime): Appointment {
return Appointment(null, clientId, DateTime.now(), start, start.plusMinutes(90), "", null, null)
}
}
val idComparator: (Appointment) -> Boolean
get() = { that -> this.id == that.id }
override val yetPersisted: Boolean get() = id != null
override fun compareTo(other: Appointment): Int {
return ComparisonChain.start()
.compare(this.start, other.start)
.compare(this.end, other.end)
.compare(this.clientId, other.clientId)
.compare(this.id, other.id, Ordering.natural<String>().nullsFirst())
.result()
}
}
| apache-2.0 | fd650105dd62436d8ab91d9fcb0c6fe5 | 31.804878 | 108 | 0.634944 | 4.256329 | false | false | false | false |
STUDIO-apps/GeoShare_Android | mobile/src/main/java/uk/co/appsbystudio/geoshare/authentication/signup/SignupFragment.kt | 1 | 3142 | package uk.co.appsbystudio.geoshare.authentication.signup
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import kotlinx.android.synthetic.main.fragment_signup.*
import uk.co.appsbystudio.geoshare.R
import uk.co.appsbystudio.geoshare.authentication.AuthActivity
import uk.co.appsbystudio.geoshare.authentication.AuthView
class SignupFragment : Fragment(), SignupView {
private var fragmentCallback: AuthView? = null
private var presenter: SignupPresenter? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_signup, container, false)
presenter = SignupPresenterImpl(this, SignupInteractorImpl())
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
progress_button_signup.setOnClickListener {
presenter?.validate(edit_name_signup.text.toString(), edit_email_signup.text.toString(), edit_password_signup.text.toString(), checkbox_terms_signup.isChecked)
}
text_terms_link_signup.setOnClickListener {
presenter?.onTermsClick()
}
button_back_signup.setOnClickListener {
fragmentCallback?.onBack()
}
}
override fun onAttach(context: Context?) {
super.onAttach(context)
try {
fragmentCallback = context as AuthActivity
} catch (e: ClassCastException) {
throw ClassCastException(activity.toString() + "must implement AuthView")
}
}
override fun setNameError() {
edit_name_signup.error = resources.getString(R.string.error_field_required)
edit_name_signup.requestFocus()
}
override fun setEmailError() {
edit_email_signup.error = resources.getString(R.string.error_field_required)
edit_email_signup.requestFocus()
}
override fun setPasswordError() {
edit_password_signup.error = resources.getString(R.string.error_field_required)
edit_password_signup.requestFocus()
}
override fun setTermsError() {
checkbox_terms_signup.error = resources.getString(R.string.error_field_required)
}
override fun showTerms() {
//TODO: Create a dialog to show the terms
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://geoshare.appsbystudio.co.uk/terms")))
}
override fun showProgress() {
progress_button_signup.startAnimation()
}
override fun hideProgress() {
progress_button_signup.revertAnimation()
}
override fun updateUI() {
fragmentCallback?.onSuccess()
}
override fun showError(error: String) {
Toast.makeText(this.context, error, Toast.LENGTH_SHORT).show()
}
}
| apache-2.0 | ef16ef3da2e3ad0993bd8050d07333b4 | 31.391753 | 171 | 0.693189 | 4.586861 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/engine/GivenAPlayingPlaybackEngine/WhenNotObservingPlayback.kt | 1 | 2881 | package com.lasthopesoftware.bluewater.client.playback.engine.GivenAPlayingPlaybackEngine
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.library.access.ILibraryStorage
import com.lasthopesoftware.bluewater.client.browsing.library.access.ISpecificLibraryProvider
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library
import com.lasthopesoftware.bluewater.client.playback.engine.PlaybackEngine.Companion.createEngine
import com.lasthopesoftware.bluewater.client.playback.engine.bootstrap.PlaylistPlaybackBootstrapper
import com.lasthopesoftware.bluewater.client.playback.engine.preparation.PreparedPlaybackQueueResourceManagement
import com.lasthopesoftware.bluewater.client.playback.file.preparation.FakeDeferredPlayableFilePreparationSourceProvider
import com.lasthopesoftware.bluewater.client.playback.file.preparation.queues.CompletingFileQueueProvider
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.storage.NowPlayingRepository
import com.lasthopesoftware.bluewater.client.playback.volume.PlaylistVolumeManager
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions
import org.joda.time.Duration
import org.junit.Test
import java.util.*
class WhenNotObservingPlayback {
companion object {
private val library = Library(_id = 1, _nowPlayingId = 5)
private val playbackEngine by lazy {
val fakePlaybackPreparerProvider = FakeDeferredPlayableFilePreparationSourceProvider()
val libraryProvider = mockk<ISpecificLibraryProvider>()
every { libraryProvider.library } returns Promise(library)
val libraryStorage = mockk<ILibraryStorage>()
every { libraryStorage.saveLibrary(any()) } returns Promise(library)
val playbackEngine = createEngine(
PreparedPlaybackQueueResourceManagement(
fakePlaybackPreparerProvider
) { 1 }, listOf(CompletingFileQueueProvider()),
NowPlayingRepository(libraryProvider, libraryStorage),
PlaylistPlaybackBootstrapper(PlaylistVolumeManager(1.0f))
).toFuture().get()
playbackEngine
?.startPlaylist(
Arrays.asList(
ServiceFile(1),
ServiceFile(2),
ServiceFile(3),
ServiceFile(4),
ServiceFile(5)
), 0, Duration.ZERO
)
val resolveablePlaybackHandler =
fakePlaybackPreparerProvider.deferredResolution.resolve()
fakePlaybackPreparerProvider.deferredResolution.resolve()
resolveablePlaybackHandler.resolve()
playbackEngine
}
}
@Test
fun thenTheSavedTrackPositionIsOne() {
Assertions.assertThat(library.nowPlayingId).isEqualTo(1)
}
@Test
fun thenTheManagerIsPlaying() {
Assertions.assertThat(playbackEngine?.isPlaying).isTrue
}
}
| lgpl-3.0 | 741ceaf54de7c756e197efcb8f68a612 | 40.157143 | 120 | 0.820896 | 4.639291 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/file/exoplayer/GivenAPlayingFile/AndThePlayerIdles/AndTheFilePositionIsAtTheEnd/WhenThePlayerWillNotPlayWhenReady.kt | 1 | 2220 | package com.lasthopesoftware.bluewater.client.playback.file.exoplayer.GivenAPlayingFile.AndThePlayerIdles.AndTheFilePositionIsAtTheEnd
import com.annimon.stream.Stream
import com.google.android.exoplayer2.Player
import com.lasthopesoftware.any
import com.lasthopesoftware.bluewater.client.playback.exoplayer.PromisingExoPlayer
import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.ExoPlayerPlaybackHandler
import com.lasthopesoftware.bluewater.shared.promises.extensions.FuturePromise
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import org.assertj.core.api.AssertionsForClassTypes
import org.junit.BeforeClass
import org.junit.Test
import org.mockito.Mockito
import java.util.*
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
class WhenThePlayerWillNotPlayWhenReady {
companion object {
private val eventListeners: MutableCollection<Player.EventListener> = ArrayList()
private var isComplete = false
@JvmStatic
@BeforeClass
@Throws(InterruptedException::class, TimeoutException::class, ExecutionException::class)
fun before() {
val mockExoPlayer = Mockito.mock(PromisingExoPlayer::class.java)
Mockito.`when`(mockExoPlayer.getPlayWhenReady()).thenReturn(true.toPromise())
Mockito.`when`(mockExoPlayer.setPlayWhenReady(true)).thenReturn(mockExoPlayer.toPromise())
Mockito.`when`(mockExoPlayer.getCurrentPosition()).thenReturn(100L.toPromise())
Mockito.`when`(mockExoPlayer.getDuration()).thenReturn(100L.toPromise())
Mockito.doAnswer { invocation ->
eventListeners.add(invocation.getArgument(0))
mockExoPlayer.toPromise()
}.`when`(mockExoPlayer).addListener(any())
val exoPlayerPlaybackHandler = ExoPlayerPlaybackHandler(mockExoPlayer)
val playbackPromise = exoPlayerPlaybackHandler.promisePlayback()
.eventually { obj -> obj.promisePlayedFile() }
.then { isComplete = true }
Stream.of(eventListeners).forEach { e -> e.onPlayerStateChanged(false, Player.STATE_IDLE) }
FuturePromise(playbackPromise)[1, TimeUnit.SECONDS]
}
}
@Test
fun thenPlaybackCompletes() {
AssertionsForClassTypes.assertThat(isComplete).isTrue
}
}
| lgpl-3.0 | 92aec96445aa2a8e6675158e03812602 | 40.886792 | 134 | 0.812613 | 4.422311 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/ModuleCombustionChamber.kt | 2 | 6053 | package com.cout970.magneticraft.systems.tilemodules
import com.cout970.magneticraft.api.heat.IHeatNode
import com.cout970.magneticraft.misc.*
import com.cout970.magneticraft.misc.inventory.Inventory
import com.cout970.magneticraft.misc.inventory.get
import com.cout970.magneticraft.misc.inventory.isNotEmpty
import com.cout970.magneticraft.misc.inventory.withSize
import com.cout970.magneticraft.misc.network.IntSyncVariable
import com.cout970.magneticraft.misc.network.SyncVariable
import com.cout970.magneticraft.misc.vector.*
import com.cout970.magneticraft.misc.world.isClient
import com.cout970.magneticraft.systems.blocks.*
import com.cout970.magneticraft.systems.config.Config
import com.cout970.magneticraft.systems.gui.DATA_ID_BURNING_TIME
import com.cout970.magneticraft.systems.gui.DATA_ID_MAX_BURNING_TIME
import com.cout970.magneticraft.systems.integration.ItemHolder
import com.cout970.magneticraft.systems.tileentities.IModule
import com.cout970.magneticraft.systems.tileentities.IModuleContainer
import net.minecraft.init.Blocks
import net.minecraft.init.Items
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.tileentity.TileEntityFurnace
import net.minecraft.util.EnumParticleTypes
/**
* Created by cout970 on 2017/07/13.
*/
class ModuleCombustionChamber(
val node: IHeatNode,
val inventory: Inventory,
override val name: String = "module_combustion_chamber"
) : IModule, IOnActivated {
override lateinit var container: IModuleContainer
var burningTime = 0
var maxBurningTime = 0
var doorOpen = false
companion object {
@JvmStatic
val MAX_HEAT = 600.fromCelsiusToKelvin()
}
override fun onActivated(args: OnActivatedArgs): Boolean {
val block = container.blockState.block
val boxes = (block as? BlockBase)
?.aabb
?.invoke(BoundingBoxArgs(container.blockState, world, pos))
?: emptyList()
val index = boxes.indexOfFirst { it.isHitBy(args.hit) }
if (index != 2) {
return if (Config.allowCombustionChamberGui) {
CommonMethods.openGui(args)
} else {
false
}
} else {
if (doorOpen && isValidFuel(args.heldItem)) {
val space = 64 - inventory[0].count
val toMove = Math.min(args.heldItem.count, space)
if (toMove > 0) {
val notMoved = inventory.insertItem(0, args.heldItem.withSize(toMove), false)
args.heldItem.shrink(toMove - notMoved.count)
}
} else {
doorOpen = !doorOpen
container.sendUpdateToNearPlayers()
}
return true
}
}
fun spawnParticles() {
if (doorOpen && inventory[0].isNotEmpty) {
repeat(2) {
val rand = world.rand
val offset = (vec3Of(rand.nextFloat(), 0, rand.nextFloat()) * 2 - vec3Of(1, 0, 1)) * 0.25
val pos = pos.toVec3d() + vec3Of(0.5, 0.2, 0.5) + offset
val randDir = vec3Of(rand.nextFloat(), rand.nextFloat(), rand.nextFloat())
val randDirAllDirections = randDir * vec3Of(2, 1, 2) - vec3Of(1, 0, 1)
val dir = randDirAllDirections * 0.001 + (-offset + vec3Of(0, 1, 0)) * 0.025
world.spawnParticle(EnumParticleTypes.FLAME, pos.x, pos.y, pos.z, dir.x, dir.y, dir.z)
}
}
}
override fun update() {
if (world.isClient) {
spawnParticles()
return
}
if (maxBurningTime > 0) {
if (burningTime > maxBurningTime) {
maxBurningTime = 0
burningTime = 0
} else {
if (node.temperature < MAX_HEAT) {
val speed = ((if (doorOpen) 0.5f else 1f) * Config.combustionChamberMaxSpeed.toFloat()).toInt()
burningTime += speed
node.applyHeat(Config.fuelToJoules * speed)
}
}
}
if (maxBurningTime <= 0) {
val consumed = consumeFuel()
if (!consumed && node.temperature > STANDARD_AMBIENT_TEMPERATURE) {
node.applyHeat(Config.heatDissipationSpeed)
}
}
}
fun consumeFuel(): Boolean {
maxBurningTime = 0
val stack = inventory[0]
if (stack.isEmpty || !isValidFuel(stack)) return false
val time = TileEntityFurnace.getItemBurnTime(stack)
if (time > 0) {
stack.shrink(1)
maxBurningTime = (time * Config.combustionChamberFuelMultiplier).toInt()
}
return true
}
fun isValidFuel(stack: ItemStack): Boolean {
if (stack.isEmpty) return false
if (!Config.combustionChamberOnlyCoal) {
return TileEntityFurnace.getItemBurnTime(stack) > 0
}
// vanilla
if (stack.item == Items.COAL) return true
if (stack.item == Item.getItemFromBlock(Blocks.COAL_BLOCK)) return true
// other mods
ItemHolder.coalCoke?.let { if (it.isItemEqual(stack)) return true }
ItemHolder.coalCokeBlock?.let { if (it.isItemEqual(stack)) return true }
return false
}
override fun serializeNBT(): NBTTagCompound = newNbt {
add("burningTime", burningTime)
add("maxBurningTime", maxBurningTime)
add("doorOpen", doorOpen)
}
override fun deserializeNBT(nbt: NBTTagCompound) {
burningTime = nbt.getInteger("burningTime")
maxBurningTime = nbt.getInteger("maxBurningTime")
doorOpen = nbt.getBoolean("doorOpen")
}
override fun getGuiSyncVariables(): List<SyncVariable> {
return listOf(
IntSyncVariable(DATA_ID_BURNING_TIME, { burningTime }, { burningTime = it }),
IntSyncVariable(DATA_ID_MAX_BURNING_TIME, { maxBurningTime }, { maxBurningTime = it })
)
}
} | gpl-2.0 | 7a261f4bd2a9ad1a9ebc7eb5b3bf67bb | 35.690909 | 115 | 0.623658 | 4.351546 | false | false | false | false |
JLLeitschuh/ktlint-gradle | plugin/src/main/kotlin/org/jlleitschuh/gradle/ktlint/KtlintIdeaPlugin.kt | 1 | 1706 | package org.jlleitschuh.gradle.ktlint
import org.gradle.api.Plugin
import org.gradle.api.Project
/**
* Adds tasks associated with configuring IntelliJ IDEA.
*/
open class KtlintIdeaPlugin : Plugin<Project> {
override fun apply(target: Project) {
val extension = target.plugins.apply(KtlintBasePlugin::class.java).extension
if (target == target.rootProject) {
/*
* Only add these tasks if we are applying to the root project.
*/
addApplyToIdeaTasks(target, extension)
}
}
private fun addApplyToIdeaTasks(rootProject: Project, extension: KtlintExtension) {
val ktLintConfig = createKtlintConfiguration(rootProject, extension)
rootProject.registerTask<KtlintApplyToIdeaTask>(APPLY_TO_IDEA_TASK_NAME) {
group = HELP_GROUP
description = "Generates IDEA built-in formatter rules and apply them to the project." +
"It will overwrite existing ones."
classpath.setFrom(ktLintConfig)
android.set(extension.android)
globally.set(rootProject.provider { false })
ktlintVersion.set(extension.version)
}
rootProject.registerTask<KtlintApplyToIdeaTask>(APPLY_TO_IDEA_GLOBALLY_TASK_NAME) {
group = HELP_GROUP
description = "Generates IDEA built-in formatter rules and apply them globally " +
"(in IDEA user settings folder). It will overwrite existing ones."
classpath.setFrom(ktLintConfig)
android.set(extension.android)
globally.set(rootProject.provider { true })
ktlintVersion.set(extension.version)
}
}
}
| mit | ac05d6e2c84dca2bad50a77761b507aa | 37.772727 | 100 | 0.651817 | 4.752089 | false | true | false | false |
JetBrains/resharper-unity | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/run/attach/UnityLocalAttachProcessDebuggerProvider.kt | 1 | 1565 | package com.jetbrains.rider.plugins.unity.run.attach
import com.intellij.execution.process.ProcessInfo
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder
import com.intellij.xdebugger.attach.*
import com.jetbrains.rd.platform.util.idea.getOrCreateUserData
import com.jetbrains.rider.plugins.unity.run.UnityProcessInfo
import com.jetbrains.rider.plugins.unity.run.UnityRunUtil
class UnityLocalAttachProcessDebuggerProvider : XAttachDebuggerProvider {
companion object {
val PROCESS_INFO_KEY: Key<MutableMap<Int, UnityProcessInfo>> = Key("UnityProcess::Info")
}
override fun getAvailableDebuggers(project: Project, host: XAttachHost, process: ProcessInfo, userData: UserDataHolder): MutableList<XAttachDebugger> {
if (UnityRunUtil.isUnityEditorProcess(process)) {
// Fetch the project + role names while we're not on the EDT, and cache so we can use it in the presenter
val unityProcessInfo = UnityRunUtil.getUnityProcessInfo(process, project)?.apply {
val map = userData.getOrCreateUserData(PROCESS_INFO_KEY) { mutableMapOf() }
map[process.pid] = this
}
return mutableListOf(UnityLocalAttachDebugger(unityProcessInfo))
}
return mutableListOf()
}
override fun isAttachHostApplicable(host: XAttachHost) = host is LocalAttachHost
override fun getPresentationGroup(): XAttachPresentationGroup<ProcessInfo> = UnityLocalAttachProcessPresentationGroup
} | apache-2.0 | 457f74b190ebe2047dbfad24d66f5bc1 | 46.454545 | 155 | 0.757188 | 4.771341 | false | false | false | false |
f-droid/fdroidclient | libs/download/src/androidMain/kotlin/org/fdroid/download/Downloader.kt | 1 | 8626 | package org.fdroid.download
import mu.KotlinLogging
import org.fdroid.fdroid.ProgressListener
import org.fdroid.fdroid.isMatching
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.security.MessageDigest
public abstract class Downloader constructor(
@JvmField
protected val outputFile: File,
) {
public companion object {
private val log = KotlinLogging.logger {}
}
protected var fileSize: Long? = null
/**
* If not null, this is the expected sha256 hash of the [outputFile] after download.
*/
protected var sha256: String? = null
/**
* If you ask for the cacheTag before calling download(), you will get the
* same one you passed in (if any). If you call it after download(), you
* will get the new cacheTag from the server, or null if there was none.
*
* If this cacheTag matches that returned by the server, then no download will
* take place, and a status code of 304 will be returned by download().
*/
@Deprecated("Used only for v1 repos")
public var cacheTag: String? = null
@Volatile
private var cancelled = false
@Volatile
private var progressListener: ProgressListener? = null
/**
* Call this to start the download.
* Never call this more than once. Create a new [Downloader], if you need to download again!
*
* @totalSize must be set to what the index tells us the size will be
* @sha256 must be set to the sha256 hash from the index and only be null for `entry.jar`.
*/
@Throws(IOException::class, InterruptedException::class)
public abstract fun download(totalSize: Long, sha256: String? = null)
/**
* Call this to start the download.
* Never call this more than once. Create a new [Downloader], if you need to download again!
*/
@Deprecated("Use only for v1 repos")
@Throws(IOException::class, InterruptedException::class)
public abstract fun download()
@Throws(IOException::class, NotFoundException::class)
protected abstract fun getInputStream(resumable: Boolean): InputStream
protected open suspend fun getBytes(resumable: Boolean, receiver: BytesReceiver) {
throw NotImplementedError()
}
/**
* Returns the size of the file to be downloaded in bytes.
* Note this is -1 when the size is unknown.
* Used only for progress reporting.
*/
protected abstract fun totalDownloadSize(): Long
/**
* After calling [download], this returns true if a new file was downloaded and
* false if the file on the server has not changed and thus was not downloaded.
*/
@Deprecated("Only for v1 repos")
public abstract fun hasChanged(): Boolean
public abstract fun close()
public fun setListener(listener: ProgressListener) {
progressListener = listener
}
@Throws(IOException::class, InterruptedException::class)
protected fun downloadFromStream(isResume: Boolean) {
log.debug { "Downloading from stream" }
try {
FileOutputStream(outputFile, isResume).use { outputStream ->
getInputStream(isResume).use { input ->
// Getting the input stream is slow(ish) for HTTP downloads, so we'll check if
// we were interrupted before proceeding to the download.
throwExceptionIfInterrupted()
copyInputToOutputStream(input, outputStream)
}
}
// Even if we have completely downloaded the file, we should probably respect
// the wishes of the user who wanted to cancel us.
throwExceptionIfInterrupted()
} finally {
close()
}
}
@Suppress("BlockingMethodInNonBlockingContext")
@Throws(InterruptedException::class, IOException::class, NoResumeException::class)
protected suspend fun downloadFromBytesReceiver(isResume: Boolean) {
try {
val messageDigest: MessageDigest? = if (sha256 == null) null else {
MessageDigest.getInstance("SHA-256")
}
FileOutputStream(outputFile, isResume).use { outputStream ->
var bytesCopied = outputFile.length()
var lastTimeReported = 0L
val bytesTotal = totalDownloadSize()
getBytes(isResume) { bytes, numTotalBytes ->
// Getting the input stream is slow(ish) for HTTP downloads, so we'll check if
// we were interrupted before proceeding to the download.
throwExceptionIfInterrupted()
outputStream.write(bytes)
messageDigest?.update(bytes)
bytesCopied += bytes.size
val total = if (bytesTotal == -1L) numTotalBytes ?: -1L else bytesTotal
lastTimeReported = reportProgress(lastTimeReported, bytesCopied, total)
}
// check if expected sha256 hash matches
sha256?.let { expectedHash ->
if (!messageDigest.isMatching(expectedHash)) {
throw IOException("Hash not matching")
}
}
// force progress reporting at the end
reportProgress(0L, bytesCopied, bytesTotal)
}
// Even if we have completely downloaded the file, we should probably respect
// the wishes of the user who wanted to cancel us.
throwExceptionIfInterrupted()
} finally {
close()
}
}
/**
* This copies the downloaded data from the [InputStream] to the [OutputStream],
* keeping track of the number of bytes that have flown through for the [progressListener].
*
* Attention: The caller is responsible for closing the streams.
*/
@Throws(IOException::class, InterruptedException::class)
private fun copyInputToOutputStream(input: InputStream, output: OutputStream) {
val messageDigest: MessageDigest? = if (sha256 == null) null else {
MessageDigest.getInstance("SHA-256")
}
try {
var bytesCopied = outputFile.length()
var lastTimeReported = 0L
val bytesTotal = totalDownloadSize()
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var numBytes = input.read(buffer)
while (numBytes >= 0) {
throwExceptionIfInterrupted()
output.write(buffer, 0, numBytes)
messageDigest?.update(buffer, 0, numBytes)
bytesCopied += numBytes
lastTimeReported = reportProgress(lastTimeReported, bytesCopied, bytesTotal)
numBytes = input.read(buffer)
}
// check if expected sha256 hash matches
sha256?.let { expectedHash ->
if (!messageDigest.isMatching(expectedHash)) {
throw IOException("Hash not matching")
}
}
// force progress reporting at the end
reportProgress(0L, bytesCopied, bytesTotal)
} finally {
output.flush()
progressListener = null
}
}
private fun reportProgress(lastTimeReported: Long, bytesRead: Long, bytesTotal: Long): Long {
val now = System.currentTimeMillis()
return if (now - lastTimeReported > 100) {
log.debug { "onProgress: $bytesRead/$bytesTotal" }
progressListener?.onProgress(bytesRead, bytesTotal)
now
} else {
lastTimeReported
}
}
/**
* Cancel a running download, triggering an [InterruptedException]
*/
public fun cancelDownload() {
cancelled = true
}
/**
* After every network operation that could take a while, we will check if an
* interrupt occurred during that blocking operation. The goal is to ensure we
* don't move onto another slow, network operation if we have cancelled the
* download.
*
* @throws InterruptedException
*/
@Throws(InterruptedException::class)
private fun throwExceptionIfInterrupted() {
if (cancelled) {
log.info { "Received interrupt, cancelling download" }
Thread.currentThread().interrupt()
throw InterruptedException()
}
}
}
public fun interface BytesReceiver {
public suspend fun receive(bytes: ByteArray, numTotalBytes: Long?)
}
| gpl-3.0 | b7f50bf32a38261c017e1ea8a4989d80 | 37.337778 | 98 | 0.622305 | 5.301782 | false | false | false | false |
Dreamersoul/FastHub | app/src/main/java/com/fastaccess/ui/modules/repos/extras/license/RepoLicenseBottomSheet.kt | 1 | 3874 | package com.fastaccess.ui.modules.repos.extras.license
import android.os.Bundle
import android.support.annotation.StringRes
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import com.evernote.android.state.State
import com.fastaccess.R
import com.fastaccess.helper.BundleConstant
import com.fastaccess.helper.Bundler
import com.fastaccess.ui.base.BaseMvpBottomSheetDialogFragment
import com.fastaccess.ui.widgets.StateLayout
import com.prettifier.pretty.PrettifyWebView
/**
* Created by Kosh on 30 Jun 2017, 12:38 PM
*/
class RepoLicenseBottomSheet : BaseMvpBottomSheetDialogFragment<RepoLicenseMvp.View, RepoLicensePresenter>(), RepoLicenseMvp.View,
PrettifyWebView.OnContentChangedListener {
@State var content: String? = null
val stateLayout: StateLayout by lazy { view!!.findViewById<StateLayout>(R.id.stateLayout) }
val loader: ProgressBar by lazy { view!!.findViewById<ProgressBar>(R.id.readmeLoader) }
val webView: PrettifyWebView by lazy { view!!.findViewById<PrettifyWebView>(R.id.webView) }
val licenseName: TextView by lazy { view!!.findViewById<TextView>(R.id.licenseName) }
override fun providePresenter(): RepoLicensePresenter = RepoLicensePresenter()
override fun onLicenseLoaded(license: String) {
this.content = license
if (!license.isNullOrBlank()) {
loader.isIndeterminate = false
val licenseText = license.replace("<pre>", "<pre style='overflow: hidden;word-wrap:break-word;word-break:break-all;" +
"white-space:pre-line;'>")
webView.setGithubContent("<div class='markdown-body'>$licenseText</div>", null)
} else {
hideProgress()
}
}
override fun fragmentLayout(): Int = R.layout.license_viewer_layout
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val login = arguments.getString(BundleConstant.EXTRA)
val repo = arguments.getString(BundleConstant.ID)
val licenseTitle = arguments.getString(BundleConstant.EXTRA_TWO)
licenseName.text = licenseTitle
if (content.isNullOrBlank() && !presenter.isApiCalled) {
presenter.onLoadLicense(login, repo)
} else {
content?.let { onLicenseLoaded(it) }
}
webView.setOnContentChangedListener(this)
}
override fun onContentChanged(progress: Int) {
loader.let {
it.progress = progress
if (progress == 100) {
it.visibility = View.GONE
hideProgress()
}
}
}
override fun showProgress(@StringRes resId: Int) {
loader.visibility = View.VISIBLE
loader.isIndeterminate = true
stateLayout.showProgress()
}
override fun hideProgress() {
loader.visibility = View.GONE
stateLayout.hideProgress()
}
override fun showErrorMessage(msgRes: String) {
hideProgress()
super.showErrorMessage(msgRes)
}
override fun showMessage(titleRes: Int, msgRes: Int) {
hideProgress()
super.showMessage(titleRes, msgRes)
}
override fun showMessage(titleRes: String, msgRes: String) {
hideProgress()
super.showMessage(titleRes, msgRes)
}
override fun onScrollChanged(reachedTop: Boolean, scroll: Int) {}
companion object {
fun newInstance(login: String, repo: String, license: String): RepoLicenseBottomSheet {
val view = RepoLicenseBottomSheet()
view.arguments = Bundler.start()
.put(BundleConstant.ID, repo)
.put(BundleConstant.EXTRA, login)
.put(BundleConstant.EXTRA_TWO, license)
.end()
return view
}
}
} | gpl-3.0 | 0a73c58512eb98a993b943cc5470ed25 | 33.90991 | 130 | 0.66572 | 4.759214 | false | false | false | false |
alfadur/roomservice | src/Level.kt | 1 | 26349 | import kotlin.browser.window
abstract class Task
{
class Wait(var time: Double) : Task()
class Move(val location: Location, val placeItem: Item?) : Task()
{
override fun toString() =
if (placeItem == null) "Take item from $location"
else "Place ${placeItem.name} on $location"
}
}
abstract class LevelState
{
class AwaitVisitor(val character: Character, var progress: Double): LevelState()
class ManageItems(val character: Character, val tasks: ArrayList<Task>): LevelState()
class AwaitFailure(var progress: Double): LevelState()
class CheckPause(val character: Character, val messages: List<String>, var progress: Double) : LevelState()
}
val allItems = listOf(
Item(Point(50, 35), "Wallet"),
Item(Point(50, 40), "Flashlight"),
Item(Point(50, 60), "Kettle"),
Item(Point(50, 50), "Clock"),
Item(Point(50, 45), "Book"),
Item(Point(50, 35), "Pencil"),
Item(Point(50, 60), "Ball"),
Item(Point(50, 50), "Hat"),
Item(Point(50, 80), "Panda"))
val colors = listOf(
0xFFFFFF,
0x0000FF,
0xFF00FF,
0xFFFF00,
0x00FFFF,
0xAAAAAA,
0x8844AA,
0xAA8844,
0x44AA88)
class Level(val container: PIXI.Container, val stageSize: Point,
val charactersCount: Int = 3,
val itemsPerCharacter: Int = 1,
val dialogTexture: PIXI.BaseTexture)
{
val size = Point(560, 240)
val spawnPoint = Point(size.x / 2, 80)
val topLeft = Point(50, 80)
val bottomRight = Point(510, 200)
val locations = arrayListOf<Location>()
val characterSize = Point(60, 30)
val player = Character(characterSize)
val inventory = Array<Item?>(allItems.size) {null}
val npcs = arrayListOf<Character>()
val schedule: Schedule
var currentState: LevelState
var activeLocation: Location? = null
var moveDirection = Direction.None
val roomRoot = PIXI.Container()
val inventoryRoot = PIXI.Container()
val inventoryGraphics = PIXI.Graphics()
val graphics = PIXI.Graphics()
val locationSprites = arrayListOf<PIXI.Sprite>()
val itemSprites = arrayListOf<PIXI.Sprite>()
val inventorySprites = arrayListOf<PIXI.Sprite>()
//val inventoryHighlights = Array(allItems.size) {0.0}
val highlightSprite: PIXI.Sprite
val playerSprite: PIXI.Sprite
val npcSprite: PIXI.Sprite
var npcSpriteFirst: Boolean = true
val previewSprite: PIXI.Sprite
val playerAnimation: CharacterAnimation
val npcAnimation: CharacterAnimation
val help: PIXI.Text
var levelCompleted: Boolean? = null
init
{
val shuffledItems = ArrayList(allItems)
permute(shuffledItems)
for (i in 0..charactersCount - 1)
{
val items = shuffledItems.drop(itemsPerCharacter * i).take(itemsPerCharacter)
val character = Character(characterSize)
character.items.addAll(items)
npcs.add(character)
}
val locationsCount = 4
val spacing = size.x / (locationsCount + 1)
for (i in 0..locationsCount - 1)
{
val location = Location(Point(75, 75))
location.position =
Point((i + 1) * spacing - location.width / 2,
size.y - location.height)
locations.add(location)
}
schedule = Schedule(npcs, locations, rounds = 6)
currentState = LevelState.AwaitVisitor(schedule.nextCharacter, 0.5)
val inventoryPart = stageSize.y / 5
val background = PIXI.Sprite(LevelResources.roomTexture)
background.width = size.x
background.position = PIXI.Point(0, 8)
roomRoot.addChild(background)
roomRoot.addChild(graphics)
roomRoot.position = PIXI.Point((stageSize.x - size.x) / 2, inventoryPart)
playerSprite = PIXI.Sprite(LevelResources.characterTextures[1])
npcSprite = PIXI.Sprite(LevelResources.characterTextures[1])
npcSprite.visible = false
player.position = spawnPoint
playerAnimation = CharacterAnimation(playerSprite)
npcAnimation = CharacterAnimation(npcSprite)
roomRoot.addChild(playerSprite)
roomRoot.addChild(npcSprite)
for (location in locations)
{
val sprite = PIXI.Sprite(LevelResources.tableTexture)
sprite.width = location.width
sprite.height = location.height
sprite.position = PIXI.Point(location.x, location.y - 10)
locationSprites.add(sprite)
roomRoot.addChild(sprite)
}
highlightSprite = PIXI.Sprite(LevelResources.tableTexture)
highlightSprite.visible = false
highlightSprite.width = 75
highlightSprite.height = 75
highlightSprite.blendMode = PIXI.BLEND_MODES.SCREEN
roomRoot.addChild(highlightSprite)
for (i in allItems.indices)
{
val sprite = PIXI.Sprite(LevelResources.itemTextures[i])
roomRoot.addChild(sprite)
itemSprites.add(sprite)
sprite.visible = false
}
previewSprite = PIXI.Sprite(LevelResources.characterTextures[
(npcs.indexOf(schedule.nextCharacter) + 1) * 3 + 1])
previewSprite.position = PIXI.Point(0, size.y + 20)
previewSprite.scale = PIXI.Point(0.5, 0.5)
roomRoot.addChild(previewSprite)
inventoryGraphics.lineStyle(3, 0xAA7700)
val shift = size.x.toDouble() / (allItems.size) + 1
for ((i, item) in allItems.withIndex())
{
val sprite = PIXI.Sprite(LevelResources.itemTextures[i])
sprite.width = 60
sprite.height = 60
//sprite._tint = 0x444444
sprite.visible = false
sprite.position = PIXI.Point((i + 1) * shift - sprite.width.toDouble() / 2, 6)
inventoryRoot.addChild(sprite)
inventorySprites.add(sprite)
inventoryGraphics.drawRect(
sprite.position.x.toInt() - 2, sprite.position.y.toInt() + 4,
sprite.width.toInt() + 4, sprite.height.toInt() + 4)
}
inventoryRoot.addChild(inventoryGraphics)
val helpText = "<Arrows>, <WASD>: Move\n<Enter>, <Space>: Skip to the next visitor\n<1-9>: Take/place item\n<Esc>: Pause"
help = PIXI.Text(helpText, TextStyle(
fill = "blanchedAlmond",
wordWrap = false,
font = "14pt"))
help.position = PIXI.Point(80, size.y + 10)
roomRoot.addChild(help)
container.addChild(inventoryRoot)
container.addChild(roomRoot)
}
fun update()
{
if (moveDirection != Direction.None)
{
playerAnimation.start()
move(moveDirection.shift)
}
else
{
playerAnimation.stop()
}
playerAnimation.update(player.position, moveDirection)
graphics.clear()
graphics.lineStyle(4, 0x00FF00)
/*graphics.lineStyle(4, 0xFF0000)
graphics.drawRect(0, 0, size.x, size.y)
graphics.lineStyle(2, 0x00FF00)
for (it in locations)
{
if (it == activeLocation) graphics.lineStyle(2, 0xFFFF00)
else graphics.lineStyle(2, 0x00FF00)
graphics.draw(it)
val item = it.item
if (item != null)
{
graphics.lineStyle(2, colors[allItems.indexOf(item)])
graphics.drawRect(it.x, it.y, item.width, item.height)
}
}
graphics.lineStyle(2, 0x00FF00)
graphics.draw(player)*/
val state = currentState
when (state)
{
is LevelState.AwaitVisitor ->
{
activeLocation =
if (player.position.y > bottomRight.y - 30)
locations.minBy { Math.abs((it.midX - player.x).toDouble()) }
else
null
graphics.beginFill(0x0000FF)
graphics.drawRect(0, size.y, state.progress * 50, 10)
graphics.endFill()
state.progress -= 0.001
if (state.progress <= 0.0)
{
activeLocation = null
state.character.position = spawnPoint
npcSprite.visible = true
npcAnimation.animationIndex = npcs.indexOf(state.character) + 1
npcAnimation.stop()
npcAnimation.update(state.character.position, Direction.Left)
val messages = schedule.checkState()
currentState = LevelState.CheckPause(
state.character, messages, if (messages.isNotEmpty()) 1.0 else 0.5)
}
}
is LevelState.CheckPause ->
{
state.progress -= 0.02
if (state.progress <= 0)
{
if (state.messages.isNotEmpty())
{
initFailure(state.messages)
}
else
{
val tasks = createTasks(state.character)
currentState = LevelState.ManageItems(state.character, tasks)
npcAnimation.start()
npcAnimation.update(state.character.position, Direction.Left)
}
}
}
is LevelState.ManageItems ->
{
val character = state.character
//graphics.draw(character)
if (state.tasks.isEmpty())
{
schedule.rememberState()
if (schedule.completed)
{
levelCompleted = true
}
else
{
currentState = LevelState.AwaitVisitor(schedule.nextCharacter, 1.0)
activeLocation = null
npcSprite.visible = false
npcAnimation.stop()
previewSprite.texture =
LevelResources.characterTextures[
(npcs.indexOf(schedule.nextCharacter) + 1) * 3 + 1]
}
}
else
{
val task = state.tasks.first()
if (task is Task.Wait)
{
val dy = if (character.y > topLeft.y + 10) - 2 else 0
val dx = when
{
(topLeft.x + bottomRight.x) / 2 > character.x + 4 -> 3
(topLeft.x + bottomRight.x) / 2 < character.x - 4 -> -3
else -> 0
}
if (dx != 0 || dy != 0)
{
character.position += Point(dx, dy)
npcAnimation.update(
character.position,
when
{
dx > 0 -> Direction.Right
dx < 0 -> Direction.Left
else -> Direction.Up
})
}
else
{
npcAnimation.stop()
task.time -= 0.1
if (task.time <= 0.0)
{
state.tasks.removeAt(0)
npcAnimation.start()
}
}
}
else if (task is Task.Move)
{
val dx = Math.abs((task.location.midX - character.x).toDouble()).toInt()
if (character.y > bottomRight.y - 20 &&
dx < task.location.width / 4)
{
val item = task.location.item
if (item != null)
{
updateItemSprite(item, null)
character.items.add(item)
task.location.item = null
}
else if (task.placeItem != null)
{
updateItemSprite(task.placeItem, task.location)
character.items.remove(task.placeItem)
task.location.item = task.placeItem
}
state.tasks.removeAt(0)
}
else
{
val shift = Point(
when
{
task.location.midX > character.x + 4 -> 3
task.location.midX < character.x - 4 -> -3
else -> 0
},
if (character.y < bottomRight.y) 2 else 0)
character.position += shift
npcAnimation.update(
character.position,
if (shift.x > 0) Direction.Right else Direction.Left)
}
}
}
}
is LevelState.AwaitFailure ->
{
state.progress -= 0.005
if (state.progress <= 0.0)
{
levelCompleted = false
}
}
}
val location = activeLocation
if (location != null)
{
highlightSprite.position = PIXI.Point(location.x, location.y - 10)
highlightSprite.visible = true
}
else
{
highlightSprite.visible = false
}
if (npcSpriteFirst)
{
if (npcSprite.position.y.toInt() < playerSprite.position.y.toInt())
{
roomRoot.swapChildren(playerSprite, npcSprite)
npcSpriteFirst = false
}
}
else
{
if (npcSprite.position.y.toInt() > playerSprite.position.y.toInt())
{
roomRoot.swapChildren(playerSprite, npcSprite)
npcSpriteFirst = true
}
}
}
fun PIXI.Graphics.draw(item: GameItem)
{
drawRect(item.x, item.y, item.width, item.height)
}
fun initFailure(messages: List<String>)
{
val text = PIXI.Text(messages.take(3).joinToString("\n"), TextStyle(
fill = "blanchedAlmond",
font = "14pt bold",
align = "center"))
val width = text.width.toInt() + Dialog.side * 2 + Dialog.tileSize * 2
val height = text.height.toInt() + Dialog.side * 2 + Dialog.tileSize
val dialog = Dialog(
roomRoot,
PIXI.Rectangle((size.x - width) / 2, 0, width, height),
dialogTexture)
text.position = PIXI.Point(
(dialog.clientWidth - text.width.toInt()) / 2,
(dialog.clientHeight - text.height.toInt()) / 2)
dialog.add(text)
currentState = LevelState.AwaitFailure(1.0)
}
fun updateItemSprite(item: Item, location: Location?)
{
val sprite = itemSprites[allItems.indexOf(item)]
if (location == null)
{
sprite.visible = false
}
else
{
sprite.position = PIXI.Point(
location.position.x + (location.width - item.width) / 2,
location.position.y - item.height / 4 - 15)
val scale = item.width / sprite.texture.frame.width.toDouble()
sprite.scale = PIXI.Point(scale, scale)
sprite.visible = true
}
}
fun move(shift: Point)
{
val state = currentState
val scaleShift = shift * 4
var newPosition = player.position + scaleShift
if (state is LevelState.ManageItems)
{
newPosition = state.character.block(player, scaleShift) ?: newPosition
}
player.position = newPosition.clamp(topLeft, bottomRight)
}
fun createTasks(character: Character): ArrayList<Task>
{
val heldItems = character.items
val placedItems = locations.mapNotNull{ it.item }
val maxActions = heldItems.size + placedItems.size
val actions = Math.min(2, (Math.random() * (maxActions - 1)).toInt() + 1)
val _takeActions = (Math.random() * actions).toInt()
val _placeActions = Math.min(actions - _takeActions, heldItems.size)
val takeActions = Math.min(placedItems.size, Math.max(_takeActions, actions - _placeActions))
val placeActions = Math.min(heldItems.size, Math.max(_placeActions, actions - takeActions))
val tasks = arrayListOf<Task>()
for (i in 0..takeActions - 1)
{
val item = placedItems[i]
val location = locations.first{ it.item == item }
tasks.add(Task.Move(location, null))
}
val placeLocations = ArrayList(locations)
permute(placeLocations)
for ((i, location) in placeLocations.take(placeActions).withIndex())
{
val item = heldItems[i]
tasks.add(Task.Move(location, item))
}
tasks.add(Task.Wait(0.5))
return tasks
}
fun GameItem.block(other: GameItem, shift: Point): Point?
{
val intersects =
other.x + shift.x in x - other.width..endX &&
other.y + shift.y in y - other.height..endY
return if (intersects)
{
val xClamp = when
{
x in other.endX..other.endX + shift.x -> x - other.width - 1
endX in other.x + shift.x..other.x -> endX + 1
else -> other.x + shift.x
}
val yClamp = when
{
y in other.endY..other.endY + shift.y -> y - other.height - 1
endY in other.y + shift.y..other.y -> endY + 1
else -> other.y + shift.y
}
Point(xClamp, yClamp)
}
else
{
null
}
}
fun action(inventoryIndex: Int)
{
val location = activeLocation
if (location != null)
{
val item = location.item
val replaceItem = inventory[inventoryIndex]
if (item != null)
{
updateItemSprite(item, null)
location.item = null
inventory[inventoryIndex] = item
}
if (replaceItem != null)
{
updateItemSprite(replaceItem, location)
location.item = replaceItem
if (item == null)
{
inventory[inventoryIndex] = null
}
}
}
val shift = size.x.toDouble() / (allItems.size) + 1
inventorySprites.forEach { it.visible = false }
for ((i, item) in allItems.withIndex())
{
val index = inventory.indexOf(item)
if (index >= 0)
{
val sprite = inventorySprites[i]
sprite.position = PIXI.Point((index + 1) * shift - sprite.width.toDouble() / 2, 10)
sprite.visible = true
}
}
}
fun hurry()
{
val state = currentState
if (state is LevelState.AwaitVisitor)
{
state.progress = 0.0
}
else if (state is LevelState.AwaitFailure)
{
state.progress = 0.08
}
}
companion object
{
val activateDistance = 20
}
}
object LevelResources
{
val roomTexture = PIXI.Texture.fromImage("images/room.png", false)
val tableTexture = PIXI.Texture.fromImage("images/table.png", false)
val itemsBase = PIXI.BaseTexture.fromImage("images/items.png", false)
val itemTextures = itemsBase.slice(100, 100, 100)
val charactersBase = PIXI.BaseTexture.fromImage("images/characters.png", false)
val characterTextures = charactersBase.slice(PIXI.Point(100, 162), 3, 4)
}
class CharacterAnimation(val sprite: PIXI.Sprite, var animationIndex: Int = 0)
{
var progress = 0.0
var isRunning = false
val scale = 0.65
var orientation = 1.0
fun start()
{
isRunning = true
}
fun stop()
{
isRunning = false
sprite.texture = LevelResources.characterTextures[animationIndex * 3 + 1]
}
fun update(position: Point, direction: Direction)
{
if (isRunning)
{
progress += 0.1
if (progress >= 4.0)
{
progress = 0.0
}
val frame = Math.floor(progress)
val texture = animationIndex * 3 + frame - 2 * frame.div(3)
sprite.texture = LevelResources.characterTextures[texture]
when (direction)
{
Direction.Right -> orientation = -1.0
Direction.Left -> orientation = 1.0
Direction.Up -> orientation = if (position.x < 280) 1.0 else -1.0
Direction.Down -> orientation = if (position.x < 280) -1.0 else 1.0
}
}
val dy = 200 - position.y
val perspective = 1.0 - dy / 270.0
val dx = (280 - position.x) * perspective
val x = 280 - dx
val scale = scale * perspective
sprite.scale = PIXI.Point(scale * orientation, scale)
val y = position.y - sprite.height.toInt()
val w = sprite.width.toInt() / 2
sprite.position =
if (sprite.scale.x.toDouble() > 0) PIXI.Point(x - w, y)
else PIXI.Point(x + w, y)
}
}
class Schedule(val characters: List<Character>,
val locations: List<Location>,
val rounds: Int)
{
class Entry(val character: Character)
{
val expectedState = arrayListOf<Pair<Location, Item?>>()
}
val entries = arrayListOf<Entry>()
var nextEntry = 0
val nextCharacter: Character
get() = entries[nextEntry].character
val completed: Boolean; get() = nextEntry >= entries.size
init
{
for (round in 0..rounds - 1)
{
characters.forEach { entries.add(Entry(it)) }
permute(entries, round * characters.size, characters.size)
}
if (characters.size > 1)
{
for (round in 1..rounds - 1)
{
val borderIndex = round * characters.size
if (entries[borderIndex].character == entries[borderIndex - 1].character)
{
val swapIndex =
borderIndex + 1 + (Math.random() * (characters.size - 1)).toInt()
val t = entries[borderIndex]
entries[borderIndex] = entries[swapIndex]
entries[swapIndex] = t
}
}
}
for (character in characters)
{
val entry = entries.first{it.character == character}
for (location in locations)
{
entry.expectedState.add(Pair(location, null))
}
}
}
fun nextVisit(character: Character) =
(nextEntry + 1..entries.size - 1)
.firstOrNull{ entries[it].character == character }
?: - 1
fun rememberState()
{
val returnEntry = nextVisit(entries[nextEntry].character)
++nextEntry
if (returnEntry >= 0)
{
val entry = entries[returnEntry]
for (location in locations)
{
entry.expectedState.add(Pair(location, location.item))
}
}
}
fun checkState(): List<String>
{
val result = ArrayList<String>()
val entry = entries[nextEntry]
val expectedItems = entry.expectedState.mapNotNull{ it.second }
for ((location, item) in entry.expectedState)
{
val existingItem = location.item
if (existingItem == null)
{
if (item != null && !locations.any{it.item == item})
{
result.add("Where is my ${item.name}?!")
}
}
else if (!expectedItems.contains(existingItem))
{
result.add("What is this ${existingItem.name} doing here?!")
}
else if (existingItem != item)
{
result.add("Why has my ${existingItem.name} been moved?!")
}
}
return result
}
}
inline fun <reified T> permute(list: MutableList<T>,
start: Int = 0,
count: Int = list.size)
{
for (i in 0..count - 1)
{
val swapIndex = (Math.random() * (i + 1)).toInt()
if (swapIndex < i)
{
val t = list[start + swapIndex]
list[start + swapIndex] = list[start + i]
list[start + i] = t
}
}
}
open class GameItem(val size: Point)
{
var position = Point.zero
val x: Int; get() = position.x
val y: Int; get() = position.y
val width: Int; get() = size.x
val height: Int; get() = size.y
val midX: Int; get() = x + width / 2
val midY: Int; get() = y + height / 2
val endX: Int; get() = x + width
val endY: Int; get() = y + height
}
class Location(size: Point) : GameItem(size)
{
var item: Item? = null
}
class Character(size: Point) : GameItem(size)
{
val items = arrayListOf<Item>()
}
class Item(val size: Point, val name: String)
{
val width: Int; get() = size.x
val height: Int; get() = size.y
} | mit | 523e861102feceb12567d7a640bf8f36 | 30.331748 | 130 | 0.503359 | 4.676784 | false | false | false | false |
anton-okolelov/intellij-rust | src/test/kotlin/org/rust/ide/inspections/RsExtraSemicolonInspectionTest.kt | 2 | 1929 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
class RsExtraSemicolonInspectionTest : RsInspectionsTestBase(RsExtraSemicolonInspection()) {
fun `test not applicable without return type`() = checkByText("""
fn foo() { 92; }
""")
fun `test not applicable for let`() = checkByText("""
fn foo() -> i32 { let x = 92; }
""")
fun `test not applicable with explicit return`() = checkByText("""
fn foo() -> i32 { return 92; }
""")
fun `test not applicable with explicit unit type`() = checkByText("""
fn fun() -> () { 2 + 2; }
""")
fun `test not applicable with macro`() = checkByText("""
fn fun() -> i32 { panic!("diverge"); }
""")
fun `test not applicable with trailing fn`() = checkByText("""
fn foo() -> bool {
loop {}
fn f() {}
}
""")
fun `test not applicable with diverging if`() = checkByText("""
fn a() -> i32 {
if true { return 0; } else { return 6; };
}
""")
fun `test fix`() = checkFixByText("Remove semicolon", """
fn foo() -> i32 {
let x = 92;
<warning descr="Function returns () instead of i32">x;<caret></warning>
}
""", """
fn foo() -> i32 {
let x = 92;
x
}
""")
fun `test recurse into complex expressions`() = checkFixByText("Remove semicolon", """
fn foo() -> i32 {
let x = 92;
if true {
<warning descr="Function returns () instead of i32">x;<caret></warning>
} else {
x
}
}
""", """
fn foo() -> i32 {
let x = 92;
if true {
x<caret>
} else {
x
}
}
""")
}
| mit | 9ecdafe3f426426dd7825d1f092de3d9 | 24.72 | 92 | 0.468118 | 4.465278 | false | true | false | false |
Ekito/koin | koin-projects/examples/androidx-compose-jetnews/src/main/java/com/example/jetnews/ui/Navigation.kt | 1 | 4581 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.example.jetnews.ui
import android.os.Bundle
import androidx.annotation.MainThread
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.core.os.bundleOf
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import com.example.jetnews.ui.Screen.*
import com.example.jetnews.ui.ScreenName.*
import com.example.jetnews.utils.getMutableStateOf
/**
* Screen names (used for serialization)
*/
enum class ScreenName { HOME, INTERESTS, ARTICLE }
/**
* Class defining the screens we have in the app: home, article details and interests
*/
sealed class Screen(val id: ScreenName) {
object Home : Screen(HOME)
object Interests : Screen(INTERESTS)
data class Article(val postId: String) : Screen(ARTICLE)
}
/**
* Helpers for saving and loading a [Screen] object to a [Bundle].
*
* This allows us to persist navigation across process death, for example caused by a long video
* call.
*/
private const val SIS_SCREEN = "sis_screen"
private const val SIS_NAME = "screen_name"
private const val SIS_POST = "post"
/**
* Convert a screen to a bundle that can be stored in [SavedStateHandle]
*/
private fun Screen.toBundle(): Bundle {
return bundleOf(SIS_NAME to id.name).also {
// add extra keys for various types here
if (this is Article) {
it.putString(SIS_POST, postId)
}
}
}
/**
* Read a bundle stored by [Screen.toBundle] and return desired screen.
*
* @return the parsed [Screen]
* @throws IllegalArgumentException if the bundle could not be parsed
*/
private fun Bundle.toScreen(): Screen {
val screenName = ScreenName.valueOf(getStringOrThrow(SIS_NAME))
return when (screenName) {
HOME -> Home
INTERESTS -> Interests
ARTICLE -> {
val postId = getStringOrThrow(SIS_POST)
Article(postId)
}
}
}
/**
* Throw [IllegalArgumentException] if key is not in bundle.
*
* @see Bundle.getString
*/
private fun Bundle.getStringOrThrow(key: String) =
requireNotNull(getString(key)) { "Missing key '$key' in $this" }
/**
* This is expected to be replaced by the navigation component, but for now handle navigation
* manually.
*
* Instantiate this ViewModel at the scope that is fully-responsible for navigation, which in this
* application is [MainActivity].
*
* This app has simplified navigation; the back stack is always [Home] or [Home, dest] and more
* levels are not allowed. To use a similar pattern with a longer back stack, use a [StateList] to
* hold the back stack state.
*/
class NavigationViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() {
/**
* Hold the current screen in an observable, restored from savedStateHandle after process
* death.
*
* mutableStateOf is an observable similar to LiveData that's designed to be read by compose. It
* supports observability via property delegate syntax as shown here.
*/
var currentScreen: Screen by savedStateHandle.getMutableStateOf<Screen>(
key = SIS_SCREEN,
default = Home,
save = { it.toBundle() },
restore = { it.toScreen() }
)
private set // limit the writes to only inside this class.
/**
* Go back (always to [Home]).
*
* Returns true if this call caused user-visible navigation. Will always return false
* when [currentScreen] is [Home].
*/
@MainThread
fun onBack(): Boolean {
val wasHandled = currentScreen != Home
currentScreen = Home
return wasHandled
}
/**
* Navigate to requested [Screen].
*
* If the requested screen is not [Home], it will always create a back stack with one element:
* ([Home] -> [screen]). More back entries are not supported in this app.
*/
@MainThread
fun navigateTo(screen: Screen) {
currentScreen = screen
}
} | apache-2.0 | c879d7ffda116d396fad781980ccb0d6 | 31.267606 | 100 | 0.689587 | 4.277311 | false | false | false | false |
semonte/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/ScriptGenerator.kt | 1 | 11686 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.recorder
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.ui.SimpleToolWindowPanel
import com.intellij.openapi.util.Ref
import com.intellij.openapi.wm.WindowManager
import com.intellij.testGuiFramework.fixtures.SettingsTreeFixture
import com.intellij.testGuiFramework.generators.ComponentCodeGenerator
import com.intellij.testGuiFramework.generators.Generators
import com.intellij.testGuiFramework.recorder.ScriptGenerator.scriptBuffer
import com.intellij.testGuiFramework.recorder.components.GuiRecorderComponent
import com.intellij.testGuiFramework.recorder.ui.KeyUtil
import com.intellij.ui.KeyStrokeAdapter
import com.intellij.ui.treeStructure.SimpleTree
import com.intellij.util.ui.tree.TreeUtil
import java.awt.Component
import java.awt.Menu
import java.awt.MenuItem
import java.awt.Point
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import javax.swing.JComponent
import javax.swing.JList
import javax.swing.JTree
import javax.swing.KeyStroke.getKeyStrokeForEvent
import javax.swing.tree.TreeNode
import javax.swing.tree.TreePath
/**
* @author Sergey Karashevich
*/
object ScriptGenerator {
val scriptBuffer = StringBuilder("")
var openComboBox = false
fun getScriptBuffer() = scriptBuffer.toString()
fun clearScriptBuffer() = scriptBuffer.setLength(0)
private val generators: List<ComponentCodeGenerator<*>> = Generators.getGenerators()
object ScriptWrapper {
val TEST_METHOD_NAME = "testMe"
private fun classWrap(function: () -> (String)): String = "class CurrentTest: GuiTestCase() {\n${function.invoke()}\n}"
private fun funWrap(function: () -> String): String = "fun $TEST_METHOD_NAME(){\n${function.invoke()}\n}"
private fun importsWrap(vararg imports: String, function: () -> String): String {
val sb = StringBuilder()
imports.forEach { sb.append("$it\n") }
sb.append(function.invoke())
return sb.toString()
}
fun wrapScript(code: String): String =
importsWrap(
"import com.intellij.testGuiFramework.* ",
"import com.intellij.testGuiFramework.fixtures.*",
"import com.intellij.testGuiFramework.framework.*",
"import com.intellij.testGuiFramework.impl.*",
"import org.fest.swing.core.Robot",
"import java.awt.Component",
"import com.intellij.openapi.application.ApplicationManager",
"import org.fest.swing.fixture.*")
{
classWrap {
funWrap {
code
}
}
}
}
// fun actionPerformed(e: com.intellij.openapi.actionSystem.AnActionEvent?) {
// get action type for script: click, enter text, mark checkbox
// val component = e!!.getDataContext().getData("Component") as Component
// checkGlobalContext(component)
// clickCmp(component, e)
// }
fun processTyping(keyChar: Char) {
Typer.type(keyChar)
}
//(keyEvent.id == KeyEvent.KEY_PRESSED) for all events here
fun processKeyPressing(keyEvent: KeyEvent) {
//retrieve shortcut here
// val keyStroke = getKeyStrokeForEvent(keyEvent)
// val actionIds = KeymapManager.getInstance().activeKeymap.getActionIds(keyStroke)
// if (!actionIds.isEmpty()) {
// val firstActionId = actionIds[0]
// if (IgnoredActions.ignore(firstActionId)) return
// val keyStrokeStr = KeyStrokeAdapter.toString(keyStroke)
// if (IgnoredActions.ignore(keyStrokeStr)) return
// Writer.writeln(Templates.invokeActionComment(firstActionId))
// makeIndent()
// Writer.writeln(Templates.shortcut(keyStrokeStr))
// }
}
fun processKeyActionEvent(anAction: AnAction, anActionEvent: AnActionEvent) {
//retrieve shortcut here
val keyEvent = anActionEvent.inputEvent as KeyEvent
val keyStroke = getKeyStrokeForEvent(keyEvent)
val actionId = anActionEvent.actionManager.getId(anAction)
if (IgnoredActions.ignore(actionId)) return
val keyStrokeStr = KeyStrokeAdapter.toString(keyStroke)
if (IgnoredActions.ignore(keyStrokeStr)) return
ScriptGenerator.flushTyping()
addToScript(Templates.invokeActionComment(actionId))
addToScript(Templates.shortcut(keyStrokeStr))
}
// clickComponent methods
fun clickComponent(component: Component, convertedPoint: Point, me: MouseEvent) {
awareListsAndPopups(component) {
ContextChecker.checkContext(component, me, convertedPoint)
// checkGlobalContext(component, me, convertedPoint)
// checkLocalContext(component, me, convertedPoint)
}
val suitableGenerator = generators.filter { generator -> generator.accept(component) }.sortedByDescending(
ComponentCodeGenerator<*>::priority).firstOrNull() ?: return
val code = suitableGenerator.generateCode(component, me, convertedPoint)
addToScript(code)
}
//
fun awareListsAndPopups(cmp: Component, body: () -> Unit) {
cmp as JComponent
if (cmp is JList<*> && openComboBox) return //don't change context for comboBox list
if (isPopupList(cmp)) return //dont' change context for a popup menu
body()
}
fun clearContext() {
ContextChecker.clearContext()
}
fun processMainMenuActionEvent(anActionToBePerformed: AnAction, anActionEvent: AnActionEvent) {
val actionId: String? = ActionManager.getInstance().getId(anActionToBePerformed)
if (actionId == null) {
addToScript("//called action (${anActionToBePerformed.templatePresentation.text}) from main menu with null actionId"); return
}
addToScript(Templates.invokeMainMenuAction(actionId))
}
fun flushTyping() {
Typer.flushBuffer()
}
private fun isPopupList(cmp: Component) = cmp.javaClass.name.toLowerCase().contains("listpopup")
private fun isFrameworksTree(cmp: Component) = cmp.javaClass.name.toLowerCase().contains("AddSupportForFrameworksPanel".toLowerCase())
private fun Component.inToolWindow(): Boolean {
var pivotComponent = this
while (pivotComponent.parent != null) {
if (pivotComponent is SimpleToolWindowPanel) return true
else pivotComponent = pivotComponent.parent
}
return false
}
fun addToScript(code: String, withIndent: Boolean = true, indent: Int = 2) {
if (withIndent) {
val indentedString = (0..(indent * ContextChecker.getContextDepth() - 1)).map { i -> ' ' }.joinToString(separator = "")
ScriptGenerator.addToScriptDelegate("$indentedString$code")
}
else ScriptGenerator.addToScriptDelegate(code)
}
//use it for outer generators
private fun addToScriptDelegate(code: String?) {
if (code != null) Writer.writeln(code)
}
}
object Writer {
fun writeln(str: String) {
write(str + "\n")
}
fun write(str: String) {
writeToConsole(str)
if (GuiRecorderComponent.getFrame() != null && GuiRecorderComponent.getFrame()!!.isSyncToEditor())
writeToEditor(str)
else
writeToBuffer(str)
}
fun writeToConsole(str: String) {
print(str)
}
fun writeToBuffer(str: String) {
scriptBuffer.append(str)
}
fun writeToEditor(str: String) {
if (GuiRecorderComponent.getFrame() != null && GuiRecorderComponent.getFrame()!!.getEditor() != null) {
val editor = GuiRecorderComponent.getFrame()!!.getEditor()
val document = editor.document
// ApplicationManager.getApplication().runWriteAction { document.insertString(document.textLength, str) }
WriteCommandAction.runWriteCommandAction(null, { document.insertString(document.textLength, str) })
}
}
}
private object Typer {
val strBuffer = StringBuilder()
val rawBuffer = StringBuilder()
fun type(keyChar: Char) {
strBuffer.append(KeyUtil.patch(keyChar))
rawBuffer.append("${if (rawBuffer.length > 0) ", " else ""}\"${keyChar.toInt()}\"")
}
fun flushBuffer() {
if (strBuffer.length == 0) return
ScriptGenerator.addToScript("//typed:[${strBuffer.length},\"${strBuffer.toString()}\", raw=[${rawBuffer.toString()}]]")
ScriptGenerator.addToScript(Templates.typeText(strBuffer.toString()))
strBuffer.setLength(0)
rawBuffer.setLength(0)
}
}
//TEMPLATES
object IgnoredActions {
val ignoreActions = listOf("EditorBackSpace")
val ignoreShortcuts = listOf("space")
fun ignore(actionOrShortCut: String): Boolean = (ignoreActions.contains(actionOrShortCut) || ignoreShortcuts.contains(actionOrShortCut))
}
object Util {
// fun isActionFromMainMenu(anActionTobePerformed: AnAction, anActionEvent: AnActionEvent): Boolean {
// val menuBar = WindowManager.getInstance().findVisibleFrame().menuBar ?: return false
// }
fun getPathFromMainMenu(anActionTobePerformed: AnAction, anActionEvent: AnActionEvent): String? {
// WindowManager.getInstance().findVisibleFrame().menuBar.getMenu(0).label
val menuBar = WindowManager.getInstance().findVisibleFrame().menuBar ?: return null
//in fact it should be only one String in "map"
return (0..(menuBar.menuCount - 1)).mapNotNull {
traverseMenu(menuBar.getMenu(it), anActionTobePerformed.templatePresentation.text!!)
}.lastOrNull()
}
fun traverseMenu(menuItem: MenuItem, itemName: String): String? {
if (menuItem is Menu) {
if (menuItem.itemCount == 0) {
if (menuItem.label == itemName) return itemName
else return null
}
else {
(0..(menuItem.itemCount - 1))
.mapNotNull { traverseMenu(menuItem.getItem(it), itemName) }
.forEach { return "${menuItem.label};$it" }
return null
}
}
else {
if (menuItem.label == itemName) return itemName
else return null
}
}
fun convertSimpleTreeItemToPath(tree: SimpleTree, itemName: String): String {
val searchableNodeRef = Ref.create<TreeNode>()
val searchableNode: TreeNode?
TreeUtil.traverse(tree.getModel().getRoot() as TreeNode) { node ->
val valueFromNode = SettingsTreeFixture.getValueFromNode(tree, node)
if (valueFromNode != null && valueFromNode == itemName) {
assert(node is TreeNode)
searchableNodeRef.set(node as TreeNode)
}
true
}
searchableNode = searchableNodeRef.get()
val path = TreeUtil.getPathFromRoot(searchableNode!!)
return (0..path.pathCount - 1).map { path.getPathComponent(it).toString() }.filter(String::isNotEmpty).joinToString("/")
}
fun getJTreePath(cmp: JTree, path: TreePath): String {
var treePath = path
val result = StringBuilder()
val bcr = org.fest.swing.driver.BasicJTreeCellReader()
while (treePath.pathCount != 1 || (cmp.isRootVisible && treePath.pathCount == 1)) {
val valueAt = bcr.valueAt(cmp, treePath.lastPathComponent)
result.insert(0, "$valueAt${if (!result.isEmpty()) "/" else ""}")
if (treePath.pathCount == 1) break
else treePath = treePath.parentPath
}
return result.toString()
}
} | apache-2.0 | a862cb717b5d869da2f9dd4dacc1a605 | 34.308157 | 138 | 0.708882 | 4.462008 | false | false | false | false |
AllanWang/Frost-for-Facebook | app/src/main/kotlin/com/pitchedapps/frost/views/SwipeRefreshLayout.kt | 1 | 3907 | /*
* Copyright 2019 Allan Wang
*
* 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.pitchedapps.frost.views
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.webkit.WebView
import android.widget.ListView
import androidx.core.widget.ListViewCompat
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnChildScrollUpCallback
import com.pitchedapps.frost.prefs.Prefs
import com.pitchedapps.frost.utils.L
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
/**
* Variant that forbids refreshing if child layout is not at the top Inspired by
* https://github.com/slapperwan/gh4a/blob/master/app/src/main/java/com/gh4a/widget/SwipeRefreshLayout.java
*/
@AndroidEntryPoint
class SwipeRefreshLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
SwipeRefreshLayout(context, attrs) {
@Inject lateinit var prefs: Prefs
private var preventRefresh: Boolean = false
private var downY: Float = -1f
private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
private var nestedCanChildScrollUp: OnChildScrollUpCallback? = null
/** Copy of [canChildScrollUp], with additional support if necessary */
private val canChildScrollUp = OnChildScrollUpCallback { parent, child ->
nestedCanChildScrollUp?.canChildScrollUp(parent, child)
?: when (child) {
is WebView -> child.canScrollVertically(-1).apply { L.d { "Webview can scroll up $this" } }
is ListView -> ListViewCompat.canScrollList(child, -1)
// Supports webviews as well
else -> child?.canScrollVertically(-1) ?: false
}
}
init {
setOnChildScrollUpCallback(canChildScrollUp)
}
override fun setOnChildScrollUpCallback(callback: OnChildScrollUpCallback?) {
this.nestedCanChildScrollUp = callback
}
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
if (!prefs.swipeToRefresh) {
return false
}
if (ev.action != MotionEvent.ACTION_DOWN && preventRefresh) {
return false
}
when (ev.action) {
MotionEvent.ACTION_DOWN -> {
downY = ev.y
preventRefresh = canChildScrollUp()
}
MotionEvent.ACTION_MOVE -> {
if (downY - ev.y > touchSlop) {
preventRefresh = true
return false
}
}
}
return super.onInterceptTouchEvent(ev)
}
override fun onStartNestedScroll(child: View, target: View, nestedScrollAxes: Int): Boolean {
return prefs.swipeToRefresh && super.onStartNestedScroll(child, target, nestedScrollAxes)
}
override fun onNestedScroll(
target: View,
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int
) {
if (preventRefresh) {
/*
* Ignoring offsetInWindow since
* 1. It doesn't seem to matter in the typical use case
* 2. It isn't being transferred to the underlying array used by the super class
*/
dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, null)
} else {
super.onNestedScroll(target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed)
}
}
}
| gpl-3.0 | d62d815711aa58c674089e881e627617 | 33.575221 | 107 | 0.727156 | 4.591069 | false | false | false | false |
HendraAnggrian/kota | kota/src/fragments/FragmentTransits.kt | 1 | 2059 | package kota
import android.app.FragmentTransaction
import android.app.FragmentTransaction.*
import android.support.annotation.AnimatorRes
import android.support.annotation.StyleRes
import kota.FragmentTransit.Companion.TRANSIT_TYPE_CONSTANT
import kota.FragmentTransit.Companion.TRANSIT_TYPE_CUSTOM
open class FragmentTransit @PublishedApi internal constructor(
private val type: Int,
private vararg val value: Int
) {
operator fun component1(): Int = type
operator fun component2(): IntArray = value
companion object {
const val TRANSIT_TYPE_CUSTOM: Int = 0
const val TRANSIT_TYPE_CONSTANT: Int = 1
const val TRANSIT_TYPE_STYLE: Int = 2
}
}
open class CustomTransit : FragmentTransit {
constructor(
@AnimatorRes enter: Int,
@AnimatorRes exit: Int
) : super(TRANSIT_TYPE_CUSTOM, enter, exit)
constructor(
@AnimatorRes enter: Int,
@AnimatorRes exit: Int,
@AnimatorRes popEnter: Int,
@AnimatorRes popExit: Int
) : super(TRANSIT_TYPE_CUSTOM, enter, exit, popEnter, popExit)
}
object NoTransit : FragmentTransit(TRANSIT_TYPE_CONSTANT, TRANSIT_NONE)
object OpenTransit : FragmentTransit(TRANSIT_TYPE_CONSTANT, TRANSIT_FRAGMENT_OPEN)
object CloseTransit : FragmentTransit(TRANSIT_TYPE_CONSTANT, TRANSIT_FRAGMENT_CLOSE)
open class FadeTransit : FragmentTransit(TRANSIT_TYPE_CONSTANT, TRANSIT_FRAGMENT_FADE) {
companion object : FadeTransit()
}
open class StyleTransit(@StyleRes styleRes: Int) : FragmentTransit(TRANSIT_TYPE_STYLE, styleRes)
@PublishedApi
@Suppress("NOTHING_TO_INLINE")
internal inline fun FragmentTransaction.setTransit(transit: FragmentTransit): FragmentTransaction = transit.let { (type, value) ->
return when (type) {
TRANSIT_TYPE_CUSTOM -> if (value.size == 2) setCustomAnimations(value[0], value[1]) else setCustomAnimations(value[0], value[1], value[2], value[3])
TRANSIT_TYPE_CONSTANT -> setTransition(value[0])
else -> setTransitionStyle(value[0])
}
} | apache-2.0 | 3be7cd53d720851c7b6a32d6f1076acf | 35.785714 | 156 | 0.72171 | 4.316562 | false | false | false | false |
minibugdev/Collaborate-Board | app/src/main/kotlin/com/trydroid/coboard/CoBoardActivity.kt | 1 | 2495 | package com.trydroid.coboard
import android.graphics.Point
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import com.google.firebase.database.*
import kotlinx.android.synthetic.main.activity_main.*
class CoBoardActivity : AppCompatActivity() {
private val mLinesReference: DatabaseReference by lazy {
FirebaseDatabase.getInstance().reference.child(CHILD_LINES)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_co_board, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?) =
when (item?.itemId) {
R.id.action_clear -> consumeMenuSelected { removeFirebaseChild() }
else -> super.onOptionsItemSelected(item)
}
override fun onStart() {
super.onStart()
mLinesReference.addChildEventListener(mLinesReferenceListener)
drawView.drawListener = { lineList ->
lineList?.let { sendToFirebase(lineList) }
}
}
override fun onStop() {
super.onStop()
mLinesReference.removeEventListener(mLinesReferenceListener)
drawView.drawListener = null
}
private fun sendToFirebase(lineList: List<Point>) {
mLinesReference.push().setValue(lineList)
}
private fun removeFirebaseChild() {
mLinesReference.removeValue()
}
private fun clearDrawView() {
drawView.clear()
}
private fun drawLine(lineList: List<Point>) {
drawView.drawLine(lineList)
}
private val mLinesReferenceListener = object : ChildEventListener {
override fun onChildAdded(dataSnapshot: DataSnapshot?, p1: String?) {
Log.e(TAG, "onChildAdded")
dataSnapshot?.children
?.map { children -> children.getValue<Point>(Point::class.java) }
?.let { lineList -> drawLine(lineList) }
}
override fun onChildRemoved(dataSnapshot: DataSnapshot?) {
Log.e(TAG, "onChildRemoved")
clearDrawView()
}
override fun onChildMoved(dataSnapshot: DataSnapshot?, p1: String?) {
}
override fun onChildChanged(dataSnapshot: DataSnapshot?, p1: String?) {
}
override fun onCancelled(databaseError: DatabaseError) {
}
}
inline fun consumeMenuSelected(func: () -> Unit): Boolean {
func()
return true
}
companion object {
private val TAG = CoBoardActivity::class.java.simpleName
private val CHILD_LINES = "lines"
}
}
| mit | 1c5b0ae177cd863738bd2584e0fcdb77 | 24.721649 | 73 | 0.744289 | 3.826687 | false | false | false | false |
eprendre/v2rayNG | V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/PerAppProxyAdapter.kt | 1 | 3380 | package com.v2ray.ang.ui
import android.graphics.Color
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.v2ray.ang.R
import com.v2ray.ang.dto.AppInfo
import kotlinx.android.synthetic.main.item_recycler_bypass_list.view.*
import org.jetbrains.anko.image
import org.jetbrains.anko.layoutInflater
import org.jetbrains.anko.textColor
import java.util.*
class PerAppProxyAdapter(val activity: BaseActivity, val apps: List<AppInfo>, blacklist: MutableSet<String>?) :
RecyclerView.Adapter<PerAppProxyAdapter.BaseViewHolder>() {
companion object {
private const val VIEW_TYPE_HEADER = 0
private const val VIEW_TYPE_ITEM = 1
}
private var mActivity: BaseActivity = activity
val blacklist = if (blacklist == null) HashSet<String>() else HashSet<String>(blacklist)
override fun onBindViewHolder(holder: BaseViewHolder?, position: Int) {
if (holder is AppViewHolder) {
val appInfo = apps[position - 1]
holder.bind(appInfo)
}
}
override fun getItemCount() = apps.size + 1
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder? {
val ctx = parent.context
return when (viewType) {
VIEW_TYPE_HEADER -> {
val view = View(ctx)
view.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ctx.resources.getDimensionPixelSize(R.dimen.bypass_list_header_height) * 3)
BaseViewHolder(view)
}
VIEW_TYPE_ITEM -> AppViewHolder(ctx.layoutInflater
.inflate(R.layout.item_recycler_bypass_list, parent, false))
else -> null
}
}
override fun getItemViewType(position: Int)
= if (position == 0) VIEW_TYPE_HEADER else VIEW_TYPE_ITEM
open class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
inner class AppViewHolder(itemView: View) : BaseViewHolder(itemView),
View.OnClickListener {
private val inBlacklist: Boolean get() = blacklist.contains(appInfo.packageName)
private lateinit var appInfo: AppInfo
val icon = itemView.icon!!
val name = itemView.name!!
val checkBox = itemView.check_box!!
fun bind(appInfo: AppInfo) {
this.appInfo = appInfo
icon.image = appInfo.appIcon
// name.text = appInfo.appName
checkBox.isChecked = inBlacklist
// name.textColor = mActivity.resources.getColor(if (appInfo.isSystemApp)
// R.color.color_highlight_material else R.color.abc_secondary_text_material_light)
if (appInfo.isSystemApp) {
name.text = String.format("** %1s", appInfo.appName)
name.textColor = Color.RED
} else {
name.text = appInfo.appName
name.textColor = Color.DKGRAY
}
itemView.setOnClickListener(this)
}
override fun onClick(v: View?) {
if (inBlacklist) {
blacklist.remove(appInfo.packageName)
checkBox.isChecked = false
} else {
blacklist.add(appInfo.packageName)
checkBox.isChecked = true
}
}
}
} | mit | 78169b04e89d78b287ffe4768d4361d8 | 33.151515 | 111 | 0.626923 | 4.623803 | false | false | false | false |
msebire/intellij-community | plugins/svn4idea/src/org/jetbrains/idea/svn/info/Info.kt | 1 | 1739 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.svn.info
import org.jetbrains.idea.svn.api.*
import org.jetbrains.idea.svn.checkin.CommitInfo
import org.jetbrains.idea.svn.conflict.TreeConflictDescription
import org.jetbrains.idea.svn.lock.Lock
import java.io.File
private fun resolveConflictFile(file: File?, path: String?) = if (file != null && path != null) File(file.parentFile, path) else null
class Info(val file: File?,
val url: Url?,
val revision: Revision,
nodeKind: NodeKind,
val repositoryRootUrl: Url?,
val repositoryId: String?,
commitInfo: CommitInfo? = null,
val schedule: String? = null,
val depth: Depth? = null,
val copyFromUrl: Url? = null,
val copyFromRevision: Revision = Revision.UNDEFINED,
val lock: Lock? = null,
conflictOldFileName: String? = null,
conflictNewFileName: String? = null,
conflictWorkingFileName: String? = null,
val treeConflict: TreeConflictDescription? = null) : BaseNodeDescription(nodeKind) {
val commitInfo: CommitInfo = commitInfo ?: CommitInfo.EMPTY
val conflictOldFile = resolveConflictFile(file, conflictOldFileName)
val conflictNewFile = resolveConflictFile(file, conflictNewFileName)
val conflictWrkFile = resolveConflictFile(file, conflictWorkingFileName)
@Deprecated("Use nodeKind property", ReplaceWith("nodeKind"))
val kind
get() = nodeKind
@Deprecated("Use url property", ReplaceWith("url"))
fun getURL() = url
companion object {
const val SCHEDULE_ADD = "add"
}
} | apache-2.0 | d6736694799c607fedb3ae28d9459f17 | 39.465116 | 140 | 0.691777 | 4.358396 | false | false | false | false |
RyotaMurohoshi/KotLinq | src/main/kotlin/com/muhron/kotlinq/sum.kt | 1 | 8474 | package com.muhron.kotlinq
import com.muhron.kotlinq.inner.Calculator
@JvmName("sumOfByte")
fun Sequence<Byte>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfShort")
fun Sequence<Short>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfInt")
fun Sequence<Int>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfLong")
fun Sequence<Long>.sum(): Long {
return Calculator.sum(this)
}
@JvmName("sumOfFloat")
fun Sequence<Float>.sum(): Float {
return Calculator.sum(this)
}
@JvmName("sumOfDouble")
fun Sequence<Double>.sum(): Double {
return Calculator.sum(this)
}
@JvmName("sumOfByte")
fun Iterable<Byte>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfShort")
fun Iterable<Short>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfInt")
fun Iterable<Int>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfLong")
fun Iterable<Long>.sum(): Long {
return Calculator.sum(this)
}
@JvmName("sumOfFloat")
fun Iterable<Float>.sum(): Float {
return Calculator.sum(this)
}
@JvmName("sumOfDouble")
fun Iterable<Double>.sum(): Double {
return Calculator.sum(this)
}
@JvmName("sumOfByte")
fun Array<Byte>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfShort")
fun Array<Short>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfInt")
fun Array<Int>.sum(): Int {
return Calculator.sum(this)
}
@JvmName("sumOfLong")
fun Array<Long>.sum(): Long {
return Calculator.sum(this)
}
@JvmName("sumOfFloat")
fun Array<Float>.sum(): Float {
return Calculator.sum(this)
}
@JvmName("sumOfDouble")
fun Array<Double>.sum(): Double {
return Calculator.sum(this)
}
fun ByteArray.sum(): Int {
require(any()) { "empty." }
return Calculator.sum(this)
}
fun ShortArray.sum(): Int {
require(any()) { "empty." }
return Calculator.sum(this)
}
fun IntArray.sum(): Int {
require(any()) { "empty." }
return Calculator.sum(this)
}
fun LongArray.sum(): Long {
require(any()) { "empty." }
return Calculator.sum(this)
}
fun FloatArray.sum(): Float {
require(any()) { "empty." }
return Calculator.sum(this)
}
fun DoubleArray.sum(): Double {
require(any()) { "empty." }
return Calculator.sum(this)
}
@JvmName("sumOfByte")
fun <T> Sequence<T>.sum(selector: (T) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun <T> Sequence<T>.sum(selector: (T) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun <T> Sequence<T>.sum(selector: (T) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun <T> Sequence<T>.sum(selector: (T) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun <T> Sequence<T>.sum(selector: (T) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun <T> Sequence<T>.sum(selector: (T) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun <T> Iterable<T>.sum(selector: (T) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun <T> Iterable<T>.sum(selector: (T) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun <T> Iterable<T>.sum(selector: (T) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun <T> Iterable<T>.sum(selector: (T) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun <T> Iterable<T>.sum(selector: (T) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun <T> Iterable<T>.sum(selector: (T) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun <T> Array<T>.sum(selector: (T) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun <T> Array<T>.sum(selector: (T) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun <T> Array<T>.sum(selector: (T) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun <T> Array<T>.sum(selector: (T) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun <T> Array<T>.sum(selector: (T) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun <T> Array<T>.sum(selector: (T) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun ByteArray.sum(selector: (Byte) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun ByteArray.sum(selector: (Byte) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun ByteArray.sum(selector: (Byte) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun ByteArray.sum(selector: (Byte) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun ByteArray.sum(selector: (Byte) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun ByteArray.sum(selector: (Byte) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun ShortArray.sum(selector: (Short) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun ShortArray.sum(selector: (Short) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun ShortArray.sum(selector: (Short) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun ShortArray.sum(selector: (Short) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun ShortArray.sum(selector: (Short) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun ShortArray.sum(selector: (Short) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun IntArray.sum(selector: (Int) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun IntArray.sum(selector: (Int) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun IntArray.sum(selector: (Int) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun IntArray.sum(selector: (Int) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun IntArray.sum(selector: (Int) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun IntArray.sum(selector: (Int) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun LongArray.sum(selector: (Long) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun LongArray.sum(selector: (Long) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun LongArray.sum(selector: (Long) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun LongArray.sum(selector: (Long) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun LongArray.sum(selector: (Long) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun LongArray.sum(selector: (Long) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun FloatArray.sum(selector: (Float) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun FloatArray.sum(selector: (Float) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun FloatArray.sum(selector: (Float) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun FloatArray.sum(selector: (Float) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun FloatArray.sum(selector: (Float) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun FloatArray.sum(selector: (Float) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun DoubleArray.sum(selector: (Double) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun DoubleArray.sum(selector: (Double) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun DoubleArray.sum(selector: (Double) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun DoubleArray.sum(selector: (Double) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun DoubleArray.sum(selector: (Double) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun DoubleArray.sum(selector: (Double) -> Double): Double = map(selector).sum()
@JvmName("sumOfByte")
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.sum(selector: (Map.Entry<TSourceK, TSourceV>) -> Byte): Int = map(selector).sum()
@JvmName("sumOfShort")
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.sum(selector: (Map.Entry<TSourceK, TSourceV>) -> Short): Int = map(selector).sum()
@JvmName("sumOfInt")
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.sum(selector: (Map.Entry<TSourceK, TSourceV>) -> Int): Int = map(selector).sum()
@JvmName("sumOfLong")
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.sum(selector: (Map.Entry<TSourceK, TSourceV>) -> Long): Long = map(selector).sum()
@JvmName("sumOfFloat")
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.sum(selector: (Map.Entry<TSourceK, TSourceV>) -> Float): Float = map(selector).sum()
@JvmName("sumOfDouble")
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.sum(selector: (Map.Entry<TSourceK, TSourceV>) -> Double): Double = map(selector).sum()
| mit | c3bd541cb150683733df0793a2a55a8f | 25.398754 | 135 | 0.675124 | 3.260485 | false | false | false | false |
bs616/Note | app/src/main/java/com/dev/bins/note/utils/InitData.kt | 1 | 485 | package com.dev.bins.note.utils
/**
* Created by bin on 11/25/15.
*/
object InitData {
fun initCategory() {
// val db = Connector.getDatabase()
// val category = Category()
// category.categoty = "默认"
// category.save()
//
// val category1 = Category()
// category1.categoty = "剪切板"
// category1.save()
//
// val category2 = Category()
// category2.categoty = "私人"
// category2.save()
}
}
| apache-2.0 | 06e5e24faf166bb7b336988fdc874ee0 | 20.409091 | 42 | 0.539278 | 3.204082 | false | false | false | false |
ebraminio/DroidPersianCalendar | PersianCalendar/src/test/java/com/byagowi/persiancalendar/MainLogicTests.kt | 1 | 24970 | package com.byagowi.persiancalendar
import com.byagowi.persiancalendar.utils.CalendarType
import com.byagowi.persiancalendar.utils.getDayOfWeekFromJdn
import com.byagowi.persiancalendar.utils.getMonthLength
import com.byagowi.persiancalendar.utils.isMoonInScorpio
import com.cepmuvakkit.times.view.QiblaCompassView
import io.github.persiancalendar.Equinox
import io.github.persiancalendar.calendar.CivilDate
import io.github.persiancalendar.calendar.IslamicDate
import io.github.persiancalendar.calendar.PersianDate
import io.github.persiancalendar.praytimes.CalculationMethod
import io.github.persiancalendar.praytimes.Clock
import io.github.persiancalendar.praytimes.Coordinate
import io.github.persiancalendar.praytimes.PrayTimesCalculator
import org.junit.Assert.*
import org.junit.Test
import java.util.*
class MainLogicTests {
@Test
fun islamic_converter_test() {
listOf(
listOf(2453767, 1427, 1, 1), listOf(2455658, 1432, 5, 2)
// listOf(2458579, 1440, 7, 29), listOf(2458580, 1440, 8, 1)
).forEach {
val reference = IslamicDate(it[1], it[2], it[3])
assertEquals(it[0].toLong(), reference.toJdn())
val converted = IslamicDate(it[0].toLong())
assertEquals(it[1], converted.year)
assertEquals(it[2], converted.month)
assertEquals(it[3], converted.dayOfMonth)
assertEquals(it[0].toLong(), converted.toJdn())
assertTrue(reference == IslamicDate(reference.toJdn()))
}
listOf(
listOf(2016, 10, 3, 1438, 1, 1),
listOf(2016, 11, 1, 1438, 2, 1),
listOf(2016, 12, 1, 1438, 3, 1),
listOf(2016, 12, 31, 1438, 4, 1),
listOf(2016, 10, 3, 1438, 1, 1),
listOf(2016, 11, 1, 1438, 2, 1),
listOf(2016, 12, 1, 1438, 3, 1),
listOf(2016, 12, 31, 1438, 4, 1),
listOf(2017, 1, 30, 1438, 5, 1),
listOf(2017, 2, 28, 1438, 6, 1),
listOf(2017, 3, 30, 1438, 7, 1),
listOf(2017, 4, 28, 1438, 8, 1),
listOf(2017, 5, 27, 1438, 9, 1),
listOf(2017, 6, 26, 1438, 10, 1),
listOf(2017, 7, 25, 1438, 11, 1),
listOf(2017, 8, 23, 1438, 12, 1),
listOf(2017, 9, 22, 1439, 1, 1),
listOf(2017, 10, 21, 1439, 2, 1),
listOf(2017, 11, 20, 1439, 3, 1),
listOf(2017, 12, 20, 1439, 4, 1),
listOf(2018, 1, 19, 1439, 5, 1),
listOf(2018, 2, 18, 1439, 6, 1),
listOf(2018, 3, 19, 1439, 7, 1),
listOf(2018, 4, 18, 1439, 8, 1),
listOf(2018, 5, 17, 1439, 9, 1),
listOf(2018, 6, 15, 1439, 10, 1),
listOf(2018, 7, 15, 1439, 11, 1),
listOf(2018, 8, 13, 1439, 12, 1),
listOf(2018, 9, 11, 1440, 1, 1),
listOf(2018, 10, 11, 1440, 2, 1),
listOf(2018, 11, 9, 1440, 3, 1),
listOf(2018, 12, 9, 1440, 4, 1),
listOf(2019, 1, 8, 1440, 5, 1),
listOf(2019, 2, 7, 1440, 6, 1)
// listOf(2040, 5, 12, 1462, 5, 1),
// listOf(2040, 6, 11, 1462, 6, 1),
// listOf(2040, 7, 10, 1462, 7, 1),
// listOf(2040, 8, 9, 1462, 8, 1),
// listOf(2040, 9, 7, 1462, 9, 1),
// listOf(2040, 10, 7, 1462, 10, 1),
// listOf(2040, 11, 6, 1462, 11, 1),
// listOf(2040, 12, 5, 1462, 12, 1),
// listOf(2041, 1, 4, 1463, 1, 1),
// listOf(2041, 2, 2, 1463, 2, 1),
// listOf(2041, 3, 4, 1463, 3, 1),
// listOf(2041, 4, 2, 1463, 4, 1),
// listOf(2041, 5, 1, 1463, 5, 1),
// listOf(2041, 5, 31, 1463, 6, 1),
// listOf(2041, 6, 29, 1463, 7, 1),
// listOf(2041, 7, 29, 1463, 8, 1),
// listOf(2041, 8, 28, 1463, 9, 1),
// listOf(2041, 9, 26, 1463, 10, 1),
// listOf(2041, 10, 26, 1463, 11, 1),
// listOf(2041, 11, 25, 1463, 12, 1),
// listOf(2041, 12, 24, 1464, 1, 1)
).forEach {
val jdn = CivilDate(it[0], it[1], it[2]).toJdn()
val islamicDate = IslamicDate(it[3], it[4], it[5])
assertEquals(jdn, islamicDate.toJdn())
assertTrue(islamicDate == IslamicDate(jdn))
}
IslamicDate.useUmmAlQura = true
listOf(
listOf(listOf(2015, 3, 14), listOf(1436, 5, 23)),
listOf(listOf(1999, 4, 1), listOf(1419, 12, 15)),
listOf(listOf(1989, 2, 25), listOf(1409, 7, 19))
).forEach {
val jdn = CivilDate(it[0][0], it[0][1], it[0][2]).toJdn()
val islamicDate = IslamicDate(it[1][0], it[1][1], it[1][2])
assertEquals(jdn, islamicDate.toJdn())
assertTrue(islamicDate == IslamicDate(jdn))
}
IslamicDate.useUmmAlQura = false
// int i = -1;
// long last = 0;
// for (int[][] test : tests2) {
// if (i % 12 == 0) {
// System.out.print(test[1][0]);
// System.out.print(", ");
// }
// long jdn = DateConverter.toJdn(test[0][0], test[0][1], test[0][2]);
// System.out.print(jdn - last);
// last = jdn;
// System.out.print(", ");
// if (i % 12 == 11)
// System.out.print("\n");
// ++i;
// }
}
@Test
fun practice_persian_converting_back_and_forth() {
assertEquals(PersianDate(1398, 1, 1).toJdn(), 2458564)
val startJdn = CivilDate(1750, 1, 1).toJdn()
val endJdn = CivilDate(2350, 1, 1).toJdn()
(startJdn..endJdn).forEach { assertEquals(it, PersianDate(it).toJdn()) }
}
@Test
fun practice_islamic_converting_back_and_forth() {
val startJdn = CivilDate(1750, 1, 1).toJdn()
val endJdn = CivilDate(2350, 1, 1).toJdn()
(startJdn..endJdn).forEach { assertEquals(it, IslamicDate(it).toJdn()) }
}
@Test
fun practice_ummalqara_converting_back_and_forth() {
IslamicDate.useUmmAlQura = true
val startJdn = CivilDate(1750, 1, 1).toJdn()
val endJdn = CivilDate(2350, 1, 1).toJdn()
(startJdn..endJdn).forEach { assertEquals(it, IslamicDate(it).toJdn()) }
IslamicDate.useUmmAlQura = false
}
@Test
fun practice_civil_converting_back_and_forth() {
val startJdn = CivilDate(1750, 1, 1).toJdn()
val endJdn = CivilDate(2350, 1, 1).toJdn()
(startJdn..endJdn).forEach { assertEquals(it, CivilDate(it).toJdn()) }
}
@Test
fun practice_moon_in_scorpio() {
val positiveJdn = listOf(
listOf(1397, 1, 14), listOf(1397, 1, 15), listOf(1397, 2, 10),
listOf(1397, 2, 11), listOf(1397, 2, 12), listOf(1397, 3, 6),
listOf(1397, 3, 7), listOf(1397, 3, 8), listOf(1397, 4, 2),
listOf(1397, 4, 3), listOf(1397, 4, 30), listOf(1397, 4, 31),
listOf(1397, 5, 26), listOf(1397, 5, 27), listOf(1397, 6, 22),
listOf(1397, 6, 23), listOf(1397, 7, 18), listOf(1397, 7, 19),
listOf(1397, 7, 20), listOf(1397, 8, 16), listOf(1397, 8, 17),
listOf(1397, 9, 12), listOf(1397, 9, 13), listOf(1397, 9, 14),
listOf(1397, 10, 10), listOf(1397, 10, 11), listOf(1397, 11, 8),
listOf(1397, 11, 9), listOf(1397, 12, 6), listOf(1397, 12, 7)
).map { PersianDate(it[0], it[1], it[2]).toJdn() }
val startOfYear = PersianDate(1397, 1, 1).toJdn()
(0..365).forEach {
val jdn = startOfYear + it
val persian = PersianDate(jdn)
val year = persian.year
val month = persian.month
val day = persian.dayOfMonth
assertEquals(
"%d %d %d".format(year, month, day),
jdn in positiveJdn,
isMoonInScorpio(persian, IslamicDate(jdn))
)
}
}
@Test
fun test_getMonthLength() {
assertEquals(31, getMonthLength(CalendarType.SHAMSI, 1397, 1))
assertEquals(31, getMonthLength(CalendarType.SHAMSI, 1397, 2))
assertEquals(31, getMonthLength(CalendarType.SHAMSI, 1397, 3))
assertEquals(31, getMonthLength(CalendarType.SHAMSI, 1397, 4))
assertEquals(31, getMonthLength(CalendarType.SHAMSI, 1397, 5))
assertEquals(31, getMonthLength(CalendarType.SHAMSI, 1397, 6))
assertEquals(30, getMonthLength(CalendarType.SHAMSI, 1397, 7))
assertEquals(30, getMonthLength(CalendarType.SHAMSI, 1397, 8))
assertEquals(30, getMonthLength(CalendarType.SHAMSI, 1397, 9))
assertEquals(30, getMonthLength(CalendarType.SHAMSI, 1397, 10))
assertEquals(30, getMonthLength(CalendarType.SHAMSI, 1397, 11))
assertEquals(29, getMonthLength(CalendarType.SHAMSI, 1397, 12))
}
private fun getDate(year: Int, month: Int, dayOfMonth: Int): Date =
Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply {
set(year, month - 1, dayOfMonth)
}.time
@Test
fun test_praytimes() {
// http://praytimes.org/code/v2/js/examples/monthly.htm
var prayTimes = PrayTimesCalculator.calculate(
CalculationMethod.MWL,
getDate(2018, 9, 5),
Coordinate(43.0, -80.0, 0.0),
-5.0, true
)
assertEquals(Clock(5, 9).toInt(), prayTimes.fajrClock.toInt())
assertEquals(Clock(6, 49).toInt(), prayTimes.sunriseClock.toInt())
assertEquals(Clock(13, 19).toInt(), prayTimes.dhuhrClock.toInt())
assertEquals(Clock(16, 57).toInt(), prayTimes.asrClock.toInt())
assertEquals(Clock(19, 48).toInt(), prayTimes.maghribClock.toInt())
assertEquals(Clock(21, 21).toInt(), prayTimes.ishaClock.toInt())
prayTimes = PrayTimesCalculator.calculate(
CalculationMethod.ISNA,
getDate(2018, 9, 5),
Coordinate(43.0, -80.0, 0.0),
-5.0, true
)
assertEquals(Clock(5, 27).toInt(), prayTimes.fajrClock.toInt())
assertEquals(Clock(6, 49).toInt(), prayTimes.sunriseClock.toInt())
assertEquals(Clock(13, 19).toInt(), prayTimes.dhuhrClock.toInt())
assertEquals(Clock(16, 57).toInt(), prayTimes.asrClock.toInt())
assertEquals(Clock(19, 48).toInt(), prayTimes.maghribClock.toInt())
assertEquals(Clock(21, 9).toInt(), prayTimes.ishaClock.toInt())
prayTimes = PrayTimesCalculator.calculate(
CalculationMethod.Egypt,
getDate(2018, 9, 5),
Coordinate(43.0, -80.0, 0.0),
-5.0, true
)
assertEquals(Clock(5, 0).toInt(), prayTimes.fajrClock.toInt())
assertEquals(Clock(6, 49).toInt(), prayTimes.sunriseClock.toInt())
assertEquals(Clock(13, 19).toInt(), prayTimes.dhuhrClock.toInt())
assertEquals(Clock(16, 57).toInt(), prayTimes.asrClock.toInt())
assertEquals(Clock(19, 48).toInt(), prayTimes.maghribClock.toInt())
assertEquals(Clock(21, 24).toInt(), prayTimes.ishaClock.toInt())
prayTimes = PrayTimesCalculator.calculate(
CalculationMethod.Makkah,
getDate(2018, 9, 5),
Coordinate(43.0, -80.0, 0.0),
-5.0, true
)
assertEquals(Clock(5, 6).toInt(), prayTimes.fajrClock.toInt())
assertEquals(Clock(6, 49).toInt(), prayTimes.sunriseClock.toInt())
assertEquals(Clock(13, 19).toInt(), prayTimes.dhuhrClock.toInt())
assertEquals(Clock(16, 57).toInt(), prayTimes.asrClock.toInt())
assertEquals(Clock(19, 48).toInt(), prayTimes.maghribClock.toInt())
assertEquals(Clock(21, 18).toInt(), prayTimes.ishaClock.toInt())
prayTimes = PrayTimesCalculator.calculate(
CalculationMethod.Karachi,
getDate(2018, 9, 5),
Coordinate(43.0, -80.0, 0.0),
-5.0, true
)
assertEquals(Clock(5, 9).toInt(), prayTimes.fajrClock.toInt())
assertEquals(Clock(6, 49).toInt(), prayTimes.sunriseClock.toInt())
assertEquals(Clock(13, 19).toInt(), prayTimes.dhuhrClock.toInt())
assertEquals(Clock(16, 57).toInt(), prayTimes.asrClock.toInt())
assertEquals(Clock(19, 48).toInt(), prayTimes.maghribClock.toInt())
assertEquals(Clock(21, 27).toInt(), prayTimes.ishaClock.toInt())
prayTimes = PrayTimesCalculator.calculate(
CalculationMethod.Jafari,
getDate(2018, 9, 5),
Coordinate(43.0, -80.0, 0.0),
-5.0, true
)
assertEquals(Clock(5, 21).toInt(), prayTimes.fajrClock.toInt())
assertEquals(Clock(6, 49).toInt(), prayTimes.sunriseClock.toInt())
assertEquals(Clock(13, 19).toInt(), prayTimes.dhuhrClock.toInt())
assertEquals(Clock(16, 57).toInt(), prayTimes.asrClock.toInt())
assertEquals(Clock(20, 5).toInt(), prayTimes.maghribClock.toInt())
assertEquals(Clock(21, 3).toInt(), prayTimes.ishaClock.toInt())
prayTimes = PrayTimesCalculator.calculate(
CalculationMethod.Tehran,
getDate(2018, 9, 5),
Coordinate(43.0, -80.0, 0.0),
-5.0, true
)
assertEquals(Clock(5, 11).toInt(), prayTimes.fajrClock.toInt())
assertEquals(Clock(6, 49).toInt(), prayTimes.sunriseClock.toInt())
assertEquals(Clock(13, 19).toInt(), prayTimes.dhuhrClock.toInt())
assertEquals(Clock(16, 57).toInt(), prayTimes.asrClock.toInt())
assertEquals(Clock(20, 8).toInt(), prayTimes.maghribClock.toInt())
assertEquals(Clock(21, 3).toInt(), prayTimes.ishaClock.toInt())
prayTimes = PrayTimesCalculator.calculate(
CalculationMethod.Tehran,
getDate(2019, 6, 9),
Coordinate(3.147778, 101.695278, 0.0),
8.0, false
)
assertEquals(Clock(5, 49).toInt(), prayTimes.fajrClock.toInt())
assertEquals(Clock(7, 3).toInt(), prayTimes.sunriseClock.toInt())
assertEquals(Clock(13, 12).toInt(), prayTimes.dhuhrClock.toInt())
assertEquals(Clock(16, 39).toInt(), prayTimes.asrClock.toInt())
assertEquals(Clock(19, 37).toInt(), prayTimes.maghribClock.toInt())
assertEquals(Clock(20, 19).toInt(), prayTimes.ishaClock.toInt())
}
@Test
fun test_isNearToDegree() {
assertTrue(QiblaCompassView.isNearToDegree(360f, 1f))
assertTrue(QiblaCompassView.isNearToDegree(1f, 360f))
assertTrue(QiblaCompassView.isNearToDegree(2f, 360f))
assertFalse(QiblaCompassView.isNearToDegree(3f, 360f))
assertTrue(QiblaCompassView.isNearToDegree(360f, 2f))
assertFalse(QiblaCompassView.isNearToDegree(360f, 3f))
assertTrue(QiblaCompassView.isNearToDegree(180f, 181f))
assertTrue(QiblaCompassView.isNearToDegree(180f, 182f))
assertFalse(QiblaCompassView.isNearToDegree(180f, 183f))
assertFalse(QiblaCompassView.isNearToDegree(180f, 184f))
assertTrue(QiblaCompassView.isNearToDegree(181f, 180f))
assertTrue(QiblaCompassView.isNearToDegree(182f, 180f))
assertFalse(QiblaCompassView.isNearToDegree(183f, 180f))
assertFalse(QiblaCompassView.isNearToDegree(184f, 180f))
}
@Test
fun test_it_different_date_object_equal() {
assertFalse(CivilDate(2000, 1, 1) == PersianDate(2000, 1, 1))
assertTrue(CivilDate(2000, 1, 1) == CivilDate(2000, 1, 1))
assertFalse(CivilDate(2000, 1, 1) == CivilDate(2000, 2, 1))
}
@Test
fun tests_imported_from_calendariale() {
val J0000 = 1721425L // Ours is different apparently
listOf(
// listOf(-214193, -1208, 5, 1),
// listOf(-61387, -790, 9, 14),
// listOf(25469, -552, 7, 2),
// listOf(49217, -487, 7, 9),
// listOf(171307, -153, 10, 18),
// listOf(210155, -46, 2, 30),
listOf(253427, 73, 8, 19),
listOf(369740, 392, 2, 5),
listOf(400085, 475, 3, 3),
listOf(434355, 569, 1, 3),
listOf(452605, 618, 12, 20),
listOf(470160, 667, 1, 14),
listOf(473837, 677, 2, 8),
listOf(507850, 770, 3, 22),
listOf(524156, 814, 11, 13),
listOf(544676, 871, 1, 21),
listOf(567118, 932, 6, 28),
listOf(569477, 938, 12, 14),
listOf(601716, 1027, 3, 21),
listOf(613424, 1059, 4, 10),
listOf(626596, 1095, 5, 2),
listOf(645554, 1147, 3, 30),
listOf(664224, 1198, 5, 10),
listOf(671401, 1218, 1, 7),
listOf(694799, 1282, 1, 29),
listOf(704424, 1308, 6, 3),
listOf(708842, 1320, 7, 7),
listOf(709409, 1322, 1, 29),
listOf(709580, 1322, 7, 14),
listOf(727274, 1370, 12, 27),
listOf(728714, 1374, 12, 6),
listOf(744313, 1417, 8, 19),
listOf(764652, 1473, 4, 28)
).forEach {
assertEquals(it[0] + J0000, PersianDate(it[1], it[2], it[3]).toJdn())
val from = PersianDate(it[0] + J0000)
assertEquals(from.year, it[1])
assertEquals(from.month, it[2])
assertEquals(from.dayOfMonth, it[3])
}
listOf(
// listOf(1507231, -586, 7, 24),
// listOf(1660037, -168, 12, 5),
// listOf(1746893, 70, 9, 24),
// listOf(1770641, 135, 10, 2),
// listOf(1892731, 470, 1, 8),
// listOf(1931579, 576, 5, 20),
// listOf(1974851, 694, 11, 10),
// listOf(2091164, 1013, 4, 25),
// listOf(2121509, 1096, 5, 24),
// listOf(2155779, 1190, 3, 23),
// listOf(2174029, 1240, 3, 10),
// listOf(2191584, 1288, 4, 2),
// listOf(2195261, 1298, 4, 27),
// listOf(2229274, 1391, 6, 12),
// listOf(2245580, 1436, 2, 3),
// listOf(2266100, 1492, 4, 9),
// listOf(2288542, 1553, 9, 19),
// listOf(2290901, 1560, 3, 5),
// listOf(2323140, 1648, 6, 10),
listOf(2334848, 1680, 6, 30),
listOf(2348020, 1716, 7, 24),
listOf(2366978, 1768, 6, 19),
listOf(2385648, 1819, 8, 2),
listOf(2392825, 1839, 3, 27),
listOf(2416223, 1903, 4, 19),
listOf(2425848, 1929, 8, 25),
listOf(2430266, 1941, 9, 29),
listOf(2430833, 1943, 4, 19),
listOf(2431004, 1943, 10, 7),
listOf(2448698, 1992, 3, 17),
listOf(2450138, 1996, 2, 25),
listOf(2465737, 2038, 11, 10),
listOf(2486076, 2094, 7, 18)
).forEach {
assertEquals(it[0] + 1L, CivilDate(it[1], it[2], it[3]).toJdn())
val from = CivilDate(it[0] + 1L)
assertEquals(from.year, it[1])
assertEquals(from.month, it[2])
assertEquals(from.dayOfMonth, it[3])
}
listOf(
// listOf(-214193, -1245, 12, 11),
// listOf(-61387, -813, 2, 25),
// listOf(25469, -568, 4, 2),
// listOf(49217, -501, 4, 7),
// listOf(171307, -157, 10, 18),
// listOf(210155, -47, 6, 3),
// listOf(253427, 75, 7, 13),
// listOf(369740, 403, 10, 5),
// listOf(400085, 489, 5, 22),
// listOf(434355, 586, 2, 7),
listOf(452605, 637, 8, 7),
// listOf(470160, 687, 2, 21),
// listOf(473837, 697, 7, 7),
// listOf(507850, 793, 6, 30),
// listOf(524156, 839, 7, 6),
// listOf(544676, 897, 6, 2),
// listOf(567118, 960, 9, 30),
// listOf(569477, 967, 5, 27),
// listOf(601716, 1058, 5, 18),
// listOf(613424, 1091, 6, 3),
// listOf(626596, 1128, 8, 4),
listOf(645554, 1182, 2, 4),
// listOf(664224, 1234, 10, 10),
// listOf(671401, 1255, 1, 11),
// listOf(694799, 1321, 1, 20),
listOf(704424, 1348, 3, 19),
// listOf(708842, 1360, 9, 7),
// listOf(709409, 1362, 4, 14),
// listOf(709580, 1362, 10, 7),
// listOf(727274, 1412, 9, 12),
// listOf(728714, 1416, 10, 5),
// listOf(744313, 1460, 10, 12),
listOf(764652, 1518, 3, 5)
).forEach {
assertEquals("${it[0]}", it[0] + J0000, IslamicDate(it[1], it[2], it[3]).toJdn())
val from = IslamicDate(it[0] + J0000)
assertEquals(from.year, it[1])
assertEquals(from.month, it[2])
assertEquals(from.dayOfMonth, it[3])
}
}
@Test
fun test_leap_years() {
// Doesn't match with https://calendar.ut.ac.ir/Fa/News/Data/Doc/KabiseShamsi1206-1498.pdf
val leapYears = listOf(
1210, 1214, 1218, 1222, 1226, 1230, 1234, 1238, 1243, 1247, 1251, 1255, 1259, 1263,
1267, 1271, 1276, 1280, 1284, 1288, 1292, 1296, 1300, 1304, 1309, 1313, 1317, 1321,
1325, 1329, 1333, 1337, 1342, 1346, 1350, 1354, 1358, 1362, 1366, 1370, 1375, 1379,
1383, 1387, 1391, 1395, 1399, 1403, 1408, 1412, 1416, 1420, 1424, 1428, 1432, 1436,
1441, 1445, 1449, 1453, 1457, 1461, 1465, 1469, 1474, 1478, 1482, 1486, 1490, 1494,
1498
)
(1206..1498).forEach {
assertEquals(
it.toString(), if (it in leapYears) 30 else 29,
getMonthLength(CalendarType.SHAMSI, it, 12)
)
}
}
@Test
fun test_equinox_time() {
val calendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Tehran"))
listOf(
// https://calendar.ut.ac.ir/Fa/News/Data/Doc/Calendar%201398-Full.pdf
listOf(2020, 3, 20, 7, 20/*should be 19*/, 43/* should be 37*/),
// https://calendar.ut.ac.ir/Fa/News/Data/Doc/Calendar%201398-Full.pdf
listOf(2019, 3, 21, 1, 28, 13/*should be 27*/),
// https://calendar.ut.ac.ir/Fa/News/Data/Doc/Calendar%201397-Full.pdf
listOf(2018, 3, 20, 19, 45, 53/*should be 28*/),
// https://calendar.ut.ac.ir/Fa/News/Data/Doc/Calendar%201396-Full.pdf
listOf(2017, 3, 20, 13, 59/*should be 58*/, 38/*should be 40*/),
// https://calendar.ut.ac.ir/Fa/News/Data/Doc/Calendar%201395-Full.pdf
listOf(2016, 3, 20, 8, 0, 55/*should be 12*/),
// http://vetmed.uk.ac.ir/documents/203998/204600/calendar-1394.pdf
listOf(2015, 3, 21, 2, 16/*should be 15*/, 0/*should be 11*/),
// https://raw.githubusercontent.com/ilius/starcal/master/plugins/iran-jalali-data.txt
listOf(2014, 3, 20, 20, 27, 41/*should be 7*/),
listOf(2013, 3, 20, 14, 32/*should be 31*/, 41/*should be 56*/),
listOf(2012, 3, 20, 8, 44, 19/*should be 27*/),
listOf(2011, 3, 21, 2, 51/*should be 50*/, 38/*should be 25*/),
listOf(2010, 3, 20, 21, 2, 49/*should be 13*/),
listOf(2009, 3, 20, 15, 14/*should be 13*/, 50/*should be 39*/),
listOf(2008, 3, 20, 9, 18, 17/*should be 19*/)
).forEach {
calendar.time = Equinox.northwardEquinox(it[0])
assertEquals(it[0].toString(), it[0], calendar[Calendar.YEAR])
assertEquals(it[0].toString(), it[1], calendar[Calendar.MONTH] + 1)
assertEquals(it[0].toString(), it[2], calendar[Calendar.DAY_OF_MONTH])
assertEquals(it[0].toString(), it[3], calendar[Calendar.HOUR_OF_DAY])
assertEquals(it[0].toString(), it[4], calendar[Calendar.MINUTE])
assertEquals(it[0].toString(), it[5], calendar[Calendar.SECOND])
}
// And not having random crashes
(-2000..10000).forEach { Equinox.northwardEquinox(it) }
}
@Test
fun test_day_of_week_from_jdn() {
assertEquals(0, getDayOfWeekFromJdn(PersianDate(1398, 9, 9).toJdn()))
assertEquals(1, getDayOfWeekFromJdn(PersianDate(1398, 9, 10).toJdn()))
assertEquals(2, getDayOfWeekFromJdn(PersianDate(1398, 9, 11).toJdn()))
assertEquals(3, getDayOfWeekFromJdn(PersianDate(1398, 9, 12).toJdn()))
assertEquals(4, getDayOfWeekFromJdn(PersianDate(1398, 9, 13).toJdn()))
assertEquals(5, getDayOfWeekFromJdn(PersianDate(1398, 9, 14).toJdn()))
assertEquals(6, getDayOfWeekFromJdn(PersianDate(1398, 9, 15).toJdn()))
assertEquals(0, getDayOfWeekFromJdn(PersianDate(1398, 9, 16).toJdn()))
assertEquals(1, getDayOfWeekFromJdn(PersianDate(1398, 9, 17).toJdn()))
assertEquals(2, getDayOfWeekFromJdn(PersianDate(1398, 9, 18).toJdn()))
assertEquals(3, getDayOfWeekFromJdn(PersianDate(1398, 9, 19).toJdn()))
assertEquals(4, getDayOfWeekFromJdn(PersianDate(1398, 9, 20).toJdn()))
assertEquals(5, getDayOfWeekFromJdn(PersianDate(1398, 9, 21).toJdn()))
assertEquals(6, getDayOfWeekFromJdn(PersianDate(1398, 9, 22).toJdn()))
}
}
| gpl-3.0 | a566352a46eed30e21d0c24b7184ae1c | 43.038801 | 98 | 0.561954 | 3.555967 | false | true | false | false |
pdvrieze/ProcessManager | darwin/src/jvmMain/kotlin/uk/ac/bournemouth/darwin/html/darwinPage.kt | 1 | 10130 | /*
* Copyright (c) 2021.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
@file:JvmName("ServletKt")
package uk.ac.bournemouth.darwin.html
import kotlinx.html.*
import kotlinx.html.stream.appendHTML
import uk.ac.bournemouth.darwin.sharedhtml.*
import java.net.URI
import java.security.Principal
import java.util.*
/** Should Javascript initialization be delayed to the footer of the page. */
private const val DELAY_JS = true
val RequestInfo.isNoChromeRequested: Boolean
get() = getHeader("X-Darwin")?.contains("nochrome") ?: false
/**
* Method that encapsulates the darwin web template.
*
* @param request The request to respond to
* @param windowTitle The title that should be in the head element
* @param pageTitle The title to display on page (if not the same as windowTitle)
* @param bodyContent The closure that creates the actual body content of the document.
*/
fun ResponseContext.darwinResponse(request: RequestInfo,
windowTitle: String = "Darwin",
pageTitle: String? = null,
includeLogin: Boolean = true,
context: ServiceContext = RequestServiceContext(request),
bodyContent: ContextTagConsumer<HtmlBlockTag>.() -> Unit) {
respondWriter { result ->
if (request.isNoChromeRequested) {
contentType("text/xml")
result.append("<?xml version=\"1.0\" ?>\n")
result.appendHTML().partialHTML {
title(windowTitle, pageTitle)
script(context.jsLocalRef("main.js"))
body {
withContext(context).bodyContent()
}
}
} else {
contentType("text/html")
result.append("<!DOCTYPE html>\n")
result.appendHTML().html {
head {
title(windowTitle)
styleLink(context.cssRef("darwin.css"))
meta(name = "viewport", content = "width=device-width, initial-scale=1.0")
if (!DELAY_JS) script(
type = ScriptType.textJavaScript,
src = context.jsGlobalRef("require.js")
) { this.attributes["data-main"] = context.jsLocalRef("main.js") }
}
body {
h1 {
id = "header"
a(href = "/") {
id = "logo"
+"Darwin"
}
span {
id = "title"
+(pageTitle ?: windowTitle)
}
}
darwinMenu(request)
div {
id = "login"
loginPanelContent(context, request.userPrincipal?.name)
}
div {
id = "content"
withContext(context).bodyContent()
}
if (includeLogin) {
// A mini form that we use to get username/password out of the account manager
form(action = "${context.accountMgrPath}login", method = FormMethod.post) {
id = "xloginform"; style = "display:none"
input(type = InputType.text, name = "username")
input(type = InputType.password, name = "password")
}
}
div {
id = "footer"
span { id = "divider" }
+"Darwin is a Bournemouth University Project"
}
if (DELAY_JS) script(
type = ScriptType.textJavaScript, src = context.jsGlobalRef(
"require.js"
)
) { this.attributes["data-main"] = context.jsLocalRef("main.js") }
// script(type= ScriptType.textJavaScript, src="/js/darwin.js")
}
}
}
}
}
fun ResponseContext.darwinError(req: RequestInfo,
message: String,
code: Int = 500,
status: String = "Server error",
cause: Exception? = null) {
setStatus(code)
darwinResponse(req, windowTitle = "$code $status") {
h2 { +status }
p {
style = "margin-top: 2em"
+message.trim().replace("\n", "<br />")
}
if (cause != null && System.getProperty("DEBUG")?.let { it != "false" } == true) {
p {
this.printCauseAsHtml(cause)
}
}
}
}
private fun HtmlBlockTag.printCauseAsHtml(cause: Throwable) {
b { +cause.javaClass.simpleName }
+": ${cause.message}"
div {
style = "margin-left: 1em"
ul {
for (elem in cause.stackTrace) {
li { +elem.toString() }
}
}
cause.cause?.let {
i { +"caused by " }
printCauseAsHtml(it)
}
for (suppressed in cause.suppressed) {
i { +"suppressing " }
printCauseAsHtml(suppressed)
}
}
}
class MenuItem(val label: String, val target: URI) {
constructor(label: String, target: String) : this(label, URI.create(target))
}
fun <T, C : TagConsumer<T>> C.darwinMenu(request: RequestInfo): T {
val user = request.userPrincipal
return div {
id = "menu"
var first = true
for (menuItem in getMenuItems(request, user)) {
if (!first) +"\n" else first = false
a(href = menuItem.target.toString(), classes = "menuitem") {
+menuItem.label
}
}
}
}
fun FlowContent.darwinMenu(request: RequestInfo) {
consumer.darwinMenu(request)
}
private fun getMenuItems(request: RequestInfo, user: Principal?): List<MenuItem> {
val menuItems: MutableList<MenuItem> = ArrayList()
// Pages with /#/... urls are virtual pages. They don't have valid other urls
if (user == null) {
menuItems += MenuItem("Welcome", "/")
} else {
menuItems += MenuItem("Home", "/")
if (request.isUserInRole("admin") || request.isUserInRole("appprogramming")) {
menuItems += MenuItem("Trac", user.name + "/trac/")
}
}
menuItems += MenuItem("About", "/#/about")
return menuItems
}
/**
* A class representing the idea of sending sufficient html to replace the content, but not the layout of the page.
*/
class PartialHTML(initialAttributes: Map<String, String>, override val consumer: TagConsumer<*>) :
HTMLTag("root", consumer, initialAttributes, null, false, false) {
fun title(block: TITLE.() -> Unit = {}): Unit = TITLE(emptyMap, consumer).visit(block)
fun title(windowTitle: String = "", pageTitle: String? = null): Unit =
TITLE(emptyMap, consumer).visit {
attributes["windowtitle"] = windowTitle
+(pageTitle ?: windowTitle)
}
fun script(src: String) {
SCRIPT(emptyMap, consumer).visit {
this.type = ScriptType.textJavaScript
this.src = src
}
}
fun body(block: XMLBody.() -> Unit = {}): Unit = XMLBody(emptyMap, consumer).visit(block)
}
class XMLBody(initialAttributes: Map<String, String>, override val consumer: TagConsumer<*>) : HTMLTag("body", consumer,
initialAttributes,
null, false,
false), HtmlBlockTag
fun <T, C : TagConsumer<T>> C.partialHTML(block: PartialHTML.() -> Unit = {}): T = PartialHTML(emptyMap,
this).visitAndFinalize(
this, block)
val RequestInfo.htmlAccepted: Boolean
get() {
return getHeader("Accept")?.let { it.contains("text/html") || it.contains("application/nochrome") } ?: false
}
fun ContextTagConsumer<HtmlBlockTag>.darwinDialog(title: String,
id: String? = null,
bodyContent: FlowContent.() -> Unit = {}) {
div(classes = "dialog centerContents") {
if (id != null) {
this.id = id
}
div(classes = "dialogOuter") {
h1(classes = "dlgTitle") { +title }
div(classes = "dialogInner centerContents") {
div(classes = "dlgContent") {
bodyContent()
}
}
}
}
}
class RequestServiceContext(private val request: RequestInfo) : ServiceContext {
override val accountMgrPath: String
get() = "/accountmgr/"
override val assetPath: String
get() = "/assets/"
override val cssPath: String
get() = "/css/"
override val jsGlobalPath: String
get() = "/js/"
override val jsLocalPath: String
get() = "${request.contextPath}/js/"
}
| lgpl-3.0 | 646dfb40b2ce3f4d252ecda16f38fb2c | 36.106227 | 123 | 0.507502 | 4.970559 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | example/src/test/java/org/wordpress/android/fluxc/network/rest/wpcom/activity/ActivityLogRestClientTest.kt | 1 | 29822 | package org.wordpress.android.fluxc.network.rest.wpcom.activity
import com.android.volley.RequestQueue
import com.nhaarman.mockitokotlin2.KArgumentCaptor
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.anyOrNull
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.isNull
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.activity.ActivityTypeModel
import org.wordpress.android.fluxc.model.activity.RewindStatusModel.Reason
import org.wordpress.android.fluxc.model.activity.RewindStatusModel.State
import org.wordpress.android.fluxc.network.BaseRequest.BaseNetworkError
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.NETWORK_ERROR
import org.wordpress.android.fluxc.network.UserAgent
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequest.WPComGsonNetworkError
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response.Success
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.ActivitiesResponse
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.ActivitiesResponse.Page
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.ActivityTypesResponse
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.ActivityTypesResponse.ActivityType
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.ActivityTypesResponse.Groups
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.BackupDownloadResponse
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.BackupDownloadStatusResponse
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.DismissBackupDownloadResponse
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.RewindResponse
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient.RewindStatusResponse
import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken
import org.wordpress.android.fluxc.store.ActivityLogStore.ActivityLogErrorType
import org.wordpress.android.fluxc.store.ActivityLogStore.ActivityTypesErrorType
import org.wordpress.android.fluxc.store.ActivityLogStore.BackupDownloadRequestTypes
import org.wordpress.android.fluxc.store.ActivityLogStore.BackupDownloadStatusErrorType
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchActivityLogPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchedActivityLogPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchedBackupDownloadStatePayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchedRewindStatePayload
import org.wordpress.android.fluxc.store.ActivityLogStore.RewindRequestTypes
import org.wordpress.android.fluxc.store.ActivityLogStore.RewindStatusErrorType
import org.wordpress.android.fluxc.test
import org.wordpress.android.fluxc.tools.FormattableContent
import org.wordpress.android.fluxc.utils.TimeZoneProvider
import java.util.Date
import java.util.TimeZone
private const val DATE_1_IN_MILLIS = 1578614400000L // 2020-01-10T00:00:00+00:00
private const val DATE_2_IN_MILLIS = 1578787200000L // 2020-01-12T00:00:00+00:00
@RunWith(MockitoJUnitRunner::class)
class ActivityLogRestClientTest {
@Mock private lateinit var dispatcher: Dispatcher
@Mock private lateinit var wpComGsonRequestBuilder: WPComGsonRequestBuilder
@Mock private lateinit var site: SiteModel
@Mock private lateinit var requestPayload: FetchActivityLogPayload
@Mock private lateinit var requestQueue: RequestQueue
@Mock private lateinit var accessToken: AccessToken
@Mock private lateinit var userAgent: UserAgent
@Mock private lateinit var timeZoneProvider: TimeZoneProvider
private lateinit var urlCaptor: KArgumentCaptor<String>
private lateinit var paramsCaptor: KArgumentCaptor<Map<String, String>>
private lateinit var activityRestClient: ActivityLogRestClient
private val siteId: Long = 12
private val number = 10
private val offset = 0
@Before
fun setUp() {
urlCaptor = argumentCaptor()
paramsCaptor = argumentCaptor()
activityRestClient = ActivityLogRestClient(
wpComGsonRequestBuilder,
timeZoneProvider,
dispatcher,
null,
requestQueue,
accessToken,
userAgent)
whenever(requestPayload.site).thenReturn(site)
whenever(timeZoneProvider.getDefaultTimeZone()).thenReturn(TimeZone.getTimeZone("GMT"))
}
@Test
fun fetchActivity_passesCorrectParamToBuildRequest() = test {
initFetchActivity()
val payload = FetchActivityLogPayload(
site,
false,
Date(DATE_1_IN_MILLIS),
Date(DATE_2_IN_MILLIS),
listOf("post", "attachment")
)
activityRestClient.fetchActivity(payload, number, offset)
assertEquals(urlCaptor.firstValue, "https://public-api.wordpress.com/wpcom/v2/sites/$siteId/activity/")
with(paramsCaptor.firstValue) {
assertEquals("1", this["page"])
assertEquals("$number", this["number"])
assertNotNull(this["after"])
assertNotNull(this["before"])
assertEquals("post", this["group[0]"])
assertEquals("attachment", this["group[1]"])
}
}
@Test
fun fetchActivity_passesOnlyNonEmptyParamsToBuildRequest() = test {
initFetchActivity()
val payload = FetchActivityLogPayload(
site,
false,
after = null,
before = null,
groups = listOf()
)
activityRestClient.fetchActivity(payload, number, offset)
assertEquals(urlCaptor.firstValue, "https://public-api.wordpress.com/wpcom/v2/sites/$siteId/activity/")
with(paramsCaptor.firstValue) {
assertEquals("1", this["page"])
assertEquals("$number", this["number"])
assertEquals(2, size)
}
}
@Test
fun fetchActivity_adjustsDateRangeBasedOnTimezoneGMT3() = test {
val timezoneOffset = 3
whenever(timeZoneProvider.getDefaultTimeZone()).thenReturn(TimeZone.getTimeZone("GMT+$timezoneOffset"))
initFetchActivity()
val payload = FetchActivityLogPayload(
site,
false,
// 2020-01-10T00:00:00+00:00
Date(DATE_1_IN_MILLIS),
// 2020-01-12T00:00:00+00:00
Date(DATE_2_IN_MILLIS)
)
activityRestClient.fetchActivity(payload, number, offset)
with(paramsCaptor.firstValue) {
assertEquals("2020-01-09T21:00:00+00:00", this["after"])
assertEquals("2020-01-11T21:00:00+00:00", this["before"])
}
}
@Test
fun fetchActivity_adjustsDateRangeBasedOnTimezoneGMTMinus7() = test {
val timezoneOffset = -7
whenever(timeZoneProvider.getDefaultTimeZone()).thenReturn(TimeZone.getTimeZone("GMT$timezoneOffset"))
initFetchActivity()
val payload = FetchActivityLogPayload(
site,
false,
// 2020-01-10T00:00:00+00:00
Date(DATE_1_IN_MILLIS),
// 2020-01-12T00:00:00+00:00
Date(DATE_2_IN_MILLIS)
)
activityRestClient.fetchActivity(payload, number, offset)
with(paramsCaptor.firstValue) {
assertEquals("2020-01-10T07:00:00+00:00", this["after"])
assertEquals("2020-01-12T07:00:00+00:00", this["before"])
}
}
@Test
fun fetchActivity_dispatchesResponseOnSuccess() = test {
val response = ActivitiesResponse(1, "response", ACTIVITY_RESPONSE_PAGE)
initFetchActivity(response)
val payload = activityRestClient.fetchActivity(requestPayload, number, offset)
with(payload) {
assertEquals([email protected], number)
assertEquals([email protected], offset)
assertEquals(totalItems, 1)
assertEquals([email protected], site)
assertEquals(activityLogModels.size, 1)
assertNull(error)
with(activityLogModels[0]) {
assertEquals(activityID, ACTIVITY_RESPONSE.activity_id)
assertEquals(gridicon, ACTIVITY_RESPONSE.gridicon)
assertEquals(name, ACTIVITY_RESPONSE.name)
assertEquals(published, ACTIVITY_RESPONSE.published)
assertEquals(rewindID, ACTIVITY_RESPONSE.rewind_id)
assertEquals(rewindable, ACTIVITY_RESPONSE.is_rewindable)
assertEquals(content, ACTIVITY_RESPONSE.content)
assertEquals(actor?.avatarURL, ACTIVITY_RESPONSE.actor?.icon?.url)
assertEquals(actor?.wpcomUserID, ACTIVITY_RESPONSE.actor?.wpcom_user_id)
}
}
}
@Test
fun fetchActivity_dispatchesErrorOnMissingActivityId() = test {
val failingPage = Page(listOf(ACTIVITY_RESPONSE.copy(activity_id = null)))
val activitiesResponse = ActivitiesResponse(1, "response", failingPage)
initFetchActivity(activitiesResponse)
val payload = activityRestClient.fetchActivity(requestPayload, number, offset)
assertEmittedActivityError(payload, ActivityLogErrorType.MISSING_ACTIVITY_ID)
}
@Test
fun fetchActivity_dispatchesErrorOnMissingSummary() = test {
val failingPage = Page(listOf(ACTIVITY_RESPONSE.copy(summary = null)))
val activitiesResponse = ActivitiesResponse(1, "response", failingPage)
initFetchActivity(activitiesResponse)
val payload = activityRestClient.fetchActivity(requestPayload, number, offset)
assertEmittedActivityError(payload, ActivityLogErrorType.MISSING_SUMMARY)
}
@Test
fun fetchActivity_dispatchesErrorOnMissingContentText() = test {
val emptyContent = FormattableContent(null)
val failingPage = Page(listOf(ACTIVITY_RESPONSE.copy(content = emptyContent)))
val activitiesResponse = ActivitiesResponse(1, "response", failingPage)
initFetchActivity(activitiesResponse)
val payload = activityRestClient.fetchActivity(requestPayload, number, offset)
assertEmittedActivityError(payload, ActivityLogErrorType.MISSING_CONTENT_TEXT)
}
@Test
fun fetchActivity_dispatchesErrorOnMissingPublishedDate() = test {
val failingPage = Page(listOf(ACTIVITY_RESPONSE.copy(published = null)))
val activitiesResponse = ActivitiesResponse(1, "response", failingPage)
initFetchActivity(activitiesResponse)
val payload = activityRestClient.fetchActivity(requestPayload, number, offset)
assertEmittedActivityError(payload, ActivityLogErrorType.MISSING_PUBLISHED_DATE)
}
@Test
fun fetchActivity_dispatchesErrorOnFailure() = test {
initFetchActivity(error = WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR)))
val payload = activityRestClient.fetchActivity(requestPayload, number, offset)
assertEmittedActivityError(payload, ActivityLogErrorType.GENERIC_ERROR)
}
@Test
fun fetchActivityRewind_dispatchesResponseOnSuccess() = test {
val state = State.ACTIVE
val rewindResponse = REWIND_STATUS_RESPONSE.copy(state = state.value)
initFetchRewindStatus(rewindResponse)
val payload = activityRestClient.fetchActivityRewind(site)
with(payload) {
assertEquals([email protected], site)
assertNull(error)
assertNotNull(rewindStatusModelResponse)
rewindStatusModelResponse?.apply {
assertEquals(reason, Reason.UNKNOWN)
assertEquals(state, state)
assertNotNull(rewind)
rewind?.apply {
assertEquals(status.value, REWIND_RESPONSE.status)
}
}
}
}
@Test
fun fetchActivityRewind_dispatchesGenericErrorOnFailure() = test {
initFetchRewindStatus(error = WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR)))
val payload = activityRestClient.fetchActivityRewind(site)
assertEmittedRewindStatusError(payload, RewindStatusErrorType.GENERIC_ERROR)
}
@Test
fun fetchActivityRewind_dispatchesErrorOnWrongState() = test {
initFetchRewindStatus(REWIND_STATUS_RESPONSE.copy(state = "wrong"))
val payload = activityRestClient.fetchActivityRewind(site)
assertEmittedRewindStatusError(payload, RewindStatusErrorType.INVALID_RESPONSE)
}
@Test
fun fetchActivityRewind_dispatchesErrorOnMissingRestoreId() = test {
initFetchRewindStatus(REWIND_STATUS_RESPONSE.copy(rewind = REWIND_RESPONSE.copy(rewind_id = null)))
val payload = activityRestClient.fetchActivityRewind(site)
assertEmittedRewindStatusError(payload, RewindStatusErrorType.MISSING_REWIND_ID)
}
@Test
fun fetchActivityRewind_dispatchesErrorOnWrongRestoreStatus() = test {
initFetchRewindStatus(REWIND_STATUS_RESPONSE.copy(rewind = REWIND_RESPONSE.copy(status = "wrong")))
val payload = activityRestClient.fetchActivityRewind(site)
assertEmittedRewindStatusError(payload, RewindStatusErrorType.INVALID_REWIND_STATE)
}
@Test
fun postRewindOperation() = test {
val restoreId = 10L
val response = RewindResponse(restoreId, true, null)
initPostRewind(response)
val payload = activityRestClient.rewind(site, "rewindId")
assertEquals(restoreId, payload.restoreId)
}
@Test
fun postRewindOperationError() = test {
initPostRewind(error = WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR)))
val payload = activityRestClient.rewind(site, "rewindId")
assertTrue(payload.isError)
}
@Test
fun postRewindApiError() = test {
val restoreId = 10L
initPostRewind(RewindResponse(restoreId, false, "error"))
val payload = activityRestClient.rewind(site, "rewindId")
assertTrue(payload.isError)
}
@Test
fun postRewindOperationWithTypes() = test {
val restoreId = 10L
val response = RewindResponse(restoreId, true, null)
val types = RewindRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
initPostRewindWithTypes(data = response, requestTypes = types)
val payload = activityRestClient.rewind(site, "rewindId", types)
assertEquals(restoreId, payload.restoreId)
}
@Test
fun postRewindOperationErrorWithTypes() = test {
val types = RewindRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
initPostRewindWithTypes(error = WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR)), requestTypes = types)
val payload = activityRestClient.rewind(site, "rewindId", types)
assertTrue(payload.isError)
}
@Test
fun postRewindApiErrorWithTypes() = test {
val restoreId = 10L
val types = RewindRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
initPostRewindWithTypes(data = RewindResponse(restoreId, false, "error"), requestTypes = types)
val payload = activityRestClient.rewind(site, "rewindId", types)
assertTrue(payload.isError)
}
@Test
fun postBackupDownloadOperation() = test {
val downloadId = 10L
val rewindId = "rewind_id"
val backupPoint = "backup_point"
val startedAt = "started_at"
val progress = 0
val response = BackupDownloadResponse(downloadId, rewindId, backupPoint, startedAt, progress)
val types = BackupDownloadRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
initPostBackupDownload(rewindId = rewindId, data = response, requestTypes = types)
val payload = activityRestClient.backupDownload(site, rewindId, types)
assertEquals(downloadId, payload.downloadId)
}
@Test
fun postBackupDownloadOperationError() = test {
val rewindId = "rewind_id"
val types = BackupDownloadRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
initPostBackupDownload(rewindId = rewindId, error =
WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR)), requestTypes = types)
val payload = activityRestClient.backupDownload(site, rewindId, types)
assertTrue(payload.isError)
}
@Test
fun fetchActivityDownload_dispatchesGenericErrorOnFailure() = test {
initFetchBackupDownloadStatus(
error = WPComGsonNetworkError(
BaseNetworkError(
NETWORK_ERROR
)
)
)
val payload = activityRestClient.fetchBackupDownloadState(site)
assertEmittedDownloadStatusError(payload, BackupDownloadStatusErrorType.GENERIC_ERROR)
}
@Test
fun fetchActivityBackupDownload_dispatchesResponseOnSuccess() = test {
val progress = 55
val downloadResponse = BACKUP_DOWNLOAD_STATUS_RESPONSE.copy(progress = progress)
initFetchBackupDownloadStatus(arrayOf(downloadResponse))
val payload = activityRestClient.fetchBackupDownloadState(site)
with(payload) {
assertEquals([email protected], site)
assertNull(error)
assertNotNull(backupDownloadStatusModelResponse)
backupDownloadStatusModelResponse?.apply {
assertEquals(downloadId, BACKUP_DOWNLOAD_STATUS_RESPONSE.downloadId)
assertEquals(rewindId, BACKUP_DOWNLOAD_STATUS_RESPONSE.rewindId)
assertEquals(backupPoint, BACKUP_DOWNLOAD_STATUS_RESPONSE.backupPoint)
assertEquals(startedAt, BACKUP_DOWNLOAD_STATUS_RESPONSE.startedAt)
assertEquals(downloadCount, BACKUP_DOWNLOAD_STATUS_RESPONSE.downloadCount)
assertEquals(validUntil, BACKUP_DOWNLOAD_STATUS_RESPONSE.validUntil)
assertEquals(url, BACKUP_DOWNLOAD_STATUS_RESPONSE.url)
assertEquals(progress, progress)
}
}
}
@Test
fun fetchEmptyActivityBackupDownload_dispatchesResponseOnSuccess() = test {
initFetchBackupDownloadStatus(arrayOf())
val payload = activityRestClient.fetchBackupDownloadState(site)
with(payload) {
assertEquals(site, [email protected])
assertNull(error)
assertNull(backupDownloadStatusModelResponse)
}
}
@Test
fun fetchActivityTypes_dispatchesSuccessResponseOnSuccess() = test {
initFetchActivityTypes()
val siteId = 90L
val payload = activityRestClient.fetchActivityTypes(siteId, null, null)
with(payload) {
assertEquals(siteId, remoteSiteId)
assertEquals(false, isError)
}
}
@Test
fun fetchActivityTypes_dispatchesGenericErrorOnFailure() = test {
initFetchActivityTypes(error = WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR)))
val siteId = 90L
val payload = activityRestClient.fetchActivityTypes(siteId, null, null)
with(payload) {
assertEquals(siteId, remoteSiteId)
assertEquals(true, isError)
assertEquals(error.type, ActivityTypesErrorType.GENERIC_ERROR)
}
}
@Test
fun fetchActivityTypes_mapsResponseModelsToDomainModels() = test {
val activityType = ActivityType("key1", "name1", 10)
initFetchActivityTypes(
data = ActivityTypesResponse(
groups = Groups(
activityTypes = listOf(activityType)
),
15
)
)
val siteId = site.siteId
val payload = activityRestClient.fetchActivityTypes(siteId, null, null)
assertEquals(
payload.activityTypeModels[0],
ActivityTypeModel(activityType.key!!, activityType.name!!, activityType.count!!)
)
}
@Test
fun fetchActivityTypes_passesCorrectParams() = test {
initFetchActivityTypes()
val siteId = site.siteId
val afterMillis = 234124242145
val beforeMillis = 234124242999
val after = Date(afterMillis)
val before = Date(beforeMillis)
activityRestClient.fetchActivityTypes(siteId, after, before)
with(paramsCaptor.firstValue) {
assertNotNull(this["after"])
assertNotNull(this["before"])
}
}
@Test
fun postDismissBackupDownloadOperation() = test {
val downloadId = 10L
val response = DismissBackupDownloadResponse(downloadId, true)
initPostDismissBackupDownload(data = response)
val payload = activityRestClient.dismissBackupDownload(site, downloadId)
assertEquals(downloadId, payload.downloadId)
}
@Test
fun postDismissBackupDownloadOperationError() = test {
val downloadId = 10L
initPostDismissBackupDownload(error = WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR)))
val payload = activityRestClient.dismissBackupDownload(site, downloadId)
assertTrue(payload.isError)
}
private suspend fun initFetchActivity(
data: ActivitiesResponse = mock(),
error: WPComGsonNetworkError? = null
): Response<ActivitiesResponse> {
val response = if (error != null) Response.Error<ActivitiesResponse>(error) else Success(data)
whenever(wpComGsonRequestBuilder.syncGetRequest(
eq(activityRestClient),
urlCaptor.capture(),
paramsCaptor.capture(),
eq(ActivitiesResponse::class.java),
eq(false),
any(),
eq(false))
).thenReturn(response)
whenever(site.siteId).thenReturn(siteId)
return response
}
private suspend fun initFetchRewindStatus(
data: RewindStatusResponse = mock(),
error: WPComGsonNetworkError? = null
):
Response<RewindStatusResponse> {
val response = if (error != null) Response.Error<RewindStatusResponse>(error) else Success(data)
whenever(wpComGsonRequestBuilder.syncGetRequest(
eq(activityRestClient),
urlCaptor.capture(),
paramsCaptor.capture(),
eq(RewindStatusResponse::class.java),
eq(false),
any(),
eq(false))).thenReturn(response)
whenever(site.siteId).thenReturn(siteId)
return response
}
private suspend fun initPostRewind(
data: RewindResponse = mock(),
error: WPComGsonNetworkError? = null
): Response<RewindResponse> {
val response = if (error != null) Response.Error<RewindResponse>(error) else Success(data)
whenever(wpComGsonRequestBuilder.syncPostRequest(
eq(activityRestClient),
urlCaptor.capture(),
eq(null),
eq(mapOf()),
eq(RewindResponse::class.java),
isNull()
)).thenReturn(response)
whenever(site.siteId).thenReturn(siteId)
return response
}
private suspend fun initPostRewindWithTypes(
data: RewindResponse = mock(),
error: WPComGsonNetworkError? = null,
requestTypes: RewindRequestTypes
): Response<RewindResponse> {
val response = if (error != null) Response.Error<RewindResponse>(error) else Success(data)
whenever(wpComGsonRequestBuilder.syncPostRequest(
eq(activityRestClient),
urlCaptor.capture(),
eq(null),
eq(mapOf("types" to requestTypes)),
eq(RewindResponse::class.java),
isNull()
)).thenReturn(response)
whenever(site.siteId).thenReturn(siteId)
return response
}
private suspend fun initPostBackupDownload(
data: BackupDownloadResponse = mock(),
error: WPComGsonNetworkError? = null,
requestTypes: BackupDownloadRequestTypes,
rewindId: String
): Response<BackupDownloadResponse> {
val response = if (error != null) Response.Error<BackupDownloadResponse>(error) else Success(data)
whenever(wpComGsonRequestBuilder.syncPostRequest(
eq(activityRestClient),
urlCaptor.capture(),
eq(null),
eq(mapOf("rewindId" to rewindId,
"types" to requestTypes)),
eq(BackupDownloadResponse::class.java),
isNull()
)).thenReturn(response)
whenever(site.siteId).thenReturn(siteId)
return response
}
private suspend fun initFetchBackupDownloadStatus(
data: Array<BackupDownloadStatusResponse>? = null,
error: WPComGsonNetworkError? = null
): Response<Array<BackupDownloadStatusResponse>> {
val defaultError = WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR))
val response = when {
error != null -> { Response.Error(error) }
data != null -> { Success(data) }
else -> { Response.Error(defaultError) }
}
whenever(wpComGsonRequestBuilder.syncGetRequest(
eq(activityRestClient),
urlCaptor.capture(),
paramsCaptor.capture(),
eq(Array<BackupDownloadStatusResponse>::class.java),
eq(false),
any(),
eq(false))).thenReturn(response)
whenever(site.siteId).thenReturn(siteId)
return response
}
private suspend fun initFetchActivityTypes(
data: ActivityTypesResponse = mock(),
error: WPComGsonNetworkError? = null
): Response<ActivityTypesResponse> {
val response = if (error != null) Response.Error<ActivityTypesResponse>(error) else Success(data)
whenever(wpComGsonRequestBuilder.syncGetRequest(
eq(activityRestClient),
urlCaptor.capture(),
paramsCaptor.capture(),
eq(ActivityTypesResponse::class.java),
eq(false),
any(),
eq(false))
).thenReturn(response)
return response
}
private suspend fun initPostDismissBackupDownload(
data: DismissBackupDownloadResponse = mock(),
error: WPComGsonNetworkError? = null
): Response<DismissBackupDownloadResponse> {
val response = if (error != null) Response.Error(error) else Success(data)
whenever(wpComGsonRequestBuilder.syncPostRequest(
eq(activityRestClient),
urlCaptor.capture(),
anyOrNull(),
eq(mapOf("dismissed" to true.toString())),
eq(DismissBackupDownloadResponse::class.java),
isNull()
)).thenReturn(response)
whenever(site.siteId).thenReturn(siteId)
return response
}
private fun assertEmittedActivityError(payload: FetchedActivityLogPayload, errorType: ActivityLogErrorType) {
with(payload) {
assertEquals([email protected], number)
assertEquals([email protected], offset)
assertEquals([email protected], site)
assertTrue(isError)
assertEquals(error.type, errorType)
}
}
private fun assertEmittedRewindStatusError(payload: FetchedRewindStatePayload, errorType: RewindStatusErrorType) {
with(payload) {
assertEquals([email protected], site)
assertTrue(isError)
assertEquals(errorType, error.type)
}
}
private fun assertEmittedDownloadStatusError(
payload: FetchedBackupDownloadStatePayload,
errorType: BackupDownloadStatusErrorType
) {
with(payload) {
assertEquals([email protected], site)
assertTrue(isError)
assertEquals(errorType, error.type)
}
}
}
| gpl-2.0 | 6156c78ab1c4738b506140d920ce8293 | 38.187911 | 119 | 0.668869 | 5.426128 | false | true | false | false |
youkai-app/Youkai | app/src/main/kotlin/app/youkai/data/models/Anime.kt | 1 | 1924 | package app.youkai.data.models
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
import com.github.jasminb.jsonapi.Links
import com.github.jasminb.jsonapi.annotations.Relationship
import com.github.jasminb.jsonapi.annotations.RelationshipLinks
import com.github.jasminb.jsonapi.annotations.Type
@Type("anime") @JsonIgnoreProperties(ignoreUnknown = true)
class Anime : BaseMedia(JsonType("anime")) {
companion object FieldNames {
val EPISODE_COUNT = "episodeCount"
val EPISODE_LENGTH = "episodeLength"
val SHOW_TYPE = "showType"
val YOUTUBE_VIDEO_ID = "youtubeVideoId"
val NSFW = "nsfw"
val EPISODES = "episodes"
val STREAMING_LINKS = "streamingLinks"
val PRODUCTIONS = "animeProductions"
val CHARACTERS = "animeCharacters"
val STAFF = "animeStaff"
}
var episodeCount: Int? = null
var episodeLength: Int? = null
var showType: String? = null
var youtubeVideoId: String? = null
@JsonProperty("nsfw")
var isNsfw: Boolean? = null
@Relationship("episodes")
var episodes: List<Episode>? = null
@RelationshipLinks("episodes")
var episodeLinks: Links? = null
@Relationship("streamingLinks")
var streamingLinks: List<StreamingLink>? = null
@RelationshipLinks("streamingLinks")
var streamingLinksLinks: Links? = null
@Relationship("animeProductions")
var productions: List<AnimeProduction>? = null
@RelationshipLinks("animeProductions")
var productionLinks: Links? = null
@Relationship("animeCharacters")
var animeCharacters: List<AnimeCharacter>? = null
@RelationshipLinks("animeCharacters")
var animeCharacterLinks: Links? = null
@Relationship("animeStaff")
var staff: List<AnimeStaff>? = null
@RelationshipLinks("animeStaff")
var staffLinks: Links? = null
} | gpl-3.0 | 6befb4ed95ef746e9621b8f596796925 | 27.731343 | 63 | 0.70842 | 4.402746 | false | false | false | false |
Kotlin/kotlinx.serialization | formats/json/jvmMain/src/kotlinx/serialization/json/internal/JsonToStringWriter.kt | 1 | 5236 | package kotlinx.serialization.json.internal
/**
* Optimized version of StringBuilder that is specific to JSON-encoding.
*
* ## Implementation note
*
* In order to encode a single string, it should be processed symbol-per-symbol,
* in order to detect and escape unicode symbols.
*
* Doing naively, it drastically slows down strings processing due to factors:
* * Byte-by-byte copying that does not leverage optimized array copying
* * A lot of range and flags checks due to Java's compact strings
*
* The following technique is used:
* 1) Instead of storing intermediate result in `StringBuilder`, we store it in
* `CharArray` directly, skipping compact strings checks in `StringBuilder`
* 2) Instead of copying symbols one-by-one, we optimistically copy it in batch using
* optimized and intrinsified `string.toCharArray(destination)`.
* It copies the content by up-to 8 times faster.
* Then we iterate over the char-array and execute single check over
* each character that is easily unrolled and vectorized by the inliner.
* If escape character is found, we fallback to per-symbol processing.
*
* 3) We pool char arrays in order to save excess resizes, allocations
* and nulls-out of arrays.
*/
internal actual class JsonToStringWriter : JsonWriter {
private var array: CharArray = CharArrayPool.take()
private var size = 0
actual override fun writeLong(value: Long) {
// Can be hand-rolled, but requires a lot of code and corner-cases handling
write(value.toString())
}
actual override fun writeChar(char: Char) {
ensureAdditionalCapacity(1)
array[size++] = char
}
actual override fun write(text: String) {
val length = text.length
if (length == 0) return
ensureAdditionalCapacity(length)
text.toCharArray(array, size, 0, text.length)
size += length
}
actual override fun writeQuoted(text: String) {
ensureAdditionalCapacity(text.length + 2)
val arr = array
var sz = size
arr[sz++] = '"'
val length = text.length
text.toCharArray(arr, sz, 0, length)
for (i in sz until sz + length) {
val ch = arr[i].code
// Do we have unescaped symbols?
if (ch < ESCAPE_MARKERS.size && ESCAPE_MARKERS[ch] != 0.toByte()) {
// Go to slow path
return appendStringSlowPath(i - sz, i, text)
}
}
// Update the state
// Capacity is not ensured because we didn't hit the slow path and thus guessed it properly in the beginning
sz += length
arr[sz++] = '"'
size = sz
}
private fun appendStringSlowPath(firstEscapedChar: Int, currentSize: Int, string: String) {
var sz = currentSize
for (i in firstEscapedChar until string.length) {
/*
* We ar already on slow path and haven't guessed the capacity properly.
* Reserve +2 for backslash-escaped symbols on each iteration
*/
sz = ensureTotalCapacity(sz, 2)
val ch = string[i].code
// Do we have unescaped symbols?
if (ch < ESCAPE_MARKERS.size) {
/*
* Escape markers are populated for backslash-escaped symbols.
* E.g. ESCAPE_MARKERS['\b'] == 'b'.toByte()
* Everything else is populated with either zeros (no escapes)
* or ones (unicode escape)
*/
when (val marker = ESCAPE_MARKERS[ch]) {
0.toByte() -> {
array[sz++] = ch.toChar()
}
1.toByte() -> {
val escapedString = ESCAPE_STRINGS[ch]!!
sz = ensureTotalCapacity(sz, escapedString.length)
escapedString.toCharArray(array, sz, 0, escapedString.length)
sz += escapedString.length
size = sz // Update size so the next resize will take it into account
}
else -> {
array[sz] = '\\'
array[sz + 1] = marker.toInt().toChar()
sz += 2
size = sz // Update size so the next resize will take it into account
}
}
} else {
array[sz++] = ch.toChar()
}
}
sz = ensureTotalCapacity(sz, 1)
array[sz++] = '"'
size = sz
}
actual override fun release() {
CharArrayPool.release(array)
}
actual override fun toString(): String {
return String(array, 0, size)
}
private fun ensureAdditionalCapacity(expected: Int) {
ensureTotalCapacity(size, expected)
}
// Old size is passed and returned separately to avoid excessive [size] field read
private fun ensureTotalCapacity(oldSize: Int, additional: Int): Int {
val newSize = oldSize + additional
if (array.size <= newSize) {
array = array.copyOf(newSize.coerceAtLeast(oldSize * 2))
}
return oldSize
}
}
| apache-2.0 | 1785c5cfef0d05448c4c117322247ba2 | 37.5 | 116 | 0.578113 | 4.691756 | false | false | false | false |
lllllT/kktAPK | app/src/main/kotlin/com/bl_lia/kirakiratter/domain/entity/realm/RealmStatus.kt | 1 | 1270 | package com.bl_lia.kirakiratter.domain.entity.realm
import com.bl_lia.kirakiratter.domain.entity.Status
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import java.util.*
open class RealmStatus(
@PrimaryKey
open var id: Int = -1,
open var content: RealmContent? = null,
open var account: RealmAccount? = null,
open var reblog: RealmStatus? = null,
open var reblogged: Boolean = false,
open var favourited: Boolean = false,
open var mediaAttachments: RealmList<RealmMedia> = RealmList(),
open var sensitive: Boolean = false,
open var createdAt: Date? = null,
open var url: String? = null
): RealmObject() {
fun toStatus(): Status =
Status(
id = id,
content = content?.toContent(),
account = account?.toAccount(),
reblog = reblog?.toStatus(),
reblogged = reblogged,
favourited = favourited,
mediaAttachments = mediaAttachments.map { it.toMedia() },
sensitive = sensitive,
createdAt = createdAt,
url = url
)
} | mit | 00409814b6faed1cd45bedc119d4c956 | 34.305556 | 77 | 0.567717 | 4.828897 | false | false | false | false |
i7c/cfm | server/recorder/src/main/kotlin/org/rliz/cfm/recorder/playback/api/PlaybackApi.kt | 1 | 3869 | package org.rliz.cfm.recorder.playback.api
import org.rliz.cfm.recorder.common.api.toHttpResponse
import org.rliz.cfm.recorder.common.api.toRes
import org.rliz.cfm.recorder.common.security.currentUser
import org.rliz.cfm.recorder.playback.boundary.PlaybackBoundary
import org.rliz.cfm.recorder.playback.data.Playback
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.data.web.SortDefault
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.util.UUID
import javax.validation.Valid
@RestController
@RequestMapping(path = ["/rec/v1/playbacks"])
class PlaybackApi {
@Autowired
lateinit var playbackBoundary: PlaybackBoundary
@RequestMapping(method = [RequestMethod.POST])
fun postPlayback(
@Valid @RequestBody body: PlaybackRes,
@RequestParam(name = "id-method", required = false) idMethod: String?
) =
playbackBoundary.createPlayback(
id = body.id,
artists = body.artists,
release = body.releaseTitle!!,
recording = body.recordingTitle!!,
timestamp = body.timestamp,
idMethod = idMethod,
length = body.trackLength,
playtime = body.playTime,
source = body.source
).toRes().toHttpResponse(HttpStatus.CREATED)
@RequestMapping(method = [RequestMethod.GET])
fun getPlaybacks(
@RequestParam("userId", required = false) userId: UUID?,
@RequestParam("broken", required = false, defaultValue = "false") unattached: Boolean,
@SortDefault(sort = ["timestamp"], direction = Sort.Direction.DESC) pageable: Pageable
) =
playbackBoundary.getPlaybacksForUser(userId ?: currentUser().uuid!!, unattached, pageable)
.toRes(Playback::toRes).toHttpResponse(HttpStatus.OK)
@RequestMapping(method = [RequestMethod.GET], path = ["/{playbackId}"])
fun getPlayback(@PathVariable("playbackId") playbackId: UUID) =
playbackBoundary.getPlayback(playbackId).toRes().toHttpResponse(HttpStatus.OK)
@RequestMapping(method = [RequestMethod.POST], path = ["/batch"])
fun postPlaybackBatch(@RequestBody batch: PlaybackBatchRes) =
playbackBoundary.batchCreatePlaybacks(batch.playbacks).toRes().toHttpResponse(HttpStatus.OK)
@RequestMapping(method = [RequestMethod.PUT], path = ["/now"])
fun putNowPlaying(
@RequestBody body: PlaybackRes,
@RequestParam(name = "id-method", required = false) idMethod: String?
) =
playbackBoundary.setNowPlaying(
artists = body.artists,
release = body.releaseTitle!!,
recording = body.recordingTitle!!,
timestamp = body.timestamp,
trackLength = body.trackLength,
idMethod = idMethod
).toRes().toHttpResponse(HttpStatus.OK)
@RequestMapping(method = [RequestMethod.GET], path = ["/now"])
fun getNowPlaying() = playbackBoundary.getNowPlaying().toRes().toHttpResponse(HttpStatus.OK)
@RequestMapping(method = [RequestMethod.DELETE])
fun deletePlaybacks(@RequestParam(required = true) withSource: String?) =
playbackBoundary.deletePlaybacks(withSource).toRes().toHttpResponse(HttpStatus.OK)
@RequestMapping(method = [RequestMethod.GET], path = ["/fixlog"])
fun getFixLog(pageable: Pageable) = playbackBoundary.getFixLog(currentUser(), pageable)
.toRes(Playback::toRes)
}
| gpl-3.0 | 6d886258aa2a01ff2813b6486a374959 | 43.471264 | 100 | 0.717498 | 4.578698 | false | false | false | false |
PaulWoitaschek/Voice | scanner/src/main/kotlin/voice/app/scanner/MediaScanner.kt | 1 | 1630 | package voice.app.scanner
import androidx.documentfile.provider.DocumentFile
import voice.common.BookId
import voice.data.folders.FolderType
import voice.data.repo.BookContentRepo
import javax.inject.Inject
class MediaScanner
@Inject constructor(
private val contentRepo: BookContentRepo,
private val chapterParser: ChapterParser,
private val bookParser: BookParser,
) {
suspend fun scan(folders: Map<FolderType, List<DocumentFile>>) {
val files = folders.flatMap { (folderType, files) ->
when (folderType) {
FolderType.SingleFile, FolderType.SingleFolder -> {
files
}
FolderType.Root -> {
files.flatMap { file ->
file.listFiles().toList()
}
}
}
}
contentRepo.setAllInactiveExcept(files.map { BookId(it.uri) })
files.forEach { scan(it) }
}
private suspend fun scan(file: DocumentFile) {
val chapters = chapterParser.parse(file)
if (chapters.isEmpty()) return
val content = bookParser.parseAndStore(chapters, file)
val chapterIds = chapters.map { it.id }
val currentChapterGone = content.currentChapter !in chapterIds
val currentChapter = if (currentChapterGone) chapterIds.first() else content.currentChapter
val positionInChapter = if (currentChapterGone) 0 else content.positionInChapter
val updated = content.copy(
chapters = chapterIds,
currentChapter = currentChapter,
positionInChapter = positionInChapter,
isActive = true,
)
if (content != updated) {
validateIntegrity(updated, chapters)
contentRepo.put(updated)
}
}
}
| gpl-3.0 | 254d1ecb1865849968a9dcde14bca6f7 | 28.107143 | 95 | 0.692638 | 4.578652 | false | false | false | false |
Mauin/detekt | detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/util/IteratorExtension.kt | 1 | 1189 | package io.gitlab.arturbosch.detekt.rules.bugs.util
import io.gitlab.arturbosch.detekt.rules.collectByType
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtThrowExpression
internal fun KtClassOrObject.isImplementingIterator(): Boolean {
val typeList = this.getSuperTypeList()?.entries
val name = typeList?.firstOrNull()?.typeAsUserType?.referencedName
return name == "Iterator"
}
internal fun KtClassOrObject.getMethod(name: String): KtNamedFunction? {
val functions = this.declarations.filterIsInstance(KtNamedFunction::class.java)
return functions.firstOrNull { it.name == name && it.valueParameters.isEmpty() }
}
internal fun KtNamedFunction.throwsNoSuchElementExceptionThrown(): Boolean {
return this.bodyExpression
?.collectByType<KtThrowExpression>()
?.any { isNoSuchElementExpression(it) } ?: false
}
private fun isNoSuchElementExpression(expression: KtThrowExpression): Boolean {
val calleeExpression = (expression.thrownExpression as? KtCallExpression)?.calleeExpression
return calleeExpression?.text == "NoSuchElementException"
}
| apache-2.0 | f3e2fd8e7d06887dd9020b9a7a26b995 | 40 | 92 | 0.81413 | 4.681102 | false | false | false | false |
AcapellaSoft/Aconite | aconite-server/src/io/aconite/server/errors/LogErrorHandler.kt | 1 | 995 | package io.aconite.server.errors
import io.aconite.*
import io.aconite.server.ServerRequestAcceptor
import org.slf4j.LoggerFactory
object LogErrorHandler : ServerRequestAcceptor.Factory<LogErrorHandler.Configuration> {
class Configuration {
var clazz: Class<*> = LogErrorHandler::class.java
}
override fun create(inner: ServerRequestAcceptor, configurator: Configuration.() -> Unit): ServerRequestAcceptor {
val config = Configuration().apply(configurator)
val logger = LoggerFactory.getLogger(config.clazz)
return ErrorHandler(inner) { ex ->
when (ex) {
is HttpException -> ex.toResponse()
else -> {
logger.error("Internal server error", ex)
Response (
code = 500,
body = BodyBuffer(Buffer.wrap("Internal server error"), "text/plain")
)
}
}
}
}
} | mit | 4f2c4b04d2e95febd8f21c2a29184744 | 33.344828 | 118 | 0.58191 | 5.292553 | false | true | false | false |
songzhw/AndroidArchitecture | deprecated/CoroutineFlowLiveData/app/src/main/java/ca/six/archi/cfl/biz/MainActivity.kt | 1 | 3459 | package ca.six.archi.cfl.biz
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import ca.six.archi.cfl.ui.OnRvItemClickListener
import ca.six.archi.cfl.R
import ca.six.archi.cfl.core.App
import ca.six.archi.cfl.data.Plant
import ca.six.oneadapter.lib.OneDiffAdapter
import ca.six.oneadapter.lib.RvViewHolder
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private lateinit var adapter: OneDiffAdapter<Plant>
private lateinit var vm: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val diffCallback = object : DiffUtil.ItemCallback<Plant>() {
override fun areItemsTheSame(oldItem: Plant, newItem: Plant): Boolean = oldItem.plantId == newItem.plantId
override fun areContentsTheSame(oldItem: Plant, newItem: Plant): Boolean = oldItem == newItem
}
rv.layoutManager = GridLayoutManager(this, 2)
adapter = object : OneDiffAdapter<Plant>(diffCallback, R.layout.item_plants) {
override fun apply(vh: RvViewHolder, value: Plant, position: Int) {
val iv = vh.getView<ImageView>(R.id.ivPlant)
Glide.with(this@MainActivity).load(value.imageUrl).into(iv)
// Picasso.get().load(value.imageUrl).into(iv); //让界面超级卡, 故我改为Glide
vh.setText(R.id.tvPlant, value.name)
}
}
rv.addOnItemTouchListener(object : OnRvItemClickListener(rv) {
override fun onItemClick(vh: RecyclerView.ViewHolder) {
val position = vh.adapterPosition
val plant = vm.getPlant(position)
val intent = Intent(this@MainActivity, DetailActivity::class.java)
.putExtra("plant", plant)
startActivity(intent)
}
})
rv.adapter = adapter
vm = ViewModelProvider(this).get(MainViewModel::class.java)
vm.injector = App.injector
vm.dataLiveData.observe(this) { resp ->
adapter.refresh(resp)
}
vm.gridDisplayLiveData.observe(this) { isGrid ->
rv.layoutManager = GridLayoutManager(this, 2)
}
vm.listDisplayLiveData.observe(this) { isList ->
rv.layoutManager = LinearLayoutManager(this)
}
vm.fetchPlants()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menuDisplay -> {
vm.updateDisplay()
item.setIcon(vm.displayIcon)
true
}
R.id.menuFilter -> {
vm.filterData()
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
| apache-2.0 | f020950c17369d6bc3dc638db94c6787 | 34.822917 | 118 | 0.655423 | 4.542933 | false | false | false | false |
coconautti/sequel | src/main/kotlin/coconautti/ddl/Column.kt | 1 | 1762 | package coconautti.ddl
import coconautti.sql.Value
abstract class Column(val name: String) {
private var primaryKey = false
private var autoIncrement = false
private var unique = false
private var nullable = false
private var default: Value? = null
fun primaryKey(): Column {
primaryKey = true
return this
}
fun autoIncrement(): Column {
autoIncrement = true
return this
}
fun unique(): Column {
unique = true
return this
}
fun nullable(): Column {
nullable = true
return this
}
fun default(value: Any?): Column {
default = Value(value)
return this
}
abstract fun type(): String
override fun toString(): String {
val sb = StringBuilder()
sb.append(name)
sb.append(type())
if (unique) {
sb.append(" UNIQUE")
}
if (autoIncrement) {
sb.append(" AUTO_INCREMENT")
}
if (primaryKey) {
sb.append(" PRIMARY KEY")
} else if (!nullable) {
sb.append(" NOT NULL")
}
default?.let {
sb.append(" DEFAULT ${default.toString()}")
}
return sb.toString()
}
}
class Varchar(name: String, private val length: Int) : Column(name) {
override fun type(): String = " VARCHAR($length)"
}
class Bigint(name: String) : Column(name) {
override fun type(): String = " BIGINT"
}
class Clob(name: String) : Column(name) {
override fun type(): String = " CLOB"
}
class Timestamp(name: String) : Column(name) {
override fun type(): String = " TIMESTAMP"
}
class Bool(name: String) : Column(name) {
override fun type(): String = " BOOLEAN"
}
| apache-2.0 | 85b55ee128a0b64eda66830066dfe3b4 | 19.97619 | 69 | 0.564699 | 4.22542 | false | false | false | false |
ol-loginov/intellij-community | platform/script-debugger/protocol/protocol-reader/src/InterfaceReader.kt | 2 | 8489 | package org.jetbrains.protocolReader
import gnu.trove.THashSet
import org.jetbrains.io.JsonReaderEx
import org.jetbrains.jsonProtocol.JsonField
import org.jetbrains.jsonProtocol.JsonOptionalField
import org.jetbrains.jsonProtocol.JsonSubtype
import org.jetbrains.jsonProtocol.StringIntPair
import java.lang.reflect.Method
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.lang.reflect.WildcardType
import java.util.ArrayList
import java.util.LinkedHashMap
fun InterfaceReader(protocolInterfaces: Array<Class<*>>): InterfaceReader {
val map = LinkedHashMap<Class<*>, TypeWriter<*>>(protocolInterfaces.size())
for (typeClass in protocolInterfaces) {
map.put(typeClass, null)
}
return InterfaceReader(map)
}
private val LONG_PARSER = PrimitiveValueReader("long", "-1")
private val INTEGER_PARSER = PrimitiveValueReader("int", "-1")
private val BOOLEAN_PARSER = PrimitiveValueReader("boolean")
private val FLOAT_PARSER = PrimitiveValueReader("float")
private val NUMBER_PARSER = PrimitiveValueReader("double")
private val STRING_PARSER = PrimitiveValueReader("String")
private val NULLABLE_STRING_PARSER = PrimitiveValueReader(className = "String", nullable = true)
private val RAW_STRING_PARSER = PrimitiveValueReader("String", null, true)
private val RAW_STRING_OR_MAP_PARSER = object : PrimitiveValueReader("Object", null, true) {
override fun writeReadCode(scope: ClassScope, subtyping: Boolean, out: TextOutput) {
out.append("readRawStringOrMap(")
addReaderParameter(subtyping, out)
out.append(')')
}
}
private val JSON_PARSER = RawValueReader()
private val STRING_INT_PAIR_PARSER = StringIntPairValueReader()
val VOID_PARSER: ValueReader = object : ValueReader() {
override fun appendFinishedValueTypeName(out: TextOutput) {
out.append("void")
}
override fun writeReadCode(scope: ClassScope, subtyping: Boolean, out: TextOutput) {
out.append("null")
}
}
fun createHandler(typeToTypeHandler: LinkedHashMap<Class<*>, TypeWriter<*>>, aClass: Class<*>): TypeWriter<*> {
val reader = InterfaceReader(typeToTypeHandler)
reader.processed.addAll(typeToTypeHandler.keySet())
reader.go(array(aClass))
return typeToTypeHandler.get(aClass)
}
class InterfaceReader(val typeToTypeHandler: LinkedHashMap<Class<*>, TypeWriter<*>>) {
val processed = THashSet<Class<*>>()
private val refs = ArrayList<TypeRef<*>>()
val subtypeCasters = ArrayList<SubtypeCaster>()
fun go(): LinkedHashMap<Class<*>, TypeWriter<*>> {
return go(typeToTypeHandler.keySet().copyToArray())
}
fun go(classes: Array<Class<*>>): LinkedHashMap<Class<*>, TypeWriter<*>> {
for (typeClass in classes) {
createIfNotExists(typeClass)
}
var hasUnresolved = true
while (hasUnresolved) {
hasUnresolved = false
// refs can be modified - new items can be added
for (i in 0..refs.size() - 1) {
val ref = refs.get(i)
ref.type = typeToTypeHandler.get(ref.typeClass)
if (ref.type == null) {
createIfNotExists(ref.typeClass)
hasUnresolved = true
ref.type = typeToTypeHandler.get(ref.typeClass)
if (ref.type == null) {
throw IllegalStateException()
}
}
}
}
for (subtypeCaster in subtypeCasters) {
subtypeCaster.getSubtypeHandler().subtypeAspect?.setSubtypeCaster(subtypeCaster)
}
return typeToTypeHandler
}
private fun createIfNotExists(typeClass: Class<*>) {
if (typeClass == javaClass<Map<Any, Any>>() || typeClass == javaClass<List<Any>>() || !typeClass.isInterface()) {
return
}
if (!processed.add(typeClass)) {
return
}
typeToTypeHandler.put(typeClass, null)
for (aClass in typeClass.getDeclaredClasses()) {
createIfNotExists(aClass)
}
if (!typeClass.isInterface()) {
throw JsonProtocolModelParseException("Json model type should be interface: " + typeClass.getName())
}
val fields = FieldProcessor(this, typeClass)
for (method in fields.methodHandlerMap.keySet()) {
val returnType = method.getReturnType()
if (returnType != typeClass) {
createIfNotExists(returnType)
}
}
val typeWriter = TypeWriter(typeClass, getSuperclassRef(typeClass), fields.volatileFields, fields.methodHandlerMap, fields.fieldLoaders, fields.lazyRead)
for (ref in refs) {
if (ref.typeClass == typeClass) {
assert(ref.type == null)
ref.type = typeWriter
break
}
}
typeToTypeHandler.put(typeClass, typeWriter)
}
fun getFieldTypeParser(type: Type, isSubtyping: Boolean, method: Method?): ValueReader {
if (type is Class<*>) {
if (type == java.lang.Long.TYPE) {
return LONG_PARSER
}
else if (type == Integer.TYPE) {
return INTEGER_PARSER
}
else if (type == java.lang.Boolean.TYPE) {
return BOOLEAN_PARSER
}
else if (type == java.lang.Float.TYPE) {
return FLOAT_PARSER
}
else if (type == javaClass<Number>() || type == java.lang.Double.TYPE) {
return NUMBER_PARSER
}
else if (type == Void.TYPE) {
return VOID_PARSER
}
else if (type == javaClass<String>()) {
if (method != null) {
val jsonField = method.getAnnotation<JsonField>(javaClass<JsonField>())
if (jsonField != null && jsonField.allowAnyPrimitiveValue()) {
return RAW_STRING_PARSER
}
else if ((jsonField != null && jsonField.optional()) || method.getAnnotation<JsonOptionalField>(javaClass<JsonOptionalField>()) != null) {
return NULLABLE_STRING_PARSER
}
}
return STRING_PARSER
}
else if (type == javaClass<Any>()) {
return RAW_STRING_OR_MAP_PARSER
}
else if (type == javaClass<JsonReaderEx>()) {
return JSON_PARSER
}
else if (type == javaClass<StringIntPair>()) {
return STRING_INT_PAIR_PARSER
}
else if (type.isArray()) {
return ArrayReader(getFieldTypeParser(type.getComponentType(), false, null), false)
}
else if (type.isEnum()) {
return EnumReader(type as Class<Enum<*>>)
}
val ref = getTypeRef(type)
if (ref != null) {
return ObjectValueReader(ref, isSubtyping, method?.getAnnotation<JsonField>(javaClass<JsonField>())?.primitiveValue())
}
throw UnsupportedOperationException("Method return type " + type + " (simple class) not supported")
}
else if (type is ParameterizedType) {
val isList = type.getRawType() == javaClass<List<Any>>()
if (isList || type.getRawType() == javaClass<Map<Any, Any>>()) {
var argumentType = type.getActualTypeArguments()[if (isList) 0 else 1]
if (argumentType is WildcardType) {
val wildcard = argumentType as WildcardType
if (wildcard.getLowerBounds().size() == 0 && wildcard.getUpperBounds().size() == 1) {
argumentType = wildcard.getUpperBounds()[0]
}
}
val componentParser = getFieldTypeParser(argumentType, false, method)
return if (isList) ArrayReader(componentParser, true) else MapReader(componentParser)
}
else {
throw UnsupportedOperationException("Method return type " + type + " (generic) not supported")
}
}
else {
throw UnsupportedOperationException("Method return type " + type + " not supported")
}
}
fun <T> getTypeRef(typeClass: Class<T>): TypeRef<T>? {
val result = TypeRef(typeClass)
refs.add(result)
return result
}
private fun getSuperclassRef(typeClass: Class<*>): TypeRef<*>? {
var result: TypeRef<*>? = null
for (interfaceGeneric in typeClass.getGenericInterfaces()) {
if (interfaceGeneric !is ParameterizedType) {
continue
}
if (interfaceGeneric.getRawType() != javaClass<JsonSubtype<Any>>()) {
continue
}
val param = interfaceGeneric.getActualTypeArguments()[0]
if (param !is Class<*>) {
throw JsonProtocolModelParseException("Unexpected type of superclass " + param)
}
if (result != null) {
throw JsonProtocolModelParseException("Already has superclass " + result!!.typeClass.getName())
}
result = getTypeRef(param)
if (result == null) {
throw JsonProtocolModelParseException("Unknown base class " + param.getName())
}
}
return result
}
} | apache-2.0 | 55704a777a82127c74844f4c431f9222 | 33.37247 | 157 | 0.662269 | 4.598592 | false | false | false | false |
programingjd/server | src/test/kotlin/info/jdavid/asynk/server/http/base/DefaultHttpHandler.kt | 1 | 2835 | package info.jdavid.asynk.server.http.base
import info.jdavid.asynk.core.asyncWrite
import info.jdavid.asynk.http.Crypto
import info.jdavid.asynk.http.Headers
import info.jdavid.asynk.http.MediaType
import java.nio.ByteBuffer
import java.nio.channels.AsynchronousSocketChannel
open class DefaultHttpHandler(maxRequestSize: Int = 4096): SimpleHttpHandler(maxRequestSize) {
override suspend fun handle(acceptance: Acceptance, headers: Headers, body: ByteBuffer,
socket: AsynchronousSocketChannel,
context: Context) {
val str = StringBuilder()
str.append("${acceptance.method} ${acceptance.uri}\r\n\r\n")
str.append(headers.lines.joinToString("\r\n"))
str.append("\n\n")
val contentType = headers.value(Headers.CONTENT_TYPE) ?: "text/plain"
val isText =
contentType.startsWith("text/") ||
contentType.startsWith("application/") &&
(contentType.startsWith(MediaType.JAVASCRIPT) ||
contentType.startsWith(MediaType.JSON) ||
contentType.startsWith(MediaType.XHTML) ||
contentType.startsWith(MediaType.WEB_MANIFEST))
//val extra = if (isText) body.remaining() else Math.min(2048, body.remaining() * 2)
val extra = if (isText) body.remaining() else body.remaining() * 2
val bytes = str.toString().toByteArray(Charsets.ISO_8859_1)
socket.asyncWrite(
ByteBuffer.wrap(
"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: ${bytes.size + extra}\r\nConnection: close\r\n\r\n".
toByteArray(Charsets.US_ASCII)
),
true
)
socket.asyncWrite(ByteBuffer.wrap(bytes), true)
if (extra > 0) {
if (contentType.startsWith("text/") ||
contentType.startsWith("application/") &&
(contentType.startsWith(MediaType.JAVASCRIPT) ||
contentType.startsWith(MediaType.JSON) ||
contentType.startsWith(MediaType.XHTML) ||
contentType.startsWith(MediaType.WEB_MANIFEST))) {
socket.asyncWrite(body, true)
}
else {
// if (body.remaining() > 1024) {
// val limit = body.limit()
// body.limit(body.position() + 511)
// socket.asyncWrite(
// ByteBuffer.wrap(Crypto.hex(body).toByteArray(Charsets.US_ASCII)),
// true
// )
// socket.asyncWrite(
// ByteBuffer.wrap("....".toByteArray(Charsets.US_ASCII)),
// true
// )
// body.limit(limit)
// body.position(limit - 511)
// socket.asyncWrite(
// ByteBuffer.wrap(Crypto.hex(body).toByteArray(Charsets.US_ASCII)),
// true
// )
// }
// else {
socket.asyncWrite(ByteBuffer.wrap(Crypto.hex(body).toByteArray(Charsets.US_ASCII)), true)
// }
}
}
}
}
| apache-2.0 | bf0d32b48df5b54a119519ae486e5a87 | 37.310811 | 124 | 0.622222 | 4.044223 | false | false | false | false |
mockk/mockk | modules/mockk-agent-android/src/main/kotlin/io/mockk/proxy/android/transformation/AndroidSubclassInstrumentation.kt | 2 | 3159 | package io.mockk.proxy.android.transformation
import android.os.Build
import com.android.dx.stock.ProxyBuilder
import com.android.dx.stock.ProxyBuilder.MethodSetEntry
import io.mockk.proxy.MockKAgentException
import io.mockk.proxy.MockKInvocationHandler
import io.mockk.proxy.common.ProxyInvocationHandler
import io.mockk.proxy.common.transformation.SubclassInstrumentation
import java.lang.reflect.Method
import java.lang.reflect.Modifier
internal class AndroidSubclassInstrumentation(
val inlineInstrumentationApplied: Boolean
) : SubclassInstrumentation {
@Suppress("UNCHECKED_CAST")
override fun <T> subclass(clazz: Class<T>, interfaces: Array<Class<*>>): Class<T> =
try {
ProxyBuilder.forClass(clazz)
.implementing(*interfaces)
.apply {
if (inlineInstrumentationApplied) {
onlyMethods(getMethodsToProxy(clazz, interfaces))
}
}
.apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// markTrusted();
}
}
.apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
withSharedClassLoader()
}
}
.buildProxyClass() as Class<T>
} catch (e: Exception) {
throw MockKAgentException("Failed to mock $clazz", e)
}
private fun <T> getMethodsToProxy(clazz: Class<T>, interfaces: Array<Class<*>>): Array<Method> {
val abstractMethods = mutableSetOf<MethodSetEntry>()
val nonAbstractMethods = mutableSetOf<MethodSetEntry>()
tailrec fun fillInAbstractAndNonAbstract(clazz: Class<*>) {
clazz.declaredMethods
.filter { Modifier.isAbstract(it.modifiers) }
.map { MethodSetEntry(it) }
.filterNotTo(abstractMethods) { it in nonAbstractMethods }
clazz.declaredMethods
.filterNot { Modifier.isAbstract(it.modifiers) }
.mapTo(nonAbstractMethods) { MethodSetEntry(it) }
fillInAbstractAndNonAbstract(clazz.superclass ?: return)
}
fillInAbstractAndNonAbstract(clazz)
fun Class<*>.allSuperInterfaces(): Set<Class<*>> {
val setOfInterfaces = this.interfaces.toSet()
return setOfInterfaces + setOfInterfaces.flatMap { it.allSuperInterfaces() }
}
(clazz.interfaces + interfaces)
.asSequence()
.flatMap { it.allSuperInterfaces().asSequence() }
.flatMap { it.methods.asSequence() }
.map { MethodSetEntry(it) }
.filterNot { it in nonAbstractMethods }
.mapTo(abstractMethods) { it }
return abstractMethods.map { it.originalMethod }.toTypedArray()
}
override fun setProxyHandler(proxy: Any, handler: MockKInvocationHandler) {
if (ProxyBuilder.isProxyClass(proxy::class.java)) {
ProxyBuilder.setInvocationHandler(proxy, ProxyInvocationHandler(handler))
}
}
} | apache-2.0 | 2555d396be82d1841cd49ae6304b28ce | 36.619048 | 100 | 0.610003 | 4.951411 | false | false | false | false |
mockk/mockk | modules/mockk/src/commonMain/kotlin/io/mockk/impl/recording/states/AnsweringState.kt | 2 | 1081 | package io.mockk.impl.recording.states
import io.mockk.InternalPlatformDsl.toStr
import io.mockk.Invocation
import io.mockk.MockKGateway.VerificationParameters
import io.mockk.impl.log.Logger
import io.mockk.impl.recording.CommonCallRecorder
open class AnsweringState(recorder: CommonCallRecorder) : CallRecordingState(recorder) {
open val log = recorder.safeToString(Logger<AnsweringState>())
override fun call(invocation: Invocation): Any? {
val stub = recorder.stubRepo.stubFor(invocation.self)
stub.recordCall(invocation.copy(originalCall = { null }))
try {
val answer = stub.answer(invocation)
log.debug { "Answering ${answer.toStr()} on $invocation" }
return answer
} catch (ex: Exception) {
log.debug { "Throwing ${ex.toStr()} on $invocation" }
throw ex
}
}
override fun startStubbing() = recorder.factories.stubbingState(recorder)
override fun startVerification(params: VerificationParameters) = recorder.factories.verifyingState(recorder, params)
} | apache-2.0 | 00ef456e12f5d1fb96cb59a91af8e639 | 39.074074 | 120 | 0.708603 | 4.504167 | false | false | false | false |
HouHanLab/Android-HHLibrary | base/src/main/java/request/RetrofitUtil.kt | 1 | 1306 | package request
import constant.Constant
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import util.LogUtil
/**
* 作用 网络请求工具类,单例
* Created by 司马林 on 2017/10/10.
*/
class RetrofitUtil private constructor() {
private object getInstance {
val INSTANCE = RetrofitUtil()
}
companion object {
val instance: RetrofitUtil by lazy { getInstance.INSTANCE }
private var client: OkHttpClient? = null
init {
val interceptor = Interceptor { chain ->
val request = chain.request().newBuilder().build()
LogUtil.e(request.toString())
chain.proceed(request)
}
client = OkHttpClient.Builder().addInterceptor(interceptor).build()
}
}
fun<S> getApi(server:Class<S>): S {
val retrofit: Retrofit = Retrofit.Builder().baseUrl(Constant.BASE_URL)
.client(client)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
return retrofit.create(server)
}
} | apache-2.0 | 9ec51e84fb58ec40cec2393c9b5e3b12 | 26.76087 | 79 | 0.645768 | 4.870229 | false | false | false | false |
andremion/Louvre | louvre/src/main/java/com/andremion/louvre/data/MediaLoader.kt | 1 | 6732 | /*
* Copyright (c) 2020. André Mion
*
* 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.andremion.louvre.data
import android.database.Cursor
import android.database.MatrixCursor
import android.database.MergeCursor
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import androidx.annotation.IntRange
import androidx.fragment.app.FragmentActivity
import androidx.loader.app.LoaderManager
import androidx.loader.content.CursorLoader
import androidx.loader.content.Loader
import com.andremion.louvre.R
private const val TIME_LOADER = 0
private const val BUCKET_LOADER = 1
private const val MEDIA_LOADER = 2
private const val ARG_BUCKET_ID = MediaStore.Images.Media.BUCKET_ID
/**
* [Loader] for media and bucket data
*/
class MediaLoader : LoaderManager.LoaderCallbacks<Cursor?> {
interface Callbacks {
fun onBucketLoadFinished(data: Cursor?)
fun onMediaLoadFinished(data: Cursor?)
}
private var activity: FragmentActivity? = null
private var callbacks: Callbacks? = null
private var typeFilter = "1" // Means all media type.
override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor?> =
ensureActivityAttached().let { activity ->
when (id) {
TIME_LOADER -> CursorLoader(
activity,
GALLERY_URI,
IMAGE_PROJECTION,
typeFilter,
null,
MEDIA_SORT_ORDER
)
BUCKET_LOADER -> CursorLoader(
activity,
GALLERY_URI,
BUCKET_PROJECTION,
"$typeFilter AND $BUCKET_SELECTION",
null,
BUCKET_SORT_ORDER
)
// id == MEDIA_LOADER
else -> CursorLoader(
activity,
GALLERY_URI,
IMAGE_PROJECTION,
"${MediaStore.Images.Media.BUCKET_ID}=${args?.getLong(ARG_BUCKET_ID) ?: 0} AND $typeFilter",
null,
MEDIA_SORT_ORDER
)
}
}
override fun onLoadFinished(loader: Loader<Cursor?>, data: Cursor?) {
callbacks?.let { callbacks ->
if (loader.id == BUCKET_LOADER) {
callbacks.onBucketLoadFinished(finishUpBuckets(data))
} else {
callbacks.onMediaLoadFinished(data)
}
}
}
override fun onLoaderReset(loader: Loader<Cursor?>) {
// no-op
}
fun onAttach(activity: FragmentActivity, callbacks: Callbacks) {
this.activity = activity
this.callbacks = callbacks
}
fun onDetach() {
activity = null
callbacks = null
}
fun setMediaTypes(mediaTypes: Array<String>) {
val filter = mediaTypes.joinToString { "'$it'" }
if (filter.isNotEmpty()) {
typeFilter = "${MediaStore.Images.Media.MIME_TYPE} IN ($filter)"
}
}
fun loadBuckets() {
LoaderManager.getInstance(ensureActivityAttached())
.restartLoader(BUCKET_LOADER, null, this)
}
fun loadByBucket(@IntRange(from = 0) bucketId: Long) {
ensureActivityAttached().let { activity ->
if (ALL_MEDIA_BUCKET_ID == bucketId) {
LoaderManager.getInstance(activity).restartLoader(TIME_LOADER, null, this)
} else {
val args = Bundle()
args.putLong(ARG_BUCKET_ID, bucketId)
LoaderManager.getInstance(activity).restartLoader(MEDIA_LOADER, args, this)
}
}
}
/**
* Ensure that a FragmentActivity is attached to this loader.
*/
private fun ensureActivityAttached(): FragmentActivity =
requireNotNull(activity) { "The FragmentActivity was not attached!" }
private fun finishUpBuckets(cursor: Cursor?): Cursor? =
MergeCursor(
arrayOf(
addAllMediaBucketItem(cursor),
if (isAllowedAggregatedFunctions) cursor
else aggregateBuckets(cursor)
)
)
/**
* Add "All Media" item as the first row of bucket items.
*
* @param cursor The original data of all bucket items
* @return The data with "All Media" item added
*/
private fun addAllMediaBucketItem(cursor: Cursor?): Cursor? =
cursor?.run {
if (!moveToPosition(0)) return null
val id = ALL_MEDIA_BUCKET_ID
val label = ensureActivityAttached().getString(R.string.activity_gallery_bucket_all_media)
val data = getString(getColumnIndex(MediaStore.Images.Media.DATA))
MatrixCursor(BUCKET_PROJECTION).apply {
newRow()
.add(id)
.add(label)
.add(data)
}
}
/**
* Since we are not allowed to use SQL aggregation functions we need to do that on code
*
* @param cursor The original data of all bucket items
* @return The data aggregated by buckets
*/
private fun aggregateBuckets(cursor: Cursor?): Cursor? =
cursor?.run {
val idIndex = getColumnIndex(MediaStore.Images.Media.BUCKET_ID)
val labelIndex = getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME)
val dataIndex = getColumnIndex(MediaStore.Images.Media.DATA)
val aggregatedBucket = MatrixCursor(BUCKET_PROJECTION)
var previousId = 0L
for (position in 0 until cursor.count) {
moveToPosition(position)
val id = getLong(idIndex)
val label = getString(labelIndex)
val data = getString(dataIndex)
if (id != previousId) {
aggregatedBucket.newRow()
.add(id)
.add(label)
.add(data)
}
previousId = id
}
aggregatedBucket
}
}
internal val isAllowedAggregatedFunctions = Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
| apache-2.0 | c87dd0070ab67ff48f9a078661967cf7 | 32.994949 | 112 | 0.586243 | 4.891715 | false | false | false | false |
Orchextra/orchextra-android-sdk | core/src/main/java/com/gigigo/orchextra/core/domain/actions/actionexecutors/webview/WebViewActivity.kt | 1 | 2228 | /*
* Created by Orchextra
*
* Copyright (C) 2017 Gigigo Mobile Services SL
*
* 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.gigigo.orchextra.core.domain.actions.actionexecutors.webview
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.gigigo.orchextra.core.R
import kotlinx.android.synthetic.main.ox_activity_web_view.oxWebView
import java.net.URI
import java.net.URISyntaxException
class WebViewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.ox_activity_web_view)
initToolbar()
oxWebView.loadUrl(getUrl())
}
private fun initToolbar() {
val toolbar = findViewById<Toolbar>(R.id.ox_toolbar)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
toolbar.setNavigationOnClickListener { onBackPressed() }
title = getDomainName(getUrl())
}
private fun getUrl(): String = intent.getStringExtra(EXTRA_URL) ?: ""
@Throws(URISyntaxException::class)
private fun getDomainName(url: String): String {
val uri = URI(url)
val domain = uri.host
return if (domain.startsWith("www.")) domain.substring(4) else domain
}
companion object Navigator {
val EXTRA_URL = "extra_url"
fun open(context: Context, url: String) {
val intent = Intent(context, WebViewActivity::class.java)
intent.putExtra(EXTRA_URL, url)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
}
}
}
| apache-2.0 | a42c1a8b3535c2da38d1064d5e017ac0 | 29.108108 | 75 | 0.744165 | 4.268199 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/dialogs/LocaleSelectionDialog.kt | 1 | 8666 | /*
Copyright (c) 2020 David Allison <[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.ichi2.anki.dialogs
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.Filter
import android.widget.Filterable
import android.widget.TextView
import androidx.appcompat.widget.SearchView
import androidx.appcompat.widget.Toolbar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import com.ichi2.anki.R
import com.ichi2.anki.analytics.AnalyticsDialogFragment
import com.ichi2.anki.dialogs.LocaleSelectionDialog.LocaleListAdapter.TextViewHolder
import com.ichi2.ui.RecyclerSingleTouchAdapter
import com.ichi2.utils.DisplayUtils.resizeWhenSoftInputShown
import java.util.*
/** Locale selection dialog. Note: this must be dismissed onDestroy if not called from an activity implementing LocaleSelectionDialogHandler */
class LocaleSelectionDialog : AnalyticsDialogFragment() {
private var mDialogHandler: LocaleSelectionDialogHandler? = null
interface LocaleSelectionDialogHandler {
fun onSelectedLocale(selectedLocale: Locale)
fun onLocaleSelectionCancelled()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
isCancelable = true
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is Activity) {
if (mDialogHandler == null) {
require(context is LocaleSelectionDialogHandler) { "Calling activity must implement LocaleSelectionDialogHandler" }
mDialogHandler = context
}
resizeWhenSoftInputShown(context.window)
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val activity: Activity = requireActivity()
val tagsDialogView = LayoutInflater.from(activity)
.inflate(R.layout.locale_selection_dialog, activity.findViewById(R.id.root_layout), false)
val adapter = LocaleListAdapter(Locale.getAvailableLocales())
setupRecyclerView(activity, tagsDialogView, adapter)
inflateMenu(tagsDialogView, adapter)
// Only show a negative button, use the RecyclerView for positive actions
val builder = MaterialDialog.Builder(activity)
.negativeText(getString(R.string.dialog_cancel))
.customView(tagsDialogView, false)
.onNegative { _: MaterialDialog?, _: DialogAction? -> mDialogHandler!!.onLocaleSelectionCancelled() }
val dialog: Dialog = builder.build()
val window = dialog.window
if (window != null) {
resizeWhenSoftInputShown(window)
}
return dialog
}
private fun setupRecyclerView(activity: Activity, tagsDialogView: View, adapter: LocaleListAdapter) {
val recyclerView: RecyclerView = tagsDialogView.findViewById(R.id.locale_dialog_selection_list)
recyclerView.requestFocus()
val layoutManager: RecyclerView.LayoutManager = LinearLayoutManager(activity)
recyclerView.layoutManager = layoutManager
recyclerView.adapter = adapter
recyclerView.addOnItemTouchListener(
RecyclerSingleTouchAdapter(activity) { _: View?, position: Int ->
val l = adapter.getLocaleAtPosition(position)
mDialogHandler!!.onSelectedLocale(l)
}
)
}
private fun inflateMenu(tagsDialogView: View, adapter: LocaleListAdapter) {
val toolbar: Toolbar = tagsDialogView.findViewById(R.id.locale_dialog_selection_toolbar)
toolbar.setTitle(R.string.locale_selection_dialog_title)
toolbar.inflateMenu(R.menu.locale_dialog_search_bar)
val searchItem = toolbar.menu.findItem(R.id.locale_dialog_action_search)
val searchView = searchItem.actionView as SearchView
searchView.imeOptions = EditorInfo.IME_ACTION_DONE
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
return false
}
override fun onQueryTextChange(newText: String): Boolean {
adapter.filter.filter(newText)
return false
}
})
}
class LocaleListAdapter(locales: Array<Locale?>) : RecyclerView.Adapter<TextViewHolder>(), Filterable {
private val mCurrentlyVisibleLocales: MutableList<Locale>
private val mSelectableLocales: List<Locale> = Collections.unmodifiableList(ArrayList(mutableListOf(*locales)))
class TextViewHolder(private val textView: TextView) : RecyclerView.ViewHolder(textView) {
fun setText(text: String) {
textView.text = text
}
fun setLocale(locale: Locale) {
val displayValue = locale.displayName
textView.text = displayValue
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): TextViewHolder {
val v = LayoutInflater.from(parent.context)
.inflate(R.layout.locale_dialog_fragment_textview, parent, false) as TextView
return TextViewHolder(v)
}
override fun onBindViewHolder(holder: TextViewHolder, position: Int) {
holder.setLocale(mCurrentlyVisibleLocales[position])
}
override fun getItemCount(): Int {
return mCurrentlyVisibleLocales.size
}
fun getLocaleAtPosition(position: Int): Locale {
return mCurrentlyVisibleLocales[position]
}
override fun getFilter(): Filter {
val selectableLocales = mSelectableLocales
val visibleLocales = mCurrentlyVisibleLocales
return object : Filter() {
override fun performFiltering(constraint: CharSequence): FilterResults {
if (TextUtils.isEmpty(constraint)) {
val filterResults = FilterResults()
filterResults.values = selectableLocales
return filterResults
}
val normalisedConstraint = constraint.toString().lowercase(Locale.getDefault())
val locales = ArrayList<Locale>(selectableLocales.size)
for (l in selectableLocales) {
if (l.displayName.lowercase(Locale.getDefault()).contains(normalisedConstraint)) {
locales.add(l)
}
}
val filterResults = FilterResults()
filterResults.values = locales
return filterResults
}
@Suppress("UNCHECKED_CAST")
override fun publishResults(constraint: CharSequence, results: FilterResults) {
visibleLocales.clear()
val values = results.values as Collection<Locale>
visibleLocales.addAll(values)
notifyDataSetChanged()
}
}
}
init {
mCurrentlyVisibleLocales = ArrayList(mutableListOf(*locales))
}
}
companion object {
/**
* @param handler Marker interface to enforce the convention the caller implementing LocaleSelectionDialogHandler
*/
@JvmStatic
fun newInstance(handler: LocaleSelectionDialogHandler): LocaleSelectionDialog {
val t = LocaleSelectionDialog()
t.mDialogHandler = handler
val args = Bundle()
t.arguments = args
return t
}
}
}
| gpl-3.0 | ebfbe38907e8d9bfaa48f004951196c7 | 41.067961 | 144 | 0.665243 | 5.630929 | false | false | false | false |
android/databinding-samples | TwoWaySample/app/src/main/java/com/example/android/databinding/twowaysample/ui/MainActivity.kt | 1 | 5628 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.databinding.twowaysample.ui
import android.annotation.SuppressLint
import androidx.lifecycle.ViewModelProviders
import android.content.Context
import androidx.databinding.DataBindingUtil
import androidx.databinding.Observable
import androidx.databinding.ObservableInt
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import com.example.android.databinding.twowaysample.BR
import com.example.android.databinding.twowaysample.R
import com.example.android.databinding.twowaysample.data.IntervalTimerViewModel
import com.example.android.databinding.twowaysample.data.IntervalTimerViewModelFactory
import com.example.android.databinding.twowaysample.databinding.IntervalTimerBinding
const val SHARED_PREFS_KEY = "timer"
/**
* This activity only takes care of binding a ViewModel to the layout. All UI calls are delegated
* to the Data Binding library or Binding Adapters ([BindingAdapters]).
*
* Note that not all calls to the framework are removed, activities are still responsible for non-UI
* interactions with the framework, like Shared Preferences or Navigation.
*/
class MainActivity : AppCompatActivity() {
private val intervalTimerViewModel: IntervalTimerViewModel
by lazy {
ViewModelProviders.of(this, IntervalTimerViewModelFactory)
.get(IntervalTimerViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: IntervalTimerBinding = DataBindingUtil.setContentView(
this, R.layout.interval_timer)
val viewmodel = intervalTimerViewModel
binding.viewmodel = viewmodel
/* Save the user settings whenever they change */
observeAndSaveTimePerSet(
viewmodel.timePerWorkSet, R.string.prefs_timePerWorkSet)
observeAndSaveTimePerSet(
viewmodel.timePerRestSet, R.string.prefs_timePerRestSet)
/* Number of sets needs a different */
observeAndSaveNumberOfSets(viewmodel)
if (savedInstanceState == null) {
/* If this is the first run, restore shared settings */
restorePreferences(viewmodel)
observeAndSaveNumberOfSets(viewmodel)
}
}
private fun observeAndSaveTimePerSet(timePerWorkSet: ObservableInt, prefsKey: Int) {
timePerWorkSet.addOnPropertyChangedCallback(
object : Observable.OnPropertyChangedCallback() {
@SuppressLint("CommitPrefEdits")
override fun onPropertyChanged(observable: Observable?, p1: Int) {
Log.d("saveTimePerWorkSet", "Saving time-per-set preference")
val sharedPref =
getSharedPreferences(SHARED_PREFS_KEY, Context.MODE_PRIVATE) ?: return
sharedPref.edit().apply {
putInt(getString(prefsKey), (observable as ObservableInt).get())
commit()
}
}
})
}
private fun restorePreferences(viewModel: IntervalTimerViewModel) {
val sharedPref =
getSharedPreferences(SHARED_PREFS_KEY, Context.MODE_PRIVATE) ?: return
val timePerWorkSetKey = getString(R.string.prefs_timePerWorkSet)
var wasAnythingRestored = false
if (sharedPref.contains(timePerWorkSetKey)) {
viewModel.timePerWorkSet.set(sharedPref.getInt(timePerWorkSetKey, 100))
wasAnythingRestored = true
}
val timePerRestSetKey = getString(R.string.prefs_timePerRestSet)
if (sharedPref.contains(timePerRestSetKey)) {
viewModel.timePerRestSet.set(sharedPref.getInt(timePerRestSetKey, 50))
wasAnythingRestored = true
}
val numberOfSetsKey = getString(R.string.prefs_numberOfSets)
if (sharedPref.contains(numberOfSetsKey)) {
viewModel.numberOfSets = arrayOf(0, sharedPref.getInt(numberOfSetsKey, 5))
wasAnythingRestored = true
}
if (wasAnythingRestored) Log.d("saveTimePerWorkSet", "Preferences restored")
viewModel.stopButtonClicked()
}
private fun observeAndSaveNumberOfSets(viewModel: IntervalTimerViewModel) {
viewModel.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() {
@SuppressLint("CommitPrefEdits")
override fun onPropertyChanged(observable: Observable?, p1: Int) {
if (p1 == BR.numberOfSets) {
Log.d("saveTimePerWorkSet", "Saving number of sets preference")
val sharedPref =
getSharedPreferences(SHARED_PREFS_KEY, Context.MODE_PRIVATE) ?: return
sharedPref.edit().apply {
putInt(getString(R.string.prefs_numberOfSets), viewModel.numberOfSets[1])
commit()
}
}
}
})
}
}
| apache-2.0 | ebc239933214ddeee77d4bd917dd0a67 | 41.961832 | 100 | 0.683191 | 5.240223 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/adapter/StatusDetailsAdapter.kt | 1 | 20962 | /*
* 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.adapter
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.util.SparseBooleanArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Space
import android.widget.TextView
import org.mariotaku.kpreferences.get
import org.mariotaku.ktextension.contains
import de.vanita5.microblog.library.twitter.model.TranslationResult
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.adapter.iface.IGapSupportedAdapter
import de.vanita5.twittnuker.adapter.iface.IItemCountsAdapter
import de.vanita5.twittnuker.adapter.iface.ILoadMoreSupportAdapter
import de.vanita5.twittnuker.adapter.iface.IStatusesAdapter
import de.vanita5.twittnuker.constant.*
import de.vanita5.twittnuker.extension.model.originalId
import de.vanita5.twittnuker.extension.model.retweet_sort_id
import de.vanita5.twittnuker.fragment.status.StatusFragment
import de.vanita5.twittnuker.model.*
import de.vanita5.twittnuker.util.StatusAdapterLinkClickHandler
import de.vanita5.twittnuker.util.ThemeUtils
import de.vanita5.twittnuker.util.TwidereLinkify
import de.vanita5.twittnuker.view.holder.EmptyViewHolder
import de.vanita5.twittnuker.view.holder.LoadIndicatorViewHolder
import de.vanita5.twittnuker.view.holder.iface.IStatusViewHolder
import de.vanita5.twittnuker.view.holder.status.DetailStatusViewHolder
class StatusDetailsAdapter(
val fragment: StatusFragment
) : LoadMoreSupportAdapter<RecyclerView.ViewHolder>(fragment.context, fragment.requestManager),
IStatusesAdapter<List<ParcelableStatus>>, IItemCountsAdapter {
override val twidereLinkify: TwidereLinkify
override var statusClickListener: IStatusViewHolder.StatusClickListener? = null
override val itemCounts = ItemCounts(ITEM_TYPES_SUM)
override val nameFirst = preferences[nameFirstKey]
override val mediaPreviewStyle = preferences[mediaPreviewStyleKey]
override val linkHighlightingStyle = preferences[linkHighlightOptionKey]
override val lightFont = preferences[lightFontKey]
override val mediaPreviewEnabled = preferences[mediaPreviewKey]
override val sensitiveContentEnabled = preferences[displaySensitiveContentsKey]
override val useStarsForLikes = preferences[iWantMyStarsBackKey]
private val inflater: LayoutInflater
private val cardBackgroundColor: Int
private val showCardActions = !preferences[hideCardActionsKey]
private var recyclerView: RecyclerView? = null
private var detailMediaExpanded: Boolean = false
var status: ParcelableStatus? = null
internal set
var translationResult: TranslationResult? = null
internal set(translation) {
if (translation == null || status?.originalId != translation.id) {
field = null
} else {
field = translation
}
notifyDataSetChanged()
}
var statusActivity: StatusFragment.StatusActivity? = null
internal set(value) {
val status = status ?: return
if (value != null && !value.isStatus(status)) {
return
}
field = value
val statusIndex = getIndexStart(ITEM_IDX_STATUS)
notifyItemChanged(statusIndex, value)
}
var statusAccount: AccountDetails? = null
internal set
private var data: List<ParcelableStatus>? = null
private var replyError: CharSequence? = null
private var conversationError: CharSequence? = null
private var replyStart: Int = 0
private var showingActionCardPosition = RecyclerView.NO_POSITION
private val showingFullTextStates = SparseBooleanArray()
init {
setHasStableIds(true)
val context = fragment.activity
// There's always a space at the end of the list
itemCounts[ITEM_IDX_SPACE] = 1
itemCounts[ITEM_IDX_STATUS] = 1
itemCounts[ITEM_IDX_CONVERSATION_LOAD_MORE] = 1
itemCounts[ITEM_IDX_REPLY_LOAD_MORE] = 1
inflater = LayoutInflater.from(context)
cardBackgroundColor = ThemeUtils.getCardBackgroundColor(context,
preferences[themeBackgroundOptionKey], preferences[themeBackgroundAlphaKey])
val listener = StatusAdapterLinkClickHandler<List<ParcelableStatus>>(context, preferences)
listener.setAdapter(this)
twidereLinkify = TwidereLinkify(listener)
}
override fun getStatus(position: Int, raw: Boolean): ParcelableStatus {
when (getItemCountIndex(position, raw)) {
ITEM_IDX_CONVERSATION -> {
var idx = position - getIndexStart(ITEM_IDX_CONVERSATION)
if (data!![idx].is_filtered) idx++
return data!![idx]
}
ITEM_IDX_REPLY -> {
var idx = position - getIndexStart(ITEM_IDX_CONVERSATION) -
getTypeCount(ITEM_IDX_CONVERSATION) - getTypeCount(ITEM_IDX_STATUS) +
replyStart
if (data!![idx].is_filtered) idx++
return data!![idx]
}
ITEM_IDX_STATUS -> {
return status!!
}
}
throw IndexOutOfBoundsException("index: $position")
}
fun getIndexStart(index: Int): Int {
if (index == 0) return 0
return itemCounts.getItemStartPosition(index)
}
override fun getStatusId(position: Int, raw: Boolean): String {
return getStatus(position, raw).id
}
override fun getStatusTimestamp(position: Int, raw: Boolean): Long {
return getStatus(position, raw).timestamp
}
override fun getStatusPositionKey(position: Int, raw: Boolean): Long {
val status = getStatus(position, raw)
return if (status.position_key > 0) status.timestamp else getStatusTimestamp(position, raw)
}
override fun getAccountKey(position: Int, raw: Boolean) = getStatus(position, raw).account_key
override fun findStatusById(accountKey: UserKey, statusId: String): ParcelableStatus? {
if (status != null && accountKey == status!!.account_key && TextUtils.equals(statusId, status!!.id)) {
return status
}
return data?.firstOrNull { accountKey == it.account_key && TextUtils.equals(it.id, statusId) }
}
override fun getStatusCount(raw: Boolean): Int {
return getTypeCount(ITEM_IDX_CONVERSATION) + getTypeCount(ITEM_IDX_STATUS) + getTypeCount(ITEM_IDX_REPLY)
}
override fun isCardActionsShown(position: Int): Boolean {
if (position == RecyclerView.NO_POSITION) return showCardActions
return showCardActions || showingActionCardPosition == position
}
override fun showCardActions(position: Int) {
if (showingActionCardPosition != RecyclerView.NO_POSITION) {
notifyItemChanged(showingActionCardPosition)
}
showingActionCardPosition = position
if (position != RecyclerView.NO_POSITION) {
notifyItemChanged(position)
}
}
override fun isFullTextVisible(position: Int): Boolean {
return showingFullTextStates.get(position)
}
override fun setFullTextVisible(position: Int, visible: Boolean) {
showingFullTextStates.put(position, visible)
if (position != RecyclerView.NO_POSITION) {
notifyItemChanged(position)
}
}
override fun setData(data: List<ParcelableStatus>?): Boolean {
val status = this.status ?: return false
val changed = this.data != data
this.data = data
if (data == null || data.isEmpty()) {
setTypeCount(ITEM_IDX_CONVERSATION, 0)
setTypeCount(ITEM_IDX_REPLY, 0)
replyStart = -1
} else {
val sortId = if (status.is_retweet) {
status.retweet_sort_id
} else {
status.sort_id
}
var conversationCount = 0
var replyCount = 0
var replyStart = -1
data.forEachIndexed { i, item ->
if (item.sort_id < sortId) {
if (!item.is_filtered) {
conversationCount++
}
} else if (status.id == item.id) {
this.status = item
} else if (item.sort_id > sortId) {
if (replyStart < 0) {
replyStart = i
}
if (!item.is_filtered) {
replyCount++
}
}
}
setTypeCount(ITEM_IDX_CONVERSATION, conversationCount)
setTypeCount(ITEM_IDX_REPLY, replyCount)
this.replyStart = replyStart
}
notifyDataSetChanged()
updateItemDecoration()
return changed
}
override val showAccountsColor: Boolean
get() = false
var isDetailMediaExpanded: Boolean
get() {
if (detailMediaExpanded) return true
if (mediaPreviewEnabled) {
val status = this.status
return status != null && (sensitiveContentEnabled || !status.is_possibly_sensitive)
}
return false
}
set(expanded) {
detailMediaExpanded = expanded
notifyDataSetChanged()
updateItemDecoration()
}
override fun isGapItem(position: Int): Boolean {
return false
}
override val gapClickListener: IGapSupportedAdapter.GapClickListener?
get() = statusClickListener
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder? {
when (viewType) {
VIEW_TYPE_DETAIL_STATUS -> {
val view = inflater.inflate(R.layout.header_status, parent, false)
view.setBackgroundColor(cardBackgroundColor)
return DetailStatusViewHolder(this, view)
}
VIEW_TYPE_LIST_STATUS -> {
return ListParcelableStatusesAdapter.createStatusViewHolder(this, inflater, parent)
}
VIEW_TYPE_CONVERSATION_LOAD_INDICATOR, VIEW_TYPE_REPLIES_LOAD_INDICATOR -> {
val view = inflater.inflate(R.layout.list_item_load_indicator, parent,
false)
return LoadIndicatorViewHolder(view)
}
VIEW_TYPE_SPACE -> {
return EmptyViewHolder(Space(context))
}
VIEW_TYPE_REPLY_ERROR -> {
val view = inflater.inflate(R.layout.adapter_item_status_error, parent,
false)
return StatusErrorItemViewHolder(view)
}
}
return null
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int, payloads: List<Any>) {
var handled = false
when (holder.itemViewType) {
VIEW_TYPE_DETAIL_STATUS -> {
holder as DetailStatusViewHolder
payloads.forEach { it ->
when (it) {
is StatusFragment.StatusActivity -> {
holder.updateStatusActivity(it)
}
is ParcelableStatus -> {
holder.displayStatus(statusAccount, status, statusActivity,
translationResult)
}
}
handled = true
}
}
}
if (handled) return
super.onBindViewHolder(holder, position, payloads)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder.itemViewType) {
VIEW_TYPE_DETAIL_STATUS -> {
val status = getStatus(position)
val detailHolder = holder as DetailStatusViewHolder
detailHolder.displayStatus(statusAccount, status, statusActivity, translationResult)
}
VIEW_TYPE_LIST_STATUS -> {
val status = getStatus(position)
val statusHolder = holder as IStatusViewHolder
// Display 'in reply to' for first item
// useful to indicate whether first tweet has reply or not
// We only display that indicator for first conversation item
val itemType = getItemType(position)
val displayInReplyTo = itemType == ITEM_IDX_CONVERSATION && position - getItemTypeStart(position) == 0
statusHolder.display(status = status, displayInReplyTo = displayInReplyTo)
}
VIEW_TYPE_REPLY_ERROR -> {
val errorHolder = holder as StatusErrorItemViewHolder
errorHolder.showError(replyError!!)
}
VIEW_TYPE_CONVERSATION_ERROR -> {
val errorHolder = holder as StatusErrorItemViewHolder
errorHolder.showError(conversationError!!)
}
VIEW_TYPE_CONVERSATION_LOAD_INDICATOR -> {
val indicatorHolder = holder as LoadIndicatorViewHolder
indicatorHolder.setLoadProgressVisible(isConversationsLoading)
}
VIEW_TYPE_REPLIES_LOAD_INDICATOR -> {
val indicatorHolder = holder as LoadIndicatorViewHolder
indicatorHolder.setLoadProgressVisible(isRepliesLoading)
}
}
}
override fun getItemViewType(position: Int): Int {
return getItemViewTypeByItemType(getItemType(position))
}
override fun addGapLoadingId(id: ObjectId) {
}
override fun removeGapLoadingId(id: ObjectId) {
}
private fun getItemViewTypeByItemType(type: Int): Int {
when (type) {
ITEM_IDX_CONVERSATION, ITEM_IDX_REPLY -> return VIEW_TYPE_LIST_STATUS
ITEM_IDX_CONVERSATION_LOAD_MORE -> return VIEW_TYPE_CONVERSATION_LOAD_INDICATOR
ITEM_IDX_REPLY_LOAD_MORE -> return VIEW_TYPE_REPLIES_LOAD_INDICATOR
ITEM_IDX_STATUS -> return VIEW_TYPE_DETAIL_STATUS
ITEM_IDX_SPACE -> return VIEW_TYPE_SPACE
ITEM_IDX_REPLY_ERROR -> return VIEW_TYPE_REPLY_ERROR
ITEM_IDX_CONVERSATION_ERROR -> return VIEW_TYPE_CONVERSATION_ERROR
}
throw IllegalStateException()
}
private fun getItemCountIndex(position: Int, raw: Boolean): Int {
return itemCounts.getItemCountIndex(position)
}
fun getItemType(position: Int): Int {
var typeStart = 0
for (type in 0 until ITEM_TYPES_SUM) {
val typeCount = getTypeCount(type)
val typeEnd = typeStart + typeCount
if (position in typeStart until typeEnd) return type
typeStart = typeEnd
}
throw IllegalStateException("Unknown position " + position)
}
fun getItemTypeStart(position: Int): Int {
var typeStart = 0
for (type in 0 until ITEM_TYPES_SUM) {
val typeCount = getTypeCount(type)
val typeEnd = typeStart + typeCount
if (position in typeStart until typeEnd) return typeStart
typeStart = typeEnd
}
throw IllegalStateException()
}
override fun getItemId(position: Int): Long {
val countIndex = getItemCountIndex(position)
when (countIndex) {
ITEM_IDX_CONVERSATION, ITEM_IDX_STATUS, ITEM_IDX_REPLY -> {
val status = getStatus(position)
val hashCode = ParcelableStatus.calculateHashCode(status.account_key, status.id)
return (countIndex.toLong() shl 32) or hashCode.toLong()
}
}
val countPos = (position - getItemStartPosition(countIndex)).toLong()
return (countIndex.toLong() shl 32) or countPos
}
override fun getItemCount(): Int {
if (status == null) return 0
return itemCounts.itemCount
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView?) {
super.onAttachedToRecyclerView(recyclerView)
this.recyclerView = recyclerView
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView?) {
super.onDetachedFromRecyclerView(recyclerView)
this.recyclerView = null
}
private fun setTypeCount(idx: Int, size: Int) {
itemCounts[idx] = size
notifyDataSetChanged()
}
fun getTypeCount(idx: Int): Int {
return itemCounts[idx]
}
fun setReplyError(error: CharSequence?) {
replyError = error
setTypeCount(ITEM_IDX_REPLY_ERROR, if (error != null) 1 else 0)
updateItemDecoration()
}
fun setConversationError(error: CharSequence?) {
conversationError = error
setTypeCount(ITEM_IDX_CONVERSATION_ERROR, if (error != null) 1 else 0)
updateItemDecoration()
}
fun setStatus(status: ParcelableStatus, account: AccountDetails?): Boolean {
val oldStatus = this.status
val oldAccount = this.statusAccount
val changed = oldStatus != status && oldAccount != account
this.status = status
this.statusAccount = account
if (changed) {
notifyDataSetChanged()
updateItemDecoration()
} else {
val statusIndex = getIndexStart(ITEM_IDX_STATUS)
notifyItemChanged(statusIndex, status)
}
return changed
}
fun updateItemDecoration() {
if (recyclerView == null) return
}
fun getFirstPositionOfItem(itemIdx: Int): Int {
var position = 0
for (i in 0 until ITEM_TYPES_SUM) {
if (itemIdx == i) return position
position += getTypeCount(i)
}
return RecyclerView.NO_POSITION
}
fun getData(): List<ParcelableStatus>? {
return data
}
var isConversationsLoading: Boolean
get() = ILoadMoreSupportAdapter.START in loadMoreIndicatorPosition
set(loading) {
if (loading) {
loadMoreIndicatorPosition = loadMoreIndicatorPosition or ILoadMoreSupportAdapter.START
} else {
loadMoreIndicatorPosition = loadMoreIndicatorPosition and ILoadMoreSupportAdapter.START.inv()
}
updateItemDecoration()
}
var isRepliesLoading: Boolean
get() = ILoadMoreSupportAdapter.END in loadMoreIndicatorPosition
set(loading) {
if (loading) {
loadMoreIndicatorPosition = loadMoreIndicatorPosition or ILoadMoreSupportAdapter.END
} else {
loadMoreIndicatorPosition = loadMoreIndicatorPosition and ILoadMoreSupportAdapter.END.inv()
}
updateItemDecoration()
}
class StatusErrorItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val textView = itemView.findViewById<TextView>(android.R.id.text1)
init {
textView.movementMethod = LinkMovementMethod.getInstance()
textView.linksClickable = true
}
fun showError(text: CharSequence) {
textView.text = text
}
}
companion object {
const val VIEW_TYPE_LIST_STATUS = 0
const val VIEW_TYPE_DETAIL_STATUS = 1
const val VIEW_TYPE_CONVERSATION_LOAD_INDICATOR = 2
const val VIEW_TYPE_REPLIES_LOAD_INDICATOR = 3
const val VIEW_TYPE_REPLY_ERROR = 4
const val VIEW_TYPE_CONVERSATION_ERROR = 5
const val VIEW_TYPE_SPACE = 6
const val VIEW_TYPE_EMPTY = 7
const val ITEM_IDX_CONVERSATION_LOAD_MORE = 0
const val ITEM_IDX_CONVERSATION_ERROR = 1
const val ITEM_IDX_CONVERSATION = 2
const val ITEM_IDX_STATUS = 3
const val ITEM_IDX_REPLY = 4
const val ITEM_IDX_REPLY_ERROR = 5
const val ITEM_IDX_REPLY_LOAD_MORE = 6
const val ITEM_IDX_SPACE = 7
const val ITEM_TYPES_SUM = 8
}
} | gpl-3.0 | b113578fd3183917e910b8748a0ea8ae | 37.114545 | 118 | 0.631237 | 5.065732 | false | false | false | false |
bl-lia/kktAPK | app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/transform/AvatarTransformation.kt | 1 | 1721 | package com.bl_lia.kirakiratter.presentation.transform
import android.content.Context
import android.graphics.*
import android.os.Build
import android.support.annotation.ColorRes
import android.support.v4.content.ContextCompat
import com.squareup.picasso.Transformation
class AvatarTransformation(val context: Context, @ColorRes val borderColor: Int) : Transformation {
override fun key(): String = "avatar"
override fun transform(source: Bitmap?): Bitmap? {
if (source == null) return source
if (Build.VERSION.SDK_INT < 21) return source
val size = Math.min(source.width, source.height)
val x = (source.width - size) / 2
val y = (source.height - size) / 2
val squareBitmap = Bitmap.createBitmap(source, x, y, size, size)
if (squareBitmap != source) {
source.recycle()
}
val config = source.config ?: Bitmap.Config.ARGB_8888
val bitmap = Bitmap.createBitmap(size, size, config)
val canvas = Canvas(bitmap)
val paint = Paint()
val shader = BitmapShader(squareBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
paint.shader = shader
paint.isAntiAlias = true
val borader: Int = 5
val r: Float = 10F
val paintBg = Paint().apply {
color = ContextCompat.getColor(context, borderColor)
isAntiAlias = true
}
canvas.drawRoundRect(x.toFloat(), y.toFloat(), size.toFloat(), size.toFloat(), r, r, paintBg)
canvas.drawRoundRect((x + borader).toFloat(), (y + borader).toFloat(), (size - borader).toFloat(), (size - borader).toFloat(), r, r, paint)
squareBitmap.recycle()
return bitmap
}
} | mit | 3609dee145459b8b0a48d9894b8e4707 | 33.44 | 147 | 0.647879 | 4.218137 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.