repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ebean-orm-examples/example-kotlin-web
|
src/main/java/org/example/web/api/BaseResource.kt
|
1
|
6166
|
package org.example.web.api
import com.avaje.ebean.EbeanServer
import com.avaje.ebean.Query
import com.avaje.ebean.text.json.JsonContext
import com.avaje.ebean.text.json.JsonWriteOptions
import org.example.web.BeanValidationException
import org.slf4j.LoggerFactory
import javax.inject.Inject
import javax.ws.rs.Consumes
import javax.ws.rs.DELETE
import javax.ws.rs.GET
import javax.ws.rs.POST
import javax.ws.rs.PUT
import javax.ws.rs.Path
import javax.ws.rs.PathParam
import javax.ws.rs.Produces
import javax.ws.rs.core.Context
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
import javax.ws.rs.core.UriInfo
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
abstract class BaseResource<T> {
protected val server: EbeanServer
protected val beanType: Class<T>
protected var log = LoggerFactory.getLogger(javaClass)
protected val jsonContext: JsonContext
protected var updateReturnProperties = "id,whenUpdated,version"
@Inject
constructor(server: EbeanServer, beanType: Class<T>) {
this.server = server;
this.beanType = beanType;
this.jsonContext = server.json()
}
@GET
open fun all(): List<T> {
val query = server.find(beanType).order().asc("id")
return query.findList()
}
@GET
@Path("/{id}")
open fun getById(@PathParam("id") id: String): T? {
val query = server.find(beanType).setId(id)//.select("*")
applyGetByIdPredicates(query)
return query.findUnique()
}
/**
* Apply predicates and order by clauses to the query as necessary.
*/
protected fun applyGetByIdPredicates(query: Query<T>) {
}
protected fun sanitiseBean(bean: T) {
}
protected fun validateBean(bean: T) {
}
@POST
open fun insert(@Context uriInfo: UriInfo, bean: T): Response {
try {
validateBean(bean);
sanitiseBean(bean)
server.save(bean)
val id = server.getBeanId(bean)
val ub = uriInfo.absolutePathBuilder
val createdUri = ub.path("" + id).build()
postInsert(bean)
return Response.created(createdUri).entity(bean).build()
} catch (e: BeanValidationException) {
log.info("validation errors " + e)
return Response.ok("TODO: BeanValidationException").build()
}
}
/**
* Override to lookup important related objects.
*/
protected fun postInsert(bean: T) {
}
@PUT
@Path("/{id}")
open fun update(@PathParam("id") id: String, bean: T): Response {
try {
validateBean(bean);
sanitiseBean(bean)
server.setBeanId(bean, id)
server.update(bean)
postUpdate(bean)
val beanUpdateOptions = JsonWriteOptions.parsePath("($updateReturnProperties)")
val json = jsonContext.toJson(bean, beanUpdateOptions)
return Response.ok(json).build()
} catch (e: BeanValidationException) {
log.info("validation errors " + e)
return Response.ok("TODO: BeanValidationException").build()
}
}
/**
* Override to lookup important related objects etc.
*/
protected fun postUpdate(bean: T) {
}
/**
* Delete just using the Id. Note that this doesn't take into account
* optimistic locking.
*
*
* Also consume Application/XML as AngularJS will send that for some browsers.
*
*/
@Consumes(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
@DELETE
@Path("/{id}")
fun delete(@PathParam("id") id: String): Response {
return performDelete(id)
}
/**
* Delete using a POST to get around issues with AngularJS sending the wrong
* content type.
*/
@POST
@Path("/{id}/delete")
fun deletePath(@PathParam("id") id: String): Response {
return performDelete(id)
}
protected fun performDelete(id: String): Response {
server.delete(beanType, id)
return Response.ok().build()
}
// @Path("/query")
// @POST
// @Produces({ MediaType.APPLICATION_JSON })
// public String query(QueryRequest queryRequest) {
//
// QueryResponse<T> fetchData = fetchData(queryRequest);
//
// JsonWriteOptions writeOptions = null;// JsonWriteOptions.parsePath("(success,pageIndex,pageSize,list(*))");
// String val = jsonContext.toJson(fetchData, writeOptions);
//
// // String val = jacksonService.serialise(fetchData);
// return val;
// }
//
// /**
// * Apply predicates and order by clauses to the query as necessary.
// */
// protected void applyPredicates(QueryRequest request, Query<T> query) {
// if(request.getPredicate("order") != null){
// query.orderBy(request.getPredicate("order"));
// }
// }
//
// /**
// * Fetch the data based on the paging information.
// */
// public QueryResponse<T> fetchData(QueryRequest request) {
//
// log.info("process query request for {}", beanType);
// Query<T> query = server.find(beanType);
// if (request.hasPaging()) {
// query.setFirstRow(request.getFirstRow());
// query.setMaxRows(request.getPageSize());
// }
//
// // Apply predicates and Order by clause to the query
// applyPredicates(request, query);
//
// Future<Integer> rowCount = null;
// if (request.getPageSize() > 0 && request.getPageIndex() == 0) {
// rowCount = query.findFutureRowCount();
// }
//
// List<T> list = query.findList();
//
// return buildResponse(request, list, rowCount);
// }
//
// protected QueryResponse<T> buildResponse(QueryRequest request, List<T> list, Future<Integer> rowCount) {
//
// @SuppressWarnings("unchecked")
// boolean hasNext = ((BeanCollection<User>) list).hasMoreRows();
//
// QueryResponse<T> response = new QueryResponse<T>();
// response.setList(list);
// response.setPageIndex(request.getPageIndex());
// response.setPageSize(request.getPageSize());
// response.setMore(hasNext);
//
// if (rowCount != null) {
// try {
// response.setTotalCount(rowCount.get(60, TimeUnit.SECONDS));
// } catch (Exception e) {
// log.error("Error trying to fetch total Row count", e);
// }
// }
//
// return response;
// }
}
|
apache-2.0
|
116b4d3ae8824d5158ce8211acf3c3da
| 25.238298 | 115 | 0.650989 | 3.808524 | false | false | false | false |
sargunster/Klap
|
src/main/kotlin/me/sargunvohra/lib/klap/internal/KlapGrammar.kt
|
1
|
966
|
package me.sargunvohra.lib.klap.internal
import me.sargunvohra.lib.cakeparse.api.*
internal object KlapGrammar {
// TODO allow token with no pattern in CakeParse
private const val regexMatchNothing = "(?!)"
val longFlag = token("flag", regexMatchNothing)
val shortFlag = token("shortFlag", regexMatchNothing)
val word = token("word", regexMatchNothing)
val flags = (longFlag map {
listOf(it.raw)
}) or (shortFlag map {
it.raw.map { it.toString() }
})
val wordVal = word map {
it.raw
}
val flagArg = flags map {
Arg.FlagArgs(keys = it)
}
val wordArg = wordVal map {
Arg.WordArgs(values = listOf(it))
}
val valueArg = flags and wordVal map {
Arg.ValueArgs(
pair = it.first.last() to it.second,
extraFlags = Arg.FlagArgs(it.first.dropLast(1))
)
}
val goal = zeroOrMore(valueArg or flagArg or wordArg)
}
|
apache-2.0
|
40a20b3d88f17021dc10baed137ba66f
| 22.585366 | 63 | 0.60766 | 3.758755 | false | false | false | false |
Kotlin/anko
|
anko/library/generator/src/org/jetbrains/android/anko/generator/dslElements.kt
|
4
|
2309
|
/*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko.generator
import org.jetbrains.android.anko.utils.MethodNodeWithClass
import org.jetbrains.android.anko.utils.fqName
import org.jetbrains.android.anko.utils.simpleName
import org.objectweb.asm.Type
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.MethodNode
class ViewElement(val clazz: ClassNode, val isContainer: Boolean, allMethods: () -> List<MethodNode>) {
val allMethods: List<MethodNode> by lazy {
allMethods()
}
val fqName: String
get() = clazz.fqName
}
class LayoutElement(val layout: ClassNode, val layoutParams: ClassNode, val constructors: List<MethodNode>)
class ServiceElement(val service: ClassNode, val constantName: String) {
val simpleName: String
get() = service.simpleName.decapitalize()
val fqName: String
get() = service.fqName
}
class PropertyElement(val name: String, val getter: MethodNodeWithClass?, val setters: List<MethodNodeWithClass>)
class ListenerMethod(val methodWithClass: MethodNodeWithClass, val name: String, val returnType: Type)
abstract class ListenerElement(val setter: MethodNodeWithClass, val clazz: ClassNode) {
abstract val id: String
}
class SimpleListenerElement(
setter: MethodNodeWithClass,
clazz: ClassNode,
val method: ListenerMethod
) : ListenerElement(setter, clazz) {
override val id: String
get() = "${clazz.name}#${method.name}"
}
class ComplexListenerElement(
setter: MethodNodeWithClass,
clazz: ClassNode,
val name: String,
val methods: List<ListenerMethod>
) : ListenerElement(setter, clazz) {
override val id: String
get() = "${clazz.name}#$name"
}
|
apache-2.0
|
f7c932630613465d438b991ce5a1c973
| 32 | 113 | 0.730186 | 4.315888 | false | false | false | false |
Cardstock/Cardstock
|
src/main/kotlin/xyz/cardstock/cardstock/players/hands/PlayerHand.kt
|
1
|
1253
|
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package xyz.cardstock.cardstock.players.hands
import com.google.common.collect.Lists
import xyz.cardstock.cardstock.cards.Card
import java.util.Collections
import java.util.Objects
/**
* A hand designed to be held by a [Player][xyz.cardstock.cardstock.players.Player].
*/
open class PlayerHand<T : Card> : Hand<T> {
private val _cards: MutableList<T> = Lists.newArrayList()
override val cards: List<T>
get() = Collections.unmodifiableList(this._cards)
operator override fun get(index: Int) = this._cards[index]
override fun size() = this._cards.size
override fun add(card: T) {
this._cards.add(card)
}
override fun remove(card: T) {
this._cards.remove(card)
}
override fun remove(index: Int) {
this._cards.removeAt(index)
}
override fun iterator() = this._cards.iterator()
override fun equals(other: Any?) = if (other == null || other !is PlayerHand<*>) false else this._cards == other._cards
override fun hashCode() = Objects.hash(this._cards)
}
|
mpl-2.0
|
a020ccf552a28f2a82b48aeda35ea5fd
| 28.139535 | 123 | 0.676776 | 3.696165 | false | false | false | false |
LorittaBot/Loritta
|
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/utils/TranslateExecutor.kt
|
1
|
5290
|
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils
import net.perfectdreams.discordinteraktions.common.autocomplete.FocusedCommandOption
import net.perfectdreams.discordinteraktions.common.builder.message.embed
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
import net.perfectdreams.i18nhelper.core.keydata.StringI18nData
import net.perfectdreams.i18nhelper.core.keys.StringI18nKey
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.autocomplete.AutocompleteContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.styled
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.declarations.TranslateCommand
import net.perfectdreams.loritta.cinnamon.discord.utils.google.HackyGoogleTranslateClient
import net.perfectdreams.loritta.cinnamon.discord.utils.google.Language
import net.perfectdreams.loritta.cinnamon.discord.utils.toKordColor
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.i18n.I18nKeysData
import net.perfectdreams.loritta.common.utils.LorittaColors
import net.perfectdreams.loritta.common.utils.text.TextUtils
class TranslateExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) {
val cinnamonAutocomplete: (AutocompleteContext, FocusedCommandOption, Boolean) -> (Map<String, String>) = { autocompleteContext, focusedCommandOption, includeAuto ->
val value = focusedCommandOption.value
Language.values()
.asSequence()
.filter {
if (!includeAuto) it != Language.AUTO_DETECT else true
}
.filter {
autocompleteContext.i18nContext.get(it.languageNameI18nKey).startsWith(value, true)
}
.take(25)
.associate {
autocompleteContext.i18nContext.get(TranslateCommand.I18N_PREFIX.LanguageFormat(it.languageNameI18nKey, it.code)) to it.code
}
}
inner class Options : LocalizedApplicationCommandOptions(loritta) {
val from = string("from", TranslateCommand.I18N_PREFIX.Options.From.Text) {
cinnamonAutocomplete { autocompleteContext, focusedCommandOption ->
cinnamonAutocomplete.invoke(autocompleteContext, focusedCommandOption, true)
}
}
val to = string("to", TranslateCommand.I18N_PREFIX.Options.To.Text) {
cinnamonAutocomplete { autocompleteContext, focusedCommandOption ->
cinnamonAutocomplete.invoke(autocompleteContext, focusedCommandOption, false)
}
}
val text = string("text", TranslateCommand.I18N_PREFIX.Options.Text.Text)
}
override val options = Options()
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
val from = try {
Language.fromLanguageCode(args[options.from])
} catch (e: NoSuchElementException) {
context.failEphemerally {
styled(
context.i18nContext.get(TranslateCommand.I18N_PREFIX.InvalidLanguage),
Emotes.LoriSob
)
}
}
val to = try {
Language.fromLanguageCode(args[options.to])
} catch (e: NoSuchElementException) {
context.failEphemerally {
styled(
context.i18nContext.get(TranslateCommand.I18N_PREFIX.InvalidLanguage),
Emotes.LoriSob
)
}
}
if (to == Language.AUTO_DETECT) {
context.failEphemerally {
styled(
context.i18nContext.get(TranslateCommand.I18N_PREFIX.InvalidLanguage),
Emotes.LoriSob
)
}
}
if (from == to) {
context.failEphemerally {
styled(
context.i18nContext.get(TranslateCommand.I18N_PREFIX.TranslatingFromToSameLanguage),
Emotes.LoriHmpf
)
}
}
val input = args[options.text]
val translated = loritta.googleTranslateClient.translate(from, to, input)
?: context.failEphemerally {
styled(
context.i18nContext.get(TranslateCommand.I18N_PREFIX.TranslationFailed),
Emotes.LoriSob
)
}
context.sendMessage {
embed {
title = "${Emotes.Map} ${context.i18nContext.get(I18nKeysData.Commands.Command.Translate.TranslatedFromLanguageToLanguage(translated.sourceLanguage.languageNameI18nKey, to.languageNameI18nKey))}"
description = translated.output
// TODO: Maybe another color?
color = LorittaColors.LorittaAqua.toKordColor()
}
}
}
}
|
agpl-3.0
|
4b234e251782f135708ad69d829d667c
| 43.462185 | 211 | 0.675992 | 5.160976 | false | false | false | false |
Blankj/AndroidUtilCode
|
feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/screen/ScreenActivity.kt
|
1
|
4044
|
package com.blankj.utilcode.pkg.feature.screen
import android.content.Context
import android.content.Intent
import android.os.Build
import android.widget.ImageView
import android.widget.TextView
import com.blankj.common.activity.CommonActivity
import com.blankj.common.item.CommonItem
import com.blankj.common.item.CommonItemClick
import com.blankj.common.item.CommonItemSwitch
import com.blankj.common.item.CommonItemTitle
import com.blankj.utilcode.pkg.R
import com.blankj.utilcode.pkg.helper.DialogHelper
import com.blankj.utilcode.util.*
/**
* ```
* author: Blankj
* blog : http://blankj.com
* time : 2019/01/29
* desc : demo about RomUtils
* ```
*/
class ScreenActivity : CommonActivity() {
companion object {
fun start(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PermissionUtils.requestWriteSettings(object : PermissionUtils.SimpleCallback {
override fun onGranted() {
val starter = Intent(context, ScreenActivity::class.java)
context.startActivity(starter)
}
override fun onDenied() {
ToastUtils.showLong("No permission of write settings.")
}
})
} else {
val starter = Intent(context, ScreenActivity::class.java)
context.startActivity(starter)
}
}
}
override fun bindTitleRes(): Int {
return R.string.demo_screen
}
override fun bindItems(): MutableList<CommonItem<*>> {
return CollectionUtils.newArrayList(
CommonItemTitle("getScreenWidth", ScreenUtils.getScreenWidth().toString()),
CommonItemTitle("getScreenHeight", ScreenUtils.getScreenHeight().toString()),
CommonItemTitle("getAppScreenWidth", ScreenUtils.getAppScreenWidth().toString()),
CommonItemTitle("getAppScreenHeight", ScreenUtils.getAppScreenHeight().toString()),
CommonItemTitle("getScreenDensity", ScreenUtils.getScreenDensity().toString()),
CommonItemTitle("getScreenDensityDpi", ScreenUtils.getScreenDensityDpi().toString()),
CommonItemTitle("getScreenRotation", ScreenUtils.getScreenRotation(this).toString()),
CommonItemTitle("isScreenLock", ScreenUtils.isScreenLock().toString()),
CommonItemTitle("getSleepDuration", ScreenUtils.getSleepDuration().toString()),
CommonItemSwitch(
"isFullScreen",
{ ScreenUtils.isFullScreen(this) },
{
if (it) {
ScreenUtils.setFullScreen(this)
BarUtils.setStatusBarVisibility(this, false)
} else {
ScreenUtils.setNonFullScreen(this)
BarUtils.setStatusBarVisibility(this, true)
}
}
),
CommonItemSwitch(
"isLandscape",
{ ScreenUtils.isLandscape() },
{
if (it) {
ScreenUtils.setLandscape(this)
} else {
ScreenUtils.setPortrait(this)
}
}
),
CommonItemClick(R.string.screen_screenshot) {
val iv :ImageView = ImageView(this)
iv.setImageResource(R.mipmap.ic_launcher)
val tv: TextView = TextView(this)
tv.setText("wowowowwowo")
DialogHelper.showScreenshotDialog(ImageUtils.view2Bitmap(tv))
// DialogHelper.showScreenshotDialog(ScreenUtils.screenShot(this))
}
)
}
}
|
apache-2.0
|
5d8f7f54cd5110cfc9b017b78774864c
| 39.039604 | 101 | 0.550445 | 5.852388 | false | false | false | false |
Nagarajj/orca
|
orca-queue-sqs/src/main/kotlin/com/netflix/spinnaker/config/SqsQueueConfiguration.kt
|
1
|
2107
|
/*
* Copyright 2017 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.config
import com.amazonaws.auth.AWSCredentialsProvider
import com.amazonaws.services.sqs.AmazonSQS
import com.amazonaws.services.sqs.AmazonSQSClient
import com.netflix.spinnaker.clouddriver.aws.bastion.BastionConfig
import com.netflix.spinnaker.orca.q.amazon.SqsQueue
import com.netflix.spinnaker.orca.q.handler.DeadMessageHandler
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
@Configuration
@ConditionalOnExpression("\${queue.sqs.enabled:false}")
@Import(BastionConfig::class)
@ComponentScan(basePackages = arrayOf("com.netflix.spinnaker.orca.q.amazon"))
@EnableConfigurationProperties(SqsProperties::class)
open class SqsQueueConfiguration {
@Bean open fun amazonSqsClient(awsCredentialsProvider: AWSCredentialsProvider, sqsProperties: SqsProperties) =
AmazonSQSClient
.builder()
.withCredentials(awsCredentialsProvider)
.withRegion(sqsProperties.region)
.build()
@Bean(name = arrayOf("queueImpl"))
open fun sqsQueue(amazonSqs: AmazonSQS, sqsProperties: SqsProperties, deadMessageHandler: DeadMessageHandler) =
SqsQueue(amazonSqs, sqsProperties, deadMessageHandler = deadMessageHandler::handle)
}
|
apache-2.0
|
cc240b5072c8b2fc84288facbeba2d57
| 42.895833 | 113 | 0.807309 | 4.353306 | false | true | false | false |
christophpickl/gadsu
|
src/main/kotlin/at/cpickl/gadsu/export/export.kt
|
1
|
5070
|
package at.cpickl.gadsu.export
import at.cpickl.gadsu.client.Client
import at.cpickl.gadsu.image.MyImage
import at.cpickl.gadsu.image.defaultImage
import at.cpickl.gadsu.treatment.Treatment
import com.google.common.base.MoreObjects
import com.google.common.io.BaseEncoding
import com.google.inject.AbstractModule
import com.thoughtworks.xstream.XStream
import com.thoughtworks.xstream.converters.Converter
import com.thoughtworks.xstream.converters.MarshallingContext
import com.thoughtworks.xstream.converters.UnmarshallingContext
import com.thoughtworks.xstream.io.HierarchicalStreamReader
import com.thoughtworks.xstream.io.HierarchicalStreamWriter
import com.thoughtworks.xstream.security.NoTypePermission
import com.thoughtworks.xstream.security.NullPermission
import com.thoughtworks.xstream.security.PrimitiveTypePermission
import org.joda.time.DateTime
import org.joda.time.format.ISODateTimeFormat
import org.slf4j.LoggerFactory
import java.util.ArrayList
class ExportModule : AbstractModule() {
override fun configure() {
bind(ExportService::class.java).to(ExportXstreamService::class.java)
}
}
class ExportData(val created: DateTime, _clients: List<Client>, _treatments: List<Treatment>) {
val clients: List<Client>
// data version
val treatments: List<Treatment>
init {
clients = ArrayList(_clients)
treatments = ArrayList(_treatments)
}
override fun toString() = MoreObjects.toStringHelper(javaClass)
.add("created", created)
.add("clients", clients)
.add("treatments", treatments)
.toString()
}
interface ExportService {
fun export(toExport: ExportData): String
fun import(xml: String): ExportData
}
class ExportXstreamService : ExportService {
private val log = LoggerFactory.getLogger(javaClass)
override fun export(toExport: ExportData): String {
log.info("export(toExport)")
return xstream().toXML(toExport)
}
override fun import(xml: String): ExportData {
log.info("export(toExport)")
val export = xstream().fromXML(xml) as ExportData
return ExportData(
export.created,
export.clients.map {
// YES, converter might have set to null (although kotlin disallowed)
val maybeMyImage: MyImage? = it.picture
if (maybeMyImage == null) {
it.copy(picture = it.gender.defaultImage)
} else {
it
}
},
export.treatments)
}
private fun xstream(): XStream {
val xstream = XStream()
XStream.setupDefaultSecurity(xstream)
// http://x-stream.github.io/graphs.html
xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES)
xstream.addPermission(NullPermission.NULL)
xstream.addPermission(PrimitiveTypePermission.PRIMITIVES)
xstream.addPermission(NoTypePermission.NONE)
xstream.allowTypesByWildcard(arrayOf("at.cpickl.gadsu.**"))
xstream.registerConverter(MyImageConverter())
xstream.registerConverter(JodaDateTimeConverter())
xstream.alias("treatment", Treatment::class.java)
xstream.alias("client", Client::class.java)
xstream.alias("gadsuExport", ExportData::class.java)
return xstream
}
}
private class JodaDateTimeConverter : BaseConverter<DateTime>(DateTime::class.java, "dateTime") {
private val formatter = ISODateTimeFormat.dateTime()
override fun _marshal(source: DateTime) = formatter.print(source)!!
override fun _unmarshal(read: String): DateTime = formatter.parseDateTime(read)
}
private class MyImageConverter : BaseConverter<MyImage>(MyImage::class.java, "myImage") {
private val base64 = BaseEncoding.base64()
override fun _marshal(source: MyImage) = if (source.isUnsavedDefaultPicture) null else base64.encode(source.toSaveRepresentation()!!)
override fun _unmarshal(read: String) = MyImage.byByteArray(base64.decode(read))
}
abstract private class BaseConverter<T>(private val targetClass: Class<T>, private val nodeName: String) : Converter {
abstract protected fun _marshal(source: T): String?
abstract protected fun _unmarshal(read: String): T?
override final fun canConvert(type: Class<*>): Boolean {
return targetClass.isAssignableFrom(type)
}
@Suppress("UNCHECKED_CAST")
override final fun marshal(source: Any, writer: HierarchicalStreamWriter, context: MarshallingContext) {
val marshalled = _marshal(source as T)
writer.startNode(nodeName)
if (marshalled != null) {
writer.setValue(marshalled)
}
writer.endNode()
}
override final fun unmarshal(reader: HierarchicalStreamReader, context: UnmarshallingContext): T? {
reader.moveDown()
val read = reader.value
reader.moveUp()
if (read.isEmpty()) {
return null
}
return _unmarshal(read)
}
}
|
apache-2.0
|
698bcb1531b06554170d8485117ce88e
| 33.026846 | 137 | 0.690138 | 4.555256 | false | false | false | false |
nisrulz/android-examples
|
ReadJSONFile/app/src/main/java/github/nisrulz/example/readjsonfile/ReadConfig.kt
|
1
|
886
|
package github.nisrulz.example.readjsonfile
import android.content.Context
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import kotlin.text.Charsets.UTF_8
class ReadConfig {
fun loadJSONFromAsset(context: Context, filename: String?): JSONObject? {
var jsonObject: JSONObject? = null
val json = try {
val inputStream = context.assets.open(filename!!)
val size = inputStream.available()
val buffer = ByteArray(size)
inputStream.read(buffer)
inputStream.close()
String(buffer, UTF_8)
} catch (ex: IOException) {
ex.printStackTrace()
return null
}
try {
jsonObject = JSONObject(json)
} catch (e: JSONException) {
e.printStackTrace()
}
return jsonObject
}
}
|
apache-2.0
|
732196932b42aadc9425a7a0dc235f92
| 26.71875 | 77 | 0.609481 | 4.737968 | false | false | false | false |
springboot-angular2-tutorial/boot-app
|
src/main/kotlin/com/myapp/domain/User.kt
|
1
|
1338
|
package com.myapp.domain
import com.fasterxml.jackson.annotation.JsonGetter
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonProperty
import com.myapp.generated.tables.records.UserRecord
import com.myapp.md5
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
data class User(
// ------- DB fields -------
override val _id: Long? = null,
@get:JsonIgnore
@get:Pattern(regexp = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$")
@get:Size(min = 4, max = 30)
val username: String,
@get:JsonIgnore
val password: String,
@get:Size(min = 4, max = 30)
val name: String,
// ------- Others -------
val userStats: UserStats? = null,
@get:JsonProperty("isFollowedByMe")
val isFollowedByMe: Boolean? = null, // null means unknown
@get:JsonIgnore
val isMyself: Boolean? = null // null means unknown
) : HasIdentity<Long> {
constructor(record: UserRecord) : this(
_id = record.id,
name = record.name,
username = record.username,
password = record.password
)
@JsonGetter
fun email(): String? {
return isMyself?.let { if (it) username else null }
}
@JsonGetter
fun avatarHash(): String = username.md5()
}
|
mit
|
6db58710a62ae45d9e9de1a23baec8f9
| 23.327273 | 98 | 0.633034 | 3.63587 | false | false | false | false |
Aidlab/Android-Example
|
app/src/main/java/com/aidlab/example/MainActivity.kt
|
1
|
10028
|
/**
*
* MainActivity.kt
* Android-Example
*
* Created by Michal Baranski on 03.11.2016.
* Copyright (c) 2016-2020 Aidlab. MIT License.
*
*/
package com.aidlab.example
import com.aidlab.sdk.communication.*
import android.content.Intent
import android.os.Handler
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Looper
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import kotlin.concurrent.fixedRateTimer
class MainActivity : AppCompatActivity(), AidlabDelegate, AidlabSDKDelegate, AidlabSynchronizationDelegate {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView1 = findViewById(R.id.textView)
textView2 = findViewById(R.id.textView2)
textView3 = findViewById(R.id.textView3)
textView4 = findViewById(R.id.textView4)
textView5 = findViewById(R.id.textView5)
textView6 = findViewById(R.id.textView6)
chartView = findViewById(R.id.chartView)
completeTextSpace()
connectedDevice = null
/// Start the bluetooth check process - Request necessary permissions and ask the user to
/// enable Bluetooth if it's disabled
textView1?.text = "Starting bluetooth..."
aidlabSDK.checkBluetooth(this)
startTimer()
}
private fun startTimer() {
if (timerTask != null) return
timerTask = fixedRateTimer("timer", false, 0, 1000L / 20) {
runOnUiThread {
chartView?.update()
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
/// Activity result has to be passed to Aidlab system's callback manager for the Bluetooth
/// check process
aidlabSDK.callbackManager.onActivityResult(this, requestCode, resultCode, data)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
/// Permissions result has to be passed to Aidlab system's callback manager for the
/// Bluetooth check process
aidlabSDK.callbackManager.onRequestPermissionsResult(this, requestCode, permissions, grantResults)
}
//-- AidlabSDKDelegate --------------------------------------------------------------------
override fun onBluetoothStarted() {
/// Bluetooth check process completed - start scanning for devices
aidlabSDK.scanForDevices()
}
override fun onDeviceScanStarted() {
textView1?.text = "Looking for devices..."
}
override fun onDeviceScanStopped() {
if (connectedDevice == null) {
aidlabSDK.clearDeviceList()
aidlabSDK.scanForDevices()
}
}
override fun onScanFailed(errorCode: Int) {}
override fun onAidlabDetected(aidlab: Aidlab, rssi: Int) {
/// Connect to first found device
if (connectedDevice == null) {
connectedDevice = aidlab
lastConnectedDevice = aidlab
aidlabSDK.stopDeviceScan()
textView1?.text = "Detected Aidlab. Connecting..."
/// Wait for the scan to finish and connect to the device
val dataReceiver = this
val signals = EnumSet.of(Signal.ecg, Signal.respiration, Signal.temperature,
Signal.motion, Signal.battery, Signal.activity,
Signal.orientation, Signal.steps, Signal.heartRate)
handler.postDelayed({
connectedDevice?.connect(signals, true, dataReceiver) /// Connect with all functions active
}, 100)
}
}
//-- Callbacks from Aidlab ---------------------------------------------------------------------
override fun didConnectAidlab(aidlab: IAidlab) {
println("MainActivity: Connected to Aidlab")
if(connectedDevice == null)
connectedDevice = lastConnectedDevice
this.aidlab = aidlab
runOnUiThread {
textView1?.text = "Connected to ${connectedDevice?.address()}"
}
}
override fun didDisconnectAidlab(aidlab: IAidlab, disconnectReason: DisconnectReason) {
runOnUiThread {
textView1?.text = "Disconnected"
}
}
override fun didReceiveECG(aidlab: IAidlab, timestamp: Long, values: FloatArray) {
runOnUiThread {
textView2?.text = "ECG: ${values[0]}"
values.forEach { chartView?.addECGSample(it) }
}
}
override fun didReceiveRespiration(aidlab: IAidlab, timestamp: Long, values: FloatArray) {
runOnUiThread {
textView3?.text = "RESP: ${values[0]}"
values.forEach { chartView?.addRespirationSample(it) }
}
}
override fun didReceiveBatteryLevel(aidlab: IAidlab, stateOfCharge: Int) {
runOnUiThread {
textView4?.text = "Battery state of charge = $stateOfCharge"
}
}
override fun didReceiveSkinTemperature(aidlab: IAidlab, timestamp: Long, value: Float) {
runOnUiThread {
textView5?.text = "Skin temperature $value"
}
}
override fun didReceiveHeartRate(aidlab: IAidlab, timestamp: Long, heartRate: Int) {
runOnUiThread {
textView6?.text = String.format("HR $heartRate")
}
}
override fun didReceiveHrv(aidlab: IAidlab, timestamp: Long, hrv: Int) {}
override fun didReceiveAccelerometer(aidlab: IAidlab, timestamp: Long, ax: Float, ay: Float, az: Float) {}
override fun didReceiveGyroscope(aidlab: IAidlab, timestamp: Long, qx: Float, qy: Float, qz: Float) {}
override fun didReceiveMagnetometer(aidlab: IAidlab, timestamp: Long, mx: Float, my: Float, mz: Float) {}
override fun didReceiveQuaternion(aidlab: IAidlab, timestamp: Long, qw: Float, qx: Float, qy: Float, qz: Float) {}
override fun didReceiveOrientation(aidlab: IAidlab, timestamp: Long, roll: Float, pitch: Float, yaw: Float) {}
override fun didReceiveBodyPosition(aidlab: IAidlab, timestamp: Long, bodyPosition: BodyPosition) {}
override fun didReceiveActivity(aidlab: IAidlab, timestamp: Long, activity: ActivityType) {}
override fun didReceiveSteps(aidlab: IAidlab, timestamp: Long, value: Long) {}
override fun didReceiveRespirationRate(aidlab: IAidlab, timestamp: Long, value: Int) {}
override fun wearStateDidChange(aidlab: IAidlab, wearState: WearState) {}
override fun didDetectExercise(aidlab: IAidlab, exercise: Exercise) {}
override fun didReceiveSoundVolume(aidlab: IAidlab, timestamp: Long, value: Int) {}
override fun didReceiveCommand(aidlab: IAidlab) {}
override fun didReceiveError(error: String) {}
override fun syncStateDidChange(aidlab: IAidlab, state: SyncState) {}
override fun didReceivePastECG(aidlab: IAidlab, timestamp: Long, values: FloatArray) {}
override fun didReceivePastRespiration(aidlab: IAidlab, timestamp: Long, values: FloatArray) {}
override fun didReceivePastSkinTemperature(aidlab: IAidlab, timestamp: Long, value: Float) {}
override fun didReceivePastHeartRate(aidlab: IAidlab, timestamp: Long, heartRate: Int) {}
override fun didReceiveUnsynchronizedSize(aidlab: IAidlab, unsynchronizedSize: Int) {}
override fun didReceivePastRespirationRate(aidlab: IAidlab, timestamp: Long, value: Int) {}
override fun didReceivePastActivity(aidlab: IAidlab, timestamp: Long, activity: ActivityType) {}
override fun didReceivePastSteps(aidlab: IAidlab, timestamp: Long, value: Long) {}
override fun didDetectPastUserEvent(timestamp: Long) {}
override fun didReceivePastAccelerometer(aidlab: IAidlab, timestamp: Long, ax: Float, ay: Float, az: Float) {}
override fun didReceivePastBodyPosition(aidlab: IAidlab, timestamp: Long, bodyPosition: BodyPosition) {}
override fun didReceivePastGyroscope(aidlab: IAidlab, timestamp: Long, qx: Float, qy: Float, qz: Float) {}
override fun didReceivePastHrv(aidlab: IAidlab, timestamp: Long, hrv: Int) {}
override fun didReceivePastMagnetometer(aidlab: IAidlab, timestamp: Long, mx: Float, my: Float, mz: Float) {}
override fun didReceivePastOrientation(aidlab: IAidlab, timestamp: Long, roll: Float, pitch: Float, yaw: Float) {}
override fun didReceivePastPressure(aidlab: IAidlab, timestamp: Long, values: IntArray) {}
override fun didReceivePastQuaternion(aidlab: IAidlab, timestamp: Long, qw: Float, qx: Float, qy: Float, qz: Float) {}
override fun didReceivePastSoundFeatures(aidlab: IAidlab, values: FloatArray) {}
override fun didReceivePastSoundVolume(aidlab: IAidlab, timestamp: Long, value: Int) {}
override fun didReceiveMessage(aidlab: IAidlab, process: String, message: String) {}
//-- Private -----------------------------------------------------------------------------------
private var timerTask: Timer? = null
private var aidlab: IAidlab? = null
private val aidlabSDK: AidlabSDK by lazy {
AidlabSDK(this, this)
}
private var connectedDevice: Aidlab? = null
private var lastConnectedDevice: Aidlab? = null
private val handler = Handler(Looper.getMainLooper())
private var textView1: TextView? = null
private var textView2: TextView? = null
private var textView3: TextView? = null
private var textView4: TextView? = null
private var textView5: TextView? = null
private var textView6: TextView? = null
private var chartView: ChartView? = null
private fun completeTextSpace() {
textView2?.text = "ECG --"
textView3?.text = "RESP --"
textView4?.text = "Battery state of charge --"
textView5?.text = "Skin temperature --"
textView6?.text = "HR --"
}
}
|
mit
|
18edec3b9966fd7e8265ee166d0fb2c5
| 33.463918 | 122 | 0.666434 | 4.807287 | false | false | false | false |
toastkidjp/Jitte
|
app/src/test/java/jp/toastkid/yobidashi/settings/DarkModeApplierTest.kt
|
2
|
2537
|
/*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.settings
import android.graphics.Color
import android.view.View
import androidx.core.content.ContextCompat
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.mockk
import io.mockk.mockkConstructor
import io.mockk.mockkObject
import io.mockk.mockkStatic
import io.mockk.unmockkAll
import io.mockk.verify
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.yobidashi.libs.Toaster
import org.junit.After
import org.junit.Before
import org.junit.Test
/**
* @author toastkidjp
*/
class DarkModeApplierTest {
private lateinit var darkModeApplier: DarkModeApplier
@MockK
private lateinit var preferenceApplier: PreferenceApplier
@MockK
private lateinit var parent: View
@Before
fun setUp() {
MockKAnnotations.init(this)
every { parent.getContext() }.returns(mockk())
every { preferenceApplier.colorPair() }.returns(mockk())
mockkStatic(ContextCompat::class)
every { ContextCompat.getColor(any(), any()) }.returns(Color.TRANSPARENT)
mockkObject(Theme)
every { Theme.extract(any(), any(), any()) }.returns(mockk())
mockkStatic(Color::class)
every { Color.parseColor(any()) }.returns(Color.TRANSPARENT)
mockkConstructor(Theme::class)
every { anyConstructed<Theme>().apply(any()) }.returns(Unit)
mockkObject(Toaster)
every { Toaster.snackLong(any(), any<String>(), any(), any(), any()) }.returns(mockk())
darkModeApplier = DarkModeApplier()
}
@After
fun tearDown() {
unmockkAll()
}
@Test
fun testInvoke() {
darkModeApplier.invoke(preferenceApplier, parent)
verify(exactly = 1) { parent.getContext() }
verify(exactly = 1) { preferenceApplier.colorPair() }
verify(atLeast = 1) { ContextCompat.getColor(any(), any()) }
verify(exactly = 1) { Theme.extract(any(), any(), any()) }
verify(atLeast = 1) { Color.parseColor(any()) }
verify(exactly = 1) { anyConstructed<Theme>().apply(any()) }
verify(exactly = 1) { Toaster.snackLong(any(), any<String>(), any(), any(), any()) }
}
}
|
epl-1.0
|
67f0d92521d34e497d19bb13b6255ac6
| 29.214286 | 95 | 0.683484 | 4.271044 | false | false | false | false |
Constantinuous/Angus
|
infrastructure/src/main/kotlin/de/constantinuous/angus/sql/impl/AntlrTsqlListener.kt
|
1
|
1135
|
package de.constantinuous.angus.sql.impl
import tsqlParser
import tsqlBaseListener
/**
* Created by RichardG on 25.11.2016.
*/
class AntlrTsqlListener : tsqlBaseListener() {
override fun exitSelect_statement(ctx: tsqlParser.Select_statementContext){
val tableName = ctx.getTableName()
val selectedColumnNames = ctx.getSelectedColumnNames()
}
override fun exitDelete_statement(ctx: tsqlParser.Delete_statementContext) {
val tableName = ctx.getTableName()
}
override fun exitDelete_statement_from(ctx: tsqlParser.Delete_statement_fromContext) {
}
override fun exitInsert_statement(ctx: tsqlParser.Insert_statementContext) {
val columnNames = ctx.getColumnNames()
val tableName = ctx.getTableName()
}
override fun exitUpdate_statement(ctx: tsqlParser.Update_statementContext) {
}
override fun exitExecute_statement(ctx: tsqlParser.Execute_statementContext) {
val procedureNames = ctx.getProcedureNames()
}
override fun exitFunction_call(ctx: tsqlParser.Function_callContext) {
println("Function call context")
}
}
|
mit
|
52f472b88da6d4d171f3b372662e0ff8
| 27.4 | 90 | 0.721586 | 4.521912 | false | false | false | false |
google/ksp
|
examples/playground/test-processor/src/main/kotlin/BuilderProcessor.kt
|
1
|
3521
|
import com.google.devtools.ksp.processing.*
import com.google.devtools.ksp.symbol.*
import com.google.devtools.ksp.validate
import java.io.File
import java.io.OutputStream
fun OutputStream.appendText(str: String) {
this.write(str.toByteArray())
}
class BuilderProcessor(
val codeGenerator: CodeGenerator,
val logger: KSPLogger
) : SymbolProcessor {
override fun process(resolver: Resolver): List<KSAnnotated> {
val symbols = resolver.getSymbolsWithAnnotation("com.example.annotation.Builder")
val ret = symbols.filter { !it.validate() }.toList()
symbols
.filter { it is KSClassDeclaration && it.validate() }
.forEach { it.accept(BuilderVisitor(), Unit) }
return ret
}
inner class BuilderVisitor : KSVisitorVoid() {
override fun visitClassDeclaration(classDeclaration: KSClassDeclaration, data: Unit) {
classDeclaration.primaryConstructor!!.accept(this, data)
}
override fun visitFunctionDeclaration(function: KSFunctionDeclaration, data: Unit) {
val parent = function.parentDeclaration as KSClassDeclaration
val packageName = parent.containingFile!!.packageName.asString()
val className = "${parent.simpleName.asString()}Builder"
val file = codeGenerator.createNewFile(Dependencies(true, function.containingFile!!), packageName , className)
file.appendText("package $packageName\n\n")
file.appendText("import HELLO\n\n")
file.appendText("class $className{\n")
function.parameters.forEach {
val name = it.name!!.asString()
val typeName = StringBuilder(it.type.resolve().declaration.qualifiedName?.asString() ?: "<ERROR>")
val typeArgs = it.type.element!!.typeArguments
if (it.type.element!!.typeArguments.isNotEmpty()) {
typeName.append("<")
typeName.append(
typeArgs.map {
val type = it.type?.resolve()
"${it.variance.label} ${type?.declaration?.qualifiedName?.asString() ?: "ERROR"}" +
if (type?.nullability == Nullability.NULLABLE) "?" else ""
}.joinToString(", ")
)
typeName.append(">")
}
file.appendText(" private var $name: $typeName? = null\n")
file.appendText(" internal fun with${name.capitalize()}($name: $typeName): $className {\n")
file.appendText(" this.$name = $name\n")
file.appendText(" return this\n")
file.appendText(" }\n\n")
}
file.appendText(" internal fun build(): ${parent.qualifiedName!!.asString()} {\n")
file.appendText(" return ${parent.qualifiedName!!.asString()}(")
file.appendText(
function.parameters.map {
"${it.name!!.asString()}!!"
}.joinToString(", ")
)
file.appendText(")\n")
file.appendText(" }\n")
file.appendText("}\n")
file.close()
}
}
}
class BuilderProcessorProvider : SymbolProcessorProvider {
override fun create(
env: SymbolProcessorEnvironment
): SymbolProcessor {
return BuilderProcessor(env.codeGenerator, env.logger)
}
}
|
apache-2.0
|
84ccb438c17163994ce761dc241e57e8
| 43.582278 | 122 | 0.571997 | 5.20858 | false | false | false | false |
HendraAnggrian/kota
|
buildSrc/src/main/kotlin/extensions.kt
|
1
|
1660
|
import org.gradle.api.artifacts.dsl.DependencyHandler
import org.gradle.plugin.use.PluginDependenciesSpec
const val bintrayUser = "hendraanggrian"
const val bintrayGroup = "com.hendraanggrian"
const val bintrayArtifact = "kota"
const val bintrayPublish = "0.22"
const val bintrayDesc = "Minimalist Android development"
const val bintrayWeb = "https://github.com/hendraanggrian/kota"
const val minSdk = 14
const val targetSdk = 27
const val buildTools = "27.0.2"
const val androidVersion = "3.0.1"
const val kotlinVersion = "1.2.10"
const val dokkaVersion = "0.9.15"
const val bintrayReleaseVersion = "0.8.0"
const val supportVersion = "27.0.2"
const val runnerVersion = "1.0.1"
const val espressoVersion = "3.0.1"
const val junitVersion = "4.12"
fun DependencyHandler.android(version: String) = "com.android.tools.build:gradle:$version"
fun PluginDependenciesSpec.android(module: String) = id("com.android.$module")
fun DependencyHandler.dokka(module: String? = null, version: String) = "org.jetbrains.dokka:${if (module != null) "dokka-$module" else "dokka"}-gradle-plugin:$version"
fun PluginDependenciesSpec.dokka(module: String? = null) = id("org.jetbrains.${if (module != null) "dokka-$module" else "dokka"}")
fun DependencyHandler.bintrayRelease(version: String) = "com.novoda:bintray-release:$version"
fun PluginDependenciesSpec.bintrayRelease() = id("com.novoda.bintray-release")
fun DependencyHandler.support(module: String, version: String, vararg suffixes: String) = "${StringBuilder("com.android.support").apply { suffixes.forEach { append(".$it") } }}:$module:$version"
fun DependencyHandler.junit(version: String) = "junit:junit:$version"
|
apache-2.0
|
c19b5ffdc6ad32b46541b3b8bc10ef66
| 46.457143 | 194 | 0.760241 | 3.616558 | false | false | false | false |
vsch/idea-multimarkdown
|
src/main/java/com/vladsch/md/nav/util/ParameterDataPrinter.kt
|
1
|
3601
|
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.util
import kotlin.reflect.KCallable
class UnquotedString(val text: String) {
override fun toString(): String {
return text
}
}
fun dataColText(colStringer: ((Array<Any?>) -> String)? = null, row: Array<Any?>?, col: Any?, padStart: Int = 0, padEnd: Int = 0): String {
val text: String
if (col == null) text = "null";
else {
if (colStringer != null && row != null) text = colStringer(row)
else {
when (col) {
is DataPrinterAware -> text = col.testData()
is Array<*> -> {
var colText = "";
for (elem in col) {
if (colText.isNotEmpty()) colText += ", ";
colText += dataColText(null, null, elem)
}
text = "arrayOf<String>($colText)";
}
is UnquotedString -> text = col.toString()
is Boolean -> text = col.toString()
is Int -> when (col) {
Integer.MAX_VALUE -> text = "Integer.MAX_VALUE"
Integer.MIN_VALUE -> text = "Integer.MIN_VALUE"
else -> text = col.toString()
}
is KCallable<*> -> text = "::" + col.toString().substringAfterLast('.')
else -> text = "\"${col.toString().replace("\\", "\\\\").replace("\"", "\\\"")}\"";
}
}
}
return text.padStart(padStart, ' ').padEnd(padEnd, ' ')
}
fun printData(data: Collection<Array<Any?>>, header: Array<String>, colStringersMap: Map<String, (Array<Any?>) -> String>? = null): Unit {
if (data.size == 0) return
var colWidths = Array<Int>(data.last().size, { 0 });
val colStringers = Array<((Array<Any?>) -> String)?>(data.last().size, { null })
for (i in header.indices) {
val col = header[i]
colStringers[i] = colStringersMap?.get(header[i])
val colText = dataColText(null, null, col)
if (colWidths[i] < colText.length) colWidths[i] = colText.length
}
for (row in data) {
for (i in row.indices) {
val col = row[i]
val colText = dataColText(colStringers[i], row, col)
if (colWidths[i] < colText.length) colWidths[i] = colText.length
}
}
System.out.println(" return arrayListOf<Array<Any?>>(")
// remove last column width, we don't pad the last column
colWidths[colWidths.lastIndex] = 0
var rowText = "";
for (i in header.indices) {
val col = header[i]
if (rowText.isNotEmpty()) rowText += ", ";
rowText += dataColText(null, null, col, padEnd = colWidths[i])
}
val rowPad = data.size.toString().length
System.out.println(" /* ${"".padStart(rowPad)} arrayOf<Any?>($rowText) */")
var rowIndex = 0
for (row in data) {
rowText = "";
for (i in row.indices) {
val col = row[i]
if (rowText.isNotEmpty()) rowText += ", ";
rowText += dataColText(colStringers[i], row, col, padEnd = colWidths[i])
}
if (rowIndex > 0) System.out.print(",\n")
System.out.print(" /* ${rowIndex.toString().padStart(rowPad)} */arrayOf<Any?>($rowText) /* ${rowIndex.toString().padStart(rowPad)} */")
rowIndex++
}
System.out.println("\n )")
}
|
apache-2.0
|
8022fe30ca2ea8332c37cc81ec3b2c1c
| 37.72043 | 177 | 0.527631 | 4.059752 | false | false | false | false |
Fitbit/MvRx
|
mvrx-mocking/src/main/kotlin/com/airbnb/mvrx/mocking/MockStateHolder.kt
|
1
|
6030
|
package com.airbnb.mvrx.mocking
import android.os.Parcelable
import com.airbnb.mvrx.MavericksViewModel
import com.airbnb.mvrx.MavericksState
import com.airbnb.mvrx.lifecycleAwareLazy
import kotlin.reflect.KProperty
/**
* Used to mock the initial state value of a viewmodel.
*/
class MockStateHolder {
private val stateMap = mutableMapOf<MockableMavericksView, MavericksMock<*, *>>()
private val delegateInfoMap =
mutableMapOf<MockableMavericksView, MutableList<ViewModelDelegateInfo<*, *>>>()
/**
* Set mock data for a view reference. The mocks will be used to provide initial state
* when the view models are initialized as the view is started.
*/
fun <V : MockableMavericksView, A : Parcelable> setMock(
view: MockableMavericksView,
mockInfo: MavericksMock<V, A>
) {
stateMap[view] = mockInfo
}
/**
* Clear the stored mock info for the given view. This should be called after the view is done initializing itself with the mock.
* This should be done to prevent leaking references to the view and its mocks.
*/
fun clearMock(view: MockableMavericksView) {
stateMap.remove(view)
// If the mocked view was just mocked with args and doesn't haven't view models then this will be empty
delegateInfoMap.remove(view)
}
fun clearAllMocks() {
stateMap.clear()
delegateInfoMap.clear()
}
/**
* Get the mocked state for the viewmodel on the given view. Returns null if no mocked state has been set - this is valid if a view
* under mock contains nested views that are not under mock.
*
* The mock state is not cleared after being retrieved because if the view has multiple viewmodels they will each need to
* access this separately.
*
* If null is returned it means that the view should be initialized from its arguments.
* This will only happen if this is not an "existing" view model.
*
* @param forceMockExistingViewModel If true, and if [existingViewModel] is true, then we expect that no mock state has been set for this viewmodel
* and we should instead manually retrieve the default mock state from the View and force that as the mock state to use.
*/
fun <S : MavericksState> getMockedState(
view: MockableMavericksView,
viewModelProperty: KProperty<*>,
existingViewModel: Boolean,
stateClass: Class<S>,
forceMockExistingViewModel: Boolean
): S? {
val mockInfo = if (existingViewModel && forceMockExistingViewModel) {
check(!stateMap.containsKey(view)) {
"Expected to force mock existing view model, but mocked state already " +
"exists (${view.javaClass.simpleName}#${viewModelProperty.name})"
}
MavericksViewMocks.getFrom(view).mocks
.firstOrNull { it.isDefaultState }
?.let { mvRxMock ->
@Suppress("UNCHECKED_CAST")
mvRxMock as MavericksMock<MockableMavericksView, *>
}
?: error(
"No mock state found in ${view.javaClass.simpleName} for ViewModel ${viewModelProperty.name}. " +
"A mock state must be provided to support this existing ViewModel."
)
} else {
stateMap[view] ?: return null
}
@Suppress("UNCHECKED_CAST") val state =
mockInfo.stateForViewModelProperty(viewModelProperty, existingViewModel)
if (state == null && existingViewModel) {
error("An 'existingViewModel' must have its state provided in the mocks")
}
// TODO Higher order view model support in Mavericks
// It's possible for this viewmodel to be injected with another view model in its constructor.
// In that case, the other viewmodel needs to be initialized first, otherwise it will crash.
// Fragments should use the 'dependencies' property of the viewmodel delegate function to specify viewmodels to initialize first,
// however, in the existingViewModel case we don't use 'dependencies' because we expect it to already exist, which is true in production.
// However, for mocking it won't exist, so we need to force existing view models to be created first.
// We only do this from non existing view models to prevent a loop.
if (!existingViewModel) {
val otherViewModelsOnView =
delegateInfoMap[view]?.filter { it.viewModelProperty != viewModelProperty }
?: error("No delegates registered for ${view.javaClass.simpleName}")
otherViewModelsOnView
.filter { it.existingViewModel }
.forEach { it.viewModelDelegate.value }
}
@Suppress("UNCHECKED_CAST")
return when {
state == null -> null
state as? S != null -> state
else -> error("Expected state of type ${stateClass.simpleName} but found ${state::class.java.simpleName}")
}
}
fun <VM : MavericksViewModel<S>, S : MavericksState> addViewModelDelegate(
view: MockableMavericksView,
existingViewModel: Boolean,
viewModelProperty: KProperty<*>,
viewModelDelegate: lifecycleAwareLazy<VM>
) {
delegateInfoMap
.getOrPut(view) { mutableListOf() }
.also { delegateInfoList ->
require(delegateInfoList.none { it.viewModelProperty == viewModelProperty }) {
"Delegate already registered for ${viewModelProperty.name}"
}
}
.add(ViewModelDelegateInfo(existingViewModel, viewModelProperty, viewModelDelegate))
}
data class ViewModelDelegateInfo<VM : MavericksViewModel<S>, S : MavericksState>(
val existingViewModel: Boolean,
val viewModelProperty: KProperty<*>,
val viewModelDelegate: lifecycleAwareLazy<VM>
)
}
|
apache-2.0
|
e542c89db36c788b8bc940dac108e8cc
| 42.695652 | 151 | 0.648425 | 5.229835 | false | false | false | false |
Fitbit/MvRx
|
todomvrx/src/main/java/com/airbnb/mvrx/todomvrx/util/ToDoEpoxyController.kt
|
1
|
1859
|
package com.airbnb.mvrx.todomvrx.util
import com.airbnb.epoxy.AsyncEpoxyController
import com.airbnb.epoxy.EpoxyController
import com.airbnb.mvrx.BaseMvRxViewModel
import com.airbnb.mvrx.MavericksState
import com.airbnb.mvrx.todomvrx.core.BaseFragment
import com.airbnb.mvrx.todomvrx.core.MvRxViewModel
import com.airbnb.mvrx.withState
class ToDoEpoxyController(
val buildModelsCallback: EpoxyController.() -> Unit = {}
) : AsyncEpoxyController() {
override fun buildModels() {
buildModelsCallback()
}
}
/**
* Create a [MvRxEpoxyController] that builds models with the given callback.
*/
fun BaseFragment.simpleController(
buildModels: EpoxyController.() -> Unit
) = ToDoEpoxyController {
// Models are built asynchronously, so it is possible that this is called after the fragment
// is detached under certain race conditions.
if (view == null || isRemoving) return@ToDoEpoxyController
buildModels()
}
/**
* Create a [ToDoEpoxyController] that builds models with the given callback.
* When models are built the current state of the viewmodel will be provided.
*/
fun <S : MavericksState, A : MvRxViewModel<S>> BaseFragment.simpleController(
viewModel: A,
buildModels: EpoxyController.(state: S) -> Unit
) = ToDoEpoxyController {
if (view == null || isRemoving) return@ToDoEpoxyController
com.airbnb.mvrx.withState(viewModel) { state ->
buildModels(state)
}
}
fun <A : BaseMvRxViewModel<B>, B : MavericksState, C : BaseMvRxViewModel<D>, D : MavericksState> BaseFragment.simpleController(
viewModel1: A,
viewModel2: C,
buildModels: EpoxyController.(state1: B, state2: D) -> Unit
) = ToDoEpoxyController {
if (view == null || isRemoving) return@ToDoEpoxyController
withState(viewModel1, viewModel2) { state1, state2 ->
buildModels(state1, state2)
}
}
|
apache-2.0
|
11f538fa78a05fdd0a35953822d1d51f
| 33.425926 | 127 | 0.733728 | 4.263761 | false | false | false | false |
rei-m/android_hyakuninisshu
|
domain/src/main/java/me/rei_m/hyakuninisshu/domain/question/model/Question.kt
|
1
|
3822
|
/*
* Copyright (c) 2020. Rei Matsushita
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package me.rei_m.hyakuninisshu.domain.question.model
import me.rei_m.hyakuninisshu.domain.AbstractEntity
import me.rei_m.hyakuninisshu.domain.karuta.model.KarutaNo
import java.util.Date
/**
* 百人一首の問題.
*
* @param id ID
* @param no 何番目の問題か
* @param choiceList 選択肢の歌番号のリスト
* @param state 問題の状態
*/
class Question constructor(
id: QuestionId,
val no: Int,
val choiceList: List<KarutaNo>,
val correctNo: KarutaNo,
state: State
) : AbstractEntity<QuestionId>(id) {
var state: State = state
private set
/**
* 解答を開始する.
*
* @param startDate 解答開始時間
*
* @return 問題
*
* @throws IllegalStateException すでに回答済だった場合
*/
@Throws(IllegalStateException::class)
fun start(startDate: Date): Question {
if (state is State.Answered) {
throw IllegalStateException("Question is already answered.")
}
this.state = State.InAnswer(startDate)
return this
}
/**
* 選択肢が正解か判定する.
*
* @param selectedNo 選択した歌の番号
* @param answerDate 解答した時間
*
* @return 解答後の問題
*
* @throws IllegalStateException 解答開始していない場合, すでに回答済の場合.
*/
@Throws(IllegalStateException::class)
fun verify(selectedNo: KarutaNo, answerDate: Date): Question {
when (val current = state) {
is State.Ready -> {
throw IllegalStateException("Question is not started. Call start.")
}
is State.InAnswer -> {
val answerTime = answerDate.time - current.startDate.time
val judgement = QuestionJudgement(
correctNo,
correctNo == selectedNo
)
this.state = State.Answered(
current.startDate,
QuestionResult(selectedNo, answerTime, judgement)
)
return this
}
is State.Answered -> {
throw IllegalStateException("Question is already answered.")
}
}
}
override fun toString() =
"Question(id=$identifier no=$no, choiceList=$choiceList, correctNo=$correctNo, state=$state)"
/**
* 問題の状態.
*
* Ready: 開始前
* InAnswer: 回答中
* Answered: 回答済
*/
sealed class State {
object Ready : State()
class InAnswer(val startDate: Date) : State()
class Answered(val startDate: Date, val result: QuestionResult) : State()
companion object {
fun create(startDate: Date?, result: QuestionResult?): State {
return if (startDate != null) {
if (result != null) {
Answered(startDate, result)
} else {
InAnswer(startDate)
}
} else {
Ready
}
}
}
}
companion object {
const val CHOICE_SIZE = 4
}
}
|
apache-2.0
|
7940e5c22b82a0d8d77e4d526e6c7333
| 27.870968 | 112 | 0.575698 | 4.261905 | false | false | false | false |
dexbleeker/hamersapp
|
hamersapp/src/main/java/nl/ecci/hamers/ui/activities/NewEventActivity.kt
|
1
|
6308
|
package nl.ecci.hamers.ui.activities
import android.app.TimePickerDialog
import android.os.Bundle
import android.view.View
import android.widget.DatePicker
import android.widget.TimePicker
import android.widget.Toast
import com.android.volley.VolleyError
import kotlinx.android.synthetic.main.activity_general.*
import kotlinx.android.synthetic.main.stub_new_event.*
import nl.ecci.hamers.R
import nl.ecci.hamers.data.Loader
import nl.ecci.hamers.data.PostCallback
import nl.ecci.hamers.models.Event
import nl.ecci.hamers.ui.fragments.DatePickerFragment
import nl.ecci.hamers.ui.fragments.TimePickerFragment
import nl.ecci.hamers.utils.DataUtils
import nl.ecci.hamers.utils.Utils
import org.json.JSONException
import org.json.JSONObject
import java.text.SimpleDateFormat
class NewEventActivity : HamersNewItemActivity(), TimePickerDialog.OnTimeSetListener {
private val fragmentManager = supportFragmentManager
private var eventID: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initToolbar()
stub.layoutResource = R.layout.stub_new_event
stub.inflate()
val timeFormat = SimpleDateFormat("HH:mm", MainActivity.locale)
val dateFormat = SimpleDateFormat("dd-MM-yyyy", MainActivity.locale)
eventID = intent.getIntExtra(Event.EVENT, -1)
if (eventID != -1) {
val event = DataUtils.getEvent(this, eventID)
event_title.setText(event.title)
event_location.setText(event.location)
event_beschrijving.setText(event.description)
event_time_button.text = timeFormat.format(event.date)
event_date_button.text = dateFormat.format(event.date)
event_end_time_button.text = timeFormat.format(event.endDate)
event_end_date_button.text = dateFormat.format(event.endDate)
event_deadline_time_button.text = timeFormat.format(event.deadline)
event_deadline_date_button.text = dateFormat.format(event.deadline)
}
}
override fun onResume() {
super.onResume()
setTitle(R.string.new_event)
}
fun showDatePickerDialog(v: View) {
val picker = DatePickerFragment()
picker.show(fragmentManager, "date")
}
fun showEndDatePickerDialog(v: View) {
val picker = DatePickerFragment()
picker.show(fragmentManager, "end_date")
}
fun showTimePickerDialog(v: View) {
val picker = TimePickerFragment()
picker.show(fragmentManager, "time")
}
fun showEndTimePickerDialog(v: View) {
val picker = TimePickerFragment()
picker.show(fragmentManager, "end_time")
}
fun showDeadlineTimePickerDialog(v: View) {
val picker = TimePickerFragment()
picker.show(fragmentManager, "deadline_time")
}
fun showDeadlineDatePickerDialog(v: View) {
val picker = DatePickerFragment()
picker.show(fragmentManager, "deadline_date")
}
override fun onDateSet(datePicker: DatePicker?, year: Int, month: Int, day: Int) {
val date = day.toString() + "-" + (month + 1) + "-" + year
if (supportFragmentManager.findFragmentByTag("date") != null) {
event_date_button?.text = date
}
if (supportFragmentManager.findFragmentByTag("end_date") != null) {
event_end_date_button?.text = date
}
if (supportFragmentManager.findFragmentByTag("deadline_date") != null) {
event_deadline_date_button?.text = date
}
}
override fun onTimeSet(view: TimePicker, hour: Int, minute: Int) {
val builder = StringBuilder()
builder.append(hour).append(":")
if (minute < 10) {
builder.append(0).append(minute)
} else {
builder.append(minute)
}
val time = builder.toString()
if (supportFragmentManager.findFragmentByTag("time") != null) {
event_time_button?.text = time
}
if (supportFragmentManager.findFragmentByTag("end_time") != null) {
event_end_time_button?.text = time
}
if (supportFragmentManager.findFragmentByTag("deadline_time") != null) {
event_deadline_time_button?.text = time
}
}
/**
* Posts event
*/
override fun postItem() {
val title = event_title.text.toString()
val location = event_location.text.toString()
val description = event_beschrijving.text.toString()
val eventTime = event_time_button.text.toString()
val eventEndTime = event_end_time_button.text.toString()
val eventDate = event_date_button.text.toString()
val eventEndDate = event_end_date_button.text.toString()
val deadlineTime = event_deadline_time_button.text.toString()
val deadlineDate = event_deadline_date_button.text.toString()
if (!eventDate.contains("Datum") &&
title.isNotBlank() &&
description.isNotBlank() &&
!eventTime.contains("Tijd") &&
!eventEndDate.contains("Datum") &&
!eventEndTime.contains("Tijd") &&
!deadlineDate.contains("Datum") &&
!deadlineTime.contains("Tijd")) {
val body = JSONObject()
try {
body.put("title", title)
body.put("beschrijving", description)
body.put("location", location)
body.put("end_time", Utils.parseDate("$eventEndDate $eventEndTime"))
body.put("deadline", Utils.parseDate("$deadlineDate $deadlineTime"))
body.put("date", Utils.parseDate("$eventDate $eventTime"))
} catch (ignored: JSONException) {
}
Loader.postOrPatchData(this, Loader.EVENTURL, body, eventID, object : PostCallback {
override fun onSuccess(response: JSONObject) {
finish()
}
override fun onError(error: VolleyError) {
disableLoadingAnimation()
}
})
} else {
disableLoadingAnimation()
Utils.showToast(this, getString(R.string.missing_fields), Toast.LENGTH_SHORT)
}
}
}
|
gpl-3.0
|
1d79cacad4f5f9f97a141e951c3e2648
| 35.045714 | 96 | 0.629518 | 4.49608 | false | false | false | false |
fossasia/open-event-android
|
app/src/main/java/org/fossasia/openevent/general/di/Modules.kt
|
1
|
17092
|
package org.fossasia.openevent.general.di
import androidx.paging.PagedList
import androidx.room.Room
import com.facebook.stetho.okhttp3.StethoInterceptor
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.github.jasminb.jsonapi.ResourceConverter
import com.github.jasminb.jsonapi.retrofit.JSONAPIConverterFactory
import java.util.concurrent.TimeUnit
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.fossasia.openevent.general.BuildConfig
import org.fossasia.openevent.general.OpenEventDatabase
import org.fossasia.openevent.general.StartupViewModel
import org.fossasia.openevent.general.about.AboutEventViewModel
import org.fossasia.openevent.general.attendees.Attendee
import org.fossasia.openevent.general.attendees.AttendeeApi
import org.fossasia.openevent.general.attendees.AttendeeService
import org.fossasia.openevent.general.attendees.AttendeeViewModel
import org.fossasia.openevent.general.attendees.forms.CustomForm
import org.fossasia.openevent.general.auth.AuthApi
import org.fossasia.openevent.general.auth.AuthHolder
import org.fossasia.openevent.general.auth.AuthService
import org.fossasia.openevent.general.auth.AuthViewModel
import org.fossasia.openevent.general.auth.EditProfileViewModel
import org.fossasia.openevent.general.auth.LoginViewModel
import org.fossasia.openevent.general.auth.ProfileViewModel
import org.fossasia.openevent.general.auth.RequestAuthenticator
import org.fossasia.openevent.general.auth.SignUp
import org.fossasia.openevent.general.auth.SignUpViewModel
import org.fossasia.openevent.general.auth.SmartAuthViewModel
import org.fossasia.openevent.general.auth.User
import org.fossasia.openevent.general.connectivity.MutableConnectionLiveData
import org.fossasia.openevent.general.data.Network
import org.fossasia.openevent.general.data.Preference
import org.fossasia.openevent.general.data.Resource
import org.fossasia.openevent.general.discount.DiscountApi
import org.fossasia.openevent.general.discount.DiscountCode
import org.fossasia.openevent.general.event.Event
import org.fossasia.openevent.general.event.EventApi
import org.fossasia.openevent.general.event.EventDetailsViewModel
import org.fossasia.openevent.general.event.EventId
import org.fossasia.openevent.general.event.EventService
import org.fossasia.openevent.general.event.EventsViewModel
import org.fossasia.openevent.general.event.faq.EventFAQ
import org.fossasia.openevent.general.event.faq.EventFAQApi
import org.fossasia.openevent.general.event.faq.EventFAQViewModel
import org.fossasia.openevent.general.event.location.EventLocation
import org.fossasia.openevent.general.event.location.EventLocationApi
import org.fossasia.openevent.general.event.subtopic.EventSubTopic
import org.fossasia.openevent.general.event.tax.Tax
import org.fossasia.openevent.general.event.tax.TaxApi
import org.fossasia.openevent.general.event.tax.TaxService
import org.fossasia.openevent.general.event.topic.EventTopic
import org.fossasia.openevent.general.event.topic.EventTopicApi
import org.fossasia.openevent.general.event.types.EventType
import org.fossasia.openevent.general.event.types.EventTypesApi
import org.fossasia.openevent.general.favorite.FavoriteEvent
import org.fossasia.openevent.general.favorite.FavoriteEventApi
import org.fossasia.openevent.general.favorite.FavoriteEventsViewModel
import org.fossasia.openevent.general.feedback.Feedback
import org.fossasia.openevent.general.feedback.FeedbackApi
import org.fossasia.openevent.general.feedback.FeedbackService
import org.fossasia.openevent.general.feedback.FeedbackViewModel
import org.fossasia.openevent.general.notification.Notification
import org.fossasia.openevent.general.notification.NotificationApi
import org.fossasia.openevent.general.notification.NotificationService
import org.fossasia.openevent.general.notification.NotificationViewModel
import org.fossasia.openevent.general.order.Charge
import org.fossasia.openevent.general.order.ConfirmOrder
import org.fossasia.openevent.general.order.Order
import org.fossasia.openevent.general.order.OrderApi
import org.fossasia.openevent.general.order.OrderCompletedViewModel
import org.fossasia.openevent.general.order.OrderDetailsViewModel
import org.fossasia.openevent.general.order.OrderService
import org.fossasia.openevent.general.order.OrdersUnderUserViewModel
import org.fossasia.openevent.general.paypal.Paypal
import org.fossasia.openevent.general.paypal.PaypalApi
import org.fossasia.openevent.general.search.SearchResultsViewModel
import org.fossasia.openevent.general.search.SearchViewModel
import org.fossasia.openevent.general.search.location.GeoLocationViewModel
import org.fossasia.openevent.general.search.location.LocationService
import org.fossasia.openevent.general.search.location.LocationServiceImpl
import org.fossasia.openevent.general.search.location.SearchLocationViewModel
import org.fossasia.openevent.general.search.time.SearchTimeViewModel
import org.fossasia.openevent.general.search.type.SearchTypeViewModel
import org.fossasia.openevent.general.sessions.Session
import org.fossasia.openevent.general.sessions.SessionApi
import org.fossasia.openevent.general.sessions.SessionService
import org.fossasia.openevent.general.sessions.SessionViewModel
import org.fossasia.openevent.general.sessions.microlocation.MicroLocation
import org.fossasia.openevent.general.sessions.sessiontype.SessionType
import org.fossasia.openevent.general.sessions.track.Track
import org.fossasia.openevent.general.settings.Settings
import org.fossasia.openevent.general.settings.SettingsApi
import org.fossasia.openevent.general.settings.SettingsService
import org.fossasia.openevent.general.settings.SettingsViewModel
import org.fossasia.openevent.general.social.SocialLink
import org.fossasia.openevent.general.social.SocialLinkApi
import org.fossasia.openevent.general.social.SocialLinksService
import org.fossasia.openevent.general.speakercall.EditSpeakerViewModel
import org.fossasia.openevent.general.speakercall.Proposal
import org.fossasia.openevent.general.speakercall.SpeakersCall
import org.fossasia.openevent.general.speakercall.SpeakersCallProposalViewModel
import org.fossasia.openevent.general.speakercall.SpeakersCallViewModel
import org.fossasia.openevent.general.speakers.Speaker
import org.fossasia.openevent.general.speakers.SpeakerApi
import org.fossasia.openevent.general.speakers.SpeakerService
import org.fossasia.openevent.general.speakers.SpeakerViewModel
import org.fossasia.openevent.general.sponsor.Sponsor
import org.fossasia.openevent.general.sponsor.SponsorApi
import org.fossasia.openevent.general.sponsor.SponsorService
import org.fossasia.openevent.general.sponsor.SponsorsViewModel
import org.fossasia.openevent.general.ticket.Ticket
import org.fossasia.openevent.general.ticket.TicketApi
import org.fossasia.openevent.general.ticket.TicketId
import org.fossasia.openevent.general.ticket.TicketService
import org.fossasia.openevent.general.ticket.TicketsViewModel
import org.koin.android.ext.koin.androidApplication
import org.koin.android.ext.koin.androidContext
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.jackson.JacksonConverterFactory
val commonModule = module {
single { Preference() }
single { Network() }
single { Resource() }
factory { MutableConnectionLiveData() }
factory<LocationService> { LocationServiceImpl(androidContext(), get()) }
}
val apiModule = module {
single {
val retrofit: Retrofit = get()
retrofit.create(EventApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(AuthApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(TicketApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(FavoriteEventApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(SocialLinkApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(EventTopicApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(AttendeeApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(OrderApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(PaypalApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(EventTypesApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(EventLocationApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(FeedbackApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(SpeakerApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(EventFAQApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(SessionApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(SponsorApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(NotificationApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(DiscountApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(SettingsApi::class.java)
}
single {
val retrofit: Retrofit = get()
retrofit.create(TaxApi::class.java)
}
factory { AuthHolder(get()) }
factory { AuthService(get(), get(), get(), get(), get(), get(), get()) }
factory { EventService(get(), get(), get(), get(), get(), get(), get(), get(), get()) }
factory { SpeakerService(get(), get(), get()) }
factory { SponsorService(get(), get(), get()) }
factory { TicketService(get(), get(), get()) }
factory { SocialLinksService(get(), get()) }
factory { AttendeeService(get(), get(), get()) }
factory { OrderService(get(), get(), get(), get(), get()) }
factory { SessionService(get(), get()) }
factory { NotificationService(get(), get()) }
factory { FeedbackService(get(), get()) }
factory { SettingsService(get(), get()) }
factory { TaxService(get(), get()) }
}
val viewModelModule = module {
viewModel { LoginViewModel(get(), get(), get(), get()) }
viewModel { EventsViewModel(get(), get(), get(), get(), get(), get()) }
viewModel { StartupViewModel(get(), get(), get(), get(), get(), get()) }
viewModel { ProfileViewModel(get(), get()) }
viewModel { SignUpViewModel(get(), get(), get()) }
viewModel {
EventDetailsViewModel(get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get()) }
viewModel { SessionViewModel(get(), get(), get()) }
viewModel { SearchViewModel(get(), get()) }
viewModel { SearchResultsViewModel(get(), get(), get(), get(), get(), get()) }
viewModel { AttendeeViewModel(get(), get(), get(), get(), get(), get(), get(), get()) }
viewModel { SearchLocationViewModel(get(), get(), get()) }
viewModel { SearchTimeViewModel(get()) }
viewModel { SearchTypeViewModel(get(), get(), get()) }
viewModel { TicketsViewModel(get(), get(), get(), get(), get(), get()) }
viewModel { AboutEventViewModel(get(), get()) }
viewModel { EventFAQViewModel(get(), get()) }
viewModel { FavoriteEventsViewModel(get(), get(), get()) }
viewModel { SettingsViewModel(get(), get(), get()) }
viewModel { OrderCompletedViewModel(get(), get(), get(), get()) }
viewModel { OrdersUnderUserViewModel(get(), get(), get(), get(), get()) }
viewModel { OrderDetailsViewModel(get(), get(), get(), get()) }
viewModel { EditProfileViewModel(get(), get(), get()) }
viewModel { GeoLocationViewModel(get()) }
viewModel { SmartAuthViewModel() }
viewModel { SpeakerViewModel(get(), get()) }
viewModel { SponsorsViewModel(get(), get()) }
viewModel { NotificationViewModel(get(), get(), get(), get()) }
viewModel { AuthViewModel(get(), get(), get()) }
viewModel { SpeakersCallViewModel(get(), get(), get(), get(), get(), get()) }
viewModel { SpeakersCallProposalViewModel(get(), get(), get(), get(), get()) }
viewModel { EditSpeakerViewModel(get(), get(), get(), get()) }
viewModel { FeedbackViewModel(get(), get()) }
}
val networkModule = module {
single {
val objectMapper = jacksonObjectMapper()
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
objectMapper
}
single {
PagedList
.Config
.Builder()
.setPageSize(5)
.setInitialLoadSizeHint(5)
.setEnablePlaceholders(false)
.build()
}
single {
val connectTimeout = 15 // 15s
val readTimeout = 15 // 15s
val builder = OkHttpClient().newBuilder()
.connectTimeout(connectTimeout.toLong(), TimeUnit.SECONDS)
.readTimeout(readTimeout.toLong(), TimeUnit.SECONDS)
.addInterceptor(HostSelectionInterceptor(get()))
.addInterceptor(RequestAuthenticator(get()))
.addNetworkInterceptor(StethoInterceptor())
if (BuildConfig.DEBUG) {
val httpLoggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }
builder.addInterceptor(httpLoggingInterceptor)
}
builder.build()
}
single {
val baseUrl = BuildConfig.DEFAULT_BASE_URL
val objectMapper: ObjectMapper = get()
val onlineApiResourceConverter = ResourceConverter(
objectMapper, Event::class.java, User::class.java,
SignUp::class.java, Ticket::class.java, SocialLink::class.java, EventId::class.java,
EventTopic::class.java, Attendee::class.java, TicketId::class.java, Order::class.java,
Charge::class.java, Paypal::class.java, ConfirmOrder::class.java,
CustomForm::class.java, EventLocation::class.java, EventType::class.java,
EventSubTopic::class.java, Feedback::class.java, Speaker::class.java, FavoriteEvent::class.java,
Session::class.java, SessionType::class.java, MicroLocation::class.java, SpeakersCall::class.java,
Sponsor::class.java, EventFAQ::class.java, Notification::class.java, Track::class.java,
DiscountCode::class.java, Settings::class.java, Proposal::class.java, Tax::class.java)
Retrofit.Builder()
.client(get())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(JSONAPIConverterFactory(onlineApiResourceConverter))
.addConverterFactory(JacksonConverterFactory.create(objectMapper))
.baseUrl(baseUrl)
.build()
}
}
val databaseModule = module {
single {
Room.databaseBuilder(androidApplication(),
OpenEventDatabase::class.java, "open_event_database")
.fallbackToDestructiveMigration()
.build()
}
factory {
val database: OpenEventDatabase = get()
database.eventDao()
}
factory {
val database: OpenEventDatabase = get()
database.sessionDao()
}
factory {
val database: OpenEventDatabase = get()
database.userDao()
}
factory {
val database: OpenEventDatabase = get()
database.ticketDao()
}
factory {
val database: OpenEventDatabase = get()
database.socialLinksDao()
}
factory {
val database: OpenEventDatabase = get()
database.attendeeDao()
}
factory {
val database: OpenEventDatabase = get()
database.eventTopicsDao()
}
factory {
val database: OpenEventDatabase = get()
database.orderDao()
}
factory {
val database: OpenEventDatabase = get()
database.speakerWithEventDao()
}
factory {
val database: OpenEventDatabase = get()
database.speakerDao()
}
factory {
val database: OpenEventDatabase = get()
database.sponsorWithEventDao()
}
factory {
val database: OpenEventDatabase = get()
database.sponsorDao()
}
factory {
val database: OpenEventDatabase = get()
database.feedbackDao()
}
factory {
val database: OpenEventDatabase = get()
database.speakersCallDao()
}
factory {
val database: OpenEventDatabase = get()
database.notificationDao()
}
factory {
val database: OpenEventDatabase = get()
database.settingsDao()
}
factory {
val database: OpenEventDatabase = get()
database.taxDao()
}
}
|
apache-2.0
|
e5ed35ad7ff73efd3f8d6e3afa0b417c
| 39.406619 | 117 | 0.72414 | 4.486089 | false | false | false | false |
ccomeaux/boardgamegeek4android
|
app/src/main/java/com/boardgamegeek/entities/PlayEntity.kt
|
1
|
4279
|
package com.boardgamegeek.entities
import android.content.Context
import com.boardgamegeek.R
import com.boardgamegeek.extensions.*
import com.boardgamegeek.provider.BggContract
import java.text.SimpleDateFormat
import java.util.*
data class PlayEntity(
val internalId: Long = BggContract.INVALID_ID.toLong(),
val playId: Int = BggContract.INVALID_ID,
private val rawDate: String,
val gameId: Int,
val gameName: String,
val quantity: Int = 1,
val length: Int = 0,
val location: String = "",
val incomplete: Boolean = false,
val noWinStats: Boolean = false,
val comments: String = "",
val syncTimestamp: Long = 0L,
private val initialPlayerCount: Int = 0,
val dirtyTimestamp: Long = 0L,
val updateTimestamp: Long = 0L,
val deleteTimestamp: Long = 0L,
val startTime: Long = 0L,
val imageUrl: String = "",
val thumbnailUrl: String = "",
val heroImageUrl: String = "",
val updatedPlaysTimestamp: Long = 0L,
val subtypes: List<String> = emptyList(),
private val _players: List<PlayPlayerEntity>? = null,
) {
val players
get() = _players.orEmpty()
val isSynced
get() = playId > 0
val dateInMillis: Long by lazy {
rawDate.toMillis(FORMAT, UNKNOWN_DATE)
}
fun dateForDisplay(context: Context): CharSequence {
return dateInMillis.asPastDaySpan(context, includeWeekDay = true)
}
fun dateForDatabase(): String {
return dateInMillis.forDatabase()
}
fun hasStarted(): Boolean {
return length == 0 && startTime > 0
}
val playerCount: Int
get() = _players?.size ?: initialPlayerCount
/**
* Determine if the starting positions indicate the players are custom sorted.
*/
fun arePlayersCustomSorted(): Boolean {
if (players.isEmpty()) return false
for (seat in 1..players.size) {
if (players.count { it.seat == seat } != 1) return true
}
return false
}
fun getPlayerAtSeat(seat: Int): PlayPlayerEntity? {
return players.find { it.seat == seat }
}
fun generateSyncHashCode(): Int {
val sb = StringBuilder()
sb.append(dateForDatabase()).append("\n")
sb.append(quantity).append("\n")
sb.append(length).append("\n")
sb.append(incomplete).append("\n")
sb.append(noWinStats).append("\n")
sb.append(location).append("\n")
sb.append(comments).append("\n")
for (player in players) {
sb.append(player.username).append("\n")
sb.append(player.userId).append("\n")
sb.append(player.name).append("\n")
sb.append(player.startingPosition).append("\n")
sb.append(player.color).append("\n")
sb.append(player.score).append("\n")
sb.append(player.isNew).append("\n")
sb.append(player.rating).append("\n")
sb.append(player.isWin).append("\n")
}
return sb.toString().hashCode()
}
fun describe(context: Context, includeDate: Boolean = false): String {
val info = StringBuilder()
if (quantity > 1) info.append(context.resources.getQuantityString(R.plurals.play_description_quantity_segment, quantity, quantity))
if (includeDate && dateInMillis != UNKNOWN_DATE) {
info.append(context.getString(R.string.play_description_date_segment, dateInMillis.asDate(context, includeWeekDay = true)))
}
if (location.isNotBlank()) info.append(context.getString(R.string.play_description_location_segment, location))
if (length > 0) info.append(context.getString(R.string.play_description_length_segment, length.asTime()))
if (playerCount > 0) info.append(context.resources.getQuantityString(R.plurals.play_description_players_segment, playerCount, playerCount))
return info.trim().toString()
}
companion object {
private val FORMAT = SimpleDateFormat("yyyy-MM-dd", Locale.US)
const val UNKNOWN_DATE: Long = -1L
fun currentDate(): String {
return millisToRawDate(Calendar.getInstance().timeInMillis)
}
fun millisToRawDate(millis: Long): String {
return FORMAT.format(millis)
}
}
}
|
gpl-3.0
|
b91a71d0d90de41b8b5313c68b0d53b8
| 34.07377 | 147 | 0.635663 | 4.199215 | false | false | false | false |
shkschneider/android_Skeleton
|
core/src/main/kotlin/me/shkschneider/skeleton/extensions/android/_Extras.kt
|
1
|
478
|
package me.shkschneider.skeleton.extensions.android
import android.app.Activity
import androidx.fragment.app.Fragment
// val value by extra<String>("key")
inline fun <reified T> Activity.extra(key: String, default: T? = null) = lazy {
val value = intent?.extras?.get(key)
if (value is T) value else default
}
inline fun <reified T> Fragment.extra(key: String, default: T? = null) = lazy {
val value = arguments?.get(key)
if (value is T) value else default
}
|
apache-2.0
|
be09f5c755c799707505f3fac9ed0e46
| 28.875 | 79 | 0.707113 | 3.463768 | false | false | false | false |
Kotlin/kotlinx.serialization
|
formats/json/commonMain/src/kotlinx/serialization/json/JsonEncoder.kt
|
1
|
3730
|
/*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.json
import kotlinx.serialization.encoding.*
/**
* Encoder used by [Json] during serialization.
* This interface can be used to inject desired behaviour into a serialization process of [Json].
*
* Typical example of the usage:
* ```
* // Class representing Either<Left|Right>
* sealed class Either {
* data class Left(val errorMsg: String) : Either()
* data class Right(val data: Payload) : Either()
* }
*
* // Serializer injects custom behaviour by inspecting object content and writing
* object EitherSerializer : KSerializer<Either> {
* override val descriptor: SerialDescriptor = buildSerialDescriptor("package.Either", PolymorphicKind.SEALED) {
* // ..
* }
*
* override fun deserialize(decoder: Decoder): Either {
* val input = decoder as? JsonDecoder ?: throw SerializationException("This class can be decoded only by Json format")
* val tree = input.decodeJsonElement() as? JsonObject ?: throw SerializationException("Expected JsonObject")
* if ("error" in tree) return Either.Left(tree["error"]!!.jsonPrimitive.content)
* return Either.Right(input.json.decodeFromJsonElement(Payload.serializer(), tree))
* }
*
* override fun serialize(encoder: Encoder, value: Either) {
* val output = encoder as? JsonEncoder ?: throw SerializationException("This class can be encoded only by Json format")
* val tree = when (value) {
* is Either.Left -> JsonObject(mapOf("error" to JsonPrimitve(value.errorMsg)))
* is Either.Right -> output.json.encodeToJsonElement(Payload.serializer(), value.data)
* }
* output.encodeJsonElement(tree)
* }
* }
* ```
*
* ### Not stable for inheritance
*
* `JsonEncoder` interface is not stable for inheritance in 3rd party libraries, as new methods
* might be added to this interface or contracts of the existing methods can be changed.
* Accepting this interface in your API methods, casting [Encoder] to [JsonEncoder] and invoking its
* methods is considered stable.
*/
public interface JsonEncoder : Encoder, CompositeEncoder {
/**
* An instance of the current [Json].
*/
public val json: Json
/**
* Appends the given JSON [element] to the current output.
* This method is allowed to invoke only as the part of the whole serialization process of the class,
* calling this method after invoking [beginStructure] or any `encode*` method will lead to unspecified behaviour
* and may produce an invalid JSON result.
* For example:
* ```
* class Holder(val value: Int, val list: List<Int>())
*
* // Holder serialize method
* fun serialize(encoder: Encoder, value: Holder) {
* // Completely okay, the whole Holder object is read
* val jsonObject = JsonObject(...) // build a JsonObject from Holder
* (encoder as JsonEncoder).encodeJsonElement(jsonObject) // Write it
* }
*
* // Incorrect Holder serialize method
* fun serialize(encoder: Encoder, value: Holder) {
* val composite = encoder.beginStructure(descriptor)
* composite.encodeSerializableElement(descriptor, 0, Int.serializer(), value.value)
* val array = JsonArray(value.list)
* // Incorrect, encoder is already in an intermediate state after encodeSerializableElement
* (composite as JsonEncoder).encodeJsonElement(array)
* composite.endStructure(descriptor)
* // ...
* }
* ```
*/
public fun encodeJsonElement(element: JsonElement)
}
|
apache-2.0
|
c5e9b54482bc2c9f508ac64c6d9849c0
| 41.873563 | 128 | 0.672654 | 4.456392 | false | false | false | false |
lukashaertel/megal-vm
|
src/main/kotlin/org/softlang/megal/content/Components.kt
|
1
|
1754
|
package org.softlang.megal.content
import kotlin.reflect.KClass
/**
* Content components.
*/
/**
* A type exposing a MIME type definition and a runtime class.
*/
data class Type<T : Any>(
val mime: Mime,
val rtt: KClass<T>) {
override fun toString() = "$mime: ${rtt.simpleName}"
}
/**
* A provider for a given [Type], as defined by a producer.
*/
data class Provider<T : Any>(
val type: Type<T>,
val get: () -> T)
/**
* An adapter for two [Type]s, as defined by a transformation.
*/
data class Adapter<T : Any, U : Any>(
val src: Type<T>,
val dst: Type<U>,
val transformation: (T) -> U)
/**
* Creates a provider from the MIME type, the reified type argument and the
* provider method.
*/
inline fun <reified T : Any>
provider(mime: Mime, noinline get: () -> T) =
Provider(Type(mime, T::class), get)
/**
* Creates a provider from the MIME type as a string, the reified type argument
* and the provider method.
*/
inline fun <reified T : Any>
provider(mime: String, noinline get: () -> T) =
provider(parseMime(mime), get)
/**
* Creates an adapter from the MIME types, the reified type arguments and the
* transformation method.
*/
inline fun <reified T : Any, reified U : Any>
adapter(src: Mime, dst: Mime, noinline transformation: (T) -> U) =
Adapter(Type(src, T::class), Type(dst, U::class), transformation)
/**
* Creates an adapter from the MIME types as strings, the reified type arguments
* and the transformation method.
*/
inline fun <reified T : Any, reified U : Any>
adapter(src: String, dst: String, noinline transformation: (T) -> U) =
adapter(parseMime(src), parseMime(dst), transformation)
|
mit
|
b370959e449c13be7610620cfee96ac6
| 26.84127 | 80 | 0.633409 | 3.64657 | false | false | false | false |
danrien/projectBlueWater
|
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/engine/audiomanagement/GivenAHaltedPlaybackEngine/WhenStartingANewPlaylist.kt
|
1
|
2400
|
package com.lasthopesoftware.bluewater.client.playback.engine.audiomanagement.GivenAHaltedPlaybackEngine
import androidx.media.AudioFocusRequestCompat
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.playback.engine.AudioManagingPlaybackStateChanger
import com.lasthopesoftware.bluewater.client.playback.engine.ChangePlaybackState
import com.lasthopesoftware.bluewater.client.playback.file.PositionedProgressedFile
import com.lasthopesoftware.bluewater.shared.android.audiofocus.ControlAudioFocus
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.joda.time.Duration
import org.junit.BeforeClass
import org.junit.Test
import java.util.concurrent.TimeUnit
class WhenStartingANewPlaylist {
companion object Setup {
private var isStarted = false
private var request: AudioFocusRequestCompat? = null
private val innerPlaybackState = object : ChangePlaybackState {
override fun restoreFromSavedState(): Promise<PositionedProgressedFile?> = Promise.empty()
override fun startPlaylist(playlist: List<ServiceFile>, playlistPosition: Int, filePosition: Duration): Promise<Unit> {
isStarted = true
return Unit.toPromise()
}
override fun resume(): Promise<Unit> = Unit.toPromise()
override fun pause(): Promise<Unit> = Unit.toPromise()
}
private val audioFocus = object : ControlAudioFocus {
override fun promiseAudioFocus(audioFocusRequest: AudioFocusRequestCompat): Promise<AudioFocusRequestCompat> {
request = audioFocusRequest
return audioFocusRequest.toPromise()
}
override fun abandonAudioFocus(audioFocusRequest: AudioFocusRequestCompat) {}
}
@JvmStatic
@BeforeClass
fun context() {
val audioManagingPlaybackStateChanger = AudioManagingPlaybackStateChanger(
innerPlaybackState,
audioFocus,
mockk(relaxed = true))
audioManagingPlaybackStateChanger
.startPlaylist(ArrayList(), 0, Duration.ZERO)
.toFuture()
.get(20, TimeUnit.SECONDS)
}
}
@Test
fun thenPlaybackIsStarted() {
assertThat(isStarted).isTrue
}
@Test
fun thenAudioFocusIsGranted() {
assertThat(request).isNotNull
}
}
|
lgpl-3.0
|
156b353a7e087455f7f6acce940eea68
| 32.802817 | 122 | 0.804583 | 4.40367 | false | false | false | false |
FHannes/intellij-community
|
platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/Contexts.kt
|
8
|
5937
|
/*
* 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.testGuiFramework.recorder.ui.GuiScriptEditorFrame
import java.awt.Component
import java.util.*
import javax.swing.JComponent
import javax.swing.JDialog
import javax.swing.JFrame
/**
* @author Sergey Karashevich
*/
class Contexts() {
enum class Type {DIALOG, WELCOME_FRAME, PROJECT_WIZARD, IDE_FRAME }
enum class SubType {EDITOR, TOOL_WINDOW }
private var projectWizardFound = false
private var welcomeFrameFound = false
private var ideFrameFound = false
private var myToolWindowId: String? = null
private val indentShift = 2
private var indentLevel: Int = 0
private val contextArray = ArrayList<Int>()
fun check(cmp: Component) {
val parent = (cmp as JComponent).rootPane.parent
if (contextArray.isEmpty()) {
checkGlobalContext(parent)
checkDialogContext(parent)
contextArray.add(parent.hashCode())
indentLevel++
}
//check that we increase component level or decrease component level
else {
//hashcode equals -> no need to change components
if (parent.hashCode() == contextArray.last())
//do nothing
else {
//current context component and the previous to last in contextArray hashcodes are same
if (contextArray.size > 1 && parent.hashCode() == contextArray[contextArray.size - 2]) {
contextArray.removeAt(contextArray.size - 1)
indentLevel--
Writer.writeln(closeContext())
assert(indentLevel >= 0)
}
else
if (contextArray.size > 1 && parent.hashCode() != contextArray[contextArray.size - 2]) {
//start a new context
checkGlobalContext(parent)
checkDialogContext(parent)
contextArray.add(parent.hashCode())
indentLevel++
assert(indentLevel >= 0)
}
else
if (contextArray.size == 1 && parent.hashCode() != contextArray.last()) {
//start a new context
checkGlobalContext(parent)
checkDialogContext(parent)
contextArray.add(parent.hashCode())
indentLevel++
assert(indentLevel >= 0)
}
}
}
}
companion object {
val IDE_FRAME_VAL = "ideFrame"
}
var globalContext: Type? = null
var currentSubContextType: SubType? = null
private fun checkGlobalContext(parent: Component) {
if (parent is JFrame && parent.title == GuiScriptEditorFrame.GUI_SCRIPT_FRAME_TITLE) return //do nothing if switch to GUI Script Editor
if (contextArray.isEmpty() || contextArray.first() != parent.hashCode()) {
when (parent) {
is com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame -> {
globalContext = Type.WELCOME_FRAME
indentLevel = 0
if (contextArray.isNotEmpty()) {
Writer.writeln(closeContext())
contextArray.clear()
}
Writer.writeln(welcomeFrameStart())
return
}
is JFrame -> {
globalContext = Type.IDE_FRAME
indentLevel = 0
if (contextArray.isNotEmpty()) {
Writer.writeln(closeContext())
contextArray.clear()
}
Writer.writeln(ideFrameStart())
return
}
}
}
}
private fun checkDialogContext(parent: Component) {
if (parent is JFrame && parent.title == GuiScriptEditorFrame.GUI_SCRIPT_FRAME_TITLE) return //do nothing if switch to GUI Script Editor
when (parent) {
is JDialog -> {
if (parent.title == com.intellij.ide.IdeBundle.message("title.new.project")) {
Writer.writeln(projectWizardContextStart())
return
}
else {
Writer.writeln(dialogContextStart(parent.title))
return
}
}
}
}
fun getIndent(): String {
val size = indentLevel * indentShift
val sb = StringBuilder()
for (i in 1..size) sb.append(" ")
return sb.toString()
}
//*********** Context Scripts ************
fun closeContext() = "}"
fun dialogContextStart(title: String): String {
globalContext = Type.DIALOG
val withDialog = Templates.withDialog(title)
return withDialog
}
fun projectWizardContextStart(): String {
globalContext = Type.PROJECT_WIZARD
val withProjectWizard = Templates.withProjectWizard()
projectWizardFound = true
return withProjectWizard
}
fun welcomeFrameStart(): String {
globalContext = Type.WELCOME_FRAME
val withWelcomeFrame = Templates.withWelcomeFrame()
welcomeFrameFound = true
return withWelcomeFrame
}
fun ideFrameStart(): String {
globalContext = Type.IDE_FRAME
val withIdeFrame = Templates.withIdeFrame()
ideFrameFound = true
return withIdeFrame
}
fun editorActivate(): String {
currentSubContextType = SubType.EDITOR
return "EditorFixture(robot(), $IDE_FRAME_VAL).requestFocus()"
}
fun toolWindowActivate(toolWindowId: String? = null): String {
currentSubContextType = SubType.TOOL_WINDOW
myToolWindowId = toolWindowId
return "ToolWindowFixture(\"$toolWindowId\", $IDE_FRAME_VAL.getProject(), robot()).activate()"
}
fun clear() {
currentSubContextType = null
contextArray.clear()
indentLevel = 0
}
}
|
apache-2.0
|
f4dc13461cc027d988baaa5426580256
| 29.137056 | 139 | 0.650328 | 4.696994 | false | false | false | false |
FHannes/intellij-community
|
platform/script-debugger/protocol/protocol-reader-runtime/src/org/jetbrains/jsonProtocol/OutMessage.kt
|
13
|
6610
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jsonProtocol
import com.google.gson.stream.JsonWriter
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.util.containers.isNullOrEmpty
import com.intellij.util.io.writeUtf8
import gnu.trove.TIntArrayList
import gnu.trove.TIntHashSet
import io.netty.buffer.ByteBuf
import io.netty.buffer.ByteBufAllocator
import io.netty.buffer.ByteBufUtf8Writer
import org.jetbrains.io.JsonUtil
open class OutMessage() {
val buffer: ByteBuf = ByteBufAllocator.DEFAULT.heapBuffer()
val writer = JsonWriter(ByteBufUtf8Writer(buffer))
private var finalized: Boolean = false
init {
writer.beginObject()
}
open fun beginArguments() {
}
fun writeMap(name: String, value: Map<String, String>? = null) {
if (value == null) return
beginArguments()
writer.name(name)
writer.beginObject()
for ((key, value1) in value) {
writer.name(key).value(value1)
}
writer.endObject()
}
protected fun writeLongArray(name: String, value: LongArray) {
beginArguments()
writer.name(name)
writer.beginArray()
for (v in value) {
writer.value(v)
}
writer.endArray()
}
fun writeDoubleArray(name: String, value: DoubleArray) {
beginArguments()
writer.name(name)
writer.beginArray()
for (v in value) {
writer.value(v)
}
writer.endArray()
}
fun writeIntArray(name: String, value: IntArray? = null) {
if (value == null) {
return
}
beginArguments()
writer.name(name)
writer.beginArray()
for (v in value) {
writer.value(v.toLong())
}
writer.endArray()
}
fun writeIntSet(name: String, value: TIntHashSet) {
beginArguments()
writer.name(name)
writer.beginArray()
value.forEach { value ->
writer.value(value.toLong())
true
}
writer.endArray()
}
fun writeIntList(name: String, value: TIntArrayList) {
beginArguments()
writer.name(name)
writer.beginArray()
for (i in 0..value.size() - 1) {
writer.value(value.getQuick(i).toLong())
}
writer.endArray()
}
fun writeSingletonIntArray(name: String, value: Int) {
beginArguments()
writer.name(name)
writer.beginArray()
writer.value(value.toLong())
writer.endArray()
}
fun <E : OutMessage> writeList(name: String, value: List<E>?) {
if (value.isNullOrEmpty()) {
return
}
beginArguments()
writer.name(name)
writer.beginArray()
var isNotFirst = false
for (item in value!!) {
if (isNotFirst) {
buffer.writeByte(','.toInt()).writeByte(' '.toInt())
}
else {
isNotFirst = true
}
if (!item.finalized) {
item.finalized = true
try {
item.writer.endObject()
}
catch (e: IllegalStateException) {
if ("Nesting problem." == e.message) {
throw RuntimeException(item.buffer.toString(CharsetToolkit.UTF8_CHARSET) + "\nparent:\n" + buffer.toString(CharsetToolkit.UTF8_CHARSET), e)
}
else {
throw e
}
}
}
buffer.writeBytes(item.buffer)
}
writer.endArray()
}
fun writeStringList(name: String, value: Collection<String>?) {
if (value == null) return
beginArguments()
JsonWriters.writeStringList(writer, name, value)
}
fun writeEnumList(name: String, values: Collection<Enum<*>>) {
beginArguments()
writer.name(name).beginArray()
for (item in values) {
writer.value(item.toString())
}
writer.endArray()
}
fun writeMessage(name: String, value: OutMessage?) {
if (value == null) {
return
}
beginArguments()
prepareWriteRaw(this, name)
if (!value.finalized) {
value.close()
}
buffer.writeBytes(value.buffer)
}
fun close() {
assert(!finalized)
finalized = true
writer.endObject()
writer.close()
}
protected fun writeLong(name: String, value: Long) {
beginArguments()
writer.name(name).value(value)
}
fun writeString(name: String, value: String?) {
if (value != null) {
writeNullableString(name, value)
}
}
fun writeNullableString(name: String, value: CharSequence?) {
beginArguments()
writer.name(name).value(value?.toString())
}
}
fun prepareWriteRaw(message: OutMessage, name: String) {
message.writer.name(name).nullValue()
val itemBuffer = message.buffer
itemBuffer.writerIndex(itemBuffer.writerIndex() - "null".length)
}
fun doWriteRaw(message: OutMessage, rawValue: String) {
message.buffer.writeUtf8(rawValue)
}
fun OutMessage.writeEnum(name: String, value: Enum<*>?, defaultValue: Enum<*>?) {
if (value != null && value != defaultValue) {
writeEnum(name, value)
}
}
fun OutMessage.writeEnum(name: String, value: Enum<*>) {
beginArguments()
writer.name(name).value(value.toString())
}
fun OutMessage.writeString(name: String, value: CharSequence?, defaultValue: CharSequence?) {
if (value != null && value != defaultValue) {
writeString(name, value)
}
}
fun OutMessage.writeString(name: String, value: CharSequence) {
beginArguments()
prepareWriteRaw(this, name)
JsonUtil.escape(value, buffer)
}
fun OutMessage.writeInt(name: String, value: Int, defaultValue: Int) {
if (value != defaultValue) {
writeInt(name, value)
}
}
fun OutMessage.writeInt(name: String, value: Int) {
beginArguments()
writer.name(name).value(value.toLong())
}
fun OutMessage.writeBoolean(name: String, value: Boolean, defaultValue: Boolean) {
if (value != defaultValue) {
writeBoolean(name, value)
}
}
fun OutMessage.writeBoolean(name: String, value: Boolean) {
beginArguments()
writer.name(name).value(value)
}
fun OutMessage.writeDouble(name: String, value: Double, defaultValue: Double) {
if (value != defaultValue) {
writeDouble(name, value)
}
}
fun OutMessage.writeDouble(name: String, value: Double) {
beginArguments()
writer.name(name).value(value)
}
|
apache-2.0
|
02d6ea1d938f8c17d514b1593c96c20c
| 23.301471 | 151 | 0.659758 | 3.958084 | false | false | false | false |
bravelocation/yeltzland-android
|
app/src/main/java/com/bravelocation/yeltzlandnew/views/FixtureListView.kt
|
1
|
2423
|
package com.bravelocation.yeltzlandnew.views
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.bravelocation.yeltzlandnew.models.FixtureListDataItem
import java.util.*
@Composable
fun FixtureListView(fixtures: LinkedHashMap<String, List<FixtureListDataItem>>, currentMonthIndex: Int = 0) {
val listState = rememberLazyListState()
// Scroll to current month
LaunchedEffect(currentMonthIndex) {
// Scroll to the month before the current month
if (currentMonthIndex > 0 && currentMonthIndex < fixtures.keys.count()) {
Log.d("FixtureListView", "Auto-scrolling to month $currentMonthIndex")
listState.scrollToItem(currentMonthIndex, scrollOffset = -100)
}
}
LazyColumn(
modifier = Modifier
.background(MaterialTheme.colors.background)
.padding(top = 0.dp, start = 8.dp, end = 8.dp, bottom = 56.dp),
verticalArrangement = Arrangement.SpaceBetween,
state = listState
) {
fixtures.map { (month, monthFixtures) ->
item {
FixtureListMonthView(month = month, monthFixtures = monthFixtures)
}
}
}
}
@Preview
@Composable
fun PreviewFixtureListView() {
val model = LinkedHashMap<String, List<FixtureListDataItem>>()
model["October 2020"] = listOf(makeTextFixture())
model["November 2020"] = listOf(makeTextFixture(), makeTextFixture())
FixtureListView(model)
}
fun makeTextFixture(): FixtureListDataItem {
val cal = Calendar.getInstance()
cal[Calendar.YEAR] = 2020
cal[Calendar.MONTH] = 10 - 1
cal[Calendar.DAY_OF_MONTH] = 17
cal[Calendar.HOUR] = 15
cal[Calendar.MINUTE] = 0
val matchDate = cal.time
return FixtureListDataItem(
fixtureDate = matchDate,
opponent = "Kidderminster Harriers (FAC 1QR)",
home = true,
teamScore = 2,
opponentScore = 0
)
}
|
mit
|
7b57776b006e7522f8275ebf53a7d581
| 32.205479 | 109 | 0.707388 | 4.429616 | false | false | false | false |
ansman/okhttp
|
okhttp/src/main/kotlin/okhttp3/internal/concurrent/TaskLogger.kt
|
3
|
2589
|
/*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.concurrent
import java.util.logging.Level
internal inline fun taskLog(
task: Task,
queue: TaskQueue,
messageBlock: () -> String
) {
if (TaskRunner.logger.isLoggable(Level.FINE)) {
log(task, queue, messageBlock())
}
}
internal inline fun <T> logElapsed(
task: Task,
queue: TaskQueue,
block: () -> T
): T {
var startNs = -1L
val loggingEnabled = TaskRunner.logger.isLoggable(Level.FINE)
if (loggingEnabled) {
startNs = queue.taskRunner.backend.nanoTime()
log(task, queue, "starting")
}
var completedNormally = false
try {
val result = block()
completedNormally = true
return result
} finally {
if (loggingEnabled) {
val elapsedNs = queue.taskRunner.backend.nanoTime() - startNs
if (completedNormally) {
log(task, queue, "finished run in ${formatDuration(elapsedNs)}")
} else {
log(task, queue, "failed a run in ${formatDuration(elapsedNs)}")
}
}
}
}
private fun log(task: Task, queue: TaskQueue, message: String) {
TaskRunner.logger.fine("${queue.name} ${String.format("%-22s", message)}: ${task.name}")
}
/**
* Returns a duration in the nearest whole-number units like "999 µs" or " 1 s ". This rounds 0.5
* units away from 0 and 0.499 towards 0. The smallest unit this returns is "µs"; the largest unit
* it returns is "s". For values in [-499..499] this returns " 0 µs".
*
* The returned string attempts to be column-aligned to 6 characters. For negative and large values
* the returned string may be longer.
*/
fun formatDuration(ns: Long): String {
val s = when {
ns <= -999_500_000 -> "${(ns - 500_000_000) / 1_000_000_000} s "
ns <= -999_500 -> "${(ns - 500_000) / 1_000_000} ms"
ns <= 0 -> "${(ns - 500) / 1_000} µs"
ns < 999_500 -> "${(ns + 500) / 1_000} µs"
ns < 999_500_000 -> "${(ns + 500_000) / 1_000_000} ms"
else -> "${(ns + 500_000_000) / 1_000_000_000} s "
}
return String.format("%6s", s)
}
|
apache-2.0
|
24e0a8fa4ec7939d48dd317418f74c84
| 30.901235 | 99 | 0.651703 | 3.440746 | false | false | false | false |
jospint/Architecture-Components-DroidDevs
|
ArchitectureComponents/app/src/main/java/com/jospint/droiddevs/architecturecomponents/data/googlemaps/model/GeocodeModels.kt
|
1
|
1158
|
package com.jospint.droiddevs.architecturecomponents.data.googlemaps.model
import com.squareup.moshi.Json
import paperparcel.PaperParcel
import paperparcel.PaperParcelable
@PaperParcel
data class GeocodeResponse(
val results: List<GeocodeResult>?,
val status: String?) : PaperParcelable {
companion object {
@JvmField val CREATOR = PaperParcelGeocodeResponse.CREATOR
}
}
@PaperParcel
data class GeocodeResult(
@Json(name = "address_components") val addressComponents: List<AddressComponent>?,
@Json(name = "formatted_address") val formattedAddress: String?,
val geometry: Geometry?,
@Json(name = "place_id") val placeId: String?,
val types: List<String>?) : PaperParcelable {
companion object {
@JvmField val CREATOR = PaperParcelGeocodeResult.CREATOR
}
}
@PaperParcel
data class AddressComponent(
@Json(name = "long_name") val longName: String?,
@Json(name = "short_name") val shortName: String?,
val types: List<String>?) : PaperParcelable {
companion object {
@JvmField val CREATOR = PaperParcelAddressComponent.CREATOR
}
}
|
apache-2.0
|
5f7abd4f0db6058db782549d154f7a10
| 31.194444 | 90 | 0.698618 | 4.559055 | false | false | false | false |
sys1yagi/mastodon4j
|
mastodon4j/src/main/java/com/sys1yagi/mastodon4j/api/Link.kt
|
1
|
1257
|
package com.sys1yagi.mastodon4j.api
class Link(
val linkHeader: String,
val nextPath: String,
val prevPath: String,
val maxId: Long,
val sinceId: Long
) {
companion object {
@JvmStatic
fun parse(linkHeader: String?): Link? {
return linkHeader?.let {
val links = it.split(",")
val nextRel = ".*max_id=([0-9]+).*rel=\"next\"".toRegex()
val prevRel = ".*since_id=([0-9]+).*rel=\"prev\"".toRegex()
var nextPath = ""
var maxId = 0L
var prevPath = ""
var sinceId = 0L
links.forEach {
val link = it.trim()
nextRel.matchEntire(link)?.let {
nextPath = it.value.replace("; rel=\"next\"", "")
maxId = it.groupValues.get(1).toLong()
}
prevRel.matchEntire(link)?.let {
prevPath = it.value.replace("; rel=\"prev\"", "")
sinceId = it.groupValues.get(1).toLong()
}
}
Link(it, nextPath, prevPath, maxId, sinceId)
}
}
}
}
|
mit
|
347cbdaef04a6a4967294217b9da8358
| 33 | 75 | 0.428003 | 4.761364 | false | false | false | false |
JDA-Applications/Kotlin-JDA
|
src/examples/kotlin/Runner.kt
|
1
|
2420
|
/*
* Copyright 2016 - 2017 Florian Spieß
*
* 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.
*/
import club.minnced.kjda.*
import club.minnced.kjda.entities.sendAsync
import net.dv8tion.jda.core.AccountType.BOT
import net.dv8tion.jda.core.OnlineStatus.DO_NOT_DISTURB
import net.dv8tion.jda.core.events.ReadyEvent
import net.dv8tion.jda.core.events.message.MessageReceivedEvent
import net.dv8tion.jda.core.hooks.EventListener
import net.dv8tion.jda.core.hooks.ListenerAdapter
import java.io.File
import java.util.concurrent.TimeUnit.SECONDS
fun main(args: Array<String>) {
client(BOT) {
token { File(".token").readText() }
game {
"Powered by Kotlin-JDA"
}
status { DO_NOT_DISTURB }
this += Runner()
this += EventListener {
if (it is ReadyEvent)
println("Dab!!!")
}
httpSettings {
connectTimeout(2, SECONDS)
readTimeout(3, SECONDS)
writeTimeout(2, SECONDS)
}
websocketSettings {
connectionTimeout = SECONDS.toMillis(1).toInt()
}
}
}
class Runner : ListenerAdapter() {
override fun onMessageReceived(event: MessageReceivedEvent) {
if (event.author.isBot || event.author == event.jda.selfUser)
return
val start = System.currentTimeMillis()
event.channel.sendTyping().onlyIf(event.message.rawContent == ".ping") {
event.channel.sendAsync {
this += "Ping"
embed {
field {
name = "Time"
value = (System.currentTimeMillis() - start).toString()
}
}
} then {
println("Sent Ping response! [${it?.embeds?.firstOrNull()?.fields?.first()?.value}]")
} catch { it?.printStackTrace() }
}
}
}
|
apache-2.0
|
9e995f54adc0b143e4b8518a0b1ed30d
| 31.253333 | 101 | 0.613063 | 4.342908 | false | false | false | false |
aglne/mycollab
|
mycollab-web/src/main/java/com/mycollab/module/user/ui/SettingUIConstants.kt
|
3
|
1093
|
/**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.user.ui
/**
* @author MyCollab Ltd.
* @since 5.0.0
*/
object SettingUIConstants {
const val PROFILE = "Profile"
const val BILLING = "Billing"
const val SETTING = "Settings"
const val USERS = "Users"
const val ROLES = "Roles"
const val GENERAL_SETTING = "General-Settings"
const val THEME_CUSTOMIZE = "Theme-Customization"
}
|
agpl-3.0
|
0d3d619b353a05e909495c3d37184c59
| 28.513514 | 78 | 0.714286 | 4.05948 | false | false | false | false |
olonho/carkot
|
car_srv/kotlinSrv/src/McState.kt
|
1
|
574
|
class McState : MCConnectObserver<String> {
val VENDORID = "0483"
val MODELID = "5740"
private var connected = false
private var transportFileName = ""
init {
McConditionMonitor.instance.addObserver(this)
}
fun isConnected(): Boolean {
return connected
}
override fun connect(transportFileName: String) {
this.transportFileName = transportFileName
connected = true
}
override fun disconnect() {
connected = false
}
companion object {
val instance = McState()
}
}
|
mit
|
6f13b34083440c3fac2ddbdaaac529dd
| 18.166667 | 53 | 0.620209 | 4.704918 | false | false | false | false |
REBOOTERS/AndroidAnimationExercise
|
imitate/src/main/java/com/engineer/imitate/ui/widget/more/DZStickyNavLayouts.kt
|
1
|
7667
|
package com.engineer.imitate.ui.widget.more
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.view.animation.Transformation
import android.widget.LinearLayout
import androidx.core.view.NestedScrollingParent
import androidx.core.view.NestedScrollingParentHelper
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.RecyclerView
import com.engineer.imitate.util.dp
class DZStickyNavLayouts(
context: Context,
attrs: AttributeSet?
) : LinearLayout(context, attrs), NestedScrollingParent {
private val mParentHelper: NestedScrollingParentHelper
private val mHeaderView: View
private val mFooterView: AnimatorView
private var mChildView: RecyclerView? = null
// 解决多点触控问题
private var isRunAnim = false
interface OnStartActivityListener {
fun onStart()
}
private var mLinster: OnStartActivityListener? = null
fun setOnStartActivity(l: OnStartActivityListener?) {
mLinster = l
}
override fun onFinishInflate() {
Log.d(TAG, "onFinishInflate() called");
super.onFinishInflate()
orientation = HORIZONTAL
Log.d(TAG, ": $childCount")
Log.d(TAG, ": $maxWidth")
if (getChildAt(0) is RecyclerView) {
mChildView = getChildAt(0) as RecyclerView
val layoutParams = LayoutParams(
maxWidth,
LayoutParams.WRAP_CONTENT
)
addView(mHeaderView, 0, layoutParams)
addView(mFooterView, childCount, layoutParams)
// 左移
scrollBy(maxWidth, 0)
mChildView!!.setOnTouchListener { v, event -> // 保证动画状态中 子view不能滑动
isRunAnim
}
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
// Log.d(TAG, "onMeasure() called")
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (mChildView != null) {
val params = mChildView!!.layoutParams
params.width = measuredWidth
}
}
/**
* @param dx 水平滑动距离
* @param dy 垂直滑动距离
* @param consumed 父类消耗掉的距离
*/
@SuppressLint("LogNotTimber")
override fun onNestedPreScroll(
target: View,
dx: Int,
dy: Int,
consumed: IntArray
) {
parent.requestDisallowInterceptTouchEvent(true)
Log.d(TAG, "onNestedPreScroll() called scrollX = $scrollX")
// dx>0 往左滑动 dx<0往右滑动
Log.d(TAG, "dx=" + dx + ",getScrollX=" + scrollX +
",canScrollHorizontally=" + !target.canScrollHorizontally(1))
val hiddenLeft =
dx > 0 && scrollX < maxWidth && !target.canScrollHorizontally(-1)
val showLeft =
dx < 0 && !target.canScrollHorizontally( -1)
val hiddenRight =
dx < 0 && scrollX > maxWidth && !target.canScrollHorizontally(1)
val showRight =
dx > 0 && !target.canScrollHorizontally(1)
Log.d(TAG,"showRight = $showRight, hideRight = $hiddenRight")
if (hiddenLeft || hiddenRight || showRight) {
scrollBy(dx / DRAG, 0)
consumed[0] = dx
}
if (hiddenRight || showRight) {
mFooterView.setRefresh(dx / DRAG)
}
// 限制错位问题
if (dx > 0 && scrollX > maxWidth && !target.canScrollHorizontally(-1)) {
scrollTo(maxWidth, 0)
}
if (dx < 0 && scrollX < maxWidth && !target.canScrollHorizontally(1)) {
scrollTo(maxWidth, 0)
}
}
/**
* 必须要复写 onStartNestedScroll后调用
*/
override fun onNestedScrollAccepted(
child: View,
target: View,
axes: Int
) {
Log.d(TAG, "onNestedScrollAccepted() called scrollX = $scrollX")
mParentHelper.onNestedScrollAccepted(child, target, axes)
}
/**
* 返回true代表处理本次事件
* 在执行动画时间里不能处理本次事件
*/
override fun onStartNestedScroll(
child: View,
target: View,
nestedScrollAxes: Int
): Boolean {
Log.d(TAG, "onStartNestedScroll() called scrollX = $scrollX")
return target is RecyclerView && !isRunAnim
}
/**
* 复位初始位置
* scrollTo 移动到指定坐标
* scrollBy 在原有坐标上面移动
*/
override fun onStopNestedScroll(target: View) {
mParentHelper.onStopNestedScroll(target)
Log.d(TAG, "onStopNestedScroll() called scrollX = " + scrollX)
// 如果不在RecyclerView滑动范围内
if (maxWidth != scrollX) {
startAnimation(ProgressAnimation())
}
if (scrollX > maxWidth + maxWidth / 2 && mLinster != null) {
mLinster!!.onStart()
}
}
/**
* 回弹动画
*/
private inner class ProgressAnimation : Animation() {
override fun applyTransformation(
interpolatedTime: Float,
t: Transformation
) {
scrollBy(
((maxWidth - scrollX) * interpolatedTime).toInt(),
0
)
if (interpolatedTime == 1f) {
isRunAnim = false
mFooterView.setRelease()
}
}
override fun initialize(
width: Int,
height: Int,
parentWidth: Int,
parentHeight: Int
) {
super.initialize(width, height, parentWidth, parentHeight)
duration = 300
interpolator = AccelerateInterpolator()
}
init {
isRunAnim = true
}
}
override fun onNestedScroll(
target: View,
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int
) {
}
override fun onNestedFling(
target: View,
velocityX: Float,
velocityY: Float,
consumed: Boolean
): Boolean {
return false
}
/**
* 子view是否可以有惯性 解决右滑时快速左滑显示错位问题
*
* @return true不可以 false可以
*/
override fun onNestedPreFling(
target: View,
velocityX: Float,
velocityY: Float
): Boolean {
// 当RecyclerView在界面之内交给它自己惯性滑动
return scrollX != maxWidth
}
override fun getNestedScrollAxes(): Int {
return 0
}
/**
* 限制滑动 移动x轴不能超出最大范围
*/
override fun scrollTo(x: Int, y: Int) {
var x = x
if (x < 0) {
x = 0
} else if (x > maxWidth * 2) {
x = maxWidth * 2
}
super.scrollTo(x, y)
}
private fun dp2Px(context: Context, dp: Float): Int {
val scale = context.resources.displayMetrics.density
return (dp * scale + 0.5f).toInt()
}
companion object {
@JvmField
var maxWidth = 0
private const val DRAG = 2
val TAG = "tag"
}
init {
mHeaderView = View(context)
mHeaderView.setBackgroundColor(-0x1)
mFooterView = AnimatorView(context)
mFooterView.setBackgroundColor(Color.TRANSPARENT)
maxWidth = 60.dp
mParentHelper = NestedScrollingParentHelper(this)
}
}
|
apache-2.0
|
cfd88b150ab8e7c23211dfb67893e9c9
| 26.554717 | 81 | 0.582523 | 4.520743 | false | false | false | false |
openHPI/android-app
|
app/src/main/java/de/xikolo/utils/extensions/IntentExtensions.kt
|
1
|
4528
|
package de.xikolo.utils.extensions
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.Intent.ACTION_GET_CONTENT
import android.content.Intent.ACTION_VIEW
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Browser
import androidx.fragment.app.FragmentActivity
import de.xikolo.App
import de.xikolo.R
import de.xikolo.config.Config
import de.xikolo.controllers.dialogs.UnsupportedIntentDialog
import de.xikolo.controllers.dialogs.UnsupportedIntentDialogAutoBundle
import de.xikolo.utils.FileProviderUtil
import java.io.File
fun <T : Intent> T.createChooser(
context: Context,
title: String? = null,
packagesToHide: Array<String> = emptyArray()
): Intent? {
val resolveInfos = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
context.packageManager.queryIntentActivities(this, PackageManager.MATCH_ALL)
} else {
context.packageManager.queryIntentActivities(this, 0)
}
val intents = resolveInfos
.distinctBy {
it.activityInfo.packageName
}
.filter {
!packagesToHide.contains(it.activityInfo.packageName)
}
.map {
val intent = Intent(this)
intent.component = ComponentName(it.activityInfo.packageName, it.activityInfo.name)
intent.setPackage(it.activityInfo.packageName)
intent
}
.toMutableList()
return try {
val chooserIntent = Intent.createChooser(intents.removeAt(0), title)
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toTypedArray())
chooserIntent
} catch (e: IndexOutOfBoundsException) {
null
}
}
private fun <T : Intent> T.open(
activity: FragmentActivity,
forceChooser: Boolean,
parentFile: File? = null
): Boolean {
val chooserIntent = createChooser(App.instance)
fun startActivity(): Boolean {
return try {
activity.startActivity(
if (forceChooser) {
chooserIntent
} else {
this
}?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
true
} catch (e: Exception) {
activity.showToast(R.string.error_plain)
false
}
}
return if (chooserIntent == null) {
val dialog = UnsupportedIntentDialogAutoBundle.builder()
.apply {
if (parentFile != null) {
fileMimeType(type)
}
}
.build()
dialog.listener = object : UnsupportedIntentDialog.Listener {
override fun onOpenPathClicked() {
try {
val fileManagerIntent = Intent(ACTION_GET_CONTENT)
fileManagerIntent.setDataAndType(
FileProviderUtil.getUriForFile(
parentFile!!
),
"vnd.android.document/directory"
)
fileManagerIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
activity.startActivity(fileManagerIntent)
} catch (e: Exception) {
activity.showToast(R.string.dialog_unsupported_intent_error_no_file_manager)
}
}
override fun onOpenAnywayClicked() {
startActivity()
}
}
dialog.show(activity.supportFragmentManager, UnsupportedIntentDialog.TAG)
false
} else {
startActivity()
}
}
fun <T : File> T.open(
activity: FragmentActivity,
mimeType: String,
forceChooser: Boolean
): Boolean {
val target = Intent(ACTION_VIEW)
target.setDataAndType(FileProviderUtil.getUriForFile(this), mimeType)
target.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
target.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
return target.open(activity, forceChooser, parentFile)
}
fun <T : FragmentActivity> T.openUrl(url: String): Boolean {
val uri = try {
Uri.parse(url)
} catch (e: Exception) {
return false
}
return Intent(ACTION_VIEW, uri).open(this, false)
}
fun <T : Intent> T.includeAuthToken(token: String) {
val headers = Bundle()
headers.putString(Config.HEADER_AUTH, Config.HEADER_AUTH_VALUE_PREFIX + token)
putExtra(Browser.EXTRA_HEADERS, headers)
}
|
bsd-3-clause
|
3976f6e85cfe33377ee6db35d81bc05f
| 31.113475 | 96 | 0.623454 | 4.701973 | false | false | false | false |
kesco/SlideBack-Xposed
|
app/src/main/kotlin/com/kesco/adk/rx/HandlerScheduler.kt
|
1
|
1416
|
package com.kesco.adk.rx
import android.os.Handler
import rx.Scheduler
import rx.Subscription
import rx.functions.Action0
import rx.internal.schedulers.ScheduledAction
import rx.subscriptions.CompositeSubscription
import rx.subscriptions.Subscriptions
import java.util.concurrent.TimeUnit
public class HandlerScheduler(val handler: Handler) : Scheduler() {
override fun createWorker(): Scheduler.Worker = HandlerWorker(handler)
class HandlerWorker(val handler: Handler) : Scheduler.Worker() {
private val subscriptions = CompositeSubscription()
override fun unsubscribe() = subscriptions.unsubscribe()
override fun isUnsubscribed(): Boolean = subscriptions.isUnsubscribed
override fun schedule(action: Action0): Subscription = schedule(action, 0L, TimeUnit.MILLISECONDS)
override fun schedule(action: Action0, delayTime: Long, unit: TimeUnit): Subscription {
if (subscriptions.isUnsubscribed) {
return Subscriptions.unsubscribed()
}
val scheduledAction = ScheduledAction(action)
scheduledAction.addParent(subscriptions)
subscriptions.add(scheduledAction)
handler.postDelayed(scheduledAction, unit.toMillis(delayTime))
scheduledAction.add(Subscriptions.create { handler.removeCallbacks(scheduledAction) })
return scheduledAction
}
}
}
|
mit
|
a2ab307bbcfbff343cdcca801a9411e8
| 35.307692 | 106 | 0.725282 | 5.186813 | false | false | false | false |
Setekh/Gleipnir-Graphics
|
src/main/kotlin/eu/corvus/corax/platforms/desktop/assets/loaders/AssimpLoader.kt
|
1
|
4362
|
/**
* Copyright (c) 2013-2019 Corvus Corax Entertainment
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of Corvus Corax Entertainment nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package eu.corvus.corax.platforms.desktop.assets.loaders
import eu.corvus.corax.app.storage.StorageAccess
import eu.corvus.corax.scene.Object
import eu.corvus.corax.scene.Spatial
import eu.corvus.corax.scene.assets.AssetManager
import eu.corvus.corax.scene.geometry.Mesh
import org.lwjgl.assimp.AIMesh
import org.lwjgl.assimp.Assimp.*
import org.lwjgl.system.MemoryUtil
/**
* @author Vlad Ravenholm on 12/28/2019
*/
class AssimpLoader : AssetManager.AssetLoader {
override suspend fun load(assetManager: AssetManager, storageAccess: StorageAccess, path: String): Object {
val spatial = Spatial(path)
storageAccess.readFrom(path) {
val alloc = MemoryUtil.memAlloc(it.available())
alloc.put(it.readBytes()).flip()
val suffix = path.substringAfterLast('.')
val aiScene = aiImportFileFromMemory(alloc,
aiProcess_JoinIdenticalVertices or aiProcess_Triangulate or aiProcess_FixInfacingNormals or aiProcess_CalcTangentSpace,
suffix
) ?: error("Failed loading asset $path!")
val numMeshes = aiScene.mNumMeshes()
val aiMeshes = aiScene.mMeshes()!!
repeat(numMeshes) { index ->
val aiMesh = AIMesh.create(aiMeshes.get(index))
val vertexes = aiMesh.getVertices()
val texCoords = aiMesh.getTexCoords()
val normals = aiMesh.getNormals()
val tangents = aiMesh.getTangents()
val bitangents = aiMesh.getBitangents()
val indices = aiMesh.getIndices()
val geometry = Mesh(aiMesh.mName().dataString())
geometry.createMesh(vertexes, indices, texCoords, normals, tangents, bitangents)
geometry.forceUpdate()
spatial.appendChild(geometry)
}
MemoryUtil.memFree(alloc)
}
return spatial
}
}
fun AIMesh.getVertices(): FloatArray = mVertices().map { listOf(it.x(), it.y(), it.z()) }.flatten().toFloatArray()
fun AIMesh.getTexCoords(): FloatArray? = mTextureCoords(0)?.map { listOf(it.x(), it.y()) }?.flatten()?.toFloatArray()
fun AIMesh.getNormals(): FloatArray? = mNormals()?.map { listOf(it.x(), it.y(), it.z()) }?.flatten()?.toFloatArray()
fun AIMesh.getTangents(): FloatArray? = mTangents()?.map { listOf(it.x(), it.y(), it.z()) }?.flatten()?.toFloatArray()
fun AIMesh.getBitangents(): FloatArray? = mBitangents()?.map { listOf(it.x(), it.y(), it.z()) }?.flatten()?.toFloatArray()
fun AIMesh.getIndices(): IntArray = mFaces().map {
val collect = mutableListOf<Int>()
val mIndices = it.mIndices()
while (mIndices.remaining() > 0)
collect.add(mIndices.get())
collect
}.flatten().toIntArray()
|
bsd-3-clause
|
f2ff15fa17845895200bf7df0e6ddb5e
| 44.447917 | 135 | 0.691655 | 4.492276 | false | false | false | false |
Logout22/fonefwd
|
app/src/androidTest/java/de/nebensinn/fonefwd/ViewRulesActivityTest.kt
|
1
|
1396
|
package de.nebensinn.fonefwd
import android.content.Intent
import android.support.test.filters.MediumTest
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import android.support.v7.widget.RecyclerView
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
val ForwardRule = Rule("param1", "param2")
@MediumTest
@RunWith(AndroidJUnit4::class)
class ViewRulesActivityTest {
class MyActivityTestRule : ActivityTestRule<ViewRulesActivity>(ViewRulesActivity::class.java) {
override fun getActivityIntent(): Intent {
val initialIntent = super.getActivityIntent()
initialIntent.putExtra(VIEWRULES_EXTRA_NEWRULE, ForwardRule)
return initialIntent
}
}
@get:Rule
val activityTestRule = MyActivityTestRule()
@Test
fun shouldAddRuleWhenStartedInAddRuleMode() {
val rulesView = activityTestRule.activity.findViewById(R.id.rulesView) as RecyclerView
val adapter = rulesView.adapter
assertEquals(1, adapter.itemCount)
val firstViewHolder =
rulesView.findViewHolderForAdapterPosition(0) as RulesViewHolder
assertEquals("When on param1, forward to param2", firstViewHolder.ruleLabel.text)
// TODO: add rule to shared preferences and update mainactivity
}
}
|
gpl-3.0
|
345dfd3bc2e1e76da1d6e52d325a42b3
| 34.820513 | 99 | 0.747135 | 4.532468 | false | true | false | false |
cashapp/sqldelight
|
drivers/native-driver/src/mingwMain/kotlin/app/cash/sqldelight/driver/native/util/PoolLock.kt
|
1
|
2623
|
package app.cash.sqldelight.driver.native.util
import co.touchlab.stately.concurrency.AtomicBoolean
import kotlinx.cinterop.alloc
import kotlinx.cinterop.free
import kotlinx.cinterop.nativeHeap
import kotlinx.cinterop.ptr
import platform.posix.PTHREAD_MUTEX_RECURSIVE
import platform.posix.pthread_cond_destroy
import platform.posix.pthread_cond_init
import platform.posix.pthread_cond_signal
import platform.posix.pthread_cond_tVar
import platform.posix.pthread_cond_wait
import platform.posix.pthread_mutex_destroy
import platform.posix.pthread_mutex_init
import platform.posix.pthread_mutex_lock
import platform.posix.pthread_mutex_tVar
import platform.posix.pthread_mutex_unlock
import platform.posix.pthread_mutexattr_destroy
import platform.posix.pthread_mutexattr_init
import platform.posix.pthread_mutexattr_settype
import platform.posix.pthread_mutexattr_tVar
internal actual class PoolLock actual constructor(reentrant: Boolean) {
private val isActive = AtomicBoolean(true)
private val attr = nativeHeap.alloc<pthread_mutexattr_tVar>()
.apply {
pthread_mutexattr_init(ptr)
if (reentrant) {
pthread_mutexattr_settype(ptr, PTHREAD_MUTEX_RECURSIVE.toInt())
}
}
private val mutex = nativeHeap.alloc<pthread_mutex_tVar>()
.apply { pthread_mutex_init(ptr, attr.ptr) }
private val cond = nativeHeap.alloc<pthread_cond_tVar>()
.apply { pthread_cond_init(ptr, null) }
actual fun <R> withLock(
action: CriticalSection.() -> R,
): R {
check(isActive.value)
pthread_mutex_lock(mutex.ptr)
val result: R
try {
result = action(CriticalSection())
} finally {
pthread_mutex_unlock(mutex.ptr)
}
return result
}
actual fun notifyConditionChanged() {
pthread_cond_signal(cond.ptr)
}
actual fun close(): Boolean {
if (isActive.compareAndSet(expected = true, new = false)) {
pthread_cond_destroy(cond.ptr)
pthread_mutex_destroy(mutex.ptr)
pthread_mutexattr_destroy(attr.ptr)
nativeHeap.free(cond)
nativeHeap.free(mutex)
nativeHeap.free(attr)
return true
}
return false
}
actual inner class CriticalSection {
actual fun <R> loopForConditionalResult(block: () -> R?): R {
check(isActive.value)
var result = block()
while (result == null) {
pthread_cond_wait(cond.ptr, mutex.ptr)
result = block()
}
return result
}
actual fun loopUntilConditionalResult(block: () -> Boolean) {
check(isActive.value)
while (!block()) {
pthread_cond_wait(cond.ptr, mutex.ptr)
}
}
}
}
|
apache-2.0
|
ac7aecedf47b7ae6a59a64c15cfcb269
| 26.610526 | 71 | 0.707205 | 3.868732 | false | false | false | false |
vanita5/twittnuker
|
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/EntityArrays.kt
|
1
|
24984
|
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util
import java.util.*
/**
* Class holding various entity data for HTML and XML - generally for use with
* the LookupTranslator.
* All Maps are generated using `java.util.Collections.unmodifiableMap()`.
*
* @since 1.0
*/
object EntityArrays {
/**
* A Map<CharSequence, CharSequence> to to escape
* [ISO-8859-1](https://secure.wikimedia.org/wikipedia/en/wiki/ISO/IEC_8859-1)
* characters to their named HTML 3.x equivalents.
*/
val ISO8859_1_ESCAPE: Map<CharSequence, CharSequence> = mapOf(
"\u00A0" to " ", // non-breaking space
"\u00A1" to "¡", // inverted exclamation mark
"\u00A2" to "¢", // cent sign
"\u00A3" to "£", // pound sign
"\u00A4" to "¤", // currency sign
"\u00A5" to "¥", // yen sign = yuan sign
"\u00A6" to "¦", // broken bar = broken vertical bar
"\u00A7" to "§", // section sign
"\u00A8" to "¨", // diaeresis = spacing diaeresis
"\u00A9" to "©", // © - copyright sign
"\u00AA" to "ª", // feminine ordinal indicator
"\u00AB" to "«", // left-pointing double angle quotation mark = left pointing guillemet
"\u00AC" to "¬", // not sign
"\u00AD" to "­", // soft hyphen = discretionary hyphen
"\u00AE" to "®", // ® - registered trademark sign
"\u00AF" to "¯", // macron = spacing macron = overline = APL overbar
"\u00B0" to "°", // degree sign
"\u00B1" to "±", // plus-minus sign = plus-or-minus sign
"\u00B2" to "²", // superscript two = superscript digit two = squared
"\u00B3" to "³", // superscript three = superscript digit three = cubed
"\u00B4" to "´", // acute accent = spacing acute
"\u00B5" to "µ", // micro sign
"\u00B6" to "¶", // pilcrow sign = paragraph sign
"\u00B7" to "·", // middle dot = Georgian comma = Greek middle dot
"\u00B8" to "¸", // cedilla = spacing cedilla
"\u00B9" to "¹", // superscript one = superscript digit one
"\u00BA" to "º", // masculine ordinal indicator
"\u00BB" to "»", // right-pointing double angle quotation mark = right pointing guillemet
"\u00BC" to "¼", // vulgar fraction one quarter = fraction one quarter
"\u00BD" to "½", // vulgar fraction one half = fraction one half
"\u00BE" to "¾", // vulgar fraction three quarters = fraction three quarters
"\u00BF" to "¿", // inverted question mark = turned question mark
"\u00C0" to "À", // À - uppercase A, grave accent
"\u00C1" to "Á", // Á - uppercase A, acute accent
"\u00C2" to "Â", // Â - uppercase A, circumflex accent
"\u00C3" to "Ã", // Ã - uppercase A, tilde
"\u00C4" to "Ä", // Ä - uppercase A, umlaut
"\u00C5" to "Å", // Å - uppercase A, ring
"\u00C6" to "Æ", // Æ - uppercase AE
"\u00C7" to "Ç", // Ç - uppercase C, cedilla
"\u00C8" to "È", // È - uppercase E, grave accent
"\u00C9" to "É", // É - uppercase E, acute accent
"\u00CA" to "Ê", // Ê - uppercase E, circumflex accent
"\u00CB" to "Ë", // Ë - uppercase E, umlaut
"\u00CC" to "Ì", // Ì - uppercase I, grave accent
"\u00CD" to "Í", // Í - uppercase I, acute accent
"\u00CE" to "Î", // Î - uppercase I, circumflex accent
"\u00CF" to "Ï", // Ï - uppercase I, umlaut
"\u00D0" to "Ð", // Ð - uppercase Eth, Icelandic
"\u00D1" to "Ñ", // Ñ - uppercase N, tilde
"\u00D2" to "Ò", // Ò - uppercase O, grave accent
"\u00D3" to "Ó", // Ó - uppercase O, acute accent
"\u00D4" to "Ô", // Ô - uppercase O, circumflex accent
"\u00D5" to "Õ", // Õ - uppercase O, tilde
"\u00D6" to "Ö", // Ö - uppercase O, umlaut
"\u00D7" to "×", // multiplication sign
"\u00D8" to "Ø", // Ø - uppercase O, slash
"\u00D9" to "Ù", // Ù - uppercase U, grave accent
"\u00DA" to "Ú", // Ú - uppercase U, acute accent
"\u00DB" to "Û", // Û - uppercase U, circumflex accent
"\u00DC" to "Ü", // Ü - uppercase U, umlaut
"\u00DD" to "Ý", // Ý - uppercase Y, acute accent
"\u00DE" to "Þ", // Þ - uppercase THORN, Icelandic
"\u00DF" to "ß", // ß - lowercase sharps, German
"\u00E0" to "à", // à - lowercase a, grave accent
"\u00E1" to "á", // á - lowercase a, acute accent
"\u00E2" to "â", // â - lowercase a, circumflex accent
"\u00E3" to "ã", // ã - lowercase a, tilde
"\u00E4" to "ä", // ä - lowercase a, umlaut
"\u00E5" to "å", // å - lowercase a, ring
"\u00E6" to "æ", // æ - lowercase ae
"\u00E7" to "ç", // ç - lowercase c, cedilla
"\u00E8" to "è", // è - lowercase e, grave accent
"\u00E9" to "é", // é - lowercase e, acute accent
"\u00EA" to "ê", // ê - lowercase e, circumflex accent
"\u00EB" to "ë", // ë - lowercase e, umlaut
"\u00EC" to "ì", // ì - lowercase i, grave accent
"\u00ED" to "í", // í - lowercase i, acute accent
"\u00EE" to "î", // î - lowercase i, circumflex accent
"\u00EF" to "ï", // ï - lowercase i, umlaut
"\u00F0" to "ð", // ð - lowercase eth, Icelandic
"\u00F1" to "ñ", // ñ - lowercase n, tilde
"\u00F2" to "ò", // ò - lowercase o, grave accent
"\u00F3" to "ó", // ó - lowercase o, acute accent
"\u00F4" to "ô", // ô - lowercase o, circumflex accent
"\u00F5" to "õ", // õ - lowercase o, tilde
"\u00F6" to "ö", // ö - lowercase o, umlaut
"\u00F7" to "÷", // division sign
"\u00F8" to "ø", // ø - lowercase o, slash
"\u00F9" to "ù", // ù - lowercase u, grave accent
"\u00FA" to "ú", // ú - lowercase u, acute accent
"\u00FB" to "û", // û - lowercase u, circumflex accent
"\u00FC" to "ü", // ü - lowercase u, umlaut
"\u00FD" to "ý", // ý - lowercase y, acute accent
"\u00FE" to "þ", // þ - lowercase thorn, Icelandic
"\u00FF" to "ÿ" // ÿ - lowercase y, umlaut
)
/**
* Reverse of [.ISO8859_1_ESCAPE] for unescaping purposes.
*/
val ISO8859_1_UNESCAPE: Map<CharSequence, CharSequence> = ISO8859_1_ESCAPE.invert()
/**
* A Map<CharSequence, CharSequence> to escape additional
* [character entity references](http://www.w3.org/TR/REC-html40/sgml/entities.html).
* Note that this must be used with [.ISO8859_1_ESCAPE] to get the full list of
* HTML 4.0 character entities.
*/
val HTML40_EXTENDED_ESCAPE: Map<CharSequence, CharSequence> = mapOf(
// <!-- Latin Extended-B -->
"\u0192" to "ƒ", // latin small f with hook = function= florin, U+0192 ISOtech -->
// <!-- Greek -->
"\u0391" to "Α", // greek capital letter alpha, U+0391 -->
"\u0392" to "Β", // greek capital letter beta, U+0392 -->
"\u0393" to "Γ", // greek capital letter gamma,U+0393 ISOgrk3 -->
"\u0394" to "Δ", // greek capital letter delta,U+0394 ISOgrk3 -->
"\u0395" to "Ε", // greek capital letter epsilon, U+0395 -->
"\u0396" to "Ζ", // greek capital letter zeta, U+0396 -->
"\u0397" to "Η", // greek capital letter eta, U+0397 -->
"\u0398" to "Θ", // greek capital letter theta,U+0398 ISOgrk3 -->
"\u0399" to "Ι", // greek capital letter iota, U+0399 -->
"\u039A" to "Κ", // greek capital letter kappa, U+039A -->
"\u039B" to "Λ", // greek capital letter lambda,U+039B ISOgrk3 -->
"\u039C" to "Μ", // greek capital letter mu, U+039C -->
"\u039D" to "Ν", // greek capital letter nu, U+039D -->
"\u039E" to "Ξ", // greek capital letter xi, U+039E ISOgrk3 -->
"\u039F" to "Ο", // greek capital letter omicron, U+039F -->
"\u03A0" to "Π", // greek capital letter pi, U+03A0 ISOgrk3 -->
"\u03A1" to "Ρ", // greek capital letter rho, U+03A1 -->
// <!-- there is no Sigmaf, and no U+03A2 character either -->
"\u03A3" to "Σ", // greek capital letter sigma,U+03A3 ISOgrk3 -->
"\u03A4" to "Τ", // greek capital letter tau, U+03A4 -->
"\u03A5" to "Υ", // greek capital letter upsilon,U+03A5 ISOgrk3 -->
"\u03A6" to "Φ", // greek capital letter phi,U+03A6 ISOgrk3 -->
"\u03A7" to "Χ", // greek capital letter chi, U+03A7 -->
"\u03A8" to "Ψ", // greek capital letter psi,U+03A8 ISOgrk3 -->
"\u03A9" to "Ω", // greek capital letter omega,U+03A9 ISOgrk3 -->
"\u03B1" to "α", // greek small letter alpha,U+03B1 ISOgrk3 -->
"\u03B2" to "β", // greek small letter beta, U+03B2 ISOgrk3 -->
"\u03B3" to "γ", // greek small letter gamma,U+03B3 ISOgrk3 -->
"\u03B4" to "δ", // greek small letter delta,U+03B4 ISOgrk3 -->
"\u03B5" to "ε", // greek small letter epsilon,U+03B5 ISOgrk3 -->
"\u03B6" to "ζ", // greek small letter zeta, U+03B6 ISOgrk3 -->
"\u03B7" to "η", // greek small letter eta, U+03B7 ISOgrk3 -->
"\u03B8" to "θ", // greek small letter theta,U+03B8 ISOgrk3 -->
"\u03B9" to "ι", // greek small letter iota, U+03B9 ISOgrk3 -->
"\u03BA" to "κ", // greek small letter kappa,U+03BA ISOgrk3 -->
"\u03BB" to "λ", // greek small letter lambda,U+03BB ISOgrk3 -->
"\u03BC" to "μ", // greek small letter mu, U+03BC ISOgrk3 -->
"\u03BD" to "ν", // greek small letter nu, U+03BD ISOgrk3 -->
"\u03BE" to "ξ", // greek small letter xi, U+03BE ISOgrk3 -->
"\u03BF" to "ο", // greek small letter omicron, U+03BF NEW -->
"\u03C0" to "π", // greek small letter pi, U+03C0 ISOgrk3 -->
"\u03C1" to "ρ", // greek small letter rho, U+03C1 ISOgrk3 -->
"\u03C2" to "ς", // greek small letter final sigma,U+03C2 ISOgrk3 -->
"\u03C3" to "σ", // greek small letter sigma,U+03C3 ISOgrk3 -->
"\u03C4" to "τ", // greek small letter tau, U+03C4 ISOgrk3 -->
"\u03C5" to "υ", // greek small letter upsilon,U+03C5 ISOgrk3 -->
"\u03C6" to "φ", // greek small letter phi, U+03C6 ISOgrk3 -->
"\u03C7" to "χ", // greek small letter chi, U+03C7 ISOgrk3 -->
"\u03C8" to "ψ", // greek small letter psi, U+03C8 ISOgrk3 -->
"\u03C9" to "ω", // greek small letter omega,U+03C9 ISOgrk3 -->
"\u03D1" to "ϑ", // greek small letter theta symbol,U+03D1 NEW -->
"\u03D2" to "ϒ", // greek upsilon with hook symbol,U+03D2 NEW -->
"\u03D6" to "ϖ", // greek pi symbol, U+03D6 ISOgrk3 -->
// <!-- General Punctuation -->
"\u2022" to "•", // bullet = black small circle,U+2022 ISOpub -->
// <!-- bullet is NOT the same as bullet operator, U+2219 -->
"\u2026" to "…", // horizontal ellipsis = three dot leader,U+2026 ISOpub -->
"\u2032" to "′", // prime = minutes = feet, U+2032 ISOtech -->
"\u2033" to "″", // double prime = seconds = inches,U+2033 ISOtech -->
"\u203E" to "‾", // overline = spacing overscore,U+203E NEW -->
"\u2044" to "⁄", // fraction slash, U+2044 NEW -->
// <!-- Letterlike Symbols -->
"\u2118" to "℘", // script capital P = power set= Weierstrass p, U+2118 ISOamso -->
"\u2111" to "ℑ", // blackletter capital I = imaginary part,U+2111 ISOamso -->
"\u211C" to "ℜ", // blackletter capital R = real part symbol,U+211C ISOamso -->
"\u2122" to "™", // trade mark sign, U+2122 ISOnum -->
"\u2135" to "ℵ", // alef symbol = first transfinite cardinal,U+2135 NEW -->
// <!-- alef symbol is NOT the same as hebrew letter alef,U+05D0 although the
// same glyph could be used to depict both characters -->
// <!-- Arrows -->
"\u2190" to "←", // leftwards arrow, U+2190 ISOnum -->
"\u2191" to "↑", // upwards arrow, U+2191 ISOnum-->
"\u2192" to "→", // rightwards arrow, U+2192 ISOnum -->
"\u2193" to "↓", // downwards arrow, U+2193 ISOnum -->
"\u2194" to "↔", // left right arrow, U+2194 ISOamsa -->
"\u21B5" to "↵", // downwards arrow with corner leftwards= carriage return, U+21B5 NEW -->
"\u21D0" to "⇐", // leftwards double arrow, U+21D0 ISOtech -->
// <!-- ISO 10646 does not say that lArr is the same as the 'is implied by'
// arrow but also does not have any other character for that function.
// So ? lArr canbe used for 'is implied by' as ISOtech suggests -->
"\u21D1" to "⇑", // upwards double arrow, U+21D1 ISOamsa -->
"\u21D2" to "⇒", // rightwards double arrow,U+21D2 ISOtech -->
// <!-- ISO 10646 does not say this is the 'implies' character but does not
// have another character with this function so ?rArr can be used for
// 'implies' as ISOtech suggests -->
"\u21D3" to "⇓", // downwards double arrow, U+21D3 ISOamsa -->
"\u21D4" to "⇔", // left right double arrow,U+21D4 ISOamsa -->
// <!-- Mathematical Operators -->
"\u2200" to "∀", // for all, U+2200 ISOtech -->
"\u2202" to "∂", // partial differential, U+2202 ISOtech -->
"\u2203" to "∃", // there exists, U+2203 ISOtech -->
"\u2205" to "∅", // empty set = null set = diameter,U+2205 ISOamso -->
"\u2207" to "∇", // nabla = backward difference,U+2207 ISOtech -->
"\u2208" to "∈", // element of, U+2208 ISOtech -->
"\u2209" to "∉", // not an element of, U+2209 ISOtech -->
"\u220B" to "∋", // contains as member, U+220B ISOtech -->
// <!-- should there be a more memorable name than 'ni'? -->
"\u220F" to "∏", // n-ary product = product sign,U+220F ISOamsb -->
// <!-- prod is NOT the same character as U+03A0 'greek capital letter pi'
// though the same glyph might be used for both -->
"\u2211" to "∑", // n-ary summation, U+2211 ISOamsb -->
// <!-- sum is NOT the same character as U+03A3 'greek capital letter sigma'
// though the same glyph might be used for both -->
"\u2212" to "−", // minus sign, U+2212 ISOtech -->
"\u2217" to "∗", // asterisk operator, U+2217 ISOtech -->
"\u221A" to "√", // square root = radical sign,U+221A ISOtech -->
"\u221D" to "∝", // proportional to, U+221D ISOtech -->
"\u221E" to "∞", // infinity, U+221E ISOtech -->
"\u2220" to "∠", // angle, U+2220 ISOamso -->
"\u2227" to "∧", // logical and = wedge, U+2227 ISOtech -->
"\u2228" to "∨", // logical or = vee, U+2228 ISOtech -->
"\u2229" to "∩", // intersection = cap, U+2229 ISOtech -->
"\u222A" to "∪", // union = cup, U+222A ISOtech -->
"\u222B" to "∫", // integral, U+222B ISOtech -->
"\u2234" to "∴", // therefore, U+2234 ISOtech -->
"\u223C" to "∼", // tilde operator = varies with = similar to,U+223C ISOtech -->
// <!-- tilde operator is NOT the same character as the tilde, U+007E,although
// the same glyph might be used to represent both -->
"\u2245" to "≅", // approximately equal to, U+2245 ISOtech -->
"\u2248" to "≈", // almost equal to = asymptotic to,U+2248 ISOamsr -->
"\u2260" to "≠", // not equal to, U+2260 ISOtech -->
"\u2261" to "≡", // identical to, U+2261 ISOtech -->
"\u2264" to "≤", // less-than or equal to, U+2264 ISOtech -->
"\u2265" to "≥", // greater-than or equal to,U+2265 ISOtech -->
"\u2282" to "⊂", // subset of, U+2282 ISOtech -->
"\u2283" to "⊃", // superset of, U+2283 ISOtech -->
// <!-- note that nsup, 'not a superset of, U+2283' is not covered by the
// Symbol font encoding and is not included. Should it be, for symmetry?
// It is in ISOamsn -->,
"\u2284" to "⊄", // not a subset of, U+2284 ISOamsn -->
"\u2286" to "⊆", // subset of or equal to, U+2286 ISOtech -->
"\u2287" to "⊇", // superset of or equal to,U+2287 ISOtech -->
"\u2295" to "⊕", // circled plus = direct sum,U+2295 ISOamsb -->
"\u2297" to "⊗", // circled times = vector product,U+2297 ISOamsb -->
"\u22A5" to "⊥", // up tack = orthogonal to = perpendicular,U+22A5 ISOtech -->
"\u22C5" to "⋅", // dot operator, U+22C5 ISOamsb -->
// <!-- dot operator is NOT the same character as U+00B7 middle dot -->
// <!-- Miscellaneous Technical -->
"\u2308" to "⌈", // left ceiling = apl upstile,U+2308 ISOamsc -->
"\u2309" to "⌉", // right ceiling, U+2309 ISOamsc -->
"\u230A" to "⌊", // left floor = apl downstile,U+230A ISOamsc -->
"\u230B" to "⌋", // right floor, U+230B ISOamsc -->
"\u2329" to "⟨", // left-pointing angle bracket = bra,U+2329 ISOtech -->
// <!-- lang is NOT the same character as U+003C 'less than' or U+2039 'single left-pointing angle quotation
// mark' -->
"\u232A" to "⟩", // right-pointing angle bracket = ket,U+232A ISOtech -->
// <!-- rang is NOT the same character as U+003E 'greater than' or U+203A
// 'single right-pointing angle quotation mark' -->
// <!-- Geometric Shapes -->
"\u25CA" to "◊", // lozenge, U+25CA ISOpub -->
// <!-- Miscellaneous Symbols -->
"\u2660" to "♠", // black spade suit, U+2660 ISOpub -->
// <!-- black here seems to mean filled as opposed to hollow -->
"\u2663" to "♣", // black club suit = shamrock,U+2663 ISOpub -->
"\u2665" to "♥", // black heart suit = valentine,U+2665 ISOpub -->
"\u2666" to "♦", // black diamond suit, U+2666 ISOpub -->
// <!-- Latin Extended-A -->
"\u0152" to "Œ", // -- latin capital ligature OE,U+0152 ISOlat2 -->
"\u0153" to "œ", // -- latin small ligature oe, U+0153 ISOlat2 -->
// <!-- ligature is a misnomer, this is a separate character in some languages -->
"\u0160" to "Š", // -- latin capital letter S with caron,U+0160 ISOlat2 -->
"\u0161" to "š", // -- latin small letter s with caron,U+0161 ISOlat2 -->
"\u0178" to "Ÿ", // -- latin capital letter Y with diaeresis,U+0178 ISOlat2 -->
// <!-- Spacing Modifier Letters -->
"\u02C6" to "ˆ", // -- modifier letter circumflex accent,U+02C6 ISOpub -->
"\u02DC" to "˜", // small tilde, U+02DC ISOdia -->
// <!-- General Punctuation -->
"\u2002" to " ", // en space, U+2002 ISOpub -->
"\u2003" to " ", // em space, U+2003 ISOpub -->
"\u2009" to " ", // thin space, U+2009 ISOpub -->
"\u200C" to "‌", // zero width non-joiner,U+200C NEW RFC 2070 -->
"\u200D" to "‍", // zero width joiner, U+200D NEW RFC 2070 -->
"\u200E" to "‎", // left-to-right mark, U+200E NEW RFC 2070 -->
"\u200F" to "‏", // right-to-left mark, U+200F NEW RFC 2070 -->
"\u2013" to "–", // en dash, U+2013 ISOpub -->
"\u2014" to "—", // em dash, U+2014 ISOpub -->
"\u2018" to "‘", // left single quotation mark,U+2018 ISOnum -->
"\u2019" to "’", // right single quotation mark,U+2019 ISOnum -->
"\u201A" to "‚", // single low-9 quotation mark, U+201A NEW -->
"\u201C" to "“", // left double quotation mark,U+201C ISOnum -->
"\u201D" to "”", // right double quotation mark,U+201D ISOnum -->
"\u201E" to "„", // double low-9 quotation mark, U+201E NEW -->
"\u2020" to "†", // dagger, U+2020 ISOpub -->
"\u2021" to "‡", // double dagger, U+2021 ISOpub -->
"\u2030" to "‰", // per mille sign, U+2030 ISOtech -->
"\u2039" to "‹", // single left-pointing angle quotation mark,U+2039 ISO proposed -->
// <!-- lsaquo is proposed but not yet ISO standardized -->
"\u203A" to "›", // single right-pointing angle quotation mark,U+203A ISO proposed -->
// <!-- rsaquo is proposed but not yet ISO standardized -->
"\u20AC" to "€" // -- euro sign, U+20AC NEW -->
)
/**
* Reverse of [.HTML40_EXTENDED_ESCAPE] for unescaping purposes.
*/
val HTML40_EXTENDED_UNESCAPE: Map<CharSequence, CharSequence> = HTML40_EXTENDED_ESCAPE.invert()
/**
* A Map<CharSequence, CharSequence> to escape the basic XML and HTML
* character entities.
*
* Namely: `" & < >`
*/
val BASIC_ESCAPE: Map<CharSequence, CharSequence> = mapOf(
"\"" to """, // " - double-quote
"&" to "&", // & - ampersand
"<" to "<", // < - less-than
">" to ">" // > - greater-than
)
/**
* Reverse of [.BASIC_ESCAPE] for unescaping purposes.
*/
val BASIC_UNESCAPE: Map<CharSequence, CharSequence> = BASIC_ESCAPE.invert()
/**
* A Map<CharSequence, CharSequence> to escape the apostrophe character to
* its XML character entity.
*/
val APOS_ESCAPE: Map<CharSequence, CharSequence> = mapOf(
"'" to "'" // XML apostrophe
)
/**
* Reverse of [.APOS_ESCAPE] for unescaping purposes.
*/
val APOS_UNESCAPE: Map<CharSequence, CharSequence> = APOS_ESCAPE.invert()
/**
* Used to invert an escape Map into an unescape Map.
* @param this@invert Map<String, String> to be inverted
* @return Map<String, String> inverted array
*/
private fun <K, V> Map<K, V>.invert(): Map<V, K> {
val newMap = HashMap<V, K>()
val it = entries.iterator()
while (it.hasNext()) {
val pair = it.next()
newMap[pair.value] = pair.key
}
return newMap
}
}
|
gpl-3.0
|
879d47783dca0e771837d2e4280a806a
| 61.458647 | 120 | 0.540088 | 3.559492 | false | false | false | false |
wendigo/chrome-reactive-kotlin
|
src/main/kotlin/pl/wendigo/chrome/api/indexeddb/Types.kt
|
1
|
3893
|
package pl.wendigo.chrome.api.indexeddb
/**
* Database with an array of object stores.
*
* @link [IndexedDB#DatabaseWithObjectStores](https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#type-DatabaseWithObjectStores) type documentation.
*/
@kotlinx.serialization.Serializable
data class DatabaseWithObjectStores(
/**
* Database name.
*/
val name: String,
/**
* Database version (type is not 'integer', as the standard
requires the version number to be 'unsigned long long')
*/
val version: Double,
/**
* Object stores in this database.
*/
val objectStores: List<ObjectStore>
)
/**
* Object store.
*
* @link [IndexedDB#ObjectStore](https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#type-ObjectStore) type documentation.
*/
@kotlinx.serialization.Serializable
data class ObjectStore(
/**
* Object store name.
*/
val name: String,
/**
* Object store key path.
*/
val keyPath: KeyPath,
/**
* If true, object store has auto increment flag set.
*/
val autoIncrement: Boolean,
/**
* Indexes in this object store.
*/
val indexes: List<ObjectStoreIndex>
)
/**
* Object store index.
*
* @link [IndexedDB#ObjectStoreIndex](https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#type-ObjectStoreIndex) type documentation.
*/
@kotlinx.serialization.Serializable
data class ObjectStoreIndex(
/**
* Index name.
*/
val name: String,
/**
* Index key path.
*/
val keyPath: KeyPath,
/**
* If true, index is unique.
*/
val unique: Boolean,
/**
* If true, index allows multiple entries for a key.
*/
val multiEntry: Boolean
)
/**
* Key.
*
* @link [IndexedDB#Key](https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#type-Key) type documentation.
*/
@kotlinx.serialization.Serializable
data class Key(
/**
* Key type.
*/
val type: String,
/**
* Number value.
*/
val number: Double? = null,
/**
* String value.
*/
val string: String? = null,
/**
* Date value.
*/
val date: Double? = null,
/**
* Array value.
*/
val array: List<Key>? = null
)
/**
* Key range.
*
* @link [IndexedDB#KeyRange](https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#type-KeyRange) type documentation.
*/
@kotlinx.serialization.Serializable
data class KeyRange(
/**
* Lower bound.
*/
val lower: Key? = null,
/**
* Upper bound.
*/
val upper: Key? = null,
/**
* If true lower bound is open.
*/
val lowerOpen: Boolean,
/**
* If true upper bound is open.
*/
val upperOpen: Boolean
)
/**
* Data entry.
*
* @link [IndexedDB#DataEntry](https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#type-DataEntry) type documentation.
*/
@kotlinx.serialization.Serializable
data class DataEntry(
/**
* Key object.
*/
val key: pl.wendigo.chrome.api.runtime.RemoteObject,
/**
* Primary key object.
*/
val primaryKey: pl.wendigo.chrome.api.runtime.RemoteObject,
/**
* Value object.
*/
val value: pl.wendigo.chrome.api.runtime.RemoteObject
)
/**
* Key path.
*
* @link [IndexedDB#KeyPath](https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#type-KeyPath) type documentation.
*/
@kotlinx.serialization.Serializable
data class KeyPath(
/**
* Key path type.
*/
val type: String,
/**
* String value.
*/
val string: String? = null,
/**
* Array value.
*/
val array: List<String>? = null
)
|
apache-2.0
|
4fd53181c6aa75aa6e6cf5a1f78b6376
| 18.964103 | 161 | 0.591318 | 4.046778 | false | false | false | false |
stripe/stripe-android
|
payments-core/src/test/java/com/stripe/android/view/PostalCodeEditTextTest.kt
|
1
|
3483
|
package com.stripe.android.view
import android.app.Activity
import android.text.InputType
import androidx.appcompat.view.ContextThemeWrapper
import androidx.test.core.app.ApplicationProvider
import com.google.android.material.textfield.TextInputLayout
import com.google.common.truth.Truth.assertThat
import com.stripe.android.CustomerSession
import com.stripe.android.PaymentSessionFixtures
import com.stripe.android.R
import org.junit.runner.RunWith
import org.mockito.kotlin.mock
import org.robolectric.RobolectricTestRunner
import kotlin.test.BeforeTest
import kotlin.test.Test
@RunWith(RobolectricTestRunner::class)
class PostalCodeEditTextTest {
private val context = ContextThemeWrapper(
ApplicationProvider.getApplicationContext(),
R.style.StripeDefaultTheme
)
private val postalCodeEditText = PostalCodeEditText(context)
@BeforeTest
fun setup() {
CustomerSession.instance = mock()
}
@Test
fun testConfigureForUs() {
postalCodeEditText.config = PostalCodeEditText.Config.US
assertThat(postalCodeEditText.inputType)
.isEqualTo(InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD)
}
@Test
fun postalCode_whenConfiguredForUs_shouldValidate() {
postalCodeEditText.config = PostalCodeEditText.Config.US
assertThat(postalCodeEditText.postalCode)
.isNull()
postalCodeEditText.setText("1234")
assertThat(postalCodeEditText.postalCode)
.isNull()
postalCodeEditText.setText("123 5")
assertThat(postalCodeEditText.postalCode)
.isNull()
postalCodeEditText.setText("12345")
assertThat(postalCodeEditText.postalCode)
.isEqualTo("12345")
}
@Test
fun changing_from_Us_to_other_country_should_allow_longer_postal() {
postalCodeEditText.config = PostalCodeEditText.Config.US
postalCodeEditText.setText("123456")
assertThat(postalCodeEditText.postalCode)
.isEqualTo("12345")
postalCodeEditText.config = PostalCodeEditText.Config.Global
postalCodeEditText.setText("123456")
assertThat(postalCodeEditText.postalCode)
.isEqualTo("123456")
}
@Test
fun updateHint_whenTextInputLayoutHintEnabled_shouldSetHintOnTextInputLayout() {
createActivity {
val textInputLayout = TextInputLayout(it)
textInputLayout.addView(postalCodeEditText)
postalCodeEditText.config = PostalCodeEditText.Config.US
assertThat(textInputLayout.hint)
.isEqualTo("ZIP Code")
}
}
@Test
fun updateHint_whenTextInputLayoutHintDisabled_shouldSetHintOnEditText() {
createActivity {
val textInputLayout = TextInputLayout(it)
textInputLayout.isHintEnabled = false
textInputLayout.addView(postalCodeEditText)
postalCodeEditText.config = PostalCodeEditText.Config.US
assertThat(textInputLayout.hint)
.isNull()
assertThat(postalCodeEditText.hint)
.isEqualTo("ZIP Code")
}
}
private fun createActivity(onActivityCallback: (Activity) -> Unit) {
ActivityScenarioFactory(context).create<PaymentFlowActivity>(
PaymentSessionFixtures.PAYMENT_FLOW_ARGS
).use { activityScenario ->
activityScenario.onActivity(onActivityCallback)
}
}
}
|
mit
|
751e9adefdd7991696e0f9222fb78fad
| 32.490385 | 95 | 0.701694 | 5.511076 | false | true | false | false |
jk1/youtrack-idea-plugin
|
src/main/kotlin/com/github/jk1/ytplugin/scriptsDebug/ScriptsRulesHandler.kt
|
1
|
9742
|
package com.github.jk1.ytplugin.scriptsDebug
import com.github.jk1.ytplugin.ComponentAware
import com.github.jk1.ytplugin.logger
import com.github.jk1.ytplugin.rest.ScriptsRestClient
import com.github.jk1.ytplugin.timeTracker.TrackerNotification
import com.google.gson.JsonParser
import com.intellij.javascript.debugger.execution.RemoteUrlMappingBean
import com.intellij.lang.javascript.JavaScriptFileType.INSTANCE
import com.intellij.notification.NotificationType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileEditor.impl.LoadTextUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.impl.file.PsiDirectoryFactory
import com.intellij.util.IncorrectOperationException
class ScriptsRulesHandler(val project: Project) {
private var srcDir = project.guessProjectDir()
private val updatedScriptsNames = mutableListOf<String>()
private val loadedScriptsNames = mutableListOf<String>()
private val MODULE_END = "\n});"
private val MODULE_PREAMBLE = "(function (exports, require, module, __filename, __dirname) {"
fun loadWorkflowRules(mappings: MutableList<RemoteUrlMappingBean>, rootFolderName: String, instanceFolderName: String) {
val repositories = ComponentAware.of(project).taskManagerComponent.getAllConfiguredYouTrackRepositories()
val repo = if (repositories.isNotEmpty()) {
repositories.first()
} else null
val scriptsList = ScriptsRestClient(repo!!).getScriptsWithRules()
val trackerNote = TrackerNotification()
createOrFindScriptDirectory(rootFolderName)
srcDir = project.guessProjectDir()?.findFileByRelativePath(rootFolderName)
createOrFindScriptDirectory(instanceFolderName)
srcDir = project.guessProjectDir()?.findFileByRelativePath("$rootFolderName/$instanceFolderName")
scriptsList.map { workflow ->
// no need to use specific separator
srcDir = project.guessProjectDir()?.findFileByRelativePath("$rootFolderName/$instanceFolderName")
// proper directory creating for custom and default scripts
var scriptDirectory: PsiDirectory? = null
val scriptDirectories = workflow.name.split('/')
scriptDirectories.forEach {
scriptDirectory = createOrFindScriptDirectory(it)
srcDir = project.guessProjectDir()?.findFileByRelativePath("${srcDir?.path?.drop(project.guessProjectDir()!!.path.length + 1)}/$it")
}
logger.debug("Script directory: ${workflow.name}")
workflow.rules.map { rule ->
val existingScript = project.guessProjectDir()?.findFileByRelativePath(
"$rootFolderName/$instanceFolderName/${workflow.name}/${rule.name}.js"
)
if (existingScript != null) {
logger.debug("Existing script found: ${existingScript.path}")
ScriptsRestClient(repo).getScriptsContent(workflow, rule)
logger.debug("existing script content: ${existingScript.contentsToByteArray()}")
logger.debug("rule content: ${rule.content.toByteArray()}")
if (!LoadTextUtil.loadText(existingScript).toString().equals(rule.content)) {
ApplicationManager.getApplication().runWriteAction {
existingScript.delete(this)
createRuleFile("${rule.name}.js", rule.content, scriptDirectory!!)
}
updatedScriptsNames.add("${workflow.name}/${rule.name}.js")
} else {
logger.debug("No changes were made for ${workflow.name}")
}
} else {
ScriptsRestClient(repo).getScriptsContent(workflow, rule)
createRuleFile("${rule.name}.js", rule.content, scriptDirectory!!)
loadedScriptsNames.add("${workflow.name}/${rule.name}.js")
}
addScriptMapping(workflow.name, rule.name, mappings, rootFolderName, instanceFolderName)
}
}
if (updatedScriptsNames.isNotEmpty()){
trackerNote.notify(
"Scripts updated: \n ${updatedScriptsNames.joinToString("\n")}",
NotificationType.INFORMATION
)
}
if (loadedScriptsNames.isNotEmpty()) {
trackerNote.notify(
"Scripts loaded: \n ${loadedScriptsNames.joinToString("\n")}",
NotificationType.INFORMATION
)
}
if (scriptsList.isNullOrEmpty()){
val note = "The debug operation requires that you have permission to update at least one project in " +
"YouTrack and have at least one custom workflow or updated predefined workflow "
trackerNote.notify(note, NotificationType.ERROR)
}
}
private fun addScriptMapping(workflowName: String, ruleName: String, mappings: MutableList<RemoteUrlMappingBean>,
rootFolderName: String, instanceFolderName: String){
val local = project.guessProjectDir()?.path + "/$rootFolderName/$instanceFolderName/$workflowName/$ruleName.js"
val localUrls = mutableListOf<String>()
mappings.forEach { entry -> localUrls.add(entry.localFilePath) }
if (!localUrls.contains(local)) {
logger.debug("Mapping added for pair: $local and $instanceFolderName/$workflowName/$ruleName.js")
mappings.add(RemoteUrlMappingBean(local, "$instanceFolderName/$workflowName/$ruleName.js"))
}
}
private fun createRuleFile(name: String, text: String?, directory: PsiDirectory) {
ApplicationManager.getApplication().invokeAndWait {
val psiFileFactory = PsiFileFactory.getInstance(project)
ApplicationManager.getApplication().runWriteAction {
//find or create file
try {
val file: PsiFile = psiFileFactory.createFileFromText(name, INSTANCE, text as CharSequence)
logger.debug("Attempt to load file $name")
directory.add(file)
makeLoadedFileReadOnly(directory, name)
logger.debug("File $name is loaded")
} catch (e: IncorrectOperationException) {
logger.debug("Most likely file $name is already loaded: ", e)
} catch (e: AssertionError) {
logger.debug("Most likely The $name file contains unsupported line separators and was not imported from YouTrack", e)
val note = "The $name file contains unsupported line separators and was not imported from YouTrack"
val trackerNote = TrackerNotification()
trackerNote.notify(note, NotificationType.WARNING)
val file: PsiFile = psiFileFactory.createFileFromText(
name, INSTANCE,
"The source script appears to contain unsupported line separators. Please enter the content manually." as CharSequence
)
try {
logger.debug("The $name file contains unsupported line separators and was not imported from YouTrack")
directory.add(file)
} catch (e: IncorrectOperationException) {
logger.debug("Most likely file $name was already loaded", e)
}
}
}
}
}
private fun makeLoadedFileReadOnly(directory: PsiDirectory, name: String) {
directory.findFile(name)?.virtualFile?.isWritable = false
}
private fun createOrFindScriptDirectory(name: String): PsiDirectory {
var targetDirectory: PsiDirectory? = null
ApplicationManager.getApplication().invokeAndWait {
ApplicationManager.getApplication().runWriteAction {
// find or create directory
val targetVirtualDir = if (srcDir?.findFileByRelativePath(name) == null) {
logger.debug("Directory $name is created")
srcDir?.createChildDirectory(this, name)
} else {
srcDir?.findFileByRelativePath(name)
}
targetDirectory = PsiDirectoryFactory.getInstance(project).createDirectory(targetVirtualDir!!)
}
}
logger.debug("Directory created: $name")
return targetDirectory!!
}
fun handleScriptsSourcesMessages(message: String): String{
return try {
val msgResult = JsonParser.parseString(message).asJsonObject.get("result").asJsonObject
val content = msgResult.get("scriptSource").asString
val newContent = removeRedundantStringsFormScriptContent(content)
logger.debug("Handled scripts sources message: ${message.substring(50)}...")
message.replace(content, newContent)
} catch (e: Exception) {
logger.debug("Failed to handle scripts sources message $message")
logger.debug(e)
message
}
}
private fun removeRedundantStringsFormScriptContent(content: String): String {
return content.removePrefix(MODULE_PREAMBLE).removeSuffix(MODULE_END)
}
}
|
apache-2.0
|
61fb9b3d9f137548d31c8d5753e19d45
| 46.759804 | 148 | 0.628105 | 5.740719 | false | false | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/lang/core/resolve2/PathResolution.kt
|
2
|
10448
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.resolve2
import org.rust.cargo.project.workspace.CargoWorkspace
import org.rust.lang.core.crate.CratePersistentId
import org.rust.lang.core.macros.decl.MACRO_DOLLAR_CRATE_IDENTIFIER
import org.rust.lang.core.psi.RsMacro
import org.rust.lang.core.psi.ext.hasMacroExport
enum class ResolveMode { IMPORT, OTHER }
/** Returns `reachedFixedPoint=true` if we are sure that additions to [ModData.visibleItems] wouldn't change the result */
fun CrateDefMap.resolvePathFp(
containingMod: ModData,
path: Array<String>,
mode: ResolveMode,
withInvisibleItems: Boolean
): ResolvePathResult {
var (pathKind, firstSegmentIndex) = getPathKind(path)
// we use PerNs and not ModData for first segment,
// because path could be one-segment: `use crate as foo;` and `use func as func2;`
// ~~~~~ path ~~~~ path
val firstSegmentPerNs = when {
pathKind is PathKind.DollarCrate -> {
val defMap = getDefMap(pathKind.crateId) ?: error("Can't find DefMap for path ${path.joinToString("::")}")
defMap.rootAsPerNs
}
pathKind == PathKind.Crate -> rootAsPerNs
pathKind is PathKind.Super -> {
val modData = containingMod.getNthParent(pathKind.level)
?: return ResolvePathResult.empty(reachedFixedPoint = true)
if (modData.isCrateRoot) rootAsPerNs else modData.asPerNs()
}
// plain import or absolute path in 2015:
// crate-relative with fallback to extern prelude
// (with the simplification in https://github.com/rust-lang/rust/issues/57745)
metaData.edition == CargoWorkspace.Edition.EDITION_2015
&& (pathKind is PathKind.Absolute || pathKind is PathKind.Plain && mode == ResolveMode.IMPORT) -> {
val firstSegment = path[firstSegmentIndex++]
resolveNameInCrateRootOrExternPrelude(firstSegment)
}
pathKind == PathKind.Absolute -> {
val crateName = path[firstSegmentIndex++]
externPrelude[crateName]?.rootAsPerNs
// extern crate declarations can add to the extern prelude
?: return ResolvePathResult.empty(reachedFixedPoint = false)
}
pathKind == PathKind.Plain -> {
val firstSegment = path[firstSegmentIndex++]
val withLegacyMacros = mode == ResolveMode.IMPORT && path.size == 1
resolveNameInModule(containingMod, firstSegment, withLegacyMacros)
}
else -> error("unreachable")
}
var currentPerNs = firstSegmentPerNs
var visitedOtherCrate = false
for (segmentIndex in firstSegmentIndex until path.size) {
val currentModAsVisItem = currentPerNs.types
// TODO: It is not enough - we should also check that `it.visibility` is visible inside `sourceMod`
.singleOrNull { withInvisibleItems || !it.visibility.isInvisible }
// we still have path segments left, but the path so far
// didn't resolve in the types namespace => no resolution
?: return ResolvePathResult.empty(reachedFixedPoint = false)
val currentModData = tryCastToModData(currentModAsVisItem)
// could be an inherent method call in UFCS form
// (`Struct::method`), or some other kind of associated item
?: return ResolvePathResult.empty(reachedFixedPoint = true)
if (currentModData.crate != crate) visitedOtherCrate = true
val segment = path[segmentIndex]
currentPerNs = currentModData.getVisibleItem(segment)
}
val resultPerNs = if (withInvisibleItems) currentPerNs else currentPerNs.filterVisibility { !it.isInvisible }
return ResolvePathResult(resultPerNs, reachedFixedPoint = true, visitedOtherCrate = visitedOtherCrate)
}
fun CrateDefMap.resolveMacroCallToMacroDefInfo(
containingMod: ModData,
macroPath: Array<String>,
macroIndex: MacroIndex
): MacroDefInfo? {
if (macroPath.size == 1) {
val name = macroPath.single()
containingMod.resolveMacroCallToLegacyMacroDefInfo(name, macroIndex)
?.let { return it }
}
val perNs = resolvePathFp(
containingMod,
macroPath,
ResolveMode.OTHER,
withInvisibleItems = false // because we expand only cfg-enabled macros
)
val defItem = perNs.resolvedDef.macros.singleOrNull() ?: return null
return getMacroInfo(defItem)
}
private fun ModData.resolveMacroCallToLegacyMacroDefInfo(name: String, macroIndex: MacroIndex): MacroDefInfo? {
return legacyMacros[name]?.getLastBefore(macroIndex)
?: context?.resolveMacroCallToLegacyMacroDefInfo(name, macroIndex)
}
fun List<MacroDefInfo>.getLastBefore(macroIndex: MacroIndex): MacroDefInfo? =
filter { it !is DeclMacroDefInfo || it.macroIndex < macroIndex }
.asReversed()
.maxByOrNull { if (it is DeclMacroDefInfo) it.macroIndex else MacroIndex(intArrayOf(0)) }
private fun CrateDefMap.resolveNameInExternPrelude(name: String): PerNs {
val defMap = externPrelude[name] ?: return PerNs.Empty
return defMap.rootAsPerNs
}
// only when resolving `name` in `extern crate name;`
// ~~~~
fun CrateDefMap.resolveExternCrateAsDefMap(name: String): CrateDefMap? =
if (name == "self") this else directDependenciesDefMaps[name]
/**
* Resolve in:
* - legacy scope of macro (needed e.g. for `use name_ as name;`)
* - current module / scope
* - extern prelude
* - std prelude
*/
fun CrateDefMap.resolveNameInModule(modData: ModData, name: String, withLegacyMacros: Boolean): PerNs {
val result = doResolveNameInModule(modData, name, withLegacyMacros)
val context = modData.context ?: return result
val resultFromContext = resolveNameInModule(context, name, withLegacyMacros)
return result.or(resultFromContext)
}
private fun CrateDefMap.doResolveNameInModule(modData: ModData, name: String, withLegacyMacros: Boolean): PerNs {
val fromLegacyMacro = if (withLegacyMacros) modData.getFirstLegacyMacro(name) ?: PerNs.Empty else PerNs.Empty
val fromScope = modData.getVisibleItem(name)
val fromExternPrelude = resolveNameInExternPrelude(name)
val fromPrelude = resolveNameInPrelude(name)
return fromLegacyMacro.or(fromScope).or(fromExternPrelude).or(fromPrelude)
}
/**
* We take first macro, because this code is used for resolution inside import:
* ```
* macro_rules! name_ { ... }
* use name_ as name;
* ```
*
* Multiple macro definitions before import will cause compiler error:
* ```
* macro_rules! name_ { ... }
* macro_rules! name_ { ... }
* use name_ as name;
* // error[E0659]: `name_` is ambiguous
* ```
*/
private fun ModData.getFirstLegacyMacro(name: String): PerNs? {
val def = legacyMacros[name]?.firstOrNull() ?: return null
val visibility = when {
// the macro was added from another crate using `#[macro_use] export crate ...`, it must be public
def !is DeclMacroDefInfo -> Visibility.Public
def.hasMacroExport -> Visibility.Public
else -> rootModData.visibilityInSelf
}
val visItem = VisItem(def.path, visibility)
return PerNs.macros(visItem)
}
/**
* Used when macro path is qualified.
* - It is either macro from other crate,
* then it will have `macro_export` attribute
* (and there can't be two `macro_export` macros with same name in same mod).
* - Or it is reexport of legacy macro, then we peek first (see [getFirstLegacyMacro] for details)
*/
fun List<DeclMacroDefInfo>.singlePublicOrFirst(): DeclMacroDefInfo = singleOrNull { it.hasMacroExport } ?: first()
fun List<RsMacro>.singlePublicOrFirst(): RsMacro = singleOrNull { it.hasMacroExport } ?: first()
private fun CrateDefMap.resolveNameInCrateRootOrExternPrelude(name: String): PerNs {
val fromCrateRoot = root.getVisibleItem(name)
val fromExternPrelude = resolveNameInExternPrelude(name)
return fromCrateRoot.or(fromExternPrelude)
}
private fun CrateDefMap.resolveNameInPrelude(name: String): PerNs {
val prelude = prelude ?: return PerNs.Empty
return prelude.getVisibleItem(name)
}
private sealed class PathKind {
object Plain : PathKind()
/** `self` is `Super(0)` */
class Super(val level: Int) : PathKind()
/** Starts with crate */
object Crate : PathKind()
/** Starts with :: */
object Absolute : PathKind()
/** `$crate` from macro expansion */
class DollarCrate(val crateId: CratePersistentId) : PathKind()
}
private data class PathInfo(
val kind: PathKind,
/** number of segments represented by [kind]. */
val segmentsToSkip: Int,
)
/**
* Examples:
* - For path 'foo::bar' returns `PathKindInfo([PathKind.Plain], 0)`
* - For path 'super::foo::bar' returns `PathKindInfo([PathKind.Super], 1)`
* - For path 'super::super::foo::bar' returns `PathKindInfo([PathKind.Super], 2)`
*/
private fun getPathKind(path: Array<String>): PathInfo {
return when (path.first()) {
MACRO_DOLLAR_CRATE_IDENTIFIER -> {
val crateId = path.getOrNull(1)?.toIntOrNull()
if (crateId != null) {
PathInfo(PathKind.DollarCrate(crateId), 2)
} else {
RESOLVE_LOG.warn("Invalid path starting with dollar crate: '${path.contentToString()}'")
PathInfo(PathKind.Plain, 0)
}
}
"crate" -> PathInfo(PathKind.Crate, 1)
"super" -> {
var level = 0
while (path.getOrNull(level) == "super") ++level
PathInfo(PathKind.Super(level), level)
}
"self" -> {
if (path.getOrNull(1) == "super") {
val kind = getPathKind(path.copyOfRange(1, path.size))
kind.copy(segmentsToSkip = kind.segmentsToSkip + 1)
} else {
PathInfo(PathKind.Super(0), 1)
}
}
"" -> PathInfo(PathKind.Absolute, 1)
else -> PathInfo(PathKind.Plain, 0)
}
}
data class ResolvePathResult(
val resolvedDef: PerNs,
val reachedFixedPoint: Boolean,
val visitedOtherCrate: Boolean,
) {
companion object {
fun empty(reachedFixedPoint: Boolean): ResolvePathResult =
ResolvePathResult(PerNs.Empty, reachedFixedPoint, false)
}
}
|
mit
|
1fd48bdfd76de979d6bc0ad31fb121e7
| 38.877863 | 122 | 0.668358 | 4.482196 | false | false | false | false |
yzbzz/beautifullife
|
app/src/main/java/com/ddu/ui/fragment/life/LoanFragment.kt
|
2
|
4873
|
package com.ddu.ui.fragment.life
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ddu.R
import com.ddu.icore.ui.adapter.common.DefaultRVAdapter
import com.ddu.icore.ui.adapter.common.ViewHolder
import com.ddu.icore.ui.fragment.DefaultFragment
import com.ddu.ui.fragment.work.FragmentA
import com.ddu.ui.view.BottomView
import com.ddu.ui.view.DividerItemDecoration
import kotlinx.android.synthetic.main.fragment_life_mortgage_item.*
import java.util.*
/**
* Created by yzbzz on 16/4/21.
*/
class LoanFragment : DefaultFragment(), View.OnClickListener {
private var mList: MutableList<String>? = null
protected var mParties = arrayOf("a", "b", "c", "LogicActions")
private var isEnabled = false
override fun initData(savedInstanceState: Bundle?) {
mList = ArrayList()
for (i in 1..29) {
mList!!.add(i.toString() + "年" + "(" + i * 12 + "期" + ")")
}
}
override fun getLayoutId(): Int {
return R.layout.fragment_life_mortgage_item
}
override fun initView() {
setDefaultTitle("房贷计算")
rl_mortgage.setOnClickListener(this)
btn_calculator.setOnClickListener(this)
btn_calculator1.setOnClickListener(this)
}
// private fun setData() {
// ll_mortgage.visibility = View.VISIBLE
// pc_mortgage.setUsePercentValues(true)
// pc_mortgage.setDescription("Hello")
// pc_mortgage.isDrawHoleEnabled = false
// // pc_mortgage.setDragDecelerationFrictionCoef(0.95f);
//
// val yVals1 = ArrayList<Entry>()
// for (i in 0..2) {
// yVals1.add(Entry(30f, i))
// }
//
// val xVals = ArrayList<String>()
// for (i in 0..2) {
// xVals.add(mParties[i % mParties.size])
// }
//
// val colors = ArrayList<Int>()
// COLORFUL_COLORS.indices.forEach {
// colors.add(it)
// }
//
// val dataSet = PieDataSet(yVals1, "Biu")
// dataSet.sliceSpace = 3f
// dataSet.selectionShift = 5f
// dataSet.colors = colors
//
// // PieData data = new PieData(xVals, dataSet);
// // data.setValueFormatter(new PercentFormatter());
// // data.setValueTextSize(11f);
// // data.setValueTextColor(Color.WHITE);
// //
// // pc_mortgage.setData(data);
// // pc_mortgage.highlightValue(null);
// //
// // pc_mortgage.invalidate();
// //
// //
// // Legend l = pc_mortgage.getLegend();
// // l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART_CENTER);
// //// l.setXEntrySpace(7f);
// //// l.setYEntrySpace(0f);
// // l.setYOffset(10f);
// }
override fun onClick(v: View?) {
when (view?.id) {
R.id.rl_mortgage -> showBottomDialog()
// R.id.btn_calculator -> setData()
R.id.btn_calculator1 -> {
btn_calculator!!.isEnabled = isEnabled
isEnabled = !isEnabled
startFragment(FragmentA::class.java)
}
else -> {
}
}
}
private fun showBottomDialog() {
val dialog = BottomView(baseActivity)
val view = LayoutInflater.from(baseActivity).inflate(R.layout.fragment_life_mortgage_bottom, null)
val recyclerView = view.findViewById<View>(R.id.rv_bottom) as RecyclerView
recyclerView.layoutManager = LinearLayoutManager(baseActivity)
val defaultRecycleViewAdapter = object : DefaultRVAdapter<String>(baseActivity, mList) {
override fun getLayoutId(viewType: Int): Int {
return R.layout.i_rv_item_linear
}
override fun bindView(viewHolder: ViewHolder, data: String, position: Int) {
viewHolder.setText(R.id.tv_title, data)
viewHolder.setOnClickListener(R.id.ll_detail, View.OnClickListener {
dialog.dismissBottomView()
tv_loan.text = data
})
}
}
recyclerView.adapter = defaultRecycleViewAdapter
recyclerView.addItemDecoration(DividerItemDecoration(baseActivity, DividerItemDecoration.VERTICAL))
dialog.setContentView(view)
dialog.setAnimation(R.style.BottomToTopAnim)
dialog.showBottomView(true)
}
override fun isShowTitleBar(): Boolean {
return false
}
companion object {
val COLORFUL_COLORS = intArrayOf(Color.rgb(193, 37, 82), Color.rgb(255, 102, 0), Color.rgb(245, 199, 0), Color.rgb(106, 150, 31), Color.rgb(179, 100, 53))
}
}
|
apache-2.0
|
397858df4352ba91a98a8115554b00db
| 32.993007 | 162 | 0.599671 | 4.037375 | false | false | false | false |
deva666/anko
|
anko/library/static/commons/src/dialogs/AlertBuilder.kt
|
2
|
3637
|
/*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE", "unused")
package org.jetbrains.anko
import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.graphics.drawable.Drawable
import android.support.annotation.DrawableRes
import android.support.annotation.StringRes
import android.view.KeyEvent
import android.view.View
import android.view.ViewManager
import org.jetbrains.anko.internals.AnkoInternals.NO_GETTER
import kotlin.DeprecationLevel.ERROR
@SuppressLint("SupportAnnotationUsage")
interface AlertBuilder<out D : DialogInterface> {
val ctx: Context
var title: CharSequence
@Deprecated(NO_GETTER, level = ERROR) get
var titleResource: Int
@Deprecated(NO_GETTER, level = ERROR) get
var message: CharSequence
@Deprecated(NO_GETTER, level = ERROR) get
var messageResource: Int
@Deprecated(NO_GETTER, level = ERROR) get
var icon: Drawable
@Deprecated(NO_GETTER, level = ERROR) get
@setparam:DrawableRes
var iconResource: Int
@Deprecated(NO_GETTER, level = ERROR) get
var customTitle: View
@Deprecated(NO_GETTER, level = ERROR) get
var customView: View
@Deprecated(NO_GETTER, level = ERROR) get
fun onCancelled(handler: (dialog: DialogInterface) -> Unit)
fun onKeyPressed(handler: (dialog: DialogInterface, keyCode: Int, e: KeyEvent) -> Boolean)
fun positiveButton(buttonText: String, onClicked: (dialog: DialogInterface) -> Unit)
fun positiveButton(@StringRes buttonTextResource: Int, onClicked: (dialog: DialogInterface) -> Unit)
fun negativeButton(buttonText: String, onClicked: (dialog: DialogInterface) -> Unit)
fun negativeButton(@StringRes buttonTextResource: Int, onClicked: (dialog: DialogInterface) -> Unit)
fun neutralPressed(buttonText: String, onClicked: (dialog: DialogInterface) -> Unit)
fun neutralPressed(@StringRes buttonTextResource: Int, onClicked: (dialog: DialogInterface) -> Unit)
fun items(items: List<CharSequence>, onItemSelected: (dialog: DialogInterface, index: Int) -> Unit)
fun <T> items(items: List<T>, onItemSelected: (dialog: DialogInterface, item: T, index: Int) -> Unit)
fun build(): D
fun show(): D
}
fun AlertBuilder<*>.customTitle(dsl: ViewManager.() -> Unit) {
customTitle = ctx.UI(dsl).view
}
fun AlertBuilder<*>.customView(dsl: ViewManager.() -> Unit) {
customView = ctx.UI(dsl).view
}
inline fun AlertBuilder<*>.okButton(noinline handler: (dialog: DialogInterface) -> Unit) {
positiveButton(android.R.string.ok, handler)
}
inline fun AlertBuilder<*>.cancelButton(noinline handler: (dialog: DialogInterface) -> Unit) {
negativeButton(android.R.string.cancel, handler)
}
inline fun AlertBuilder<*>.yesButton(noinline handler: (dialog: DialogInterface) -> Unit) {
positiveButton(android.R.string.yes, handler)
}
inline fun AlertBuilder<*>.noButton(noinline handler: (dialog: DialogInterface) -> Unit) {
negativeButton(android.R.string.no, handler)
}
|
apache-2.0
|
10f3450c80513c89f6e8e7e2b78d4e81
| 34.320388 | 105 | 0.732197 | 4.299054 | false | false | false | false |
brianwernick/RecyclerExt
|
library/src/main/kotlin/com/devbrackets/android/recyclerext/adapter/viewholder/ClickableViewHolder.kt
|
1
|
2683
|
/*
* Copyright (C) 2016 Brian Wernick
*
* 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.devbrackets.android.recyclerext.adapter.viewholder
import android.view.HapticFeedbackConstants
import android.view.View
import androidx.recyclerview.widget.RecyclerView
/**
* A Simple ViewHolder that adds the ability to specify
* listeners that have access to the ViewHolder instead
* of a position when clicked
*/
abstract class ClickableViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener, View.OnLongClickListener {
fun interface OnClickListener {
fun onClick(viewHolder: ClickableViewHolder)
}
fun interface OnLongClickListener {
fun onLongClick(viewHolder: ClickableViewHolder): Boolean
}
private var onClickListener: OnClickListener? = null
private var onLongClickListener: OnLongClickListener? = null
protected var performLongClickHapticFeedback = true
init {
initializeClickListener()
}
/**
* Sets the click and long click listeners on the root
* view (see [.itemView])
*/
protected fun initializeClickListener() {
itemView.setOnClickListener(this)
itemView.setOnLongClickListener(this)
}
/**
* Enables or Disables haptic feedback on long clicks. If a
* long click listener has not been set with [.setOnLongClickListener]
* then no haptic feedback will be performed.
*
* @param enabled True if the long click should perform a haptic feedback [default: true]
*/
fun setHapticFeedbackEnabled(enabled: Boolean) {
performLongClickHapticFeedback = enabled
}
fun setOnClickListener(onClickListener: OnClickListener?) {
this.onClickListener = onClickListener
}
fun setOnLongClickListener(onLongClickListener: OnLongClickListener?) {
this.onLongClickListener = onLongClickListener
}
override fun onClick(view: View) {
onClickListener?.onClick(this)
}
override fun onLongClick(view: View): Boolean {
return onLongClickListener?.let {
if (performLongClickHapticFeedback) {
itemView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
}
it.onLongClick(this)
} ?: false
}
}
|
apache-2.0
|
ea0b58323a77ae622b5579a19ec83658
| 30.209302 | 136 | 0.748416 | 4.887067 | false | false | false | false |
oleksiyp/mockk
|
mockk/jvm/src/main/kotlin/io/mockk/impl/annotations/MockInjector.kt
|
1
|
4514
|
package io.mockk.impl.annotations
import io.mockk.MockKException
import kotlin.reflect.*
import kotlin.reflect.full.memberProperties
import kotlin.reflect.full.isSubclassOf
import kotlin.reflect.full.valueParameters
import io.mockk.impl.annotations.InjectionHelpers.getAnyIfLateNull
import io.mockk.impl.annotations.InjectionHelpers.setAny
import io.mockk.impl.annotations.InjectionHelpers.setImmutableAny
class MockInjector(
val mockHolder: Any,
val lookupType: InjectionLookupType,
val injectImmutable: Boolean,
val overrideValues: Boolean
) {
fun constructorInjection(type: KClass<*>): Any {
val firstMatching = findMatchingConstructor(type)
?: throw MockKException("No matching constructors found:\n" + type.constructors.joinToString("\n") { it.constructorToStr() })
return injectViaConstructor(firstMatching)
}
fun propertiesInjection(instance: Any) {
instance::class.memberProperties.forEach { property ->
val isMutable = property is KMutableProperty1
if (!injectImmutable && !isMutable) return@forEach
if (!overrideValues) {
if (property.getAnyIfLateNull(instance) != null) return@forEach
}
val newValue = lookupValueByName(property.name, property.returnType.classifier)
?: lookupValueByType(property.returnType.classifier)
?: return@forEach
if (injectImmutable && !isMutable) {
property.setImmutableAny(instance, newValue)
} else {
(property as KMutableProperty1<*, *>).setAny(instance, newValue)
}
}
}
private fun injectViaConstructor(firstMatching: KFunction<Any>): Any {
return firstMatching.call(*matchParameters(firstMatching.valueParameters))
}
private fun findMatchingConstructor(type: KClass<*>): KFunction<Any>? {
val sortCriteria = compareBy<KFunction<Any>>({
-it.parameters.size
}, {
it.parameters.map { it.type.toString() }.joinToString(",")
})
return type.constructors.sortedWith(sortCriteria)
.firstOrNull { tryMatchingParameters(it.valueParameters) }
}
private fun matchParameters(parameters: List<KParameter>): Array<Any> {
return parameters.map { param ->
lookupValueByName(param.name, param.type.classifier)
?: lookupValueByType(param.type.classifier)
?: throw MockKException("Parameter unmatched: $param")
}.toTypedArray()
}
private fun tryMatchingParameters(parameters: List<KParameter>): Boolean {
return !parameters
.map { param ->
lookupValueByName(param.name, param.type.classifier)
?: lookupValueByType(param.type.classifier)
}
.any { it == null }
}
private fun lookupValueByName(name: String?, type: KClassifier?): Any? {
if (name == null) return null
if (type == null) return null
if (type !is KClass<*>) return null
if (!lookupType.byName) return null
return mockHolder::class.memberProperties
.firstOrNull { it.name == name && isMatchingType(it, type) }
?.getAnyIfLateNull(mockHolder)
}
private fun lookupValueByType(type: KClassifier?): Any? {
if (type == null) return null
if (type !is KClass<*>) return null
if (!lookupType.byType) return null
return mockHolder::class.memberProperties
.firstOrNull {
isMatchingType(it, type)
}
?.getAnyIfLateNull(mockHolder)
}
private fun isMatchingType(
it: KProperty1<out Any, Any?>,
type: KClass<*>
): Boolean {
val propertyType = it.returnType.classifier
return if (propertyType is KClass<*>) {
propertyType.isSubclassOf(type)
} else {
false
}
}
private fun <R> KFunction<R>.constructorToStr(): String {
return "constructor(" + parameters.map {
(it.name ?: "<noname arg.>") + " : " + it.type + " = " + lookupToStr(it)
}.joinToString(", ") + ")"
}
private fun lookupToStr(param: KParameter): String {
return (lookupValueByName(param.name, param.type.classifier)
?: lookupValueByType(param.type.classifier)
?: "<not able to lookup>")
.toString()
}
}
|
apache-2.0
|
0b1a62bfa347086d9509aa177ff51de0
| 34.825397 | 141 | 0.620735 | 4.832976 | false | false | false | false |
yuncheolkim/gitmt
|
src/main/kotlin/com/joyouskim/http/UrlPipeLine.kt
|
1
|
2310
|
package com.joyouskim.http
import io.netty.handler.codec.http.HttpResponseStatus
import io.vertx.kotlin.lang.setStatus
import java.util.regex.Pattern
/**
* Created by jinyunzhe on 16/4/5.
*/
open abstract class UrlPipeLine(open val filters: Array<Filter>, open val action: Action) {
abstract fun match(httpRequest: HttpRequest): Boolean
open fun service(request: HttpRequest, response: HttpResponse) {
if (filters.size > 0) {
Chain(filters, action).doFilterChain(request,response)
} else {
action.doAction(request, response)
}
}
fun init(indent: MutableSet<Any>) {
filters.filter { !indent.contains(it) }.forEach {
it.init()
indent.add(it)
}
}
private class Chain(val filters: Array<Filter>, val action: Action) : FilterChain {
private var index = 0
override fun doFilterChain(httpRequest: HttpRequest, httpResponse: HttpResponse) {
if (index < filters.size) {
filters[index++].doFilter(httpRequest, httpResponse, this)
} else {
action.doAction(httpRequest, httpResponse)
}
}
}
}
class RegxPipeLine(val patter: Pattern, override val filters: Array<Filter>, override val action: Action) : UrlPipeLine(filters, action) {
override fun match(httpRequest: HttpRequest): Boolean {
val path = httpRequest.path()
return patter.matcher(path).matches()
}
override fun service(request: HttpRequest, response: HttpResponse) {
val uri = request.uri()
val matcher = patter.matcher(uri)
if (!matcher.matches()) {
response.setStatus(HttpResponseStatus.NOT_FOUND, "Not match")
return
}
if (matcher.groupCount() > 0) {
} else {
}
}
}
class SuffixPipeLine(val suffix: String, override val filters: Array<Filter>, override val action: Action) : UrlPipeLine(filters, action) {
val suffixLength = suffix.length
override fun match(httpRequest: HttpRequest): Boolean {
return httpRequest.path()?.endsWith(suffix) ?: false
}
override fun service(request: HttpRequest, response: HttpResponse) {
super.service(WrapHttpRequest(suffix,request), response)
}
}
|
mit
|
563eb5cf7c2d3494af8736b51992c626
| 27.518519 | 139 | 0.638961 | 4.36673 | false | false | false | false |
minecraft-dev/MinecraftDev
|
src/main/kotlin/translations/intentions/TrimKeyIntention.kt
|
1
|
1457
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.intentions
import com.demonwav.mcdev.translations.TranslationFiles
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.util.IncorrectOperationException
class TrimKeyIntention : PsiElementBaseIntentionAction() {
override fun getText() = "Trim translation key"
override fun getFamilyName() = "Minecraft"
override fun isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean {
val translation = TranslationFiles.toTranslation(
TranslationFiles.seekTranslation(element) ?: return false
) ?: return false
return translation.key != translation.trimmedKey
}
@Throws(IncorrectOperationException::class)
override fun invoke(project: Project, editor: Editor, element: PsiElement) {
val entry = TranslationFiles.seekTranslation(element) ?: return
if (!FileModificationService.getInstance().preparePsiElementForWrite(entry)) {
return
}
val translation = TranslationFiles.toTranslation(entry) ?: return
entry.setName(translation.trimmedKey)
}
}
|
mit
|
7e4986e7386e50121051e64b39561be1
| 32.113636 | 94 | 0.746054 | 5.041522 | false | false | false | false |
andstatus/andstatus
|
app/src/main/kotlin/org/andstatus/app/backup/MyBackupDescriptor.kt
|
1
|
9599
|
/*
* Copyright (C) 2014-2019 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.backup
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.ParcelFileDescriptor
import androidx.documentfile.provider.DocumentFile
import org.andstatus.app.context.MyContextHolder
import org.andstatus.app.context.MyPreferences
import org.andstatus.app.database.DatabaseCreator
import org.andstatus.app.util.DocumentFileUtils
import org.andstatus.app.util.FileDescriptorUtils
import org.andstatus.app.util.JsonUtils
import org.andstatus.app.util.MyLog
import org.json.JSONException
import org.json.JSONObject
import java.io.BufferedWriter
import java.io.FileDescriptor
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
import java.io.OutputStreamWriter
import java.nio.charset.StandardCharsets
class MyBackupDescriptor private constructor(private val progressLogger: ProgressLogger) {
private var backupSchemaVersion = BACKUP_SCHEMA_VERSION_UNKNOWN
private var appInstanceName: String = ""
private var applicationVersionCode = 0
private var applicationVersionName: String = ""
private var createdDate: Long = 0
private var saved = false
private var fileDescriptor: FileDescriptor? = null
private var docDescriptor: DocumentFile? = null
private var accountsCount: Long = 0
fun setJson(jso: JSONObject) {
backupSchemaVersion = jso.optInt(KEY_BACKUP_SCHEMA_VERSION,
backupSchemaVersion)
createdDate = jso.optLong(KEY_CREATED_DATE, createdDate)
saved = createdDate != 0L
appInstanceName = JsonUtils.optString(jso, KEY_APP_INSTANCE_NAME, appInstanceName)
applicationVersionCode = jso.optInt(KEY_APPLICATION_VERSION_CODE, applicationVersionCode)
applicationVersionName = JsonUtils.optString(jso, KEY_APPLICATION_VERSION_NAME, applicationVersionName)
accountsCount = jso.optLong(KEY_ACCOUNTS_COUNT, accountsCount)
if (backupSchemaVersion != BACKUP_SCHEMA_VERSION) {
try {
MyLog.w(TAG, "Bad backup descriptor: " + jso.toString(2))
} catch (e: JSONException) {
MyLog.d(TAG, "Bad backup descriptor: " + jso.toString(), e)
}
}
}
private fun setEmptyFields(context: Context) {
backupSchemaVersion = BACKUP_SCHEMA_VERSION
val pm = context.getPackageManager()
val pi: PackageInfo = try {
pm.getPackageInfo(context.getPackageName(), 0)
} catch (e: PackageManager.NameNotFoundException) {
throw IOException(e)
}
appInstanceName = MyPreferences.getAppInstanceName()
applicationVersionCode = pi.versionCode
applicationVersionName = pi.versionName
}
fun getBackupSchemaVersion(): Int {
return backupSchemaVersion
}
fun getCreatedDate(): Long {
return createdDate
}
fun getApplicationVersionCode(): Int {
return applicationVersionCode
}
fun getApplicationVersionName(): String {
return applicationVersionName
}
fun isEmpty(): Boolean {
return fileDescriptor == null && docDescriptor == null
}
fun save(context: Context) {
if (isEmpty()) {
throw FileNotFoundException("MyBackupDescriptor is empty")
}
try {
docDescriptor?.let {
context.getContentResolver().openOutputStream(it.getUri())?.use { outputStream ->
if (createdDate == 0L) createdDate = System.currentTimeMillis()
writeStringToStream(toJson().toString(2), outputStream)
saved = true
}
} ?: FileOutputStream(fileDescriptor)
} catch (e: JSONException) {
throw IOException(e)
}
}
private fun toJson(): JSONObject {
val jso = JSONObject()
if (isEmpty()) return jso
try {
jso.put(KEY_BACKUP_SCHEMA_VERSION, backupSchemaVersion)
jso.put(KEY_APP_INSTANCE_NAME, appInstanceName)
jso.put(KEY_CREATED_DATE, createdDate)
jso.put(KEY_CREATED_DEVICE, MyPreferences.getDeviceBrandModelString())
jso.put(KEY_APPLICATION_VERSION_CODE, applicationVersionCode)
jso.put(KEY_APPLICATION_VERSION_NAME, applicationVersionName)
jso.put(KEY_ACCOUNTS_COUNT, accountsCount)
} catch (e: JSONException) {
MyLog.w(this, "toJson", e)
}
return jso
}
private fun writeStringToStream(string: String, outputStream: OutputStream) {
val method = "writeStringToFileDescriptor"
try {
BufferedWriter(OutputStreamWriter(outputStream, StandardCharsets.UTF_8)).use { out -> out.write(string) }
} catch (e: IOException) {
MyLog.d(this, method, e)
throw FileNotFoundException(method + "; " + e.localizedMessage)
}
}
override fun toString(): String {
return "MyBackupDescriptor " + toJson().toString()
}
fun saved(): Boolean {
return saved
}
fun getAccountsCount(): Long {
return accountsCount
}
fun setAccountsCount(accountsCount: Long) {
this.accountsCount = accountsCount
progressLogger.logProgress("Accounts backed up:$accountsCount")
}
fun getLogger(): ProgressLogger {
return progressLogger
}
fun appVersionNameAndCode(): String {
return "app version name:'" +
(if (getApplicationVersionName().isEmpty()) "???" else getApplicationVersionName()) + "'" +
", version code:'" + getApplicationVersionCode() + "'"
}
companion object {
private val TAG: Any = MyBackupDescriptor::class.java
const val BACKUP_SCHEMA_VERSION_UNKNOWN = -1
/** Depends, in particular, on @[DatabaseCreator.DATABASE_VERSION]
* v.7 2017-11-04 app.v.36 Moving to ActivityStreams data model
* v.6 2016-11-27 app.v.31 database schema changed
* v.5 2016-05-22 app.v.27 database schema changed
* v.4 2016-02-28 app.v.23 database schema changed
*/
const val BACKUP_SCHEMA_VERSION = 7
val KEY_BACKUP_SCHEMA_VERSION: String = "backup_schema_version"
val KEY_APP_INSTANCE_NAME: String = MyPreferences.KEY_APP_INSTANCE_NAME
val KEY_CREATED_DATE: String = "created_date"
val KEY_CREATED_DEVICE: String = "created_device"
val KEY_APPLICATION_VERSION_CODE: String = "app_version_code"
val KEY_APPLICATION_VERSION_NAME: String = "app_version_name"
val KEY_ACCOUNTS_COUNT: String = "accounts_count"
fun getEmpty(): MyBackupDescriptor {
return MyBackupDescriptor(ProgressLogger.getEmpty(""))
}
fun fromOldParcelFileDescriptor(parcelFileDescriptor: ParcelFileDescriptor?,
progressLogger: ProgressLogger): MyBackupDescriptor {
val myBackupDescriptor = MyBackupDescriptor(progressLogger)
if (parcelFileDescriptor != null) {
myBackupDescriptor.fileDescriptor = parcelFileDescriptor.fileDescriptor
val jso = FileDescriptorUtils.getJSONObject(parcelFileDescriptor.fileDescriptor)
myBackupDescriptor.setJson(jso)
}
return myBackupDescriptor
}
fun fromOldDocFileDescriptor(context: Context, parcelFileDescriptor: DocumentFile?,
progressLogger: ProgressLogger): MyBackupDescriptor {
val myBackupDescriptor = MyBackupDescriptor(progressLogger)
if (parcelFileDescriptor != null) {
myBackupDescriptor.docDescriptor = parcelFileDescriptor
myBackupDescriptor.setJson(DocumentFileUtils.getJSONObject(context, parcelFileDescriptor))
}
return myBackupDescriptor
}
fun fromEmptyParcelFileDescriptor(parcelFileDescriptor: ParcelFileDescriptor,
progressLoggerIn: ProgressLogger): MyBackupDescriptor {
val myBackupDescriptor = MyBackupDescriptor(progressLoggerIn)
myBackupDescriptor.fileDescriptor = parcelFileDescriptor.getFileDescriptor()
myBackupDescriptor.setEmptyFields( MyContextHolder.myContextHolder.getNow().baseContext)
myBackupDescriptor.backupSchemaVersion = BACKUP_SCHEMA_VERSION
return myBackupDescriptor
}
fun fromEmptyDocumentFile(context: Context, documentFile: DocumentFile?,
progressLoggerIn: ProgressLogger): MyBackupDescriptor {
val myBackupDescriptor = MyBackupDescriptor(progressLoggerIn)
myBackupDescriptor.docDescriptor = documentFile
myBackupDescriptor.setEmptyFields(context)
return myBackupDescriptor
}
}
}
|
apache-2.0
|
74902de402822a94b94614c171a3fc7c
| 40.197425 | 117 | 0.668715 | 5.291621 | false | false | false | false |
google/android-auto-companion-android
|
trustagent/tests/unit/src/com/google/android/libraries/car/trustagent/AssociationManagerTest.kt
|
1
|
17475
|
// Copyright 2021 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.android.libraries.car.trustagent
import android.Manifest.permission
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.companion.AssociationRequest as CdmAssociationRequest
import android.companion.BluetoothDeviceFilter
import android.companion.BluetoothLeDeviceFilter
import android.companion.CompanionDeviceManager
import android.content.Context
import android.content.Intent
import android.os.ParcelUuid
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.rule.GrantPermissionRule
import com.google.android.libraries.car.trustagent.blemessagestream.BluetoothConnectionManager
import com.google.android.libraries.car.trustagent.blemessagestream.BluetoothGattManager
import com.google.android.libraries.car.trustagent.testutils.Base64CryptoHelper
import com.google.android.libraries.car.trustagent.testutils.FakeMessageStream
import com.google.android.libraries.car.trustagent.testutils.FakeSecretKey
import com.google.android.libraries.car.trustagent.testutils.createScanRecord
import com.google.android.libraries.car.trustagent.testutils.createScanResult
import com.google.common.truth.Truth.assertThat
import com.google.common.util.concurrent.MoreExecutors.directExecutor
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.inOrder
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.spy
import com.nhaarman.mockitokotlin2.verify
import java.util.UUID
import kotlin.random.Random
import kotlin.test.fail
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.shadow.api.Shadow
import org.robolectric.shadows.ShadowBluetoothDevice
// Randomly generated UUID.
private val TEST_UUID = UUID.fromString("8a16e891-d4ad-455d-8194-cbc2dfbaebdf")
private val TEST_DEVICE_ID = UUID.randomUUID()
private val TEST_PREFIX = "TestPrefix"
private val TEST_MACADDRESS = "00:11:22:AA:BB:CC"
private val TEST_BLUETOOTH_DEVICE =
BluetoothAdapter.getDefaultAdapter().getRemoteDevice(TEST_MACADDRESS)
private val TEST_IDENTIFICATION_KEY = FakeSecretKey()
private val TEST_STREAM = FakeMessageStream()
private val SHORT_LOCAL_NAME = "name"
private val SERVICE_DATA = Random.nextBytes(ByteArray(2))
/** Tests for [AssociationManager]. */
@ExperimentalCoroutinesApi
@RunWith(AndroidJUnit4::class)
class AssociationManagerTest {
@get:Rule
val grantPermissionRule: GrantPermissionRule =
GrantPermissionRule.grant(
permission.ACCESS_FINE_LOCATION,
permission.ACCESS_BACKGROUND_LOCATION,
permission.BLUETOOTH_SCAN,
permission.BLUETOOTH_CONNECT,
)
private val testDispatcher = UnconfinedTestDispatcher()
private val context = ApplicationProvider.getApplicationContext<Context>()
private lateinit var database: ConnectedCarDatabase
private lateinit var bleManager: FakeBleManager
private lateinit var associationManager: AssociationManager
private lateinit var associatedCarManager: AssociatedCarManager
private lateinit var discoveryCallback: AssociationManager.DiscoveryCallback
private lateinit var associationCallback: AssociationManager.AssociationCallback
private lateinit var disassociationCallback: AssociationManager.DisassociationCallback
private lateinit var car: Car
private lateinit var bluetoothGattManager: BluetoothGattManager
private lateinit var associationHandler: TestAssociationHandler
@Before
fun setUp() {
// Using directExecutor to ensure that all operations happen on the main thread and allows for
// tests to wait until the operations are done before continuing. Without this, operations can
// leak and interfere between tests. See b/153095973 for details.
database =
Room.inMemoryDatabaseBuilder(context, ConnectedCarDatabase::class.java)
.allowMainThreadQueries()
.setQueryExecutor(directExecutor())
.build()
associatedCarManager = AssociatedCarManager(context, database, Base64CryptoHelper())
bleManager = spy(FakeBleManager())
discoveryCallback = mock()
associationCallback = mock()
disassociationCallback = mock()
bluetoothGattManager = mock { on { bluetoothDevice } doReturn TEST_BLUETOOTH_DEVICE }
car = Car(bluetoothGattManager, TEST_STREAM, TEST_IDENTIFICATION_KEY, TEST_DEVICE_ID)
associationManager =
AssociationManager(context, associatedCarManager, bleManager).apply {
registerDiscoveryCallback(discoveryCallback)
registerAssociationCallback(associationCallback)
registerDisassociationCallback(disassociationCallback)
}
associationHandler =
spy(TestAssociationHandler()).also { associationManager.associationHandler = it }
associationManager.coroutineContext = testDispatcher
}
@After
fun after() {
database.close()
}
@Test
fun testStartDiscovery_notEnabled_doesNotStartScan() {
bleManager.isEnabled = false
assertThat(associationManager.startDiscovery(TEST_UUID, TEST_PREFIX)).isFalse()
verify(bleManager, never()).startScan(any(), any(), any())
}
@Test
fun testStartDiscovery_failedScan_returnsFalse() {
bleManager.startScanSucceeds = false
assertThat(associationManager.startDiscovery(TEST_UUID, TEST_PREFIX)).isFalse()
}
@Test
fun testStartDiscovery_startsScanWithPassedUuid() {
assertThat(associationManager.startDiscovery(TEST_UUID, TEST_PREFIX)).isTrue()
argumentCaptor<List<ScanFilter>>().apply {
verify(bleManager).startScan(capture(), any(), any())
val filters = firstValue
assertThat(filters).hasSize(1)
val scanFilter = filters.first()
assertThat(scanFilter.serviceUuid).isEqualTo(ParcelUuid(TEST_UUID))
}
}
@Test
fun testStartDiscovery_stopsPreviousScan() {
assertThat(associationManager.startDiscovery(TEST_UUID, TEST_PREFIX)).isTrue()
argumentCaptor<ScanCallback>().apply {
verify(bleManager).startScan(any(), any(), capture())
verify(bleManager).stopScan(capture())
assertThat(firstValue).isEqualTo(secondValue)
}
}
@Test
fun onScanResult_returnsCorrectDiscoveredCar() {
assertThat(associationManager.startDiscovery(TEST_UUID, TEST_PREFIX)).isTrue()
val serviceData = hashMapOf(AssociationManager.DEVICE_NAME_DATA_UUID to SERVICE_DATA)
val scanRecord =
createScanRecord(name = null, serviceUuids = listOf(TEST_UUID), serviceData = serviceData)
val scanResult = createScanResult(scanRecord)
bleManager.triggerOnScanResult(scanResult)
val expectedCar =
DiscoveredCar(scanResult.device, "$TEST_PREFIX${SERVICE_DATA.toHexString()}", TEST_UUID, null)
verify(discoveryCallback).onDiscovered(expectedCar)
}
@Test
fun onScanResult_returnScanRecordName_ifServiceDataDoesNotHaveName() {
assertThat(associationManager.startDiscovery(TEST_UUID, TEST_PREFIX)).isTrue()
val scanRecord =
createScanRecord(
name = SHORT_LOCAL_NAME,
serviceUuids = listOf(TEST_UUID),
serviceData = emptyMap()
)
val scanResult = createScanResult(scanRecord)
bleManager.triggerOnScanResult(scanResult)
val expectedCar = DiscoveredCar(scanResult.device, SHORT_LOCAL_NAME, TEST_UUID, null)
verify(discoveryCallback).onDiscovered(expectedCar)
}
@Test
fun onScanResult_doesNotInvokeCallback_ifWrongServiceUuid() {
assertThat(associationManager.startDiscovery(TEST_UUID, TEST_PREFIX)).isTrue()
val invalidUuid = UUID.fromString("b8695c70-442d-4113-9893-7ef7565940a0")
val serviceData =
hashMapOf(AssociationManager.DEVICE_NAME_DATA_UUID to "deviceName".toByteArray())
val scanRecord =
createScanRecord(name = null, serviceUuids = listOf(invalidUuid), serviceData = serviceData)
val scanResult = createScanResult(scanRecord)
bleManager.triggerOnScanResult(scanResult)
verify(discoveryCallback, never()).onDiscovered(any())
}
@Test
fun onScanResult_doesNotInvokeCallback_ifMultipleServiceUuids() {
assertThat(associationManager.startDiscovery(TEST_UUID, TEST_PREFIX)).isTrue()
val invalidUuid = UUID.fromString("b8695c70-442d-4113-9893-7ef7565940a0")
val serviceData =
hashMapOf(AssociationManager.DEVICE_NAME_DATA_UUID to "deviceName".toByteArray())
val scanRecord =
createScanRecord(
name = null,
serviceUuids = listOf(TEST_UUID, invalidUuid),
serviceData = serviceData
)
val scanResult = createScanResult(scanRecord)
bleManager.triggerOnScanResult(scanResult)
verify(discoveryCallback, never()).onDiscovered(any())
}
@Test
fun onScanResult_doesNotInvokeCallback_ifNullScanResult() {
assertThat(associationManager.startDiscovery(TEST_UUID, TEST_PREFIX)).isTrue()
bleManager.triggerOnScanResult(null)
verify(discoveryCallback, never()).onDiscovered(any())
}
@Test
fun startSppDiscovery_bluetoothDisabled_returnsFalse() {
bleManager.isEnabled = false
assertThat(associationManager.startSppDiscovery()).isFalse()
assertThat(associationManager.isSppDiscoveryStarted).isFalse()
}
@Test
fun startSppDiscovery_startedSuccessfully_updateFlag() {
bleManager.isEnabled = true
assertThat(associationManager.startSppDiscovery()).isTrue()
assertThat(associationManager.isSppDiscoveryStarted).isTrue()
}
@Test
fun associate_onAssociationFailed() {
val mockBluetoothManager =
mock<BluetoothConnectionManager> { onBlocking { connectToDevice() } doReturn false }
val mockDiscoveredCar =
mock<DiscoveredCar> {
on { toBluetoothConnectionManagers(any()) } doReturn listOf(mockBluetoothManager)
}
associationManager.associate(mockDiscoveredCar)
verify(associationCallback).onAssociationFailed()
}
@Test
fun associate_onAssociationStart() {
val mockBluetoothManager =
mock<BluetoothConnectionManager> { onBlocking { connectToDevice() } doReturn true }
val mockDiscoveredCar =
mock<DiscoveredCar> {
on { toBluetoothConnectionManagers(any()) } doReturn listOf(mockBluetoothManager)
}
associationManager.associate(mockDiscoveredCar)
verify(associationCallback).onAssociationStart()
}
@Test
fun associate_stopSppDiscovery() {
assertThat(associationManager.startSppDiscovery()).isTrue()
associationManager.coroutineContext = testDispatcher
val deviceName = SHORT_LOCAL_NAME
val scanRecord =
createScanRecord(
name = deviceName,
serviceUuids = listOf(TEST_UUID),
serviceData = emptyMap()
)
val scanResult = createScanResult(scanRecord)
// SPP UUID does not matter here.
val testDiscoveredCar =
DiscoveredCar(scanResult.device, deviceName, TEST_UUID, sppServiceUuid = null)
associationManager.associate(testDiscoveredCar)
assertThat(associationManager.isSppDiscoveryStarted).isFalse()
}
@Test
fun clearCurrentAssociation_stopSppDiscovery() {
assertThat(associationManager.startSppDiscovery()).isTrue()
associationManager.clearCurrentAssociation()
assertThat(associationManager.isSppDiscoveryStarted).isFalse()
}
@Test
fun clearCurrentCdmAssociation_disassociateCdm() {
val macAddress = "00:11:22:33:AA:BB"
val bluetoothDevice = ShadowBluetoothDevice.newInstance(macAddress)
val shadowBluetoothDevice = Shadow.extract<ShadowBluetoothDevice>(bluetoothDevice)
shadowBluetoothDevice.setName("testName")
val request =
AssociationRequest.Builder(
Intent().putExtra(CompanionDeviceManager.EXTRA_DEVICE, bluetoothDevice)
)
.build()
associationManager.associate(request)
associationManager.clearCurrentCdmAssociation()
verify(associationManager.associationHandler).disassociate(macAddress)
}
@Test
fun clearCurrentCdmAssociation_associationCompleted_doNotClearDevice() {
val macAddress = "00:11:22:33:AA:BB"
val bluetoothDevice = ShadowBluetoothDevice.newInstance(macAddress)
val shadowBluetoothDevice = Shadow.extract<ShadowBluetoothDevice>(bluetoothDevice)
shadowBluetoothDevice.setName("testName")
val request =
AssociationRequest.Builder(
Intent().putExtra(CompanionDeviceManager.EXTRA_DEVICE, bluetoothDevice)
)
.build()
associationManager.associate(request)
associationManager.pendingCarCallback.onConnected(car)
associationManager.clearCurrentCdmAssociation()
verify(associationManager.associationHandler, never()).disassociate(macAddress)
}
@Test
fun clearCdmAssociatedCar_disassociateCdm() {
runBlocking {
associatedCarManager.add(car)
associationManager.clearCdmAssociatedCar(TEST_DEVICE_ID)
verify(associationManager.associationHandler).disassociate(TEST_MACADDRESS)
}
}
@Test
fun clearAllAssociatedCars_disassociateCdm() {
runBlocking {
associationManager.clearAllCdmAssociatedCars()
verify(associationManager.associationHandler).disassociate(TEST_MACADDRESS)
}
}
@Test
fun testStartCdmDiscovery_doesNotIncludeSppDeviceFilter_ifSppDisabled() {
associationManager.isSppEnabled = false
val discoveryRequest = DiscoveryRequest.Builder(Activity()).build()
associationManager.startCdmDiscovery(discoveryRequest, mock())
// `AssocationRequest` is a final object, so cannot use an ArgumentCaptor to capture it.
val request =
checkNotNull(associationHandler.request) {
"Method `associate` was not called in startCdmDiscovery"
}
// `getDeviceFilters` is an @hide method.
val getDeviceFiltersMethod = request.javaClass.getMethod("getDeviceFilters")
val filters = getDeviceFiltersMethod.invoke(request)
if (filters !is List<*>) {
fail("Unexpected. `getDeviceFilters` returned wrong type. Did the method change?")
}
assertThat(filters).hasSize(1)
assertThat(filters.first()).isInstanceOf(BluetoothLeDeviceFilter::class.java)
}
@Test
fun testStartCdmDiscovery_doesIncludesSppDeviceFilter_ifSppEnabled() {
associationManager.isSppEnabled = true
val discoveryRequest = DiscoveryRequest.Builder(Activity()).build()
associationManager.startCdmDiscovery(discoveryRequest, mock())
// `AssocationRequest` is a final object, so cannot use an ArgumentCaptor to capture it.
val request =
checkNotNull(associationHandler.request) {
"Method `associate` was not called in startCdmDiscovery"
}
// `getDeviceFilters` is an @hide method.
val getDeviceFiltersMethod = request.javaClass.getMethod("getDeviceFilters")
val filters = getDeviceFiltersMethod.invoke(request)
if (filters !is List<*>) {
fail("Unexpected. `getDeviceFilters` returned wrong type. Did the method change?")
}
assertThat(filters).hasSize(2)
assertThat(filters.any { it is BluetoothDeviceFilter }).isTrue()
assertThat(filters.any { it is BluetoothLeDeviceFilter }).isTrue()
}
@Test
fun testDeviceIdReceived_notifiesCallback() {
associationManager.pendingCarCallback.onDeviceIdReceived(TEST_DEVICE_ID)
verify(disassociationCallback, never()).onCarDisassociated(TEST_DEVICE_ID)
verify(associationCallback).onDeviceIdReceived(TEST_DEVICE_ID)
}
@Test
fun testDeviceIdReceived_previouslyAssociated_issuesDisassocationCallback() {
runBlocking {
// Simulate that the car has already been associated.
associatedCarManager.add(car)
// Then, receiving the same device ID again.
associationManager.pendingCarCallback.onDeviceIdReceived(TEST_DEVICE_ID)
// The disassociation callback should be issued first.
val order = inOrder(disassociationCallback, associationCallback)
order.verify(disassociationCallback).onCarDisassociated(TEST_DEVICE_ID)
order.verify(associationCallback).onDeviceIdReceived(TEST_DEVICE_ID)
}
}
private fun ByteArray.toHexString(): String {
return this.joinToString("") { String.format("%02X", it) }
}
open class TestAssociationHandler() : AssociationHandler {
var request: CdmAssociationRequest? = null
override val associations = mutableListOf(TEST_MACADDRESS)
override fun associate(
activity: Activity,
request: CdmAssociationRequest,
callback: CompanionDeviceManager.Callback
) {
this.request = request
}
override fun disassociate(macAddress: String): Boolean {
// No implementation
return true
}
}
}
|
apache-2.0
|
5fd058b6d3158fa8f68e48d38d247920
| 34.95679 | 100 | 0.764177 | 4.949023 | false | true | false | false |
TUWien/DocScan
|
app/src/main/java/at/ac/tuwien/caa/docscan/api/transkribus/TranskribusHeaderInterceptor.kt
|
1
|
1390
|
package at.ac.tuwien.caa.docscan.api.transkribus
import at.ac.tuwien.caa.docscan.logic.PreferencesHandler
import okhttp3.Interceptor
import okhttp3.Response
/**
* @author matej bartalsky
*/
class TranskribusHeaderInterceptor constructor(
private val preferencesHandler: PreferencesHandler
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val requestBuilder = request.newBuilder()
// as long as the Accept header is not explicitly set for the request, then the
// default one will always be json.
if (request.header("Accept") == null) {
// accepts responses only in json format, otherwise the API would return an XML
requestBuilder.addHeader("Accept", "application/json")
}
// appends cookie for authorization, if the cookie is not available, then all transkribus
// requests which require authorization will return a http 401.
preferencesHandler.transkribusCookie?.let {
requestBuilder.addHeader("Cookie", "JSESSIONID=$it")
}
val response = chain.proceed(requestBuilder.build())
// read and update the cookie after the request has been performed.
response.header("Cookie")?.let {
preferencesHandler.transkribusCookie = it
}
return response
}
}
|
lgpl-3.0
|
97431ce275f954e3a0c9180cfc7361cb
| 37.611111 | 97 | 0.684173 | 4.843206 | false | false | false | false |
esofthead/mycollab
|
mycollab-dao/src/main/java/com/mycollab/security/AccessPermissionFlag.kt
|
3
|
1892
|
/**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.security
/**
* Access permission flag
*
* @author MyCollab Ltd
* @since 1.0
*/
class AccessPermissionFlag : PermissionFlag() {
companion object {
const val NO_ACCESS = 0
const val READ_ONLY = 1
const val READ_WRITE = 2
const val ACCESS = 4
/**
* Check whether `flag` implies read permission
*
* @param flag
* @return true of `flag` implies read permission
*/
fun canRead(flag: Int): Boolean = (flag and READ_ONLY == READ_ONLY
|| flag and READ_WRITE == READ_WRITE
|| flag and ACCESS == ACCESS)
/**
* Check whether `flag` implies write permission
*
* @param flag
* @return true of `flag` implies write permission
*/
fun canWrite(flag: Int): Boolean = flag and READ_WRITE == READ_WRITE || flag and ACCESS == ACCESS
/**
* Check whether `flag` implies access permission
*
* @param flag
* @return true of `flag` implies access permission
*/
fun canAccess(flag: Int): Boolean = flag and ACCESS == ACCESS
}
}
|
agpl-3.0
|
634f89b6170caced0255f3746f677060
| 30 | 105 | 0.619778 | 4.491686 | false | false | false | false |
inorichi/tachiyomi-extensions
|
multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/webtoons/WebtoonsTranslateGenerator.kt
|
1
|
955
|
package eu.kanade.tachiyomi.multisrc.webtoons
import generator.ThemeSourceData.SingleLang
import generator.ThemeSourceData.MultiLang
import generator.ThemeSourceGenerator
class WebtoonsTranslateGenerator : ThemeSourceGenerator {
override val themePkg = "webtoons"
override val themeClass = "WebtoonsTranslation"
override val baseVersionCode: Int = 2
override val sources = listOf(
MultiLang("Webtoons.com Translations", "https://translate.webtoons.com", listOf("en", "zh-hans", "zh-hant", "th", "id", "fr", "vi", "ru", "ar", "fil", "de", "hi", "it", "ja", "pt-BR", "tr", "ms", "pl", "pt", "bg", "da", "nl", "ro", "mn", "el", "lt", "cs", "sv", "bn", "fa", "uk", "es"), className = "WebtoonsTranslateFactory", pkgName = "webtoonstranslate", overrideVersionCode = 1),
)
companion object {
@JvmStatic
fun main(args: Array<String>) {
WebtoonsTranslateGenerator().createAll()
}
}
}
|
apache-2.0
|
021685a7b417e20e25fb5a5e5fe86b3b
| 38.791667 | 392 | 0.651309 | 3.70155 | false | false | false | false |
inorichi/tachiyomi-extensions
|
src/all/mangapark/src/eu/kanade/tachiyomi/extension/all/mangapark/MangaParkUrlActivity.kt
|
1
|
1447
|
package eu.kanade.tachiyomi.extension.all.mangapark
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.util.Log
import kotlin.system.exitProcess
class MangaParkUrlActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val host = intent?.data?.host
val pathSegments = intent?.data?.pathSegments
if (host != null && pathSegments != null) {
val query = fromGuya(pathSegments)
if (query == null) {
Log.e("MangaParkUrlActivity", "Unable to parse URI from intent $intent")
finish()
exitProcess(1)
}
val mainIntent = Intent().apply {
action = "eu.kanade.tachiyomi.SEARCH"
putExtra("query", query)
putExtra("filter", packageName)
}
try {
startActivity(mainIntent)
} catch (e: ActivityNotFoundException) {
Log.e("MangaParkUrlActivity", e.toString())
}
}
finish()
exitProcess(0)
}
private fun fromGuya(pathSegments: MutableList<String>): String? {
return if (pathSegments.size >= 2) {
val id = pathSegments[1]
"id:$id"
} else {
null
}
}
}
|
apache-2.0
|
e71039319aab3d8278de0fad0a4d1ae1
| 27.372549 | 88 | 0.570836 | 4.905085 | false | false | false | false |
elect86/jAssimp
|
src/test/kotlin/assimp/collada/treasure_smooth Pretransform.kt
|
2
|
6001
|
package assimp.collada
import assimp.*
import glm_.mat4x4.Mat4
import glm_.vec3.Vec3
import io.kotest.matchers.shouldBe
import java.net.URL
object `treasure_smooth Pretransform` {
operator fun invoke(fileName: URL) {
Importer().testFile(fileName, AiPostProcessStep.PreTransformVertices.i){
flags shouldBe 0
with(rootNode) {
name shouldBe "Scene"
transformation shouldBe Mat4()
parent shouldBe null
numChildren shouldBe 11
with(children[0]) {
name shouldBe "Plane"
transformation shouldBe Mat4()
(parent === rootNode) shouldBe true
numChildren shouldBe 0
children.isEmpty() shouldBe true
numMeshes shouldBe 1
meshes[0] shouldBe 0
metaData.isEmpty() shouldBe true
}
// with(children[16]) {
// name shouldBe "Cylinder_015"
// transformation shouldBe Mat4(
// 0.0866885632f, -0.0170170404f, 0.01285674f, 0f,
// 0.0152270300f, 0.08706335f, 0.01256552f,0f,
// -0.01493363f, -0.01000874f,0.08744479f,0f,
// 1.314583f,-5.515009f,0.4121983f,1f)
// (parent === rootNode) shouldBe true
// numChildren shouldBe 0
// children.isEmpty() shouldBe true
// numMeshes shouldBe 2
// meshes[0] shouldBe 26
// meshes[1] shouldBe 27
// metaData.isEmpty() shouldBe true
// }
//
// with(children[34]) {
// name shouldBe "Cube_015"
// transformation shouldBe Mat4(
// 0.122561797f, -0.0906103402f, 0.00194863102f, 0f,
// 0.0853303894f, 0.116471097f, 0.0488739200f, 0f,
// -0.0305411592f, -0.0382059515f, 0.144371003f, 0f,
// 1.10377395f, -4.13784218f, 0.766323626f, 1f)
// (parent === rootNode) shouldBe true
// numChildren shouldBe 0
// children.isEmpty() shouldBe true
// numMeshes shouldBe 1
// meshes[0] shouldBe 48
// metaData.isEmpty() shouldBe true
// }
//
// with(children[67]) {
// name shouldBe "Cylinder_027"
// transformation shouldBe Mat4(
// 0.0158306006f, 0.0467648916f, 0.00405431492f, 0f,
// -0.0440383293f, 0.0133153200f, 0.0183664802f, 0f,
// 0.0162486192f, -0.00947351381f, 0.0458283201f, 0f,
// -0.724227428f, -2.80546498f, 0.661597490f, 1f)
// (parent === rootNode) shouldBe true
// numChildren shouldBe 0
// children.isEmpty() shouldBe true
// numMeshes shouldBe 2
// meshes[0] shouldBe 84
// meshes[1] shouldBe 85
// metaData.isEmpty() shouldBe true
// }
}
// numMeshes shouldBe 86
// with(meshes[0]) {
// primitiveTypes shouldBe AiPrimitiveType.TRIANGLE.i
// numVertices shouldBe 1554
// numFaces shouldBe 518
// vertices[0] shouldBe Vec3(7.50098801f, 6.56336403f, 0f)
// vertices[776] shouldBe Vec3(-1.62673700f, -3.29218197f, 0.503621578f)
// vertices[1553] shouldBe Vec3(-1.15598500f, -3.56582594f, 0.488107890f)
// normals[0] shouldBe Vec3(0.00296032405f, 0.000976616982f, 0.999995172f)
// normals[776] shouldBe Vec3(0.600491107f, 0.295148909f, 0.743167281f)
// normals[1553] shouldBe Vec3(0.254105508f, 0.335226387f, 0.907223225f)
// for (i in 0 until numFaces)
// for (j in 0..2)
// faces[i][j] shouldBe i * 3 + j
// name shouldBe "Plane"
// }
// // submesh
// with(meshes[1]) {
// primitiveTypes shouldBe AiPrimitiveType.TRIANGLE.i
// numVertices shouldBe 342
// numFaces shouldBe 114
// vertices[0] shouldBe Vec3(0.860741317f, -3.45404100f, 0.648772180f)
// vertices[170] shouldBe Vec3(-0.884529710f, -1.541123f, -0.220538393f)
// vertices[341] shouldBe Vec3(-0.593643427f, -1.76318300f, -0.361052006f)
// normals[0] shouldBe Vec3(-0.639659882f, 0.316945910f, 0.700271904f)
// normals[170] shouldBe Vec3(0.697514117f, -0.194711894f, 0.689609706f)
// normals[341] shouldBe Vec3(0.263714999f, 0.0831033513f, 0.961014211f)
// for(i in 0 until numFaces)
// for(j in 0..2)
// faces[i][j] shouldBe i * 3 + j
// name shouldBe "Plane"
// }
// numMaterials shouldBe 1
// with(materials[0]) {
// name shouldBe "test_Smoothing"
// shadingModel shouldBe AiShadingMode.blinn
// twoSided shouldBe false
// wireframe shouldBe false
// with(color!!) {
// ambient shouldBe Vec3(0.100000001f)
// diffuse shouldBe Vec3(0.141176000f, 0.184313998f, 0.411765009f)
// specular shouldBe Vec3(0.400000006f)
// emissive shouldBe Vec3()
// reflective shouldBe Vec3()
// }
// shininess shouldBe 10f
// reflectivity shouldBe 0f
// refracti shouldBe 1f
// }
}
}
}
|
mit
|
02b9dbcd71a79b0eefd0e065bad1ebc4
| 44.12782 | 89 | 0.490252 | 3.864134 | false | false | false | false |
fredyw/leetcode
|
src/main/kotlin/leetcode/Problem2244.kt
|
1
|
691
|
package leetcode
/**
* https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/
*/
class Problem2244 {
fun minimumRounds(tasks: IntArray): Int {
val map = mutableMapOf<Int, Int>()
for (task in tasks) {
map[task] = (map[task] ?: 0) + 1
}
var answer = 0
for (count in map.values) {
if (count < 2) {
return -1
}
answer += if (count % 3 == 0) {
count / 3
} else if (count % 3 == 1) {
(count / 3) - 1 + 2
} else { // count % 3 == 2
(count / 3) + 1
}
}
return answer
}
}
|
mit
|
7bf015f402909c1a8ad3606c639a67ec
| 24.592593 | 70 | 0.416787 | 3.838889 | false | false | false | false |
HabitRPG/habitica-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewmodels/GroupViewModel.kt
|
1
|
9535
|
package com.habitrpg.android.habitica.ui.viewmodels
import android.os.Bundle
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.ChallengeRepository
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.helpers.NotificationsManager
import com.habitrpg.android.habitica.models.members.Member
import com.habitrpg.android.habitica.models.social.Challenge
import com.habitrpg.android.habitica.models.social.ChatMessage
import com.habitrpg.android.habitica.models.social.Group
import com.habitrpg.common.habitica.models.notifications.NewChatMessageData
import io.realm.kotlin.toFlow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import retrofit2.HttpException
import javax.inject.Inject
enum class GroupViewType(internal val order: String) {
PARTY("party"),
GUILD("guild"),
TAVERN("tavern")
}
open class GroupViewModel(initializeComponent: Boolean) : BaseViewModel(initializeComponent) {
constructor() : this(true)
@Inject
lateinit var challengeRepository: ChallengeRepository
@Inject
lateinit var socialRepository: SocialRepository
@Inject
lateinit var notificationsManager: NotificationsManager
protected val groupIDState = MutableStateFlow<String?>(null)
val groupIDFlow: Flow<String?> = groupIDState
var groupViewType: GroupViewType? = null
private val groupFlow = groupIDFlow
.filterNotNull()
.flatMapLatest { socialRepository.getGroup(it) }
private val group = groupFlow.asLiveData()
private val leaderFlow = groupFlow.map { it?.leaderID }
.filterNotNull()
.flatMapLatest { socialRepository.retrieveMember(it).toFlow() }
private val leader = leaderFlow.asLiveData()
private val isMemberFlow = groupIDFlow
.filterNotNull()
.flatMapLatest { socialRepository.getGroupMembership(it) }
.map { it != null }
private val isMemberData = isMemberFlow.asLiveData()
private val _chatMessages: MutableLiveData<List<ChatMessage>> by lazy {
MutableLiveData<List<ChatMessage>>(listOf())
}
val chatmessages: LiveData<List<ChatMessage>> by lazy {
_chatMessages
}
var gotNewMessages: Boolean = false
override fun inject(component: UserComponent) {
component.inject(this)
}
override fun onCleared() {
socialRepository.close()
super.onCleared()
}
fun setGroupID(groupID: String) {
if (groupID == groupIDState.value) return
groupIDState.value = groupID
disposable.add(
notificationsManager.getNotifications().firstElement().map {
it.filter { notification ->
val data = notification.data as? NewChatMessageData
data?.group?.id == groupID
}
}
.filter { it.isNotEmpty() }
.flatMapPublisher { userRepository.readNotification(it.first().id) }
.subscribe(
{
},
ExceptionHandler.rx()
)
)
}
val groupID: String?
get() = groupIDState.value
val isMember: Boolean
get() = isMemberData.value ?: false
val leaderID: String?
get() = group.value?.leaderID
val isLeader: Boolean
get() = user.value?.id == leaderID
val isPublicGuild: Boolean
get() = group.value?.privacy == "public"
fun getGroupData(): LiveData<Group?> = group
fun getLeaderData(): LiveData<Member?> = leader
fun getIsMemberData(): LiveData<Boolean> = isMemberData
fun retrieveGroup(function: (() -> Unit)?) {
if (groupID?.isNotEmpty() == true) {
viewModelScope.launch(ExceptionHandler.coroutine {
if (it is HttpException && it.code() == 404) {
MainNavigationController.navigateBack()
}
}) {
val group = socialRepository.retrieveGroup(groupID ?: "")
if (groupViewType == GroupViewType.PARTY) {
socialRepository.retrievePartyMembers(group?.id ?: "", true)
}
function?.invoke()
}
}
}
fun inviteToGroup(inviteData: HashMap<String, Any>) {
disposable.add(
socialRepository.inviteToGroup(group.value?.id ?: "", inviteData)
.subscribe({ }, ExceptionHandler.rx())
)
}
fun updateOrCreateGroup(bundle: Bundle?) {
viewModelScope.launch(ExceptionHandler.coroutine()) {
if (group.value == null) {
socialRepository.createGroup(
bundle?.getString("name"),
bundle?.getString("description"),
bundle?.getString("leader"),
bundle?.getString("groupType"),
bundle?.getString("privacy"),
bundle?.getBoolean("leaderCreateChallenge")
)
} else {
socialRepository.updateGroup(
group.value, bundle?.getString("name"),
bundle?.getString("description"),
bundle?.getString("leader"),
bundle?.getBoolean("leaderCreateChallenge")
)
}
}
}
fun leaveGroup(
groupChallenges: List<Challenge>,
keepChallenges: Boolean = true,
function: (() -> Unit)? = null
) {
if (!keepChallenges) {
for (challenge in groupChallenges) {
challengeRepository.leaveChallenge(challenge, "remove-all").subscribe({}, ExceptionHandler.rx())
}
}
viewModelScope.launch(ExceptionHandler.coroutine()) {
socialRepository.leaveGroup(groupID ?: "", keepChallenges)
userRepository.retrieveUser(withTasks = false, forced = true)
}
}
fun joinGroup(id: String? = null, function: (() -> Unit)? = null) {
viewModelScope.launch(ExceptionHandler.coroutine()) {
socialRepository.joinGroup(id ?: groupID)
function?.invoke()
}
}
fun rejectGroupInvite(id: String? = null) {
groupID?.let {
disposable.add(socialRepository.rejectGroupInvite(id ?: it).subscribe({ }, ExceptionHandler.rx()))
}
}
fun markMessagesSeen() {
groupID?.let {
if (groupViewType != GroupViewType.TAVERN && it.isNotEmpty() && gotNewMessages) {
socialRepository.markMessagesSeen(it)
}
}
}
fun likeMessage(message: ChatMessage) {
val index = _chatMessages.value?.indexOf(message)
if (index == null || index < 0) return
disposable.add(
socialRepository.likeMessage(message).subscribe(
{
val list = _chatMessages.value?.toMutableList()
list?.set(index, it)
_chatMessages.postValue(list)
}, ExceptionHandler.rx()
)
)
}
fun deleteMessage(chatMessage: ChatMessage) {
val oldIndex = _chatMessages.value?.indexOf(chatMessage) ?: return
val list = _chatMessages.value?.toMutableList()
list?.remove(chatMessage)
_chatMessages.postValue(list)
disposable.add(
socialRepository.deleteMessage(chatMessage).subscribe({
}, {
list?.add(oldIndex, chatMessage)
_chatMessages.postValue(list)
ExceptionHandler.reportError(it)
})
)
}
fun postGroupChat(chatText: String, onComplete: () -> Unit, onError: () -> Unit) {
groupID?.let { groupID ->
socialRepository.postGroupChat(groupID, chatText).subscribe(
{
val list = _chatMessages.value?.toMutableList()
list?.add(0, it.message)
_chatMessages.postValue(list)
onComplete()
},
{ error ->
ExceptionHandler.reportError(error)
onError()
}
)
}
}
fun retrieveGroupChat(onComplete: () -> Unit) {
val groupID = groupID
if (groupID.isNullOrEmpty()) {
onComplete()
return
}
viewModelScope.launch(ExceptionHandler.coroutine()) {
val messages = socialRepository.retrieveGroupChat(groupID)
_chatMessages.postValue(messages)
onComplete()
}
}
fun updateGroup(bundle: Bundle?) {
viewModelScope.launch(ExceptionHandler.coroutine()) {
socialRepository.updateGroup(
group.value,
bundle?.getString("name"),
bundle?.getString("description"),
bundle?.getString("leader"),
bundle?.getBoolean("leaderOnlyChallenges")
)
}
}
}
|
gpl-3.0
|
352152bd7e279ab2b026e4213203d637
| 33.79927 | 112 | 0.600839 | 5.374859 | false | false | false | false |
kohesive/klutter
|
elasticsearch-6.x/src/main/kotlin/uy/klutter/elasticsearch/Client.kt
|
2
|
6211
|
package uy.klutter.elasticsearch
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import nl.komponents.kovenant.Promise
import nl.komponents.kovenant.all
import nl.komponents.kovenant.deferred
import nl.komponents.kovenant.functional.bind
import org.elasticsearch.client.Client
import org.elasticsearch.cluster.health.ClusterHealthStatus
import org.elasticsearch.common.settings.Settings
import org.elasticsearch.common.transport.TransportAddress
import org.elasticsearch.common.unit.TimeValue
import org.elasticsearch.node.Node
import org.elasticsearch.transport.client.PreBuiltTransportClient
import uy.klutter.core.common.with
import java.nio.file.Path
import java.util.*
object EsConfig {
@Volatile var adminActionTimeoutInSeconds: Long = 30
@Volatile var indexReplicaCount: Int = 1
@Volatile var indexShardCount: Int = 4
@Volatile var objectMapper: ObjectMapper = jacksonObjectMapper()
}
fun esNodeClient(clusterName: String, settings: Map<String, String>): Client {
return esNodeClient(clusterName) {
settings.entries.forEach {
put(it.key, it.value)
}
}
}
fun esNodeClient(clusterName: String, init: Settings.Builder.() -> Unit): Client {
val settings = Settings.builder()
.put("cluster.name", clusterName)
.put("client.transport.sniff", false)
.put("node.name", "nodeClient-" + System.currentTimeMillis())
.put("http.enabled", false)
.put("node.data", false)
.put("node.master", false)
.with { init() }
.build()
return Node(settings).client()
}
fun esTransportClient(clusterName: String, nodes: List<TransportAddress>, settings: Map<String, String>): Client {
return esTransportClient(clusterName, nodes) {
settings.entries.forEach {
put(it.key, it.value)
}
}
}
fun esTransportClient(clusterName: String, nodes: List<TransportAddress>, init: Settings.Builder.() -> Unit): Client {
val settings = Settings.builder()
.put("cluster.name", clusterName)
.put("client.transport.sniff", false)
.with { init() }
.build()
val client = PreBuiltTransportClient(settings)
nodes.forEach {
client.addTransportAddress(it)
}
return client
}
fun esEmbeddedClient(clusterName: String, baseDir: Path, settings: Map<String, String>): Promise<Client, Exception> {
return esEmbeddedClient(clusterName, baseDir) {
settings.entries.forEach {
put(it.key, it.value)
}
}
}
fun esEmbeddedClient(clusterName: String, baseDir: Path, init: Settings.Builder.() -> Unit): Promise<Client, Exception> {
val deferred = deferred<Client, Exception>()
try {
val esRoot = baseDir.toAbsolutePath()
val settings = Settings.builder()
.put("path.data", "$esRoot/data")
.put("path.work", "$esRoot/work")
.put("path.logs", "$esRoot/logs")
.put("http.enabled", false)
.put("index.number_of_shards", "2")
.put("index.number_of_replicas", "0")
.put("cluster.routing.schedule", "50ms")
.put("cluster.name", clusterName)
.put("client.transport.sniff", false)
.put("node.name", "nodeEmbedded-" + System.currentTimeMillis())
.put("node.data", true)
.put("node.local", true)
.put("cluster.routing.allocation.disk.threshold_enabled", true)
.put("cluster.routing.allocation.disk.watermark.low", "10gb")
.with { init() }
.build()
val tempNode = Node(settings).start()
val tempClient = tempNode.client()
return tempClient.waitForYellowCluster().bind { deferred.promise }
} catch (ex: Throwable) {
deferred.reject(wrapThrowable(ex))
}
return deferred.promise
}
fun Client.waitForGreenCluster(): Promise<ClusterHealthStatus, Exception> {
return admin().cluster().prepareHealth().setWaitForGreenStatus().setTimeout(TimeValue.timeValueSeconds(EsConfig.adminActionTimeoutInSeconds)).promise { it.getStatus() }
}
fun Client.waitForYellowCluster(): Promise<ClusterHealthStatus, Exception> {
return admin().cluster().prepareHealth().setWaitForYellowStatus().setTimeout(TimeValue.timeValueSeconds(EsConfig.adminActionTimeoutInSeconds)).promise { it.getStatus() }
}
fun Client.waitForGreenIndex(vararg indices: String): Promise<ClusterHealthStatus, Exception> {
return admin().cluster().prepareHealth(*indices).setWaitForGreenStatus().setTimeout(TimeValue.timeValueSeconds(EsConfig.adminActionTimeoutInSeconds)).promise { it.getStatus() }
}
fun Client.waitForYellowIndex(vararg indices: String): Promise<ClusterHealthStatus, Exception> {
return admin().cluster().prepareHealth(*indices).setWaitForYellowStatus().setTimeout(TimeValue.timeValueSeconds(EsConfig.adminActionTimeoutInSeconds)).promise { it.getStatus() }
}
fun Client.indexExists(vararg indices: String): Promise<Boolean, Exception> {
return admin().indices().prepareExists(*indices).promise { it.isExists }
}
fun Client.createIndex(index: String, mappings: List<IndexTypeMapping>, shardCount: Int = EsConfig.indexShardCount, replicaCount: Int = EsConfig.indexReplicaCount, settingsInit: Settings.Builder.() -> Unit = {}): Promise<Unit, Exception> {
val indexSettings = Settings.builder()
.put("number_of_shards", shardCount)
.put("number_of_replicas", replicaCount)
.with { settingsInit() }
.build()
return admin().indices().prepareCreate(index).setSettings(indexSettings).with { mappings.forEach { addMapping(it.type, it.json) } }.promiseNothing()
}
fun Client.updateIndexMappings(index: String, mappings: List<IndexTypeMapping>): Promise<List<Boolean>, Exception> {
val actions = LinkedList<Promise<Boolean, Exception>>()
mappings.forEach {
actions.add(admin().indices().preparePutMapping(index).setType(it.type).setSource(it.json).promise { it.isAcknowledged })
}
return all<Boolean>(actions)
}
|
mit
|
4e018da7f969e327cff982c475fbe89e
| 41.541096 | 239 | 0.684914 | 4.304227 | false | false | false | false |
StepicOrg/stepic-android
|
app/src/main/java/org/stepik/android/domain/view_assignment/interactor/DeferrableViewAssignmentReportInteractor.kt
|
2
|
2979
|
package org.stepik.android.domain.view_assignment.interactor
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.rxkotlin.toObservable
import io.reactivex.subjects.BehaviorSubject
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.domain.network.repository.NetworkTypeRepository
import org.stepik.android.domain.progress.interactor.LocalProgressInteractor
import org.stepik.android.domain.view_assignment.repository.ViewAssignmentRepository
import org.stepik.android.model.ViewAssignment
import org.stepik.android.view.injection.view_assignment.ViewAssignmentBus
import javax.inject.Inject
class DeferrableViewAssignmentReportInteractor
@Inject
constructor(
private val networkTypeRepository: NetworkTypeRepository,
private val viewAssignmentRepository: ViewAssignmentRepository,
private val localProgressInteractor: LocalProgressInteractor,
@ViewAssignmentBus
private val viewAssignmentObserver: BehaviorSubject<Unit>,
@ViewAssignmentBus
private val viewAssignmentObservable: Observable<Unit>
) {
fun reportViewAssignmentsOnDemand(): Completable =
viewAssignmentObservable
.concatMapCompletable {
reportViewAssignmentsOnActiveNetwork()
.doOnSuccess { isSuccess ->
if (!isSuccess) {
viewAssignmentObserver.onNext(Unit)
}
}
.ignoreElement()
}
/**
* Returns true if all view assignments from queue were successfully posted
*/
private fun reportViewAssignmentsOnActiveNetwork(): Single<Boolean> =
waitUntilActiveNetwork()
.andThen(viewAssignmentRepository.getViewAssignments())
.flatMap { viewAssignments ->
viewAssignments
.toObservable()
.concatMap(::reportViewAssignmentFromQueue)
.toList()
.flatMap { steps ->
localProgressInteractor
.updateStepsProgress(*steps.toLongArray())
.toSingleDefault(viewAssignments.size == steps.size)
}
}
.onErrorReturnItem(false)
private fun waitUntilActiveNetwork(): Completable =
networkTypeRepository
.getAvailableNetworkTypesStream()
.filter { it.isNotEmpty() }
.take(1)
.ignoreElements()
private fun reportViewAssignmentFromQueue(viewAssignment: ViewAssignment): Observable<Long> =
viewAssignmentRepository
.createViewAssignment(viewAssignment, dataSourceType = DataSourceType.REMOTE)
.andThen(viewAssignmentRepository.removeViewAssignment(viewAssignment))
.andThen(Observable.just(viewAssignment.step))
.onErrorResumeNext(Observable.empty())
}
|
apache-2.0
|
f977ea68477cf171825212eddce4dca3
| 39.821918 | 97 | 0.676401 | 5.89901 | false | false | false | false |
farmerbb/Notepad
|
app/src/main/java/com/farmerbb/notepad/data/PreferenceManager.kt
|
1
|
4232
|
/* Copyright 2022 Braden Farmer
*
* 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.farmerbb.notepad.data
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.sp
import com.farmerbb.notepad.R
import com.farmerbb.notepad.model.FilenameFormat
import com.farmerbb.notepad.model.Prefs
import com.farmerbb.notepad.model.SortOrder
import de.schnettler.datastore.manager.DataStoreManager
import de.schnettler.datastore.manager.PreferenceRequest
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
class PreferenceManager private constructor(
private val dataStoreManager: DataStoreManager,
private val scope: CoroutineScope
) {
val isLightTheme get() = Prefs.Theme.mapToFlow { theme -> theme.contains("light") }
val backgroundColorRes get() = Prefs.Theme.mapToFlow { theme ->
when {
theme.contains("light") -> R.color.window_background
else -> R.color.window_background_dark
}
}
val primaryColorRes get() = Prefs.Theme.mapToFlow { theme ->
when {
theme.contains("light") -> R.color.text_color_primary
else -> R.color.text_color_primary_dark
}
}
val secondaryColorRes get() = Prefs.Theme.mapToFlow { theme ->
when {
theme.contains("light") -> R.color.text_color_secondary
else -> R.color.text_color_secondary_dark
}
}
val textFontSize get() = Prefs.FontSize.mapToFlow { fontSize ->
when (fontSize) {
"smallest" -> 12.sp
"small" -> 14.sp
"normal" -> 16.sp
"large" -> 18.sp
else -> 20.sp
}
}
val dateFontSize get() = Prefs.FontSize.mapToFlow { fontSize ->
when (fontSize) {
"smallest" -> 8.sp
"small" -> 10.sp
"normal" -> 12.sp
"large" -> 14.sp
else -> 16.sp
}
}
val fontFamily get() = Prefs.Theme.mapToFlow { theme ->
when {
theme.contains("sans") -> FontFamily.SansSerif
theme.contains("serif") -> FontFamily.Serif
else -> FontFamily.Monospace
}
}
val sortOrder get() = Prefs.SortBy.mapToFlow(::toSortOrder)
val filenameFormat get() = Prefs.ExportFilename.mapToFlow(::toFilenameFormat)
val showDialogs get() = Prefs.ShowDialogs.asFlow
val showDate get() = Prefs.ShowDate.asFlow
val directEdit get() = Prefs.DirectEdit.asFlow
val markdown get() = Prefs.Markdown.asFlow
val rtlLayout get() = Prefs.RtlSupport.asFlow
val firstRunComplete get() = Prefs.FirstRun.mapToFlow(::toBoolean)
val firstViewComplete get() = Prefs.FirstLoad.mapToFlow(::toBoolean)
val showDoubleTapMessage get() = Prefs.ShowDoubleTapMessage.asFlow
private fun <T, R> PreferenceRequest<T>.mapToFlow(transform: (value: T) -> R) =
dataStoreManager.getPreferenceFlow(this).map(transform).stateIn(
scope = scope,
started = SharingStarted.Lazily,
initialValue = transform(defaultValue)
)
private val <T> PreferenceRequest<T>.asFlow get() = mapToFlow { it }
private fun toSortOrder(value: String) = SortOrder.values().first {
it.stringValue == value
}
private fun toFilenameFormat(value: String) = FilenameFormat.values().first {
it.stringValue == value
}
private fun toBoolean(value: Int) = value > 0
companion object {
fun DataStoreManager.prefs(scope: CoroutineScope) = PreferenceManager(
dataStoreManager = this,
scope = scope
)
}
}
|
apache-2.0
|
d62ad8c294243403dfe7e79d09ac9f6a
| 33.696721 | 87 | 0.657372 | 4.331627 | false | false | false | false |
apollostack/apollo-android
|
apollo-mockserver/src/appleMain/kotlin/com/apollographql/apollo3/mockserver/FileDescriptorSource.kt
|
1
|
1501
|
package com.apollographql.apollo3.mockserver
import kotlinx.cinterop.ByteVar
import kotlinx.cinterop.allocArray
import kotlinx.cinterop.convert
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.readBytes
import okio.Buffer
import okio.IOException
import okio.Source
import okio.Timeout
import platform.posix.errno
// TODO: add Cursor implementation
class FileDescriptorSource(val fd: Int) : Source {
private var closed = false
private var exhausted = false
override fun read(
sink: Buffer,
byteCount: Long
): Long {
require(byteCount >= 0L) { "byteCount < 0: $byteCount" }
check(!closed) { "closed" }
if (exhausted) {
return -1L
}
return memScoped {
val bufSize = 8192
val buf = allocArray<ByteVar>(bufSize)
var read = 0L
while (read < byteCount) {
val toRead = minOf(bufSize.toLong(), byteCount - read)
val len = platform.posix.read(fd, buf, toRead.convert())
if (len < 0) {
throw IOException("Cannot read $fd (errno = $errno)")
}
if (len == 0L) {
exhausted = true
return@memScoped read
}
read += len
sink.write(buf.readBytes(len.convert()))
if (len < toRead) {
// come back later
return@memScoped read
}
}
read
}
}
override fun timeout(): Timeout = Timeout.NONE
override fun close() {
if (closed) return
closed = true
platform.posix.close(fd)
}
}
|
mit
|
e53b1a79f678815d2ef6b39d75bb3130
| 22.46875 | 64 | 0.624917 | 4.204482 | false | false | false | false |
GabrielCastro/open_otp
|
app/src/main/kotlin/ca/gabrielcastro/openotp/ui/edit/OtpEditActivity.kt
|
1
|
2621
|
package ca.gabrielcastro.openotp.ui.edit
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import ca.gabrielcastro.openotp.R
import ca.gabrielcastro.openotp.app.App
import ca.gabrielcastro.openotp.ext.addAfterTextChangedListener
import ca.gabrielcastro.openotp.ui.base.BaseActivity
import kotlinx.android.synthetic.main.activity_otp_edit.*
import javax.inject.Inject
class OtpEditActivity : BaseActivity(), OtpEditContract.View {
companion object {
const val EXTRA_ID = "id"
const val EXTRA_ACCOUNT = "account"
const val EXTRA_ISSUER = "issuer"
fun intent(context: Context, id: String, account: String, issuer: String): Intent {
return Intent(context, OtpEditActivity::class.java)
.putExtra(EXTRA_ACCOUNT, account)
.putExtra(EXTRA_ISSUER, issuer)
.putExtra(EXTRA_ID, id)
}
}
@Inject
lateinit var presenter: OtpEditContract.Presenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_otp_edit)
App.component(this).editComponent.inject(this)
val id = intent.getStringExtra(EXTRA_ID)!!
val account = intent.getStringExtra(EXTRA_ACCOUNT) ?: ""
val issuer = intent.getStringExtra(EXTRA_ISSUER) ?: ""
basePresenter = presenter
presenter.init(this, id, issuer, account)
otp_edit_issuer.addAfterTextChangedListener {
presenter.issuerChanged(it)
}
otp_edit_account.addAfterTextChangedListener {
presenter.accountNameChanged(it)
}
setResult(Activity.RESULT_CANCELED)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_otp_edit, menu)
super.onCreateOptionsMenu(menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId) {
R.id.action_save -> presenter.save()
else -> return super.onOptionsItemSelected(item)
}
return true
}
override fun setIssuer(issuer: CharSequence) {
otp_edit_issuer.setText(issuer)
}
override fun setAccountName(accountName: CharSequence) {
otp_edit_account.setText(accountName)
}
override fun finish(ok: Boolean) {
val code = if (ok) Activity.RESULT_OK else Activity.RESULT_CANCELED
setResult(code)
finish()
}
}
|
mit
|
58cbdac137678569b2a2a5827b5b66bc
| 31.7625 | 91 | 0.672644 | 4.495712 | false | false | false | false |
Mindera/skeletoid
|
base/src/main/java/com/mindera/skeletoid/dialogs/AlertDialogFragment.kt
|
1
|
3865
|
package com.mindera.skeletoid.dialogs
import android.app.AlertDialog
import android.app.Dialog
import android.content.ContentValues.TAG
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import com.mindera.skeletoid.logs.LOG
class AlertDialogFragment : AbstractDialogFragment() {
companion object {
private const val LOG_TAG = "AlertDialogFragment"
/**
* Arguments for Bundle
*/
private const val ARG_TITLE = "ARG_TITLE"
private const val ARG_MESSAGE = "ARG_MESSAGE"
private const val ARG_POSITIVE_BUTTON_TEXT = "ARG_POSITIVE_BUTTON_TEXT"
private const val ARG_NEGATIVE_BUTTON_TEXT = "ARG_NEGATIVE_BUTTON_TEXT"
private const val ARG_NEUTRAL_BUTTON_TEXT = "ARG_NEUTRAL_BUTTON_TEXT"
private const val ARG_CANCELLABLE = "ARG_CANCELLABLE"
fun newInstance(title: String? = null,
message: String,
positiveButtonText: String?,
negativeButtonText: String? = null,
neutralButtonText: String? = null,
cancellable: Boolean = true,
args: Bundle = Bundle()): AlertDialogFragment {
val frag = AlertDialogFragment()
//Parameters to be resend on onDialogResult to the target Fragment or Activity
val parameters = Bundle()
parameters.putAll(args)
frag.setParameters(parameters)
args.putString(ARG_TITLE, title)
args.putString(ARG_MESSAGE, message)
args.putString(ARG_POSITIVE_BUTTON_TEXT, positiveButtonText)
args.putString(ARG_NEGATIVE_BUTTON_TEXT, negativeButtonText)
args.putString(ARG_NEUTRAL_BUTTON_TEXT, neutralButtonText)
args.putBoolean(ARG_CANCELLABLE, cancellable)
//Dialog related parameters
frag.arguments = args
return frag
}
}
private var title: String? = null
private lateinit var message: String
private var positiveButtonText: String? = null
private var negativeButtonText: String? = null
private var neutralButtonText: String? = null
private var cancellable: Boolean? = null
override var isSingleTop = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
title = it.getString(ARG_TITLE)
message = it.getString(ARG_MESSAGE, "") //Since the constructor does not allow nulls, this won't happen, but..
positiveButtonText = it.getString(ARG_POSITIVE_BUTTON_TEXT)
negativeButtonText = it.getString(ARG_NEGATIVE_BUTTON_TEXT)
neutralButtonText = it.getString(ARG_NEUTRAL_BUTTON_TEXT)
cancellable = it.getBoolean(ARG_CANCELLABLE)
}
isCancelable = cancellable ?: true
}
override fun setupRxBindings() {
//unused
}
override fun disposeRxBindings() {
//unused
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(activity)
.setTitle(title)
.setMessage(message)
.setPositiveButton(positiveButtonText) { _, _ ->
onPositiveClick()
}
cancellable?.let { cancellable ->
builder.setCancelable(cancellable)
}
negativeButtonText?.let {
builder.setNegativeButton(it) { _, _ ->
onNegativeClick()
}
}
neutralButtonText?.let {
builder.setNeutralButton(it) { _, _ ->
onNeutralClick()
}
}
return builder.create()
}
override val isShowing: Boolean
get() = dialog?.isShowing == true
}
|
mit
|
feb686e81a46feb61b12a60bbc9e795d
| 32.034188 | 122 | 0.610349 | 5.222973 | false | false | false | false |
CarlosEsco/tachiyomi
|
app/src/main/java/eu/kanade/presentation/manga/components/MangaDialogs.kt
|
1
|
1112
|
package eu.kanade.presentation.manga.components
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import eu.kanade.tachiyomi.R
@Composable
fun DeleteChaptersDialog(
onDismissRequest: () -> Unit,
onConfirm: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismissRequest,
dismissButton = {
TextButton(onClick = onDismissRequest) {
Text(text = stringResource(android.R.string.cancel))
}
},
confirmButton = {
TextButton(
onClick = {
onDismissRequest()
onConfirm()
},
) {
Text(text = stringResource(android.R.string.ok))
}
},
title = {
Text(text = stringResource(R.string.are_you_sure))
},
text = {
Text(text = stringResource(R.string.confirm_delete_chapters))
},
)
}
|
apache-2.0
|
968007a915d375667732c185541df8eb
| 27.512821 | 73 | 0.581835 | 4.898678 | false | false | false | false |
Heiner1/AndroidAPS
|
danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketOptionSetPumpTimeTest.kt
|
1
|
1592
|
package info.nightscout.androidaps.danars.comm
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.danars.DanaRSTestBase
import org.joda.time.DateTime
import org.junit.Assert
import org.junit.Test
class DanaRsPacketOptionSetPumpTimeTest : DanaRSTestBase() {
private val packetInjector = HasAndroidInjector {
AndroidInjector {
if (it is DanaRSPacket) {
it.aapsLogger = aapsLogger
it.dateUtil = dateUtil
}
}
}
@Test fun runTest() {
val date = DateTime()
val packet = DanaRSPacketOptionSetPumpTime(packetInjector, date.millis)
// test params
val params = packet.getRequestParams()
Assert.assertEquals((date.year - 2000 and 0xff).toByte(), params[0]) // 2019 -> 19
Assert.assertEquals((date.monthOfYear and 0xff).toByte(), params[1])
Assert.assertEquals((date.dayOfMonth and 0xff).toByte(), params[2])
Assert.assertEquals((date.hourOfDay and 0xff).toByte(), params[3])
Assert.assertEquals((date.minuteOfHour and 0xff).toByte(), params[4])
Assert.assertEquals((date.secondOfMinute and 0xff).toByte(), params[5])
// test message decoding
packet.handleMessage(createArray(3, 0.toByte()))
Assert.assertEquals(false, packet.failed)
// everything ok :)
packet.handleMessage(createArray(17, 1.toByte()))
Assert.assertEquals(true, packet.failed)
Assert.assertEquals("OPTION__SET_PUMP_TIME", packet.friendlyName)
}
}
|
agpl-3.0
|
1535ee2ed4b5e87f9174b098e934e231
| 38.825 | 90 | 0.675879 | 4.668622 | false | true | false | false |
auth0/Auth0.Android
|
auth0/src/main/java/com/auth0/android/provider/OAuthManager.kt
|
1
|
13466
|
package com.auth0.android.provider
import android.content.Context
import android.net.Uri
import android.text.TextUtils
import android.util.Base64
import android.util.Log
import androidx.annotation.VisibleForTesting
import com.auth0.android.Auth0
import com.auth0.android.Auth0Exception
import com.auth0.android.authentication.AuthenticationAPIClient
import com.auth0.android.authentication.AuthenticationException
import com.auth0.android.callback.Callback
import com.auth0.android.request.internal.Jwt
import com.auth0.android.request.internal.OidcUtils
import com.auth0.android.result.Credentials
import java.security.SecureRandom
import java.util.*
internal class OAuthManager(
private val account: Auth0,
private val callback: Callback<Credentials, AuthenticationException>,
parameters: Map<String, String>,
ctOptions: CustomTabsOptions
) : ResumableManager() {
private val parameters: MutableMap<String, String>
private val headers: MutableMap<String, String>
private val ctOptions: CustomTabsOptions
private val apiClient: AuthenticationAPIClient
private var requestCode = 0
private var pkce: PKCE? = null
private var _currentTimeInMillis: Long? = null
@set:VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal var currentTimeInMillis: Long
get() = if (_currentTimeInMillis != null) _currentTimeInMillis!! else System.currentTimeMillis()
set(value) {
_currentTimeInMillis = value
}
private var idTokenVerificationLeeway: Int? = null
private var idTokenVerificationIssuer: String? = null
@VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE)
fun setPKCE(pkce: PKCE?) {
this.pkce = pkce
}
fun setIdTokenVerificationLeeway(leeway: Int?) {
idTokenVerificationLeeway = leeway
}
fun setIdTokenVerificationIssuer(issuer: String?) {
idTokenVerificationIssuer = if (TextUtils.isEmpty(issuer)) apiClient.baseURL else issuer
}
fun startAuthentication(context: Context, redirectUri: String, requestCode: Int) {
OidcUtils.includeDefaultScope(parameters)
addPKCEParameters(parameters, redirectUri, headers)
addClientParameters(parameters, redirectUri)
addValidationParameters(parameters)
val uri = buildAuthorizeUri()
this.requestCode = requestCode
AuthenticationActivity.authenticateUsingBrowser(context, uri, ctOptions)
}
fun setHeaders(headers: Map<String, String>) {
this.headers.putAll(headers)
}
public override fun resume(result: AuthorizeResult): Boolean {
if (!result.isValid(requestCode)) {
Log.w(TAG, "The Authorize Result is invalid.")
return false
}
if (result.isCanceled) {
//User cancelled the authentication
val exception = AuthenticationException(
AuthenticationException.ERROR_VALUE_AUTHENTICATION_CANCELED,
"The user closed the browser app and the authentication was canceled."
)
callback.onFailure(exception)
return true
}
val values = CallbackHelper.getValuesFromUri(result.intentData)
if (values.isEmpty()) {
Log.w(TAG, "The response didn't contain any of these values: code, state")
return false
}
Log.d(TAG, "The parsed CallbackURI contains the following parameters: ${values.keys}")
try {
assertNoError(values[KEY_ERROR], values[KEY_ERROR_DESCRIPTION])
assertValidState(parameters[KEY_STATE]!!, values[KEY_STATE])
} catch (e: AuthenticationException) {
callback.onFailure(e)
return true
}
// response_type=code
pkce!!.getToken(
values[KEY_CODE],
object : Callback<Credentials, AuthenticationException> {
override fun onSuccess(credentials: Credentials) {
assertValidIdToken(
credentials.idToken,
object : Callback<Void?, Auth0Exception> {
override fun onSuccess(result: Void?) {
callback.onSuccess(credentials)
}
override fun onFailure(error: Auth0Exception) {
val wrappedError = AuthenticationException(
ERROR_VALUE_ID_TOKEN_VALIDATION_FAILED, error
)
callback.onFailure(wrappedError)
}
})
}
override fun onFailure(error: AuthenticationException) {
if ("Unauthorized" == error.getDescription()) {
Log.e(
PKCE.TAG,
"Unable to complete authentication with PKCE. PKCE support can be enabled by setting Application Type to 'Native' and Token Endpoint Authentication Method to 'None' for this app at 'https://manage.auth0.com/#/applications/" + apiClient.clientId + "/settings'."
)
}
callback.onFailure(error)
}
})
return true
}
private fun assertValidIdToken(
idToken: String?,
validationCallback: Callback<Void?, Auth0Exception>
) {
if (TextUtils.isEmpty(idToken)) {
validationCallback.onFailure(IdTokenMissingException())
return
}
val decodedIdToken: Jwt = try {
Jwt(idToken!!)
} catch (error: Exception) {
validationCallback.onFailure(
UnexpectedIdTokenException(error)
)
return
}
val signatureVerifierCallback: Callback<SignatureVerifier, TokenValidationException> =
object : Callback<SignatureVerifier, TokenValidationException> {
override fun onFailure(error: TokenValidationException) {
validationCallback.onFailure(error)
}
override fun onSuccess(result: SignatureVerifier) {
val options = IdTokenVerificationOptions(
idTokenVerificationIssuer!!,
apiClient.clientId,
result
)
val maxAge = parameters[KEY_MAX_AGE]
if (!TextUtils.isEmpty(maxAge)) {
options.maxAge = Integer.valueOf(maxAge!!)
}
options.clockSkew = idTokenVerificationLeeway
options.nonce = parameters[KEY_NONCE]
options.clock = Date(currentTimeInMillis)
options.organization = parameters[KEY_ORGANIZATION]
try {
IdTokenVerifier().verify(decodedIdToken, options, true)
validationCallback.onSuccess(null)
} catch (exc: TokenValidationException) {
validationCallback.onFailure(exc)
}
}
}
val tokenKeyId = decodedIdToken.keyId
SignatureVerifier.forAsymmetricAlgorithm(tokenKeyId, apiClient, signatureVerifierCallback)
}
//Helper Methods
@Throws(AuthenticationException::class)
private fun assertNoError(errorValue: String?, errorDescription: String?) {
if (errorValue == null) {
return
}
Log.e(
TAG,
"Error, access denied. Check that the required Permissions are granted and that the Application has this Connection configured in Auth0 Dashboard."
)
when {
ERROR_VALUE_ACCESS_DENIED.equals(errorValue, ignoreCase = true) -> {
throw AuthenticationException(
ERROR_VALUE_ACCESS_DENIED,
errorDescription ?: "Permissions were not granted. Try again."
)
}
ERROR_VALUE_UNAUTHORIZED.equals(errorValue, ignoreCase = true) -> {
throw AuthenticationException(ERROR_VALUE_UNAUTHORIZED, errorDescription!!)
}
ERROR_VALUE_LOGIN_REQUIRED == errorValue -> {
//Whitelist to allow SSO errors go through
throw AuthenticationException(errorValue, errorDescription!!)
}
else -> {
throw AuthenticationException(
ERROR_VALUE_INVALID_CONFIGURATION,
"The application isn't configured properly for the social connection. Please check your Auth0's application configuration"
)
}
}
}
private fun buildAuthorizeUri(): Uri {
val authorizeUri = Uri.parse(account.authorizeUrl)
val builder = authorizeUri.buildUpon()
for ((key, value) in parameters) {
builder.appendQueryParameter(key, value)
}
val uri = builder.build()
Log.d(TAG, "Using the following Authorize URI: $uri")
return uri
}
private fun addPKCEParameters(
parameters: MutableMap<String, String>,
redirectUri: String,
headers: Map<String, String>
) {
createPKCE(redirectUri, headers)
val codeChallenge = pkce!!.codeChallenge
parameters[KEY_CODE_CHALLENGE] = codeChallenge
parameters[KEY_CODE_CHALLENGE_METHOD] = METHOD_SHA_256
Log.v(TAG, "Using PKCE authentication flow")
}
private fun addValidationParameters(parameters: MutableMap<String, String>) {
val state = getRandomString(parameters[KEY_STATE])
val nonce = getRandomString(parameters[KEY_NONCE])
parameters[KEY_STATE] = state
parameters[KEY_NONCE] = nonce
}
private fun addClientParameters(parameters: MutableMap<String, String>, redirectUri: String) {
parameters[KEY_AUTH0_CLIENT_INFO] = account.auth0UserAgent.value
parameters[KEY_CLIENT_ID] = account.clientId
parameters[KEY_REDIRECT_URI] = redirectUri
}
private fun createPKCE(redirectUri: String, headers: Map<String, String>) {
if (pkce == null) {
pkce = PKCE(apiClient, redirectUri, headers)
}
}
companion object {
private val TAG = OAuthManager::class.java.simpleName
const val KEY_RESPONSE_TYPE = "response_type"
const val KEY_STATE = "state"
const val KEY_NONCE = "nonce"
const val KEY_MAX_AGE = "max_age"
const val KEY_CONNECTION = "connection"
const val KEY_ORGANIZATION = "organization"
const val KEY_INVITATION = "invitation"
const val KEY_SCOPE = "scope"
const val RESPONSE_TYPE_CODE = "code"
private const val DEFAULT_SCOPE = "openid profile email"
private const val REQUIRED_SCOPE = "openid"
private const val ERROR_VALUE_INVALID_CONFIGURATION = "a0.invalid_configuration"
private const val ERROR_VALUE_ACCESS_DENIED = "access_denied"
private const val ERROR_VALUE_UNAUTHORIZED = "unauthorized"
private const val ERROR_VALUE_LOGIN_REQUIRED = "login_required"
private const val ERROR_VALUE_ID_TOKEN_VALIDATION_FAILED = "Could not verify the ID token"
private const val METHOD_SHA_256 = "S256"
private const val KEY_CODE_CHALLENGE = "code_challenge"
private const val KEY_CODE_CHALLENGE_METHOD = "code_challenge_method"
private const val KEY_CLIENT_ID = "client_id"
private const val KEY_REDIRECT_URI = "redirect_uri"
private const val KEY_AUTH0_CLIENT_INFO = "auth0Client"
private const val KEY_ERROR = "error"
private const val KEY_ERROR_DESCRIPTION = "error_description"
private const val KEY_CODE = "code"
@JvmStatic
@VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE)
@Throws(AuthenticationException::class)
fun assertValidState(requestState: String, responseState: String?) {
if (requestState != responseState) {
Log.e(
TAG,
String.format(
"Received state doesn't match. Received %s but expected %s",
responseState,
requestState
)
)
throw AuthenticationException(
ERROR_VALUE_ACCESS_DENIED,
"The received state is invalid. Try again."
)
}
}
@VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE)
fun getRandomString(defaultValue: String?): String {
return defaultValue ?: secureRandomString()
}
private fun secureRandomString(): String {
val sr = SecureRandom()
val randomBytes = ByteArray(32)
sr.nextBytes(randomBytes)
return Base64.encodeToString(
randomBytes,
Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING
)
}
}
init {
headers = HashMap()
this.parameters = parameters.toMutableMap()
this.parameters[KEY_RESPONSE_TYPE] = RESPONSE_TYPE_CODE
apiClient = AuthenticationAPIClient(account)
this.ctOptions = ctOptions
}
}
|
mit
|
86ee3e614a29f42500d054d5e926d745
| 39.933131 | 288 | 0.606342 | 5.354274 | false | false | false | false |
Maccimo/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/ProjectModule.kt
|
2
|
7559
|
/*******************************************************************************
* 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.unified.UnifiedDependency
import com.intellij.openapi.module.Module
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.Navigatable
import com.intellij.psi.PsiManager
import com.intellij.psi.util.PsiUtil
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
import kotlinx.serialization.Serializable
/**
* Class representing a native [Module] enriched with Package Search data.
*
* @param name the name of the module.
* @param nativeModule the native [Module] it refers to.
* @param parent the parent [Module] of this object.
* @param buildFile The build file used by this module (e.g. `pom.xml` for Maven, `build.gradle` for Gradle).
* @param moduleType The additional Package Searcxh related data such as project icons, additional localizations and so on.
* listed in the Dependency Analyzer tool. At the moment the DA only supports Gradle and Maven.
* @param availableScopes Scopes available for the build system of this module (e.g. `implementation`, `api` for Gradle;
* `test`, `compile` for Maven).
* @param dependencyDeclarationCallback Given a [Dependency], it should return the indexes in the build file where given
* dependency has been declared.
*/
data class ProjectModule @JvmOverloads constructor(
@NlsSafe val name: String,
val nativeModule: Module,
val parent: ProjectModule?,
val buildFile: VirtualFile,
val buildSystemType: BuildSystemType,
val moduleType: ProjectModuleType,
val availableScopes: List<String> = emptyList(),
val dependencyDeclarationCallback: DependencyDeclarationCallback = { _ -> null }
) {
@Suppress("UNUSED_PARAMETER")
@Deprecated(
"Use main constructor",
ReplaceWith("ProjectModule(name, nativeModule, parent, buildFile, buildSystemType, moduleType)")
)
constructor(
name: String,
nativeModule: Module,
parent: ProjectModule,
buildFile: VirtualFile,
buildSystemType: BuildSystemType,
moduleType: ProjectModuleType,
navigatableDependency: (groupId: String, artifactId: String, version: PackageVersion) -> Navigatable?
) : this(name, nativeModule, parent, buildFile, buildSystemType, moduleType)
@Suppress("UNUSED_PARAMETER")
@Deprecated(
"Use main constructor",
ReplaceWith("ProjectModule(name, nativeModule, parent, buildFile, buildSystemType, moduleType)")
)
constructor(
name: String,
nativeModule: Module,
parent: ProjectModule,
buildFile: VirtualFile,
buildSystemType: BuildSystemType,
moduleType: ProjectModuleType,
navigatableDependency: (groupId: String, artifactId: String, version: PackageVersion) -> Navigatable?,
availableScopes: List<String>
) : this(name, nativeModule, parent, buildFile, buildSystemType, moduleType, availableScopes)
fun getBuildFileNavigatableAtOffset(offset: Int): Navigatable? =
PsiManager.getInstance(nativeModule.project).findFile(buildFile)?.let { psiFile ->
PsiUtil.getElementAtOffset(psiFile, offset).takeIf { it != buildFile } as? Navigatable
}
@NlsSafe
fun getFullName(): String =
parent?.let { it.getFullName() + ":$name" } ?: name
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ProjectModule) return false
if (name != other.name) return false
if (!nativeModule.isTheSameAs(other.nativeModule)) return false // This can't be automated
if (parent != other.parent) return false
if (buildFile.path != other.buildFile.path) return false
if (buildSystemType != other.buildSystemType) return false
if (moduleType != other.moduleType) return false
// if (navigatableDependency != other.navigatableDependency) return false // Intentionally excluded
if (availableScopes != other.availableScopes) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + nativeModule.hashCodeOrZero()
result = 31 * result + (parent?.hashCode() ?: 0)
result = 31 * result + buildFile.path.hashCode()
result = 31 * result + buildSystemType.hashCode()
result = 31 * result + moduleType.hashCode()
// result = 31 * result + navigatableDependency.hashCode() // Intentionally excluded
result = 31 * result + availableScopes.hashCode()
return result
}
}
internal fun Module.isTheSameAs(other: Module) =
runCatching { moduleFilePath == other.moduleFilePath && name == other.name }
.getOrDefault(false)
private fun Module.hashCodeOrZero() =
runCatching { moduleFilePath.hashCode() + 31 * name.hashCode() }
.getOrDefault(0)
typealias DependencyDeclarationCallback = suspend (Dependency) -> DependencyDeclarationIndexes?
/**
* Container class for declaration coordinates for a dependency in a build file. \
* Example for Gradle:
* ```
* implementation("io.ktor:ktor-server-cio:2.0.0")
* // ▲ ▲ ▲
* // | ∟ coordinatesStartIndex |
* // ∟ wholeDeclarationStartIndex ∟ versionStartIndex
* //
* ```
* Example for Maven:
* ```
* <dependency>
* // ▲ wholeDeclarationStartIndex
* <groupId>io.ktor</groupId>
* // ▲ coordinatesStartIndex
* <artifactId>ktor-server-cio</artifactId>
* <version>2.0.0</version>
* // ▲ versionStartIndex
* </dependency>
* ```
* @param wholeDeclarationStartIndex index of the first character where the whole declarations starts.
*
*/
@Serializable
data class DependencyDeclarationIndexes(
val wholeDeclarationStartIndex: Int,
val coordinatesStartIndex: Int,
val versionStartIndex: Int?
)
data class UnifiedDependencyKey(val scope: String, val groupId: String, val module: String)
val UnifiedDependency.key: UnifiedDependencyKey?
get() {
return UnifiedDependencyKey(scope ?: return null, coordinates.groupId!!, coordinates.artifactId ?: return null)
}
fun UnifiedDependency.asDependency(): Dependency? {
return Dependency(
scope = scope ?: return null,
groupId = coordinates.groupId ?: return null,
artifactId = coordinates.artifactId ?: return null,
version = coordinates.version ?: return null
)
}
data class Dependency(val scope: String, val groupId: String, val artifactId: String, val version: String) {
override fun toString() = "$scope(\"$groupId:$artifactId:$version\")"
}
|
apache-2.0
|
ab5e49858cbe1fcf47f1d0b6a7a4fea2
| 40.20765 | 123 | 0.68174 | 4.781864 | false | false | false | false |
bajdcc/jMiniLang
|
src/main/kotlin/com/bajdcc/LALR1/interpret/module/user/ModuleUserCParser.kt
|
1
|
1115
|
package com.bajdcc.LALR1.interpret.module.user
import com.bajdcc.LALR1.grammar.Grammar
import com.bajdcc.LALR1.grammar.runtime.RuntimeCodePage
import com.bajdcc.LALR1.interpret.module.IInterpreterModule
import com.bajdcc.util.ResourceLoader
import org.apache.log4j.Logger
/**
* 【模块】用户态-C语言编译器
*
* @author bajdcc
*/
class ModuleUserCParser : IInterpreterModule {
private var runtimeCodePage: RuntimeCodePage? = null
override val moduleName: String
get() = "user.cparser"
override val moduleCode: String
get() = ResourceLoader.load(javaClass)
override val codePage: RuntimeCodePage
@Throws(Exception::class)
get() {
if (runtimeCodePage != null)
return runtimeCodePage!!
val base = ResourceLoader.load(javaClass)
val grammar = Grammar(base)
val page = grammar.codePage
runtimeCodePage = page
return page
}
companion object {
val instance = ModuleUserCParser()
private val logger = Logger.getLogger("cparser")
}
}
|
mit
|
33aa392360152905bdcd4106cf5e17db
| 24.395349 | 59 | 0.665445 | 4.399194 | false | false | false | false |
orbite-mobile/monastic-jerusalem-community
|
app/src/main/java/pl/orbitemobile/wspolnoty/activities/where/maps/MapsIntentBuilder.kt
|
1
|
1689
|
/*
* Copyright (c) 2017. All Rights Reserved. Michal Jankowski orbitemobile.pl
*/
package pl.orbitemobile.wspolnoty.activities.where.maps
import android.content.Context
import android.content.Intent
import android.net.Uri
class MapsIntentBuilder() {
private val mapsBrowserIntent: Intent
get() = Intent(Intent.ACTION_VIEW, Uri.parse(MAPS_URL))
fun mapsIntent(context: Context?) =
if (context?.canOpenMapsApplication() == true) {
mapsApplicationIntent
} else {
mapsBrowserIntent
}
private fun Context.canOpenMapsApplication(): Boolean {
val mapIntent = mapsApplicationIntent
return mapIntent.resolveActivity(packageManager) != null
}
private val mapsApplicationIntent: Intent
get() {
val mapIntent = Intent(Intent.ACTION_VIEW, parsedUri)
mapIntent.`package` = "com.google.android.apps.maps"
return mapIntent
}
private val parsedUri: Uri
get() {
val mapApplicationUri = mapsApplicationUri
return Uri.parse(mapApplicationUri)
}
private val mapsApplicationUri: String
get() {
val latitude = 52.221897
val longitude = 21.03841
val label = "Wspólnoty Jerozolimskie"
val uriBegin = "geo:$latitude,$longitude"
val query = latitude.toString() + "," + longitude + "(" + label + ")"
val encodedQuery = Uri.encode(query)
return "$uriBegin?q=$encodedQuery&z=15"
}
private val MAPS_URL = "https://www.google.pl/maps/place/Wspólnoty+Jerozolimskie/@52.221897,21.03841,15z"
}
|
agpl-3.0
|
2dc31b7eb112cd6fb726120ac5dcf79a
| 30.830189 | 109 | 0.624778 | 4.336761 | false | false | false | false |
onoderis/failchat
|
src/main/kotlin/failchat/emoticon/WordReplacer.kt
|
2
|
1415
|
package failchat.emoticon
import java.util.regex.Pattern
object WordReplacer {
val wordPattern: Pattern = Pattern.compile("""(?<=\s|^)(.+?)(?=\s|$)""")
inline fun replace(initialString: String, decisionMaker: (word: String) -> ReplaceDecision): String {
// Can't use Matcher.appendReplacement() because it resets position when Matcher.find(start) invoked
val matcher = wordPattern.matcher(initialString)
val sb = lazy(LazyThreadSafetyMode.NONE) { StringBuilder() }
var cursor = 0
while (matcher.find(cursor)) {
val code = matcher.group(1)
val decision = decisionMaker.invoke(code)
val end = matcher.end()
when (decision) {
is ReplaceDecision.Replace -> {
val appendFrom = if (sb.isInitialized()) cursor else 0
sb.value.append(initialString, appendFrom, matcher.start())
sb.value.append(decision.replacement)
}
is ReplaceDecision.Skip -> {
if (sb.isInitialized()) {
sb.value.append(initialString, cursor, end)
}
}
}
cursor = end
}
if (!sb.isInitialized()) return initialString
sb.value.append(initialString, cursor, initialString.length)
return sb.toString()
}
}
|
gpl-3.0
|
836739d504b48b73ac692e8904a6d41d
| 33.512195 | 108 | 0.561837 | 4.862543 | false | false | false | false |
Maccimo/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/ExtractableCodeDescriptor.kt
|
2
|
23811
|
// 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.refactoring.introduce.extractionEngine
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.MultiMap
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiRange
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.OutputValue.*
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference.ShorteningMode
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.approximateFlexibleTypes
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtKeywordToken
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.resolveTopLevelClass
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.typeUtil.TypeNullability
import org.jetbrains.kotlin.types.typeUtil.builtIns
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.types.typeUtil.nullability
import org.jetbrains.kotlin.utils.IDEAPlatforms
import org.jetbrains.kotlin.utils.IDEAPluginsCompatibilityAPI
import java.util.*
interface Parameter {
val argumentText: String
val originalDescriptor: DeclarationDescriptor
val name: String
val mirrorVarName: String?
val receiverCandidate: Boolean
val parameterType: KotlinType
fun getParameterTypeCandidates(): List<KotlinType>
fun copy(name: String, parameterType: KotlinType): Parameter
}
val Parameter.nameForRef: String get() = mirrorVarName ?: name
data class TypeParameter(
val originalDeclaration: KtTypeParameter,
val originalConstraints: List<KtTypeConstraint>
)
interface Replacement : Function2<ExtractableCodeDescriptor, KtElement, KtElement>
interface ParameterReplacement : Replacement {
val parameter: Parameter
fun copy(parameter: Parameter): ParameterReplacement
}
class RenameReplacement(override val parameter: Parameter) : ParameterReplacement {
override fun copy(parameter: Parameter) = RenameReplacement(parameter)
override fun invoke(descriptor: ExtractableCodeDescriptor, e: KtElement): KtElement {
val expressionToReplace = (e.parent as? KtThisExpression ?: e).let { it.getQualifiedExpressionForSelector() ?: it }
val parameterName = KtPsiUtil.unquoteIdentifier(parameter.nameForRef)
val replacingName =
if (e.text.startsWith('`') || !parameterName.isIdentifier()) "`$parameterName`" else parameterName
val psiFactory = KtPsiFactory(e)
val replacement = when {
parameter == descriptor.receiverParameter -> psiFactory.createExpression("this")
expressionToReplace is KtOperationReferenceExpression -> psiFactory.createOperationName(replacingName)
else -> psiFactory.createSimpleName(replacingName)
}
return expressionToReplace.replaced(replacement)
}
}
abstract class WrapInWithReplacement : Replacement {
abstract val argumentText: String
override fun invoke(descriptor: ExtractableCodeDescriptor, e: KtElement): KtElement {
val call = (e as? KtSimpleNameExpression)?.getQualifiedElement() ?: return e
val replacingExpression = KtPsiFactory(e).createExpressionByPattern("with($0) { $1 }", argumentText, call)
val replace = call.replace(replacingExpression)
return (replace as KtCallExpression).lambdaArguments.first().getLambdaExpression()!!.bodyExpression!!.statements.first()
}
}
class WrapParameterInWithReplacement(override val parameter: Parameter) : WrapInWithReplacement(), ParameterReplacement {
override val argumentText: String
get() = parameter.name
override fun copy(parameter: Parameter) = WrapParameterInWithReplacement(parameter)
}
class WrapObjectInWithReplacement(val descriptor: ClassDescriptor) : WrapInWithReplacement() {
override val argumentText: String
get() = IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(descriptor)
}
class AddPrefixReplacement(override val parameter: Parameter) : ParameterReplacement {
override fun copy(parameter: Parameter) = AddPrefixReplacement(parameter)
override fun invoke(descriptor: ExtractableCodeDescriptor, e: KtElement): KtElement {
if (descriptor.receiverParameter == parameter) return e
val selector = (e.parent as? KtCallExpression) ?: e
val replacingExpression = KtPsiFactory(e).createExpressionByPattern("${parameter.nameForRef}.$0", selector)
val newExpr = (selector.replace(replacingExpression) as KtQualifiedExpression).selectorExpression!!
return (newExpr as? KtCallExpression)?.calleeExpression ?: newExpr
}
}
class FqNameReplacement(val fqName: FqName) : Replacement {
override fun invoke(descriptor: ExtractableCodeDescriptor, e: KtElement): KtElement {
val thisExpr = e.parent as? KtThisExpression
if (thisExpr != null) {
return thisExpr.replaced(KtPsiFactory(e).createExpression(fqName.asString())).getQualifiedElementSelector()!!
}
val newExpr = (e as? KtSimpleNameExpression)?.mainReference?.bindToFqName(fqName, ShorteningMode.NO_SHORTENING) as KtElement
return if (newExpr is KtQualifiedExpression) newExpr.selectorExpression!! else newExpr
}
}
interface OutputValue {
val originalExpressions: List<KtExpression>
val valueType: KotlinType
class ExpressionValue(
val callSiteReturn: Boolean,
override val originalExpressions: List<KtExpression>,
override val valueType: KotlinType
) : OutputValue
class Jump(
val elementsToReplace: List<KtExpression>,
val elementToInsertAfterCall: KtElement?,
val conditional: Boolean,
builtIns: KotlinBuiltIns
) : OutputValue {
override val originalExpressions: List<KtExpression> get() = elementsToReplace
override val valueType: KotlinType = with(builtIns) { if (conditional) booleanType else unitType }
}
class ParameterUpdate(
val parameter: Parameter,
override val originalExpressions: List<KtExpression>
) : OutputValue {
override val valueType: KotlinType get() = parameter.parameterType
}
class Initializer(
val initializedDeclaration: KtProperty,
override val valueType: KotlinType
) : OutputValue {
override val originalExpressions: List<KtExpression> get() = Collections.singletonList(initializedDeclaration)
}
}
abstract class OutputValueBoxer(val outputValues: List<OutputValue>) {
val outputValueTypes: List<KotlinType> get() = outputValues.map { it.valueType }
abstract val returnType: KotlinType
protected abstract fun getBoxingExpressionPattern(arguments: List<KtExpression>): String?
abstract val boxingRequired: Boolean
fun getReturnExpression(arguments: List<KtExpression>, psiFactory: KtPsiFactory): KtReturnExpression? {
val expressionPattern = getBoxingExpressionPattern(arguments) ?: return null
return psiFactory.createExpressionByPattern("return $expressionPattern", *arguments.toTypedArray()) as KtReturnExpression
}
protected abstract fun extractExpressionByIndex(boxedExpression: KtExpression, index: Int): KtExpression?
protected fun extractArgumentExpressionByIndex(boxedExpression: KtExpression, index: Int): KtExpression? {
val call: KtCallExpression? = when (boxedExpression) {
is KtCallExpression -> boxedExpression
is KtQualifiedExpression -> boxedExpression.selectorExpression as? KtCallExpression
else -> null
}
val arguments = call?.valueArguments
if (arguments == null || arguments.size <= index) return null
return arguments[index].getArgumentExpression()
}
fun extractExpressionByValue(boxedExpression: KtExpression, value: OutputValue): KtExpression? {
val index = outputValues.indexOf(value)
if (index < 0) return null
return extractExpressionByIndex(boxedExpression, index)
}
abstract fun getUnboxingExpressions(boxedText: String): Map<OutputValue, String>
class AsTuple(
outputValues: List<OutputValue>,
val module: ModuleDescriptor
) : OutputValueBoxer(outputValues) {
init {
assert(outputValues.size <= 3) { "At most 3 output values are supported" }
}
companion object {
private val selectors = arrayOf("first", "second", "third")
}
override val returnType: KotlinType by lazy {
fun getType(): KotlinType {
val boxingClass = when (outputValues.size) {
1 -> return outputValues.first().valueType
2 -> module.resolveTopLevelClass(FqName("kotlin.Pair"), NoLookupLocation.FROM_IDE)!!
3 -> module.resolveTopLevelClass(FqName("kotlin.Triple"), NoLookupLocation.FROM_IDE)!!
else -> return module.builtIns.defaultReturnType
}
return TypeUtils.substituteParameters(boxingClass, outputValueTypes)
}
getType()
}
override val boxingRequired: Boolean = outputValues.size > 1
override fun getBoxingExpressionPattern(arguments: List<KtExpression>): String? {
return when (arguments.size) {
0 -> null
1 -> "$0"
else -> {
val constructorName = DescriptorUtils.getFqName(returnType.constructor.declarationDescriptor!!).asString()
return arguments.indices.joinToString(prefix = "$constructorName(", separator = ", ", postfix = ")") { "\$$it" }
}
}
}
override fun extractExpressionByIndex(boxedExpression: KtExpression, index: Int): KtExpression? {
if (outputValues.size == 1) return boxedExpression
return extractArgumentExpressionByIndex(boxedExpression, index)
}
override fun getUnboxingExpressions(boxedText: String): Map<OutputValue, String> {
return when (outputValues.size) {
0 -> Collections.emptyMap()
1 -> Collections.singletonMap(outputValues.first(), boxedText)
else -> {
var i = 0
ContainerUtil.newMapFromKeys(outputValues.iterator()) { "$boxedText.${selectors[i++]}" }
}
}
}
}
class AsList(outputValues: List<OutputValue>) : OutputValueBoxer(outputValues) {
override val returnType: KotlinType by lazy {
assert(outputValues.isNotEmpty())
val builtIns = outputValues.first().valueType.builtIns
TypeUtils.substituteParameters(
builtIns.list,
Collections.singletonList(CommonSupertypes.commonSupertype(outputValues.map { it.valueType }))
)
}
override val boxingRequired: Boolean = outputValues.isNotEmpty()
override fun getBoxingExpressionPattern(arguments: List<KtExpression>): String? {
if (arguments.isEmpty()) return null
return arguments.indices.joinToString(prefix = "kotlin.collections.listOf(", separator = ", ", postfix = ")") { "\$$it" }
}
override fun extractExpressionByIndex(boxedExpression: KtExpression, index: Int): KtExpression? {
return extractArgumentExpressionByIndex(boxedExpression, index)
}
override fun getUnboxingExpressions(boxedText: String): Map<OutputValue, String> {
var i = 0
return ContainerUtil.newMapFromKeys(outputValues.iterator()) { "$boxedText[${i++}]" }
}
}
}
data class ControlFlow(
val outputValues: List<OutputValue>,
val boxerFactory: (List<OutputValue>) -> OutputValueBoxer,
val declarationsToCopy: List<KtDeclaration>
) {
val outputValueBoxer = boxerFactory(outputValues)
val defaultOutputValue: ExpressionValue? = with(outputValues.filterIsInstance<ExpressionValue>()) {
if (size > 1) throw IllegalArgumentException("Multiple expression values: ${outputValues.joinToString()}") else firstOrNull()
}
val jumpOutputValue: Jump? = with(outputValues.filterIsInstance<Jump>()) {
val jumpCount = size
when {
isEmpty() ->
null
outputValues.size > jumpCount || jumpCount > 1 ->
throw IllegalArgumentException("Jump values must be the only value if it's present: ${outputValues.joinToString()}")
else ->
first()
}
}
}
val ControlFlow.possibleReturnTypes: List<KotlinType>
get() {
val returnType = outputValueBoxer.returnType
return when {
!returnType.isNullabilityFlexible() ->
listOf(returnType)
returnType.nullability() != TypeNullability.FLEXIBLE ->
listOf(returnType.approximateFlexibleTypes())
else ->
(returnType.unwrap() as FlexibleType).let { listOf(it.upperBound, it.lowerBound) }
}
}
fun ControlFlow.toDefault(): ControlFlow =
copy(outputValues = outputValues.filterNot { it is Jump || it is ExpressionValue })
fun ControlFlow.copy(oldToNewParameters: Map<Parameter, Parameter>): ControlFlow {
val newOutputValues = outputValues.map {
if (it is ParameterUpdate) ParameterUpdate(oldToNewParameters[it.parameter]!!, it.originalExpressions) else it
}
return copy(outputValues = newOutputValues)
}
data class ExtractableCodeDescriptor(
val extractionData: ExtractionData,
val originalContext: BindingContext,
val suggestedNames: List<String>,
val visibility: KtModifierKeywordToken?,
val parameters: List<Parameter>,
val receiverParameter: Parameter?,
val typeParameters: List<TypeParameter>,
val replacementMap: MultiMap<KtSimpleNameExpression, Replacement>,
val controlFlow: ControlFlow,
val returnType: KotlinType,
val modifiers: List<KtKeywordToken> = emptyList(),
val annotations: List<AnnotationDescriptor> = emptyList(),
val optInMarkers: List<FqName> = emptyList()
) {
val name: String get() = suggestedNames.firstOrNull() ?: ""
val duplicates: List<DuplicateInfo> by lazy { findDuplicates() }
}
@IDEAPluginsCompatibilityAPI(
usedIn = [IDEAPlatforms._213],
message = "Provided for binary backward compatibility",
plugins = "Jetpack Compose plugin in IDEA"
)
fun ExtractableCodeDescriptor.copy(
extractionData: ExtractionData = this.extractionData,
originalContext: BindingContext = this.originalContext,
suggestedNames: List<String> = this.suggestedNames,
visibility: KtModifierKeywordToken? = this.visibility,
parameters: List<Parameter> = this.parameters,
receiverParameter: Parameter? = this.receiverParameter,
typeParameters: List<TypeParameter> = this.typeParameters,
replacementMap: MultiMap<KtSimpleNameExpression, Replacement> = this.replacementMap,
controlFlow: ControlFlow = this.controlFlow,
returnType: KotlinType = this.returnType,
modifiers: List<KtKeywordToken> = this.modifiers,
annotations: List<AnnotationDescriptor> = this.annotations
) = copy(
extractionData,
originalContext,
suggestedNames,
visibility,
parameters,
receiverParameter,
typeParameters,
replacementMap,
controlFlow,
returnType,
modifiers,
annotations,
emptyList()
)
fun ExtractableCodeDescriptor.copy(
newName: String,
newVisibility: KtModifierKeywordToken?,
oldToNewParameters: Map<Parameter, Parameter>,
newReceiver: Parameter?,
returnType: KotlinType?
): ExtractableCodeDescriptor {
val newReplacementMap = MultiMap.create<KtSimpleNameExpression, Replacement>()
for ((ref, replacements) in replacementMap.entrySet()) {
val newReplacements = replacements.map {
if (it is ParameterReplacement) {
val parameter = it.parameter
val newParameter = oldToNewParameters[parameter] ?: return@map it
it.copy(newParameter)
} else it
}
newReplacementMap.putValues(ref, newReplacements)
}
return ExtractableCodeDescriptor(
extractionData,
originalContext,
listOf(newName),
newVisibility,
oldToNewParameters.values.filter { it != newReceiver },
newReceiver,
typeParameters,
newReplacementMap,
controlFlow.copy(oldToNewParameters),
returnType ?: this.returnType,
modifiers,
annotations,
optInMarkers
)
}
enum class ExtractionTarget(val targetName: String) {
FUNCTION(KotlinBundle.message("text.function")) {
override fun isAvailable(descriptor: ExtractableCodeDescriptor) = true
},
FAKE_LAMBDALIKE_FUNCTION(KotlinBundle.message("text.lambda.parameter")) {
override fun isAvailable(descriptor: ExtractableCodeDescriptor): Boolean {
return checkSimpleControlFlow(descriptor) || descriptor.controlFlow.outputValues.isEmpty()
}
},
PROPERTY_WITH_INITIALIZER(KotlinBundle.message("text.property.with.initializer")) {
override fun isAvailable(descriptor: ExtractableCodeDescriptor): Boolean {
return checkSignatureAndParent(descriptor)
&& checkSimpleControlFlow(descriptor)
&& checkSimpleBody(descriptor)
&& checkNotTrait(descriptor)
&& descriptor.receiverParameter == null
}
},
PROPERTY_WITH_GETTER(KotlinBundle.message("text.property.with.getter")) {
override fun isAvailable(descriptor: ExtractableCodeDescriptor): Boolean {
return checkSignatureAndParent(descriptor)
}
},
LAZY_PROPERTY(KotlinBundle.message("text.lazy.property")) {
override fun isAvailable(descriptor: ExtractableCodeDescriptor): Boolean {
return checkSignatureAndParent(descriptor)
&& checkSimpleControlFlow(descriptor)
&& checkNotTrait(descriptor)
&& descriptor.receiverParameter == null
}
};
abstract fun isAvailable(descriptor: ExtractableCodeDescriptor): Boolean
companion object {
fun checkNotTrait(descriptor: ExtractableCodeDescriptor): Boolean {
val parent = descriptor.extractionData.targetSibling.getStrictParentOfType<KtDeclaration>()
return !(parent is KtClass && parent.isInterface())
}
fun checkSimpleBody(descriptor: ExtractableCodeDescriptor): Boolean {
val expression = descriptor.extractionData.expressions.singleOrNull()
return expression != null && expression !is KtDeclaration && expression !is KtBlockExpression
}
fun checkSimpleControlFlow(descriptor: ExtractableCodeDescriptor): Boolean {
val outputValue = descriptor.controlFlow.outputValues.singleOrNull()
return (outputValue is ExpressionValue && !outputValue.callSiteReturn) || outputValue is Initializer
}
fun checkSignatureAndParent(descriptor: ExtractableCodeDescriptor): Boolean {
if (!descriptor.parameters.isEmpty()) return false
if (descriptor.returnType.isUnit()) return false
val parent = descriptor.extractionData.targetSibling.parent
return (parent is KtFile || parent is KtClassBody)
}
}
}
val propertyTargets: List<ExtractionTarget> = listOf(
ExtractionTarget.PROPERTY_WITH_INITIALIZER,
ExtractionTarget.PROPERTY_WITH_GETTER,
ExtractionTarget.LAZY_PROPERTY
)
data class ExtractionGeneratorOptions(
val inTempFile: Boolean = false,
val target: ExtractionTarget = ExtractionTarget.FUNCTION,
val dummyName: String? = null,
val allowExpressionBody: Boolean = true,
val delayInitialOccurrenceReplacement: Boolean = false,
val isConst: Boolean = false
) {
companion object {
@JvmField
val DEFAULT = ExtractionGeneratorOptions()
}
}
data class ExtractionGeneratorConfiguration(
val descriptor: ExtractableCodeDescriptor,
val generatorOptions: ExtractionGeneratorOptions
)
data class ExtractionResult(
val config: ExtractionGeneratorConfiguration,
val declaration: KtNamedDeclaration,
val duplicateReplacers: Map<KotlinPsiRange, () -> Unit>
) : Disposable {
override fun dispose() = unmarkReferencesInside(declaration)
}
class AnalysisResult(
val descriptor: ExtractableCodeDescriptor?,
val status: Status,
val messages: List<ErrorMessage>
) {
enum class Status {
SUCCESS,
NON_CRITICAL_ERROR,
CRITICAL_ERROR
}
enum class ErrorMessage {
NO_EXPRESSION,
NO_CONTAINER,
SYNTAX_ERRORS,
SUPER_CALL,
DENOTABLE_TYPES,
ERROR_TYPES,
MULTIPLE_OUTPUT,
OUTPUT_AND_EXIT_POINT,
MULTIPLE_EXIT_POINTS,
DECLARATIONS_ARE_USED_OUTSIDE,
DECLARATIONS_OUT_OF_SCOPE;
var additionalInfo: List<String>? = null
fun addAdditionalInfo(info: List<String>): ErrorMessage {
additionalInfo = info
return this
}
@Nls
fun renderMessage(): String {
val message = KotlinBundle.message(
when (this) {
NO_EXPRESSION -> "cannot.refactor.no.expression"
NO_CONTAINER -> "cannot.refactor.no.container"
SYNTAX_ERRORS -> "cannot.refactor.syntax.errors"
SUPER_CALL -> "cannot.extract.super.call"
DENOTABLE_TYPES -> "parameter.types.are.not.denotable"
ERROR_TYPES -> "error.types.in.generated.function"
MULTIPLE_OUTPUT -> "selected.code.fragment.has.multiple.output.values"
OUTPUT_AND_EXIT_POINT -> "selected.code.fragment.has.output.values.and.exit.points"
MULTIPLE_EXIT_POINTS -> "selected.code.fragment.has.multiple.exit.points"
DECLARATIONS_ARE_USED_OUTSIDE -> "declarations.are.used.outside.of.selected.code.fragment"
DECLARATIONS_OUT_OF_SCOPE -> "declarations.will.move.out.of.scope"
}
)
return additionalInfo?.let { "$message\n\n${it.joinToString("\n") { msg -> StringUtil.htmlEmphasize(msg) }}" } ?: message
}
}
}
sealed class ExtractableCodeDescriptorWithConflictsResult
data class ExtractableCodeDescriptorWithConflicts(
val descriptor: ExtractableCodeDescriptor,
val conflicts: MultiMap<PsiElement, String>
): ExtractableCodeDescriptorWithConflictsResult()
data class ExtractableCodeDescriptorWithException(val exception: RuntimeException): ExtractableCodeDescriptorWithConflictsResult()
|
apache-2.0
|
e7cf0090e01b49f7342c6f91b2e1f4f3
| 39.633106 | 158 | 0.699845 | 5.409132 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/test/java/org/wordpress/android/ui/mediapicker/insert/StockMediaInsertUseCaseTest.kt
|
1
|
2238
|
package org.wordpress.android.ui.mediapicker.insert
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.flow.toList
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.kotlin.any
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.wordpress.android.BaseUnitTest
import org.wordpress.android.fluxc.model.MediaModel
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.MediaStore.OnStockMediaUploaded
import org.wordpress.android.fluxc.store.StockMediaStore
import org.wordpress.android.fluxc.store.StockMediaUploadItem
import org.wordpress.android.test
import org.wordpress.android.ui.mediapicker.MediaItem.Identifier
import org.wordpress.android.ui.mediapicker.MediaItem.Identifier.RemoteId
import org.wordpress.android.ui.mediapicker.insert.MediaInsertHandler.InsertModel
@InternalCoroutinesApi
class StockMediaInsertUseCaseTest : BaseUnitTest() {
@Mock lateinit var site: SiteModel
@Mock lateinit var stockMediaStore: StockMediaStore
private lateinit var stockMediaInsertUseCase: StockMediaInsertUseCase
private val url = "wordpress://url"
private val title = "title"
private val name = "name"
@Before
fun setUp() {
stockMediaInsertUseCase = StockMediaInsertUseCase(site, stockMediaStore)
}
@Test
fun `uploads media on insert`() = test {
val itemToInsert = Identifier.StockMediaIdentifier(url, name, title)
val insertedMediaModel = MediaModel()
val mediaId: Long = 10
insertedMediaModel.mediaId = mediaId
whenever(stockMediaStore.performUploadStockMedia(any(), any())).thenReturn(OnStockMediaUploaded(site, listOf(
insertedMediaModel
)))
val result = stockMediaInsertUseCase.insert(listOf(itemToInsert)).toList()
assertThat(result[0] is InsertModel.Progress).isTrue()
(result[1] as InsertModel.Success).apply {
assertThat(this.identifiers).containsExactly(RemoteId(mediaId))
}
verify(stockMediaStore).performUploadStockMedia(site, listOf(StockMediaUploadItem(name, title, url)))
}
}
|
gpl-2.0
|
325073444caa7c790cde91d7a4755885
| 39.690909 | 117 | 0.771224 | 4.558045 | false | true | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/jetpack/java/org/wordpress/android/ui/accounts/login/LoginPrologueRevampedViewModel.kt
|
1
|
4604
|
package org.wordpress.android.ui.accounts.login
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import kotlin.math.PI
/**
* This factor is used to convert the raw values emitted from device sensor to an appropriate scale for the consuming
* composables. The range for pitch values is -π/2 to π/2, representing an upright pose and an upside-down pose,
* respectively. E.g. Setting this factor to 0.2 / (π/2) will scale this output range to -0.2 to 0.2. The resulting
* product is interpreted in units proportional to the repeating child composable's height per second, i.e. at a
* velocity of 0.1, it will take 10 seconds for the looping animation to repeat. When applied, the product can also be
* thought of as a frequency value in Hz.
*/
private const val VELOCITY_FACTOR = (0.2 / (PI / 2)).toFloat()
/**
* This is the default pitch provided for devices lacking support for the sensors used. This is consumed by the model
* as a value in radians, but is specified here as -30 degrees for convenience. This represents a device pose that is
* slightly upright from flat, approximating a typical usage pattern, and will ensure that the text is animated at
* an appropriate velocity when sensors are unavailable.
*/
private const val DEFAULT_PITCH = (-30 * PI / 180).toFloat()
@HiltViewModel
class LoginPrologueRevampedViewModel @Inject constructor(
@ApplicationContext appContext: Context,
) : ViewModel() {
private val accelerometerData = FloatArray(3)
private val magnetometerData = FloatArray(3)
private val rotationMatrix = FloatArray(9)
private val orientationAngles = floatArrayOf(0f, DEFAULT_PITCH, 0f)
private var position = 0f
/**
* This function updates the physics model for the interactive animation by applying the elapsed time (in seconds)
* to update the velocity and position.
*
* * Velocity is calculated as proportional to the pitch angle
* * Position is constrained so that it always falls between 0 and 1, and represents the relative vertical offset
* in terms of the height of the repeated child composable.
*
* @param elapsed the elapsed time (in seconds) since the last frame
*/
fun updateForFrame(elapsed: Float) {
orientationAngles.let { (_, pitch) ->
val velocity = pitch * VELOCITY_FACTOR
// Update the position, modulo 1 (ensuring a value greater or equal to 0, and less than 1)
position = ((position + elapsed * velocity) % 1 + 1) % 1
_positionData.postValue(position)
}
}
/**
* This LiveData responds to orientation data to calculate the pitch of the device. This is then used to update the
* velocity and position for each frame.
*/
private val _positionData = object : MutableLiveData<Float>(), SensorEventListener {
private val sensorManager
get() = appContext.getSystemService(Context.SENSOR_SERVICE) as SensorManager
override fun onActive() {
super.onActive()
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)?.also {
sensorManager.registerListener( this, it, SensorManager.SENSOR_DELAY_GAME)
}
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)?.also {
sensorManager.registerListener( this, it, SensorManager.SENSOR_DELAY_GAME)
}
}
override fun onInactive() {
super.onInactive()
sensorManager.unregisterListener(this)
}
override fun onSensorChanged(event: SensorEvent) {
when (event.sensor.type) {
Sensor.TYPE_ACCELEROMETER -> event.values.copyInto(accelerometerData)
Sensor.TYPE_MAGNETIC_FIELD -> event.values.copyInto(magnetometerData)
}
// Update the orientation angles when sensor data is updated
SensorManager.getRotationMatrix(rotationMatrix, null, accelerometerData, magnetometerData)
SensorManager.getOrientation(rotationMatrix, orientationAngles)
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
}
val positionData: LiveData<Float> = _positionData
}
|
gpl-2.0
|
dc3c6c540fa8946486cdd9de69a03854
| 44.554455 | 119 | 0.708976 | 4.743299 | false | false | false | false |
mdaniel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertPropertyToFunctionIntention.kt
|
1
|
11344
|
// 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.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.refactoring.*
import org.jetbrains.kotlin.idea.references.KtReference
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.hasJvmFieldAnnotation
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.resolve.calls.util.getCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.utils.findFunction
class ConvertPropertyToFunctionIntention : SelfTargetingIntention<KtProperty>(
KtProperty::class.java,
KotlinBundle.lazyMessage("convert.property.to.function")
), LowPriorityAction {
private inner class Converter(
project: Project,
editor: Editor?,
descriptor: CallableDescriptor
) : CallableRefactoring<CallableDescriptor>(project, editor, descriptor, text) {
private val newName: String = JvmAbi.getterName(callableDescriptor.name.asString())
private fun convertProperty(originalProperty: KtProperty, psiFactory: KtPsiFactory) {
val property = originalProperty.copy() as KtProperty
val getter = property.getter
val sampleFunction = psiFactory.createFunction("fun foo() {\n\n}")
property.valOrVarKeyword.replace(sampleFunction.funKeyword!!)
property.addAfter(psiFactory.createParameterList("()"), property.nameIdentifier)
if (property.initializer == null) {
if (getter != null) {
val dropGetterTo = (getter.equalsToken ?: getter.bodyExpression)
?.siblings(forward = false, withItself = false)
?.firstOrNull { it !is PsiWhiteSpace }
getter.deleteChildRange(getter.firstChild, dropGetterTo)
val dropPropertyFrom = getter
.siblings(forward = false, withItself = false)
.first { it !is PsiWhiteSpace }
.nextSibling
property.deleteChildRange(dropPropertyFrom, getter.prevSibling)
val typeReference = property.typeReference
if (typeReference != null) {
property.addAfter(psiFactory.createWhiteSpace(), typeReference)
}
}
}
property.setName(newName)
property.annotationEntries.forEach {
if (it.useSiteTarget != null) {
it.replace(psiFactory.createAnnotationEntry("@${it.shortName}${it.valueArgumentList?.text ?: ""}"))
}
}
originalProperty.replace(psiFactory.createFunction(property.text))
}
override fun performRefactoring(descriptorsForChange: Collection<CallableDescriptor>) {
val propertyName = callableDescriptor.name.asString()
val nameChanged = propertyName != newName
val getterName = JvmAbi.getterName(callableDescriptor.name.asString())
val conflicts = MultiMap<PsiElement, String>()
val callables = getAffectedCallables(project, descriptorsForChange)
val kotlinRefsToReplaceWithCall = ArrayList<KtSimpleNameExpression>()
val refsToRename = ArrayList<PsiReference>()
val javaRefsToReplaceWithCall = ArrayList<PsiReferenceExpression>()
project.runSynchronouslyWithProgress(KotlinBundle.message("looking.for.usages.and.conflicts"), true) {
runReadAction {
val progressIndicator = ProgressManager.getInstance().progressIndicator
progressIndicator.isIndeterminate = false
val progressStep = 1.0 / callables.size
for ((i, callable) in callables.withIndex()) {
progressIndicator.fraction = (i + 1) * progressStep
if (callable !is PsiNamedElement) continue
if (!checkModifiable(callable)) {
val renderedCallable = RefactoringUIUtil.getDescription(callable, true).capitalize()
conflicts.putValue(callable, KotlinBundle.message("can.t.modify.0", renderedCallable))
}
if (callable is KtParameter) {
conflicts.putValue(
callable,
if (callable.hasActualModifier()) KotlinBundle.message("property.has.an.actual.declaration.in.the.class.constructor")
else KotlinBundle.message("property.overloaded.in.child.class.constructor")
)
}
if (callable is KtProperty) {
callableDescriptor.getContainingScope()
?.findFunction(callableDescriptor.name, NoLookupLocation.FROM_IDE) { it.valueParameters.isEmpty() }
?.takeIf { it.receiverType() == callableDescriptor.receiverType() }
?.let { DescriptorToSourceUtilsIde.getAnyDeclaration(project, it) }
?.let { reportDeclarationConflict(conflicts, it) { s -> KotlinBundle.message("0.already.exists", s) } }
} else if (callable is PsiMethod) callable.checkDeclarationConflict(propertyName, conflicts, callables)
val usages = ReferencesSearch.search(callable)
for (usage in usages) {
if (usage is KtReference) {
if (usage is KtSimpleNameReference) {
val expression = usage.expression
if (expression.getCall(expression.analyze(BodyResolveMode.PARTIAL)) != null
&& expression.getStrictParentOfType<KtCallableReferenceExpression>() == null
) {
kotlinRefsToReplaceWithCall.add(expression)
} else if (nameChanged) {
refsToRename.add(usage)
}
} else {
val refElement = usage.element
conflicts.putValue(
refElement,
KotlinBundle.message(
"unrecognized.reference.will.be.skipped.0",
StringUtil.htmlEmphasize(refElement.text)
)
)
}
continue
}
val refElement = usage.element
if (refElement.text.endsWith(getterName)) continue
if (usage is PsiJavaReference) {
if (usage.resolve() is PsiField && usage is PsiReferenceExpression) {
javaRefsToReplaceWithCall.add(usage)
}
continue
}
conflicts.putValue(
refElement,
KotlinBundle.message(
"can.t.replace.foreign.reference.with.call.expression.0",
StringUtil.htmlEmphasize(refElement.text)
)
)
}
}
}
}
project.checkConflictsInteractively(conflicts) {
project.executeWriteCommand(text) {
val kotlinPsiFactory = KtPsiFactory(project)
val javaPsiFactory = PsiElementFactory.getInstance(project)
val newKotlinCallExpr = kotlinPsiFactory.createExpression("$newName()")
kotlinRefsToReplaceWithCall.forEach { it.replace(newKotlinCallExpr) }
refsToRename.forEach { it.handleElementRename(newName) }
javaRefsToReplaceWithCall.forEach {
val getterRef = it.handleElementRename(newName)
getterRef.replace(javaPsiFactory.createExpressionFromText("${getterRef.text}()", null))
}
callables.forEach {
when (it) {
is KtProperty -> convertProperty(it, kotlinPsiFactory)
is PsiMethod -> it.name = newName
}
}
}
}
}
}
override fun startInWriteAction(): Boolean = false
override fun isApplicableTo(element: KtProperty, caretOffset: Int): Boolean {
val identifier = element.nameIdentifier ?: return false
if (!identifier.textRange.containsOffset(caretOffset)) return false
return element.delegate == null
&& !element.isVar
&& !element.isLocal
&& (element.initializer == null || element.getter == null)
&& !element.hasJvmFieldAnnotation()
&& !element.hasModifier(KtTokens.CONST_KEYWORD)
}
override fun applyTo(element: KtProperty, editor: Editor?) {
val descriptor = element.resolveToDescriptorIfAny(BodyResolveMode.FULL) as? CallableDescriptor ?: return
Converter(element.project, editor, descriptor).run()
}
}
|
apache-2.0
|
b84e70e687be19a09d0e6bba524d16a9
| 51.762791 | 158 | 0.580483 | 6.22271 | false | false | false | false |
mdaniel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/substring/ReplaceSubstringWithDropLastInspection.kt
|
1
|
2413
|
// 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.inspections.substring
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.evaluatesTo
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
class ReplaceSubstringWithDropLastInspection : ReplaceSubstringInspection() {
override fun inspectionText(element: KtDotQualifiedExpression): String =
KotlinBundle.message("inspection.replace.substring.with.drop.last.display.name")
override val defaultFixText: String get() = KotlinBundle.message("replace.substring.call.with.droplast.call")
override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) {
val argument = element.callExpression?.valueArguments?.elementAtOrNull(1)?.getArgumentExpression() ?: return
val rightExpression = (argument as? KtBinaryExpression)?.right ?: return
element.replaceWith("$0.dropLast($1)", rightExpression)
}
override fun isApplicableInner(element: KtDotQualifiedExpression): Boolean {
val arguments = element.callExpression?.valueArguments ?: return false
if (arguments.size != 2 || !element.isFirstArgumentZero()) return false
val secondArgumentExpression = arguments[1].getArgumentExpression() as? KtBinaryExpression ?: return false
if (secondArgumentExpression.operationReference.getReferencedNameElementType() != KtTokens.MINUS) return false
return isLengthAccess(secondArgumentExpression.left, element.receiverExpression)
}
private fun isLengthAccess(expression: KtExpression?, expectedReceiver: KtExpression): Boolean =
expression is KtDotQualifiedExpression
&& expression.selectorExpression.let { it is KtNameReferenceExpression && it.getReferencedName() == "length" }
&& expression.receiverExpression.evaluatesTo(expectedReceiver)
}
|
apache-2.0
|
ce6b63683bc9efe38b0cb06a56c0882b
| 55.116279 | 158 | 0.783672 | 5.222944 | false | false | false | false |
mdaniel/intellij-community
|
platform/configuration-store-impl/src/ExportSettingsAction.kt
|
1
|
16182
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.configurationStore
import com.intellij.AbstractBundle
import com.intellij.DynamicBundle
import com.intellij.configurationStore.schemeManager.ROOT_CONFIG
import com.intellij.configurationStore.schemeManager.SchemeManagerFactoryBase
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.ImportSettingsFilenameFilter
import com.intellij.ide.actions.RevealFileAction
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.components.*
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.options.OptionsBundle
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.showOkCancelDialog
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.io.FileUtil
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.util.ArrayUtil
import com.intellij.util.ReflectionUtil
import com.intellij.util.containers.putValue
import com.intellij.util.io.*
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
// for Rider purpose
open class ExportSettingsAction : AnAction(), DumbAware {
protected open fun getExportableComponents(): Map<FileSpec, List<ExportableItem>> = filterExisting(getExportableComponentsMap(true))
protected open fun exportSettings(saveFile: Path, markedComponents: Set<ExportableItem>) {
saveFile.outputStream().use {
exportSettings(markedComponents, it)
}
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = true
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun actionPerformed(e: AnActionEvent) {
ApplicationManager.getApplication().saveSettings()
val dialog = ChooseComponentsToExportDialog(getExportableComponents(), true,
ConfigurationStoreBundle.message("title.select.components.to.export"),
ConfigurationStoreBundle.message("prompt.please.check.all.components.to.export"))
if (!dialog.showAndGet()) {
return
}
val markedComponents = dialog.exportableComponents
if (markedComponents.isEmpty()) {
return
}
val saveFile = dialog.exportFile
try {
if (saveFile.exists() && showOkCancelDialog(
title = IdeBundle.message("title.file.already.exists"),
message = ConfigurationStoreBundle.message("prompt.overwrite.settings.file", saveFile.toString()),
okText = IdeBundle.message("action.overwrite"),
icon = Messages.getWarningIcon()) != Messages.OK) {
return
}
exportSettings(saveFile, markedComponents)
RevealFileAction.showDialog(getEventProject(e), ConfigurationStoreBundle.message("message.settings.exported.successfully"),
ConfigurationStoreBundle.message("title.export.successful"), saveFile.toFile(), null)
}
catch (e: IOException) {
Messages.showErrorDialog(ConfigurationStoreBundle.message("error.writing.settings", e.toString()),
IdeBundle.message("title.error.writing.file"))
}
}
private fun filterExisting(exportableComponents: Map<FileSpec, List<ExportableItem>>): Map<FileSpec, List<ExportableItem>> {
return exportableComponents.mapNotNull { (fileSpec, items) ->
val existingItems = items.filter { exists(it) }
if (existingItems.isEmpty()) null
else fileSpec to existingItems
}.toMap()
}
private fun exists(item: ExportableItem): Boolean {
if (item.fileSpec.isDirectory) {
return checkIfDirectoryExists(item, getAppStorageManager())
}
else {
val content = loadFileContent(item, getAppStorageManager())
return content != null && isComponentDefined(item.componentName, content)
}
}
}
fun exportSettings(exportableItems: Set<ExportableItem>,
out: OutputStream,
exportableThirdPartyFiles: Map<FileSpec, Path> = mapOf(),
storageManager: StateStorageManagerImpl = getAppStorageManager()) {
val filter = HashSet<String>()
Compressor.Zip(out)
.filter { entryName, _ -> filter.add(entryName) }
.use { zip ->
for (item in exportableItems) {
if (item.fileSpec.isDirectory) {
exportDirectory(item, zip, storageManager)
}
else {
val content = loadFileContent(item, storageManager)
if (content != null) {
zip.addFile(item.fileSpec.relativePath, content)
}
}
}
// dotSettings file for Rider backend
for ((fileSpec, path) in exportableThirdPartyFiles) {
LOG.assertTrue(!fileSpec.isDirectory, "fileSpec should not be directory")
LOG.assertTrue(path.isFile(), "path should be file")
zip.addFile(fileSpec.relativePath, Files.readAllBytes(path))
}
exportInstalledPlugins(zip)
zip.addFile(ImportSettingsFilenameFilter.SETTINGS_JAR_MARKER, ArrayUtil.EMPTY_BYTE_ARRAY)
}
}
data class FileSpec(@NlsSafe val relativePath: String, val isDirectory: Boolean = false)
data class ExportableItem(val fileSpec: FileSpec,
val presentableName: String,
@NonNls val componentName: String? = null,
val roamingType: RoamingType = RoamingType.DEFAULT)
data class LocalExportableItem(val file: Path, val presentableName: String, val roamingType: RoamingType = RoamingType.DEFAULT)
fun exportInstalledPlugins(zip: Compressor) {
val pluginIds = PluginManagerCore.getLoadedPlugins()
.asSequence()
.filterNot { it.isBundled }
.joinToString("\n") { it.pluginId.idString }
if (pluginIds.isNotEmpty()) {
zip.addFile(PluginManager.INSTALLED_TXT, pluginIds.toByteArray())
}
}
fun getExportableComponentsMap(isComputePresentableNames: Boolean,
storageManager: StateStorageManager = getAppStorageManager(),
withDeprecated: Boolean = false): Map<FileSpec, List<ExportableItem>> {
val result = LinkedHashMap<FileSpec, MutableList<ExportableItem>>()
@Suppress("DEPRECATION")
val processor = { component: ExportableComponent ->
for (file in component.exportFiles) {
val path = getRelativePathOrNull(file.toPath())
if (path != null) {
val fileSpec = FileSpec(path, looksLikeDirectory(file.name))
val item = ExportableItem(fileSpec, component.presentableName)
result.putValue(fileSpec, item)
}
}
}
val app = ApplicationManager.getApplication() as ComponentManagerImpl
@Suppress("DEPRECATION")
ServiceBean.loadServicesFromBeans(ExportableComponent.EXTENSION_POINT, ExportableComponent::class.java).forEach(processor)
app.processAllImplementationClasses { aClass, pluginDescriptor ->
val stateAnnotation = getStateSpec(aClass)
@Suppress("DEPRECATION")
if (stateAnnotation == null || stateAnnotation.name.isEmpty() || ExportableComponent::class.java.isAssignableFrom(aClass)) {
return@processAllImplementationClasses
}
val storages =
if (!withDeprecated) stateAnnotation.storages.filter { !it.deprecated }
else stateAnnotation.storages.sortByDeprecated()
if (storages.isEmpty()) return@processAllImplementationClasses
val presentableName = if (isComputePresentableNames) getComponentPresentableName(stateAnnotation, aClass, pluginDescriptor) else ""
var thereIsExportableStorage = false
for (storage in storages) {
val isRoamable = getEffectiveRoamingType(storage.roamingType, storage.path) != RoamingType.DISABLED
if (isStorageExportable(storage, isRoamable)) {
thereIsExportableStorage = true
val paths = getRelativePaths(storage, storageManager, withDeprecated)
for (path in paths) {
val fileSpec = FileSpec(path, looksLikeDirectory(storage))
result.putValue(fileSpec, ExportableItem(fileSpec, presentableName, stateAnnotation.name, storage.roamingType))
}
}
}
if (thereIsExportableStorage) {
val additionalExportFile = getAdditionalExportFile(stateAnnotation)
if (additionalExportFile != null) {
val additionalFileSpec = FileSpec(additionalExportFile, true)
result.putValue(additionalFileSpec, ExportableItem(additionalFileSpec, "$presentableName (schemes)"))
}
}
}
// must be in the end - because most of SchemeManager clients specify additionalExportFile in the State spec
(SchemeManagerFactory.getInstance() as SchemeManagerFactoryBase).process {
if (it.roamingType != RoamingType.DISABLED && it.fileSpec.getOrNull(0) != '$') {
val fileSpec = FileSpec(it.fileSpec, true)
if (!result.containsKey(fileSpec)) {
result.putValue(fileSpec, ExportableItem(fileSpec, it.presentableName ?: "", null, it.roamingType))
}
}
}
return result
}
fun looksLikeDirectory(storage: Storage): Boolean {
return storage.stateSplitter.java != StateSplitterEx::class.java
}
private fun looksLikeDirectory(fileSpec: String) = !fileSpec.endsWith(PathManager.DEFAULT_EXT)
private fun getRelativePaths(storage: Storage, storageManager: StateStorageManager, withDeprecated: Boolean): List<String> {
val storagePath = storage.path
val relativePaths = mutableListOf<String>()
if (storage.roamingType == RoamingType.PER_OS) {
relativePaths += getOsDependentStorage(storagePath)
if (withDeprecated) {
relativePaths += storagePath
}
}
else {
relativePaths += storagePath
}
return relativePaths.map {
val expandedPath = storageManager.expandMacro(it)
getRelativePathOrNull(expandedPath) ?: expandedPath.toString()
}
}
private fun getRelativePathOrNull(fullPath: Path): String? {
val configPath = PathManager.getConfigDir()
if (configPath.isAncestor(fullPath)) {
return configPath.relativize(fullPath).systemIndependentPath
}
return null
}
private fun getAdditionalExportFile(stateAnnotation: State) = stateAnnotation.additionalExportDirectory.takeIf { it.isNotEmpty() }
private fun getAppStorageManager() = ApplicationManager.getApplication().stateStore.storageManager as StateStorageManagerImpl
private fun isStorageExportable(storage: Storage, isRoamable: Boolean): Boolean =
storage.exportable || isRoamable && storage.storageClass == StateStorage::class && storage.path.isNotEmpty()
private fun getComponentPresentableName(state: State, aClass: Class<*>, pluginDescriptor: PluginDescriptor?): String {
val presentableName = state.presentableName.java
if (presentableName != State.NameGetter::class.java) {
try {
return ReflectionUtil.newInstance(presentableName).get()
}
catch (e: Exception) {
LOG.error(e)
}
}
val defaultName = state.name
fun trimDefaultName(): String {
// Vcs.Log.App.Settings
return defaultName
.removeSuffix(".Settings")
.removeSuffix(".Settings")
}
var resourceBundleName: String?
if (pluginDescriptor != null && PluginManagerCore.CORE_ID != pluginDescriptor.pluginId) {
resourceBundleName = pluginDescriptor.resourceBundleBaseName
if (resourceBundleName == null) {
if (pluginDescriptor.vendor == "JetBrains") {
resourceBundleName = OptionsBundle.BUNDLE
}
else {
return trimDefaultName()
}
}
}
else {
resourceBundleName = OptionsBundle.BUNDLE
}
val classLoader = pluginDescriptor?.pluginClassLoader ?: aClass.classLoader
if (classLoader != null) {
val message = messageOrDefault(classLoader, resourceBundleName, defaultName)
if (message !== defaultName) {
return message
}
}
return trimDefaultName()
}
private fun messageOrDefault(classLoader: ClassLoader, bundleName: String, @Nls defaultName: String): String {
try {
return AbstractBundle.messageOrDefault(
DynamicBundle.getResourceBundle(classLoader, bundleName), "exportable.$defaultName.presentable.name", defaultName)
}
catch (e: MissingResourceException) {
LOG.warn("Missing bundle ${bundleName} at ${classLoader}: ${e.message}")
return defaultName
}
}
fun getExportableItemsFromLocalStorage(exportableItems: Map<FileSpec, List<ExportableItem>>, storageManager: StateStorageManager):
Map<Path, List<LocalExportableItem>> {
return exportableItems.entries.mapNotNull { (fileSpec, items) ->
getLocalPath(fileSpec, storageManager)?.let { path ->
val localItems = items.map { LocalExportableItem(path, it.presentableName, it.roamingType) }
path to localItems
}
}.toMap()
}
private fun getLocalPath(fileSpec: FileSpec, storageManager: StateStorageManager) =
storageManager.expandMacro(ROOT_CONFIG).resolve(fileSpec.relativePath).takeIf { it.exists() }
private fun loadFileContent(item: ExportableItem, storageManager: StateStorageManagerImpl): ByteArray? {
var content: ByteArray? = null
var errorDuringLoadingFromProvider = false
val skipProvider = item.roamingType == RoamingType.DISABLED
val handledByProvider = !skipProvider && storageManager.compoundStreamProvider.read(item.fileSpec.relativePath,
item.roamingType) { inputStream ->
// null stream means empty file which shouldn't be exported
inputStream?.let {
try {
content = FileUtil.loadBytes(inputStream)
}
catch (e: Exception) {
LOG.warn(e)
errorDuringLoadingFromProvider = true
}
}
}
if (!handledByProvider || errorDuringLoadingFromProvider) {
val path = getLocalPath(item.fileSpec, storageManager)
if (path != null) {
val bytes = Files.readAllBytes(path)
if (isComponentDefined(item.componentName, bytes)) {
content = bytes
}
}
}
return content
}
private fun isComponentDefined(componentName: String?, bytes: ByteArray): Boolean {
return componentName == null || String(bytes).contains("""<component name="${componentName}"""")
}
private fun exportDirectory(item: ExportableItem, zip: Compressor, storageManager: StateStorageManagerImpl) {
var error = false
val success = storageManager.compoundStreamProvider.processChildren(item.fileSpec.relativePath, item.roamingType,
{ true }) { name: String, inputStream: InputStream, _: Boolean ->
try {
val fileName = item.fileSpec.relativePath + "/" + name
zip.addFile(fileName, inputStream)
true
}
catch (e: Exception) {
LOG.warn(e)
error = true
false
}
}
if (!success || error) {
val localPath = getLocalPath(item.fileSpec, storageManager)
if (localPath != null) {
zip.addDirectory(item.fileSpec.relativePath, localPath)
}
}
}
private fun checkIfDirectoryExists(item: ExportableItem, storageManager: StateStorageManagerImpl): Boolean {
var exists = false
val handledByProvider = storageManager.compoundStreamProvider.processChildren(item.fileSpec.relativePath, item.roamingType,
{ true }) { _, _, _ ->
exists = true
false // stop processing children: now we know that the directory exists and is not empty
}
if (handledByProvider) {
return exists
}
else {
val localPath = getLocalPath(item.fileSpec, storageManager)
return localPath != null && localPath.exists()
}
}
|
apache-2.0
|
eb7b7c4f0433e7fc37da2121da06b45c
| 37.255319 | 135 | 0.712026 | 5.091882 | false | false | false | false |
hermantai/samples
|
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-4/app/src/main/java/dev/mfazio/pennydrop/types/NewPlayer.kt
|
2
|
1143
|
package dev.mfazio.pennydrop.types
import androidx.databinding.ObservableBoolean
import dev.mfazio.pennydrop.game.AI
data class NewPlayer(
var playerName: String = "",
val isHuman: ObservableBoolean = ObservableBoolean(true),
val canBeRemoved: Boolean = true,
val canBeToggled: Boolean = true,
var isIncluded: ObservableBoolean = ObservableBoolean(!canBeRemoved),
var selectedAIPosition: Int = -1
) {
fun selectedAI() = if (!isHuman.get()) {
AI.basicAI.getOrNull(selectedAIPosition)
} else {
null
}
fun toPlayer() = Player(
if (this.isHuman.get()) this.playerName else (this.selectedAI()?.name ?: "AI"),
this.isHuman.get(),
this.selectedAI()
)
override fun toString() = listOf(
"name" to this.playerName,
"isIncluded" to this.isIncluded.get(),
"isHuman" to this.isHuman.get(),
"canBeRemoved" to this.canBeRemoved,
"canBeToggled" to this.canBeToggled,
"selectedAI" to (this.selectedAI()?.name ?: "N/A")
).joinToString(", ", "NewPlayer(", ")") { (property, value) ->
"$property=$value"
}
}
|
apache-2.0
|
e07ac912b8c8a2b70448d10bce28ce2c
| 30.777778 | 87 | 0.636045 | 4.141304 | false | false | false | false |
eneim/android-UniversalMusicPlayer
|
media/src/main/java/com/example/android/uamp/media/library/BrowseTree.kt
|
1
|
4427
|
/*
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp.media.library
import android.support.v4.media.MediaBrowserCompat.MediaItem
import android.support.v4.media.MediaMetadataCompat
import com.example.android.uamp.media.MusicService
import com.example.android.uamp.media.extensions.album
import com.example.android.uamp.media.extensions.albumArt
import com.example.android.uamp.media.extensions.albumArtUri
import com.example.android.uamp.media.extensions.artist
import com.example.android.uamp.media.extensions.flag
import com.example.android.uamp.media.extensions.id
import com.example.android.uamp.media.extensions.title
import com.example.android.uamp.media.extensions.urlEncoded
/**
* Represents a tree of media that's used by [MusicService.onLoadChildren].
*
* [BrowseTree] maps a media id (see: [MediaMetadataCompat.METADATA_KEY_MEDIA_ID]) to one (or
* more) [MediaMetadataCompat] objects, which are children of that media id.
*
* For example, given the following conceptual tree:
* root
* +-- Albums
* | +-- Album_A
* | | +-- Song_1
* | | +-- Song_2
* ...
* +-- Artists
* ...
*
* Requesting `browseTree["root"]` would return a list that included "Albums", "Artists", and
* any other direct children. Taking the media ID of "Albums" ("Albums" in this example),
* `browseTree["Albums"]` would return a single item list "Album_A", and, finally,
* `browseTree["Album_A"]` would return "Song_1" and "Song_2". Since those are leaf nodes,
* requesting `browseTree["Song_1"]` would return null (there aren't any children of it).
*/
class BrowseTree(musicSource: MusicSource) {
private val mediaIdToChildren = mutableMapOf<String, MutableList<MediaMetadataCompat>>()
/**
* In this example, there's a single root node (identified by the constant
* [UAMP_BROWSABLE_ROOT]). The root's children are each album included in the
* [MusicSource], and the children of each album are the songs on that album.
* (See [BrowseTree.buildAlbumRoot] for more details.)
*
* TODO: Expand to allow more browsing types.
*/
init {
musicSource.forEach { mediaItem ->
val albumMediaId = mediaItem.album.urlEncoded
val albumChildren = mediaIdToChildren[albumMediaId] ?: buildAlbumRoot(mediaItem)
albumChildren += mediaItem
}
}
/**
* Provide access to the list of children with the `get` operator.
* i.e.: `browseTree\[UAMP_BROWSABLE_ROOT\]`
*/
operator fun get(mediaId: String) = mediaIdToChildren[mediaId]
/**
* Builds a node, under the root, that represents an album, given
* a [MediaMetadataCompat] object that's one of the songs on that album,
* marking the item as [MediaItem.FLAG_BROWSABLE], since it will have child
* node(s) AKA at least 1 song.
*/
private fun buildAlbumRoot(mediaItem: MediaMetadataCompat): MutableList<MediaMetadataCompat> {
val albumMetadata = MediaMetadataCompat.Builder().apply {
id = mediaItem.album.urlEncoded
title = mediaItem.album
artist = mediaItem.artist
albumArt = mediaItem.albumArt
albumArtUri = mediaItem.albumArtUri?.toString()
flag = MediaItem.FLAG_BROWSABLE
}.build()
// Ensure the root node exists and add this album to the list.
val rootList = mediaIdToChildren[UAMP_BROWSABLE_ROOT] ?: mutableListOf()
rootList += albumMetadata
mediaIdToChildren[UAMP_BROWSABLE_ROOT] = rootList
// Insert the album's root with an empty list for its children, and return the list.
return mutableListOf<MediaMetadataCompat>().also {
mediaIdToChildren[albumMetadata.id] = it
}
}
}
const val UAMP_BROWSABLE_ROOT = "/"
const val UAMP_EMPTY_ROOT = "@empty@"
|
apache-2.0
|
2b47cc26464b7025496214319e8292e5
| 39.990741 | 98 | 0.697086 | 4.277295 | false | false | false | false |
hzsweers/CatchUp
|
services/dribbble/src/main/kotlin/io/sweers/catchup/service/dribbble/model/Images.kt
|
1
|
1176
|
/*
* Copyright (C) 2019. Zac Sweers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sweers.catchup.service.dribbble.model
/**
* Models links to the various quality of images of a shot.
*/
data class Images(
val hidpi: String?,
val normal: String
) {
fun best(preferHidpi: Boolean = false): String {
return if (preferHidpi && hidpi != null) hidpi else normal
}
fun bestSize(preferHidpi: Boolean = false): Pair<Int, Int> {
return if (preferHidpi && hidpi != null) TWO_X_IMAGE_SIZE else NORMAL_IMAGE_SIZE
}
companion object {
private val NORMAL_IMAGE_SIZE = 400 to 300
private val TWO_X_IMAGE_SIZE = 800 to 600
}
}
|
apache-2.0
|
c32d769d06366be83d4d5044aaed4cff
| 29.947368 | 84 | 0.707483 | 3.818182 | false | false | false | false |
AberrantFox/hotbot
|
src/main/kotlin/me/aberrantfox/hotbot/services/PersistentSet.kt
|
1
|
877
|
package me.aberrantfox.hotbot.services
import com.google.common.reflect.TypeToken
import com.google.gson.Gson
import java.io.File
class PersistentSet(location: String) : HashSet<String>() {
private val gson = Gson()
private val file = File(location)
init {
if(file.exists()) {
val type = object : TypeToken<ArrayList<String>>() {}.type
addAll(gson.fromJson<ArrayList<String>>(file.readText(), type))
}
}
override fun add(data: String): Boolean {
val result = super.add(data)
save()
return result
}
override fun remove(data: String): Boolean {
val result = super.remove(data)
save()
return result
}
override fun clear() {
super.clear()
save()
}
private fun save() = file.writeText(gson.toJson(this as HashSet<String>))
}
|
mit
|
a8f9ca35ebe27ab19f5e293951107a4e
| 21.512821 | 77 | 0.607754 | 4.17619 | false | false | false | false |
GunoH/intellij-community
|
platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/WithSoftLinkEntityData.kt
|
1
|
10081
|
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
// ------------------------------ Persistent Id ---------------
data class NameId(private val name: String) : SymbolicEntityId<NamedEntity> {
override val presentableName: String
get() = name
override fun toString(): String = name
}
data class AnotherNameId(private val name: String) : SymbolicEntityId<NamedEntity> {
override val presentableName: String
get() = name
override fun toString(): String = name
}
data class ComposedId(val name: String, val link: NameId) : SymbolicEntityId<ComposedIdSoftRefEntity> {
override val presentableName: String
get() = "$name - ${link.presentableName}"
}
// ------------------------------ Entity With Persistent Id ------------------
interface NamedEntity : WorkspaceEntityWithSymbolicId {
val myName: String
val additionalProperty: String?
val children: List<@Child NamedChildEntity>
override val symbolicId: NameId
get() = NameId(myName)
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : NamedEntity, WorkspaceEntity.Builder<NamedEntity>, ObjBuilder<NamedEntity> {
override var entitySource: EntitySource
override var myName: String
override var additionalProperty: String?
override var children: List<NamedChildEntity>
}
companion object : Type<NamedEntity, Builder>() {
operator fun invoke(myName: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): NamedEntity {
val builder = builder()
builder.myName = myName
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: NamedEntity, modification: NamedEntity.Builder.() -> Unit) = modifyEntity(
NamedEntity.Builder::class.java, entity, modification)
//endregion
fun MutableEntityStorage.addNamedEntity(
name: String,
additionalProperty: String? = null,
source: EntitySource = MySource
): NamedEntity {
val namedEntity = NamedEntity(name, source) {
this.additionalProperty = additionalProperty
this.children = emptyList()
}
this.addEntity(namedEntity)
return namedEntity
}
//val NamedEntity.children: List<NamedChildEntity>
// get() = TODO()
// get() = referrers(NamedChildEntity::parent)
// ------------------------------ Child of entity with persistent id ------------------
interface NamedChildEntity : WorkspaceEntity {
val childProperty: String
val parentEntity: NamedEntity
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : NamedChildEntity, WorkspaceEntity.Builder<NamedChildEntity>, ObjBuilder<NamedChildEntity> {
override var entitySource: EntitySource
override var childProperty: String
override var parentEntity: NamedEntity
}
companion object : Type<NamedChildEntity, Builder>() {
operator fun invoke(childProperty: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): NamedChildEntity {
val builder = builder()
builder.childProperty = childProperty
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: NamedChildEntity, modification: NamedChildEntity.Builder.() -> Unit) = modifyEntity(
NamedChildEntity.Builder::class.java, entity, modification)
//endregion
fun MutableEntityStorage.addNamedChildEntity(
parentEntity: NamedEntity,
childProperty: String = "child",
source: EntitySource = MySource
): NamedChildEntity {
val namedChildEntity = NamedChildEntity(childProperty, source) {
this.parentEntity = parentEntity
}
this.addEntity(namedChildEntity)
return namedChildEntity
}
// ------------------------------ Entity with soft link --------------------
interface WithSoftLinkEntity : WorkspaceEntity {
val link: NameId
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : WithSoftLinkEntity, WorkspaceEntity.Builder<WithSoftLinkEntity>, ObjBuilder<WithSoftLinkEntity> {
override var entitySource: EntitySource
override var link: NameId
}
companion object : Type<WithSoftLinkEntity, Builder>() {
operator fun invoke(link: NameId, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): WithSoftLinkEntity {
val builder = builder()
builder.link = link
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: WithSoftLinkEntity, modification: WithSoftLinkEntity.Builder.() -> Unit) = modifyEntity(
WithSoftLinkEntity.Builder::class.java, entity, modification)
//endregion
fun MutableEntityStorage.addWithSoftLinkEntity(link: NameId, source: EntitySource = MySource): WithSoftLinkEntity {
val withSoftLinkEntity = WithSoftLinkEntity(link, source)
this.addEntity(withSoftLinkEntity)
return withSoftLinkEntity
}
interface ComposedLinkEntity : WorkspaceEntity {
val link: ComposedId
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ComposedLinkEntity, WorkspaceEntity.Builder<ComposedLinkEntity>, ObjBuilder<ComposedLinkEntity> {
override var entitySource: EntitySource
override var link: ComposedId
}
companion object : Type<ComposedLinkEntity, Builder>() {
operator fun invoke(link: ComposedId, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ComposedLinkEntity {
val builder = builder()
builder.link = link
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ComposedLinkEntity, modification: ComposedLinkEntity.Builder.() -> Unit) = modifyEntity(
ComposedLinkEntity.Builder::class.java, entity, modification)
//endregion
fun MutableEntityStorage.addComposedLinkEntity(link: ComposedId, source: EntitySource = MySource): ComposedLinkEntity {
val composedLinkEntity = ComposedLinkEntity(link, source)
this.addEntity(composedLinkEntity)
return composedLinkEntity
}
// ------------------------- Entity with SymbolicId and the list of soft links ------------------
interface WithListSoftLinksEntity : WorkspaceEntityWithSymbolicId {
val myName: String
val links: List<NameId>
override val symbolicId: AnotherNameId get() = AnotherNameId(myName)
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : WithListSoftLinksEntity, WorkspaceEntity.Builder<WithListSoftLinksEntity>, ObjBuilder<WithListSoftLinksEntity> {
override var entitySource: EntitySource
override var myName: String
override var links: MutableList<NameId>
}
companion object : Type<WithListSoftLinksEntity, Builder>() {
operator fun invoke(myName: String,
links: List<NameId>,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): WithListSoftLinksEntity {
val builder = builder()
builder.myName = myName
builder.links = links.toMutableWorkspaceList()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: WithListSoftLinksEntity,
modification: WithListSoftLinksEntity.Builder.() -> Unit) = modifyEntity(
WithListSoftLinksEntity.Builder::class.java, entity, modification)
//endregion
fun MutableEntityStorage.addWithListSoftLinksEntity(
name: String,
links: List<NameId>,
source: EntitySource = MySource
): WithListSoftLinksEntity {
val withListSoftLinksEntity = WithListSoftLinksEntity(name, links, source)
this.addEntity(withListSoftLinksEntity)
return withListSoftLinksEntity
}
// --------------------------- Entity with composed persistent id via soft reference ------------------
interface ComposedIdSoftRefEntity : WorkspaceEntityWithSymbolicId {
val myName: String
val link: NameId
override val symbolicId: ComposedId get() = ComposedId(myName, link)
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ComposedIdSoftRefEntity, WorkspaceEntity.Builder<ComposedIdSoftRefEntity>, ObjBuilder<ComposedIdSoftRefEntity> {
override var entitySource: EntitySource
override var myName: String
override var link: NameId
}
companion object : Type<ComposedIdSoftRefEntity, Builder>() {
operator fun invoke(myName: String,
link: NameId,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): ComposedIdSoftRefEntity {
val builder = builder()
builder.myName = myName
builder.link = link
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ComposedIdSoftRefEntity,
modification: ComposedIdSoftRefEntity.Builder.() -> Unit) = modifyEntity(
ComposedIdSoftRefEntity.Builder::class.java, entity, modification)
//endregion
fun MutableEntityStorage.addComposedIdSoftRefEntity(
name: String,
link: NameId,
source: EntitySource = MySource
): ComposedIdSoftRefEntity {
val composedIdSoftRefEntity = ComposedIdSoftRefEntity(name, link, source)
this.addEntity(composedIdSoftRefEntity)
return composedIdSoftRefEntity
}
|
apache-2.0
|
d7ff7f71259425fd39eb6484e3fc3482
| 31.837134 | 134 | 0.72473 | 5.484766 | false | false | false | false |
fvasco/pinpoi
|
app/src/main/java/io/github/fvasco/pinpoi/dao/AbstractDao.kt
|
1
|
1935
|
package io.github.fvasco.pinpoi.dao
import android.content.Context
import android.database.SQLException
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import io.github.fvasco.pinpoi.util.assertDebug
/**
* Generic Dao.
*
* @author Francesco Vasco
*/
abstract class AbstractDao(private val context: Context) {
var database: SQLiteDatabase? = null
protected set
@Volatile
private var openCount: Int = 0
private var sqLiteOpenHelper: SQLiteOpenHelper = createSqLiteOpenHelper(context)
protected abstract fun createSqLiteOpenHelper(context: Context): SQLiteOpenHelper
@Synchronized
@Throws(SQLException::class)
fun open() {
check(openCount >= 0) { "Database locked" }
if (openCount == 0) {
assertDebug(database == null)
database = sqLiteOpenHelper.writableDatabase
}
assertDebug(database != null)
++openCount
}
@Synchronized
fun close() {
check(openCount > 0)
--openCount
if (openCount == 0) {
database?.close()
database = null
} else
assertDebug(database != null)
}
/**
* Lock database, use [.reset] to unlock
*/
@Synchronized
fun lock() {
check(openCount == 0) { "Database is open" }
sqLiteOpenHelper.close()
assertDebug(database == null)
openCount = -1
}
/**
* Reinitialize dao state
* @throws IllegalStateException Error if dao instance is open
*/
@Synchronized
fun reset() {
check(openCount == -1) { "Dao not locked" }
sqLiteOpenHelper.close()
sqLiteOpenHelper = createSqLiteOpenHelper(context)
openCount = 0
}
}
inline fun <D : AbstractDao, R> D.use(block: (D) -> R): R {
open()
try {
return block(this)
} finally {
close()
}
}
|
gpl-3.0
|
353fb4d93131142dfe6796eef566b460
| 22.313253 | 85 | 0.61292 | 4.563679 | false | false | false | false |
GunoH/intellij-community
|
plugins/markdown/core/src/org/intellij/plugins/markdown/google/authorization/GoogleOAuthRequest.kt
|
9
|
2785
|
// 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.intellij.plugins.markdown.google.authorization
import com.intellij.collaboration.auth.services.OAuthCredentialsAcquirer
import com.intellij.collaboration.auth.services.OAuthRequest
import com.intellij.collaboration.auth.services.PkceUtils
import com.intellij.openapi.components.service
import com.intellij.util.Url
import com.intellij.util.Urls
import com.intellij.util.io.DigestUtil
import org.intellij.plugins.markdown.google.GoogleAppCredentialsException
import org.intellij.plugins.markdown.google.utils.GoogleAccountsUtils
import org.jetbrains.ide.BuiltInServerManager
import org.jetbrains.ide.RestService
import java.util.*
internal fun getGoogleAuthRequest(): GoogleOAuthRequest {
val googleAppCred = GoogleAccountsUtils.getGoogleAppCredentials() ?: throw GoogleAppCredentialsException()
return GoogleOAuthRequest(googleAppCred)
}
internal class GoogleOAuthRequest(googleAppCred: GoogleAccountsUtils.GoogleAppCredentials) : OAuthRequest<GoogleCredentials> {
private val port: Int get() = BuiltInServerManager.getInstance().port
private val encoder = Base64.getUrlEncoder().withoutPadding()
private val codeVerifier = PkceUtils.generateCodeVerifier()
private val codeChallenge = PkceUtils.generateShaCodeChallenge(codeVerifier, encoder)
override val authorizationCodeUrl: Url
get() = Urls.newFromEncoded("http://localhost:${port}/${RestService.PREFIX}/${service<GoogleOAuthService>().name}/authorization_code")
override val credentialsAcquirer: OAuthCredentialsAcquirer<GoogleCredentials> =
GoogleOAuthCredentialsAcquirer(googleAppCred, authorizationCodeUrl, codeVerifier)
override val authUrlWithParameters: Url = AUTHORIZE_URI.addParameters(mapOf(
"scope" to scope,
"response_type" to responseType,
"code_challenge" to codeChallenge,
"code_challenge_method" to codeChallengeMethod,
"state" to state,
"client_id" to googleAppCred.clientId,
"redirect_uri" to authorizationCodeUrl.toExternalForm()
))
companion object {
private val scope
get() = listOf(
"https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email"
).joinToString(" ")
private const val responseType = "code" // For installed applications the parameter value is code
private const val codeChallengeMethod = "S256"
private val AUTHORIZE_URI: Url get() = Urls.newFromEncoded("https://accounts.google.com/o/oauth2/v2/auth")
private val state: String get() = DigestUtil.randomToken() // state token to prevent request forgery
}
}
|
apache-2.0
|
ed0e0bdbefee4e875d658c562e564a25
| 45.416667 | 158 | 0.786355 | 4.406646 | false | false | false | false |
GunoH/intellij-community
|
plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/model/completion/MavenArtifactIdCompletionContributor.kt
|
2
|
3155
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.dom.model.completion
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.concurrency.Promise
import org.jetbrains.idea.maven.dom.converters.MavenDependencyCompletionUtil
import org.jetbrains.idea.maven.dom.model.MavenDomShortArtifactCoordinates
import org.jetbrains.idea.maven.dom.model.completion.insert.MavenArtifactIdInsertionHandler
import org.jetbrains.idea.maven.onlinecompletion.model.MavenRepositoryArtifactInfo
import org.jetbrains.idea.reposearch.DependencySearchService
import org.jetbrains.idea.reposearch.RepositoryArtifactData
import java.util.concurrent.ConcurrentLinkedDeque
import java.util.function.Consumer
import java.util.function.Predicate
class MavenArtifactIdCompletionContributor : MavenCoordinateCompletionContributor("artifactId") {
override fun validate(groupId: String, artifactId: String): Boolean {
return true
}
override fun find(service: DependencySearchService,
coordinates: MavenDomShortArtifactCoordinates,
parameters: CompletionParameters,
consumer: Consumer<RepositoryArtifactData>): Promise<Int> {
val searchParameters = createSearchParameters(parameters)
val groupId = trimDummy(coordinates.groupId.stringValue)
val artifactId = trimDummy(coordinates.artifactId.stringValue)
if (MavenAbstractPluginExtensionCompletionContributor.isPluginOrExtension(coordinates) && StringUtil.isEmpty(groupId)) {
return MavenAbstractPluginExtensionCompletionContributor.findPluginByArtifactId(service, artifactId, searchParameters, consumer)
}
return service.suggestPrefix(groupId, artifactId, searchParameters,
withPredicate(consumer,
Predicate { it is MavenRepositoryArtifactInfo && (groupId.isEmpty() || groupId == it.groupId) }))
}
override fun fillResults(result: CompletionResultSet,
coordinates: MavenDomShortArtifactCoordinates,
cld: ConcurrentLinkedDeque<RepositoryArtifactData>,
promise: Promise<Int>,
completionPrefix: String) {
val set = HashSet<String>()
//todo hot spot - spin loop (see also parent and other child classes)
while (promise.state == Promise.State.PENDING || !cld.isEmpty()) {
ProgressManager.checkCanceled()
val item = cld.poll()
if (item is MavenRepositoryArtifactInfo && set.add(item.artifactId)) {
result.addElement(
MavenDependencyCompletionUtil.lookupElement(item, item.artifactId)
.withInsertHandler(MavenArtifactIdInsertionHandler.INSTANCE)
.also { it.putUserData(MAVEN_COORDINATE_COMPLETION_PREFIX_KEY, completionPrefix) }
)
}
}
}
}
|
apache-2.0
|
3f7e72996467bfe834d78c365e6c5be2
| 51.583333 | 144 | 0.739778 | 5.393162 | false | false | false | false |
NiciDieNase/chaosflix
|
common/src/main/java/de/nicidienase/chaosflix/common/PreferencesManager.kt
|
1
|
1320
|
package de.nicidienase.chaosflix.common
import android.content.SharedPreferences
class PreferencesManager(private val sharedPref: SharedPreferences) {
val externalPlayer: Boolean
get() = sharedPref.getBoolean(keyAlwaysUseExternalPlayer, false)
val analyticsDisabled: Boolean
get() = sharedPref.getBoolean(keyAnalyticsDisabled, false)
val downloadFolder: String?
get() = sharedPref.getString(keyDownloadFolder, null)
var autoselectRecording: Boolean
get() = sharedPref.getBoolean(keyAutoselectRecording, false)
set(value) = sharedPref.edit().putBoolean(keyAutoselectRecording, value).apply()
var autoselectStream: Boolean
get() = sharedPref.getBoolean(keyAutoselectStream, false)
set(value) = sharedPref.edit().putBoolean(keyAutoselectStream, value).apply()
fun getMetered() = sharedPref.getBoolean(keyMetered, false)
companion object {
private val keyMetered = "allow_metered_networks"
private val keyAutoselectStream = "auto_select_stream"
private val keyAutoselectRecording = "auto_select_recording"
private val keyAlwaysUseExternalPlayer = "auto_external_player"
private val keyAnalyticsDisabled = "disable_analytics"
private val keyDownloadFolder = "download_folder"
}
}
|
mit
|
2bc22b0a353748d2e811554a63827948
| 37.823529 | 88 | 0.733333 | 4.782609 | false | false | false | false |
roylanceMichael/yaclib
|
core/src/main/java/org/roylance/yaclib/core/services/java/client/JavaRetrofitBuilder.kt
|
1
|
2368
|
package org.roylance.yaclib.core.services.java.client
import org.roylance.common.service.IBuilder
import org.roylance.yaclib.YaclibModel
import org.roylance.yaclib.core.enums.CommonTokens
import org.roylance.yaclib.core.utilities.StringUtilities
class JavaRetrofitBuilder(private val controller: YaclibModel.Controller,
private val mainDependency: YaclibModel.Dependency) : IBuilder<YaclibModel.File> {
override fun build(): YaclibModel.File {
val workspace = StringBuilder()
val lowercaseName = controller.name.toLowerCase()
val interfaceName = "I${controller.name}${CommonTokens.UpperCaseRestName}"
val initialTemplate = """${CommonTokens.DoNotAlterMessage}
package ${mainDependency.group}.${CommonTokens.ServicesName};
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
public interface $interfaceName {
"""
workspace.append(initialTemplate)
val initialUrl = StringUtilities.buildUrl("/rest/$lowercaseName/")
controller.actionsList.forEach { action ->
if (action.inputsCount == 1) {
val input = action.inputsList.first()
val lowercaseActionName = StringUtilities.buildUrl(action.name.toLowerCase())
val initialActionTemplate = """
@POST("$initialUrl$lowercaseActionName")
Call<String> ${action.name.toLowerCase()}(@Body String ${input.argumentName});
"""
workspace.append(initialActionTemplate)
} else if (action.inputsCount > 1) {
val inputArguments = action.inputsList.map { input ->
"""@Part("${input.argumentName}") String ${input.argumentName}
"""
}.joinToString()
val lowercaseActionName = StringUtilities.buildUrl(action.name.toLowerCase())
val initialActionTemplate = """
@Multipart
@POST("$initialUrl$lowercaseActionName")
Call<String> ${action.name.toLowerCase()}($inputArguments);
"""
workspace.append(initialActionTemplate)
}
}
workspace.append("}")
val returnFile = YaclibModel.File.newBuilder()
.setFileToWrite(workspace.toString())
.setFileName(interfaceName)
.setFileExtension(YaclibModel.FileExtension.JAVA_EXT)
.setFullDirectoryLocation(
StringUtilities.convertPackageToJavaFolderStructureServices(mainDependency.group,
CommonTokens.ServicesName))
return returnFile.build()
}
}
|
mit
|
3728248d1e996e7e129408c46c76f907
| 36.015625 | 93 | 0.722551 | 4.717131 | false | false | false | false |
dongqianwei/tcp-tool
|
tool/src/Controllor.kt
|
1
|
1954
|
import javafx.event.ActionEvent
import javafx.fxml.FXML
import javafx.scene.control.TextArea
import javafx.scene.control.TextField
import io.netty.bootstrap.Bootstrap
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.EventLoopGroup
import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.channel.ChannelOption
import io.netty.channel.ChannelInitializer
import io.netty.channel.socket.SocketChannel
import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.channel.ChannelHandlerContext
import io.netty.buffer.ByteBuf
class Controllor {
private val thdPool: EventLoopGroup = NioEventLoopGroup()
private val bs = Bootstrap().group(thdPool)
?.channel(javaClass<NioSocketChannel>())
?.option(ChannelOption.SO_KEEPALIVE, true)
?.handler(object: ChannelInitializer<SocketChannel>() {
override fun initChannel(ch: SocketChannel?) {
ch!!.pipeline()!!.addLast(
object: ChannelInboundHandlerAdapter() {
override fun channelRead(ctx: ChannelHandlerContext?, msg: Any?) {
msg as ByteBuf
val buf = ByteArray(msg.readableBytes())
msg.readBytes(buf)
logText!!.appendText(String(buf))
}
})
}
})
FXML
var inputText: TextArea? = null
FXML
var logText: TextArea? = null
FXML
var address: TextField? = null
FXML
var port: TextField? = null
FXML
fun send(e: ActionEvent) {
}
FXML
fun clear(e: ActionEvent) {
}
FXML
fun connect(e: ActionEvent) {
bs!!.connect(address!!.getText(), port!!.getText()!!.toInt())
}
}
|
gpl-2.0
|
2caafc9a61618f4490902658420a72a2
| 29.047619 | 98 | 0.58086 | 5.169312 | false | false | false | false |
code-disaster/lwjgl3
|
modules/lwjgl/opengl/src/templates/kotlin/opengl/GLXTypes.kt
|
4
|
1135
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl
import org.lwjgl.generator.*
import core.linux.*
val GLXContext = "GLXContext".handle
val GLXFBConfig = "GLXFBConfig".handle
val GLXFBConfigSGIX = "GLXFBConfigSGIX".handle
val GLXWindow = "GLXWindow".handle
val GLXDrawable = "GLXDrawable".handle
val GLXPixmap = "GLXPixmap".handle
val GLXContextID = typedef(XID, "GLXContextID")
val GLXPbuffer = "GLXPbuffer".handle
fun configGLX() {
struct(Module.OPENGL, "GLXStereoNotifyEventEXT", nativeSubPath = "glx", mutable = false) {
int("type", "GenericEvent")
unsigned_long("serial", "\\# of last request server processed")
Bool("send_event", "{@code True} if generated by {@code SendEvent} request")
Display.p("display", "display the event was read from")
int("extension", "GLX major opcode, from {@code XQueryExtension}")
int("evtype", "always {@code GLX_STEREO_NOTIFY_EXT}")
GLXDrawable("window", "XID of the X window affected")
Bool("stereo_tree", "{@code True} if tree contains stereo windows")
}
}
|
bsd-3-clause
|
7182188bb00c1d22f0497911285ce0ca
| 33.424242 | 94 | 0.689868 | 3.913793 | false | true | false | false |
burakeregar/KotlinMvpArchitecture
|
app/src/main/kotlin/com/base/mvp/BasePresenter.kt
|
1
|
721
|
package com.base.mvp
import java.lang.ref.WeakReference
/**
* Created by Burak Eregar on 20.05.2017.
* [email protected]
* https://github.com/burakeregar
*/
open class BasePresenter<V : BaseView>: Presenter<V> {
private var weakReference: WeakReference<V>? = null
override fun attachView(view: V) {
if (!isViewAttached) {
weakReference = WeakReference(view)
view.setPresenter(this)
}
}
override fun detachView() {
weakReference?.clear()
weakReference = null
}
val view: V?
get() = weakReference?.get()
private val isViewAttached: Boolean
get() = weakReference != null && weakReference!!.get() != null
}
|
mit
|
ea57789adfdbfb2df334e369924701d3
| 20.205882 | 70 | 0.622746 | 4.096591 | false | false | false | false |
cdietze/klay
|
klay-demo/klay-demo-jvm/src/main/kotlin/klay/tests/jvm/HelloLwjglMain.kt
|
1
|
4053
|
package klay.tests.jvm
import org.lwjgl.Version
import org.lwjgl.glfw.Callbacks.glfwFreeCallbacks
import org.lwjgl.glfw.GLFW.*
import org.lwjgl.glfw.GLFWErrorCallback
import org.lwjgl.opengl.GL
import org.lwjgl.opengl.GL11.*
import org.lwjgl.system.MemoryStack
import org.lwjgl.system.MemoryStack.stackPush
import org.lwjgl.system.MemoryUtil.NULL
class HelloLwjglWorld {
// The window handle
private var window: Long = 0
fun run() {
println("Hello LWJGL " + Version.getVersion() + "!")
init()
loop()
// Free the window callbacks and destroy the window
glfwFreeCallbacks(window)
glfwDestroyWindow(window)
// Terminate GLFW and free the error callback
glfwTerminate()
glfwSetErrorCallback(null).free()
}
private fun init() {
// Setup an error callback. The default implementation
// will print the error message in System.err.
GLFWErrorCallback.createPrint(System.err).set()
// Initialize GLFW. Most GLFW functions will not work before doing this.
if (!glfwInit())
throw IllegalStateException("Unable to initialize GLFW")
// Configure GLFW
glfwDefaultWindowHints() // optional, the current window hints are already the default
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE) // the window will stay hidden after creation
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE) // the window will be resizable
// Create the window
window = glfwCreateWindow(300, 300, "Hello World!", NULL, NULL)
if (window == NULL)
throw RuntimeException("Failed to create the GLFW window")
// Setup a key callback. It will be called every time a key is pressed, repeated or released.
glfwSetKeyCallback(window) { window, key, scancode, action, mods ->
if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
glfwSetWindowShouldClose(window, true) // We will detect this in the rendering loop
}
// Get the thread stack and push a new frame
stackPush().use { stack: MemoryStack ->
val pWidth = stack.mallocInt(1) // int*
val pHeight = stack.mallocInt(1) // int*
// Get the window size passed to glfwCreateWindow
glfwGetWindowSize(window, pWidth, pHeight)
// Get the resolution of the primary monitor
val vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor())
// Center the window
glfwSetWindowPos(
window,
(vidmode.width() - pWidth.get(0)) / 2,
(vidmode.height() - pHeight.get(0)) / 2
)
} // the stack frame is popped automatically
// Make the OpenGL context current
glfwMakeContextCurrent(window)
// Enable v-sync
glfwSwapInterval(1)
// Make the window visible
glfwShowWindow(window)
}
private fun loop() {
// This line is critical for LWJGL's interoperation with GLFW's
// OpenGL context, or any context that is managed externally.
// LWJGL detects the context that is current in the current thread,
// creates the GLCapabilities instance and makes the OpenGL
// bindings available for use.
GL.createCapabilities()
// Set the clear color
glClearColor(1.0f, 0.0f, 0.0f, 0.0f)
// Run the rendering loop until the user has attempted to close
// the window or has pressed the ESCAPE key.
while (!glfwWindowShouldClose(window)) {
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT) // clear the framebuffer
glfwSwapBuffers(window) // swap the color buffers
// Poll for window events. The key callback above will only be
// invoked during this call.
glfwPollEvents()
}
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
HelloLwjglWorld().run()
}
}
}
|
apache-2.0
|
7b69e4e35ea36a69641da8773a0be4e0
| 33.355932 | 101 | 0.62719 | 4.830751 | false | false | false | false |
subhalaxmin/Programming-Kotlin
|
Chapter07/src/main/kotlin/com/packt/chapter2/controlflowasexpression.kt
|
4
|
436
|
package com.packt.chapter2
import java.io.IOException
import java.util.*
fun expression() {
"hello".startsWith("h")
}
fun statement() {
val a = 1
}
fun isZero(x: Int): Boolean {
return if (x == 0) true else false
}
fun c1() {
val date = Date()
val today = if (date.year == 2016) true else false
}
fun t1() {
fun readFile() = {}
val success = try {
readFile()
true
} catch (e: IOException) {
false
}
}
|
mit
|
8b650774a3e5a67abd4fac51f3f79cd0
| 13.096774 | 52 | 0.603211 | 3.048951 | false | false | false | false |
awsdocs/aws-doc-sdk-examples
|
kotlin/services/glue/src/main/kotlin/com/kotlin/glue/GetJobRun.kt
|
1
|
1697
|
// snippet-sourcedescription:[GetJobRun.kt demonstrates how to get a job run request.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-keyword:[AWS Glue]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.glue
// snippet-start:[glue.kotlin.get_job.import]
import aws.sdk.kotlin.services.glue.GlueClient
import aws.sdk.kotlin.services.glue.model.GetJobRunRequest
import kotlin.system.exitProcess
// snippet-end:[glue.kotlin.get_job.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<jobName> <runId>
Where:
jobName - the name of the job.
runId - the run id value that you can obtain from the AWS Management Console.
"""
if (args.size != 2) {
println(usage)
exitProcess(0)
}
val jobName = args[0]
val runId = args[1]
getGlueJobRun(jobName, runId)
}
// snippet-start:[glue.kotlin.get_job.main]
suspend fun getGlueJobRun(jobNameVal: String?, runIdVal: String?) {
val request = GetJobRunRequest {
jobName = jobNameVal
runId = runIdVal
}
GlueClient { region = "us-east-1" }.use { glueClient ->
val runResponse = glueClient.getJobRun(request)
println("Job status is ${runResponse.jobRun?.toString()}")
}
}
// snippet-end:[glue.kotlin.get_job.main]
|
apache-2.0
|
dd95292049fb9f9f659d9483126ef82c
| 26.762712 | 86 | 0.665292 | 3.68913 | false | false | false | false |
awsdocs/aws-doc-sdk-examples
|
kotlin/services/emr/src/main/kotlin/com/kotlin/emr/DescribeCluster.kt
|
1
|
1649
|
// snippet-sourcedescription:[DescribeCluster.kt demonstrates how to describe a given cluster.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-keyword:[Amazon EMR]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.emr
// snippet-start:[erm.kotlin.describe_cluster.import]
import aws.sdk.kotlin.services.emr.EmrClient
import aws.sdk.kotlin.services.emr.model.DescribeClusterRequest
import kotlin.system.exitProcess
// snippet-end:[erm.kotlin.describe_cluster.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<clusterIdVal>
Where:
clusterIdVal - The id of the cluster to describe.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val clusterIdVal = args[0]
describeMyCluster(clusterIdVal)
}
// snippet-start:[erm.kotlin.describe_cluster.main]
suspend fun describeMyCluster(clusterIdVal: String?) {
val request = DescribeClusterRequest {
clusterId = clusterIdVal
}
EmrClient { region = "us-west-2" }.use { emrClient ->
val response = emrClient.describeCluster(request)
println("The name of the cluster is ${response.cluster?.name}")
}
}
// snippet-end:[erm.kotlin.describe_cluster.main]
|
apache-2.0
|
09c4f72db74e624a824b3c7f3dbe951d
| 27.446429 | 95 | 0.6792 | 3.88 | false | false | false | false |
tateisu/SubwayTooter
|
app/src/main/java/jp/juggler/subwaytooter/api/entity/TootApplication.kt
|
1
|
674
|
package jp.juggler.subwaytooter.api.entity
import jp.juggler.subwaytooter.api.TootParser
import jp.juggler.util.JsonObject
class TootApplication(parser: TootParser, src: JsonObject) {
val name: String?
@Suppress("unused")
private val website: String?
// val description : String?
init {
if (parser.serviceType == ServiceType.MISSKEY) {
name = src.string("name")
website = null
// description = src.string("description")
} else {
name = src.string("name")
website = src.string("website")
// description = website
}
}
}
|
apache-2.0
|
6525105f9e6c71cb5212d62ca5ef294e
| 23.923077 | 60 | 0.574184 | 4.292994 | false | false | false | false |
flesire/ontrack
|
ontrack-git/src/main/java/net/nemerosa/ontrack/git/model/plot/GPlot.kt
|
2
|
608
|
package net.nemerosa.ontrack.git.model.plot
import java.util.*
class GPlot {
private val items = ArrayList<GItem>()
val width: Int
get() {
var width = 0
for (item in items) {
width = Math.max(width, item.maxX)
}
return width
}
val height: Int
get() {
var height = 0
for (item in items) {
height = Math.max(height, item.maxY)
}
return height
}
fun add(item: GItem): GPlot {
items.add(item)
return this
}
}
|
mit
|
3bc2f831fc8229cc84931f7d9c9b5d4b
| 18 | 52 | 0.465461 | 4.136054 | false | false | false | false |
paplorinc/intellij-community
|
plugins/git4idea/tests/git4idea/update/GitSingleRepoUpdateTest.kt
|
2
|
3323
|
// 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 git4idea.update
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.vcs.Executor.cd
import com.intellij.openapi.vcs.update.UpdatedFiles
import git4idea.config.UpdateMethod
import git4idea.repo.GitRepository
import git4idea.test.*
import java.io.File
class GitSingleRepoUpdateTest : GitUpdateBaseTest() {
private lateinit var repo: GitRepository
private lateinit var broRepo : File
override fun setUp() {
super.setUp()
repo = createRepository(project, projectPath, true)
cd(projectPath)
val parent = prepareRemoteRepo(repo)
git("push -u origin master")
broRepo = createBroRepo("bro", parent)
repo.update()
}
override fun getDebugLogCategories() = super.getDebugLogCategories().plus("#git4idea.update")
fun `test stash is called for rebase if there are local changes and local commits`() {
broRepo.commitAndPush()
tac("a.txt")
val localFile = file("a.txt").append("content").add().file
updateChangeListManager()
var stashCalled = false
git.stashListener = {
stashCalled = true
}
val result = updateWithRebase()
assertSuccessfulUpdate(result)
assertTrue("Stash should have been called for dirty working tree", stashCalled)
repo.assertStatus(localFile, 'M')
}
// "Fast-forward merge" optimization
fun `test stash is not called for rebase if there are local changes, but no local commits`() {
broRepo.commitAndPush()
val localFile = file("a.txt").append("content").add().file
updateChangeListManager()
var stashCalled = false
git.stashListener = {
stashCalled = true
}
val result = updateWithRebase()
assertSuccessfulUpdate(result)
assertFalse("Stash shouldn't be called, because of fast-forward merge optimization", stashCalled)
repo.assertStatus(localFile, 'A')
}
// IDEA-167688
fun `test stash is not called for rebase if there are no local changes`() {
broRepo.commitAndPush()
var stashCalled = false
git.stashListener = {
stashCalled = true
}
updateWithRebase()
assertFalse("Stash shouldn't be called for clean working tree", stashCalled)
}
// IDEA-76760
fun `test stash is called for rebase in case of AD changes`() {
broRepo.commitAndPush()
var stashCalled = false
git.stashListener = {
stashCalled = true
}
cd(repo)
val file = file("a.txt").create().add().delete().file
updateChangeListManager()
val result = updateWithRebase()
assertSuccessfulUpdate(result)
assertTrue("Stash should be called for clean working tree", stashCalled)
repo.assertStatus(file, 'A')
}
private fun updateWithRebase(): GitUpdateResult {
return GitUpdateProcess(project, EmptyProgressIndicator(), listOf(repo), UpdatedFiles.create(), false, true).update(UpdateMethod.REBASE)
}
private fun File.commitAndPush() {
cd(this)
tac("f.txt")
git("push -u origin master")
cd(repo)
}
private fun assertSuccessfulUpdate(result: GitUpdateResult) {
assertEquals("Incorrect update result", GitUpdateResult.SUCCESS, result)
}
internal fun file(path: String) = repo.file(path)
}
|
apache-2.0
|
72d9643f7abffdf8edd3a4805692c2f7
| 28.415929 | 140 | 0.711104 | 4.570839 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.