repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
simplifycom/simplify-android-sdk-sample | simplify-android/src/main/kotlin/com/simplify/android/sdk/Simplify.kt | 2 | 7266 | package com.simplify.android.sdk
import android.app.Activity
import android.content.Intent
import android.util.Base64
import android.util.Log
import androidx.annotation.VisibleForTesting
import io.reactivex.Single
import java.nio.charset.Charset
import java.util.*
/**
*
* The public interface to the Simplify SDK
*
* Example set up:
* <pre>
* Simplify simplify = new Simplify("YOUR_SIMPLIFY_PUBLIC_API_KEY");
* </pre>
*/
@Suppress("unused")
class Simplify(apiKey: String) {
/**
* The Simplify public API key
*/
var apiKey: String = ""
set(value) {
if (!validateApiKey(value)) {
throw IllegalArgumentException("Invalid api key: $value")
}
field = value
}
init {
// keep this in init block, forces setter validation
this.apiKey = apiKey
}
@VisibleForTesting
internal var comms = SimplifyComms()
private val url: String
get() = if (isLive) API_BASE_LIVE_URL else API_BASE_SANDBOX_URL
private val isLive: Boolean
get() = apiKey.startsWith(LIVE_KEY_PREFIX)
/**
*
* Performs an asynchronous request to the Simplify server to retrieve a card token
* that can then be used to process a payment.
* <br>Includes optional 3DS request data required to initiate a 3DS authentication process.
*
* @param card A valid card object
* @param secure3DRequestData Data required to initiate 3DS authentication. may be null
* @param callback The callback to invoke after the request is complete
*/
@JvmOverloads
fun createCardToken(card: SimplifyMap, secure3DRequestData: SimplifyMap? = null, callback: SimplifyCallback) =
buildCreateCardTokenRequest(card, secure3DRequestData).run { comms.runSimplifyRequest(this, callback) }
/**
*
* Builds a Single to retrieve a card token that can then be used to process a payment
* <br>Includes optional 3DS request data required to initiate a 3DS authentication process.
* <br>Does not operate on any particular scheduler
*
* @param card A valid card object
* @param secure3DRequestData Data requires to initiate 3DS authentication
* @return A Single of a SimplifyMap containing card token information
*/
@JvmOverloads
fun createCardToken(card: SimplifyMap, secure3DRequestData: SimplifyMap? = null): Single<SimplifyMap> =
buildCreateCardTokenRequest(card, secure3DRequestData).run(comms::runSimplifyRequest)
private fun buildCreateCardTokenRequest(card: SimplifyMap, secure3DRequestData: SimplifyMap?): SimplifyRequest {
val payload = SimplifyMap()
.set("key", apiKey)
.set("card", card)
secure3DRequestData?.let {
payload.set("secure3DRequestData", it)
}
return SimplifyRequest(
url = url + API_PATH_CARDTOKEN,
method = SimplifyRequest.Method.POST,
payload = payload
)
}
private fun validateApiKey(apiKey: String): Boolean {
return PATTERN_API_KEY.toRegex().find(apiKey)?.groupValues?.get(1)?.let { group ->
try {
// parse UUID
UUID.fromString(Base64.decode(group, Base64.DEFAULT).toString(Charset.defaultCharset()))
true
} catch (e: Exception) {
Log.d("Simplify", "Error parsing API key: $group", e)
false
}
} ?: false
}
companion object {
@VisibleForTesting
internal const val REQUEST_CODE_3DS = 1000
@VisibleForTesting
internal const val API_BASE_LIVE_URL = "https://api.simplify.com/v1/api"
@VisibleForTesting
internal const val API_BASE_SANDBOX_URL = "https://sandbox.simplify.com/v1/api"
@VisibleForTesting
internal const val API_PATH_CARDTOKEN = "/payment/cardToken"
private const val PATTERN_API_KEY = "(?:lv|sb)pb_(.+)"
private const val LIVE_KEY_PREFIX = "lvpb_"
/**
* Starts the [SimplifySecure3DActivity] for result, and initializes it with the required 3DS info
*
* @param activity The calling activity
* @param cardToken A map of card token data with a valid card, containing 3DS data
* @param title The title to display in the activity's toolbar
* @throws IllegalArgumentException If cardToken missing 3DS data
*/
@JvmOverloads
@JvmStatic
fun start3DSActivity(activity: Activity, cardToken: SimplifyMap, title: String? = null) {
cardToken["card.secure3DData"]?.run {
SimplifySecure3DActivity.buildIntent(activity, cardToken, title).run {
activity.startActivityForResult(this, REQUEST_CODE_3DS)
}
} ?: throw IllegalArgumentException("The provided card token must contain 3DS data.")
}
/**
*
* Convenience method to handle the 3DS authentication lifecycle. You may use this method within
* [Activity.onActivityResult] to delegate the transaction to a [SimplifySecure3DCallback].
* <pre>
* protected void onActivityResult(int requestCode, int resultCode, Intent data) {
*
* if (Simplify.handle3DSResult(requestCode, resultCode, data, this)) {
* return;
* }
*
* // ...
* }</pre>
*
* @param requestCode The activity request code
* @param resultCode The activity result code
* @param data Data returned by the activity
* @param callback The [SimplifySecure3DCallback]
* @return True if handled, False otherwise
* @throws IllegalArgumentException If callback is null
*/
@JvmStatic
fun handle3DSResult(requestCode: Int, resultCode: Int, data: Intent?, callback: SimplifySecure3DCallback): Boolean {
return when (requestCode) {
REQUEST_CODE_3DS -> {
when (resultCode) {
Activity.RESULT_OK -> {
try {
SimplifyMap(data!!.getStringExtra(SimplifySecure3DActivity.EXTRA_RESULT)).run {
when {
containsKey("secure3d.authenticated") -> callback.onSecure3DComplete(this["secure3d.authenticated"] as Boolean)
containsKey("secure3d.error") -> callback.onSecure3DError(this["secure3d.error.message"] as String)
else -> callback.onSecure3DError("Unknown error occurred during authentication")
}
}
} catch (e: Exception) {
callback.onSecure3DError("Unable to read 3DS result")
}
}
else -> callback.onSecure3DCancel()
}
true
}
else -> false
}
}
}
}
| mit | 8db100a064767195cbc4fdcaacccb5ae | 36.84375 | 151 | 0.589733 | 4.856952 | false | false | false | false |
dahlstrom-g/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/DirectoryChangesGroupingPolicy.kt | 13 | 3165 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.ui
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.vcs.changes.ui.TreeModelBuilder.DIRECTORY_CACHE
import com.intellij.openapi.vcs.changes.ui.TreeModelBuilder.PATH_NODE_BUILDER
import javax.swing.tree.DefaultTreeModel
class DirectoryChangesGroupingPolicy(val project: Project, val model: DefaultTreeModel) : BaseChangesGroupingPolicy() {
override fun getParentNodeFor(nodePath: StaticFilePath, subtreeRoot: ChangesBrowserNode<*>): ChangesBrowserNode<*> {
DIRECTORY_POLICY.set(subtreeRoot, this)
val grandParent = nextPolicy?.getParentNodeFor(nodePath, subtreeRoot) ?: subtreeRoot
HIERARCHY_UPPER_BOUND.set(subtreeRoot, grandParent)
CACHING_ROOT.set(subtreeRoot, getCachingRoot(grandParent, subtreeRoot))
return getParentNodeRecursive(nodePath, subtreeRoot)
}
private fun getParentNodeRecursive(nodePath: StaticFilePath, subtreeRoot: ChangesBrowserNode<*>): ChangesBrowserNode<*> {
generateSequence(nodePath.parent) { it.parent }.forEach { parentPath ->
val cachingRoot = getCachingRoot(subtreeRoot)
DIRECTORY_CACHE.getValue(cachingRoot)[parentPath.key]?.let {
if (HIERARCHY_UPPER_BOUND.get(subtreeRoot) == it) {
GRAND_PARENT_CANDIDATE.set(subtreeRoot, it)
try {
return getPathNode(parentPath, subtreeRoot) ?: it
}
finally {
GRAND_PARENT_CANDIDATE.set(subtreeRoot, null)
}
}
return it
}
getPathNode(parentPath, subtreeRoot)?.let { return it }
}
return HIERARCHY_UPPER_BOUND.getRequired(subtreeRoot)
}
private fun getPathNode(nodePath: StaticFilePath, subtreeRoot: ChangesBrowserNode<*>): ChangesBrowserNode<*>? {
PATH_NODE_BUILDER.getRequired(subtreeRoot).apply(nodePath)?.let {
it.markAsHelperNode()
val grandParent = GRAND_PARENT_CANDIDATE.get(subtreeRoot) ?: getParentNodeRecursive(nodePath, subtreeRoot)
val cachingRoot = getCachingRoot(subtreeRoot)
model.insertNodeInto(it, grandParent, grandParent.childCount)
DIRECTORY_CACHE.getValue(cachingRoot)[nodePath.key] = it
return it
}
return null
}
class Factory : ChangesGroupingPolicyFactory() {
override fun createGroupingPolicy(project: Project, model: DefaultTreeModel): DirectoryChangesGroupingPolicy = DirectoryChangesGroupingPolicy(project, model)
}
companion object {
@JvmField internal val DIRECTORY_POLICY = Key.create<DirectoryChangesGroupingPolicy>("ChangesTree.DirectoryPolicy")
internal val GRAND_PARENT_CANDIDATE = Key.create<ChangesBrowserNode<*>?>("ChangesTree.GrandParentCandidate")
internal val HIERARCHY_UPPER_BOUND = Key.create<ChangesBrowserNode<*>?>("ChangesTree.HierarchyUpperBound")
internal val CACHING_ROOT = Key.create<ChangesBrowserNode<*>?>("ChangesTree.CachingRoot")
internal fun getCachingRoot(subtreeRoot: ChangesBrowserNode<*>) = CACHING_ROOT.get(subtreeRoot) ?: subtreeRoot
}
} | apache-2.0 | e290505bb2c42a35ae23bda926e17ea9 | 44.228571 | 161 | 0.749763 | 4.489362 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/Element.kt | 6 | 4122 | // 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.j2k.ast
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.j2k.CodeBuilder
import org.jetbrains.kotlin.j2k.CodeConverter
import org.jetbrains.kotlin.idea.j2k.EmptyDocCommentConverter
fun <TElement: Element> TElement.assignPrototype(prototype: PsiElement?, inheritance: CommentsAndSpacesInheritance = CommentsAndSpacesInheritance()): TElement {
prototypes = if (prototype != null) listOf(PrototypeInfo(prototype, inheritance)) else listOf()
return this
}
fun <TElement: Element> TElement.assignPrototypes(vararg prototypes: PrototypeInfo): TElement {
this.prototypes = prototypes.asList()
return this
}
fun <TElement: Element> TElement.assignNoPrototype(): TElement {
prototypes = listOf()
return this
}
fun <TElement: Element> TElement.assignPrototypesFrom(element: Element, inheritance: CommentsAndSpacesInheritance? = null): TElement {
prototypes = element.prototypes
if (inheritance != null) {
prototypes = prototypes?.map { PrototypeInfo(it.element, inheritance) }
}
createdAt = element.createdAt
return this
}
data class PrototypeInfo(val element: PsiElement, val commentsAndSpacesInheritance: CommentsAndSpacesInheritance)
enum class SpacesInheritance {
NONE, BLANK_LINES_ONLY, LINE_BREAKS
}
data class CommentsAndSpacesInheritance(
val spacesBefore: SpacesInheritance = SpacesInheritance.BLANK_LINES_ONLY,
val commentsBefore: Boolean = true,
val commentsAfter: Boolean = true,
val commentsInside: Boolean = true
) {
companion object {
val NO_SPACES = CommentsAndSpacesInheritance(spacesBefore = SpacesInheritance.NONE)
val LINE_BREAKS = CommentsAndSpacesInheritance(spacesBefore = SpacesInheritance.LINE_BREAKS)
}
}
fun Element.canonicalCode(): String {
val builder = CodeBuilder(null, EmptyDocCommentConverter)
builder.append(this)
return builder.resultText
}
abstract class Element {
var prototypes: List<PrototypeInfo>? = null
set(value) {
// do not assign prototypes to singleton instances
if (canBeSingleton) {
field = listOf()
return
}
field = value
}
protected open val canBeSingleton: Boolean
get() = isEmpty
var createdAt: String?
= if (saveCreationStacktraces)
Exception().stackTrace.joinToString("\n")
else
null
/** This method should not be used anywhere except for CodeBuilder! Use CodeBuilder.append instead. */
abstract fun generateCode(builder: CodeBuilder)
open fun postGenerateCode(builder: CodeBuilder) { }
open val isEmpty: Boolean get() = false
object Empty : Element() {
override fun generateCode(builder: CodeBuilder) { }
override val isEmpty: Boolean get() = true
}
companion object {
var saveCreationStacktraces = false
}
}
// this class should never be created directly - Converter.deferredElement() should be used!
class DeferredElement<TResult : Element>(
private val generator: (CodeConverter) -> TResult
) : Element() {
private var result: TResult? = null
init {
assignNoPrototype()
}
// need to override it to not use isEmpty
override val canBeSingleton: Boolean
get() = false
fun unfold(codeConverter: CodeConverter) {
assert(result == null)
result = generator(codeConverter)
}
override fun generateCode(builder: CodeBuilder) {
resultNotNull.generateCode(builder)
}
override val isEmpty: Boolean
get() = resultNotNull.isEmpty
private val resultNotNull: TResult
get() {
assert(result != null) { "No code generated for deferred element $this. Possible reason is that it has been created directly instead of Converter.lazyElement() call." }
return result!!
}
}
| apache-2.0 | cfc86922ba7ffcd9edced49c1f55bd77 | 31.203125 | 180 | 0.691897 | 4.58 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/column/ColumnFire.kt | 1 | 1906 | package jp.juggler.subwaytooter.column
import jp.juggler.subwaytooter.ActMain
import jp.juggler.subwaytooter.columnviewholder.*
import jp.juggler.util.AdapterChange
import jp.juggler.util.isMainThread
fun Column.removeColumnViewHolder(cvh: ColumnViewHolder) {
val it = listViewHolder.iterator()
while (it.hasNext()) {
if (cvh == it.next()) it.remove()
}
}
fun Column.removeColumnViewHolderByActivity(activity: ActMain) {
val it = listViewHolder.iterator()
while (it.hasNext()) {
val cvh = it.next()
if (cvh.activity == activity) {
it.remove()
}
}
}
// 複数のリスナがある場合、最も新しいものを返す
val Column.viewHolder: ColumnViewHolder?
get() {
if (isDispose.get()) return null
return if (listViewHolder.isEmpty()) null else listViewHolder.first
}
fun Column.fireShowContent(
reason: String,
changeList: List<AdapterChange>? = null,
reset: Boolean = false,
) {
if (!isMainThread) error("fireShowContent: not on main thread.")
viewHolder?.showContent(reason, changeList, reset)
}
fun Column.fireShowColumnHeader() {
if (!isMainThread) error("fireShowColumnHeader: not on main thread.")
viewHolder?.showColumnHeader()
}
fun Column.fireShowColumnStatus() {
if (!isMainThread) error("fireShowColumnStatus: not on main thread.")
viewHolder?.showColumnStatus()
}
fun Column.fireColumnColor() {
if (!isMainThread) error("fireColumnColor: not on main thread.")
viewHolder?.showColumnColor()
}
fun Column.fireRelativeTime() {
if (!isMainThread) error("fireRelativeTime: not on main thread.")
viewHolder?.updateRelativeTime()
}
fun Column.fireRebindAdapterItems() {
if (!isMainThread) error("fireRelativeTime: not on main thread.")
viewHolder?.rebindAdapterItems()
}
| apache-2.0 | 9d81f02880674a85cd87f86ff478c818 | 27.09375 | 75 | 0.67884 | 3.92827 | false | false | false | false |
zeapo/Android-Password-Store | app/src/main/java/com/zeapo/pwdstore/git/BreakOutOfDetached.kt | 1 | 3321 | package com.zeapo.pwdstore.git
import android.app.Activity
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.zeapo.pwdstore.R
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.api.GitCommand
import org.eclipse.jgit.api.PushCommand
import org.eclipse.jgit.api.RebaseCommand
import java.io.File
class BreakOutOfDetached(fileDir: File, callingActivity: Activity) : GitOperation(fileDir, callingActivity) {
private lateinit var commands: List<GitCommand<out Any>>
/**
* Sets the command
*
* @return the current object
*/
fun setCommands(): BreakOutOfDetached {
val git = Git(repository)
val branchName = "conflicting-master-${System.currentTimeMillis()}"
this.commands = listOf(
// abort the rebase
git.rebase().setOperation(RebaseCommand.Operation.ABORT),
// git checkout -b conflict-branch
git.checkout().setCreateBranch(true).setName(branchName),
// push the changes
git.push().setRemote("origin"),
// switch back to master
git.checkout().setName("master")
)
return this
}
override fun execute() {
val git = Git(repository)
if (!git.repository.repositoryState.isRebasing) {
MaterialAlertDialogBuilder(callingActivity)
.setTitle(callingActivity.resources.getString(R.string.git_abort_and_push_title))
.setMessage("The repository is not rebasing, no need to push to another branch")
.setPositiveButton(callingActivity.resources.getString(R.string.dialog_ok)) { _, _ ->
callingActivity.finish()
}.show()
return
}
if (this.provider != null) {
// set the credentials for push command
this.commands.forEach { cmd ->
if (cmd is PushCommand) {
cmd.setCredentialsProvider(this.provider)
}
}
}
GitAsyncTask(callingActivity, false, true, this)
.execute(*this.commands.toTypedArray())
}
override fun onError(errorMessage: String) {
MaterialAlertDialogBuilder(callingActivity)
.setTitle(callingActivity.resources.getString(R.string.jgit_error_dialog_title))
.setMessage("Error occurred when checking out another branch operation $errorMessage")
.setPositiveButton(callingActivity.resources.getString(R.string.dialog_ok)) { _, _ ->
callingActivity.finish()
}.show()
}
override fun onSuccess() {
MaterialAlertDialogBuilder(callingActivity)
.setTitle(callingActivity.resources.getString(R.string.git_abort_and_push_title))
.setMessage("There was a conflict when trying to rebase. " +
"Your local master branch was pushed to another branch named conflicting-master-....\n" +
"Use this branch to resolve conflict on your computer")
.setPositiveButton(callingActivity.resources.getString(R.string.dialog_ok)) { _, _ ->
callingActivity.finish()
}.show()
}
}
| gpl-3.0 | 9d0c8608cfa1edf0e1bec60567b301ae | 40.5125 | 113 | 0.609154 | 4.971557 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/sqs/src/main/kotlin/com/kotlin/sqs/ReceiveMessages.kt | 1 | 1897 | // snippet-sourcedescription:[RetrieveMessages.kt demonstrates how to retrieve messages from an Amazon Simple Queue Service (Amazon SQS) queue.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon Simple Queue Service]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.sqs
// snippet-start:[sqs.kotlin.get_messages.import]
import aws.sdk.kotlin.services.sqs.SqsClient
import aws.sdk.kotlin.services.sqs.model.ReceiveMessageRequest
import kotlin.system.exitProcess
// snippet-end:[sqs.kotlin.get_messages.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:
<queueName> <tagName>
Where:
queueURL - The URL of the queue from which messages are retrieved.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val queueUrl = args[0]
receiveMessages(queueUrl)
println("The AWS SQS operation example is complete!")
}
// snippet-start:[sqs.kotlin.get_messages.main]
suspend fun receiveMessages(queueUrlVal: String?) {
println("Retrieving messages from $queueUrlVal")
val receiveMessageRequest = ReceiveMessageRequest {
queueUrl = queueUrlVal
maxNumberOfMessages = 5
}
SqsClient { region = "us-east-1" }.use { sqsClient ->
val response = sqsClient.receiveMessage(receiveMessageRequest)
response.messages?.forEach { message ->
println(message.body)
}
}
}
// snippet-end:[sqs.kotlin.get_messages.main]
| apache-2.0 | 9d38bd32e1eb425a16b02de3f23ae38a | 29.098361 | 144 | 0.680021 | 4.062099 | false | false | false | false |
github/codeql | java/ql/test/kotlin/library-tests/jvmstatic-annotation/test.kt | 1 | 3274 | // Test both definining static members, and referring to an object's other static members, in companion object and non-companion object contexts.
// For the companion object all the references to other properties and methods should extract as ordinary instance calls and field read and writes,
// but those methods / getters / setters that are annotated static should get an additional static proxy method defined on the surrounding class--
// for example, we should see (using Java notation) public static String HasCompanion.staticMethod(String s) { return Companion.staticMethod(s); }.
// For the non-companion object, the static-annotated methods should themselves be extracted as static members, and calls / gets / sets that use them
// should extract as static calls. Static members using non-static ones should extract like staticMethod(...) { INSTANCE.nonStaticMethod(...) },
// where the reference to INSTANCE replaces what would normally be a `this` reference.
public class HasCompanion {
companion object {
@JvmStatic fun staticMethod(s: String): String = nonStaticMethod(s)
fun nonStaticMethod(s: String): String = staticMethod(s)
@JvmStatic var staticProp: String = "a"
var nonStaticProp: String = "b"
var propWithStaticGetter: String
@JvmStatic get() = propWithStaticSetter
set(s: String) { propWithStaticSetter = s }
var propWithStaticSetter: String
get() = propWithStaticGetter
@JvmStatic set(s: String) { propWithStaticGetter = s }
}
}
object NonCompanion {
@JvmStatic fun staticMethod(s: String): String = nonStaticMethod(s)
fun nonStaticMethod(s: String): String = staticMethod(s)
@JvmStatic var staticProp: String = "a"
var nonStaticProp: String = "b"
var propWithStaticGetter: String
@JvmStatic get() = propWithStaticSetter
set(s: String) { propWithStaticSetter = s }
var propWithStaticSetter: String
get() = propWithStaticGetter
@JvmStatic set(s: String) { propWithStaticGetter = s }
}
fun externalUser() {
// These all extract as instance calls (to HasCompanion.Companion), since a Kotlin caller won't use the static proxy methods generated by the @JvmStatic annotation.
HasCompanion.staticMethod("1")
HasCompanion.nonStaticMethod("2")
HasCompanion.staticProp = HasCompanion.nonStaticProp
HasCompanion.nonStaticProp = HasCompanion.staticProp
HasCompanion.propWithStaticGetter = HasCompanion.propWithStaticSetter
HasCompanion.propWithStaticSetter = HasCompanion.propWithStaticGetter
// These extract as static methods, since there is no proxy method in the non-companion object case.
NonCompanion.staticMethod("1")
NonCompanion.nonStaticMethod("2")
NonCompanion.staticProp = NonCompanion.nonStaticProp
NonCompanion.nonStaticProp = NonCompanion.staticProp
NonCompanion.propWithStaticGetter = NonCompanion.propWithStaticSetter
NonCompanion.propWithStaticSetter = NonCompanion.propWithStaticGetter
}
// Diagnostic Matches: Completion failure for type: kotlin.jvm.JvmStatic
// Diagnostic Matches: Completion failure for type: org.jetbrains.annotations.NotNull
// Diagnostic Matches: Unknown location for kotlin.jvm.JvmStatic
// Diagnostic Matches: Unknown location for org.jetbrains.annotations.NotNull
| mit | ce170e9e7447b0b5f662066f93531cc9 | 44.472222 | 166 | 0.767257 | 4.442334 | false | false | false | false |
ranmocy/rCaltrain | android/app/src/main/java/me/ranmocy/rcaltrain/database/Queries.kt | 1 | 1935 | package me.ranmocy.rcaltrain.database
import me.ranmocy.rcaltrain.database.ScheduleDao.ServiceType
private const val FROM_STATION_ID = "SELECT id FROM stations WHERE name = :from"
private const val TO_STATION_ID = "SELECT id FROM stations WHERE name = :to"
private const val FROM_SEQUENCE = "SELECT sequence FROM stops WHERE trip_id = trips.id AND station_id in ($FROM_STATION_ID)"
private const val TO_SEQUENCE = "SELECT sequence FROM stops WHERE trip_id = trips.id AND station_id in ($TO_STATION_ID)"
// WITH was introduced in sqlite 3.8.3: https://stackoverflow.com/questions/24036310/error-using-sql-with-clause
// sqlite versions: https://stackoverflow.com/questions/2421189/version-of-sqlite-used-in-android
const val QUERY = """
SELECT f.time AS departureTime, t.time AS arrivalTime
FROM stops AS f, stops AS t
WHERE f.station_id IN (SELECT id FROM stations WHERE name = :from)
AND t.station_id IN (SELECT id FROM stations WHERE name = :to)
AND f.trip_id = t.trip_id
AND (:now IS NULL OR departureTime >= :now)
AND f.trip_id IN
(SELECT id
FROM trips
WHERE ($FROM_SEQUENCE) NOT NULL
AND ($TO_SEQUENCE) NOT NULL
AND ($FROM_SEQUENCE) < ($TO_SEQUENCE)
AND service_id IN
(SELECT id
FROM services
WHERE CASE :serviceType
WHEN ${ServiceType.SERVICE_WEEKDAY} THEN weekday
WHEN ${ServiceType.SERVICE_SATURDAY} THEN saturday
WHEN ${ServiceType.SERVICE_SUNDAY} THEN sunday
ELSE NULL
END
AND ((:today BETWEEN start_date AND end_date
AND id NOT IN (SELECT service_id FROM service_dates WHERE date = :today AND type = 2))
OR id IN (SELECT service_id FROM service_dates WHERE date = :today AND type = 1))))
ORDER BY departureTime
"""
| mit | 2c7678f5148fb49db131b1279dc07157 | 49.921053 | 124 | 0.639793 | 4.152361 | false | false | false | false |
TongmingWu/BLPlayer | app/src/main/java/com/tm/blplayer/ui/activity/HomeActivity.kt | 1 | 4771 | package com.tm.blplayer.ui.activity
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.content.ContextCompat
import android.support.v4.view.ViewPager
import android.view.Gravity
import android.view.View
import android.widget.Toast
import com.tm.blplayer.R
import com.tm.blplayer.base.BaseActivity
import com.tm.blplayer.ui.fragment.*
import kotlinx.android.synthetic.main.activity_home.*
import kotlinx.android.synthetic.main.include_common_toolbar.*
import java.util.*
class HomeActivity : BaseActivity() {
private val tabs = arrayOf("直播", "推荐", "番剧", "分区", "动态", "发现")
private val fragments = ArrayList<Fragment>()
private var mExitTime = 0L
override val layoutId: Int
get() = R.layout.activity_home
override fun initView() {
initTab()
view_pager.offscreenPageLimit = tabs.size
view_pager.adapter = object : FragmentPagerAdapter(supportFragmentManager) {
override fun getItem(position: Int): Fragment {
return fragments[position]
}
override fun getPageTitle(position: Int): CharSequence {
return tabs[position]
}
override fun getCount(): Int {
return tabs.size
}
}
view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
}
override fun onPageScrollStateChanged(state: Int) {
}
})
view_pager.currentItem = 1
tab_layout.setupWithViewPager(view_pager)
}
override fun initData() {
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// TODO: show explanation
} else {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE)
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE -> {
if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the task you need to do.
} else {
// permission denied, boo! Disable the functionality that depends on this permission.
}
}
}
}
override fun initToolbar() {
super.initToolbar()
ll_menu.visibility = View.VISIBLE
ll_home_button.visibility = View.VISIBLE
}
/**
* 初始化TAB
*/
private fun initTab() {
val mLiveFragment = LiveFragment()
val mRecommendFragment = RecommendFragment()
val mBangumiFragment = BangumiFragment()
val mCategoryFragment = CategoryFragment()
val mTrendsFragment = TrendsFragment()
val mDiscoverFragment = DiscoverFragment()
fragments.add(mLiveFragment)
fragments.add(mRecommendFragment)
fragments.add(mBangumiFragment)
fragments.add(mCategoryFragment)
fragments.add(mTrendsFragment)
fragments.add(mDiscoverFragment)
}
override fun onClick(view: View?) {
super.onClick(view)
when (view?.id) {
R.id.ll_menu -> draw_layout.openDrawer(Gravity.START)
R.id.iv_game -> {
}
R.id.iv_download -> {
}
R.id.iv_search -> {
}
}
}
override fun onBackPressed() {
val currentTimeMillis = System.currentTimeMillis()
if (currentTimeMillis - mExitTime <= 2000) {
System.exit(0)
} else {
Toast.makeText(this, resources.getString(R.string.home_exit_hint), Toast.LENGTH_SHORT).show()
mExitTime = currentTimeMillis
}
}
companion object {
private val MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1
}
}
| mit | 15e98fb79c1a00c87b08adcc2b61ba68 | 31.472603 | 115 | 0.623075 | 4.741 | false | false | false | false |
gituser9/InvoiceManagement | app/src/main/java/com/user/invoicemanagement/view/adapter/MainTabRecyclerViewAdapter.kt | 1 | 5149 | package com.user.invoicemanagement.view.adapter
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.user.invoicemanagement.R
import com.user.invoicemanagement.model.data.WeightEnum
import com.user.invoicemanagement.model.dto.Product
import com.user.invoicemanagement.other.Constant
import com.user.invoicemanagement.view.adapter.holder.MainViewHolder
import com.user.invoicemanagement.view.fragment.MainTabFragment
class MainTabRecyclerViewAdapter(var view: MainTabFragment) : RecyclerView.Adapter<MainViewHolder>() {
var items = mutableListOf<Product>()
var holders = mutableListOf<MainViewHolder>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.fragment_main_item, parent, false)
val holder = MainViewHolder(view)
holders.add(holder)
return holder
}
override fun onBindViewHolder(holder: MainViewHolder, position: Int) {
val product = items[position]
holder.product = product
holder.edtName.setText(product.name)
holder.btnWeightOnStore.text = product.weightOnStore.toString()
holder.btnWeightInFridge.text = product.weightInFridge.toString()
holder.btnWeightInStorage.text = product.weightInStorage.toString()
holder.btnWeight4.text = product.weight4.toString()
holder.btnWeight5.text = product.weight5.toString()
holder.edtWeightOnStore.setText(product.weightOnStore.toString())
holder.edtWeightInFridge.setText(product.weightInFridge.toString())
holder.edtWeightInStorage.setText(product.weightInStorage.toString())
holder.edtWeight4.setText(product.weight4.toString())
holder.edtWeight5.setText(product.weight5.toString())
if (product.purchasePrice != 0f) {
holder.edtPurchasePrice.setText(product.purchasePrice.toString())
}
if (product.sellingPrice != 0f) {
holder.edtSellingPrice.setText(product.sellingPrice.toString())
}
holder.tvPurchasePriceSummary.text = Constant.priceFormat.format(product.purchasePriceSummary)
holder.tvSellingPriceSummary.text = Constant.priceFormat.format(product.sellingPriceSummary)
holder.btnWeightOnStore.setOnClickListener { view.showSetWeightDialog(holder.btnWeightOnStore, product, WeightEnum.WEIGHT_1) }
holder.btnWeightInFridge.setOnClickListener { view.showSetWeightDialog(holder.btnWeightInFridge, product, WeightEnum.WEIGHT_2) }
holder.btnWeightInStorage.setOnClickListener { view.showSetWeightDialog(holder.btnWeightInStorage, product, WeightEnum.WEIGHT_3) }
holder.btnWeight4.setOnClickListener { view.showSetWeightDialog(holder.btnWeight4, product, WeightEnum.WEIGHT_4) }
holder.btnWeight5.setOnClickListener { view.showSetWeightDialog(holder.btnWeight5, product, WeightEnum.WEIGHT_5) }
holder.setListener(View.OnLongClickListener {
if (holder.product != null) {
view.deleteProduct(holder.product!!, position)
}
true
})
}
override fun getItemCount(): Int = items.size
fun getViewData(): List<Product> {
val products = mutableListOf<Product>()
for (item in holders) {
if (item.product != null) {
try {
item.product!!.name = item.edtName.text.toString()
item.product!!.weightOnStore = prepareString(item.btnWeightOnStore.text.toString()).toFloatOrNull() ?: 0f
item.product!!.weightInFridge = prepareString(item.btnWeightInFridge.text.toString()).toFloatOrNull() ?: 0f
item.product!!.weightInStorage = prepareString(item.btnWeightInStorage.text.toString()).toFloatOrNull() ?: 0f
item.product!!.weight4 = prepareString(item.btnWeight4.text.toString()).toFloatOrNull() ?: 0f
item.product!!.weight5 = prepareString(item.btnWeight5.text.toString()).toFloatOrNull() ?: 0f
item.product!!.purchasePrice = prepareString(item.edtPurchasePrice.text.toString()).toFloatOrNull() ?: 0f
item.product!!.sellingPrice = prepareString(item.edtSellingPrice.text.toString()).toFloatOrNull() ?: 0f
products.add(item.product!!)
} catch (e: Exception) {
continue
}
}
}
return products
}
fun updateSummaryData() {
for (item in holders) {
if (item.product != null) {
item.tvPurchasePriceSummary.text = Constant.priceFormat.format(item.product!!.purchasePriceSummary)
item.tvSellingPriceSummary.text = Constant.priceFormat.format(item.product!!.sellingPriceSummary)
}
}
}
// todo: to Common
private fun prepareString(string: String): String {
return string
.replace(',', '.')
.replace(Constant.whiteSpaceRegex, "")
}
}
| mit | 98aa10115eb25a5e4b7ef9c69a72e441 | 43.773913 | 138 | 0.683822 | 4.889839 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/nbt/Nbt.kt | 1 | 6992 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt
import com.demonwav.mcdev.nbt.tags.NbtTag
import com.demonwav.mcdev.nbt.tags.NbtTypeId
import com.demonwav.mcdev.nbt.tags.RootCompound
import com.demonwav.mcdev.nbt.tags.TagByte
import com.demonwav.mcdev.nbt.tags.TagByteArray
import com.demonwav.mcdev.nbt.tags.TagCompound
import com.demonwav.mcdev.nbt.tags.TagDouble
import com.demonwav.mcdev.nbt.tags.TagEnd
import com.demonwav.mcdev.nbt.tags.TagFloat
import com.demonwav.mcdev.nbt.tags.TagInt
import com.demonwav.mcdev.nbt.tags.TagIntArray
import com.demonwav.mcdev.nbt.tags.TagList
import com.demonwav.mcdev.nbt.tags.TagLong
import com.demonwav.mcdev.nbt.tags.TagLongArray
import com.demonwav.mcdev.nbt.tags.TagShort
import com.demonwav.mcdev.nbt.tags.TagString
import java.io.DataInputStream
import java.io.InputStream
import java.util.zip.GZIPInputStream
import java.util.zip.ZipException
object Nbt {
private fun getActualInputStream(stream: InputStream): Pair<DataInputStream, Boolean> {
return try {
DataInputStream(GZIPInputStream(stream)) to true
} catch (e: ZipException) {
stream.reset()
DataInputStream(stream) to false
}
}
/**
* Parse the NBT file from the InputStream and return the root TagCompound for the NBT file. This method closes the stream when
* it is finished with it.
*/
@Throws(MalformedNbtFileException::class)
fun buildTagTree(inputStream: InputStream, timeout: Long): Pair<RootCompound, Boolean> {
try {
val (stream, isCompressed) = getActualInputStream(inputStream)
stream.use {
val tagIdByte = stream.readByte()
val tagId = NbtTypeId.getById(tagIdByte)
?: throw MalformedNbtFileException("Unexpected tag id found: $tagIdByte")
if (tagId != NbtTypeId.COMPOUND) {
throw MalformedNbtFileException("Root tag in NBT file is not a compound.")
}
val start = System.currentTimeMillis()
return RootCompound(stream.readUTF(), stream.readCompoundTag(start, timeout).tagMap) to isCompressed
}
} catch (e: Throwable) {
if (e is MalformedNbtFileException) {
throw e
} else {
throw MalformedNbtFileException("Error reading file", e)
}
}
}
private fun DataInputStream.readCompoundTag(start: Long, timeout: Long) = checkTimeout(start, timeout) {
val tagMap = HashMap<String, NbtTag>()
var tagIdByte = this.readByte()
var tagId =
NbtTypeId.getById(tagIdByte) ?: throw MalformedNbtFileException("Unexpected tag id found: $tagIdByte")
while (tagId != NbtTypeId.END) {
val name = this.readUTF()
tagMap[name] = this.readTag(tagId, start, timeout)
tagIdByte = this.readByte()
tagId =
NbtTypeId.getById(tagIdByte) ?: throw MalformedNbtFileException("Unexpected tag id found: $tagIdByte")
}
return@checkTimeout TagCompound(tagMap)
}
private fun DataInputStream.readByteTag(start: Long, timeout: Long) =
checkTimeout(start, timeout) { TagByte(this.readByte()) }
private fun DataInputStream.readShortTag(start: Long, timeout: Long) =
checkTimeout(start, timeout) { TagShort(this.readShort()) }
private fun DataInputStream.readIntTag(start: Long, timeout: Long) =
checkTimeout(start, timeout) { TagInt(this.readInt()) }
private fun DataInputStream.readLongTag(start: Long, timeout: Long) =
checkTimeout(start, timeout) { TagLong(this.readLong()) }
private fun DataInputStream.readFloatTag(start: Long, timeout: Long) =
checkTimeout(start, timeout) { TagFloat(this.readFloat()) }
private fun DataInputStream.readDoubleTag(start: Long, timeout: Long) =
checkTimeout(start, timeout) { TagDouble(this.readDouble()) }
private fun DataInputStream.readStringTag(start: Long, timeout: Long) =
checkTimeout(start, timeout) { TagString(this.readUTF()) }
private fun DataInputStream.readListTag(start: Long, timeout: Long) = checkTimeout(start, timeout) {
val tagIdByte = this.readByte()
val tagId =
NbtTypeId.getById(tagIdByte) ?: throw MalformedNbtFileException("Unexpected tag id found: $tagIdByte")
val length = this.readInt()
if (length <= 0) {
return@checkTimeout TagList(tagId, emptyList())
}
val list = List(length) {
this.readTag(tagId, start, timeout)
}
return@checkTimeout TagList(tagId, list)
}
private fun DataInputStream.readByteArrayTag(start: Long, timeout: Long) = checkTimeout(start, timeout) {
val length = this.readInt()
val bytes = ByteArray(length)
this.readFully(bytes)
return@checkTimeout TagByteArray(bytes)
}
private fun DataInputStream.readIntArrayTag(start: Long, timeout: Long) = checkTimeout(start, timeout) {
val length = this.readInt()
val ints = IntArray(length) {
this.readInt()
}
return@checkTimeout TagIntArray(ints)
}
private fun DataInputStream.readLongArrayTag(start: Long, timeout: Long) = checkTimeout(start, timeout) {
val length = this.readInt()
val longs = LongArray(length) {
this.readLong()
}
return@checkTimeout TagLongArray(longs)
}
private fun DataInputStream.readTag(tagId: NbtTypeId, start: Long, timeout: Long): NbtTag {
return when (tagId) {
NbtTypeId.END -> TagEnd
NbtTypeId.BYTE -> this.readByteTag(start, timeout)
NbtTypeId.SHORT -> this.readShortTag(start, timeout)
NbtTypeId.INT -> this.readIntTag(start, timeout)
NbtTypeId.LONG -> this.readLongTag(start, timeout)
NbtTypeId.FLOAT -> this.readFloatTag(start, timeout)
NbtTypeId.DOUBLE -> this.readDoubleTag(start, timeout)
NbtTypeId.BYTE_ARRAY -> this.readByteArrayTag(start, timeout)
NbtTypeId.STRING -> this.readStringTag(start, timeout)
NbtTypeId.LIST -> this.readListTag(start, timeout)
NbtTypeId.COMPOUND -> this.readCompoundTag(start, timeout)
NbtTypeId.INT_ARRAY -> this.readIntArrayTag(start, timeout)
NbtTypeId.LONG_ARRAY -> this.readLongArrayTag(start, timeout)
}
}
private inline fun <T : Any> checkTimeout(start: Long, timeout: Long, action: () -> T): T {
val now = System.currentTimeMillis()
val took = now - start
if (took > timeout) {
throw NbtFileParseTimeoutException("NBT parse timeout exceeded - Parse time: $took, Timeout: $timeout.")
}
return action()
}
}
| mit | b48d545ea1d83f9c4f182ab79edad41d | 36.191489 | 131 | 0.656035 | 4.300123 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SoftLinkReferencedChildImpl.kt | 1 | 8951 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
import org.jetbrains.deft.annotations.Open
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SoftLinkReferencedChildImpl(val dataSource: SoftLinkReferencedChildData) : SoftLinkReferencedChild, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(EntityWithSoftLinks::class.java,
SoftLinkReferencedChild::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val parentEntity: EntityWithSoftLinks
get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: SoftLinkReferencedChildData?) : ModifiableWorkspaceEntityBase<SoftLinkReferencedChild>(), SoftLinkReferencedChild.Builder {
constructor() : this(SoftLinkReferencedChildData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SoftLinkReferencedChild is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) {
error("Field SoftLinkReferencedChild#parentEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) {
error("Field SoftLinkReferencedChild#parentEntity should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as SoftLinkReferencedChild
this.entitySource = dataSource.entitySource
if (parents != null) {
this.parentEntity = parents.filterIsInstance<EntityWithSoftLinks>().single()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var parentEntity: EntityWithSoftLinks
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)]!! as EntityWithSoftLinks
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as EntityWithSoftLinks
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityData(): SoftLinkReferencedChildData = result ?: super.getEntityData() as SoftLinkReferencedChildData
override fun getEntityClass(): Class<SoftLinkReferencedChild> = SoftLinkReferencedChild::class.java
}
}
class SoftLinkReferencedChildData : WorkspaceEntityData<SoftLinkReferencedChild>() {
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<SoftLinkReferencedChild> {
val modifiable = SoftLinkReferencedChildImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): SoftLinkReferencedChild {
return getCached(snapshot) {
val entity = SoftLinkReferencedChildImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SoftLinkReferencedChild::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return SoftLinkReferencedChild(entitySource) {
this.parentEntity = parents.filterIsInstance<EntityWithSoftLinks>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(EntityWithSoftLinks::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SoftLinkReferencedChildData
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SoftLinkReferencedChildData
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 3d0d3c35e9c0a7864131a55a2c204814 | 37.089362 | 157 | 0.704167 | 5.626021 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/imports/KotlinImportOptimizer.kt | 3 | 15012 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.imports
import com.intellij.lang.ImportOptimizer
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressIndicatorProvider
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.references.fe10.Fe10SyntheticPropertyAccessorReference
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfoOrNull
import org.jetbrains.kotlin.idea.base.scripting.projectStructure.ScriptModuleInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.idea.references.*
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.ImportPath
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.HierarchicalScope
import org.jetbrains.kotlin.resolve.scopes.utils.*
import org.jetbrains.kotlin.types.error.ErrorFunctionDescriptor
class KotlinImportOptimizer : ImportOptimizer {
override fun supports(file: PsiFile) = file is KtFile
override fun processFile(file: PsiFile): ImportOptimizer.CollectingInfoRunnable {
val ktFile = (file as? KtFile) ?: return DO_NOTHING
val (add, remove, imports) = prepareImports(ktFile) ?: return DO_NOTHING
return object : ImportOptimizer.CollectingInfoRunnable {
override fun getUserNotificationInfo(): String = if (remove == 0)
KotlinBundle.message("import.optimizer.text.zero")
else
KotlinBundle.message(
"import.optimizer.text.non.zero",
remove,
KotlinBundle.message("import.optimizer.text.import", remove),
add,
KotlinBundle.message("import.optimizer.text.import", add)
)
override fun run() = replaceImports(ktFile, imports)
}
}
// The same as com.intellij.pom.core.impl.PomModelImpl.isDocumentUncommitted
// Which is checked in com.intellij.pom.core.impl.PomModelImpl.startTransaction
private val KtFile.isDocumentUncommitted: Boolean
get() {
val documentManager = PsiDocumentManager.getInstance(project)
val cachedDocument = documentManager.getCachedDocument(this)
return cachedDocument != null && documentManager.isUncommited(cachedDocument)
}
private fun prepareImports(file: KtFile): OptimizeInformation? {
ApplicationManager.getApplication().assertReadAccessAllowed()
// Optimize imports may be called after command
// And document can be uncommitted after running that command
// In that case we will get ISE: Attempt to modify PSI for non-committed Document!
if (file.isDocumentUncommitted) return null
val moduleInfo = file.moduleInfoOrNull
if (moduleInfo !is ModuleSourceInfo && moduleInfo !is ScriptModuleInfo) return null
val oldImports = file.importDirectives
if (oldImports.isEmpty()) return null
//TODO: keep existing imports? at least aliases (comments)
val descriptorsToImport = collectDescriptorsToImport(file, true)
val imports = prepareOptimizedImports(file, descriptorsToImport) ?: return null
val intersect = imports.intersect(oldImports.map { it.importPath })
return OptimizeInformation(
add = imports.size - intersect.size,
remove = oldImports.size - intersect.size,
imports = imports
)
}
private data class OptimizeInformation(val add: Int, val remove: Int, val imports: List<ImportPath>)
private class CollectUsedDescriptorsVisitor(file: KtFile, val progressIndicator: ProgressIndicator? = null) : KtVisitorVoid() {
//private val elementsSize: Int = if (progressIndicator != null) {
// var size = 0
// file.accept(object : KtVisitorVoid() {
// override fun visitElement(element: PsiElement) {
// size += 1
// element.acceptChildren(this)
// }
// })
//
// size
//} else {
// 0
//}
private var elementProgress: Int = 0
private val currentPackageName = file.packageFqName
private val aliases: Map<FqName, List<Name>> = file.importDirectives
.asSequence()
.filter { !it.isAllUnder && it.alias != null }
.mapNotNull { it.importPath }
.groupBy(keySelector = { it.fqName }, valueTransform = { it.importedName as Name })
private val descriptorsToImport = hashSetOf<OptimizedImportsBuilder.ImportableDescriptor>()
private val namesToImport = hashMapOf<FqName, MutableSet<Name>>()
private val abstractRefs = ArrayList<OptimizedImportsBuilder.AbstractReference>()
private val unresolvedNames = hashSetOf<Name>()
val data: OptimizedImportsBuilder.InputData
get() = OptimizedImportsBuilder.InputData(
descriptorsToImport,
namesToImport,
abstractRefs,
unresolvedNames,
)
override fun visitElement(element: PsiElement) {
ProgressIndicatorProvider.checkCanceled()
elementProgress += 1
//progressIndicator?.apply {
// if (elementsSize != 0) {
// fraction = elementProgress / elementsSize.toDouble()
// }
//}
element.acceptChildren(this)
}
override fun visitImportList(importList: KtImportList) {
}
override fun visitPackageDirective(directive: KtPackageDirective) {
}
override fun visitKtElement(element: KtElement) {
super.visitKtElement(element)
if (element is KtLabelReferenceExpression) return
val references = element.references.ifEmpty { return }
val bindingContext = element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
val isResolved = hasResolvedDescriptor(element, bindingContext)
for (reference in references) {
if (reference !is KtReference) continue
ProgressIndicatorProvider.checkCanceled()
abstractRefs.add(AbstractReferenceImpl(reference))
val names = reference.resolvesByNames
if (!isResolved) {
unresolvedNames += names
}
for (target in reference.targets(bindingContext)) {
val importableDescriptor = target.getImportableDescriptor()
val importableFqName = target.importableFqName ?: continue
val parentFqName = importableFqName.parent()
if (target is PackageViewDescriptor && parentFqName == FqName.ROOT) continue // no need to import top-level packages
if (target !is PackageViewDescriptor && parentFqName == currentPackageName && (importableFqName !in aliases)) continue
if (!reference.canBeResolvedViaImport(target, bindingContext)) continue
if (importableDescriptor.name in names && isAccessibleAsMember(importableDescriptor, element, bindingContext)) {
continue
}
val descriptorNames = (aliases[importableFqName].orEmpty() + importableFqName.shortName()).intersect(names)
namesToImport.getOrPut(importableFqName) { hashSetOf() } += descriptorNames
descriptorsToImport += OptimizedImportsBuilder.ImportableDescriptor(importableDescriptor, importableFqName)
}
}
}
private fun isAccessibleAsMember(target: DeclarationDescriptor, place: KtElement, bindingContext: BindingContext): Boolean {
if (target.containingDeclaration !is ClassDescriptor) return false
fun isInScope(scope: HierarchicalScope): Boolean {
return when (target) {
is FunctionDescriptor ->
scope.findFunction(target.name, NoLookupLocation.FROM_IDE) { it == target } != null
&& bindingContext[BindingContext.DEPRECATED_SHORT_NAME_ACCESS, place] != true
is PropertyDescriptor ->
scope.findVariable(target.name, NoLookupLocation.FROM_IDE) { it == target } != null
&& bindingContext[BindingContext.DEPRECATED_SHORT_NAME_ACCESS, place] != true
is ClassDescriptor ->
scope.findClassifier(target.name, NoLookupLocation.FROM_IDE) == target
&& bindingContext[BindingContext.DEPRECATED_SHORT_NAME_ACCESS, place] != true
else -> false
}
}
val resolutionScope = place.getResolutionScope(bindingContext, place.getResolutionFacade())
val noImportsScope = resolutionScope.replaceImportingScopes(null)
if (isInScope(noImportsScope)) return true
// classes not accessible through receivers, only their constructors
return if (target is ClassDescriptor) false
else resolutionScope.getImplicitReceiversHierarchy().any { isInScope(it.type.memberScope.memberScopeAsImportingScope()) }
}
private class AbstractReferenceImpl(private val reference: KtReference) : OptimizedImportsBuilder.AbstractReference {
override val element: KtElement
get() = reference.element
override val dependsOnNames: Collection<Name>
get() {
val resolvesByNames = reference.resolvesByNames
if (reference is KtInvokeFunctionReference) {
val additionalNames =
(reference.element.calleeExpression as? KtNameReferenceExpression)?.mainReference?.resolvesByNames
if (additionalNames != null) {
return resolvesByNames + additionalNames
}
}
return resolvesByNames
}
override fun resolve(bindingContext: BindingContext) = reference.resolveToDescriptors(bindingContext)
override fun toString() = when (reference) {
is Fe10SyntheticPropertyAccessorReference -> {
reference.toString().replace(
"Fe10SyntheticPropertyAccessorReference",
if (reference.getter) "Getter" else "Setter"
)
}
else -> reference.toString().replace("Fe10", "")
}
}
}
companion object {
fun collectDescriptorsToImport(file: KtFile, inProgressBar: Boolean = false): OptimizedImportsBuilder.InputData {
val progressIndicator = if (inProgressBar) ProgressIndicatorProvider.getInstance().progressIndicator else null
progressIndicator?.text = KotlinBundle.message("import.optimizer.progress.indicator.text.collect.imports.for", file.name)
progressIndicator?.isIndeterminate = false
val visitor = CollectUsedDescriptorsVisitor(file, progressIndicator)
file.accept(visitor)
return visitor.data
}
fun prepareOptimizedImports(file: KtFile, data: OptimizedImportsBuilder.InputData): List<ImportPath>? {
val settings = file.kotlinCustomSettings
val options = OptimizedImportsBuilder.Options(
settings.NAME_COUNT_TO_USE_STAR_IMPORT,
settings.NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS,
isInPackagesToUseStarImport = { fqName -> fqName.asString() in settings.PACKAGES_TO_USE_STAR_IMPORTS }
)
return OptimizedImportsBuilder(file, data, options, file.languageVersionSettings.apiVersion).buildOptimizedImports()
}
fun replaceImports(file: KtFile, imports: List<ImportPath>) {
val manager = PsiDocumentManager.getInstance(file.project)
manager.getDocument(file)?.let { manager.commitDocument(it) }
val importList = file.importList ?: return
val oldImports = importList.imports
val psiFactory = KtPsiFactory(file.project)
for (importPath in imports) {
importList.addBefore(
psiFactory.createImportDirective(importPath),
oldImports.lastOrNull()
) // insert into the middle to keep collapsed state
}
// remove old imports after adding new ones to keep imports folding state
for (import in oldImports) {
import.delete()
}
}
private fun KtReference.targets(bindingContext: BindingContext): Collection<DeclarationDescriptor> {
//class qualifiers that refer to companion objects should be considered (containing) class references
return bindingContext[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, element as? KtReferenceExpression]?.let { listOf(it) }
?: resolveToDescriptors(bindingContext)
}
private val DO_NOTHING = object : ImportOptimizer.CollectingInfoRunnable {
override fun run() = Unit
override fun getUserNotificationInfo() = KotlinBundle.message("import.optimizer.notification.text.unused.imports.not.found")
}
}
}
private fun hasResolvedDescriptor(element: KtElement, bindingContext: BindingContext): Boolean =
if (element is KtCallElement)
element.getResolvedCall(bindingContext) != null
else
element.mainReference?.resolveToDescriptors(bindingContext)?.let { descriptors ->
descriptors.isNotEmpty() && descriptors.none { it is ErrorFunctionDescriptor }
} == true
| apache-2.0 | cac2c98bfe9b1c8f4803f1a0724efff3 | 46.356467 | 140 | 0.654809 | 5.859485 | false | false | false | false |
oryanm/TrelloWidget | app/src/main/kotlin/com/github/oryanmat/trellowidget/activity/ConfigActivity.kt | 1 | 3964 | package com.github.oryanmat.trellowidget.activity
import android.app.Activity
import android.appwidget.AppWidgetManager.EXTRA_APPWIDGET_ID
import android.appwidget.AppWidgetManager.INVALID_APPWIDGET_ID
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.Toast
import com.android.volley.Response
import com.android.volley.VolleyError
import com.github.oryanmat.trellowidget.R
import com.github.oryanmat.trellowidget.T_WIDGET
import com.github.oryanmat.trellowidget.model.Board
import com.github.oryanmat.trellowidget.model.BoardList
import com.github.oryanmat.trellowidget.model.BoardList.Companion.BOARD_LIST_TYPE
import com.github.oryanmat.trellowidget.util.*
import com.github.oryanmat.trellowidget.widget.updateWidget
import kotlinx.android.synthetic.main.activity_config.*
class ConfigActivity : Activity(), OnItemSelectedAdapter, Response.Listener<String>, Response.ErrorListener {
private var appWidgetId = INVALID_APPWIDGET_ID
private var board: Board = Board()
private var list: BoardList = BoardList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_config)
setWidgetId()
get(TrelloAPIUtil.instance.boards(), this)
}
private fun setWidgetId() {
val extras = intent.extras
if (extras != null) {
appWidgetId = extras.getInt(EXTRA_APPWIDGET_ID, INVALID_APPWIDGET_ID)
}
if (appWidgetId == INVALID_APPWIDGET_ID) {
finish()
}
}
private fun get(url: String, listener: ConfigActivity) =
TrelloAPIUtil.instance.getAsync(url, listener, listener)
override fun onResponse(response: String) {
progressBar.visibility = View.GONE
content.visibility = View.VISIBLE
val boards = Json.tryParseJson(response, BOARD_LIST_TYPE, emptyList<Board>())
board = getBoard(appWidgetId)
setSpinner(boardSpinner, boards, this, boards.indexOf(board))
}
override fun onErrorResponse(error: VolleyError) {
finish()
Log.e(T_WIDGET, error.toString())
val text = getString(R.string.board_load_fail)
Toast.makeText(this, text, Toast.LENGTH_LONG).show()
startActivity(Intent(this, MainActivity::class.java))
}
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
when (parent) {
boardSpinner -> boardSelected(parent, position)
listSpinner -> list = parent.getItemAtPosition(position) as BoardList
}
}
private fun boardSelected(spinner: AdapterView<*>, position: Int) {
board = spinner.getItemAtPosition(position) as Board
list = getList(appWidgetId)
setSpinner(listSpinner, board.lists, this, board.lists.indexOf(list))
}
private fun <T> setSpinner(spinner: Spinner, lists: List<T>,
listener: AdapterView.OnItemSelectedListener, selectedIndex: Int): Spinner {
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, lists)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = adapter
spinner.onItemSelectedListener = listener
spinner.setSelection(if (selectedIndex > -1) selectedIndex else 0)
return spinner
}
fun ok(view: View) {
if (board.id.isEmpty() || list.id.isEmpty()) return
putConfigInfo(appWidgetId, board, list)
updateWidget(appWidgetId)
returnOk()
}
private fun returnOk() {
val resultValue = Intent()
resultValue.putExtra(EXTRA_APPWIDGET_ID, appWidgetId)
setResult(RESULT_OK, resultValue)
finish()
}
fun cancel(view: View) = finish()
} | mit | da46783cfb5589d72b7583e4f791a208 | 36.056075 | 109 | 0.702573 | 4.271552 | false | false | false | false |
Raizlabs/DBFlow | processor/src/main/kotlin/com/dbflow5/processor/definition/ManyToManyDefinition.kt | 1 | 4974 | package com.dbflow5.processor.definition
import com.dbflow5.annotation.ForeignKey
import com.dbflow5.annotation.ManyToMany
import com.dbflow5.annotation.PrimaryKey
import com.dbflow5.annotation.Table
import com.dbflow5.processor.ClassNames
import com.dbflow5.processor.ProcessorManager
import com.dbflow5.processor.utils.annotation
import com.dbflow5.processor.utils.extractTypeNameFromAnnotation
import com.dbflow5.processor.utils.isNullOrEmpty
import com.dbflow5.processor.utils.lower
import com.dbflow5.processor.utils.toClassName
import com.dbflow5.processor.utils.toTypeElement
import com.grosner.kpoet.L
import com.grosner.kpoet.`@`
import com.grosner.kpoet.`fun`
import com.grosner.kpoet.`return`
import com.grosner.kpoet.field
import com.grosner.kpoet.final
import com.grosner.kpoet.member
import com.grosner.kpoet.modifiers
import com.grosner.kpoet.param
import com.grosner.kpoet.public
import com.grosner.kpoet.statement
import com.squareup.javapoet.AnnotationSpec
import com.squareup.javapoet.TypeName
import com.squareup.javapoet.TypeSpec
import javax.lang.model.element.TypeElement
/**
* Description: Generates the Model class that is used in a many to many.
*/
class ManyToManyDefinition(element: TypeElement, processorManager: ProcessorManager,
manyToMany: ManyToMany)
: BaseDefinition(element, processorManager) {
val databaseTypeName: TypeName? = element.extractTypeNameFromAnnotation<Table> { it.database }
private val referencedTable: TypeName = manyToMany.extractTypeNameFromAnnotation { it.referencedTable }
private val generateAutoIncrement: Boolean = manyToMany.generateAutoIncrement
private val sameTableReferenced: Boolean = referencedTable == elementTypeName
private val generatedTableClassName = manyToMany.generatedTableClassName
private val saveForeignKeyModels: Boolean = manyToMany.saveForeignKeyModels
private val thisColumnName = manyToMany.thisTableColumnName
private val referencedColumnName = manyToMany.referencedTableColumnName
init {
if (!thisColumnName.isNullOrEmpty() && !referencedColumnName.isNullOrEmpty()
&& thisColumnName == referencedColumnName) {
manager.logError(ManyToManyDefinition::class, "The thisTableColumnName and referenceTableColumnName cannot be the same")
}
}
fun prepareForWrite() {
if (generatedTableClassName.isNullOrEmpty()) {
val referencedOutput = referencedTable.toTypeElement(manager).toClassName(manager)
setOutputClassName("_${referencedOutput?.simpleName()}")
} else {
setOutputClassNameFull(generatedTableClassName)
}
}
override fun onWriteDefinition(typeBuilder: TypeSpec.Builder) {
typeBuilder.apply {
addAnnotation(AnnotationSpec.builder(Table::class.java)
.addMember("database", "\$T.class", databaseTypeName).build())
val referencedDefinition = manager.getTableDefinition(databaseTypeName, referencedTable)
val selfDefinition = manager.getTableDefinition(databaseTypeName, elementTypeName)
if (generateAutoIncrement) {
addField(field(`@`(PrimaryKey::class) { this["autoincrement"] = "true" }, TypeName.LONG, "_id").build())
`fun`(TypeName.LONG, "getId") {
modifiers(public, final)
`return`("_id")
}
}
referencedDefinition?.let { appendColumnDefinitions(this, it, 0, referencedColumnName) }
selfDefinition?.let { appendColumnDefinitions(this, it, 1, thisColumnName) }
}
}
override val extendsClass: TypeName? = ClassNames.BASE_MODEL
private fun appendColumnDefinitions(typeBuilder: TypeSpec.Builder,
referencedDefinition: TableDefinition, index: Int, optionalName: String) {
var fieldName = referencedDefinition.elementName.lower()
if (sameTableReferenced) {
fieldName += index.toString()
}
// override with the name (if specified)
if (!optionalName.isNullOrEmpty()) {
fieldName = optionalName
}
typeBuilder.apply {
`field`(referencedDefinition.elementClassName!!, fieldName) {
if (!generateAutoIncrement) {
`@`(PrimaryKey::class)
}
`@`(ForeignKey::class) { member("saveForeignKeyModel", saveForeignKeyModels.toString()) }
}
`fun`(referencedDefinition.elementClassName!!, "get${fieldName.capitalize()}") {
modifiers(public, final)
`return`(fieldName.L)
}
`fun`(TypeName.VOID, "set${fieldName.capitalize()}",
param(referencedDefinition.elementClassName!!, "param")) {
modifiers(public, final)
statement("$fieldName = param")
}
}
}
} | mit | d36b4412a84ed44b7df214d267314cfe | 41.521368 | 132 | 0.689184 | 4.895669 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/secondaryConstructors/delegateWithComplexExpression.kt | 5 | 832 | var log = ""
open class Base(val s: String)
class A(s: String) : Base(s) {
constructor(i: Int) : this("O" + if (i == 23) {
log += "logged1;"
"K"
}
else {
"fail"
})
constructor(i: Long) : this(if (i == 23L) {
log += "logged2;"
23
}
else {
42
})
}
class B : Base {
constructor(i: Int) : super("O" + if (i == 23) {
log += "logged3;"
"K"
}
else {
"fail"
})
}
fun box(): String {
var result = A(23).s
if (result != "OK") return "fail1: $result"
result = A(23L).s
if (result != "OK") return "fail2: $result"
result = B(23).s
if (result != "OK") return "fail3: $result"
if (log != "logged1;logged2;logged1;logged3;") return "fail log: $log"
return "OK"
} | apache-2.0 | e93cf282aa1b558c3858a44ae7243767 | 17.108696 | 74 | 0.449519 | 3.025455 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/callableReference/function/overloadedFun.kt | 5 | 559 | fun foo(): String = "foo1"
fun foo(i: Int): String = "foo2"
val f1: () -> String = ::foo
val f2: (Int) -> String = ::foo
fun foo1() {}
fun foo2(i: Int) {}
fun bar(f: () -> Unit): String = "bar1"
fun bar(f: (Int) -> Unit): String = "bar2"
fun box(): String {
val x1 = f1()
if (x1 != "foo1") return "Fail 1: $x1"
val x2 = f2(0)
if (x2 != "foo2") return "Fail 2: $x2"
val y1 = bar(::foo1)
if (y1 != "bar1") return "Fail 3: $y1"
val y2 = bar(::foo2)
if (y2 != "bar2") return "Fail 4: $y2"
return "OK"
}
| apache-2.0 | 93a3b5c1c889478a7fe4b1c92b33e3bb | 19.703704 | 42 | 0.488372 | 2.441048 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/boxInline/argumentOrder/boundFunctionReference.kt | 3 | 898 | // NO_CHECK_LAMBDA_INLINING
// FILE: 1.kt
package test
inline fun test(a: String, b: String, c: () -> String): String {
return a + b + c();
}
// FILE: 2.kt
import test.*
var res = ""
fun String.id() = this
val receiver: String
get() {
res += "L"
return "L"
}
fun box(): String {
res = ""
var call = test(b = { res += "K"; "K" }(), a = { res += "O"; "O" }(), c = receiver::id)
if (res != "KOL" || call != "OKL") return "fail 1: $res != KOL or $call != OKL"
res = ""
call = test(b = { res += "K"; "K" }(), c = receiver::id, a = { res += "O"; "O" }())
if (res != "KLO" || call != "OKL") return "fail 2: $res != KLO or $call != OKL"
res = ""
call = test(c = receiver::id, b = { res += "K"; "K" }(), a = { res += "O"; "O" }())
if (res != "LKO" || call != "OKL") return "fail 3: $res != LKO or $call != OKL"
return "OK"
}
| apache-2.0 | 88ad72b5f8fe4a15b24b766b180b71fc | 20.902439 | 91 | 0.451002 | 2.641176 | false | true | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/callBy/simpleMemberFunciton.kt | 2 | 329 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
class A(val result: String = "OK") {
fun foo(x: Int = 42): String {
assert(x == 42) { x }
return result
}
}
fun box(): String = A::foo.callBy(mapOf(A::foo.parameters.first() to A()))
| apache-2.0 | b2ccafae4016f81f88a0dbd10a1f2479 | 24.307692 | 74 | 0.607903 | 3.29 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinCallerUsages.kt | 6 | 2921 | // 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.changeSignature.usages
import com.intellij.usageView.UsageInfo
import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo
import org.jetbrains.kotlin.idea.refactoring.changeSignature.getAffectedCallables
import org.jetbrains.kotlin.idea.refactoring.changeSignature.isInsideOfCallerBody
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
class KotlinCallerUsage(element: KtNamedDeclaration) : KotlinUsageInfo<KtNamedDeclaration>(element) {
override fun processUsage(changeInfo: KotlinChangeInfo, element: KtNamedDeclaration, allUsages: Array<out UsageInfo>): Boolean {
// Do not process function twice
if (changeInfo.getAffectedCallables().any { it is KotlinCallableDefinitionUsage<*> && it.element == element }) return true
val parameterList = when (element) {
is KtFunction -> element.valueParameterList
is KtClass -> element.createPrimaryConstructorParameterListIfAbsent()
else -> null
} ?: return true
changeInfo.getNonReceiverParameters()
.asSequence()
.withIndex()
.filter { it.value.isNewParameter }
.toList()
.forEach {
val newParameter = it.value.getDeclarationSignature(it.index, changeInfo.methodDescriptor.originalPrimaryCallable)
parameterList.addParameter(newParameter).addToShorteningWaitSet()
}
return true
}
}
class KotlinCallerCallUsage(element: KtCallElement) : KotlinUsageInfo<KtCallElement>(element) {
override fun processUsage(changeInfo: KotlinChangeInfo, element: KtCallElement, allUsages: Array<out UsageInfo>): Boolean {
val argumentList = element.valueArgumentList ?: return true
val psiFactory = KtPsiFactory(project)
val isNamedCall = argumentList.arguments.any { it.isNamed() }
changeInfo.getNonReceiverParameters()
.filter { it.isNewParameter }
.forEach {
val parameterName = it.name
val argumentExpression = if (element.isInsideOfCallerBody(allUsages)) {
psiFactory.createExpression(parameterName)
} else {
it.defaultValueForCall ?: psiFactory.createExpression("_")
}
val argument = psiFactory.createArgument(
expression = argumentExpression,
name = if (isNamedCall) Name.identifier(parameterName) else null
)
argumentList.addArgument(argument).addToShorteningWaitSet()
}
return true
}
}
| apache-2.0 | e707d6953cf0fdbfc521b9002236da97 | 46.112903 | 158 | 0.686751 | 5.727451 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/refIndex/src/org/jetbrains/kotlin/idea/search/refIndex/KotlinReferenceIndexBundle.kt | 6 | 900 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.search.refIndex
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import org.jetbrains.kotlin.util.AbstractKotlinBundle
import java.util.function.Supplier
@NonNls
private const val BUNDLE = "messages.KotlinReferenceIndexBundle"
object KotlinReferenceIndexBundle : AbstractKotlinBundle(BUNDLE) {
fun message(
@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String,
vararg params: Any,
): @Nls String = getMessage(key, *params)
fun lazyMessage(
@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String,
vararg params: Any,
): Supplier<@Nls String> = getLazyMessage(key, *params)
}
| apache-2.0 | 928d97e4093bfb0e7a4c8f6373ed0bcd | 38.130435 | 158 | 0.76 | 4.245283 | false | false | false | false |
smmribeiro/intellij-community | python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyStdlibCanonicalPathProvider.kt | 2 | 2627 | /*
* Copyright 2000-2014 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.jetbrains.python.codeInsight.stdlib
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiUtilCore
import com.intellij.psi.util.QualifiedName
import com.jetbrains.python.psi.resolve.PyCanonicalPathProvider
import com.jetbrains.python.sdk.PythonSdkUtil
import java.util.*
class PyStdlibCanonicalPathProvider : PyCanonicalPathProvider {
override fun getCanonicalPath(symbol: PsiElement?, qName: QualifiedName, foothold: PsiElement?): QualifiedName? {
val virtualFile = PsiUtilCore.getVirtualFile(symbol)
if (virtualFile != null && foothold != null && PythonSdkUtil.isStdLib(virtualFile, PythonSdkUtil.findPythonSdk(foothold))) {
return restoreStdlibCanonicalPath(qName)
}
return null
}
}
fun replace0(comp0: String, components: ArrayList<String>): QualifiedName {
val cmp = ArrayList<String>(comp0.split('.'))
val newComponents = ArrayList<String>(components)
newComponents.removeAt(0)
cmp.addAll(newComponents)
return QualifiedName.fromComponents(cmp)
}
fun restoreStdlibCanonicalPath(qName: QualifiedName): QualifiedName? {
if (qName.componentCount > 0) {
val components = ArrayList(qName.components)
val head = components[0]
return when (head) {
"_abcoll", "_collections" -> replace0("collections", components)
"_collections_abc" -> replace0("collections.abc", components)
"posix", "nt" -> replace0("os", components)
"_functools" -> replace0("functools", components)
"_struct" -> replace0("struct", components)
"_io", "_pyio", "_fileio" -> replace0("io", components)
"_datetime" -> replace0("datetime", components)
"ntpath", "posixpath", "path", "macpath", "os2emxpath", "genericpath" -> replace0("os.path", components)
"_sqlite3" -> replace0("sqlite3", components)
"_pickle" -> replace0("pickle", components)
else -> if (qName.matchesPrefix(QualifiedName.fromComponents("mock", "mock"))) {
return qName.removeHead(1)
}
else null
}
}
return null
}
| apache-2.0 | 78e5446bd2bd64572300d1c3c075fa01 | 37.072464 | 128 | 0.716407 | 4.098284 | false | false | false | false |
Flank/flank | tool/execution/parallel/src/main/kotlin/flank/exection/parallel/Execute.kt | 1 | 845 | package flank.exection.parallel
import flank.exection.parallel.internal.Execution
import flank.exection.parallel.internal.invoke
import flank.exection.parallel.internal.minusContextValidators
import kotlinx.coroutines.flow.Flow
/**
* Execute tasks in parallel with a given args.
*
* @return [Flow] of [ParallelState] changes.
*/
infix operator fun Tasks.invoke(
args: ParallelState
): Flow<ParallelState> =
Execution(minusContextValidators(), args).invoke()
// ======================= Extensions =======================
/**
* Shortcut for executing tasks on a given state.
*/
operator fun Tasks.invoke(
vararg state: Pair<Parallel.Type<*>, Any>
): Flow<ParallelState> = invoke(state.toMap())
/**
* Shortcut for executing tasks on empty state.
*/
operator fun Tasks.invoke(): Flow<ParallelState> =
invoke(emptyMap())
| apache-2.0 | c31cd593ffacb029ffddb4a15530c4f3 | 26.258065 | 62 | 0.702959 | 4.101942 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnect.kt | 1 | 2344 | package info.nightscout.androidaps.plugins.general.automation.elements
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.LinearLayout
import android.widget.Spinner
import androidx.annotation.StringRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.resources.ResourceHelper
import java.util.*
import javax.inject.Inject
class ComparatorConnect(injector: HasAndroidInjector) : Element(injector) {
@Inject lateinit var resourceHelper: ResourceHelper
enum class Compare {
ON_CONNECT, ON_DISCONNECT;
@get:StringRes val stringRes: Int
get() = when (this) {
ON_CONNECT -> R.string.onconnect
ON_DISCONNECT -> R.string.ondisconnect
}
companion object {
fun labels(resourceHelper: ResourceHelper): List<String> {
val list: MutableList<String> = ArrayList()
for (c in values()) list.add(resourceHelper.gs(c.stringRes))
return list
}
}
}
constructor(injector: HasAndroidInjector, value: Compare) : this(injector) {
this.value = value
}
var value = Compare.ON_CONNECT
override fun addToLayout(root: LinearLayout) {
val spinner = Spinner(root.context)
val spinnerArrayAdapter = ArrayAdapter(root.context, R.layout.spinner_centered, Compare.labels(resourceHelper))
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = spinnerArrayAdapter
val spinnerParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4))
spinner.layoutParams = spinnerParams
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
value = Compare.values()[position]
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
spinner.setSelection(value.ordinal)
root.addView(spinner)
}
} | agpl-3.0 | ba9c36b44fa59bbfa6db66b51cb7957e | 38.083333 | 133 | 0.692833 | 4.945148 | false | false | false | false |
ingokegel/intellij-community | plugins/completion-ml-ranking/src/com/intellij/completion/ml/features/ContextFeaturesStorage.kt | 10 | 1296 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.completion.ml.features
import com.intellij.codeInsight.completion.ml.ContextFeatures
import com.intellij.codeInsight.completion.ml.MLFeatureValue
import com.intellij.openapi.util.UserDataHolderBase
class ContextFeaturesStorage(private val featuresSnapshot: Map<String, MLFeatureValue>) : ContextFeatures, UserDataHolderBase() {
companion object {
val EMPTY = ContextFeaturesStorage(emptyMap())
}
override fun binaryValue(name: String): Boolean? = findValue<MLFeatureValue.BinaryValue>(name)?.value
override fun floatValue(name: String): Double? = findValue<MLFeatureValue.FloatValue>(name)?.value
override fun categoricalValue(name: String): String? = findValue<MLFeatureValue.CategoricalValue>(name)?.value
override fun classNameValue(name: String): String? = findValue<MLFeatureValue.ClassNameValue>(name)
?.let { MLFeaturesUtil.getClassNameSafe(it) }
override fun asMap(): Map<String, String> = featuresSnapshot.mapValues { MLFeaturesUtil.getRawValue(it.value).toString() }
private inline fun <reified T : MLFeatureValue> findValue(name: String): T? {
return featuresSnapshot[name] as? T
}
}
| apache-2.0 | 1f6fe2e01c5222f8f33e4057af76fa2f | 45.285714 | 140 | 0.783179 | 4.24918 | false | false | false | false |
siosio/intellij-community | platform/configuration-store-impl/src/schemeManager/SchemeManagerImpl.kt | 2 | 24225 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore.schemeManager
import com.intellij.concurrency.ConcurrentCollectionFactory
import com.intellij.configurationStore.*
import com.intellij.ide.ui.UITheme
import com.intellij.ide.ui.laf.TempUIThemeBasedLookAndFeelInfo
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StateStorageOperation
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.options.Scheme
import com.intellij.openapi.options.SchemeProcessor
import com.intellij.openapi.options.SchemeState
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.SafeWriteRequestor
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.NewVirtualFile
import com.intellij.util.*
import com.intellij.util.containers.catch
import com.intellij.util.containers.mapSmart
import com.intellij.util.io.*
import com.intellij.util.text.UniqueNameGenerator
import org.jdom.Document
import org.jdom.Element
import java.io.File
import java.io.IOException
import java.nio.file.FileSystemException
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.function.Function
import java.util.function.Predicate
class SchemeManagerImpl<T: Scheme, MUTABLE_SCHEME : T>(val fileSpec: String,
processor: SchemeProcessor<T, MUTABLE_SCHEME>,
private val provider: StreamProvider?,
internal val ioDirectory: Path,
val roamingType: RoamingType = RoamingType.DEFAULT,
val presentableName: String? = null,
private val schemeNameToFileName: SchemeNameToFileName = CURRENT_NAME_CONVERTER,
private val fileChangeSubscriber: FileChangeSubscriber? = null,
private val virtualFileResolver: VirtualFileResolver? = null) : SchemeManagerBase<T, MUTABLE_SCHEME>(processor), SafeWriteRequestor, StorageManagerFileWriteRequestor {
private val isUseVfs: Boolean
get() = fileChangeSubscriber != null || virtualFileResolver != null
internal val isOldSchemeNaming = schemeNameToFileName == OLD_NAME_CONVERTER
private val isLoadingSchemes = AtomicBoolean()
internal val schemeListManager = SchemeListManager(this)
internal val schemes: MutableList<T>
get() = schemeListManager.schemes
internal var cachedVirtualDirectory: VirtualFile? = null
internal val schemeExtension: String
private val updateExtension: Boolean
internal val filesToDelete: MutableSet<String> = Collections.newSetFromMap(ConcurrentHashMap())
// scheme could be changed - so, hashcode will be changed - we must use identity hashing strategy
internal val schemeToInfo = ConcurrentCollectionFactory.createConcurrentIdentityMap<T, ExternalInfo>()
init {
if (processor is SchemeExtensionProvider) {
schemeExtension = processor.schemeExtension
updateExtension = true
}
else {
schemeExtension = FileStorageCoreUtil.DEFAULT_EXT
updateExtension = false
}
if (isUseVfs) {
LOG.runAndLogException { refreshVirtualDirectory() }
}
}
override val rootDirectory: File
get() = ioDirectory.toFile()
override val allSchemeNames: Collection<String>
get() = schemes.mapSmart { processor.getSchemeKey(it) }
override val allSchemes: List<T>
get() = Collections.unmodifiableList(schemes)
override val isEmpty: Boolean
get() = schemes.isEmpty()
private fun refreshVirtualDirectory() {
// store refreshes root directory, so, we don't need to use refreshAndFindFile
val directory = LocalFileSystem.getInstance().findFileByPath(ioDirectory.systemIndependentPath) ?: return
cachedVirtualDirectory = directory
directory.children
if (directory is NewVirtualFile) {
directory.markDirty()
}
directory.refresh(true, false)
}
override fun loadBundledScheme(resourceName: String, requestor: Any?, pluginDescriptor: PluginDescriptor?) {
try {
val bytes: ByteArray
if (pluginDescriptor == null) {
when (requestor) {
is TempUIThemeBasedLookAndFeelInfo -> {
bytes = Files.readAllBytes(Path.of(resourceName))
}
is UITheme -> {
val stream = requestor.providerClassLoader.getResourceAsStream(resourceName.removePrefix("/"))
if (stream == null) {
LOG.error("Cannot find $resourceName in ${requestor.providerClassLoader}")
return
}
bytes = stream.use { it.readAllBytes() }
}
else -> {
val stream = (if (requestor is ClassLoader) requestor else requestor!!.javaClass.classLoader)
.getResourceAsStream(resourceName.removePrefix("/"))
if (stream == null) {
LOG.error("Cannot read scheme from $resourceName")
return
}
bytes = stream.use { it.readAllBytes() }
}
}
}
else {
val stream = pluginDescriptor.pluginClassLoader.getResourceAsStream(resourceName.removePrefix("/"))
if (stream == null) {
LOG.error("Cannot found scheme $resourceName in ${pluginDescriptor.pluginClassLoader}")
return
}
bytes = stream.use { it.readAllBytes() }
}
lazyPreloadScheme(bytes, isOldSchemeNaming) { name, parser ->
val attributeProvider = Function<String, String?> { parser.getAttributeValue(null, it) }
val fileName = PathUtilRt.getFileName(resourceName)
val extension = getFileExtension(fileName, true)
val externalInfo = ExternalInfo(fileName.substring(0, fileName.length - extension.length), extension)
val schemeKey = name
?: (processor as LazySchemeProcessor).getSchemeKey(attributeProvider, externalInfo.fileNameWithoutExtension)
?: throw nameIsMissed(bytes)
externalInfo.schemeKey = schemeKey
val scheme = (processor as LazySchemeProcessor).createScheme(SchemeDataHolderImpl(processor, bytes, externalInfo), schemeKey, attributeProvider, true)
val oldInfo = schemeToInfo.put(scheme, externalInfo)
LOG.assertTrue(oldInfo == null)
val oldScheme = schemeListManager.readOnlyExternalizableSchemes.put(schemeKey, scheme)
if (oldScheme != null) {
LOG.warn("Duplicated scheme $schemeKey - old: $oldScheme, new $scheme")
}
schemes.add(scheme)
if (requestor is UITheme) {
requestor.editorSchemeName = schemeKey
}
if (requestor is TempUIThemeBasedLookAndFeelInfo) {
requestor.theme.editorSchemeName = schemeKey
}
}
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error("Cannot read scheme from $resourceName", e)
}
}
internal fun createSchemeLoader(isDuringLoad: Boolean = false): SchemeLoader<T, MUTABLE_SCHEME> {
val filesToDelete = HashSet(filesToDelete)
// caller must call SchemeLoader.apply to bring back scheduled for delete files
this.filesToDelete.removeAll(filesToDelete)
// SchemeLoader can use retain list to bring back previously scheduled for delete file,
// but what if someone will call save() during load and file will be deleted, although should be loaded by a new load session
// (because modified on disk)
return SchemeLoader(this, schemes, filesToDelete, isDuringLoad)
}
internal fun getFileExtension(fileName: CharSequence, isAllowAny: Boolean): String {
return when {
StringUtilRt.endsWithIgnoreCase(fileName, schemeExtension) -> schemeExtension
StringUtilRt.endsWithIgnoreCase(fileName, FileStorageCoreUtil.DEFAULT_EXT) -> FileStorageCoreUtil.DEFAULT_EXT
isAllowAny -> PathUtil.getFileExtension(fileName.toString())!!
else -> throw IllegalStateException("Scheme file extension $fileName is unknown, must be filtered out")
}
}
override fun loadSchemes(): Collection<T> {
if (!isLoadingSchemes.compareAndSet(false, true)) {
throw IllegalStateException("loadSchemes is already called")
}
try {
// isDuringLoad is true even if loadSchemes called not first time, but on reload,
// because scheme processor should use cumulative event `reloaded` to update runtime state/caches
val schemeLoader = createSchemeLoader(isDuringLoad = true)
val isLoadOnlyFromProvider = provider != null && provider.processChildren(fileSpec, roamingType, { canRead(it) }) { name, input, readOnly ->
catchAndLog({ "${provider.javaClass.name}: $name" }) {
val scheme = schemeLoader.loadScheme(name, input, null)
if (readOnly && scheme != null) {
schemeListManager.readOnlyExternalizableSchemes.put(processor.getSchemeKey(scheme), scheme)
}
}
true
}
if (!isLoadOnlyFromProvider) {
if (virtualFileResolver == null) {
ioDirectory.directoryStreamIfExists({ canRead(it.fileName.toString()) }) { directoryStream ->
for (file in directoryStream) {
catchAndLog({ file.toString() }) {
val bytes = try {
Files.readAllBytes(file)
}
catch (e: FileSystemException) {
when {
file.isDirectory() -> return@catchAndLog
else -> throw e
}
}
schemeLoader.loadScheme(file.fileName.toString(), null, bytes)
}
}
}
}
else {
for (file in getVirtualDirectory(StateStorageOperation.READ)?.children ?: VirtualFile.EMPTY_ARRAY) {
catchAndLog({ file.path }) {
if (canRead(file.nameSequence)) {
schemeLoader.loadScheme(file.name, null, file.contentsToByteArray())
}
}
}
}
}
val newSchemes = schemeLoader.apply()
for (newScheme in newSchemes) {
if (processPendingCurrentSchemeName(newScheme)) {
break
}
}
fileChangeSubscriber?.invoke(this)
return newSchemes
}
finally {
isLoadingSchemes.set(false)
}
}
override fun reload() {
processor.beforeReloaded(this)
// we must not remove non-persistent (e.g. predefined) schemes, because we cannot load it (obviously)
// do not schedule scheme file removing because we just need to update our runtime state, not state on disk
removeExternalizableSchemesFromRuntimeState()
processor.reloaded(this, loadSchemes())
}
// method is used to reflect already performed changes on disk, so, `isScheduleToDelete = false` is passed to `retainExternalInfo`
internal fun removeExternalizableSchemesFromRuntimeState() {
// todo check is bundled/read-only schemes correctly handled
val iterator = schemes.iterator()
for (scheme in iterator) {
if ((scheme as? SerializableScheme)?.schemeState ?: processor.getState(scheme) == SchemeState.NON_PERSISTENT) {
continue
}
activeScheme?.let {
if (scheme === it) {
currentPendingSchemeName = processor.getSchemeKey(it)
activeScheme = null
}
}
iterator.remove()
@Suppress("UNCHECKED_CAST")
processor.onSchemeDeleted(scheme as MUTABLE_SCHEME)
}
retainExternalInfo(isScheduleToDelete = false)
}
internal fun getFileName(scheme: T) = schemeToInfo.get(scheme)?.fileNameWithoutExtension
fun canRead(name: CharSequence) = (updateExtension && name.endsWith(FileStorageCoreUtil.DEFAULT_EXT, true) || name.endsWith(schemeExtension, ignoreCase = true)) && (processor !is LazySchemeProcessor || processor.isSchemeFile(name))
override fun save(errors: MutableList<Throwable>) {
if (isLoadingSchemes.get()) {
LOG.warn("Skip save - schemes are loading")
}
var hasSchemes = false
val nameGenerator = UniqueNameGenerator()
val changedSchemes = SmartList<MUTABLE_SCHEME>()
for (scheme in schemes) {
val state = (scheme as? SerializableScheme)?.schemeState ?: processor.getState(scheme)
if (state == SchemeState.NON_PERSISTENT) {
continue
}
hasSchemes = true
if (state != SchemeState.UNCHANGED) {
@Suppress("UNCHECKED_CAST")
changedSchemes.add(scheme as MUTABLE_SCHEME)
}
val fileName = getFileName(scheme)
if (fileName != null && !isRenamed(scheme)) {
nameGenerator.addExistingName(fileName)
}
}
val filesToDelete = HashSet(filesToDelete)
for (scheme in changedSchemes) {
try {
saveScheme(scheme, nameGenerator, filesToDelete)
}
catch (e: Throwable) {
errors.add(RuntimeException("Cannot save scheme $fileSpec/$scheme", e))
}
}
if (filesToDelete.isNotEmpty()) {
val iterator = schemeToInfo.values.iterator()
for (info in iterator) {
if (filesToDelete.contains(info.fileName)) {
iterator.remove()
}
}
this.filesToDelete.removeAll(filesToDelete)
deleteFiles(errors, filesToDelete)
// remove empty directory only if some file was deleted - avoid check on each save
if (!hasSchemes && (provider == null || !provider.isApplicable(fileSpec, roamingType))) {
removeDirectoryIfEmpty(errors)
}
}
}
private fun removeDirectoryIfEmpty(errors: MutableList<Throwable>) {
ioDirectory.directoryStreamIfExists {
for (file in it) {
if (!file.isHidden()) {
LOG.info("Directory ${ioDirectory.fileName} is not deleted: at least one file ${file.fileName} exists")
return@removeDirectoryIfEmpty
}
}
}
LOG.info("Remove scheme directory ${ioDirectory.fileName}")
if (isUseVfs) {
val dir = getVirtualDirectory(StateStorageOperation.WRITE)
cachedVirtualDirectory = null
if (dir != null) {
runWriteAction {
try {
dir.delete(this)
}
catch (e: IOException) {
errors.add(e)
}
}
}
}
else {
errors.catch {
ioDirectory.delete()
}
}
}
private fun saveScheme(scheme: MUTABLE_SCHEME, nameGenerator: UniqueNameGenerator, filesToDelete: MutableSet<String>) {
var externalInfo: ExternalInfo? = schemeToInfo.get(scheme)
val currentFileNameWithoutExtension = externalInfo?.fileNameWithoutExtension
val element = processor.writeScheme(scheme)?.let { it as? Element ?: (it as Document).detachRootElement() }
if (element.isEmpty()) {
externalInfo?.scheduleDelete(filesToDelete, "empty")
return
}
var fileNameWithoutExtension = currentFileNameWithoutExtension
if (fileNameWithoutExtension == null || isRenamed(scheme)) {
fileNameWithoutExtension = nameGenerator.generateUniqueName(schemeNameToFileName(processor.getSchemeKey(scheme)))
}
val fileName = fileNameWithoutExtension + schemeExtension
// file will be overwritten, so, we don't need to delete it
filesToDelete.remove(fileName)
val newDigest = element!!.digest()
when {
externalInfo != null && currentFileNameWithoutExtension === fileNameWithoutExtension && externalInfo.isDigestEquals(newDigest) -> return
isEqualToBundledScheme(externalInfo, newDigest, scheme, filesToDelete) -> return
// we must check it only here to avoid delete old scheme just because it is empty (old idea save -> new idea delete on open)
processor is LazySchemeProcessor && processor.isSchemeDefault(scheme, newDigest) -> {
externalInfo?.scheduleDelete(filesToDelete, "equals to default")
return
}
}
// stream provider always use LF separator
val byteOut = element.toBufferExposingByteArray()
var providerPath: String?
if (provider != null && provider.enabled) {
providerPath = "$fileSpec/$fileName"
if (!provider.isApplicable(providerPath, roamingType)) {
providerPath = null
}
}
else {
providerPath = null
}
// if another new scheme uses old name of this scheme, we must not delete it (as part of rename operation)
@Suppress("SuspiciousEqualsCombination")
val renamed = externalInfo != null && fileNameWithoutExtension !== currentFileNameWithoutExtension && currentFileNameWithoutExtension != null && nameGenerator.isUnique(currentFileNameWithoutExtension)
if (providerPath == null) {
if (isUseVfs) {
var file: VirtualFile? = null
var dir = getVirtualDirectory(StateStorageOperation.WRITE)
if (dir == null || !dir.isValid) {
dir = createDir(ioDirectory, this)
cachedVirtualDirectory = dir
}
if (renamed) {
val oldFile = dir.findChild(externalInfo!!.fileName)
if (oldFile != null) {
// VFS doesn't allow to rename to existing file, so, check it
if (dir.findChild(fileName) == null) {
runWriteAction {
oldFile.rename(this, fileName)
}
file = oldFile
}
else {
externalInfo.scheduleDelete(filesToDelete, "renamed")
}
}
}
if (file == null) {
file = dir.getOrCreateChild(fileName, this)
}
runWriteAction {
file.getOutputStream(this).use { byteOut.writeTo(it) }
}
}
else {
if (renamed) {
externalInfo!!.scheduleDelete(filesToDelete, "renamed")
}
ioDirectory.resolve(fileName).write(byteOut.internalBuffer, 0, byteOut.size())
}
}
else {
if (renamed) {
externalInfo!!.scheduleDelete(filesToDelete, "renamed")
}
provider!!.write(providerPath, byteOut.internalBuffer, byteOut.size(), roamingType)
}
if (externalInfo == null) {
externalInfo = ExternalInfo(fileNameWithoutExtension, schemeExtension)
schemeToInfo.put(scheme, externalInfo)
}
else {
externalInfo.setFileNameWithoutExtension(fileNameWithoutExtension, schemeExtension)
}
externalInfo.digest = newDigest
externalInfo.schemeKey = processor.getSchemeKey(scheme)
}
private fun isEqualToBundledScheme(externalInfo: ExternalInfo?, newDigest: ByteArray, scheme: MUTABLE_SCHEME, filesToDelete: MutableSet<String>): Boolean {
fun serializeIfPossible(scheme: T): Element? {
LOG.runAndLogException {
@Suppress("UNCHECKED_CAST")
val bundledAsMutable = scheme as? MUTABLE_SCHEME ?: return null
return processor.writeScheme(bundledAsMutable) as Element
}
return null
}
val bundledScheme = schemeListManager.readOnlyExternalizableSchemes.get(processor.getSchemeKey(scheme))
if (bundledScheme == null) {
if ((processor as? LazySchemeProcessor)?.isSchemeEqualToBundled(scheme) == true) {
externalInfo?.scheduleDelete(filesToDelete, "equals to bundled")
return true
}
return false
}
val bundledExternalInfo = schemeToInfo.get(bundledScheme) ?: return false
if (bundledExternalInfo.digest == null) {
serializeIfPossible(bundledScheme)?.let {
bundledExternalInfo.digest = it.digest()
} ?: return false
}
if (bundledExternalInfo.isDigestEquals(newDigest)) {
externalInfo?.scheduleDelete(filesToDelete, "equals to bundled")
return true
}
return false
}
private fun isRenamed(scheme: T): Boolean {
val info = schemeToInfo.get(scheme)
return info != null && processor.getSchemeKey(scheme) != info.schemeKey
}
private fun deleteFiles(errors: MutableList<Throwable>, filesToDelete: MutableSet<String>) {
if (provider != null) {
val iterator = filesToDelete.iterator()
for (name in iterator) {
errors.catch {
val spec = "$fileSpec/$name"
if (provider.delete(spec, roamingType)) {
LOG.debug { "$spec deleted from provider $provider" }
iterator.remove()
}
}
}
}
if (filesToDelete.isEmpty()) {
return
}
LOG.debug { "Delete scheme files: ${filesToDelete.joinToString()}" }
if (isUseVfs) {
getVirtualDirectory(StateStorageOperation.WRITE)?.let { virtualDir ->
val childrenToDelete = virtualDir.children.filter { filesToDelete.contains(it.name) }
if (childrenToDelete.isNotEmpty()) {
runWriteAction {
for (file in childrenToDelete) {
errors.catch { file.delete(this) }
}
}
}
return
}
}
for (name in filesToDelete) {
errors.catch { ioDirectory.resolve(name).delete() }
}
}
internal fun getVirtualDirectory(reasonOperation: StateStorageOperation): VirtualFile? {
var result = cachedVirtualDirectory
if (result == null) {
val path = ioDirectory.systemIndependentPath
result = when (virtualFileResolver) {
null -> LocalFileSystem.getInstance().findFileByPath(path)
else -> virtualFileResolver.resolveVirtualFile(path, reasonOperation)
}
cachedVirtualDirectory = result
}
return result
}
override fun setSchemes(newSchemes: List<T>, newCurrentScheme: T?, removeCondition: Predicate<T>?) {
schemeListManager.setSchemes(newSchemes, newCurrentScheme, removeCondition)
}
internal fun retainExternalInfo(isScheduleToDelete: Boolean) {
if (schemeToInfo.isEmpty()) {
return
}
val iterator = schemeToInfo.entries.iterator()
l@ for ((scheme, info) in iterator) {
if (schemeListManager.readOnlyExternalizableSchemes.get(processor.getSchemeKey(scheme)) === scheme) {
continue
}
for (s in schemes) {
if (s === scheme) {
filesToDelete.remove(info.fileName)
continue@l
}
}
iterator.remove()
if (isScheduleToDelete) {
info.scheduleDelete(filesToDelete, "requested to delete")
}
}
}
override fun addScheme(scheme: T, replaceExisting: Boolean) = schemeListManager.addScheme(scheme, replaceExisting)
override fun findSchemeByName(schemeName: String) = schemes.firstOrNull { processor.getSchemeKey(it) == schemeName }
override fun removeScheme(name: String) = removeFirstScheme(true) { processor.getSchemeKey(it) == name }
override fun removeScheme(scheme: T) = removeScheme(scheme, isScheduleToDelete = true)
fun removeScheme(scheme: T, isScheduleToDelete: Boolean) = removeFirstScheme(isScheduleToDelete) { it === scheme } != null
override fun isMetadataEditable(scheme: T) = !schemeListManager.readOnlyExternalizableSchemes.containsKey(processor.getSchemeKey(scheme))
override fun toString() = fileSpec
internal fun removeFirstScheme(isScheduleToDelete: Boolean, condition: (T) -> Boolean): T? {
val iterator = schemes.iterator()
for (scheme in iterator) {
if (!condition(scheme)) {
continue
}
if (activeScheme === scheme) {
activeScheme = null
}
iterator.remove()
if (isScheduleToDelete && processor.isExternalizable(scheme)) {
schemeToInfo.remove(scheme)?.scheduleDelete(filesToDelete, "requested to delete (removeFirstScheme)")
}
return scheme
}
return null
}
} | apache-2.0 | 52be96f7c2fb57f5f39ddc51254db354 | 36.328197 | 233 | 0.664396 | 5.159744 | false | false | false | false |
siosio/intellij-community | python/python-psi-impl/src/com/jetbrains/python/inspections/PyFinalInspection.kt | 1 | 18903 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.inspections
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.jetbrains.python.PyNames
import com.jetbrains.python.PyPsiBundle
import com.jetbrains.python.codeInsight.controlflow.ScopeOwner
import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil
import com.jetbrains.python.codeInsight.functionTypeComments.psi.PyFunctionTypeAnnotation
import com.jetbrains.python.codeInsight.functionTypeComments.psi.PyParameterTypeList
import com.jetbrains.python.codeInsight.typeHints.PyTypeHintFile
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.*
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyClassImpl
import com.jetbrains.python.psi.search.PySuperMethodsSearch
import com.jetbrains.python.psi.types.PyClassType
import com.jetbrains.python.pyi.PyiUtil
class PyFinalInspection : PyInspection() {
override fun buildVisitor(holder: ProblemsHolder,
isOnTheFly: Boolean,
session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, session)
private class Visitor(holder: ProblemsHolder, session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) {
override fun visitPyClass(node: PyClass) {
super.visitPyClass(node)
node.getSuperClasses(myTypeEvalContext).filter { isFinal(it) }.let { finalSuperClasses ->
if (finalSuperClasses.isEmpty()) return@let
@NlsSafe val superClassList = finalSuperClasses.joinToString { "'${it.name}'" }
registerProblem(node.nameIdentifier,
PyPsiBundle.message("INSP.final.super.classes.are.marked.as.final.and.should.not.be.subclassed",
superClassList, finalSuperClasses.size))
}
if (PyiUtil.isInsideStub(node)) {
val visitedNames = mutableSetOf<String?>()
node.visitMethods(
{ m ->
if (!visitedNames.add(m.name) && isFinal(m)) {
registerProblem(m.nameIdentifier, PyPsiBundle.message("INSP.final.final.should.be.placed.on.first.overload"))
}
true
},
false,
myTypeEvalContext
)
}
else {
val (classLevelFinals, initAttributes) = getClassLevelFinalsAndInitAttributes(node)
checkClassLevelFinalsAreInitialized(classLevelFinals, initAttributes)
checkSameNameClassAndInstanceFinals(classLevelFinals, initAttributes)
}
checkOverridingInheritedFinalWithNewOne(node)
}
override fun visitPyFunction(node: PyFunction) {
super.visitPyFunction(node)
val cls = node.containingClass
if (cls != null) {
PySuperMethodsSearch
.search(node, myTypeEvalContext)
.asSequence()
.filterIsInstance<PyFunction>()
.firstOrNull { isFinal(it) }
?.let {
@NlsSafe val qualifiedName = it.qualifiedName ?: (it.containingClass?.name + "." + it.name)
registerProblem(node.nameIdentifier,
PyPsiBundle.message("INSP.final.method.marked.as.final.should.not.be.overridden", qualifiedName))
}
if (!PyiUtil.isInsideStub(node)) {
if (isFinal(node) && PyiUtil.isOverload(node, myTypeEvalContext)) {
registerProblem(node.nameIdentifier, PyPsiBundle.message("INSP.final.final.should.be.placed.on.implementation"))
}
checkInstanceFinalsOutsideInit(node)
}
if (PyKnownDecoratorUtil.hasAbstractDecorator(node, myTypeEvalContext)) {
if (isFinal(node)) {
registerProblem(node.nameIdentifier, PyPsiBundle.message("INSP.final.final.could.not.be.mixed.with.abstract.decorators"))
}
else if (isFinal(cls)) {
val message = PyPsiBundle.message("INSP.final.final.class.could.not.contain.abstract.methods")
registerProblem(node.nameIdentifier, message)
registerProblem(cls.nameIdentifier, message)
}
}
else if (isFinal(node) && isFinal(cls)) {
registerProblem(node.nameIdentifier, PyPsiBundle.message("INSP.final.no.need.to.mark.method.in.final.class.as.final"),
ProblemHighlightType.WEAK_WARNING)
}
}
else if (isFinal(node)) {
registerProblem(node.nameIdentifier, PyPsiBundle.message("INSP.final.non.method.function.could.not.be.marked.as.final"))
}
getFunctionTypeAnnotation(node)?.let { comment ->
if (comment.parameterTypeList.parameterTypes.any { resolvesToFinal(if (it is PySubscriptionExpression) it.operand else it) }) {
registerProblem(node.typeComment,
PyPsiBundle.message("INSP.final.final.could.not.be.used.in.annotations.for.function.parameters"))
}
}
getReturnTypeAnnotation(node, myTypeEvalContext)?.let {
if (resolvesToFinal(if (it is PySubscriptionExpression) it.operand else it)) {
registerProblem(node.typeComment ?: node.annotation,
PyPsiBundle.message("INSP.final.final.could.not.be.used.in.annotation.for.function.return.value"))
}
}
}
override fun visitPyTargetExpression(node: PyTargetExpression) {
super.visitPyTargetExpression(node)
if (!node.hasAssignedValue()) {
node.annotation?.value?.let {
if (PyiUtil.isInsideStub(node) || ScopeUtil.getScopeOwner(node) is PyClass) {
if (resolvesToFinal(it)) {
registerProblem(it,
PyPsiBundle.message("INSP.final.if.assigned.value.omitted.there.should.be.explicit.type.argument.to.final"))
}
}
else {
if (resolvesToFinal(if (it is PySubscriptionExpression) it.operand else it)) {
registerProblem(node, PyPsiBundle.message("INSP.final.final.name.should.be.initialized.with.value"))
}
}
}
}
else if (!isFinal(node)) {
checkFinalReassignment(node)
}
if (isFinal(node) && PyUtil.multiResolveTopPriority(node, resolveContext).any { it != node }) {
registerProblem(node, PyPsiBundle.message("INSP.final.already.declared.name.could.not.be.redefined.as.final"))
}
}
override fun visitPyNamedParameter(node: PyNamedParameter) {
super.visitPyNamedParameter(node)
if (isFinal(node)) {
registerProblem(node.annotation?.value ?: node.typeComment,
PyPsiBundle.message("INSP.final.final.could.not.be.used.in.annotations.for.function.parameters"))
}
}
override fun visitPyReferenceExpression(node: PyReferenceExpression) {
super.visitPyReferenceExpression(node)
checkFinalIsOuterMost(node)
}
override fun visitPyForStatement(node: PyForStatement) {
super.visitPyForStatement(node)
checkFinalInsideLoop(node)
}
override fun visitPyWhileStatement(node: PyWhileStatement) {
super.visitPyWhileStatement(node)
checkFinalInsideLoop(node)
}
override fun visitPyAugAssignmentStatement(node: PyAugAssignmentStatement) {
super.visitPyAugAssignmentStatement(node)
val target = node.target
if (target is PyQualifiedExpression) {
checkFinalReassignment(target)
}
}
private fun getClassLevelFinalsAndInitAttributes(cls: PyClass): Pair<Map<String?, PyTargetExpression>, Map<String, PyTargetExpression>> {
val classLevelFinals = mutableMapOf<String?, PyTargetExpression>()
cls.classAttributes.forEach { if (isFinal(it)) classLevelFinals[it.name] = it }
val initAttributes = mutableMapOf<String, PyTargetExpression>()
cls.findMethodByName(PyNames.INIT, false, myTypeEvalContext)?.let { PyClassImpl.collectInstanceAttributes(it, initAttributes) }
return Pair(classLevelFinals, initAttributes)
}
private fun getDeclaredClassAndInstanceFinals(cls: PyClass): Pair<Map<String, PyTargetExpression>, Map<String, PyTargetExpression>> {
val classFinals = mutableMapOf<String, PyTargetExpression>()
val instanceFinals = mutableMapOf<String, PyTargetExpression>()
for (classAttribute in cls.classAttributes) {
val name = classAttribute.name ?: continue
if (isFinal(classAttribute)) {
val mapToPut = if (classAttribute.hasAssignedValue()) classFinals else instanceFinals
mapToPut[name] = classAttribute
}
}
cls.findMethodByName(PyNames.INIT, false, myTypeEvalContext)?.let { init ->
val attributesInInit = mutableMapOf<String, PyTargetExpression>()
PyClassImpl.collectInstanceAttributes(init, attributesInInit)
attributesInInit.keys.removeAll(instanceFinals.keys)
instanceFinals += attributesInInit.filterValues { isFinal(it) }
}
return Pair(classFinals, instanceFinals)
}
private fun checkClassLevelFinalsAreInitialized(classLevelFinals: Map<String?, PyTargetExpression>,
initAttributes: Map<String, PyTargetExpression>) {
classLevelFinals.forEach { (name, psi) ->
if (!psi.hasAssignedValue() && name !in initAttributes) {
registerProblem(psi, PyPsiBundle.message("INSP.final.final.name.should.be.initialized.with.value"))
}
}
}
private fun checkSameNameClassAndInstanceFinals(classLevelFinals: Map<String?, PyTargetExpression>,
initAttributes: Map<String, PyTargetExpression>) {
initAttributes.forEach { (name, initAttribute) ->
val sameNameClassLevelFinal = classLevelFinals[name]
if (sameNameClassLevelFinal != null && isFinal(initAttribute)) {
if (sameNameClassLevelFinal.hasAssignedValue()) {
registerProblem(initAttribute, PyPsiBundle.message("INSP.final.already.declared.name.could.not.be.redefined.as.final"))
}
else {
val message = PyPsiBundle.message("INSP.final.either.instance.attribute.or.class.attribute.could.be.type.hinted.as.final")
registerProblem(sameNameClassLevelFinal, message)
registerProblem(initAttribute, message)
}
}
}
}
private fun checkOverridingInheritedFinalWithNewOne(cls: PyClass) {
val (newClassFinals, newInstanceFinals) = getDeclaredClassAndInstanceFinals(cls)
val notRegisteredClassFinals = newClassFinals.keys.toMutableSet()
val notRegisteredInstanceFinals = newInstanceFinals.keys.toMutableSet()
if (notRegisteredClassFinals.isEmpty() && notRegisteredInstanceFinals.isEmpty()) return
for (ancestor in cls.getAncestorClasses(myTypeEvalContext)) {
val (inheritedClassFinals, inheritedInstanceFinals) = getDeclaredClassAndInstanceFinals(ancestor)
checkOverridingInheritedFinalWithNewOne(newClassFinals, inheritedClassFinals, ancestor.name, notRegisteredClassFinals)
checkOverridingInheritedFinalWithNewOne(newInstanceFinals, inheritedInstanceFinals, ancestor.name, notRegisteredInstanceFinals)
if (notRegisteredClassFinals.isEmpty() && notRegisteredInstanceFinals.isEmpty()) break
}
}
private fun checkOverridingInheritedFinalWithNewOne(newFinals: Map<String, PyTargetExpression>,
inheritedFinals: Map<String, PyTargetExpression>,
ancestorName: String?,
notRegistered: MutableSet<String>) {
if (notRegistered.isEmpty()) return
for (commonFinal in newFinals.keys.intersect(inheritedFinals.keys)) {
@NlsSafe val qualifiedName = "$ancestorName.$commonFinal"
registerProblem(newFinals[commonFinal], PyPsiBundle.message("INSP.final.final.attribute.could.not.be.overridden", qualifiedName))
notRegistered.remove(commonFinal)
}
}
private fun checkInstanceFinalsOutsideInit(method: PyFunction) {
if (PyUtil.isInitMethod(method)) return
val instanceAttributes = mutableMapOf<String, PyTargetExpression>()
PyClassImpl.collectInstanceAttributes(method, instanceAttributes)
instanceAttributes.values.forEach {
if (isFinal(it)) registerProblem(it, PyPsiBundle.message("INSP.final.final.attribute.should.be.declared.in.class.body.or.init"))
}
}
private fun checkFinalReassignment(target: PyQualifiedExpression) {
val qualifierType = target.qualifier?.let { myTypeEvalContext.getType(it) }
if (qualifierType is PyClassType && !qualifierType.isDefinition) {
checkInstanceFinalReassignment(target, qualifierType.pyClass)
return
}
// TODO: revert back to PyUtil#multiResolveTopPriority when resolve into global statement is implemented
val resolved = when (target) {
is PyReferenceOwner -> target.getReference(resolveContext).multiResolve(false).mapNotNull { it.element }
else -> PyUtil.multiResolveTopPriority(target, resolveContext)
}
if (resolved.any { it is PyTargetExpression && isFinal(it) }) {
registerProblem(target, PyPsiBundle.message("INSP.final.final.target.could.not.be.reassigned", target.name))
return
}
for (e in resolved) {
if (myTypeEvalContext.maySwitchToAST(e) &&
e.parent.let { it is PyNonlocalStatement || it is PyGlobalStatement } &&
PyUtil.multiResolveTopPriority(e, resolveContext).any { it is PyTargetExpression && isFinal(it) }) {
registerProblem(target, PyPsiBundle.message("INSP.final.final.target.could.not.be.reassigned", target.name))
return
}
}
if (!target.isQualified) {
val scopeOwner = ScopeUtil.getScopeOwner(target)
if (scopeOwner is PyClass) {
checkInheritedClassFinalReassignmentOnClassLevel(target, scopeOwner)
}
}
}
private fun checkInstanceFinalReassignment(target: PyQualifiedExpression, cls: PyClass) {
val name = target.name ?: return
val classAttribute = cls.findClassAttribute(name, false, myTypeEvalContext)
if (classAttribute != null && !classAttribute.hasAssignedValue() && isFinal(classAttribute)) {
if (target is PyTargetExpression &&
ScopeUtil.getScopeOwner(target).let { it is PyFunction && PyUtil.turnConstructorIntoClass(it) == cls }) {
return
}
registerProblem(target, PyPsiBundle.message("INSP.final.final.target.could.not.be.reassigned", name))
}
for (ancestor in cls.getAncestorClasses(myTypeEvalContext)) {
val inheritedClassAttribute = ancestor.findClassAttribute(name, false, myTypeEvalContext)
if (inheritedClassAttribute != null && !inheritedClassAttribute.hasAssignedValue() && isFinal(inheritedClassAttribute)) {
@NlsSafe val qualifiedName = "${ancestor.name}.$name"
registerProblem(target, PyPsiBundle.message("INSP.final.final.target.could.not.be.reassigned", qualifiedName))
return
}
}
for (current in (sequenceOf(cls) + cls.getAncestorClasses(myTypeEvalContext).asSequence())) {
val init = current.findMethodByName(PyNames.INIT, false, myTypeEvalContext)
if (init != null) {
val attributesInInit = mutableMapOf<String, PyTargetExpression>()
PyClassImpl.collectInstanceAttributes(init, attributesInInit)
if (attributesInInit[name]?.let { it != target && isFinal(it) } == true) {
@NlsSafe val qualifiedName = (if (cls == current) "" else "${current.name}.") + name
registerProblem(target, PyPsiBundle.message("INSP.final.final.target.could.not.be.reassigned", qualifiedName))
break
}
}
}
}
private fun checkInheritedClassFinalReassignmentOnClassLevel(target: PyQualifiedExpression, cls: PyClass) {
val name = target.name ?: return
for (ancestor in cls.getAncestorClasses(myTypeEvalContext)) {
val ancestorClassAttribute = ancestor.findClassAttribute(name, false, myTypeEvalContext)
if (ancestorClassAttribute != null && ancestorClassAttribute.hasAssignedValue() && isFinal(ancestorClassAttribute)) {
@NlsSafe val qualifiedName = "${ancestor.name}.$name"
registerProblem(target, PyPsiBundle.message("INSP.final.final.target.could.not.be.reassigned", qualifiedName))
break
}
}
}
private fun checkFinalIsOuterMost(node: PyReferenceExpression) {
if (isTopLevelInAnnotationOrTypeComment(node)) return
(node.parent as? PySubscriptionExpression)?.let {
if (it.operand == node && isTopLevelInAnnotationOrTypeComment(it)) return
}
if (isInsideTypeHint(node, myTypeEvalContext) && resolvesToFinal(node)) {
registerProblem(node, PyPsiBundle.message("INSP.final.final.could.only.be.used.as.outermost.type"))
}
}
private fun checkFinalInsideLoop(loop: PyLoopStatement) {
loop.acceptChildren(
object : PyRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
if (element !is ScopeOwner) super.visitElement(element)
}
override fun visitPyForStatement(node: PyForStatement) {}
override fun visitPyWhileStatement(node: PyWhileStatement) {}
override fun visitPyTargetExpression(node: PyTargetExpression) {
if (isFinal(node)) registerProblem(node, PyPsiBundle.message("INSP.final.final.could.not.be.used.inside.loop"))
}
}
)
}
private fun isFinal(decoratable: PyDecoratable) = isFinal(decoratable, myTypeEvalContext)
private fun <T> isFinal(node: T): Boolean where T : PyAnnotationOwner, T : PyTypeCommentOwner {
return isFinal(node, myTypeEvalContext)
}
private fun resolvesToFinal(expression: PyExpression?): Boolean {
return expression is PyReferenceExpression &&
resolveToQualifiedNames(expression, myTypeEvalContext).any { it == FINAL || it == FINAL_EXT }
}
private fun isTopLevelInAnnotationOrTypeComment(node: PyExpression): Boolean {
val parent = node.parent
if (parent is PyAnnotation) return true
if (parent is PyExpressionStatement && parent.parent is PyTypeHintFile) return true
if (parent is PyParameterTypeList) return true
if (parent is PyFunctionTypeAnnotation) return true
return false
}
}
}
| apache-2.0 | dd49a4d15844646e258f76c7831e89f0 | 44.114558 | 141 | 0.686082 | 4.759063 | false | false | false | false |
dpisarenko/econsim-tr01 | src/main/java/cc/altruix/econsimtr01/CmdLineParametersValidator.kt | 1 | 2913 | /*
* Copyright 2012-2016 Dmitri Pisarenko
*
* WWW: http://altruix.cc
* E-Mail: [email protected]
* Skype: dp118m (voice calls must be scheduled in advance)
*
* Physical address:
*
* 4-i Rostovskii pereulok 2/1/20
* 119121 Moscow
* Russian Federation
*
* This file is part of econsim-tr01.
*
* econsim-tr01 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.
*
* econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cc.altruix.econsimtr01
import cc.altruix.econsimtr01.ch03.ICmdLineParametersValidator
import cc.altruix.econsimtr01.ch03.PropertiesFileSimParametersProvider
import cc.altruix.econsimtr01.ch03.ValidationResult
import java.io.File
/**
* @author Dmitri Pisarenko ([email protected])
* @version $Id$
* @since 1.0
*/
abstract class CmdLineParametersValidator(val usageStatement:String) :
ICmdLineParametersValidator {
override var simParamProviders =
emptyList<PropertiesFileSimParametersProvider>()
override fun validate(args: Array<String>): ValidationResult {
if (args.isEmpty()) {
return ValidationResult(
valid = false,
message = usageStatement
)
}
val files = args.map { createFile(it) }
val unreadableFile = files.filter { !canRead(it) }.firstOrNull()
if (unreadableFile != null) {
return ValidationResult(
valid = false,
message = "Can't read file '${unreadableFile.name}'"
)
}
simParamProviders = files.map { createSimParametersProvider(it) }
simParamProviders.forEach { it.initAndValidate() }
val invalidParamProvider = simParamProviders
.filter { !it.validity.valid }
.firstOrNull()
if (invalidParamProvider != null) {
return ValidationResult(
valid = false,
message = "File '${invalidParamProvider.file.name}' is invalid ('${invalidParamProvider.validity.message}')"
)
}
return ValidationResult(true, "")
}
internal open fun createFile(name:String): File = File(name)
internal open fun canRead(file: File) : Boolean = file.canRead()
abstract fun createSimParametersProvider(file: File) :
PropertiesFileSimParametersProvider
}
| gpl-3.0 | 11fc274b4c984dc2d818d9b941fda515 | 33.962963 | 124 | 0.652249 | 4.516279 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeRenderers.kt | 1 | 4863 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.highlighter
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.diagnostics.rendering.*
import org.jetbrains.kotlin.idea.KotlinIdeaAnalysisBundle
import org.jetbrains.kotlin.idea.highlighter.renderersUtil.renderResolvedCall
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.renderer.DescriptorRendererModifier
import org.jetbrains.kotlin.resolve.MemberComparator
import org.jetbrains.kotlin.resolve.calls.inference.InferenceErrorData
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ConflictingJvmDeclarationsData
object IdeRenderers {
@JvmField
val HTML_AMBIGUOUS_CALLS = Renderer { calls: Collection<ResolvedCall<*>> ->
renderAmbiguousDescriptors(calls.map { it.resultingDescriptor })
}
@JvmField
val HTML_COMPATIBILITY_CANDIDATE = Renderer { call: CallableDescriptor ->
renderAmbiguousDescriptors(listOf(call))
}
@JvmField
val HTML_AMBIGUOUS_REFERENCES = Renderer { descriptors: Collection<CallableDescriptor> ->
renderAmbiguousDescriptors(descriptors)
}
private fun renderAmbiguousDescriptors(descriptors: Collection<CallableDescriptor>): String {
val sortedDescriptors = descriptors.sortedWith(MemberComparator.INSTANCE)
val context = RenderingContext.Impl(sortedDescriptors)
return sortedDescriptors.joinToString("") { "<li>${HTML.render(it, context)}</li>" }
}
@JvmField
val HTML_RENDER_TYPE = SmartTypeRenderer(DescriptorRenderer.HTML.withOptions {
parameterNamesInFunctionalTypes = false
modifiers = DescriptorRendererModifier.ALL_EXCEPT_ANNOTATIONS
})
@JvmField
val HTML_NONE_APPLICABLE_CALLS = Renderer { calls: Collection<ResolvedCall<*>> ->
val context = RenderingContext.Impl(calls.map { it.resultingDescriptor })
val comparator = compareBy(MemberComparator.INSTANCE) { c: ResolvedCall<*> -> c.resultingDescriptor }
calls
.sortedWith(comparator)
.joinToString("") { "<li>${renderResolvedCall(it, context)}</li>" }
}
@JvmField
val HTML_TYPE_INFERENCE_CONFLICTING_SUBSTITUTIONS_RENDERER = Renderer<InferenceErrorData> {
Renderers.renderConflictingSubstitutionsInferenceError(it, HtmlTabledDescriptorRenderer.create()).toString()
}
@JvmField
val HTML_TYPE_INFERENCE_PARAMETER_CONSTRAINT_ERROR_RENDERER = Renderer<InferenceErrorData> {
Renderers.renderParameterConstraintError(it, HtmlTabledDescriptorRenderer.create()).toString()
}
@JvmField
val HTML_TYPE_INFERENCE_NO_INFORMATION_FOR_PARAMETER_RENDERER = Renderer<InferenceErrorData> {
Renderers.renderNoInformationForParameterError(it, HtmlTabledDescriptorRenderer.create()).toString()
}
@JvmField
val HTML_TYPE_INFERENCE_UPPER_BOUND_VIOLATED_RENDERER = Renderer<InferenceErrorData> {
Renderers.renderUpperBoundViolatedInferenceError(it, HtmlTabledDescriptorRenderer.create()).toString()
}
@JvmField
val HTML_RENDER_RETURN_TYPE = ContextDependentRenderer<CallableMemberDescriptor> { member, context ->
HTML_RENDER_TYPE.render(member.returnType!!, context)
}
@JvmField
val HTML_CONFLICTING_JVM_DECLARATIONS_DATA = Renderer { data: ConflictingJvmDeclarationsData ->
val descriptors = data.signatureOrigins
.mapNotNull { it.descriptor }
.sortedWith(MemberComparator.INSTANCE)
val context = RenderingContext.of(descriptors)
val conflicts = descriptors.joinToString("") { "<li>" + HTML.render(it, context) + "</li>\n" }
KotlinIdeaAnalysisBundle.message(
"the.following.declarations.have.the.same.jvm.signature.code.0.1.code.br.ul.2.ul",
data.signature.name,
data.signature.desc,
conflicts
)
}
@JvmField
val HTML_THROWABLE = Renderer<Throwable> { throwable ->
if (throwable.message != null) {
"${throwable::class.java.simpleName}: ${throwable.message}"
} else {
"<pre>${CommonRenderers.THROWABLE.render(throwable)}</pre>"
}.replace("\n", "<br/>")
}
@JvmField
val HTML = DescriptorRenderer.HTML.withOptions {
modifiers = DescriptorRendererModifier.ALL_EXCEPT_ANNOTATIONS
}.asRenderer()
@JvmField
val HTML_WITH_ANNOTATIONS = DescriptorRenderer.HTML.withOptions {
modifiers = DescriptorRendererModifier.ALL
}.asRenderer()
@JvmField
val HTML_WITH_ANNOTATIONS_WHITELIST = DescriptorRenderer.HTML.withAnnotationsWhitelist()
}
| apache-2.0 | 61a98b4175091a0308a0ef7f9ae6cb66 | 40.211864 | 120 | 0.727534 | 4.730545 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/voice/VoiceNotePlayer.kt | 1 | 2185 | package org.thoughtcrime.securesms.components.voice
import android.content.Context
import com.google.android.exoplayer2.C
import com.google.android.exoplayer2.DefaultLoadControl
import com.google.android.exoplayer2.DefaultRenderersFactory
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.ForwardingPlayer
import com.google.android.exoplayer2.audio.AudioAttributes
import com.google.android.exoplayer2.audio.AudioSink
import org.thoughtcrime.securesms.video.exo.SignalMediaSourceFactory
class VoiceNotePlayer @JvmOverloads constructor(
context: Context,
val internalPlayer: ExoPlayer = ExoPlayer.Builder(context)
.setRenderersFactory(WorkaroundRenderersFactory(context))
.setMediaSourceFactory(SignalMediaSourceFactory(context))
.setLoadControl(
DefaultLoadControl.Builder()
.setBufferDurationsMs(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE)
.build()
).build().apply {
setAudioAttributes(AudioAttributes.Builder().setContentType(C.AUDIO_CONTENT_TYPE_MUSIC).setUsage(C.USAGE_MEDIA).build(), true)
}
) : ForwardingPlayer(internalPlayer) {
override fun seekTo(windowIndex: Int, positionMs: Long) {
super.seekTo(windowIndex, positionMs)
val isQueueToneIndex = windowIndex % 2 == 1
val isSeekingToStart = positionMs == C.TIME_UNSET
return if (isQueueToneIndex && isSeekingToStart) {
val nextVoiceNoteWindowIndex = if (currentWindowIndex < windowIndex) windowIndex + 1 else windowIndex - 1
if (mediaItemCount <= nextVoiceNoteWindowIndex) {
super.seekTo(windowIndex, positionMs)
} else {
super.seekTo(nextVoiceNoteWindowIndex, positionMs)
}
} else {
super.seekTo(windowIndex, positionMs)
}
}
}
/**
* @see RetryableInitAudioSink
*/
class WorkaroundRenderersFactory(val context: Context) : DefaultRenderersFactory(context) {
override fun buildAudioSink(context: Context, enableFloatOutput: Boolean, enableAudioTrackPlaybackParams: Boolean, enableOffload: Boolean): AudioSink? {
return RetryableInitAudioSink(context, enableFloatOutput, enableAudioTrackPlaybackParams, enableOffload)
}
}
| gpl-3.0 | 6edf777ea78c334b220a8612b5c8774d | 40.226415 | 154 | 0.776201 | 4.234496 | false | false | false | false |
androidx/androidx | compose/ui/ui-tooling/src/jvmMain/kotlin/androidx/compose/ui/tooling/ComposableInvoker.kt | 3 | 8295 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.tooling
import androidx.compose.runtime.Composer
import androidx.compose.ui.ExperimentalComposeUiApi
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import kotlin.math.ceil
/**
* A utility object to invoke composable function by its name and containing class.
*/
@Deprecated("Use androidx.compose.runtime.reflect.ComposableMethodInvoker instead")
@ExperimentalComposeUiApi
object ComposableInvoker {
/**
* Returns true if the [methodTypes] and [actualTypes] are compatible. This means that every
* `actualTypes[n]` are assignable to `methodTypes[n]`.
*/
private fun compatibleTypes(
methodTypes: Array<Class<*>>,
actualTypes: Array<Class<*>>
): Boolean =
methodTypes.size == actualTypes.size &&
methodTypes.mapIndexed { index, clazz -> clazz.isAssignableFrom(actualTypes[index]) }
.all { it }
/**
* Same as [Class#getDeclaredMethod] but it accounts for compatible types so the signature does
* not need to exactly match. This allows finding method calls that use subclasses as parameters
* instead of the exact types.
*/
private fun Class<*>.getDeclaredCompatibleMethod(
methodName: String,
vararg args: Class<*>
): Method {
val actualTypes: Array<Class<*>> = arrayOf(*args)
return declaredMethods.firstOrNull {
// Methods with inlined classes as parameter will have the name mangled
// so we need to check for methodName-xxxx as well
(methodName == it.name || it.name.startsWith("$methodName-")) &&
compatibleTypes(it.parameterTypes, actualTypes)
} ?: throw NoSuchMethodException("$methodName not found")
}
private inline fun <reified T> T.dup(count: Int): Array<T> {
return (0 until count).map { this }.toTypedArray()
}
/**
* Find the given method by name. If the method has parameters, this function will try to find
* the version that accepts default parameters.
*/
private fun Class<*>.findComposableMethod(methodName: String, vararg args: Any?): Method {
val method = try {
// without defaults
val changedParams = changedParamCount(args.size, 0)
getDeclaredCompatibleMethod(
methodName,
*args.mapNotNull { it?.javaClass }.toTypedArray(),
Composer::class.java, // composer param
*kotlin.Int::class.java.dup(changedParams) // changed param
)
} catch (e: ReflectiveOperationException) {
try {
declaredMethods.find {
it.name == methodName ||
// Methods with inlined classes as parameter will have the name mangled
// so we need to check for methodName-xxxx as well
it.name.startsWith("$methodName-")
}
} catch (e: ReflectiveOperationException) {
null
}
} ?: throw NoSuchMethodException("$name.$methodName")
return method
}
/**
* Returns the default value for the [Class] type. This will be 0 for numeric types, false for
* boolean, '0' for char and null for object references.
*/
private fun Class<*>.getDefaultValue(): Any? = when (name) {
"int" -> 0.toInt()
"short" -> 0.toShort()
"byte" -> 0.toByte()
"long" -> 0.toLong()
"double" -> 0.toDouble()
"float" -> 0.toFloat()
"boolean" -> false
"char" -> 0.toChar()
else -> null
}
/**
* Calls the method on the given [instance]. If the method accepts default values, this function
* will call it with the correct options set.
*/
@Suppress("BanUncheckedReflection")
private fun Method.invokeComposableMethod(
instance: Any?,
composer: Composer,
vararg args: Any?
): Any? {
val composerIndex = parameterTypes.indexOfLast { it == Composer::class.java }
val realParams = composerIndex
val thisParams = if (instance != null) 1 else 0
val changedParams = changedParamCount(realParams, thisParams)
val totalParamsWithoutDefaults = realParams +
1 + // composer
changedParams
val totalParams = parameterTypes.size
val isDefault = totalParams != totalParamsWithoutDefaults
val defaultParams = if (isDefault)
defaultParamCount(realParams)
else
0
check(
realParams +
1 + // composer
changedParams +
defaultParams ==
totalParams
)
val changedStartIndex = composerIndex + 1
val defaultStartIndex = changedStartIndex + changedParams
val arguments = Array(totalParams) { idx ->
when (idx) {
// pass in "empty" value for all real parameters since we will be using defaults.
in 0 until realParams -> args.getOrElse(idx) {
parameterTypes[idx].getDefaultValue()
}
// the composer is the first synthetic parameter
composerIndex -> composer
// since this is the root we don't need to be anything unique. 0 should suffice.
// changed parameters should be 0 to indicate "uncertain"
in changedStartIndex until defaultStartIndex -> 0
// Default values mask, all parameters set to use defaults
in defaultStartIndex until totalParams -> 0b111111111111111111111.toInt()
else -> error("Unexpected index")
}
}
return invoke(instance, *arguments)
}
private const val SLOTS_PER_INT = 10
private const val BITS_PER_INT = 31
private fun changedParamCount(realValueParams: Int, thisParams: Int): Int {
if (realValueParams == 0) return 1
val totalParams = realValueParams + thisParams
return ceil(
totalParams.toDouble() / SLOTS_PER_INT.toDouble()
).toInt()
}
private fun defaultParamCount(realValueParams: Int): Int {
return ceil(
realValueParams.toDouble() / BITS_PER_INT.toDouble()
).toInt()
}
/**
* Invokes the given [methodName] belonging to the given [className]. The [methodName] is
* expected to be a Composable function.
* This method [args] will be forwarded to the Composable function.
*/
@ExperimentalComposeUiApi
fun invokeComposable(
className: String,
methodName: String,
composer: Composer,
vararg args: Any?
) {
try {
val composableClass = Class.forName(className)
val method = composableClass.findComposableMethod(methodName, *args)
method.isAccessible = true
if (Modifier.isStatic(method.modifiers)) {
// This is a top level or static method
method.invokeComposableMethod(null, composer, *args)
} else {
// The method is part of a class. We try to instantiate the class with an empty
// constructor.
val instance = composableClass.getConstructor().newInstance()
method.invokeComposableMethod(instance, composer, *args)
}
} catch (e: ReflectiveOperationException) {
PreviewLogger.logWarning(
"Failed to invoke Composable Method '$className.$methodName'"
)
throw e
}
}
}
| apache-2.0 | 32ba728df9cd9c893b76d306c8a98681 | 37.225806 | 100 | 0.610368 | 4.967066 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/findJavaPropertyUsages/javaPropertyUsagesK.0.kt | 5 | 384 | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtProperty
// OPTIONS: usages
open class A {
open var <caret>p: Int = 1
}
class AA : A() {
override var p: Int = 1
}
class B : J() {
override var p: Int = 1
}
fun test() {
val t = A().p
A().p = 1
val t2 = AA().p
AA().p = 1
val t3 = J().p
J().p = 1
val t4 = B().p
B().p = 1
}
// FIR_COMPARISON | apache-2.0 | bc71a325662b03123e89c6e1b31d80fa | 12.275862 | 51 | 0.492188 | 2.704225 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ide/minimap/actions/OpenMinimapSettingsAction.kt | 2 | 1104 | // 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.ide.minimap.actions
import com.intellij.ide.actions.ShowSettingsUtilImpl
import com.intellij.ide.minimap.settings.MinimapConfigurable
import com.intellij.ide.minimap.utils.MiniMessagesBundle
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.options.ex.ConfigurableVisitor
import com.intellij.openapi.options.newEditor.SettingsDialogFactory
class OpenMinimapSettingsAction : AnAction(MiniMessagesBundle.message("action.settings")) {
override fun isDumbAware() = true
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val groups = ShowSettingsUtilImpl.getConfigurableGroups(project, true).filter { it.configurables.isNotEmpty() }
val configurable = ConfigurableVisitor.findById(MinimapConfigurable.ID, groups)
val dialog = SettingsDialogFactory.getInstance().create(project, groups, configurable, null)
dialog.show()
}
} | apache-2.0 | c9c2867bc4f3a6b223006bbcc866ebee | 51.619048 | 120 | 0.814312 | 4.506122 | false | true | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/actions/GitAbortOperationAction.kt | 8 | 4843 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.actions
import com.intellij.CommonBundle
import com.intellij.dvcs.DvcsUtil
import com.intellij.dvcs.repo.Repository
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.runBackgroundableTask
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vcs.update.RefreshVFsSynchronously
import git4idea.DialogManager
import git4idea.GitNotificationIdsHolder.Companion.CHERRY_PICK_ABORT_FAILED
import git4idea.GitNotificationIdsHolder.Companion.CHERRY_PICK_ABORT_SUCCESS
import git4idea.GitNotificationIdsHolder.Companion.MERGE_ABORT_FAILED
import git4idea.GitNotificationIdsHolder.Companion.MERGE_ABORT_SUCCESS
import git4idea.GitNotificationIdsHolder.Companion.REVERT_ABORT_FAILED
import git4idea.GitNotificationIdsHolder.Companion.REVERT_ABORT_SUCCESS
import git4idea.GitUtil
import git4idea.changes.GitChangeUtils
import git4idea.commands.Git
import git4idea.commands.GitCommand
import git4idea.commands.GitLineHandler
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepository
import git4idea.util.GitFreezingProcess
import org.jetbrains.annotations.Nls
internal abstract class GitAbortOperationAction(repositoryState: Repository.State,
final override val operationName: @Nls String,
private val gitCommand: GitCommand)
: GitOperationActionBase(repositoryState) {
private val operationNameCapitalised = StringUtil.capitalizeWords(operationName, true)
protected abstract val notificationSuccessDisplayId: String
protected abstract val notificationErrorDisplayId: String
class Merge : GitAbortOperationAction(Repository.State.MERGING, GitBundle.message("abort.operation.merge.name"), GitCommand.MERGE) {
override val notificationSuccessDisplayId = MERGE_ABORT_SUCCESS
override val notificationErrorDisplayId = MERGE_ABORT_FAILED
}
class CherryPick : GitAbortOperationAction(Repository.State.GRAFTING, GitBundle.message("abort.operation.cherry.pick.name"), GitCommand.CHERRY_PICK) {
override val notificationSuccessDisplayId = CHERRY_PICK_ABORT_SUCCESS
override val notificationErrorDisplayId = CHERRY_PICK_ABORT_FAILED
}
class Revert : GitAbortOperationAction(Repository.State.REVERTING, GitBundle.message("abort.operation.revert.name"), GitCommand.REVERT) {
override val notificationSuccessDisplayId = REVERT_ABORT_SUCCESS
override val notificationErrorDisplayId = REVERT_ABORT_FAILED
}
override fun performInBackground(repository: GitRepository): Boolean {
if (!confirmAbort(repository)) return false
runBackgroundableTask(GitBundle.message("abort.operation.progress.title", operationNameCapitalised), repository.project) { indicator ->
doAbort(repository, indicator)
}
return true
}
private fun confirmAbort(repository: GitRepository): Boolean {
val title = GitBundle.message("abort.operation.dialog.title", operationNameCapitalised)
val message = GitBundle.message("abort.operation.dialog.msg", operationName, GitUtil.mention(repository))
return DialogManager.showOkCancelDialog(repository.project, message, title, GitBundle.message("abort"), CommonBundle.getCancelButtonText(),
Messages.getQuestionIcon()) == Messages.OK
}
private fun doAbort(repository: GitRepository, indicator: ProgressIndicator) {
val project = repository.project
GitFreezingProcess(project, GitBundle.message("abort")) {
DvcsUtil.workingTreeChangeStarted(project, GitBundle.message("abort")).use {
indicator.text2 = GitBundle.message("abort.operation.indicator.text", gitCommand.name(), GitUtil.mention(repository))
val startHash = GitUtil.getHead(repository)
val stagedChanges = GitChangeUtils.getStagedChanges(project, repository.root)
val handler = GitLineHandler(project, repository.root, gitCommand)
handler.addParameters("--abort")
val result = Git.getInstance().runCommand(handler)
if (!result.success()) {
VcsNotifier.getInstance(project).notifyError(notificationErrorDisplayId, GitBundle.message("abort.operation.failed", operationNameCapitalised), result.errorOutputAsHtmlString, true)
}
else {
VcsNotifier.getInstance(project).notifySuccess(notificationSuccessDisplayId, "", GitBundle.message("abort.operation.succeeded", operationNameCapitalised))
GitUtil.updateAndRefreshChangedVfs(repository, startHash)
RefreshVFsSynchronously.refresh(stagedChanges, true)
}
}
}.execute()
}
}
| apache-2.0 | b3f78f9dc6769fe28b254fe0e7ff9529 | 49.447917 | 191 | 0.777824 | 4.752699 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/InnerClassConversion.kt | 2 | 1817 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.nj2k.conversions
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.RecursiveApplicableConversionBase
import org.jetbrains.kotlin.nj2k.isLocalClass
import org.jetbrains.kotlin.nj2k.tree.JKClass
import org.jetbrains.kotlin.nj2k.tree.JKClass.ClassKind.*
import org.jetbrains.kotlin.nj2k.tree.JKOtherModifierElement
import org.jetbrains.kotlin.nj2k.tree.JKTreeElement
import org.jetbrains.kotlin.nj2k.tree.OtherModifier.INNER
import org.jetbrains.kotlin.nj2k.tree.OtherModifier.STATIC
import org.jetbrains.kotlin.nj2k.tree.elementByModifier
class InnerClassConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement =
if (element is JKClass) recurseArmed(element, outerClass = element) else recurse(element)
private fun recurseArmed(element: JKTreeElement, outerClass: JKClass): JKTreeElement =
applyRecursive(element, outerClass) { elem, outer -> elem.applyArmed(outer) }
private fun JKTreeElement.applyArmed(outerClass: JKClass): JKTreeElement {
if (this !is JKClass || classKind == COMPANION || isLocalClass()) return recurseArmed(this, outerClass)
val static = elementByModifier(STATIC)
when {
static != null ->
otherModifierElements -= static
outerClass.classKind != INTERFACE && classKind != INTERFACE && classKind != ENUM && classKind != RECORD ->
otherModifierElements += JKOtherModifierElement(INNER)
}
return recurseArmed(this, outerClass = this)
}
}
| apache-2.0 | ec398fc7ebe70dcd7945ba148d1f76b1 | 50.914286 | 158 | 0.757292 | 4.357314 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/gradle/hmppImportAndHighlighting/multiModulesHmpp/api-jvm/src/main/kotlin/transitiveStory/apiJvm/beginning/KotlinApiContainer.kt | 10 | 1242 | package transitiveStory.apiJvm.beginning
import playground.moduleName
open class <!LINE_MARKER("descr='Is subclassed by Jvm18KApiInheritor Click or press ... to navigate'")!>KotlinApiContainer<!> {
private val privateKotlinDeclaration = "I'm a private Kotlin string from `" + moduleName +
"` and shall be never visible to the others."
internal val packageVisibleKotlinDeclaration = "I'm a package visible Kotlin string from `" + moduleName +
"` and shall be never visible to the other modules."
protected open val <!LINE_MARKER("descr='Is overridden in transitiveStory.bottomActual.apiCall.Jvm18KApiInheritor'")!>protectedKotlinDeclaration<!> = "I'm a protected Kotlin string from `" + moduleName +
"` and shall be never visible to the other modules except my subclasses."
val publicKotlinDeclaration = "I'm a public Kotlin string from `" + moduleName +
"` and shall be visible to the other modules."
companion object {
val publicStaticKotlinDeclaration = "I'm a public Kotlin static string from `" + moduleName +
"` and shall be visible to the other modules even without instantiation of `JavaApiContainer` class."
}
}
val tlAPIval = 42
| apache-2.0 | 4d7203f52ba7ff45e2111ed48608db10 | 50.75 | 207 | 0.70934 | 4.987952 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/http/ClientCertKeyManager.kt | 1 | 1822 | package ch.rmy.android.http_shortcuts.http
import android.content.Context
import android.security.KeyChain
import java.net.Socket
import java.security.Principal
import java.security.PrivateKey
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import javax.net.ssl.X509KeyManager
class ClientCertKeyManager(
private val alias: String,
private val certChain: Array<X509Certificate>,
private val privateKey: PrivateKey,
) : X509KeyManager {
override fun chooseClientAlias(keyType: Array<String>, issuers: Array<Principal>?, socket: Socket?) =
alias
override fun getCertificateChain(alias: String): Array<X509Certificate>? =
if (alias == this.alias) certChain else null
override fun getPrivateKey(alias: String): PrivateKey? =
if (alias == this.alias) privateKey else null
override fun chooseServerAlias(keyType: String, issuers: Array<Principal>?, socket: Socket?): String {
throw UnsupportedOperationException()
}
override fun getClientAliases(keyType: String, issuers: Array<Principal>?): Array<String> {
throw UnsupportedOperationException()
}
override fun getServerAliases(keyType: String, issuers: Array<Principal>?): Array<String> {
throw UnsupportedOperationException()
}
companion object {
fun getClientCertKeyManager(context: Context, alias: String): ClientCertKeyManager {
val certChain = KeyChain.getCertificateChain(context, alias)
val privateKey = KeyChain.getPrivateKey(context, alias)
if (certChain == null || privateKey == null) {
throw CertificateException("Can't access certificate from keystore")
}
return ClientCertKeyManager(alias, certChain, privateKey)
}
}
}
| mit | 4fb27f350779c8bbc0182ce732cd7bb8 | 36.958333 | 106 | 0.717892 | 4.60101 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | platform/configuration-store-impl/src/ProjectStoreImpl.kt | 1 | 15823 | /*
* Copyright 2000-2015 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.configurationStore
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.ide.highlighter.WorkspaceFileType
import com.intellij.notification.Notifications
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeAndWaitIfNeed
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.*
import com.intellij.openapi.components.StateStorage.SaveSession
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.components.impl.stores.IProjectStore
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectCoreUtil
import com.intellij.openapi.project.ex.ProjectNameProvider
import com.intellij.openapi.project.impl.ProjectImpl
import com.intellij.openapi.project.impl.ProjectManagerImpl.UnableToSaveProjectNotification
import com.intellij.openapi.project.impl.ProjectStoreClassProvider
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.ReadonlyStatusHandler
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PathUtilRt
import com.intellij.util.SmartList
import com.intellij.util.containers.computeIfAny
import com.intellij.util.containers.isNullOrEmpty
import com.intellij.util.io.*
import com.intellij.util.lang.CompoundRuntimeException
import com.intellij.util.text.nullize
import java.io.File
import java.io.IOException
import java.nio.file.Path
import java.nio.file.Paths
const val PROJECT_FILE = "\$PROJECT_FILE$"
const val PROJECT_CONFIG_DIR = "\$PROJECT_CONFIG_DIR$"
val IProjectStore.nameFile: Path
get() = Paths.get(directoryStorePath, ProjectImpl.NAME_FILE)
internal val PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, false)
internal val DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, true)
abstract class ProjectStoreBase(override final val project: ProjectImpl) : ComponentStoreImpl(), IProjectStore {
// protected setter used in upsource
// Zelix KlassMaster - ERROR: Could not find method 'getScheme()'
var scheme = StorageScheme.DEFAULT
override final var loadPolicy = StateLoadPolicy.LOAD
override final fun isOptimiseTestLoadSpeed() = loadPolicy != StateLoadPolicy.LOAD
override final fun getStorageScheme() = scheme
override abstract val storageManager: StateStorageManagerImpl
protected val isDirectoryBased: Boolean
get() = scheme == StorageScheme.DIRECTORY_BASED
override final fun setOptimiseTestLoadSpeed(value: Boolean) {
// we don't load default state in tests as app store does because
// 1) we should not do it
// 2) it was so before, so, we preserve old behavior (otherwise RunManager will load template run configurations)
loadPolicy = if (value) StateLoadPolicy.NOT_LOAD else StateLoadPolicy.LOAD
}
override fun getProjectFilePath() = storageManager.expandMacro(PROJECT_FILE)
override final fun getWorkspaceFilePath() = storageManager.expandMacro(StoragePathMacros.WORKSPACE_FILE)
override final fun clearStorages() {
storageManager.clearStorages()
}
override final fun loadProjectFromTemplate(defaultProject: Project) {
defaultProject.save()
val element = (defaultProject.stateStore as DefaultProjectStoreImpl).getStateCopy() ?: return
LOG.runAndLogException {
if (isDirectoryBased) {
normalizeDefaultProjectElement(defaultProject, element, Paths.get(storageManager.expandMacro(PROJECT_CONFIG_DIR)))
}
else {
LOG.runAndLogException {
moveComponentConfiguration(defaultProject, element) { if (it == "workspace.xml") Paths.get(workspaceFilePath) else Paths.get(projectFilePath) }
}
}
}
(storageManager.getOrCreateStorage(PROJECT_FILE) as XmlElementStorage).setDefaultState(element)
}
override final fun getProjectBasePath(): String {
if (isDirectoryBased) {
val path = PathUtilRt.getParentPath(storageManager.expandMacro(PROJECT_CONFIG_DIR))
if (Registry.`is`("store.basedir.parent.detection", true) && PathUtilRt.getFileName(path).startsWith("${Project.DIRECTORY_STORE_FOLDER}.")) {
return PathUtilRt.getParentPath(PathUtilRt.getParentPath(path))
}
return path
}
else {
return PathUtilRt.getParentPath(projectFilePath)
}
}
// used in upsource
protected fun setPath(filePath: String, refreshVfs: Boolean, useOldWorkspaceContentIfExists: Boolean) {
val storageManager = storageManager
val fs = LocalFileSystem.getInstance()
if (filePath.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)) {
scheme = StorageScheme.DEFAULT
storageManager.addMacro(PROJECT_FILE, filePath)
val workspacePath = composeWsPath(filePath)
storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, workspacePath)
if (refreshVfs) {
invokeAndWaitIfNeed {
VfsUtil.markDirtyAndRefresh(false, true, false, fs.refreshAndFindFileByPath(filePath), fs.refreshAndFindFileByPath(workspacePath))
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
// load state only if there are existing files
isOptimiseTestLoadSpeed = !File(filePath).exists()
}
}
else {
scheme = StorageScheme.DIRECTORY_BASED
// if useOldWorkspaceContentIfExists false, so, file path is expected to be correct (we must avoid file io operations)
val isDir = !useOldWorkspaceContentIfExists || Paths.get(filePath).isDirectory()
val configDir = "${(if (isDir) filePath else PathUtilRt.getParentPath(filePath))}/${Project.DIRECTORY_STORE_FOLDER}"
storageManager.addMacro(PROJECT_CONFIG_DIR, configDir)
storageManager.addMacro(PROJECT_FILE, "$configDir/misc.xml")
storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, "$configDir/workspace.xml")
if (!isDir) {
val workspace = File(workspaceFilePath)
if (!workspace.exists()) {
useOldWorkspaceContent(filePath, workspace)
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
// load state only if there are existing files
isOptimiseTestLoadSpeed = !Paths.get(filePath).exists()
}
if (refreshVfs) {
invokeAndWaitIfNeed { VfsUtil.markDirtyAndRefresh(false, true, true, fs.refreshAndFindFileByPath(configDir)) }
}
}
}
override fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): List<Storage> {
val storages = stateSpec.storages
if (storages.isEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
if (isDirectoryBased) {
var result: MutableList<Storage>? = null
for (storage in storages) {
if (storage.path != PROJECT_FILE) {
if (result == null) {
result = SmartList()
}
result.add(storage)
}
}
if (result.isNullOrEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
else {
result!!.sortWith(deprecatedComparator)
StreamProviderFactory.EP_NAME.getExtensions(project).computeIfAny {
LOG.runAndLogException { it.customizeStorageSpecs(component, project, stateSpec, result!!, operation) }
}?.let {
// yes, DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION is not added in this case
return it
}
// if we create project from default, component state written not to own storage file, but to project file,
// we don't have time to fix it properly, so, ancient hack restored
result.add(DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION)
return result
}
}
else {
var result: MutableList<Storage>? = null
// FlexIdeProjectLevelCompilerOptionsHolder, FlexProjectLevelCompilerOptionsHolderImpl and CustomBeanRegistry
var hasOnlyDeprecatedStorages = true
for (storage in storages) {
@Suppress("DEPRECATION")
if (storage.path == PROJECT_FILE || storage.path == StoragePathMacros.WORKSPACE_FILE) {
if (result == null) {
result = SmartList()
}
result.add(storage)
if (!storage.deprecated) {
hasOnlyDeprecatedStorages = false
}
}
}
if (result.isNullOrEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
else {
if (hasOnlyDeprecatedStorages) {
result!!.add(PROJECT_FILE_STORAGE_ANNOTATION)
}
result!!.sortWith(deprecatedComparator)
return result
}
}
}
override fun isProjectFile(file: VirtualFile): Boolean {
if (!file.isInLocalFileSystem || !ProjectCoreUtil.isProjectOrWorkspaceFile(file)) {
return false
}
val filePath = file.path
if (!isDirectoryBased) {
return filePath == projectFilePath || filePath == workspaceFilePath
}
return FileUtil.isAncestor(PathUtilRt.getParentPath(projectFilePath), filePath, false)
}
override fun getDirectoryStorePath(ignoreProjectStorageScheme: Boolean) = if (!ignoreProjectStorageScheme && !isDirectoryBased) null else PathUtilRt.getParentPath(projectFilePath).nullize()
override fun getDirectoryStoreFile() = directoryStorePath?.let { LocalFileSystem.getInstance().findFileByPath(it) }
override fun getDirectoryStorePathOrBase() = PathUtilRt.getParentPath(projectFilePath)
}
private open class ProjectStoreImpl(project: ProjectImpl, private val pathMacroManager: PathMacroManager) : ProjectStoreBase(project) {
private var lastSavedProjectName: String? = null
init {
assert(!project.isDefault)
}
override final fun getPathMacroManagerForDefaults() = pathMacroManager
override val storageManager = ProjectStateStorageManager(pathMacroManager.createTrackingSubstitutor(), project)
override fun setPath(filePath: String) {
setPath(filePath, true, true)
}
override fun getProjectName(): String {
if (!isDirectoryBased) {
return PathUtilRt.getFileName(projectFilePath).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION)
}
val baseDir = projectBasePath
val nameFile = nameFile
if (nameFile.exists()) {
LOG.runAndLogException {
nameFile.inputStream().reader().useLines { it.firstOrNull { !it.isEmpty() }?.trim() }?.let {
lastSavedProjectName = it
return it
}
}
}
return ProjectNameProvider.EP_NAME.extensions.computeIfAny {
LOG.runAndLogException { it.getDefaultName(project) }
} ?: PathUtilRt.getFileName(baseDir).replace(":", "")
}
private fun saveProjectName() {
if (!isDirectoryBased) {
return
}
val currentProjectName = project.name
if (lastSavedProjectName == currentProjectName) {
return
}
lastSavedProjectName = currentProjectName
val basePath = projectBasePath
if (currentProjectName == PathUtilRt.getFileName(basePath)) {
// name equals to base path name - just remove name
nameFile.delete()
}
else {
if (Paths.get(basePath).isDirectory()) {
nameFile.write(currentProjectName.toByteArray())
}
}
}
override fun doSave(saveSessions: List<SaveSession>, readonlyFiles: MutableList<Pair<SaveSession, VirtualFile>>, prevErrors: MutableList<Throwable>?): MutableList<Throwable>? {
try {
saveProjectName()
}
catch (e: Throwable) {
LOG.error("Unable to store project name", e)
}
var errors = prevErrors
beforeSave(readonlyFiles)
errors = super.doSave(saveSessions, readonlyFiles, errors)
val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
if (readonlyFiles.isEmpty()) {
for (notification in notifications) {
notification.expire()
}
return errors
}
if (!notifications.isEmpty()) {
throw IComponentStore.SaveCancelledException()
}
val status = runReadAction { ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(*getFilesList(readonlyFiles)) }
if (status.hasReadonlyFiles()) {
dropUnableToSaveProjectNotification(project, status.readonlyFiles)
throw IComponentStore.SaveCancelledException()
}
val oldList = readonlyFiles.toTypedArray()
readonlyFiles.clear()
for (entry in oldList) {
errors = executeSave(entry.first, readonlyFiles, errors)
}
CompoundRuntimeException.throwIfNotEmpty(errors)
if (!readonlyFiles.isEmpty()) {
dropUnableToSaveProjectNotification(project, getFilesList(readonlyFiles))
throw IComponentStore.SaveCancelledException()
}
return errors
}
protected open fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) {
}
}
private fun dropUnableToSaveProjectNotification(project: Project, readOnlyFiles: Array<VirtualFile>) {
val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
if (notifications.isEmpty()) {
Notifications.Bus.notify(UnableToSaveProjectNotification(project, readOnlyFiles), project)
}
else {
notifications[0].myFiles = readOnlyFiles
}
}
private fun getFilesList(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) = Array(readonlyFiles.size) { readonlyFiles[it].second }
private class ProjectWithModulesStoreImpl(project: ProjectImpl, pathMacroManager: PathMacroManager) : ProjectStoreImpl(project, pathMacroManager) {
override fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) {
super.beforeSave(readonlyFiles)
for (module in (ModuleManager.getInstance(project)?.modules ?: Module.EMPTY_ARRAY)) {
module.stateStore.save(readonlyFiles)
}
}
}
// used in upsource
class PlatformLangProjectStoreClassProvider : ProjectStoreClassProvider {
override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> {
return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectWithModulesStoreImpl::class.java
}
}
private class PlatformProjectStoreClassProvider : ProjectStoreClassProvider {
override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> {
return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectStoreImpl::class.java
}
}
private fun composeWsPath(filePath: String) = "${FileUtilRt.getNameWithoutExtension(filePath)}${WorkspaceFileType.DOT_DEFAULT_EXTENSION}"
private fun useOldWorkspaceContent(filePath: String, ws: File) {
val oldWs = File(composeWsPath(filePath))
if (!oldWs.exists()) {
return
}
try {
FileUtil.copyContent(oldWs, ws)
}
catch (e: IOException) {
LOG.error(e)
}
} | apache-2.0 | f7fe3c29736c07da4ceecf4c084e628b | 36.49763 | 191 | 0.735575 | 5.16585 | false | false | false | false |
TachiWeb/TachiWeb-Server | Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/data/sync/protocol/snapshot/SnapshotHelper.kt | 1 | 2902 | package eu.kanade.tachiyomi.data.sync.protocol.snapshot
import android.content.Context
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.io.File
import java.io.FileNotFoundException
/**
* Helper class used to generate and manage snapshots
*/
class SnapshotHelper(private val context: Context,
private val db: DatabaseHelper = Injekt.get()) {
/**
* The file holding a snapshot for objects of [type] and for the
* specified [id]
*/
private fun snapshotFile(type: String, id: String)
= File(context.filesDir, "sync_${type}_$id.snapshot")
/**
* Take all snapshots for the provided device
*/
fun takeSnapshots(id: String) {
//Take snapshots
val categorySnapshots = db.getCategories().executeAsBlocking().map {
CategorySnapshot(it).serialize()
}
val trackSnapshots = db.getTracks().executeAsBlocking().map {
TrackSnapshot(it).serialize()
}
//Write snapshots to disk
writeSnapshot(CATEGORY_SNAPSHOTS, id, categorySnapshots)
writeSnapshot(TRACK_SNAPSHOTS, id, trackSnapshots)
}
/**
* Write a snapshot to disk
*/
private fun writeSnapshot(type: String, id: String, snapshots: List<String>) {
snapshotFile(type, id).writeText(snapshots.joinToString("\n"), CHARSET)
}
/**
* Read the [CategorySnapshot] for the specified device
*/
fun readCategorySnapshots(id: String): List<CategorySnapshot>
= baseReadSnapshots(CATEGORY_SNAPSHOTS, id) {
CategorySnapshot.deserialize(it)
}
/**
* Read the [TrackSnapshot] for the specified device
*/
fun readTrackSnapshots(id: String): List<TrackSnapshot>
= baseReadSnapshots(TRACK_SNAPSHOTS, id) {
TrackSnapshot.deserialize(it)
}
/**
* Read a set of snapshots from disk
*
* @param R The type of snapshots to read
*/
private fun <R> baseReadSnapshots(type: String, id: String, deserializer: (String) -> R): List<R> {
//Read snapshots from disk
return try {
snapshotFile(type, id).useLines(CHARSET) {
it.filterNot(String::isBlank).map(deserializer).toList()
}
} catch(e: FileNotFoundException) {
//No previous snapshot, return empty list
emptyList()
}
}
/**
* Delete the snapshots for a device
*/
fun deleteSnapshots(id: String) {
snapshotFile(CATEGORY_SNAPSHOTS, id).delete()
snapshotFile(TRACK_SNAPSHOTS, id).delete()
}
companion object {
private val CHARSET = Charsets.UTF_8
private const val CATEGORY_SNAPSHOTS = "categories"
private const val TRACK_SNAPSHOTS = "tracks"
}
} | apache-2.0 | 22f5025a851e03960faa004c9a1ccc01 | 30.215054 | 103 | 0.626465 | 4.506211 | false | false | false | false |
Suomaa/androidLearning | LoginApp/app/src/main/java/com/example/loginapp/data/LoginRepository.kt | 1 | 1327 | package com.example.loginapp.data
import com.example.loginapp.data.model.LoggedInUser
/**
* Class that requests authentication and user information from the remote data source and
* maintains an in-memory cache of login status and user credentials information.
*/
class LoginRepository(val dataSource: LoginDataSource) {
// in-memory cache of the loggedInUser object
var user: LoggedInUser? = null
private set
val isLoggedIn: Boolean
get() = user != null
init {
// If user credentials will be cached in local storage, it is recommended it be encrypted
// @see https://developer.android.com/training/articles/keystore
user = null
}
fun logout() {
user = null
dataSource.logout()
}
fun login(username: String, password: String): Result<LoggedInUser> {
// handle login
val result = dataSource.login(username, password)
if (result is Result.Success) {
setLoggedInUser(result.data)
}
return result
}
private fun setLoggedInUser(loggedInUser: LoggedInUser) {
this.user = loggedInUser
// If user credentials will be cached in local storage, it is recommended it be encrypted
// @see https://developer.android.com/training/articles/keystore
}
}
| apache-2.0 | 3968f9500e07ca76a2bbf1fe55414596 | 27.847826 | 97 | 0.667671 | 4.689046 | false | false | false | false |
kerubistan/kerub | src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/mount/UnmountNfsFactory.kt | 2 | 1402 | package com.github.kerubistan.kerub.planner.steps.storage.mount
import com.github.kerubistan.kerub.model.Expectation
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageFsAllocation
import com.github.kerubistan.kerub.model.services.NfsMount
import com.github.kerubistan.kerub.planner.OperationalState
import com.github.kerubistan.kerub.planner.issues.problems.Problem
import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStepFactory
import com.github.kerubistan.kerub.utils.normalizePath
import io.github.kerubistan.kroki.collections.concat
import kotlin.reflect.KClass
object UnmountNfsFactory : AbstractOperationalStepFactory<UnmountNfs>() {
override val problemHints = setOf<KClass<out Problem>>()
override val expectationHints = setOf<KClass<out Expectation>>()
override fun produce(state: OperationalState): List<UnmountNfs> {
return state.hosts.values.mapNotNull { hostColl ->
val storage = state.vmsOnHost(hostColl.stat.id).map { it.virtualStorageLinks }.concat()
.mapNotNull { state.vStorage[it.virtualStorageId] }
hostColl.config?.services?.filterIsInstance<NfsMount>()?.filter {
storage.none {
it.dynamic?.allocations?.any {
it is VirtualStorageFsAllocation && it.hostId != hostColl.stat.id
} ?: false
}
}?.map {
UnmountNfs(host = hostColl.stat, mountDir = it.localDirectory.normalizePath())
}
}.concat()
}
} | apache-2.0 | 64c7c34042de631579bdbffe00878a42 | 40.264706 | 90 | 0.783167 | 3.960452 | false | false | false | false |
npryce/snodge | common/src/main/com/natpryce/snodge/form/Form.kt | 1 | 297 | package com.natpryce.snodge.form
typealias Form = List<Pair<String, String>>
fun form(vararg fields: Pair<String, String>): Form = fields.toList()
operator fun Form.get(key: String): List<String> =
filter { it.first == key }.map { it.second }
val Form.keys get() = map { it.first }.toSet()
| apache-2.0 | 3985d134d7acb1f72f2128c07cd5a876 | 32 | 69 | 0.690236 | 3.228261 | false | false | false | false |
quran/quran_android | app/src/main/java/com/quran/labs/androidquran/model/bookmark/RecentPageModel.kt | 2 | 4636 | package com.quran.labs.androidquran.model.bookmark
import androidx.annotation.UiThread
import com.quran.data.model.bookmark.RecentPage
import com.quran.labs.androidquran.data.Constants
import com.quran.labs.androidquran.database.BookmarksDBAdapter
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.observers.DisposableSingleObserver
import io.reactivex.rxjava3.schedulers.Schedulers
import io.reactivex.rxjava3.subjects.BehaviorSubject
import io.reactivex.rxjava3.subjects.PublishSubject
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
open class RecentPageModel @Inject constructor(
private val bookmarksDBAdapter: BookmarksDBAdapter
) {
private val lastPageSubject = BehaviorSubject.create<Int>()
private val refreshRecentPagePublishSubject = PublishSubject.create<Boolean>().toSerialized()
private val recentWriterSubject = PublishSubject.create<PersistRecentPagesRequest>()
private val recentPagesUpdatedObservable: Observable<Boolean>
private var initialDataSubscription: DisposableSingleObserver<List<RecentPage>>? = null
init {
val recentWritesObservable = recentWriterSubject.hide()
.observeOn(Schedulers.io())
.map { update ->
if (update.deleteRangeStart != null) {
bookmarksDBAdapter.replaceRecentRangeWithPage(
update.deleteRangeStart,
update.deleteRangeEnd!!,
update.page
)
} else {
bookmarksDBAdapter.addRecentPage(update.page)
}
return@map true
}
recentPagesUpdatedObservable = Observable.merge(
recentWritesObservable,
refreshRecentPagePublishSubject.hide()
).share()
// there needs to always be one subscriber in order for us to properly be able
// to write updates to the database (even when no one else is subscribed).
recentPagesUpdatedObservable.subscribe()
// fetch the first set of "recent pages"
initialDataSubscription = this.getRecentPagesObservable()
// this is only to avoid serializing lastPageSubject
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableSingleObserver<List<RecentPage>>() {
override fun onSuccess(recentPages: List<RecentPage>) {
val page = if (recentPages.isNotEmpty()) recentPages[0].page else Constants.NO_PAGE
lastPageSubject.onNext(page)
initialDataSubscription = null
}
override fun onError(e: Throwable) {}
})
}
fun notifyRecentPagesUpdated() {
refreshRecentPagePublishSubject.onNext(true)
}
@UiThread
fun updateLatestPage(page: Int) {
// it is possible (though unlikely) for a page update to come in while we're still waiting
// for the initial query of recent pages from the database. if so, unsubscribe from the initial
// query since its data will be stale relative to this data.
initialDataSubscription?.dispose()
lastPageSubject.onNext(page)
}
@UiThread
fun persistLatestPage(minimumPage: Int, maximumPage: Int, lastPage: Int) {
val min = if (minimumPage == maximumPage) null else minimumPage
val max = if (min == null) null else maximumPage
recentWriterSubject.onNext(
PersistRecentPagesRequest(lastPage, min, max)
)
}
/**
* Returns an observable of the very latest pages visited
*
* Note that this stream never terminates, and will return pages even when they have not yet been
* persisted to the database. This is basically a stream of every page as it gets visited.
*
* @return an Observable of the latest pages visited
*/
fun getLatestPageObservable(): Observable<Int> {
return lastPageSubject.hide()
}
/**
* Returns an observable of observing when recent pages change in the database
*
* Note that this stream never terminates, and will emit onNext when the database has been
* updated. Note that writes to the database are typically batched, and as thus, this observable
* will fire a lot less than [.getLatestPageObservable].
*
* @return an observable that receives events whenever recent pages is persisted
*/
fun getRecentPagesUpdatedObservable(): Observable<Boolean> = recentPagesUpdatedObservable
open fun getRecentPagesObservable(): Single<List<RecentPage>> {
return Single.fromCallable { bookmarksDBAdapter.getRecentPages() }
.subscribeOn(Schedulers.io())
}
private class PersistRecentPagesRequest(
val page: Int,
val deleteRangeStart: Int?,
val deleteRangeEnd: Int?,
)
}
| gpl-3.0 | b6448363245de674ae39fda38bf80163 | 36.691057 | 99 | 0.738783 | 4.626747 | false | false | false | false |
syrop/Wiktor-Navigator | navigator/src/main/kotlin/pl/org/seva/navigator/contact/FriendshipListener.kt | 1 | 3728 | /*
* Copyright (C) 2017 Wiktor Nizio
*
* 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/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.navigator.contact
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import pl.org.seva.navigator.main.data.ParcelableInt
import pl.org.seva.navigator.main.data.appContext
import java.util.Random
import pl.org.seva.navigator.main.data.db.contactDao
import pl.org.seva.navigator.main.data.db.delete
import pl.org.seva.navigator.main.data.db.insert
import pl.org.seva.navigator.main.data.fb.fbWriter
import pl.org.seva.navigator.main.init.instance
import pl.org.seva.navigator.main.data.setShortcuts
val friendshipListener by instance<FriendshipListener>()
class FriendshipListener {
private val nm by lazy {
appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
}
fun onPeerRequestedFriendship(contact: Contact) {
fun NotificationManager.friendshipRequested(contact: Contact, notificationId: ParcelableInt) =
notify(notificationId.value, friendshipRequestedNotification(appContext) {
this.contact = contact
this.nid = notificationId
})
appContext.registerReceiver(FriendshipReceiver(), IntentFilter(FRIENDSHIP_REQUESTED_INTENT))
val notificationId = ParcelableInt(Random().nextInt())
nm.friendshipRequested(contact, notificationId)
}
fun onPeerAcceptedFriendship(contact: Contact) {
contacts add contact
contactDao insert contact
fbWriter addFriendship contact
setShortcuts()
}
fun onPeerDeletedFriendship(contact: Contact) {
contacts delete contact
contactDao delete contact
setShortcuts()
}
private inner class FriendshipReceiver: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
fun Contact.acceptFriend() {
fbWriter acceptFriendship this
if (this in contacts) {
return
}
contacts add this
contactDao insert this
}
val nid = intent.getParcelableExtra<ParcelableInt>(NOTIFICATION_ID).value
nm.cancel(nid)
context.unregisterReceiver(this)
val action = intent.getParcelableExtra<ParcelableInt>(ACTION).value
if (action == ACCEPTED_ACTION) {
intent.getParcelableExtra<Contact>(CONTACT_EXTRA).acceptFriend()
setShortcuts()
}
}
}
companion object {
const val FRIENDSHIP_REQUESTED_INTENT = "friendship_requested_intent"
const val NOTIFICATION_ID = "notification_id"
const val ACTION = "friendship_action"
const val CONTACT_EXTRA = "contact_extra"
const val ACCEPTED_ACTION = 0
const val REJECTED_ACTION = 1
}
}
| gpl-3.0 | f73884a6bf4663de4f68068fc07fd524 | 34.846154 | 102 | 0.694206 | 4.671679 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/bookmark/src/main/java/jp/hazuki/yuzubrowser/bookmark/view/AddBookmarkDialog.kt | 1 | 6263 | /*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.bookmark.view
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.CheckBox
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import jp.hazuki.bookmark.R
import jp.hazuki.yuzubrowser.bookmark.item.BookmarkFolder
import jp.hazuki.yuzubrowser.bookmark.item.BookmarkItem
import jp.hazuki.yuzubrowser.bookmark.repository.BookmarkManager
import jp.hazuki.yuzubrowser.core.eventbus.LocalEventBus
import jp.hazuki.yuzubrowser.ui.BROADCAST_ACTION_NOTIFY_CHANGE_WEB_STATE
import jp.hazuki.yuzubrowser.ui.extensions.toPunyCodeUrl
import jp.hazuki.yuzubrowser.ui.settings.AppPrefs
import jp.hazuki.yuzubrowser.ui.widget.SpinnerButton
abstract class AddBookmarkDialog<S : BookmarkItem, T>(
protected val context: Context,
manager: BookmarkManager?,
protected val mItem: S?,
title: String?,
url: T
) : BookmarkFoldersDialog.OnFolderSelectedListener {
protected val mDialog: AlertDialog
protected val titleEditText: EditText
protected val urlEditText: EditText
protected val folderTextView: TextView
protected val folderButton: SpinnerButton
protected val addToTopCheckBox: CheckBox
protected var mOnClickListener: DialogInterface.OnClickListener? = null
protected val mManager: BookmarkManager = manager ?: BookmarkManager.getInstance(context)
protected lateinit var mParent: BookmarkFolder
init {
val view = inflateView()
titleEditText = view.findViewById(R.id.titleEditText)
urlEditText = view.findViewById(R.id.urlEditText)
folderTextView = view.findViewById(R.id.folderTextView)
folderButton = view.findViewById(R.id.folderButton)
addToTopCheckBox = view.findViewById(R.id.addToTopCheckBox)
initView(view, title, url)
mDialog = AlertDialog.Builder(context)
.setTitle(if (mItem == null) R.string.add_bookmark else R.string.edit_bookmark)
.setView(view)
.setPositiveButton(android.R.string.ok, null)
.setNegativeButton(android.R.string.cancel, null)
.create()
}
protected fun inflateView(): View {
return LayoutInflater.from(context).inflate(R.layout.add_bookmark_dialog, null)
}
protected open fun initView(view: View, title: String?, url: T) {
if (mItem == null) {
val root = getRootPosition()
mParent = root
folderButton.text = root.title
folderButton.setOnClickListener { v ->
BookmarkFoldersDialog(context, mManager)
.setTitle(R.string.folder)
.setCurrentFolder(root)
.setOnFolderSelectedListener(this@AddBookmarkDialog)
.show()
}
} else {
folderTextView.visibility = View.GONE
folderButton.visibility = View.GONE
addToTopCheckBox.visibility = View.GONE
}
}
private fun getRootPosition(): BookmarkFolder {
if (AppPrefs.saveBookmarkFolder.get()) {
val id = AppPrefs.saveBookmarkFolderId.get()
val item = mManager[id]
if (item is BookmarkFolder) {
return item
}
}
return mManager.root
}
fun show() {
mDialog.show()
mDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener { v ->
val title = titleEditText.text
if (TextUtils.isEmpty(title)) {
Toast.makeText(mDialog.context, R.string.title_empty_mes, Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
val url = urlEditText.text
if (TextUtils.isEmpty(url)) {
Toast.makeText(mDialog.context, R.string.url_empty_mes, Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
val item = makeItem(mItem, title.toString(), url.toString().toPunyCodeUrl())
if (item != null) {
if (addToTopCheckBox.isChecked)
mManager.addFirst(mParent, item)
else
mManager.add(mParent, item)
}
if (mItem != null && addToTopCheckBox.isChecked) {
mManager.moveToFirst(mParent, mItem)
}
if (mManager.save()) {
Toast.makeText(mDialog.context, R.string.succeed, Toast.LENGTH_SHORT).show()
mOnClickListener?.onClick(mDialog, DialogInterface.BUTTON_POSITIVE)
LocalEventBus.getDefault().notify(BROADCAST_ACTION_NOTIFY_CHANGE_WEB_STATE)
mDialog.dismiss()
} else {
Toast.makeText(mDialog.context, R.string.failed, Toast.LENGTH_LONG).show()
}
}
}
protected abstract fun makeItem(item: S?, title: String, url: String): S?
fun setOnClickListener(l: DialogInterface.OnClickListener): AddBookmarkDialog<S, T> {
mOnClickListener = l
return this
}
inline fun setOnClickListener(crossinline listener: (DialogInterface, Int) -> Unit): AddBookmarkDialog<S, T> {
setOnClickListener(DialogInterface.OnClickListener { dialog, which -> listener(dialog, which) })
return this
}
override fun onFolderSelected(dialog: DialogInterface, folder: BookmarkFolder): Boolean {
folderButton.text = folder.title
mParent = folder
return false
}
}
| apache-2.0 | c90763291af7f80d385114eb3c22eb25 | 37.660494 | 114 | 0.658311 | 4.680867 | false | false | false | false |
rjhdby/motocitizen | Motocitizen/src/motocitizen/ui/activity/AccidentDetailsActivity.kt | 1 | 6674 | package motocitizen.ui.activity
import android.app.Fragment
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.RadioGroup
import motocitizen.content.Content
import motocitizen.content.accident.Accident
import motocitizen.datasources.network.ApiResponse
import motocitizen.datasources.network.requests.ActivateAccident
import motocitizen.datasources.network.requests.EndAccident
import motocitizen.datasources.network.requests.HideAccident
import motocitizen.dictionary.AccidentStatus
import motocitizen.dictionary.AccidentStatus.ACTIVE
import motocitizen.dictionary.AccidentStatus.ENDED
import motocitizen.main.R
import motocitizen.subscribe.SubscribeManager
import motocitizen.ui.Screens
import motocitizen.ui.fragments.DetailHistoryFragment
import motocitizen.ui.fragments.DetailMessagesFragment
import motocitizen.ui.fragments.DetailVolunteersFragment
import motocitizen.ui.frames.create.DetailsSummaryFrame
import motocitizen.ui.menus.AccidentContextMenu
import motocitizen.ui.menus.DetailsMenuController
import motocitizen.utils.*
class AccidentDetailsActivity : AppCompatActivity() {
companion object {
const val ACCIDENT_ID_KEY = "id"
private const val ROOT_LAYOUT = R.layout.activity_accident_details
private const val GENERAL_INFORMATION_VIEW = R.id.acc_details_general
private const val FRAGMENT_ROOT_VIEW = R.id.details_tab_content
}
enum class Tab(val id: Int) {
MESSAGE_TAB(R.id.details_tab_messages),
HISTORY_TAB(R.id.details_tab_history),
VOLUNTEER_TAB(R.id.details_tab_people);
companion object {
fun byId(id: Int) = values().firstOrNull { it.id == id } ?: VOLUNTEER_TAB
}
fun fragment(accident: Accident): Fragment = when (this) {
MESSAGE_TAB -> DetailMessagesFragment()
HISTORY_TAB -> DetailHistoryFragment()
VOLUNTEER_TAB -> DetailVolunteersFragment()
}.apply {
setAccident(accident)
}
}
private lateinit var accident: Accident
private lateinit var summaryFrame: DetailsSummaryFrame
private lateinit var menuController: DetailsMenuController
private val tabs: RadioGroup by bindView(R.id.details_tabs_group)
//todo exterminatus
private var accNewState: AccidentStatus? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(ROOT_LAYOUT)
init(savedInstanceState?.getInt(ACCIDENT_ID_KEY))
}
private fun init(savedId: Int? = null) {
try {
val id = savedId ?: intent.extras.getInt(ACCIDENT_ID_KEY)
accident = Content[id] ?: throw RuntimeException()
menuController = DetailsMenuController(this, accident)
summaryFrame = DetailsSummaryFrame(this, accident)
Content.requestDetailsForAccident(accident) { setupFragments() }
tabs.hide()
update()
} catch (e: Exception) {
goTo(Screens.MAIN)
}
}
private fun setupFragments() = runOnUiThread {
tabs.show()
showFragment(Tab.VOLUNTEER_TAB)
tabs.setOnCheckedChangeListener { group, _ ->
showFragment(Tab.byId(group.checkedRadioButtonId))
}
}
private fun showFragment(tab: Tab) = changeFragmentTo(FRAGMENT_ROOT_VIEW, tab.fragment(accident))
override fun onResume() {
super.onResume()
findViewById<View>(GENERAL_INFORMATION_VIEW)
.setOnLongClickListener(this@AccidentDetailsActivity::generalPopUpListener)
init()
}
private fun generalPopUpListener(view: View): Boolean {
AccidentContextMenu(this, accident).showAsDropDown(view)
return true
}
fun update() {
summaryFrame.update()
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
try {
menuController.optionsMenuCreated(menu)
menuController.menuReconstruction()
} catch (e: Exception) {
e.printStackTrace()
} finally {
return super.onPrepareOptionsMenu(menu)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (menuController.itemSelected(item)) {
DetailsMenuController.MenuAction.TO_MAP -> toMap()
DetailsMenuController.MenuAction.HIDE_INFO, DetailsMenuController.MenuAction.SHARE -> Unit
DetailsMenuController.MenuAction.SEND_HIDE_REQUEST -> sendHideRequest()
DetailsMenuController.MenuAction.SEND_FINISH_REQUEST -> sendFinishRequest()
else -> return false
}
return true
}
private fun sendFinishRequest() {
//TODO Суперкостыль !!!
when (accident.status) {
ENDED -> ActivateAccident(accident.id, this::accidentChangeCallback).call()
else -> EndAccident(accident.id, this::accidentChangeCallback).call()
}
}
private fun sendHideRequest() {
//TODO какая то хуета
accNewState = when (accident.status) {
ENDED -> {
ActivateAccident(accident.id, this::accidentChangeCallback).call()
ACTIVE
}
else -> {
HideAccident(accident.id, this::accidentChangeCallback).call()
ENDED
}
}
}
private fun accidentChangeCallback(result: ApiResponse) {
if (result.hasError()) {
//todo
} else {
SubscribeManager.fireEvent(SubscribeManager.Event.ACCIDENTS_UPDATED)
//TODO Суперкостыль
accident.status = accNewState!!
update()
}
}
fun toMap() = goTo(Screens.MAIN, mapOf("toMap" to accident.id))
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
if (intent != null && intent.hasExtra(ACCIDENT_ID_KEY)) {
val cached = Content[intent.getIntExtra(ACCIDENT_ID_KEY, 0)]
if (cached == null) {
goTo(Screens.MAIN)
} else {
accident = cached
}
}
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
outState?.putInt(ACCIDENT_ID_KEY, accident.id)
}
}
| mit | 6366fbb5948cf943e5bc3e4ac2216013 | 34.497326 | 117 | 0.644471 | 4.701133 | false | false | false | false |
elpassion/el-abyrinth-android | bot/src/main/java/pl/elpassion/elabyrinth/bot/Board.kt | 1 | 2188 | package pl.elpassion.elabyrinth.bot
import pl.elpassion.elabyrinth.core.Cell
import pl.elpassion.elabyrinth.core.Direction
import java.util.*
class Board {
val map: Set<Field>
val start: Field
val finish: Field
val visited: MutableSet<Field>
constructor(map: List<List<Cell>>) {
this.map = map.withIndex().map { row -> val y = row.index; row.value.withIndex().filter { it.value != Cell.WALL }.map { Field(it.index, y) } }.flatten().toSet()
this.start = map.withIndex().map { row -> val y = row.index; row.value.withIndex().filter { it.value == Cell.START }.map { Field(it.index, y) } }.flatten().first()
this.finish = map.withIndex().map { row -> val y = row.index; row.value.withIndex().filter { it.value == Cell.END }.map { Field(it.index, y) } }.flatten().first()
this.visited = mutableSetOf(start)
}
fun solve(): List<Direction> {
return solve(Stack<Field>().apply { push(start) })
}
private fun solve(stack: Stack<Field>): List<Direction> {
if (stack.peek() == finish) {
return stack.toDirectionList()
} else {
val next = anyUnvisitedNeighbour(stack.peek())
if (next != null) {
visited.add(next)
return solve(stack.apply { push(next) })
} else {
return solve(stack.apply { pop() })
}
}
}
private fun anyUnvisitedNeighbour(field: Field): Field? {
val neighbours = field.neighbours()
return map.filter { neighbours.contains(it) && !visited.contains(it) }.firstOrNull()
}
}
fun Stack<Field>.toDirectionList(): List<Direction> {
val list = toList()
val moves = list.dropLast(1).zip(list.drop(1))
return moves.map { toDirection(it.first, it.second) }
}
fun toDirection(first: Field, second: Field) =
if (first.x == second.x) {
if (first.y < second.y) {
Direction.DOWN
} else {
Direction.UP
}
} else {
if (first.x < second.x) {
Direction.RIGHT
} else {
Direction.LEFT
}
}
| mit | dc4b5cf28a341fc823366085bc22c843 | 33.1875 | 171 | 0.564442 | 3.753002 | false | false | false | false |
facebook/fresco | vito/core-java-impl/src/main/java/com/facebook/fresco/vito/core/impl/ImagePipelineUtilsImpl.kt | 1 | 3624 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.vito.core.impl
import android.net.Uri
import com.facebook.fresco.vito.core.ImagePipelineUtils
import com.facebook.fresco.vito.options.DecodedImageOptions
import com.facebook.fresco.vito.options.EncodedImageOptions
import com.facebook.imagepipeline.common.ImageDecodeOptions
import com.facebook.imagepipeline.common.Priority
import com.facebook.imagepipeline.request.ImageRequest
import com.facebook.imagepipeline.request.ImageRequestBuilder
/**
* Utility methods to create [ImageRequest]s for [com.facebook.fresco.vito.options.ImageOptions].
*/
class ImagePipelineUtilsImpl(private val imageDecodeOptionsProvider: ImageDecodeOptionsProvider) :
ImagePipelineUtils {
fun interface CircularBitmapRounding {
fun getDecodeOptions(antiAliased: Boolean): ImageDecodeOptions?
}
fun interface ImageDecodeOptionsProvider {
fun create(
imageRequestBuilder: ImageRequestBuilder,
imageOptions: DecodedImageOptions
): ImageDecodeOptions?
}
override fun buildImageRequest(uri: Uri?, imageOptions: DecodedImageOptions): ImageRequest? {
if (uri == null) {
return null
}
return createDecodedImageRequestBuilder(
createEncodedImageRequestBuilder(uri, imageOptions), imageOptions)
?.build()
}
override fun wrapDecodedImageRequest(
originalRequest: ImageRequest,
imageOptions: DecodedImageOptions
): ImageRequest? =
createDecodedImageRequestBuilder(
createEncodedImageRequestBuilder(originalRequest, imageOptions), imageOptions)
?.build()
override fun buildEncodedImageRequest(
uri: Uri?,
imageOptions: EncodedImageOptions
): ImageRequest? = createEncodedImageRequestBuilder(uri, imageOptions)?.build()
protected fun createDecodedImageRequestBuilder(
imageRequestBuilder: ImageRequestBuilder?,
imageOptions: DecodedImageOptions
): ImageRequestBuilder? =
imageRequestBuilder?.apply {
imageOptions.resizeOptions?.let { resizeOptions = it }
imageOptions.rotationOptions?.let { rotationOptions = it }
imageDecodeOptionsProvider.create(imageRequestBuilder, imageOptions)?.let {
imageDecodeOptions = it
}
isLocalThumbnailPreviewsEnabled = imageOptions.areLocalThumbnailPreviewsEnabled()
loadThumbnailOnly = imageOptions.loadThumbnailOnly
imageOptions.postprocessor?.let { postprocessor = it }
imageOptions.isProgressiveDecodingEnabled?.let { isProgressiveRenderingEnabled = it }
}
protected fun createEncodedImageRequestBuilder(
uri: Uri?,
imageOptions: EncodedImageOptions
): ImageRequestBuilder? {
if (uri == null) {
return null
}
val builder = ImageRequestBuilder.newBuilderWithSource(uri)
maybeSetRequestPriority(builder, imageOptions.priority)
return builder
}
protected fun createEncodedImageRequestBuilder(
imageRequest: ImageRequest?,
imageOptions: EncodedImageOptions
): ImageRequestBuilder? {
if (imageRequest == null) {
return null
}
val builder = ImageRequestBuilder.fromRequest(imageRequest)
maybeSetRequestPriority(builder, imageOptions.priority)
return builder
}
companion object {
private fun maybeSetRequestPriority(builder: ImageRequestBuilder, priority: Priority?) {
if (priority != null) {
builder.requestPriority = priority
}
}
}
}
| mit | 3a5b994f90d3f880056d11c4449df5d2 | 33.514286 | 98 | 0.745585 | 5.199426 | false | false | false | false |
tonyofrancis/Fetch | fetch2core/src/main/java/com/tonyodev/fetch2core/DownloadBlockInfo.kt | 1 | 2912 | package com.tonyodev.fetch2core
import android.os.Parcel
import android.os.Parcelable
class DownloadBlockInfo : DownloadBlock {
override var downloadId: Int = -1
override var blockPosition: Int = -1
override var startByte: Long = -1L
override var endByte: Long = -1L
override var downloadedBytes: Long = -1L
override val progress: Int
get() {
return calculateProgress(downloadedBytes, endByte - startByte)
}
override fun copy(): DownloadBlock {
val downloadBlockInfo = DownloadBlockInfo()
downloadBlockInfo.downloadId = downloadId
downloadBlockInfo.blockPosition = blockPosition
downloadBlockInfo.startByte = startByte
downloadBlockInfo.endByte = endByte
downloadBlockInfo.downloadedBytes = downloadedBytes
return downloadBlockInfo
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as DownloadBlockInfo
if (downloadId != other.downloadId) return false
if (blockPosition != other.blockPosition) return false
if (startByte != other.startByte) return false
if (endByte != other.endByte) return false
if (downloadedBytes != other.downloadedBytes) return false
return true
}
override fun hashCode(): Int {
var result = downloadId
result = 31 * result + blockPosition
result = 31 * result + startByte.hashCode()
result = 31 * result + endByte.hashCode()
result = 31 * result + downloadedBytes.hashCode()
return result
}
override fun toString(): String {
return "DownloadBlock(downloadId=$downloadId, blockPosition=$blockPosition, " +
"startByte=$startByte, endByte=$endByte, downloadedBytes=$downloadedBytes)"
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(downloadId)
dest.writeInt(blockPosition)
dest.writeLong(startByte)
dest.writeLong(endByte)
dest.writeLong(downloadedBytes)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<DownloadBlockInfo> {
@Suppress("UNCHECKED_CAST")
override fun createFromParcel(source: Parcel): DownloadBlockInfo {
val downloadBlockInfo = DownloadBlockInfo()
downloadBlockInfo.downloadId = source.readInt()
downloadBlockInfo.blockPosition = source.readInt()
downloadBlockInfo.startByte = source.readLong()
downloadBlockInfo.endByte = source.readLong()
downloadBlockInfo.downloadedBytes = source.readLong()
return downloadBlockInfo
}
override fun newArray(size: Int): Array<DownloadBlockInfo?> {
return arrayOfNulls(size)
}
}
} | apache-2.0 | c13e17c594554725e43ae5df2928fe4d | 32.872093 | 91 | 0.659341 | 5.144876 | false | false | false | false |
tikivn/android-template | app/src/main/java/vn/tiki/sample/productlist/ProductListingPresenter.kt | 1 | 5314 | package vn.tiki.sample.productlist
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import vn.tale.viewholdersdemo.viewholder.ProductModel
import vn.tiki.architecture.redux.Epic
import vn.tiki.architecture.redux.Store
import vn.tiki.architecture.redux.createStore
import vn.tiki.sample.entity.ListData
import vn.tiki.sample.entity.Paging
import vn.tiki.sample.entity.Product
import vn.tiki.sample.mvp.rx.RxBasePresenter
import vn.tiki.sample.productlist.State.Idle
import vn.tiki.sample.productlist.State.LoadMoreError
import vn.tiki.sample.productlist.State.LoadMoreLoading
import vn.tiki.sample.productlist.State.RefreshError
import vn.tiki.sample.productlist.State.RefreshLoading
import vn.tiki.sample.productlist.State.StartError
import vn.tiki.sample.productlist.State.StartLoading
import vn.tiki.sample.productlist.State.Success
import vn.tiki.sample.repository.ProductRepository
import javax.inject.Inject
val page0: Paging = Paging.builder()
.currentPage(0)
.lastPage(0)
.total(0)
.make()
sealed class State {
object Idle : State()
object StartLoading : State()
object RefreshLoading : State()
object LoadMoreLoading : State()
object StartError : State()
object RefreshError : State()
object LoadMoreError : State()
object Success : State()
}
data class Model(val state: State, val paging: Paging = page0, val products: List<ProductModel> = emptyList())
object LoadAction
object LoadMoreAction
object RefreshAction
class ProductListingPresenter @Inject constructor(productRepository: ProductRepository) : RxBasePresenter<ProductListingView>() {
private val store: Store<Model>
init {
val map: (ListData<Product>) -> Pair<Paging, List<ProductModel>> = {
val paging = Paging.builder()
.currentPage(it.currentPage())
.lastPage(it.lastPage())
.total(it.total())
.make()
val productModels = it.items()
.map { ProductModel(it.title(), it.price(), it.image()) }
Pair(paging, productModels)
}
val load = Epic<Model> { actions, getModel ->
actions
.filter { it is LoadAction }
.filter {
val model = getModel()
val state = model.state
state !is StartLoading
&& state !is RefreshLoading
&& state !is LoadMoreLoading
}
.switchMap {
productRepository.getProducts(1)
.toObservable()
.doOnError(Throwable::printStackTrace)
.map { map(it) }
.map { Model(Success, it.first, it.second) }
.onErrorReturnItem(Model(StartError))
.subscribeOn(Schedulers.io())
.startWith(Model(StartLoading))
}
}
val refresh = Epic<Model> { actions, getModel ->
actions
.filter { it is RefreshAction }
.filter {
val state = getModel().state
state !is StartLoading
&& state !is RefreshLoading
}
.switchMap {
val model = getModel()
productRepository.fetchProducts(model.paging.currentPage() + 1)
.toObservable()
.map { map(it) }
.map { Model(Success, it.first, it.second) }
.onErrorReturnItem(model.copy(state = RefreshError))
.subscribeOn(Schedulers.io())
.startWith(model.copy(state = RefreshLoading))
}
}
val loadMore = Epic<Model> { actions, getModel ->
val model = getModel()
actions
.filter { it is LoadMoreAction }
.filter {
model.state !is RefreshLoading
}
.switchMap {
val refreshAction: Observable<Any> = actions.filter { it is RefreshAction }
productRepository.getProducts(1)
.toObservable()
.takeUntil(refreshAction)
.map { map(it) }
.map { Model(Success, it.first, model.products + it.second) }
.onErrorReturnItem(model.copy(state = LoadMoreError))
.subscribeOn(Schedulers.io())
.startWith(model.copy(state = LoadMoreLoading))
}
}
store = createStore(
initialState = Model(Idle),
epics = listOf(load, refresh, loadMore),
debug = true)
disposeOnDestroy(store.getState()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { model ->
sendToView { view ->
when (model.state) {
StartLoading -> view.showStartLoading()
RefreshLoading -> view.showRefreshLoading()
LoadMoreLoading -> view.showLoadMoreLoading()
StartError -> view.showStartError()
RefreshError -> view.showRefreshError()
LoadMoreError -> view.showLoadMoreError()
is Success -> view.showContent(model.products)
}
}
})
}
fun onLoad() {
store.dispatch(LoadAction)
}
fun onRefresh() {
store.dispatch(RefreshAction)
}
fun onLoadMore() {
store.dispatch(LoadMoreAction)
}
override fun destroy() {
super.destroy()
store.destroy()
}
} | apache-2.0 | 2e4ca28c8212a309642f8ef82ddc3562 | 30.636905 | 129 | 0.619684 | 4.439432 | false | false | false | false |
hammerheadnav/mocha | mocha-api/src/main/kotlin/io/hammerhead/mocha/api/expectations/espresso/EspressoCustomMatchers.kt | 1 | 3436 | package io.hammerhead.mocha.api.expectations.espresso
import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.StateListDrawable
import android.support.test.espresso.matcher.BoundedMatcher
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.TypeSafeMatcher
internal fun withTextColor(color: Int): Matcher<View> {
return object : BoundedMatcher<View, TextView>(TextView::class.java) {
override fun matchesSafely(textView: TextView): Boolean {
return color == textView.currentTextColor
}
override fun describeTo(description: Description) {
description.appendText("with text color: $color")
}
}
}
internal fun withEnabled(shouldBeEnabled: Boolean): Matcher<View> {
return object : BoundedMatcher<View, View>(View::class.java) {
override fun matchesSafely(view: View): Boolean {
return shouldBeEnabled == view.isEnabled
}
override fun describeTo(description: Description) {
description.appendText("with enabled state: $shouldBeEnabled")
}
}
}
internal fun withBackground(resourceId: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun matchesSafely(view: View): Boolean {
return sameBitmap(view.context, view.background, resourceId)
}
override fun describeTo(description: Description) {
description.appendText("has background resource " + resourceId)
}
}
}
internal fun withCompoundDrawable(resourceId: Int): Matcher<View> {
return object : BoundedMatcher<View, TextView>(TextView::class.java) {
override fun describeTo(description: Description) {
description.appendText("has compound drawable resource " + resourceId)
}
public override fun matchesSafely(textView: TextView): Boolean {
for (drawable in textView.compoundDrawables) {
if (sameBitmap(textView.context, drawable, resourceId)) {
return true
}
}
return false
}
}
}
internal fun withImageDrawable(resourceId: Int): Matcher<View> {
return object : BoundedMatcher<View, ImageView>(ImageView::class.java!!) {
override fun describeTo(description: Description) {
description.appendText("has image drawable resource " + resourceId)
}
public override fun matchesSafely(imageView: ImageView): Boolean {
return sameBitmap(imageView.getContext(), imageView.getDrawable(), resourceId)
}
}
}
private fun sameBitmap(context: Context, drawable: Drawable?, resourceId: Int): Boolean {
var drawable = drawable
var otherDrawable = context.getResources().getDrawable(resourceId)
if (drawable == null || otherDrawable == null) {
return false
}
if (drawable is StateListDrawable && otherDrawable is StateListDrawable) {
drawable = drawable.current
otherDrawable = otherDrawable!!.getCurrent()
}
if (drawable is BitmapDrawable) {
val bitmap = drawable.bitmap
val otherBitmap = (otherDrawable as BitmapDrawable).bitmap
return bitmap.sameAs(otherBitmap)
}
return false
}
| apache-2.0 | 37915a737c65e0be3d41787dec81425d | 34.061224 | 90 | 0.683935 | 5.045521 | false | false | false | false |
google/fhir-app-examples | demo/src/main/java/com/google/fhir/examples/demo/PatientDetailsRecyclerViewAdapter.kt | 1 | 8416 | /*
* Copyright 2022 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.fhir.examples.demo
import android.content.res.ColorStateList
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.ColorInt
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.shape.MaterialShapeDrawable
import com.google.android.material.shape.RoundedCornerTreatment
import com.google.android.material.shape.ShapeAppearanceModel
import com.google.fhir.examples.demo.PatientDetailsRecyclerViewAdapter.Companion.allCornersRounded
import com.google.fhir.examples.demo.databinding.PatientDetailsCardViewBinding
import com.google.fhir.examples.demo.databinding.PatientDetailsHeaderBinding
import com.google.fhir.examples.demo.databinding.PatientListItemViewBinding
class PatientDetailsRecyclerViewAdapter(private val onScreenerClick: () -> Unit) :
ListAdapter<PatientDetailData, PatientDetailItemViewHolder>(PatientDetailDiffUtil()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PatientDetailItemViewHolder {
return when (ViewTypes.from(viewType)) {
ViewTypes.HEADER ->
PatientDetailsHeaderItemViewHolder(
PatientDetailsCardViewBinding.inflate(LayoutInflater.from(parent.context), parent, false)
)
ViewTypes.PATIENT ->
PatientOverviewItemViewHolder(
PatientDetailsHeaderBinding.inflate(LayoutInflater.from(parent.context), parent, false),
onScreenerClick
)
ViewTypes.PATIENT_PROPERTY ->
PatientPropertyItemViewHolder(
PatientListItemViewBinding.inflate(LayoutInflater.from(parent.context), parent, false)
)
ViewTypes.OBSERVATION ->
PatientDetailsObservationItemViewHolder(
PatientListItemViewBinding.inflate(LayoutInflater.from(parent.context), parent, false)
)
ViewTypes.CONDITION ->
PatientDetailsConditionItemViewHolder(
PatientListItemViewBinding.inflate(LayoutInflater.from(parent.context), parent, false)
)
}
}
override fun onBindViewHolder(holder: PatientDetailItemViewHolder, position: Int) {
val model = getItem(position)
holder.bind(model)
if (holder is PatientDetailsHeaderItemViewHolder) return
holder.itemView.background =
if (model.firstInGroup && model.lastInGroup) {
allCornersRounded()
} else if (model.firstInGroup) {
topCornersRounded()
} else if (model.lastInGroup) {
bottomCornersRounded()
} else {
noCornersRounded()
}
}
override fun getItemViewType(position: Int): Int {
val item = getItem(position)
return when (item) {
is PatientDetailHeader -> ViewTypes.HEADER
is PatientDetailOverview -> ViewTypes.PATIENT
is PatientDetailProperty -> ViewTypes.PATIENT_PROPERTY
is PatientDetailObservation -> ViewTypes.OBSERVATION
is PatientDetailCondition -> ViewTypes.CONDITION
else -> {
throw IllegalArgumentException("Undefined Item type")
}
}.ordinal
}
companion object {
private const val STROKE_WIDTH = 2f
private const val CORNER_RADIUS = 10f
@ColorInt private const val FILL_COLOR = Color.TRANSPARENT
@ColorInt private const val STROKE_COLOR = Color.GRAY
fun allCornersRounded(): MaterialShapeDrawable {
return MaterialShapeDrawable(
ShapeAppearanceModel.builder()
.setAllCornerSizes(CORNER_RADIUS)
.setAllCorners(RoundedCornerTreatment())
.build()
)
.applyStrokeColor()
}
fun topCornersRounded(): MaterialShapeDrawable {
return MaterialShapeDrawable(
ShapeAppearanceModel.builder()
.setTopLeftCornerSize(CORNER_RADIUS)
.setTopRightCornerSize(CORNER_RADIUS)
.setTopLeftCorner(RoundedCornerTreatment())
.setTopRightCorner(RoundedCornerTreatment())
.build()
)
.applyStrokeColor()
}
fun bottomCornersRounded(): MaterialShapeDrawable {
return MaterialShapeDrawable(
ShapeAppearanceModel.builder()
.setBottomLeftCornerSize(CORNER_RADIUS)
.setBottomRightCornerSize(CORNER_RADIUS)
.setBottomLeftCorner(RoundedCornerTreatment())
.setBottomRightCorner(RoundedCornerTreatment())
.build()
)
.applyStrokeColor()
}
fun noCornersRounded(): MaterialShapeDrawable {
return MaterialShapeDrawable(ShapeAppearanceModel.builder().build()).applyStrokeColor()
}
private fun MaterialShapeDrawable.applyStrokeColor(): MaterialShapeDrawable {
strokeWidth = STROKE_WIDTH
fillColor = ColorStateList.valueOf(FILL_COLOR)
strokeColor = ColorStateList.valueOf(STROKE_COLOR)
return this
}
}
}
abstract class PatientDetailItemViewHolder(v: View) : RecyclerView.ViewHolder(v) {
abstract fun bind(data: PatientDetailData)
}
class PatientOverviewItemViewHolder(
private val binding: PatientDetailsHeaderBinding,
val onScreenerClick: () -> Unit
) : PatientDetailItemViewHolder(binding.root) {
override fun bind(data: PatientDetailData) {
binding.screener.setOnClickListener { onScreenerClick() }
(data as PatientDetailOverview).let { binding.title.text = it.patient.name }
data.patient.riskItem?.let {
binding.patientContainer.setBackgroundColor(it.patientCardColor)
binding.statusValue.text = it.riskStatus
binding.statusValue.setTextColor(Color.BLACK)
binding.statusValue.background =
allCornersRounded().apply { fillColor = ColorStateList.valueOf(it.riskStatusColor) }
binding.lastContactValue.text = it.lastContacted
}
}
}
class PatientPropertyItemViewHolder(private val binding: PatientListItemViewBinding) :
PatientDetailItemViewHolder(binding.root) {
override fun bind(data: PatientDetailData) {
(data as PatientDetailProperty).let {
binding.name.text = it.patientProperty.header
binding.fieldName.text = it.patientProperty.value
}
binding.status.visibility = View.GONE
binding.id.visibility = View.GONE
}
}
class PatientDetailsHeaderItemViewHolder(private val binding: PatientDetailsCardViewBinding) :
PatientDetailItemViewHolder(binding.root) {
override fun bind(data: PatientDetailData) {
(data as PatientDetailHeader).let { binding.header.text = it.header }
}
}
class PatientDetailsObservationItemViewHolder(private val binding: PatientListItemViewBinding) :
PatientDetailItemViewHolder(binding.root) {
override fun bind(data: PatientDetailData) {
(data as PatientDetailObservation).let {
binding.name.text = it.observation.code
binding.fieldName.text = it.observation.value
}
binding.status.visibility = View.GONE
binding.id.visibility = View.GONE
}
}
class PatientDetailsConditionItemViewHolder(private val binding: PatientListItemViewBinding) :
PatientDetailItemViewHolder(binding.root) {
override fun bind(data: PatientDetailData) {
(data as PatientDetailCondition).let {
binding.name.text = it.condition.code
binding.fieldName.text = it.condition.value
}
binding.status.visibility = View.GONE
binding.id.visibility = View.GONE
}
}
enum class ViewTypes {
HEADER,
PATIENT,
PATIENT_PROPERTY,
OBSERVATION,
CONDITION;
companion object {
fun from(ordinal: Int): ViewTypes {
return values()[ordinal]
}
}
}
class PatientDetailDiffUtil : DiffUtil.ItemCallback<PatientDetailData>() {
override fun areItemsTheSame(o: PatientDetailData, n: PatientDetailData) = o == n
override fun areContentsTheSame(o: PatientDetailData, n: PatientDetailData) =
areItemsTheSame(o, n)
}
| apache-2.0 | fcffe914ee8573289f20a6c2282b1be5 | 35.275862 | 99 | 0.734316 | 4.486141 | false | false | false | false |
coil-kt/coil | coil-base/src/main/java/coil/fetch/ResourceUriFetcher.kt | 1 | 3582 | package coil.fetch
import android.content.ContentResolver.SCHEME_ANDROID_RESOURCE
import android.net.Uri
import android.util.TypedValue
import android.webkit.MimeTypeMap
import coil.ImageLoader
import coil.decode.DataSource
import coil.decode.ImageSource
import coil.decode.ResourceMetadata
import coil.request.Options
import coil.util.DrawableUtils
import coil.util.getDrawableCompat
import coil.util.getMimeTypeFromUrl
import coil.util.getXmlDrawableCompat
import coil.util.isVector
import coil.util.toDrawable
import okio.buffer
import okio.source
internal class ResourceUriFetcher(
private val data: Uri,
private val options: Options
) : Fetcher {
override suspend fun fetch(): FetchResult {
// Expected format: android.resource://example.package.name/12345678
val packageName = data.authority?.takeIf { it.isNotBlank() } ?: throwInvalidUriException(data)
val resId = data.pathSegments.lastOrNull()?.toIntOrNull() ?: throwInvalidUriException(data)
val context = options.context
val resources = if (packageName == context.packageName) {
context.resources
} else {
context.packageManager.getResourcesForApplication(packageName)
}
val path = TypedValue().apply { resources.getValue(resId, this, true) }.string
val entryName = path.substring(path.lastIndexOf('/'))
val mimeType = MimeTypeMap.getSingleton().getMimeTypeFromUrl(entryName)
return if (mimeType == MIME_TYPE_XML) {
// getDrawableCompat can only load resources that are in the current package.
val drawable = if (packageName == context.packageName) {
context.getDrawableCompat(resId)
} else {
context.getXmlDrawableCompat(resources, resId)
}
val isVector = drawable.isVector
DrawableResult(
drawable = if (isVector) {
DrawableUtils.convertToBitmap(
drawable = drawable,
config = options.config,
size = options.size,
scale = options.scale,
allowInexactSize = options.allowInexactSize
).toDrawable(context)
} else {
drawable
},
isSampled = isVector,
dataSource = DataSource.DISK
)
} else {
val typedValue = TypedValue()
val inputStream = resources.openRawResource(resId, typedValue)
SourceResult(
source = ImageSource(
source = inputStream.source().buffer(),
context = context,
metadata = ResourceMetadata(packageName, resId, typedValue.density)
),
mimeType = mimeType,
dataSource = DataSource.DISK
)
}
}
private fun throwInvalidUriException(data: Uri): Nothing {
throw IllegalStateException("Invalid $SCHEME_ANDROID_RESOURCE URI: $data")
}
class Factory : Fetcher.Factory<Uri> {
override fun create(data: Uri, options: Options, imageLoader: ImageLoader): Fetcher? {
if (!isApplicable(data)) return null
return ResourceUriFetcher(data, options)
}
private fun isApplicable(data: Uri): Boolean {
return data.scheme == SCHEME_ANDROID_RESOURCE
}
}
companion object {
private const val MIME_TYPE_XML = "text/xml"
}
}
| apache-2.0 | 0574dea10626565934abc4c4e542f415 | 35.181818 | 102 | 0.615578 | 5.31454 | false | false | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/ide/formatter/blocks/SyntheticRustFmtBlock.kt | 1 | 2127 | package org.rust.ide.formatter.blocks
import com.intellij.formatting.*
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import org.rust.ide.formatter.RustFmtContext
import org.rust.ide.formatter.impl.computeSpacing
/**
* Synthetic formatting block wraps a subsequence of sub blocks
* and presents itself as one of the members of this subsequence.
*/
class SyntheticRustFmtBlock(
val representative: ASTBlock? = null,
private val subBlocks: List<Block>,
private val alignment: Alignment? = null,
private val indent: Indent? = null,
private val wrap: Wrap? = null,
val ctx: RustFmtContext
) : ASTBlock {
init {
assert(subBlocks.isNotEmpty()) { "tried to build empty synthetic block" }
}
private val textRange = TextRange(
subBlocks.first().textRange.startOffset,
subBlocks.last().textRange.endOffset)
override fun getTextRange(): TextRange = textRange
override fun getNode(): ASTNode? = representative?.node
override fun getAlignment(): Alignment? = alignment ?: representative?.alignment
override fun getIndent(): Indent? = indent ?: representative?.indent
override fun getWrap(): Wrap? = wrap ?: representative?.wrap
override fun getSubBlocks(): List<Block> = subBlocks
override fun getChildAttributes(newChildIndex: Int): ChildAttributes = ChildAttributes(indent, null)
override fun getSpacing(child1: Block?, child2: Block): Spacing? = computeSpacing(child1, child2, ctx)
override fun isLeaf(): Boolean = false
override fun isIncomplete(): Boolean = subBlocks.last().isIncomplete
override fun toString(): String {
val text = findFirstNonSyntheticChild()?.psi?.containingFile?.text?.let { textRange.subSequence(it) }
?: "<rust synthetic>"
return "$text $textRange"
}
private fun findFirstNonSyntheticChild(): ASTNode? {
val child = subBlocks.first()
return when (child) {
is SyntheticRustFmtBlock -> child.findFirstNonSyntheticChild()
is ASTBlock -> child.node
else -> null
}
}
}
| mit | c0140c77a1d5255dfb8e04d18b009560 | 34.45 | 109 | 0.697226 | 4.633987 | false | false | false | false |
quarck/CalendarNotification | app/src/main/java/com/github/quarck/calnotify/app/ApplicationController.kt | 1 | 43608 | //
// Calendar Notifications Plus
// Copyright (C) 2016 Sergey Parshin ([email protected])
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
package com.github.quarck.calnotify.app
import android.content.Context
import com.github.quarck.calnotify.Consts
import com.github.quarck.calnotify.Settings
import com.github.quarck.calnotify.calendareditor.CalendarChangeRequestMonitor
import com.github.quarck.calnotify.calendareditor.CalendarChangeRequestMonitorInterface
import com.github.quarck.calnotify.calendar.*
import com.github.quarck.calnotify.calendarmonitor.CalendarMonitor
import com.github.quarck.calnotify.calendarmonitor.CalendarMonitorInterface
import com.github.quarck.calnotify.dismissedeventsstorage.DismissedEventsStorage
import com.github.quarck.calnotify.dismissedeventsstorage.EventDismissType
import com.github.quarck.calnotify.eventsstorage.EventsStorage
import com.github.quarck.calnotify.eventsstorage.EventsStorageInterface
import com.github.quarck.calnotify.globalState
import com.github.quarck.calnotify.logs.DevLog
import com.github.quarck.calnotify.notification.EventNotificationManager
import com.github.quarck.calnotify.notification.EventNotificationManagerInterface
import com.github.quarck.calnotify.persistentState
import com.github.quarck.calnotify.quiethours.QuietHoursManager
import com.github.quarck.calnotify.quiethours.QuietHoursManagerInterface
import com.github.quarck.calnotify.reminders.ReminderState
import com.github.quarck.calnotify.textutils.EventFormatter
import com.github.quarck.calnotify.ui.UINotifier
import com.github.quarck.calnotify.calendareditor.CalendarChangeManagerInterface
import com.github.quarck.calnotify.calendareditor.CalendarChangeManager
import com.github.quarck.calnotify.utils.detailed
object ApplicationController : EventMovedHandler {
private const val LOG_TAG = "App"
private var settings: Settings? = null
private fun getSettings(ctx: Context): Settings {
if (settings == null) {
synchronized(this) {
if (settings == null)
settings = Settings(ctx)
}
}
return settings!!
}
private val notificationManager: EventNotificationManagerInterface = EventNotificationManager()
private val alarmScheduler: AlarmSchedulerInterface = AlarmScheduler
private var quietHoursManagerValue: QuietHoursManagerInterface? = null
private fun getQuietHoursManager(ctx: Context): QuietHoursManagerInterface {
if (quietHoursManagerValue == null) {
synchronized(this) {
if (quietHoursManagerValue == null)
quietHoursManagerValue = QuietHoursManager(ctx)
}
}
return quietHoursManagerValue!!
}
private val calendarReloadManager: CalendarReloadManagerInterface = CalendarReloadManager
private val calendarProvider: CalendarProviderInterface = CalendarProvider
private val calendarChangeManager: CalendarChangeManagerInterface by lazy { CalendarChangeManager(calendarProvider)}
private val calendarMonitorInternal: CalendarMonitorInterface by lazy { CalendarMonitor(calendarProvider) }
private val addEventMonitor: CalendarChangeRequestMonitorInterface by lazy { CalendarChangeRequestMonitor() }
private val tagsManager: TagsManagerInterface by lazy { TagsManager() }
val CalendarMonitor: CalendarMonitorInterface
get() = calendarMonitorInternal
val AddEventMonitorInstance: CalendarChangeRequestMonitorInterface
get() = addEventMonitor
// fun hasActiveEvents(context: Context) =
// EventsStorage(context).use {
// val settings = Settings(context)
// it.events.filter { it.snoozedUntil == 0L && it.isNotSpecial && !it.isMuted && !it.isTask }.any()
// }
fun hasActiveEventsToRemind(context: Context) =
EventsStorage(context).use {
//val settings = Settings(context)
it.events.filter { it.snoozedUntil == 0L && it.isNotSpecial && !it.isMuted && !it.isTask }.any()
}
fun onEventAlarm(context: Context) {
DevLog.info(LOG_TAG, "onEventAlarm at ${System.currentTimeMillis()}");
val alarmWasExpectedAt = context.persistentState.nextSnoozeAlarmExpectedAt
val currentTime = System.currentTimeMillis()
context.globalState?.lastTimerBroadcastReceived = System.currentTimeMillis()
notificationManager.postEventNotifications(context, EventFormatter(context), false, null)
alarmScheduler.rescheduleAlarms(context, getSettings(context), getQuietHoursManager(context))
if (currentTime > alarmWasExpectedAt + Consts.ALARM_THRESHOLD) {
this.onSnoozeAlarmLate(context, currentTime, alarmWasExpectedAt)
}
}
fun onAppUpdated(context: Context) {
DevLog.info(LOG_TAG, "Application updated")
// this will post event notifications for existing known requests
notificationManager.postEventNotifications(context, EventFormatter(context), isRepost = true)
alarmScheduler.rescheduleAlarms(context, getSettings(context), getQuietHoursManager(context))
calendarMonitorInternal.launchRescanService(
context,
reloadCalendar = true,
rescanMonitor = true
)
}
fun onBootComplete(context: Context) {
DevLog.info(LOG_TAG, "OS boot is complete")
// this will post event notifications for existing known requests
notificationManager.postEventNotifications(context, EventFormatter(context), isRepost = true)
alarmScheduler.rescheduleAlarms(context, getSettings(context), getQuietHoursManager(context))
calendarMonitorInternal.launchRescanService(
context,
reloadCalendar = true,
rescanMonitor = true
)
}
fun onCalendarChanged(context: Context) {
DevLog.info(LOG_TAG, "onCalendarChanged")
calendarMonitorInternal.launchRescanService(
context,
delayed = 2000,
reloadCalendar = true,
rescanMonitor = true
)
}
fun onCalendarRescanForRescheduledFromService(context: Context, userActionUntil: Long) {
DevLog.info(LOG_TAG, "onCalendarRescanForRescheduledFromService")
val changes = EventsStorage(context).use {
db -> calendarReloadManager.rescanForRescheduledEvents(context, db, calendarProvider, this)
}
if (changes) {
notificationManager.postEventNotifications(context,
EventFormatter(context),
isRepost = true
)
alarmScheduler.rescheduleAlarms(context, getSettings(context), getQuietHoursManager(context))
val isUserAction = (System.currentTimeMillis() < userActionUntil)
UINotifier.notify(context, isUserAction)
}
else {
DevLog.debug(LOG_TAG, "No calendar changes detected")
}
}
fun onCalendarReloadFromService(context: Context, userActionUntil: Long) {
DevLog.info(LOG_TAG, "calendarReloadFromService")
val changes = EventsStorage(context).use {
db -> calendarReloadManager.reloadCalendar(context, db, calendarProvider, this)
}
DevLog.debug(LOG_TAG, "calendarReloadFromService: ${changes}")
if (changes) {
notificationManager.postEventNotifications(
context,
EventFormatter(context),
isRepost = true
)
alarmScheduler.rescheduleAlarms(context, getSettings(context), getQuietHoursManager(context))
val isUserAction = (System.currentTimeMillis() < userActionUntil)
UINotifier.notify(context, isUserAction)
}
else {
DevLog.debug(LOG_TAG, "No calendar changes detected")
}
}
fun onCalendarEventMovedWithinApp(context: Context, oldEvent: EventRecord, newEvent: EventRecord) {
val newAlertTime = newEvent.nextAlarmTime(System.currentTimeMillis())
val shouldAutoDismiss =
ApplicationController.checkShouldRemoveMovedEvent(
context,
oldEvent.eventId,
oldEvent.startTime,
newEvent.startTime,
newAlertTime
)
if (shouldAutoDismiss) {
EventsStorage(context).use {
db ->
val alertRecord = db.getEvent(oldEvent.eventId, oldEvent.startTime)
if (alertRecord != null) {
dismissEvent(
context,
db,
alertRecord,
EventDismissType.EventMovedUsingApp,
false
)
}
}
}
UINotifier.notify(context, true)
}
// some housekeeping that we have to do after firing calendar event
fun afterCalendarEventFired(context: Context) {
alarmScheduler.rescheduleAlarms(context, getSettings(context), getQuietHoursManager(context))
UINotifier.notify(context, false)
}
fun postEventNotifications(context: Context, events: Collection<EventAlertRecord>) {
if (events.size == 1)
notificationManager.onEventAdded(context, EventFormatter(context), events.first())
else
notificationManager.postEventNotifications(context, EventFormatter(context))
}
fun shouldMarkEventAsHandledAndSkip(context: Context, event: EventAlertRecord): Boolean {
val settings = getSettings(context)
if (event.eventStatus == EventStatus.Cancelled && settings.dontShowCancelledEvents) {
// indicate that we should mark as handled in the provider and skip
DevLog.info(LOG_TAG, "Event ${event.eventId}, status Cancelled - ignored")
return true
}
if (event.attendanceStatus == AttendanceStatus.Declined && settings.dontShowDeclinedEvents) {
// indicate that we should mark as handled in the provider and skip
DevLog.info(LOG_TAG, "Event ${event.eventId}, status Declined - ignored")
return true
}
if (event.isAllDay && settings.dontShowAllDayEvents) {
DevLog.info(LOG_TAG, "Event ${event.eventId} is an all day event - ignored per user setting")
return true
}
return false
}
fun registerNewEvent(context: Context, event: EventAlertRecord): Boolean {
var ret = false
val settings = getSettings(context)
if (event.calendarId != -1L && !settings.getCalendarIsHandled(event.calendarId)) {
DevLog.info(LOG_TAG, "Event ${event.eventId} -> calendar ${event.calendarId} is not handled");
return ret;
}
tagsManager.parseEventTags(context, settings, event)
DevLog.info(LOG_TAG, "registerNewEvent: Event fired: calId ${event.calendarId}, eventId ${event.eventId}, instanceStart ${event.instanceStartTime}, alertTime ${event.alertTime}, muted: ${event.isMuted}, task: ${event.isTask}")
// 1st step - save event into DB
EventsStorage(context).use {
db ->
if (event.isNotSpecial)
event.lastStatusChangeTime = System.currentTimeMillis()
else
event.lastStatusChangeTime = Long.MAX_VALUE
if (event.isRepeating) {
// repeating event - always simply add
db.addEvent(event) // ignoring result as we are using other way of validating
//notificationManager.onEventAdded(context, EventFormatter(context), event)
}
else {
// non-repeating event - make sure we don't create two records with the same eventId
val oldEvents = db.getEventInstances(event.eventId)
DevLog.info(LOG_TAG, "Non-repeating event, already have ${oldEvents.size} old requests with same event id ${event.eventId}, removing old")
try {
// delete old instances for the same event id (should be only one, but who knows)
notificationManager.onEventsDismissing(context, oldEvents)
val formatter = EventFormatter(context)
for (oldEvent in oldEvents) {
db.deleteEvent(oldEvent)
notificationManager.onEventDismissed(context, formatter, oldEvent.eventId, oldEvent.notificationId)
}
}
catch (ex: Exception) {
DevLog.error(LOG_TAG, "exception while removing old requests: ${ex.detailed}");
}
// add newly fired event
db.addEvent(event)
//notificationManager.onEventAdded(context, EventFormatter(context), event)
}
}
// 2nd step - re-open new DB instance and make sure that event:
// * is there
// * is not set as visible
// * is not snoozed
EventsStorage(context).use {
db ->
if (event.isRepeating) {
// return true only if we can confirm, by reading event again from DB
// that it is there
// Caller is using our return value as "safeToRemoveOriginalReminder" flag
val dbEvent = db.getEvent(event.eventId, event.instanceStartTime)
ret = dbEvent != null && dbEvent.snoozedUntil == 0L
}
else {
// return true only if we can confirm, by reading event again from DB
// that it is there
// Caller is using our return value as "safeToRemoveOriginalReminder" flag
val dbEvents = db.getEventInstances(event.eventId)
ret = dbEvents.size == 1 && dbEvents[0].snoozedUntil == 0L
}
}
if (!ret)
DevLog.error(LOG_TAG, "Error adding event with id ${event.eventId}, cal id ${event.calendarId}, " +
"instance st ${event.instanceStartTime}, repeating: " +
"${event.isRepeating}, allDay: ${event.isAllDay}, alertTime=${event.alertTime}");
else {
DevLog.debug(LOG_TAG, "event added: ${event.eventId} (cal id: ${event.calendarId})")
// WasHandledCache(context).use {
// cache -> cache.addHandledAlert(event)
// }
}
ReminderState(context).onNewEventFired()
return ret
}
fun registerNewEvents(
context: Context,
//wasHandledCache: WasHandledCacheInterface,
pairs: List<Pair<MonitorEventAlertEntry, EventAlertRecord>>
): ArrayList<Pair<MonitorEventAlertEntry, EventAlertRecord>> {
val settings = getSettings(context)
val handledCalendars = calendarProvider.getHandledCalendarsIds(context, settings)
val handledPairs = pairs.filter {
(_, event) ->
handledCalendars.contains(event.calendarId) || event.calendarId == -1L
}
val pairsToAdd = arrayListOf<Pair<MonitorEventAlertEntry, EventAlertRecord>>()
val eventsToDismiss = arrayListOf<EventAlertRecord>()
var eventsToAdd: List<EventAlertRecord>? = null
// 1st step - save event into DB
EventsStorage(context).use {
db ->
for ((alert, event) in handledPairs) {
DevLog.info(LOG_TAG, "registerNewEvents: Event fired, calId ${event.calendarId}, eventId ${event.eventId}, instanceStart ${event.instanceStartTime}, alertTime=${event.alertTime}")
tagsManager.parseEventTags(context, settings, event)
if (event.isRepeating) {
// repeating event - always simply add
pairsToAdd.add(Pair(alert, event))
}
else {
// non-repeating event - make sure we don't create two records with the same eventId
val oldEvents = db.getEventInstances(event.eventId)
DevLog.info(LOG_TAG, "Non-repeating event, already have ${oldEvents.size} old requests with same event id ${event.eventId}, removing old")
try {
// delete old instances for the same event id (should be only one, but who knows)
eventsToDismiss.addAll(oldEvents)
}
catch (ex: Exception) {
DevLog.error(LOG_TAG, "exception while removing old requests: ${ex.detailed}");
}
// add newly fired event
pairsToAdd.add(Pair(alert, event))
}
}
if (!eventsToDismiss.isEmpty()) {
// delete old instances for the same event id (should be only one, but who knows)
notificationManager.onEventsDismissing(context, eventsToDismiss)
db.deleteEvents(eventsToDismiss)
val hasActiveEvents = db.events.any { it.snoozedUntil != 0L && !it.isSpecial }
notificationManager.onEventsDismissed(
context,
EventFormatter(context),
eventsToDismiss,
postNotifications = false, // don't repost notifications at this stage, but only dismiss currently active
hasActiveEvents = hasActiveEvents
)
}
if (!pairsToAdd.isEmpty()) {
var currentTime = System.currentTimeMillis()
for ((_, event) in pairsToAdd)
event.lastStatusChangeTime = currentTime++
eventsToAdd = pairsToAdd.map {
it.second
}
eventsToAdd?.let {
db.addEvents(it) // ignoring result of add - here we are using another way to validate succesfull add
}
}
}
// 2nd step - re-open new DB instance and make sure that event:
// * is there
// * is not set as visible
// * is not snoozed
val validPairs = arrayListOf<Pair<MonitorEventAlertEntry, EventAlertRecord>>()
EventsStorage(context).use {
db ->
for ((alert, event) in pairsToAdd) {
if (event.isRepeating) {
// return true only if we can confirm, by reading event again from DB
// that it is there
// Caller is using our return value as "safeToRemoveOriginalReminder" flag
val dbEvent = db.getEvent(event.eventId, event.instanceStartTime)
if (dbEvent != null && dbEvent.snoozedUntil == 0L) {
validPairs.add(Pair(alert, event))
}
else {
DevLog.error(LOG_TAG, "Failed to add event ${event.eventId} ${event.alertTime} ${event.instanceStartTime} into DB properly")
}
}
else {
// return true only if we can confirm, by reading event again from DB
// that it is there
// Caller is using our return value as "safeToRemoveOriginalReminder" flag
val dbEvents = db.getEventInstances(event.eventId)
if (dbEvents.size == 1 && dbEvents[0].snoozedUntil == 0L) {
validPairs.add(Pair(alert, event))
}
else {
DevLog.error(LOG_TAG, "Failed to add event ${event.eventId} ${event.alertTime} ${event.instanceStartTime} into DB properly")
}
}
}
}
if (pairs.size == validPairs.size) {
//eventsToAdd?.let { wasHandledCache.addHandledAlerts(it) }
}
else {
DevLog.warn(LOG_TAG, "registerNewEvents: Added ${validPairs.size} requests out of ${pairs.size}")
}
ReminderState(context).onNewEventFired()
return validPairs
}
// override fun onEventMoved(
// context: Context,
// db: EventsStorageInterface,
// oldEvent: EventAlertRecord,
// newEvent: EventRecord,
// newAlertTime: Long
// ): Boolean {
//
// var ret = false
//
// if (!getSettings(context).notificationAutoDismissOnReschedule)
// return false
//
// val oldTime = oldEvent.displayedStartTime
// val newTime = newEvent.newInstanceStartTime
//
// if (newTime - oldTime > Consts.EVENT_MOVE_THRESHOLD) {
// DevLog.info(context, LOG_TAG, "Event ${oldEvent.eventId} moved by ${newTime - oldTime} ms")
//
// if (newAlertTime > System.currentTimeMillis() + Consts.ALARM_THRESHOLD) {
//
// DevLog.info(context, LOG_TAG, "Event ${oldEvent.eventId} - alarm in the future confirmed, at $newAlertTime, auto-dismissing notification")
//
// dismissEvent(
// context,
// db,
// oldEvent.copy(newInstanceStartTime = newEvent.newInstanceStartTime, newInstanceEndTime = newEvent.newInstanceEndTime),
// EventDismissType.AutoDismissedDueToCalendarMove,
// true)
//
// ret = true
//
// if (getSettings(context).debugNotificationAutoDismiss)
// notificationManager.postNotificationsAutoDismissedDebugMessage(context)
// }
// }
//
// return ret
// }
override fun checkShouldRemoveMovedEvent(
context: Context,
oldEvent: EventAlertRecord,
newEvent: EventRecord,
newAlertTime: Long
): Boolean
= checkShouldRemoveMovedEvent(
context,
oldEvent.eventId,
oldEvent.displayedStartTime,
newEvent.startTime,
newAlertTime
)
override fun checkShouldRemoveMovedEvent(
context: Context,
eventId: Long,
oldStartTime: Long,
newStartTime: Long,
newAlertTime: Long
): Boolean {
var ret = false
if (newStartTime - oldStartTime > Consts.EVENT_MOVE_THRESHOLD) {
if (newAlertTime > System.currentTimeMillis() + Consts.ALARM_THRESHOLD) {
DevLog.info(LOG_TAG, "Event ${eventId} - alarm in the future confirmed, at $newAlertTime, marking for auto-dismissal")
ret = true
}
else {
DevLog.info(LOG_TAG, "Event ${eventId} moved by ${newStartTime - oldStartTime} ms - not enought to auto-dismiss")
}
}
return ret
}
fun toggleMuteForEvent(context: Context, eventId: Long, instanceStartTime: Long, muteAction: Int): Boolean {
var ret: Boolean = false
//val currentTime = System.currentTimeMillis()
val mutedEvent: EventAlertRecord? =
EventsStorage(context).use {
db ->
var event = db.getEvent(eventId, instanceStartTime)
if (event != null) {
val (success, newEvent) = db.updateEvent(event, isMuted = muteAction == 0)
event = if (success) newEvent else null
}
event;
}
if (mutedEvent != null) {
ret = true;
notificationManager.onEventMuteToggled(context, EventFormatter(context), mutedEvent)
ReminderState(context).onUserInteraction(System.currentTimeMillis())
alarmScheduler.rescheduleAlarms(context, getSettings(context), getQuietHoursManager(context))
DevLog.info(LOG_TAG, "Event ${eventId} / ${instanceStartTime} mute toggled: ${mutedEvent.isMuted}: $ret")
}
else {
DevLog.info(LOG_TAG, "Event ${eventId} / ${instanceStartTime} - failed to snooze evend by $muteAction")
}
return ret
}
fun snoozeEvent(context: Context, eventId: Long, instanceStartTime: Long, snoozeDelay: Long): SnoozeResult? {
var ret: SnoozeResult? = null
val currentTime = System.currentTimeMillis()
val snoozedEvent: EventAlertRecord? =
EventsStorage(context).use {
db ->
var event = db.getEvent(eventId, instanceStartTime)
if (event != null) {
var snoozedUntil =
if (snoozeDelay > 0L)
currentTime + snoozeDelay
else
event.displayedStartTime - Math.abs(snoozeDelay) // same as "event.instanceStart + snoozeDelay" but a little bit more readable
if (snoozedUntil < currentTime + Consts.ALARM_THRESHOLD) {
DevLog.error(LOG_TAG, "snooze: $eventId / $instanceStartTime by $snoozeDelay: new time is in the past, snoozing by 1m instead")
snoozedUntil = currentTime + Consts.FAILBACK_SHORT_SNOOZE
}
val (success, newEvent) = db.updateEvent(event,
snoozedUntil = snoozedUntil,
lastStatusChangeTime = currentTime,
displayStatus = EventDisplayStatus.Hidden)
event = if (success) newEvent else null
}
event;
}
if (snoozedEvent != null) {
notificationManager.onEventSnoozed(context, EventFormatter(context), snoozedEvent.eventId, snoozedEvent.notificationId);
ReminderState(context).onUserInteraction(System.currentTimeMillis())
val quietHoursManager = getQuietHoursManager(context)
alarmScheduler.rescheduleAlarms(context, getSettings(context), quietHoursManager)
val silentUntil = quietHoursManager.getSilentUntil(getSettings(context), snoozedEvent.snoozedUntil)
ret = SnoozeResult(SnoozeType.Snoozed, snoozedEvent.snoozedUntil, silentUntil)
DevLog.info(LOG_TAG, "Event ${eventId} / ${instanceStartTime} snoozed: by $snoozeDelay: $ret")
}
else {
DevLog.info(LOG_TAG, "Event ${eventId} / ${instanceStartTime} - failed to snooze evend by $snoozeDelay")
}
return ret
}
fun snoozeEvents(context: Context, filter: (EventAlertRecord)->Boolean, snoozeDelay: Long, isChange: Boolean, onlySnoozeVisible: Boolean): SnoozeResult? {
var ret: SnoozeResult? = null
val currentTime = System.currentTimeMillis()
var snoozedUntil = 0L
var allSuccess = true
EventsStorage(context).use {
db ->
val events = db.events.filter { it.isNotSpecial && filter(it) }
// Don't allow requests to have exactly the same "snoozedUntil", so to have
// predicted sorting order, so add a tiny (0.001s per event) adjust to each
// snoozed time
var snoozeAdjust = 0
for (event in events) {
val newSnoozeUntil = currentTime + snoozeDelay + snoozeAdjust
// onlySnoozeVisible
var snoozeThisEvent: Boolean
if (!onlySnoozeVisible) {
snoozeThisEvent = isChange || event.snoozedUntil == 0L || event.snoozedUntil < newSnoozeUntil
}
else {
snoozeThisEvent = event.snoozedUntil == 0L
}
if (snoozeThisEvent) {
val (success, _) =
db.updateEvent(
event,
snoozedUntil = newSnoozeUntil,
lastStatusChangeTime = currentTime
)
allSuccess = allSuccess && success;
++snoozeAdjust
snoozedUntil = newSnoozeUntil
}
}
}
if (allSuccess && snoozedUntil != 0L) {
notificationManager.onAllEventsSnoozed(context)
val quietHoursManager = getQuietHoursManager(context)
alarmScheduler.rescheduleAlarms(context, getSettings(context), quietHoursManager)
val silentUntil = quietHoursManager.getSilentUntil(getSettings(context), snoozedUntil)
ret = SnoozeResult(SnoozeType.Snoozed, snoozedUntil, silentUntil)
DevLog.info(LOG_TAG, "Snooze all by $snoozeDelay: success, $ret")
}
else {
DevLog.info(LOG_TAG, "Snooze all by $snoozeDelay: failed")
}
return ret
}
fun snoozeAllCollapsedEvents(context: Context, snoozeDelay: Long, isChange: Boolean, onlySnoozeVisible: Boolean): SnoozeResult? {
return snoozeEvents(context, { it.displayStatus == EventDisplayStatus.DisplayedCollapsed }, snoozeDelay, isChange, onlySnoozeVisible)
}
fun snoozeAllEvents(context: Context, snoozeDelay: Long, isChange: Boolean, onlySnoozeVisible: Boolean): SnoozeResult? {
return snoozeEvents(context, { true }, snoozeDelay, isChange, onlySnoozeVisible)
}
fun fireEventReminder(
context: Context,
itIsAfterQuietHoursReminder: Boolean, hasActiveAlarms: Boolean) {
notificationManager.fireEventReminder(context, itIsAfterQuietHoursReminder, hasActiveAlarms);
}
fun cleanupEventReminder(context: Context) {
notificationManager.cleanupEventReminder(context);
}
fun onMainActivityCreate(context: Context?) {
if (context != null) {
val settings = getSettings(context)
if (settings.versionCodeFirstInstalled == 0L) {
val pInfo = context.packageManager.getPackageInfo(context.packageName, 0)
settings.versionCodeFirstInstalled = pInfo.versionCode.toLong()
}
}
}
@Suppress("UNUSED_PARAMETER")
fun onMainActivityStarted(context: Context?) {
}
fun onMainActivityResumed(
context: Context?,
shouldRepost: Boolean,
monitorSettingsChanged: Boolean
) {
if (context != null) {
cleanupEventReminder(context)
if (shouldRepost) {
notificationManager.postEventNotifications(context, EventFormatter(context), isRepost = true)
context.globalState?.lastNotificationRePost = System.currentTimeMillis()
}
alarmScheduler.rescheduleAlarms(context, getSettings(context), getQuietHoursManager(context))
// this might fire new notifications
// This would automatically launch the rescan of calendar and monitor
calendarMonitorInternal.onAppResumed(context, monitorSettingsChanged)
//checkAndCleanupWasHandledCache(context)
}
}
// fun checkAndCleanupWasHandledCache(context: Context) {
//
// val prState = context.persistentState
// val now = System.currentTimeMillis()
//
// if (now - prState.lastWasHandledCacheCleanup < Consts.WAS_HANDLED_CACHE_CLEANUP_INTERVALS)
// return
//
// WasHandledCache(context).use { it.removeOldEntries( Consts.WAS_HANDLED_CACHE_MAX_AGE_MILLIS )}
//
// prState.lastWasHandledCacheCleanup = now
// }
fun onTimeChanged(context: Context) {
alarmScheduler.rescheduleAlarms(context, getSettings(context), getQuietHoursManager(context))
calendarMonitorInternal.onSystemTimeChange(context)
}
fun dismissEvents(
context: Context,
db: EventsStorageInterface,
events: Collection<EventAlertRecord>,
dismissType: EventDismissType,
notifyActivity: Boolean
) {
DevLog.info(LOG_TAG, "Dismissing ${events.size} requests")
if (dismissType.shouldKeep) {
DismissedEventsStorage(context).use {
it.addEvents(dismissType, events)
}
}
notificationManager.onEventsDismissing(context, events)
if (db.deleteEvents(events) == events.size) {
val hasActiveEvents = db.events.any { it.snoozedUntil != 0L && !it.isSpecial }
notificationManager.onEventsDismissed(context, EventFormatter(context), events, true, hasActiveEvents);
ReminderState(context).onUserInteraction(System.currentTimeMillis())
alarmScheduler.rescheduleAlarms(context, getSettings(context), getQuietHoursManager(context))
if (notifyActivity)
UINotifier.notify(context, true)
}
}
fun anyForDismissAllButRecentAndSnoozed(events: Array<EventAlertRecord>): Boolean {
val currentTime = System.currentTimeMillis()
val ret = events.any {
event ->
(event.lastStatusChangeTime < currentTime - Consts.DISMISS_ALL_THRESHOLD) &&
(event.snoozedUntil == 0L)
}
return ret
}
fun dismissAllButRecentAndSnoozed(context: Context, dismissType: EventDismissType) {
val currentTime = System.currentTimeMillis()
EventsStorage(context).use {
db ->
val eventsToDismiss = db.events.filter {
event ->
(event.lastStatusChangeTime < currentTime - Consts.DISMISS_ALL_THRESHOLD) &&
(event.snoozedUntil == 0L) &&
event.isNotSpecial
}
dismissEvents(context, db, eventsToDismiss, dismissType, false)
}
}
fun muteAllVisibleEvents(context: Context) {
EventsStorage(context).use {
db ->
val eventsToMute = db.events.filter {
event -> (event.snoozedUntil == 0L) && event.isNotSpecial && !event.isTask
}
if (eventsToMute.isNotEmpty()) {
val mutedEvents = eventsToMute.map { it.isMuted = true; it }
db.updateEvents(mutedEvents)
val formatter = EventFormatter(context)
for (mutedEvent in mutedEvents)
notificationManager.onEventMuteToggled(context, formatter, mutedEvent)
ReminderState(context).onUserInteraction(System.currentTimeMillis())
alarmScheduler.rescheduleAlarms(context, getSettings(context), getQuietHoursManager(context))
}
}
}
fun dismissEvent(
context: Context,
db: EventsStorageInterface,
event: EventAlertRecord,
dismissType: EventDismissType,
notifyActivity: Boolean
) {
DevLog.info(LOG_TAG, "Dismissing event id ${event.eventId} / instance ${event.instanceStartTime}")
if (dismissType.shouldKeep && event.isNotSpecial) {
DismissedEventsStorage(context).use {
it.addEvent(dismissType, event)
}
}
notificationManager.onEventDismissing(context, event.eventId, event.notificationId);
if (db.deleteEvent(event.eventId, event.instanceStartTime)) {
notificationManager.onEventDismissed(context, EventFormatter(context), event.eventId, event.notificationId);
ReminderState(context).onUserInteraction(System.currentTimeMillis())
alarmScheduler.rescheduleAlarms(context, getSettings(context), getQuietHoursManager(context))
if (notifyActivity)
UINotifier.notify(context, true)
}
else {
DevLog.error(LOG_TAG, "Failed to delete event id ${event.eventId} instance start ${event.instanceStartTime} from DB")
DevLog.error(LOG_TAG, " -- known events / instances: ")
for (ev in db.events) {
DevLog.error(LOG_TAG, " -- : ${ev.eventId}, ${ev.instanceStartTime}, ${ev.alertTime}, ${ev.snoozedUntil}")
}
}
}
fun dismissEvent(context: Context, dismissType: EventDismissType, event: EventAlertRecord) {
EventsStorage(context).use {
db ->
dismissEvent(context, db, event, dismissType, false)
}
}
fun dismissAndDeleteEvent(context: Context, dismissType: EventDismissType, event: EventAlertRecord): Boolean {
var ret = false
if (calendarProvider.deleteEvent(context, event.eventId)) {
dismissEvent(context, dismissType, event)
ret = true
}
return ret
}
@Suppress("UNUSED_PARAMETER")
fun dismissEvent(
context: Context,
dismissType: EventDismissType,
eventId: Long,
instanceStartTime: Long,
notificationId: Int,
notifyActivity: Boolean = true
) {
EventsStorage(context).use {
db ->
val event = db.getEvent(eventId, instanceStartTime)
if (event != null) {
DevLog.info(LOG_TAG, "Dismissing event ${event.eventId} / ${event.instanceStartTime}")
dismissEvent(context, db, event, dismissType, notifyActivity)
}
else {
DevLog.error(LOG_TAG, "dismissEvent: can't find event $eventId, $instanceStartTime")
DevLog.error(LOG_TAG, " -- known events / instances: ")
for (ev in db.events) {
DevLog.error(LOG_TAG, " -- : ${ev.eventId}, ${ev.instanceStartTime}, ${ev.alertTime}, ${ev.snoozedUntil}")
}
}
}
}
fun restoreEvent(context: Context, event: EventAlertRecord) {
val toRestore =
event.copy(
notificationId = 0, // re-assign new notification ID since old one might already in use
displayStatus = EventDisplayStatus.Hidden) // ensure correct visibility is set
val successOnAdd =
EventsStorage(context).use {
db ->
val ret = db.addEvent(toRestore)
calendarReloadManager.reloadSingleEvent(context, db, toRestore, calendarProvider, null)
ret
}
if (successOnAdd) {
notificationManager.onEventRestored(context, EventFormatter(context), toRestore)
DismissedEventsStorage(context).use {
db ->
db.deleteEvent(event)
}
}
}
fun moveEvent(context: Context, event: EventAlertRecord, addTime: Long): Boolean {
val moved = calendarChangeManager.moveEvent(context, event, addTime)
if (moved) {
DevLog.info(LOG_TAG, "moveEvent: Moved event ${event.eventId} by ${addTime / 1000L} seconds")
EventsStorage(context).use {
db ->
dismissEvent(
context,
db,
event,
EventDismissType.EventMovedUsingApp,
true
)
}
}
return moved
}
fun moveAsCopy(context: Context, calendar: CalendarRecord, event: EventAlertRecord, addTime: Long): Long {
val eventId = calendarChangeManager.moveRepeatingAsCopy(context, calendar, event, addTime)
if (eventId != -1L) {
DevLog.debug(LOG_TAG, "Event created: id=${eventId}")
EventsStorage(context).use {
db ->
dismissEvent(
context,
db,
event,
EventDismissType.EventMovedUsingApp,
true
)
}
} else {
DevLog.error(LOG_TAG, "Failed to create event")
}
return eventId
}
// used for debug purpose
@Suppress("unused")
fun forceRepostNotifications(context: Context) {
notificationManager.postEventNotifications(context, EventFormatter(context), isRepost = true)
}
// used for debug purpose
@Suppress("unused")
fun postNotificationsAutoDismissedDebugMessage(context: Context) {
notificationManager.postNotificationsAutoDismissedDebugMessage(context)
}
fun postNearlyMissedNotificationDebugMessage(context: Context) {
notificationManager.postNearlyMissedNotificationDebugMessage(context)
}
fun isCustomQuietHoursActive(ctx: Context): Boolean {
return getQuietHoursManager(ctx).isCustomQuietHoursActive(getSettings(ctx))
}
/// Set quietForSeconds to 0 to disable
fun applyCustomQuietHoursForSeconds(ctx: Context, quietForSeconds: Int) {
val settings = getSettings(ctx)
val quietHoursManager = getQuietHoursManager(ctx)
if (quietForSeconds > 0) {
quietHoursManager.startManualQuietPeriod(
settings,
System.currentTimeMillis() + quietForSeconds*1000L
)
alarmScheduler.rescheduleAlarms(ctx, getSettings(ctx), quietHoursManager)
} else {
quietHoursManager.stopManualQuietPeriod(settings)
alarmScheduler.rescheduleAlarms(ctx, getSettings(ctx), quietHoursManager)
}
}
fun onReminderAlarmLate(context: Context, currentTime: Long, alarmWasExpectedAt: Long) {
// if (getSettings(context).debugAlarmDelays) {
//
val warningMessage = "Expected: $alarmWasExpectedAt, " +
"received: $currentTime, ${(currentTime - alarmWasExpectedAt) / 1000L}s late"
DevLog.error(LOG_TAG, "Late reminders alarm detected: $warningMessage")
//
// notificationManager.postNotificationsAlarmDelayDebugMessage(context, "Reminder alarm was late!", warningMessage)
// }
}
fun onSnoozeAlarmLate(context: Context, currentTime: Long, alarmWasExpectedAt: Long) {
// if (getSettings(context).debugAlarmDelays) {
//
val warningMessage = "Expected: $alarmWasExpectedAt, " +
"received: $currentTime, ${(currentTime - alarmWasExpectedAt) / 1000L}s late"
DevLog.error(LOG_TAG, "Late snooze alarm detected: $warningMessage")
// notificationManager.postNotificationsSnoozeAlarmDelayDebugMessage(context, "Snooze alarm was late!", warningMessage)
// }
}
}
| gpl-3.0 | f416a78c930a02d92bf4d2a81c122810 | 36.723183 | 234 | 0.602688 | 4.921896 | false | false | false | false |
android/user-interface-samples | People/app/src/main/java/com/example/android/people/ui/main/ContactAdapter.kt | 1 | 2425 | /*
* Copyright (C) 2019 The Android Open Source Project
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.people.ui.main
import android.graphics.drawable.Icon
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.android.people.R
import com.example.android.people.data.Contact
import com.example.android.people.databinding.ChatItemBinding
class ContactAdapter(
private val onChatClicked: (id: Long) -> Unit
) : ListAdapter<Contact, ContactViewHolder>(DIFF_CALLBACK) {
init {
setHasStableIds(true)
}
override fun getItemId(position: Int): Long {
return getItem(position).id
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContactViewHolder {
val holder = ContactViewHolder(parent)
holder.itemView.setOnClickListener {
onChatClicked(holder.itemId)
}
return holder
}
override fun onBindViewHolder(holder: ContactViewHolder, position: Int) {
val contact: Contact = getItem(position)
holder.binding.icon.setImageIcon(Icon.createWithAdaptiveBitmapContentUri(contact.iconUri))
holder.binding.name.text = contact.name
}
}
private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Contact>() {
override fun areItemsTheSame(oldItem: Contact, newItem: Contact): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Contact, newItem: Contact): Boolean {
return oldItem == newItem
}
}
class ContactViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.chat_item, parent, false)
) {
val binding: ChatItemBinding = ChatItemBinding.bind(itemView)
}
| apache-2.0 | 411efe6c7afeab350d84dbdeb93b4e68 | 34.144928 | 98 | 0.739381 | 4.433272 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/gifs/CepoDeMadeiraGIF.kt | 1 | 1522 | package net.perfectdreams.loritta.morenitta.gifs
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.utils.ImageUtils
import net.perfectdreams.loritta.morenitta.utils.extensions.readImage
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.stream.FileImageOutputStream
object CepoDeMadeiraGIF {
suspend fun getGIF(toUse: BufferedImage): File {
var ogTeste = ImageUtils.toBufferedImage(toUse.getScaledInstance(45, 45, BufferedImage.SCALE_SMOOTH))
var fileName = LorittaBot.TEMP + "cepo-" + System.currentTimeMillis() + ".gif"
var output = FileImageOutputStream(File(fileName))
val writer = GifSequenceWriter(output, BufferedImage.TYPE_INT_ARGB, 10, true)
var fogoFx = 0
for (i in 0..112) {
val file = File(LorittaBot.ASSETS + "cepo/cepo_${i.toString().padStart(6, '0')}.png")
if (file.exists()) {
var ogImage = readImage(File(LorittaBot.ASSETS + "cepo/cepo_${i.toString().padStart(6, '0')}.png"))
var image = BufferedImage(ogImage.width, ogImage.height, BufferedImage.TYPE_INT_ARGB)
image.graphics.drawImage(ogImage, 0, 0, null)
if (i in 0..16) {
image.graphics.drawImage(ogTeste, 65, 151, null)
}
if (i in 17..26) {
val fogo = readImage(File(LorittaBot.ASSETS + "fogo/fogo_${fogoFx.toString().padStart(6, '0')}.png"))
image.graphics.drawImage(fogo, 55, 141, null)
fogoFx++
}
writer.writeToSequence(image)
}
}
writer.close()
output.close()
return File(fileName)
}
} | agpl-3.0 | 6c6fa2ee3c76d8bfa37ed00c9fd4972a | 36.146341 | 106 | 0.721419 | 3.231423 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/SVNLogParser/src/test/kotlin/de/maibornwolff/codecharta/importer/svnlogparser/parser/LogLineParserTest.kt | 1 | 1476 | package de.maibornwolff.codecharta.importer.svnlogparser.parser
import de.maibornwolff.codecharta.importer.svnlogparser.input.Modification
import de.maibornwolff.codecharta.importer.svnlogparser.input.metrics.MetricsFactory
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import java.time.OffsetDateTime
import java.util.Arrays
class LogLineParserTest {
private val metricsFactory = mockk<MetricsFactory>()
@Before
fun setup() {
every { metricsFactory.createMetrics() } returns emptyList()
}
@Test
fun parseCommit() {
// given
val parserStrategy = mockk<LogParserStrategy>()
val author = "An Author"
val commitDate = OffsetDateTime.now()
val filenames = Arrays.asList("src/Main.java", "src/Util.java")
val input = emptyList<String>()
every { parserStrategy.parseAuthor(any()) } returns author
every { parserStrategy.parseDate(any()) } returns commitDate
every { parserStrategy.parseModifications(input) } returns filenames.map { Modification(it) }
val parser = LogLineParser(parserStrategy, metricsFactory)
// when
val commit = parser.parseCommit(input)
// then
assertThat(commit.author).isEqualTo(author)
assertThat(commit.filenames).isEqualTo(filenames)
assertThat(commit.commitDate).isEqualTo(commitDate)
}
}
| bsd-3-clause | 7324acd0f4c651100c98a8708e5163c6 | 32.545455 | 101 | 0.713415 | 4.486322 | false | true | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/javac-implementationspecificargument.kt | 1 | 1636 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.taskdefs.Javac.ImplementationSpecificArgument
import org.apache.tools.ant.types.Path
import org.apache.tools.ant.types.Reference
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
fun ImplementationSpecificArgument._init(
value: String?,
line: String?,
path: String?,
pathref: String?,
file: String?,
prefix: String?,
suffix: String?,
implementation: String?,
compiler: String?)
{
if (value != null)
setValue(value)
if (line != null)
setLine(line)
if (path != null)
setPath(Path(project, path))
if (pathref != null)
setPathref(Reference(project, pathref))
if (file != null)
setFile(project.resolveFile(file))
if (prefix != null)
setPrefix(prefix)
if (suffix != null)
setSuffix(suffix)
if (implementation != null)
setImplementation(implementation)
if (compiler != null)
setCompiler(compiler)
}
| apache-2.0 | 9811868954299d9a4cd1c71a98d60bad | 28.214286 | 79 | 0.660147 | 3.885986 | false | false | false | false |
jitsi/jitsi-videobridge | jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/util/NodeStatsBlockExtensions.kt | 1 | 2202 | /*
* Copyright @ 2019 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.nlj.util
import org.jitsi.nlj.stats.NodeStatsBlock
import org.jitsi.nlj.util.Util.Companion.getMbps
import java.time.Duration
/**
* Adds a compound value which computes the bitrate in megabits per second given two values
* that represent number of bytes and duration in milliseconds.
*
* @param name the name of the new value to add.
* @param bytesKey the name of the stat which has the number of bytes.
* @param durationMsKey the name of the stat which has the duration in milliseconds.
*/
fun NodeStatsBlock.addMbps(name: String, bytesKey: String, durationMsKey: String) = addCompoundValue(name) {
getMbps(
it.getNumberOrDefault(bytesKey, 0),
Duration.ofMillis(it.getNumberOrDefault(durationMsKey, 1).toLong())
)
}
/**
* Adds a compound value which computes the ratio of two values.
*
* @param name the name of the new value to add.
* @param numeratorKey the name of the stat which holds the numerator of the ratio.
* @param denominatorKey the name of the stat which holds the denominator of the ratio.
* @param defaultDenominator default value for the denominator in case the value with the given key
* doesn't exist or is 0.
*/
fun NodeStatsBlock.addRatio(
name: String,
numeratorKey: String,
denominatorKey: String,
defaultDenominator: Number = 1
) = addCompoundValue(name) {
val numerator = it.getNumber(numeratorKey) ?: 0
val denominator = it.getNumber(denominatorKey) ?: defaultDenominator
numerator.toDouble() / (if (denominator.toDouble() == 0.0) defaultDenominator else denominator).toDouble()
}
| apache-2.0 | 57215dcd6b44242a8450028ad8fa8a55 | 37.631579 | 110 | 0.739328 | 4.003636 | false | false | false | false |
vhromada/Catalog-Spring | src/main/kotlin/cz/vhromada/catalog/web/validator/YearsValidator.kt | 1 | 1826 | package cz.vhromada.catalog.web.validator
import cz.vhromada.catalog.web.fo.SeasonFO
import cz.vhromada.catalog.web.validator.constraints.Years
import cz.vhromada.common.utils.Constants
import java.util.regex.Pattern
import javax.validation.ConstraintValidator
import javax.validation.ConstraintValidatorContext
/**
* A class represents validator for years constraint.
*
* @author Vladimir Hromada
*/
class YearsValidator : ConstraintValidator<Years, SeasonFO> {
override fun isValid(value: SeasonFO?, constraintValidatorContext: ConstraintValidatorContext): Boolean {
if (value == null) {
return true
}
val startYear = value.startYear
val endYear = value.endYear
if (isNotStringValid(startYear) || isNotStringValid(endYear)) {
return true
}
val startYearValue = Integer.parseInt(startYear!!)
val endYearValue = Integer.parseInt(endYear!!)
return if (isNotIntValid(startYearValue) || isNotIntValid(endYearValue)) {
true
} else startYearValue <= endYearValue
}
/**
* Validates year as string.
*
* @param value value to validate
* @return true if value isn't null and is valid integer
*/
private fun isNotStringValid(value: String?): Boolean {
return value == null || !PATTERN.matcher(value).matches()
}
/**
* Validates year as integer.
*
* @param value value to validate
* @return true if value is in valid range
*/
private fun isNotIntValid(value: Int): Boolean {
return value < Constants.MIN_YEAR || value > Constants.CURRENT_YEAR
}
@Suppress("CheckStyle")
companion object {
/**
* Year pattern
*/
private val PATTERN = Pattern.compile("\\d{4}")
}
}
| mit | 7afc1151dcb84ec9d5ba249a18b43712 | 27.092308 | 109 | 0.654984 | 4.531017 | false | false | false | false |
jdinkla/groovy-java-ray-tracer | src/main/kotlin/net/dinkla/raytracer/utilities/Resolution.kt | 1 | 504 | package net.dinkla.raytracer.utilities
data class Resolution(val hres: Int, val vres: Int) {
constructor(vres: Int) : this(vres / 9 * 16, vres) {}
companion object {
var RESOLUTION_32 = Resolution(32)
var RESOLUTION_320 = Resolution(320)
var RESOLUTION_480 = Resolution(480)
var RESOLUTION_720 = Resolution(720)
var RESOLUTION_1080 = Resolution(1080)
var RESOLUTION_1440 = Resolution(1440)
var RESOLUTION_2160 = Resolution(2160)
}
}
| apache-2.0 | c9b0fd5e731bc187cf3f3cc08e849544 | 30.5 | 57 | 0.650794 | 3.9375 | false | false | false | false |
googlearchive/android-AutofillFramework | kotlinApp/Application/src/main/java/com/example/android/autofillframework/multidatasetservice/model/FilledAutofillFieldCollection.kt | 4 | 4924 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.autofillframework.multidatasetservice.model
import android.service.autofill.Dataset
import android.util.Log
import android.view.View
import android.view.autofill.AutofillId
import android.view.autofill.AutofillValue
import com.example.android.autofillframework.CommonUtil.TAG
import com.example.android.autofillframework.multidatasetservice.AutofillFieldMetadataCollection
import com.google.gson.annotations.Expose
import java.util.HashMap
/**
* FilledAutofillFieldCollection is the model that represents all of the form data on a client app's page, plus the
* dataset name associated with it.
*/
class FilledAutofillFieldCollection @JvmOverloads constructor(
@Expose var datasetName: String? = null,
@Expose private val hintMap: HashMap<String, FilledAutofillField> = HashMap<String,
FilledAutofillField>()
) {
/**
* Sets values for a list of autofillHints.
*/
fun add(autofillField: FilledAutofillField) {
autofillField.autofillHints.forEach { autofillHint ->
hintMap[autofillHint] = autofillField
}
}
/**
* Populates a [Dataset.Builder] with appropriate values for each [AutofillId]
* in a `AutofillFieldMetadataCollection`. In other words, it builds an Autofill dataset
* by applying saved values (from this `FilledAutofillFieldCollection`) to Views specified
* in a `AutofillFieldMetadataCollection`, which represents the current page the user is
* on.
*/
fun applyToFields(autofillFieldMetadataCollection: AutofillFieldMetadataCollection,
datasetBuilder: Dataset.Builder): Boolean {
var setValueAtLeastOnce = false
for (hint in autofillFieldMetadataCollection.allAutofillHints) {
val autofillFields = autofillFieldMetadataCollection.getFieldsForHint(hint) ?: continue
for (autofillField in autofillFields) {
val autofillId = autofillField.autofillId
val autofillType = autofillField.autofillType
val savedAutofillValue = hintMap[hint]
when (autofillType) {
View.AUTOFILL_TYPE_LIST -> {
savedAutofillValue?.textValue?.let {
val index = autofillField.getAutofillOptionIndex(it)
if (index != -1) {
datasetBuilder.setValue(autofillId, AutofillValue.forList(index))
setValueAtLeastOnce = true
}
}
}
View.AUTOFILL_TYPE_DATE -> {
savedAutofillValue?.dateValue?.let { date ->
datasetBuilder.setValue(autofillId, AutofillValue.forDate(date))
setValueAtLeastOnce = true
}
}
View.AUTOFILL_TYPE_TEXT -> {
savedAutofillValue?.textValue?.let { text ->
datasetBuilder.setValue(autofillId, AutofillValue.forText(text))
setValueAtLeastOnce = true
}
}
View.AUTOFILL_TYPE_TOGGLE -> {
savedAutofillValue?.toggleValue?.let { toggle ->
datasetBuilder.setValue(autofillId, AutofillValue.forToggle(toggle))
setValueAtLeastOnce = true
}
}
else -> Log.w(TAG, "Invalid autofill type - " + autofillType)
}
}
}
return setValueAtLeastOnce
}
/**
* @param autofillHints List of autofill hints, usually associated with a View or set of Views.
* @return whether any of the filled fields on the page have at least 1 autofillHint that is
* in the provided autofillHints.
*/
fun helpsWithHints(autofillHints: List<String>): Boolean {
for (autofillHint in autofillHints) {
hintMap[autofillHint]?.let { savedAutofillValue ->
if (!savedAutofillValue.isNull()) {
return true
}
}
}
return false
}
}
| apache-2.0 | 149d5094bc058b73e9be10b4c5b5dea2 | 42.192982 | 115 | 0.612916 | 5.107884 | false | false | false | false |
orbit/orbit | src/orbit-util/src/main/kotlin/orbit/util/time/Clock.kt | 1 | 1569 | /*
Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved.
This file is part of the Orbit Project <https://www.orbit.cloud>.
See license in LICENSE.
*/
package orbit.util.time
import java.time.Duration
import java.time.Instant
/**
* A clock used to measure time.
*/
class Clock {
private var offsetTime = 0L
/**
* Gets the current milliseconds since the epoch according to this clock.
* Typically this is the same as from the JVM but may be different if the time has been manipulated.
*
* @return The current timestamp.
*/
val currentTime: TimeMs get() = ClockUtils.currentTimeMillis() + offsetTime
fun now() = Instant.ofEpochMilli(currentTime)
/**
* Advances the internal time by the specified amount.
*
* @param offset The amount of time to advance by.
* @param timeUnit The unit of time to advance by.
*/
fun advanceTime(offset: TimeMs) {
offsetTime += offset
}
/**
* Resets clock to the current time removing any offsets from advancing the clock manually
*/
fun resetToNow() {
offsetTime = 0L
}
fun inFuture(time: Timestamp) = time.isAfter(now())
fun inPast(time: Timestamp) = !inFuture(time)
fun nowOrPast(time: Timestamp) = time.isExactly(now()) || inPast(time)
fun until(time: Timestamp) = Duration.between(now(), time.toInstant());
}
object ClockUtils {
fun currentTimeMillis(): Long = System.currentTimeMillis()
}
/**
* Represents a time or duration in milliseconds.
*/
typealias TimeMs = Long | bsd-3-clause | 4d8f13133f954766ffda9f87eae37270 | 26.068966 | 104 | 0.669216 | 4.075325 | false | false | false | false |
gameover-fwk/gameover-fwk | src/main/kotlin/gameover/fwk/libgdx/gfx/Polygons.kt | 1 | 3257 | package gameover.fwk.libgdx.gfx
import com.badlogic.gdx.math.Polygon
import com.badlogic.gdx.math.Vector2
import gameover.fwk.libgdx.utils.GdxArray
import gameover.fwk.pool.Vector2Pool
object Polygons {
fun createArcAsPolygon(x: Float, y: Float, radius: Float, start: Float, angle: Float, segments: Int): Polygon {
if (segments < 1)
throw IllegalArgumentException("arc need at least 1 segment")
val theta: Float = (2 * 3.1415926f * (angle / 360.0f)) / segments
val cos: Float = com.badlogic.gdx.math.MathUtils.cos(theta)
val sin: Float = com.badlogic.gdx.math.MathUtils.sin(theta)
var cx: Float = radius * com.badlogic.gdx.math.MathUtils.cos(start * com.badlogic.gdx.math.MathUtils.degreesToRadians)
var cy: Float = radius * com.badlogic.gdx.math.MathUtils.sin(start * com.badlogic.gdx.math.MathUtils.degreesToRadians)
val vertices = FloatArray(segments * 2 + 2)
vertices[vertices.size - 2] = x
vertices[vertices.size - 1] = y
for (i in 0 until segments) {
val temp: Float = cx
cx = cos * cx - sin * cy
cy = sin * temp + cos * cy
vertices[i * 2] = x + cx
vertices[i * 2 + 1] = y + cy
}
return Polygon(vertices)
}
fun isPointInPolygon(polygon: GdxArray<Vector2>, pointX: Float, pointY: Float): Boolean {
val lastVertice: Vector2 = polygon.get(polygon.size - 1)
var lastVerticeX = lastVertice.x
var lastVerticeY = lastVertice.y
var oddNodes = false
for (i in 0 until polygon.size) {
val v = polygon.get(i)
val x = v.x
val y = v.y
if (y < pointY && lastVerticeY >= pointY || lastVerticeY < pointY && y >= pointY) {
if (x + (pointY - y) / (lastVerticeY - y) * (lastVerticeX - x) < pointX) {
oddNodes = !oddNodes
}
}
lastVerticeX = x
lastVerticeY = y
}
return oddNodes
}
fun createArcAsListOfVertices(x: Float, y: Float, radius: Float, start: Float, angle: Float, segments: Int, fromPool: Boolean): GdxArray<Vector2> {
if (segments < 1)
throw IllegalArgumentException("arc need at least 1 segment")
val theta = (2 * 3.1415926f * (angle / 360.0f)) / segments
val cos = com.badlogic.gdx.math.MathUtils.cos(theta)
val sin = com.badlogic.gdx.math.MathUtils.sin(theta)
var cx = radius * com.badlogic.gdx.math.MathUtils.cos(start * com.badlogic.gdx.math.MathUtils.degreesToRadians)
var cy = radius * com.badlogic.gdx.math.MathUtils.sin(start * com.badlogic.gdx.math.MathUtils.degreesToRadians)
val ret = if (fromPool) {
Vector2Pool.obtainAsGdxArray(segments + 1)
} else {
val arr = GdxArray<Vector2>(segments + 1)
for (i in 0..segments) {
arr[i] = Vector2()
}
arr
}
for (i in 0..segments) {
val temp: Float = cx
cx = cos * cx - sin * cy
cy = sin * temp + cos * cy
ret.get(i).set(x + cx, y + cy)
}
ret.get(segments).set(x, y)
return ret
}
} | mit | 9df5d9409bf9987ac1f91829b439149d | 41.311688 | 151 | 0.57906 | 3.626949 | false | false | false | false |
xiaopansky/AssemblyAdapter | sample/src/main/java/me/panpf/adapter/sample/ui/RecyclerGridLayoutSampleFragment.kt | 1 | 3060 | package me.panpf.adapter.sample.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.fm_recycler_sticky.*
import me.panpf.adapter.recycler.AssemblyGridLayoutManager
import me.panpf.adapter.sample.R
import me.panpf.adapter.sample.adapter.AssemblyStickyRecyclerAdapter
import me.panpf.adapter.sample.bean.AppsTitle
import me.panpf.adapter.sample.item.AppItem
import me.panpf.adapter.sample.item.AppListHeaderItem
import me.panpf.adapter.sample.vm.AppsViewModel
import me.panpf.arch.ktx.bindViewModel
import me.panpf.recycler.sticky.StickyRecyclerItemDecoration
import java.util.*
class RecyclerGridLayoutSampleFragment : BaseFragment() {
private val appsViewModel by bindViewModel(AppsViewModel::class)
override fun onUserVisibleChanged(isVisibleToUser: Boolean) {
val attachActivity = activity
if (isVisibleToUser && attachActivity is AppCompatActivity) {
attachActivity.supportActionBar?.subtitle = "RecyclerView - GridLayoutManager"
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fm_recycler_sticky, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val context = context ?: return
stickyRecyclerFm_recycler.layoutManager = AssemblyGridLayoutManager(context, 3, stickyRecyclerFm_recycler)
val adapter = AssemblyStickyRecyclerAdapter().apply {
addItemFactory(AppItem.Factory())
addItemFactory(AppListHeaderItem.Factory().fullSpan(stickyRecyclerFm_recycler))
}
stickyRecyclerFm_recycler.addItemDecoration(StickyRecyclerItemDecoration(stickyRecyclerFm_frame))
stickyRecyclerFm_recycler.adapter = adapter
appsViewModel.apps.observe(this, androidx.lifecycle.Observer {
it ?: return@Observer
val systemAppList = it[0]
val userAppList = it[1]
val systemAppListSize = systemAppList.size
val userAppListSize = userAppList.size
var dataListSize = if (systemAppListSize > 0) systemAppListSize + 1 else 0
dataListSize += if (userAppListSize > 0) userAppListSize + 1 else 0
val dataList = ArrayList<Any>(dataListSize)
if (userAppListSize > 0) {
dataList.add(AppsTitle(String.format("自安装应用 %d 个", userAppListSize)))
dataList.addAll(userAppList)
}
if (systemAppListSize > 0) {
dataList.add(AppsTitle(String.format("系统应用 %d 个", systemAppListSize)))
dataList.addAll(systemAppList)
}
adapter.dataList = dataList
stickyRecyclerFm_recycler.scheduleLayoutAnimation()
})
appsViewModel.load()
}
} | apache-2.0 | fac98f3023445bf94a974f3c6cdf3642 | 38.467532 | 116 | 0.71264 | 4.638168 | false | false | false | false |
alashow/music-android | modules/core-ui-media/src/main/java/tm/alashow/datmusic/ui/audios/AudioDropdownMenu.kt | 1 | 2277 | /*
* Copyright (C) 2021, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.datmusic.ui.audios
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.width
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.res.stringResource
import tm.alashow.datmusic.ui.media.R
private val defaultMenuActionLabels = listOf(
R.string.audio_menu_play,
R.string.audio_menu_playNext,
R.string.audio_menu_download,
R.string.audio_menu_copyLink
)
val currentPlayingMenuActionLabels = listOf(
R.string.audio_menu_download,
R.string.audio_menu_copyLink
)
@Composable
fun AudioDropdownMenu(
expanded: Boolean,
onExpandedChange: (Boolean) -> Unit,
modifier: Modifier = Modifier,
actionLabels: List<Int> = defaultMenuActionLabels,
onDropdownSelect: (Int) -> Unit = {}
) {
IconButton(
onClick = { onExpandedChange(true) },
modifier = modifier
) {
Icon(
painter = rememberVectorPainter(Icons.Default.MoreVert),
contentDescription = stringResource(R.string.audio_menu_cd),
)
}
Box {
DropdownMenu(
expanded = expanded,
onDismissRequest = { onExpandedChange(false) },
modifier = Modifier
.width(IntrinsicSize.Min)
.align(Alignment.Center)
) {
actionLabels.forEach { item ->
val label = stringResource(item)
DropdownMenuItem(
onClick = {
onExpandedChange(false)
onDropdownSelect(item)
}
) {
Text(text = label)
}
}
}
}
}
| apache-2.0 | a4031cd6102052fb59df5f61da5a7e0d | 29.36 | 72 | 0.65964 | 4.535857 | false | false | false | false |
b3er/idea-archive-browser | src/main/kotlin/com/github/b3er/idea/plugins/arc/browser/base/BaseArchiveHandler.kt | 1 | 2890 | package com.github.b3er.idea.plugins.arc.browser.base
import com.intellij.openapi.util.io.FileSystemUtil
import com.intellij.openapi.vfs.impl.ArchiveHandler
import com.intellij.util.io.FileAccessorCache
import java.io.Closeable
import java.io.FileNotFoundException
abstract class BaseArchiveHandler<T>(path: String) : ArchiveHandler(path) {
@Volatile
var myFileStamp: Long = DEFAULT_TIMESTAMP
@Volatile
var myFileLength: Long = DEFAULT_LENGTH
abstract val accessorCache: FileAccessorCache<BaseArchiveHandler<T>, T>
abstract fun isSingleFileArchive(): Boolean
protected fun getFileHandle(): FileAccessorCache.Handle<T> {
val handle = accessorCache[this]
val attributes = file.canonicalFile.let {
FileSystemUtil.getAttributes(it) ?: throw FileNotFoundException(it.toString())
}
if (attributes.lastModified == myFileStamp && attributes.length == myFileLength) {
return handle
}
clearCaches()
handle.release()
return accessorCache[this]
}
override fun clearCaches() {
accessorCache.remove(this)
super.clearCaches()
}
interface CacheProvider<T> {
val cache: FileAccessorCache<BaseArchiveHandler<T>, T>
}
companion object {
fun <T> cacheProvider(
protectedQueueSize: Int = 20,
probationalQueueSize: Int = 20,
onCreate: (key: BaseArchiveHandler<T>) -> T,
onDispose: (value: T) -> Unit = { (it as? Closeable)?.close() },
onEqual: (val1: BaseArchiveHandler<T>?, val2: BaseArchiveHandler<T>?) -> Boolean = { v1, v2 ->
v1?.file?.canonicalPath == v2?.file?.canonicalPath
}
): CacheProvider<T> {
return object : CacheProvider<T> {
private val _cache = createCache(protectedQueueSize, probationalQueueSize, onCreate, onDispose, onEqual)
override val cache: FileAccessorCache<BaseArchiveHandler<T>, T>
get() = _cache
}
}
fun <T> createCache(
protectedQueueSize: Int = 20,
probationalQueueSize: Int = 20,
onCreate: (key: BaseArchiveHandler<T>) -> T,
onDispose: (value: T) -> Unit,
onEqual: (val1: BaseArchiveHandler<T>?, val2: BaseArchiveHandler<T>?) -> Boolean
): FileAccessorCache<BaseArchiveHandler<T>, T> {
return object : FileAccessorCache<BaseArchiveHandler<T>, T>(protectedQueueSize, probationalQueueSize) {
override fun createAccessor(key: BaseArchiveHandler<T>): T {
val attributes = FileSystemUtil.getAttributes(key.file.canonicalFile)
key.myFileStamp = attributes?.lastModified ?: DEFAULT_TIMESTAMP
key.myFileLength = attributes?.length ?: DEFAULT_LENGTH
return onCreate(key)
}
override fun disposeAccessor(fileAccessor: T) = onDispose(fileAccessor)
override fun isEqual(val1: BaseArchiveHandler<T>?, val2: BaseArchiveHandler<T>?): Boolean =
onEqual(val1, val2)
}
}
}
} | apache-2.0 | c4dc4298c8078834c52d66e608669fc3 | 34.691358 | 112 | 0.690311 | 4.076164 | false | false | false | false |
wespeakapp/WeSpeakAndroid | app/src/main/java/com/example/aleckstina/wespeakandroid/http/ApiClient.kt | 1 | 1018 | package com.example.aleckstina.wespeakandroid.http
import com.google.gson.Gson
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
/**
* Created by aleckstina on 10/6/17.
*/
@Singleton
class ApiClient {
companion object {
private var mApiClientInstance: ApiClient? = null
public final val BASE_URL = "http://35.188.157.198:3000/"
private var retrofit: Retrofit? = null
// Thread Safe
@Synchronized
public fun getInstance(): ApiClient {
if (mApiClientInstance == null) {
mApiClientInstance = ApiClient()
}
return mApiClientInstance as ApiClient
}
}
public fun buildRetrofit(): Retrofit {
if (retrofit == null) {
retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
return retrofit as Retrofit
}
public fun getApiService() : ApiInterface = buildRetrofit().create(ApiInterface::class.java)
} | mit | 2494d1f830ebca0ff88049d4e3d18789 | 24.475 | 94 | 0.693517 | 4.350427 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/ui/ButtonItemAdapter.kt | 1 | 3827 | // noinspection MissingCopyrightHeader #8659
/*
* The MIT License (MIT)
Copyright (c) 2014-2016 Aidan Michael Follestad
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.ichi2.ui
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.ichi2.anki.R
import com.ichi2.ui.ButtonItemAdapter.ButtonVH
/**
* RecyclerView.Adapter class copied almost completely from the Material Dialogs library example
* {@see [](https://github.com/afollestad/material-dialogs/blob/0.9.6.0/sample/src/main/java/com/afollestad/materialdialogssample/ButtonItemAdapter.java>ButtonItemAdapter.java</a>
) */
class ButtonItemAdapter(
private val items: ArrayList<String>,
private val itemCallback: ItemCallback,
private val buttonCallback: ButtonCallback
) : RecyclerView.Adapter<ButtonVH>() {
fun remove(searchName: String) {
items.remove(searchName)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ButtonVH {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.card_browser_item_my_searches_dialog, parent, false)
return ButtonVH(view, this)
}
override fun onBindViewHolder(holder: ButtonVH, position: Int) {
holder.title.text = items[position]
holder.button.tag = items[position]
}
override fun getItemCount() = items.size
inner class ButtonVH constructor(itemView: View, private val adapter: ButtonItemAdapter) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
val title: TextView = itemView.findViewById(R.id.card_browser_my_search_name_textview)
val button: ImageButton = itemView.findViewById<ImageButton?>(R.id.card_browser_my_search_remove_button).apply {
setOnClickListener(this@ButtonVH)
}
override fun onClick(view: View) {
if (view is ImageButton) {
adapter.buttonCallback.onButtonClicked(items[bindingAdapterPosition])
} else {
adapter.itemCallback.onItemClicked(items[bindingAdapterPosition])
}
}
init {
itemView.setOnClickListener(this)
}
}
/**
* Ensure our strings are sorted alphabetically - call this explicitly after changing
* the saved searches in any way, prior to displaying them again
*/
fun notifyAdapterDataSetChanged() {
items.sortWith { obj: String, str: String -> obj.compareTo(str, ignoreCase = true) }
super.notifyDataSetChanged()
}
fun interface ItemCallback {
fun onItemClicked(searchName: String)
}
fun interface ButtonCallback {
fun onButtonClicked(searchName: String)
}
}
| gpl-3.0 | 4515e32c52f22e4b89334d604fcfe5df | 38.453608 | 179 | 0.728247 | 4.605295 | false | false | false | false |
JetBrains/anko | anko/library/generated/appcompat-v7-coroutines/src/main/java/ListenersWithCoroutines.kt | 2 | 6889 | @file:JvmName("AppcompatV7CoroutinesListenersWithCoroutinesKt")
package org.jetbrains.anko.appcompat.v7.coroutines
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.CoroutineStart
fun android.support.v7.widget.ActionMenuView.onMenuItemClick(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(item: android.view.MenuItem?) -> Unit
) {
setOnMenuItemClickListener { item ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(item)
}
returnValue
}
}
fun android.support.v7.widget.ActivityChooserView.onDismiss(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.() -> Unit
) {
setOnDismissListener { ->
GlobalScope.launch(context, CoroutineStart.DEFAULT, block = handler)
}
}
fun android.support.v7.widget.FitWindowsFrameLayout.onFitSystemWindows(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(insets: android.graphics.Rect?) -> Unit
) {
setOnFitSystemWindowsListener { insets ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(insets)
}
}
}
fun android.support.v7.widget.SearchView.onClose(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.() -> Unit
) {
setOnCloseListener { ->
GlobalScope.launch(context, CoroutineStart.DEFAULT, block = handler)
returnValue
}
}
fun android.support.v7.widget.SearchView.onQueryTextFocusChange(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(v: android.view.View, hasFocus: Boolean) -> Unit
) {
setOnQueryTextFocusChangeListener { v, hasFocus ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v, hasFocus)
}
}
}
fun android.support.v7.widget.SearchView.onQueryTextListener(
context: CoroutineContext = Dispatchers.Main,
init: __SearchView_OnQueryTextListener.() -> Unit
) {
val listener = __SearchView_OnQueryTextListener(context)
listener.init()
setOnQueryTextListener(listener)
}
class __SearchView_OnQueryTextListener(private val context: CoroutineContext) : android.support.v7.widget.SearchView.OnQueryTextListener {
private var _onQueryTextSubmit: (suspend CoroutineScope.(String?) -> Boolean)? = null
private var _onQueryTextSubmit_returnValue: Boolean = false
override fun onQueryTextSubmit(query: String?) : Boolean {
val returnValue = _onQueryTextSubmit_returnValue
val handler = _onQueryTextSubmit ?: return returnValue
GlobalScope.launch(context) {
handler(query)
}
return returnValue
}
fun onQueryTextSubmit(
returnValue: Boolean = false,
listener: suspend CoroutineScope.(String?) -> Boolean
) {
_onQueryTextSubmit = listener
_onQueryTextSubmit_returnValue = returnValue
}
private var _onQueryTextChange: (suspend CoroutineScope.(String?) -> Boolean)? = null
private var _onQueryTextChange_returnValue: Boolean = false
override fun onQueryTextChange(newText: String?) : Boolean {
val returnValue = _onQueryTextChange_returnValue
val handler = _onQueryTextChange ?: return returnValue
GlobalScope.launch(context) {
handler(newText)
}
return returnValue
}
fun onQueryTextChange(
returnValue: Boolean = false,
listener: suspend CoroutineScope.(String?) -> Boolean
) {
_onQueryTextChange = listener
_onQueryTextChange_returnValue = returnValue
}
}fun android.support.v7.widget.SearchView.onSearchClick(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(v: android.view.View?) -> Unit
) {
setOnSearchClickListener { v ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(v)
}
}
}
fun android.support.v7.widget.SearchView.onSuggestionListener(
context: CoroutineContext = Dispatchers.Main,
init: __SearchView_OnSuggestionListener.() -> Unit
) {
val listener = __SearchView_OnSuggestionListener(context)
listener.init()
setOnSuggestionListener(listener)
}
class __SearchView_OnSuggestionListener(private val context: CoroutineContext) : android.support.v7.widget.SearchView.OnSuggestionListener {
private var _onSuggestionSelect: (suspend CoroutineScope.(Int) -> Boolean)? = null
private var _onSuggestionSelect_returnValue: Boolean = false
override fun onSuggestionSelect(position: Int) : Boolean {
val returnValue = _onSuggestionSelect_returnValue
val handler = _onSuggestionSelect ?: return returnValue
GlobalScope.launch(context) {
handler(position)
}
return returnValue
}
fun onSuggestionSelect(
returnValue: Boolean = false,
listener: suspend CoroutineScope.(Int) -> Boolean
) {
_onSuggestionSelect = listener
_onSuggestionSelect_returnValue = returnValue
}
private var _onSuggestionClick: (suspend CoroutineScope.(Int) -> Boolean)? = null
private var _onSuggestionClick_returnValue: Boolean = false
override fun onSuggestionClick(position: Int) : Boolean {
val returnValue = _onSuggestionClick_returnValue
val handler = _onSuggestionClick ?: return returnValue
GlobalScope.launch(context) {
handler(position)
}
return returnValue
}
fun onSuggestionClick(
returnValue: Boolean = false,
listener: suspend CoroutineScope.(Int) -> Boolean
) {
_onSuggestionClick = listener
_onSuggestionClick_returnValue = returnValue
}
}fun android.support.v7.widget.Toolbar.onMenuItemClick(
context: CoroutineContext = Dispatchers.Main,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(item: android.view.MenuItem?) -> Unit
) {
setOnMenuItemClickListener { item ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(item)
}
returnValue
}
}
fun android.support.v7.widget.ViewStubCompat.onInflate(
context: CoroutineContext = Dispatchers.Main,
handler: suspend CoroutineScope.(stub: android.support.v7.widget.ViewStubCompat?, inflated: android.view.View?) -> Unit
) {
setOnInflateListener { stub, inflated ->
GlobalScope.launch(context, CoroutineStart.DEFAULT) {
handler(stub, inflated)
}
}
}
| apache-2.0 | 0d13ad13d5cbc9d2bf51c944db3faa59 | 32.935961 | 140 | 0.688053 | 5.15258 | false | false | false | false |
sephiroth74/android-target-tooltip | xtooltip/src/main/java/it/sephiroth/android/library/xtooltip/TooltipOverlay.kt | 1 | 2294 | package it.sephiroth.android.library.xtooltip
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
/**
* Created by alessandro crugnola on 12/12/15.
* [email protected]
*
*
* LICENSE
* Copyright 2015 Alessandro Crugnola
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
* OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
class TooltipOverlay : AppCompatImageView {
private var layoutMargins: Int = 0
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = R.style.ToolTipOverlayDefaultStyle
) : super(context, attrs, defStyleAttr) {
init(context, R.style.ToolTipLayoutDefaultStyle)
}
private fun init(context: Context, defStyleResId: Int) {
val drawable = TooltipOverlayDrawable(context, defStyleResId)
setImageDrawable(drawable)
val array = context.theme.obtainStyledAttributes(defStyleResId, R.styleable.TooltipOverlay)
layoutMargins = array.getDimensionPixelSize(R.styleable.TooltipOverlay_android_layout_margin, 0)
array.recycle()
}
constructor(context: Context, defStyleAttr: Int, defStyleResId: Int) : super(context, null, defStyleAttr) {
init(context, defStyleResId)
}
} | mit | 2dc8714bf96911b966d3470607585ed9 | 44.9 | 130 | 0.745859 | 4.597194 | false | false | false | false |
kropp/intellij-makefile | src/main/kotlin/name/kropp/intellij/makefile/MakefileSyntaxHighlighter.kt | 1 | 4497 | package name.kropp.intellij.makefile
import com.intellij.openapi.editor.*
import com.intellij.openapi.editor.colors.*
import com.intellij.openapi.editor.colors.TextAttributesKey.*
import com.intellij.openapi.fileTypes.*
import com.intellij.psi.*
import com.intellij.psi.tree.*
import name.kropp.intellij.makefile.psi.*
class MakefileSyntaxHighlighter : SyntaxHighlighterBase() {
companion object {
val COMMENT = createTextAttributesKey("MAKEFILE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT)
val DOCCOMMENT = createTextAttributesKey("MAKEFILE_DOCCOMMENT", DefaultLanguageHighlighterColors.DOC_COMMENT)
val KEYWORD = createTextAttributesKey("MAKEFILE_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD)
val TARGET = createTextAttributesKey("MAKEFILE_TARGET", DefaultLanguageHighlighterColors.CLASS_NAME)
val SPECIAL_TARGET = createTextAttributesKey("MAKEFILE_SPECIAL_TARGET", DefaultLanguageHighlighterColors.PREDEFINED_SYMBOL)
val SEPARATOR = createTextAttributesKey("MAKEFILE_SEPARATOR", DefaultLanguageHighlighterColors.OPERATION_SIGN)
val PREREQUISITE = createTextAttributesKey("MAKEFILE_PREREQUISITE", DefaultLanguageHighlighterColors.INSTANCE_METHOD)
val VARIABLE = createTextAttributesKey("MAKEFILE_VARIABLE", DefaultLanguageHighlighterColors.GLOBAL_VARIABLE)
val VARIABLE_VALUE = createTextAttributesKey("MAKEFILE_VARIABLE_VALUE", DefaultLanguageHighlighterColors.STRING)
val STRING = createTextAttributesKey("MAKEFILE_STRING", DefaultLanguageHighlighterColors.STRING)
val LINE_SPLIT = createTextAttributesKey("MAKEFILE_LINE_SPLIT", DefaultLanguageHighlighterColors.VALID_STRING_ESCAPE)
val TAB = createTextAttributesKey("MAKEFILE_TAB", DefaultLanguageHighlighterColors.TEMPLATE_LANGUAGE_COLOR)
val FUNCTION = createTextAttributesKey("MAKEFILE_FUNCTION", DefaultLanguageHighlighterColors.KEYWORD)
val FUNCTION_PARAM = createTextAttributesKey("MAKEFILE_FUNCTION_PARAM", DefaultLanguageHighlighterColors.STRING)
val BRACES = createTextAttributesKey("MAKEFILE_BRACES", DefaultLanguageHighlighterColors.BRACES)
val PARENS = createTextAttributesKey("MAKEFILE_PARENTHESES", DefaultLanguageHighlighterColors.PARENTHESES)
/*
private fun braces(t: TextAttributesKey) {
t.foregroundColor = Color(0x00, 0x73, 0xbf)
}
*/
val BAD_CHARACTER = createTextAttributesKey("MAKEFILE_BAD_CHARACTER", HighlighterColors.BAD_CHARACTER)
private val BAD_CHAR_KEYS = arrayOf(BAD_CHARACTER)
private val SEPARATOR_KEYS = arrayOf(SEPARATOR)
private val KEYWORD_KEYS = arrayOf(KEYWORD)
private val TARGET_KEYS = arrayOf(TARGET)
private val PREREQUISITE_KEYS = arrayOf(PREREQUISITE)
private val VARIABLE_KEYS = arrayOf(VARIABLE)
private val VARIABLE_VALUE_KEYS = arrayOf(VARIABLE_VALUE)
private val STRING_KEYS = arrayOf(STRING)
private val LINE_SPLIT_KEYS = arrayOf(LINE_SPLIT)
private val TAB_KEYS = arrayOf(TAB)
private val COMMENT_KEYS = arrayOf(COMMENT)
private val DOCCOMMENT_KEYS = arrayOf(DOCCOMMENT)
private val BRACES_KEYS = arrayOf(BRACES, PARENS)
private val EMPTY_KEYS = emptyArray<TextAttributesKey>()
}
override fun getTokenHighlights(tokenType: IElementType) = when(tokenType) {
MakefileTypes.DOC_COMMENT -> DOCCOMMENT_KEYS
MakefileTypes.COMMENT -> COMMENT_KEYS
MakefileTypes.TARGET -> TARGET_KEYS
MakefileTypes.COLON, MakefileTypes.ASSIGN, MakefileTypes.SEMICOLON, MakefileTypes.PIPE -> SEPARATOR_KEYS
MakefileTypes.KEYWORD_INCLUDE, MakefileTypes.KEYWORD_IFEQ, MakefileTypes.KEYWORD_IFNEQ, MakefileTypes.KEYWORD_IFDEF,
MakefileTypes.KEYWORD_IFNDEF, MakefileTypes.KEYWORD_ELSE, MakefileTypes.KEYWORD_ENDIF, MakefileTypes.KEYWORD_DEFINE,
MakefileTypes.KEYWORD_ENDEF, MakefileTypes.KEYWORD_UNDEFINE, MakefileTypes.KEYWORD_OVERRIDE, MakefileTypes.KEYWORD_EXPORT,
MakefileTypes.KEYWORD_PRIVATE, MakefileTypes.KEYWORD_VPATH, MakefileTypes.DOLLAR -> KEYWORD_KEYS
MakefileTypes.PREREQUISITE -> PREREQUISITE_KEYS
MakefileTypes.VARIABLE -> VARIABLE_KEYS
MakefileTypes.VARIABLE_VALUE -> VARIABLE_VALUE_KEYS
MakefileTypes.SPLIT -> LINE_SPLIT_KEYS
MakefileTypes.TAB -> TAB_KEYS
MakefileTypes.STRING -> STRING_KEYS
MakefileTypes.OPEN_PAREN, MakefileTypes.CLOSE_PAREN, MakefileTypes.OPEN_CURLY, MakefileTypes.CLOSE_CURLY, MakefileTypes.BACKTICK -> BRACES_KEYS
TokenType.BAD_CHARACTER -> BAD_CHAR_KEYS
else -> EMPTY_KEYS
}
override fun getHighlightingLexer() = MakefileLexerAdapter()
} | mit | ddcf987ef7c71ee5d045dfe8cd40296c | 57.415584 | 147 | 0.796531 | 4.92552 | false | false | false | false |
SixCan/SixDaily | app/src/main/java/ca/six/daily/biz/detail/RvDetailsAdapter.kt | 1 | 3626 | package ca.six.daily.biz.detail
import android.content.Context
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import android.webkit.WebView
import android.widget.ImageView
import ca.six.daily.R
import ca.six.daily.data.DailyDetailResponse
import ca.six.daily.view.RvViewHolder
import com.squareup.picasso.Picasso
/**
* @author hellenxu
* @date 2017-07-17
* Copyright 2017 Six. All rights reserved.
*/
class RvDetailsAdapter(val ctx: Context, val ids: List<Long>, selectedId: Long, val layoutManager: LinearLayoutManager) :
RecyclerView.Adapter<RvViewHolder>(), IDailyDetailView {
private var data = ArrayList<DailyDetailResponse>()
private var dataRight : ArrayList<Long> = ArrayList<Long>()
private val presenter: DailyDetailPresenter = DailyDetailPresenter(this)
private var separatedPos: Int = 0
private var currentPos: Int = 0
private var refreshCount: Int = 0
private val emptyJsonStr = "{\"body\":\"\",\"image_source\":\"\",\"title\":\"\",\"image\":\"file path\",\"share_url\":\"\",\"js\":[],\"ga_prefix\":\"080219\",\"images\":[\"\"],\"type\":0,\"id\":0,\"css\":[\"\"]}"
init {
separatedPos = if (ids.indexOf(selectedId) > -1) ids.indexOf(selectedId) else 0
ids.subList(separatedPos, ids.size).forEach {
dataRight.add(it)
}
refreshCount = ids.size - dataRight.size
dataRight.forEach {
val item = DailyDetailResponse(emptyJsonStr)
data.add(item)
}
presenter.getDetails(selectedId)
}
override fun onBindViewHolder(holder: RvViewHolder, position: Int) {
val size = data.size
val banner = holder.getView<ImageView>(R.id.ivBanner)
val content = holder.getView<WebView>(R.id.wvContent)
content.settings.javaScriptEnabled = true
if (size > 0 && position < size) {
val item = data[position]
Picasso.with(ctx)
.load(item.image)
.error(R.drawable.loading_placeholder)
.placeholder(R.drawable.loading_placeholder)
.into(banner)
content.addJavascriptInterface(HtmlLoader(item.body, item.cssVer), "loader")
}
content.loadUrl("file:///android_asset/details.html")
}
override fun getItemCount(): Int {
return data.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RvViewHolder {
return RvViewHolder.createViewHolder(parent, R.layout.item_daily_details)
}
override fun updateDetails(details: DailyDetailResponse) {
data[currentPos] = details
notifyDataSetChanged()
}
fun changeCurrentPosition(pos: Int, isMoveEnd: Boolean) {
println("change-pos: $pos")
val selectedId: Long
if(isMoveEnd && pos == 0 && refreshCount > 0){
data.add(0, DailyDetailResponse(emptyJsonStr))
refreshCount -= 1
dataRight.add(0, ids[refreshCount])
selectedId = dataRight[0]
currentPos = 0
println("xxl-add")
} else {
selectedId = dataRight[pos]
currentPos = pos
println("xxl-read")
}
println("change-current pos:$currentPos")
println("change-selected: $selectedId")
var isCached = false
data.forEach {
if (it.id == selectedId) {
isCached = true
}
}
if (!isCached) {
presenter.getDetails(selectedId)
}
}
} | mpl-2.0 | b24a00fab4a0c3165d2b757366d63d33 | 34.558824 | 216 | 0.620518 | 4.400485 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/run/makeindex/MakeindexSettingsEditor.kt | 1 | 3793 | package nl.hannahsten.texifyidea.run.makeindex
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.fileChooser.FileTypeDescriptor
import com.intellij.openapi.options.SettingsEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.ui.*
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.ui.RawCommandLineEditor
import nl.hannahsten.texifyidea.run.compiler.MakeindexProgram
import javax.swing.JComponent
import javax.swing.JPanel
/**
* @author Thomas Schouten
*/
class MakeindexSettingsEditor(private val project: Project) : SettingsEditor<MakeindexRunConfiguration>() {
private lateinit var panel: JPanel
private lateinit var makeindexProgram: LabeledComponent<ComboBox<MakeindexProgram>>
private lateinit var mainFile: LabeledComponent<TextFieldWithBrowseButton>
private lateinit var commandLineArguments: LabeledComponent<RawCommandLineEditor>
private lateinit var workingDirectory: LabeledComponent<TextFieldWithBrowseButton>
override fun createEditor(): JComponent {
createUIComponents()
return panel
}
// Initialize editor from given run config
override fun resetEditorFrom(runConfig: MakeindexRunConfiguration) {
makeindexProgram.component.selectedItem = runConfig.makeindexProgram
mainFile.component.text = runConfig.mainFile?.path ?: ""
commandLineArguments.component.text = runConfig.commandLineArguments
workingDirectory.component.text = runConfig.workingDirectory?.path ?: ""
}
// Save user selected settings to the given run config
override fun applyEditorTo(runConfig: MakeindexRunConfiguration) {
runConfig.makeindexProgram = makeindexProgram.component.selectedItem as MakeindexProgram
runConfig.mainFile = LocalFileSystem.getInstance().findFileByPath(mainFile.component.text)
runConfig.commandLineArguments = commandLineArguments.component.text
runConfig.workingDirectory = LocalFileSystem.getInstance().findFileByPath(workingDirectory.component.text)
}
private fun createUIComponents() {
panel = JPanel().apply {
layout = VerticalFlowLayout(VerticalFlowLayout.TOP)
// Program
val programField = ComboBox<MakeindexProgram>(MakeindexProgram.values())
makeindexProgram = LabeledComponent.create(programField, "Index program")
add(makeindexProgram)
// Main file
val mainFileField = TextFieldWithBrowseButton().apply {
addBrowseFolderListener(
TextBrowseFolderListener(
FileTypeDescriptor("Choose the main .tex file", ".tex")
.withRoots(*ProjectRootManager.getInstance(project).contentRootsFromAllModules)
)
)
}
mainFile = LabeledComponent.create(mainFileField, "Main file which uses an index")
add(mainFile)
commandLineArguments = LabeledComponent.create(RawCommandLineEditor(), "Custom arguments")
add(commandLineArguments)
// Working directory
val workDirField = TextFieldWithBrowseButton().apply {
addBrowseFolderListener(
TextBrowseFolderListener(
FileChooserDescriptor(false, true, false, false, false, false)
.withTitle("Choose the directory where the index (.idx) file will be generated")
)
)
}
workingDirectory = LabeledComponent.create(workDirField, "Working directory for the index program")
add(workingDirectory)
}
}
}
| mit | 31b5e8808e637a87a25f4a60bfb9ea0f | 44.154762 | 114 | 0.703137 | 5.826421 | false | true | false | false |
ntlv/BasicLauncher2 | app/src/main/java/se/ntlv/basiclauncher/database/DbCleaner.kt | 1 | 2193 | package se.ntlv.basiclauncher.database
import android.app.Notification
import android.os.Bundle
import android.os.SystemClock
import com.google.android.gms.gcm.*
import org.jetbrains.anko.notificationManager
import se.ntlv.basiclauncher.R
import se.ntlv.basiclauncher.tag
import java.text.SimpleDateFormat
import java.util.concurrent.TimeUnit
class DbCleaner() : GcmTaskService() {
companion object {
private val SCHEDULED_AT_KEY = "SCHEDULED_AT_KEY"
private val TAG = tag()
fun ensureScheduled(args: Bundle, manager: GcmNetworkManager) {
val cleaningTask = PeriodicTask.Builder()
.setPeriod(TimeUnit.DAYS.toSeconds(1))
.setRequiredNetwork(Task.NETWORK_STATE_ANY)
.setRequiresCharging(false)
.setTag(DbCleaner.TAG)
.setExtras(args)
.setUpdateCurrent(false)
.setService(DbCleaner::class.java)
.build()
manager.schedule(cleaningTask)
}
fun makeArgs(scheduledAt: Long): Bundle {
val b = Bundle(1)
b.putLong(SCHEDULED_AT_KEY, scheduledAt)
return b
}
}
override fun onRunTask(params: TaskParams?): Int {
val scheduleTime = params?.extras?.get(SCHEDULED_AT_KEY) ?: 0
val dateFormat = SimpleDateFormat.getDateTimeInstance()
val formattedScheduleTime = dateFormat.format(scheduleTime)
val time = SystemClock.elapsedRealtime()
val formattedTriggerTime = dateFormat.format(time)
val notification = Notification.Builder(this)
.setSmallIcon(R.drawable.common_ic_googleplayservices)
.setStyle(Notification.BigTextStyle().bigText("Scheduled at $formattedScheduleTime, triggered at $formattedTriggerTime"))
.setContentTitle("DBCleaner")
.setContentText("Scheduled at $scheduleTime")
.build()
notificationManager.notify(1, notification)
doCleanup()
return GcmNetworkManager.RESULT_SUCCESS
}
private fun doCleanup() {
//do nothing for now
}
} | mit | dae1e1105ba207fc941a7ba1b7f05d75 | 31.264706 | 137 | 0.635659 | 4.75705 | false | false | false | false |
lightem90/Sismic | app/src/main/java/com/polito/sismic/Interactors/Helpers/SismicActionCalculatorHelper.kt | 1 | 13622 | package com.polito.sismic.Interactors.Helpers
import com.github.mikephil.charting.data.Entry
import com.polito.sismic.Domain.*
import com.polito.sismic.Extensions.interpolateWith
import com.polito.sismic.Extensions.toSpectrumPointList
/**
* Created by Matteo on 04/09/2017.
*/
//"Static" class, no memory, no states
class SismicActionCalculatorHelper(val mCoordinateHelper: ParametersForCoordinateHelper) {
companion object {
fun calculateQ0(typology: Int, alfa: Double = 1.0, cda: Boolean = true): Double {
return when (typology) {
0 -> if (cda) 4.5 * alfa else 3 * alfa
1 -> if (cda) 4 * alfa else 3.0
2 -> if (cda) 3.0 else 2.0
3 -> if (cda) 2.0 else 1.5
else -> 0.0
}
}
}
fun calculatePeriodsForSquare(nodeSquare: NeighboursNodeSquare): List<PeriodData> {
val neData = mCoordinateHelper.getRowDataForNode(nodeSquare.NE.id)
val seData = mCoordinateHelper.getRowDataForNode(nodeSquare.SE.id)
val soData = mCoordinateHelper.getRowDataForNode(nodeSquare.SO.id)
val noData = mCoordinateHelper.getRowDataForNode(nodeSquare.NO.id)
//Foreach TR (reference year, it gets the relatives index of sismic data in the db and calculates the data, using distance)
return TempiRitorno.values().map {
val triple = createTripleParameterFor(it, nodeSquare.NE.distance to neData,
nodeSquare.SE.distance to seData,
nodeSquare.SO.distance to soData,
nodeSquare.NO.distance to noData)
PeriodData(it.years, triple.first, triple.second, triple.third)
}
}
private fun createTripleParameterFor(tr: TempiRitorno,
neData: Pair<Double, Array<String>>,
seData: Pair<Double, Array<String>>,
soData: Pair<Double, Array<String>>,
noData: Pair<Double, Array<String>>)
: Triple<Double, Double, Double> {
//foreach year it return the 3 index in the db where to read
val sismicTripleForYear = YearToDatabaseParameterMapper.mapYearToSismicTriple(tr)
val sismicDataTriple = sismicTripleForYear.toList().map {
//ag/f0/tc* datas, neData.second is the array, it.ordinal is the index in the db for ag/f0/tc with year param, neData.first is the distance
createPeriodData(listOf(neData.second[it.ordinal].toDouble() to neData.first,
seData.second[it.ordinal].toDouble() to seData.first,
soData.second[it.ordinal].toDouble() to soData.first,
noData.second[it.ordinal].toDouble() to noData.first))
}
//0 -> ag 1 -> F0 2 -> Tc*
return Triple(sismicDataTriple[0] / 10, sismicDataTriple[1], sismicDataTriple[2])
}
//sum of each distance - weighted parameter divided by sum of inverse of distance
private fun createPeriodData(paramAndDistancePairList: List<Pair<Double, Double>>): Double {
val numerator = paramAndDistancePairList.sumByDouble { it.first / it.second }
val denominator = paramAndDistancePairList.sumByDouble { 1 / it.second }
return numerator / denominator
}
//Sismogenetic data: shows default period data straight read from database
fun getDefaultSpectrum(sismicState: ReportState): List<SpectrumDTO> {
val st = ZonaSismica.values()[sismicState.localizationState.zone_int - 1].multiplier
return sismicState.sismicState.sismogenticState.default_periods.map { period ->
val tr = TempiRitorno.values().first { it.years == period.years }
calculateSpectrumPointListFor(period.years.toString(), period.years, tr.color, period.ag, period.f0, period.tcstar, st)
}
}
//Sismicparameters data: shows periods based on life
fun getLimitStateSpectrum(sismicState: ReportState,
currentSismicState: SismicParametersState? = null,
currentProjectSpectrumState: ProjectSpectrumState? = null,
higherPrecision: Boolean = false): MutableList<SpectrumDTO> {
if (sismicState.sismicState.sismogenticState.default_periods.isEmpty()) return mutableListOf()
val vr = if (currentSismicState != null) currentSismicState.vitaRiferimento else sismicState.sismicState.sismicParametersState.vitaRiferimento
var categoria_sottosuolo = if (sismicState.sismicState.projectSpectrumState.categoria_suolo.isEmpty()) CategoriaSottosuolo.A
else CategoriaSottosuolo.values().first { it.toString() == sismicState.sismicState.projectSpectrumState.categoria_suolo }
var q = 1.0
var st = 1.0
currentProjectSpectrumState?.let { state ->
categoria_sottosuolo = CategoriaSottosuolo.values()
.first { it.toString() == state.categoria_suolo }
q = state.q0 * state.kr
st = state.categoria_topografica
}
// SLO, SLD, SLV, SLC
val limitStateYears = StatiLimite.values().map { calculateTrFor(vr, it) }
val spectrums: MutableList<SpectrumDTO> = mutableListOf()
limitStateYears.mapTo(spectrums) { limitState ->
when {
limitState.first <= TempiRitorno.Y30.years -> //Year lesser or equal 30, I use data from db
sismicState.sismicState.sismogenticState.default_periods[TempiRitorno.Y30.ordinal].let {
calculateSpectrumPointListFor(limitState.third, it.years, limitState.second, it.ag, it.f0, it.tcstar, st, q, categoria_sottosuolo, higherPrecision)
}
limitState.first >= TempiRitorno.Y2475.years -> //Year greater or equal 2475, I use data from db
sismicState.sismicState.sismogenticState.default_periods[TempiRitorno.Y2475.ordinal].let {
calculateSpectrumPointListFor(limitState.third, it.years, limitState.second, it.ag, it.f0, it.tcstar, st, q, categoria_sottosuolo, higherPrecision)
}
else -> {
//look for a year in the db, if it exist add it, otherwise need interpolation
val period = sismicState.sismicState.sismogenticState.default_periods.firstOrNull { it.years == limitState.first }
period?.let { p ->
calculateSpectrumPointListFor(limitState.third, p.years, limitState.second, p.ag, p.f0, p.tcstar, st, q, categoria_sottosuolo, higherPrecision)
} ?:
interpolatePeriodDataForYear(limitState.third, sismicState.sismicState.sismogenticState.default_periods, limitState.first, limitState.second, st, q, categoria_sottosuolo, higherPrecision)
}
}
}
return spectrums
}
private fun interpolatePeriodDataForYear(name: String, default_periods: List<PeriodData>, year: Int, color: Int, st: Double, q: Double, categoria_sottosuolo: CategoriaSottosuolo, higherPrecision: Boolean): SpectrumDTO {
val yearIndex = default_periods.indexOfFirst { it.years > year }
val interpolatedData = default_periods[yearIndex - 1].interpolateWith(default_periods[yearIndex], year)
return calculateSpectrumPointListFor(name, interpolatedData.years, color, interpolatedData.ag, interpolatedData.f0, interpolatedData.tcstar, st, q, categoria_sottosuolo, higherPrecision)
}
private fun calculateSpectrumPointListFor(name: String, year: Int, color: Int, ag: Double, f0: Double, tcStar: Double, st: Double, q: Double = 1.0, categoria_sottosuolo: CategoriaSottosuolo = CategoriaSottosuolo.A, higherPrecision: Boolean = false): SpectrumDTO {
val td = (4.0 * ag / 9.80665) + 1.6
val cc = if (categoria_sottosuolo == CategoriaSottosuolo.A) 1.0
else categoria_sottosuolo.multiplierCC * Math.pow(tcStar, categoria_sottosuolo.expCC)
val tc = cc * tcStar
val tb = tc / 3
val ss = calculateSs(ag, f0, categoria_sottosuolo)
val s = ss * st
val ni = 1 / q
//to avoid calculating it always
val repeatingTerm = ag * s * ni * f0
val entryPointList = mutableListOf<Entry>()
//linear between 0 and tb
entryPointList.addAll(calculateFirstLinearInterval(repeatingTerm, ni, f0, tb))
entryPointList.addAll(calculateSecondCostantInterval(repeatingTerm, tc))
entryPointList.addAll(calculateThirdHyperbolicInterval(repeatingTerm, tc, td, higherPrecision))
entryPointList.addAll(calculateFourthHyperbolicInterval(repeatingTerm, tc, td, higherPrecision))
return SpectrumDTO(name, year, color, ag, f0, tcStar, ss, cc, st, q, s, ni, tb, tc, td, entryPointList.toSpectrumPointList())
}
private fun calculateFourthHyperbolicInterval(repeatingTerm: Double, tc: Double, td: Double, higherPrecision: Boolean, limit: Double = 4.0): List<Entry> {
//ten steps
val sensibility = if (higherPrecision) 20 else 10
val step = (limit - td) / sensibility
var t = td
val pointsInFourthInterval = mutableListOf<Entry>()
while (t <= limit) {
pointsInFourthInterval.add(Entry(t.toFloat(), calculatePointForFourthInterval(repeatingTerm, t, tc, td)))
t += step
}
return pointsInFourthInterval
}
private fun calculatePointForFourthInterval(repeatingTerm: Double, t: Double, tc: Double, td: Double): Float {
return (repeatingTerm * ((tc * td) / Math.pow(t, 2.0))).toFloat()
}
private fun calculateThirdHyperbolicInterval(repeatingTerm: Double, tc: Double, td: Double, higherPrecision: Boolean): List<Entry> {
//ten steps
val sensibility = if (higherPrecision) 20 else 10
val step = (td - tc) / sensibility
var t = tc
val pointsInThirdInterval = mutableListOf<Entry>()
while (t <= td) {
pointsInThirdInterval.add(Entry(t.toFloat(), calculatePointForThirdInterval(repeatingTerm, t, tc)))
t += step
}
return pointsInThirdInterval
}
private fun calculatePointForThirdInterval(repeatingTerm: Double, t: Double, tc: Double): Float {
return (repeatingTerm * (tc / t)).toFloat()
}
//costant interval equals to repeating term
private fun calculateSecondCostantInterval(repeatingTerm: Double, tc: Double): List<Entry> {
return listOf(Entry(tc.toFloat(), repeatingTerm.toFloat()))
}
//linear interval, just 2 limitStatePoints
private fun calculateFirstLinearInterval(repeatingTerm: Double, ni: Double, f0: Double, tb: Double): List<Entry> {
return listOf(Entry(0.0F, calculatePointForFirstInterval(repeatingTerm, 0.0, tb, ni, f0)),
Entry(tb.toFloat(), calculatePointForFirstInterval(repeatingTerm, tb, tb, ni, f0)))
}
private fun calculatePointForFirstInterval(repeatingTerm: Double, t: Double, tb: Double, ni: Double, f0: Double): Float {
return (repeatingTerm * ((t / tb) + ((1 / (ni * f0)) * (1 - (t / tb))))).toFloat()
}
private fun calculateSs(ag: Double, f0: Double, cat: CategoriaSottosuolo): Double {
return when (cat) {
CategoriaSottosuolo.A -> 1.0
CategoriaSottosuolo.B -> 1.4 - 0.40 * f0 * (ag / 9.86065)
CategoriaSottosuolo.C -> 1.7 - 0.60 * f0 * (ag / 9.86065)
CategoriaSottosuolo.D -> 2.4 - 1.5 * f0 * (ag / 9.86065)
CategoriaSottosuolo.E -> 2.0 - 1.10 * f0 * (ag / 9.86065)
}
}
//Return time in years ?
private fun calculateTrFor(vr: Double, st: StatiLimite): Triple<Int, Int, String> {
val tr = -1 / (Math.log(1 - st.multiplier))
return Triple(Math.round((tr * vr)).toInt(), st.color, st.name)
}
}
class YearToDatabaseParameterMapper {
companion object {
fun mapYearToSismicTriple(trReference: TempiRitorno): Triple<CoordinateDatabaseParameters, CoordinateDatabaseParameters, CoordinateDatabaseParameters> {
return when (trReference) {
TempiRitorno.Y30 -> Triple(CoordinateDatabaseParameters.ag30, CoordinateDatabaseParameters.F030, CoordinateDatabaseParameters.Tc30)
TempiRitorno.Y50 -> Triple(CoordinateDatabaseParameters.ag50, CoordinateDatabaseParameters.F050, CoordinateDatabaseParameters.Tc50)
TempiRitorno.Y72 -> Triple(CoordinateDatabaseParameters.ag72, CoordinateDatabaseParameters.F072, CoordinateDatabaseParameters.Tc72)
TempiRitorno.Y101 -> Triple(CoordinateDatabaseParameters.ag101, CoordinateDatabaseParameters.F0101, CoordinateDatabaseParameters.Tc101)
TempiRitorno.Y140 -> Triple(CoordinateDatabaseParameters.ag140, CoordinateDatabaseParameters.F0140, CoordinateDatabaseParameters.Tc140)
TempiRitorno.Y201 -> Triple(CoordinateDatabaseParameters.ag201, CoordinateDatabaseParameters.F0201, CoordinateDatabaseParameters.Tc201)
TempiRitorno.Y475 -> Triple(CoordinateDatabaseParameters.ag475, CoordinateDatabaseParameters.F0475, CoordinateDatabaseParameters.Tc475)
TempiRitorno.Y975 -> Triple(CoordinateDatabaseParameters.ag975, CoordinateDatabaseParameters.F0975, CoordinateDatabaseParameters.Tc975)
TempiRitorno.Y2475 -> Triple(CoordinateDatabaseParameters.ag2475, CoordinateDatabaseParameters.F02475, CoordinateDatabaseParameters.Tc2475)
}
}
}
} | mit | 061182e088bb622193fa8048604d4375 | 53.710843 | 267 | 0.664734 | 3.936994 | false | false | false | false |
valerio-bozzolan/bus-torino | src/it/reyboz/bustorino/backend/mato/ResponseParsing.kt | 1 | 4397 | /*
BusTO - Backend components
Copyright (C) 2022 Fabio Mazza
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 it.reyboz.bustorino.backend.mato
import it.reyboz.bustorino.data.gtfs.*
import org.json.JSONObject
abstract class ResponseParsing{
companion object{
fun parseAgencyJSON(jsonObject: JSONObject): GtfsAgency {
return GtfsAgency(
jsonObject.getString("gtfsId"),
jsonObject.getString("name"),
jsonObject.getString("url"),
jsonObject.getString("fareUrl"),
jsonObject.getString("phone"),
null
)
}
/**
* Parse a feed request json, containing the GTFS agencies it is served by
*/
fun parseFeedJSON(jsonObject: JSONObject): Pair<GtfsFeed, ArrayList<GtfsAgency>> {
val agencies = ArrayList<GtfsAgency>()
val feed = GtfsFeed(jsonObject.getString("feedId"))
val oo = jsonObject.getJSONArray("agencies")
agencies.ensureCapacity(oo.length())
for (i in 0 until oo.length()){
val agObj = oo.getJSONObject(i)
agencies.add(
GtfsAgency(
agObj.getString("gtfsId"),
agObj.getString("name"),
agObj.getString("url"),
agObj.getString("fareUrl"),
agObj.getString("phone"),
feed
)
)
}
return Pair(feed, agencies)
}
fun parseRouteJSON(jsonObject: JSONObject): GtfsRoute {
val agencyJSON = jsonObject.getJSONObject("agency")
val agencyId = agencyJSON.getString("gtfsId")
return GtfsRoute(
jsonObject.getString("gtfsId"),
agencyId,
jsonObject.getString("shortName"),
jsonObject.getString("longName"),
jsonObject.getString("desc"),
GtfsMode.getByValue(jsonObject.getInt("type"))!!,
jsonObject.getString("color"),
jsonObject.getString("textColor")
)
}
/**
* Parse a route pattern from the JSON response of the MaTO server
*/
fun parseRoutePatternsStopsJSON(jsonObject: JSONObject) : ArrayList<MatoPattern>{
val routeGtfsId = jsonObject.getString("gtfsId")
val patternsJSON = jsonObject.getJSONArray("patterns")
val patternsOut = ArrayList<MatoPattern>(patternsJSON.length())
var mPatternJSON: JSONObject
for(i in 0 until patternsJSON.length()){
mPatternJSON = patternsJSON.getJSONObject(i)
val stopsJSON = mPatternJSON.getJSONArray("stops")
val stopsCodes = ArrayList<String>(stopsJSON.length())
for(k in 0 until stopsJSON.length()){
stopsCodes.add(
stopsJSON.getJSONObject(k).getString("gtfsId")
)
}
val geometry = mPatternJSON.getJSONObject("patternGeometry")
val numGeo = geometry.getInt("length")
val polyline = geometry.getString("points")
patternsOut.add(
MatoPattern(
mPatternJSON.getString("name"), mPatternJSON.getString("code"),
mPatternJSON.getString("semanticHash"), mPatternJSON.getInt("directionId"),
routeGtfsId,mPatternJSON.getString("headsign"), polyline, numGeo, stopsCodes
)
)
}
return patternsOut
}
}
} | gpl-3.0 | 009f83224908ad53672a9ed68656c731 | 35.65 | 100 | 0.564703 | 5.253286 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/gui/video/VideoGridFragment.kt | 1 | 26020 | /*****************************************************************************
* VideoGridFragment.kt
*
* Copyright © 2019 VLC authors and VideoLAN
*
* 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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*/
package org.videolan.vlc.gui.video
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import android.view.*
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.view.ActionMode
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.paging.PagedList
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.onEach
import org.videolan.medialibrary.interfaces.Medialibrary
import org.videolan.medialibrary.interfaces.media.Folder
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.medialibrary.interfaces.media.VideoGroup
import org.videolan.medialibrary.media.FolderImpl
import org.videolan.medialibrary.media.MediaLibraryItem
import org.videolan.resources.*
import org.videolan.tools.*
import org.videolan.vlc.R
import org.videolan.vlc.databinding.VideoGridBinding
import org.videolan.vlc.gui.ContentActivity
import org.videolan.vlc.gui.SecondaryActivity
import org.videolan.vlc.gui.browser.MediaBrowserFragment
import org.videolan.vlc.gui.dialogs.CtxActionReceiver
import org.videolan.vlc.gui.dialogs.RenameDialog
import org.videolan.vlc.gui.dialogs.SavePlaylistDialog
import org.videolan.vlc.gui.dialogs.showContext
import org.videolan.vlc.gui.helpers.ItemOffsetDecoration
import org.videolan.vlc.gui.helpers.UiTools
import org.videolan.vlc.gui.helpers.UiTools.addToGroup
import org.videolan.vlc.gui.helpers.UiTools.addToPlaylist
import org.videolan.vlc.gui.view.EmptyLoadingState
import org.videolan.vlc.media.MediaUtils
import org.videolan.vlc.media.PlaylistManager
import org.videolan.vlc.media.getAll
import org.videolan.vlc.providers.medialibrary.VideosProvider
import org.videolan.vlc.reloadLibrary
import org.videolan.vlc.util.launchWhenStarted
import org.videolan.vlc.util.share
import org.videolan.vlc.viewmodels.mobile.VideoGroupingType
import org.videolan.vlc.viewmodels.mobile.VideosViewModel
import org.videolan.vlc.viewmodels.mobile.getViewModel
import java.util.*
private const val TAG = "VLC/VideoListFragment"
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
class VideoGridFragment : MediaBrowserFragment<VideosViewModel>(), SwipeRefreshLayout.OnRefreshListener, CtxActionReceiver {
private lateinit var videoListAdapter: VideoListAdapter
private lateinit var multiSelectHelper: MultiSelectHelper<MediaLibraryItem>
private lateinit var binding: VideoGridBinding
private var gridItemDecoration: RecyclerView.ItemDecoration? = null
private lateinit var settings: SharedPreferences
private fun FragmentActivity.open(item: MediaLibraryItem) {
val i = Intent(activity, SecondaryActivity::class.java)
i.putExtra("fragment", SecondaryActivity.VIDEO_GROUP_LIST)
if (item is Folder) i.putExtra(KEY_FOLDER, item)
else if (item is VideoGroup) i.putExtra(KEY_GROUP, item)
startActivityForResult(i, SecondaryActivity.ACTIVITY_RESULT_SECONDARY)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!::settings.isInitialized) settings = Settings.getInstance(requireContext())
if (!::videoListAdapter.isInitialized) {
val seenMarkVisible = settings.getBoolean("media_seen", true)
videoListAdapter = VideoListAdapter(seenMarkVisible)
multiSelectHelper = videoListAdapter.multiSelectHelper
val folder = if (savedInstanceState != null) savedInstanceState.getParcelable<Folder>(KEY_FOLDER)
else arguments?.getParcelable(KEY_FOLDER)
val group = if (savedInstanceState != null) savedInstanceState.getParcelable<VideoGroup>(KEY_GROUP)
else arguments?.getParcelable(KEY_GROUP)
val grouping = arguments?.getSerializable(KEY_GROUPING) as VideoGroupingType? ?: VideoGroupingType.NONE
viewModel = getViewModel(grouping, folder, group)
setDataObservers()
Medialibrary.lastThumb.observe(this, thumbObs)
videoListAdapter.events.onEach { it.process() }.launchWhenStarted(lifecycleScope)
}
}
private fun setDataObservers() {
videoListAdapter.dataType = viewModel.groupingType
viewModel.provider.pagedList.observe(requireActivity(), Observer {
(it as? PagedList<MediaLibraryItem>)?.let { videoListAdapter.submitList(it) }
updateEmptyView()
restoreMultiSelectHelper()
if (viewModel.group != null && it.size < 2) requireActivity().finish()
})
viewModel.provider.loading.observe(this, Observer { loading ->
setRefreshing(loading) { refresh ->
if (!refresh) {
setFabPlayVisibility(true)
menu?.let { UiTools.updateSortTitles(it, viewModel.provider) }
restoreMultiSelectHelper()
}
}
})
videoListAdapter.showFilename.set(viewModel.groupingType == VideoGroupingType.NONE && viewModel.provider.sort == Medialibrary.SORT_FILENAME)
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
menu.findItem(R.id.ml_menu_last_playlist).isVisible = settings.contains(KEY_MEDIA_LAST_PLAYLIST)
menu.findItem(R.id.ml_menu_video_group).isVisible = viewModel.group == null && viewModel.folder == null
val displayInCards = settings.getBoolean("video_display_in_cards", true)
menu.findItem(R.id.ml_menu_display_grid).isVisible = !displayInCards
menu.findItem(R.id.ml_menu_display_list).isVisible = displayInCards
menu.findItem(R.id.rename_group).isVisible = viewModel.group != null
menu.findItem(R.id.ungroup).isVisible = viewModel.group != null
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.ml_menu_last_playlist -> {
MediaUtils.loadlastPlaylist(activity, PLAYLIST_TYPE_VIDEO)
true
}
R.id.ml_menu_display_list, R.id.ml_menu_display_grid -> {
val displayInCards = settings.getBoolean("video_display_in_cards", true)
settings.putSingle("video_display_in_cards", !displayInCards)
(activity as ContentActivity).forceLoadVideoFragment()
true
}
R.id.video_min_group_length_disable -> {
lifecycleScope.launchWhenStarted {
withContext(Dispatchers.IO) {
settings.edit().putString("video_min_group_length", "-1").commit()
}
changeGroupingType(VideoGroupingType.NONE)
}
true
}
R.id.video_min_group_length_folder -> {
lifecycleScope.launchWhenStarted {
withContext(Dispatchers.IO) {
settings.edit().putString("video_min_group_length", "0").commit()
}
changeGroupingType(VideoGroupingType.FOLDER)
}
true
}
R.id.video_min_group_length_name -> {
lifecycleScope.launchWhenStarted {
withContext(Dispatchers.IO) {
settings.edit().putString("video_min_group_length", "6").commit()
}
changeGroupingType(VideoGroupingType.NAME)
}
true
}
R.id.rename_group -> {
viewModel.group?.let { renameGroup(it) }
true
}
R.id.ungroup -> {
viewModel.group?.let { viewModel.ungroup(it) }
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun sortBy(sort: Int) {
videoListAdapter.showFilename.set(sort == Medialibrary.SORT_FILENAME)
super.sortBy(sort)
}
private fun changeGroupingType(type: VideoGroupingType) {
viewModel.provider.pagedList.removeObservers(this)
viewModel.provider.loading.removeObservers(this)
viewModel.changeGroupingType(type)
setDataObservers()
(activity as? AppCompatActivity)?.run {
supportActionBar?.title = title
invalidateOptionsMenu()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = VideoGridBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val empty = viewModel.isEmpty()
binding.emptyLoading.state = if (empty) EmptyLoadingState.LOADING else EmptyLoadingState.NONE
binding.empty = empty
binding.emptyLoading.setOnNoMediaClickListener {
requireActivity().setResult(RESULT_RESTART)
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
swipeRefreshLayout.setOnRefreshListener(this)
binding.videoGrid.adapter = videoListAdapter
}
override fun onStart() {
super.onStart()
registerForContextMenu(binding.videoGrid)
updateViewMode()
setFabPlayVisibility(true)
fabPlay?.setImageResource(R.drawable.ic_fab_play)
if (!viewModel.isEmpty() && getFilterQuery() == null) viewModel.refresh()
}
override fun onStop() {
super.onStop()
unregisterForContextMenu(binding.videoGrid)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putParcelable(KEY_FOLDER, viewModel.folder)
outState.putParcelable(KEY_GROUP, viewModel.group)
outState.putSerializable(KEY_GROUPING, viewModel.groupingType)
}
override fun onDestroy() {
super.onDestroy()
videoListAdapter.release()
gridItemDecoration = null
}
override fun getTitle() = when(viewModel.groupingType) {
VideoGroupingType.NONE -> viewModel.folder?.displayTitle ?: viewModel.group?.displayTitle
?: getString(R.string.videos)
VideoGroupingType.FOLDER -> getString(R.string.videos_folders_title)
VideoGroupingType.NAME -> getString(R.string.videos_groups_title)
}
override fun getMultiHelper(): MultiSelectHelper<VideosViewModel>? = if (::videoListAdapter.isInitialized) videoListAdapter.multiSelectHelper as? MultiSelectHelper<VideosViewModel> else null
private fun updateViewMode() {
if (view == null || activity == null) {
Log.w(TAG, "Unable to setup the view")
return
}
val res = resources
if (gridItemDecoration == null)
gridItemDecoration = ItemOffsetDecoration(resources, R.dimen.left_right_1610_margin, R.dimen.top_bottom_1610_margin)
val listMode = !settings.getBoolean("video_display_in_cards", true)
// Select between grid or list
binding.videoGrid.removeItemDecoration(gridItemDecoration!!)
if (!listMode) {
val thumbnailWidth = res.getDimensionPixelSize(R.dimen.grid_card_thumb_width)
val margin = binding.videoGrid.paddingStart + binding.videoGrid.paddingEnd
val columnWidth = binding.videoGrid.getPerfectColumnWidth(thumbnailWidth, margin) - res.getDimensionPixelSize(R.dimen.left_right_1610_margin) * 2
binding.videoGrid.columnWidth = columnWidth
videoListAdapter.setGridCardWidth(binding.videoGrid.columnWidth)
binding.videoGrid.addItemDecoration(gridItemDecoration!!)
}
binding.videoGrid.setNumColumns(if (listMode) 1 else -1)
if (videoListAdapter.isListMode != listMode) videoListAdapter.isListMode = listMode
}
override fun onFabPlayClick(view: View) {
viewModel.playAll(activity)
}
private fun updateEmptyView() {
if (!::binding.isInitialized) return
val empty = viewModel.isEmpty() && videoListAdapter.currentList.isNullOrEmpty()
val working = viewModel.provider.loading.value != false
binding.emptyLoading.state = when {
empty && working -> EmptyLoadingState.LOADING
empty && !working -> EmptyLoadingState.EMPTY
else -> EmptyLoadingState.NONE
}
binding.empty = empty && !working
}
override fun onRefresh() {
activity?.reloadLibrary()
}
override fun setFabPlayVisibility(enable: Boolean) {
super.setFabPlayVisibility(!viewModel.isEmpty() && enable)
}
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
when (viewModel.groupingType) {
VideoGroupingType.NONE -> mode.menuInflater.inflate(R.menu.action_mode_video, menu)
VideoGroupingType.FOLDER -> mode.menuInflater.inflate(R.menu.action_mode_folder, menu)
VideoGroupingType.NAME -> mode.menuInflater.inflate(R.menu.action_mode_video_group, menu)
}
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
val count = multiSelectHelper.getSelectionCount()
if (count == 0) {
stopActionMode()
return false
}
when (viewModel.groupingType) {
VideoGroupingType.NONE -> {
menu.findItem(R.id.action_video_append).isVisible = PlaylistManager.hasMedia()
menu.findItem(R.id.action_video_info).isVisible = count == 1
menu.findItem(R.id.action_remove_from_group).isVisible = viewModel.group != null
}
VideoGroupingType.NAME -> {
menu.findItem(R.id.action_ungroup).isVisible = !multiSelectHelper.getSelection().any { it !is VideoGroup }
menu.findItem(R.id.action_rename).isVisible = count == 1 && !multiSelectHelper.getSelection().any { it !is VideoGroup }
menu.findItem(R.id.action_group_similar).isVisible = count == 1 && multiSelectHelper.getSelection().filterIsInstance<VideoGroup>().isEmpty()
menu.findItem(R.id.action_add_to_group).isVisible = multiSelectHelper.getSelection().filterIsInstance<VideoGroup>().isEmpty()
}
else -> {}
}
return true
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
if (!isStarted()) return false
when (viewModel.groupingType) {
VideoGroupingType.NONE -> {
val list = multiSelectHelper.getSelection().map { it as MediaWrapper }
if (list.isNotEmpty()) {
when (item.itemId) {
R.id.action_video_play -> MediaUtils.openList(activity, list, 0)
R.id.action_video_append -> MediaUtils.appendMedia(activity, list)
R.id.action_video_share -> requireActivity().share(list)
R.id.action_video_info -> showInfoDialog(list[0])
// case R.id.action_video_delete:
// for (int position : rowsAdapter.getSelectedPositions())
// removeVideo(position, rowsAdapter.getItem(position));
// break;
R.id.action_video_download_subtitles -> MediaUtils.getSubs(requireActivity(), list)
R.id.action_video_play_audio -> {
for (media in list) media.addFlags(MediaWrapper.MEDIA_FORCE_AUDIO)
MediaUtils.openList(activity, list, 0)
}
R.id.action_mode_audio_add_playlist -> requireActivity().addToPlaylist(list)
R.id.action_video_delete -> removeItems(list)
R.id.action_remove_from_group -> viewModel.removeFromGroup(list)
R.id.action_ungroup -> viewModel.ungroup(list)
else -> {
stopActionMode()
return false
}
}
}
}
VideoGroupingType.FOLDER -> {
val selection = ArrayList<Folder>()
for (mediaLibraryItem in multiSelectHelper.getSelection()) {
selection.add(mediaLibraryItem as FolderImpl)
}
when (item.itemId) {
R.id.action_folder_play -> viewModel.playFoldersSelection(selection)
R.id.action_folder_append -> viewModel.appendFoldersSelection(selection)
R.id.action_folder_add_playlist -> lifecycleScope.launch { requireActivity().addToPlaylist(withContext(Dispatchers.Default) { selection.getAll() }) }
else -> return false
}
}
VideoGroupingType.NAME -> {
val selection = multiSelectHelper.getSelection()
when (item.itemId) {
R.id.action_videogroup_play -> MediaUtils.openList(activity, selection.getAll(), 0)
R.id.action_videogroup_append -> MediaUtils.appendMedia(activity, selection.getAll())
R.id.action_videogroup_add_playlist -> lifecycleScope.launch { requireActivity().addToPlaylist(withContext(Dispatchers.Default) { selection.getAll() }) }
R.id.action_group_similar -> lifecycleScope.launch { viewModel.groupSimilar(selection.getAll().first()) }
R.id.action_ungroup -> viewModel.ungroup(selection.first() as VideoGroup)
R.id.action_rename -> renameGroup(selection.first() as VideoGroup)
R.id.action_add_to_group -> lifecycleScope.launch {
if (selection.size > 1) {
viewModel.createGroup(selection.getAll())?.let {
activity?.open(it)
}
} else requireActivity().addToGroup(selection.getAll())
}
else -> return false
}
}
}
stopActionMode()
return true
}
override fun onDestroyActionMode(mode: ActionMode) {
actionMode = null
setFabPlayVisibility(true)
multiSelectHelper.clearSelection()
}
fun updateSeenMediaMarker() {
videoListAdapter.setSeenMediaMarkerVisible(settings.getBoolean("media_seen", true))
videoListAdapter.notifyItemRangeChanged(0, videoListAdapter.itemCount - 1, UPDATE_SEEN)
}
override fun onCtxAction(position: Int, option: Long) {
if (position >= videoListAdapter.itemCount) return
val activity = activity ?: return
when (val media = videoListAdapter.getItem(position)) {
is MediaWrapper -> when (option) {
CTX_PLAY_FROM_START -> viewModel.playVideo(activity, media, position, true)
CTX_PLAY_AS_AUDIO -> viewModel.playAudio(activity, media)
CTX_PLAY_ALL -> viewModel.play(position)
CTX_INFORMATION -> showInfoDialog(media)
CTX_DELETE -> removeItem(media)
CTX_APPEND -> MediaUtils.appendMedia(activity, media)
CTX_PLAY_NEXT -> MediaUtils.insertNext(requireActivity(), media.tracks)
CTX_DOWNLOAD_SUBTITLES -> MediaUtils.getSubs(requireActivity(), media)
CTX_ADD_TO_PLAYLIST -> requireActivity().addToPlaylist(media.tracks, SavePlaylistDialog.KEY_NEW_TRACKS)
CTX_FIND_METADATA -> {
val intent = Intent().apply {
setClassName(requireContext().applicationContext, MOVIEPEDIA_ACTIVITY)
apply { putExtra(MOVIEPEDIA_MEDIA, media) }
}
startActivity(intent)
}
CTX_SHARE -> lifecycleScope.launch { (requireActivity() as AppCompatActivity).share(media) }
CTX_REMOVE_GROUP -> viewModel.removeFromGroup(media)
CTX_ADD_GROUP -> requireActivity().addToGroup(listOf(media))
CTX_GROUP_SIMILAR -> lifecycleScope.launch { viewModel.groupSimilar(media) }
}
is Folder -> when (option) {
CTX_PLAY -> viewModel.play(position)
CTX_APPEND -> viewModel.append(position)
CTX_ADD_TO_PLAYLIST -> viewModel.addItemToPlaylist(requireActivity(), position)
}
is VideoGroup -> when (option) {
CTX_PLAY -> viewModel.play(position)
CTX_APPEND -> viewModel.append(position)
CTX_ADD_TO_PLAYLIST -> viewModel.addItemToPlaylist(requireActivity(), position)
CTX_RENAME_GROUP -> renameGroup(media)
CTX_UNGROUP -> viewModel.ungroup(media)
}
}
}
private fun renameGroup(media: VideoGroup) {
RenameDialog.newInstance(media) { newName ->
viewModel.renameGroup(media, newName)
(activity as? AppCompatActivity)?.run {
supportActionBar?.title = newName
}
}.show(requireActivity().supportFragmentManager, RenameDialog::class.simpleName)
}
private val thumbObs = Observer<MediaWrapper> { media ->
if (!::videoListAdapter.isInitialized || viewModel.provider !is VideosProvider) return@Observer
val position = viewModel.provider.pagedList.value?.indexOf(media) ?: return@Observer
val item = videoListAdapter.getItem(position) as? MediaWrapper
item?.run {
artworkURL = media.artworkURL
videoListAdapter.notifyItemChanged(position)
}
}
private fun VideoAction.process() {
when (this) {
is VideoClick -> {
onClick(position, item)
}
is VideoLongClick -> {
onLongClick(position)
}
is VideoCtxClick -> {
when (item) {
is Folder -> showContext(requireActivity(), this@VideoGridFragment, position, item.title, CTX_FOLDER_FLAGS)
is VideoGroup -> showContext(requireActivity(), this@VideoGridFragment, position, item.title, CTX_FOLDER_FLAGS or CTX_RENAME_GROUP or CTX_UNGROUP)
is MediaWrapper -> {
val group = item.type == MediaWrapper.TYPE_GROUP
var flags = if (group) CTX_VIDEO_GROUP_FLAGS else CTX_VIDEO_FLAGS
if (item.time != 0L && !group) flags = flags or CTX_PLAY_FROM_START
if (viewModel.groupingType == VideoGroupingType.NAME || viewModel.group != null) flags = flags or if (viewModel.group != null) CTX_REMOVE_GROUP else flags or CTX_ADD_GROUP or CTX_GROUP_SIMILAR
showContext(requireActivity(), this@VideoGridFragment, position, item.getTitle(), flags)
}
}
}
is VideoImageClick -> {
if (actionMode != null) {
onClick(position, item)
} else {
onLongClick(position)
}
}
}
}
private fun onLongClick(position: Int) {
multiSelectHelper.toggleSelection(position, true)
if (actionMode == null) startActionMode()
}
private fun onClick(position: Int, item: MediaLibraryItem) {
when (item) {
is MediaWrapper -> {
if (actionMode != null) {
multiSelectHelper.toggleSelection(position)
invalidateActionMode()
} else {
viewModel.playVideo(activity, item, position)
}
}
is Folder -> {
if (actionMode != null) {
multiSelectHelper.toggleSelection(position)
invalidateActionMode()
} else activity?.open(item)
}
is VideoGroup -> when {
actionMode != null -> {
multiSelectHelper.toggleSelection(position)
invalidateActionMode()
}
item.mediaCount() == 1 -> viewModel.play(position)
else -> activity?.open(item)
}
}
}
}
sealed class VideoAction
class VideoClick(val position: Int, val item: MediaLibraryItem) : VideoAction()
class VideoLongClick(val position: Int, val item: MediaLibraryItem) : VideoAction()
class VideoCtxClick(val position: Int, val item: MediaLibraryItem) : VideoAction()
class VideoImageClick(val position: Int, val item: MediaLibraryItem) : VideoAction()
| gpl-2.0 | 7139ec106eba41c33348a3a574dd3e36 | 45.965704 | 216 | 0.626158 | 4.996927 | false | false | false | false |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/tools/places/RenameFileTask.kt | 1 | 1538 | /*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.tools.places
import uk.co.nickthecoder.paratask.AbstractTask
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.parameters.FileParameter
import uk.co.nickthecoder.paratask.parameters.StringParameter
import uk.co.nickthecoder.paratask.util.process.Exec
import uk.co.nickthecoder.paratask.util.process.OSCommand
import java.io.File
class RenameFileTask : AbstractTask() {
override val taskD = TaskDescription("renameFile")
val fileP = FileParameter("file", mustExist = true)
val newNameP = StringParameter("newName")
init {
fileP.enabled = false
taskD.addParameters(fileP, newNameP)
}
override fun run() {
val command = OSCommand("mv", "--", fileP.value, File(fileP.value!!.parentFile, newNameP.value))
Exec(command).start().waitFor()
}
}
| gpl-3.0 | c777b3235587ed1bca52abb3e1402642 | 33.177778 | 104 | 0.759428 | 4.168022 | false | false | false | false |
cashapp/sqldelight | extensions/rxjava2-extensions/src/test/kotlin/app/cash/sqldelight/rx2/TestDb.kt | 1 | 4330 | package app.cash.sqldelight.rx2
import app.cash.sqldelight.Query
import app.cash.sqldelight.TransacterImpl
import app.cash.sqldelight.db.QueryResult
import app.cash.sqldelight.db.SqlCursor
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver
import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver.Companion.IN_MEMORY
import app.cash.sqldelight.rx2.Employee.Companion
import app.cash.sqldelight.rx2.TestDb.Companion.TABLE_EMPLOYEE
import app.cash.sqldelight.rx2.TestDb.Companion.TABLE_MANAGER
class TestDb(
val db: SqlDriver = JdbcSqliteDriver(IN_MEMORY),
) : TransacterImpl(db) {
var aliceId: Long = 0
var bobId: Long = 0
var eveId: Long = 0
init {
db.execute(null, "PRAGMA foreign_keys=ON", 0)
db.execute(null, CREATE_EMPLOYEE, 0)
aliceId = employee(Employee("alice", "Alice Allison"))
bobId = employee(Employee("bob", "Bob Bobberson"))
eveId = employee(Employee("eve", "Eve Evenson"))
db.execute(null, CREATE_MANAGER, 0)
manager(eveId, aliceId)
}
fun <T : Any> createQuery(key: String, query: String, mapper: (SqlCursor) -> T): Query<T> {
return object : Query<T>(mapper) {
override fun <R> execute(mapper: (SqlCursor) -> R): QueryResult<R> {
return db.executeQuery(null, query, mapper, 0)
}
override fun addListener(listener: Listener) {
db.addListener(listener, arrayOf(key))
}
override fun removeListener(listener: Listener) {
db.removeListener(listener, arrayOf(key))
}
}
}
fun notify(key: String) {
db.notifyListeners(arrayOf(key))
}
fun close() {
db.close()
}
fun employee(employee: Employee): Long {
db.execute(
0,
"""
|INSERT OR FAIL INTO $TABLE_EMPLOYEE (${app.cash.sqldelight.rx2.Employee.USERNAME}, ${app.cash.sqldelight.rx2.Employee.NAME})
|VALUES (?, ?)
|
""".trimMargin(),
2,
) {
bindString(0, employee.username)
bindString(1, employee.name)
}
notify(TABLE_EMPLOYEE)
return db.executeQuery(2, "SELECT last_insert_rowid()", ::getLong, 0).value
}
fun manager(
employeeId: Long,
managerId: Long,
): Long {
db.execute(
1,
"""
|INSERT OR FAIL INTO $TABLE_MANAGER (${Manager.EMPLOYEE_ID}, ${Manager.MANAGER_ID})
|VALUES (?, ?)
|
""".trimMargin(),
2,
) {
bindLong(0, employeeId)
bindLong(1, managerId)
}
notify(TABLE_MANAGER)
return db.executeQuery(2, "SELECT last_insert_rowid()", ::getLong, 0).value
}
companion object {
const val TABLE_EMPLOYEE = "employee"
const val TABLE_MANAGER = "manager"
val CREATE_EMPLOYEE = """
|CREATE TABLE $TABLE_EMPLOYEE (
| ${app.cash.sqldelight.rx2.Employee.ID} INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
| ${app.cash.sqldelight.rx2.Employee.USERNAME} TEXT NOT NULL UNIQUE,
| ${app.cash.sqldelight.rx2.Employee.NAME} TEXT NOT NULL
|)
""".trimMargin()
val CREATE_MANAGER = """
|CREATE TABLE $TABLE_MANAGER (
| ${Manager.ID} INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
| ${Manager.EMPLOYEE_ID} INTEGER NOT NULL UNIQUE REFERENCES $TABLE_EMPLOYEE(${app.cash.sqldelight.rx2.Employee.ID}),
| ${Manager.MANAGER_ID} INTEGER NOT NULL REFERENCES $TABLE_EMPLOYEE(${app.cash.sqldelight.rx2.Employee.ID})
|)
""".trimMargin()
}
}
object Manager {
const val ID = "id"
const val EMPLOYEE_ID = "employee_id"
const val MANAGER_ID = "manager_id"
val SELECT_MANAGER_LIST = """
|SELECT e.${Companion.NAME}, m.${Companion.NAME}
|FROM $TABLE_MANAGER AS manager
|JOIN $TABLE_EMPLOYEE AS e
|ON manager.$EMPLOYEE_ID = e.${Companion.ID}
|JOIN $TABLE_EMPLOYEE AS m
|ON manager.$MANAGER_ID = m.${Companion.ID}
|
""".trimMargin()
}
data class Employee(val username: String, val name: String) {
companion object {
const val ID = "id"
const val USERNAME = "username"
const val NAME = "name"
const val SELECT_EMPLOYEES = "SELECT $USERNAME, $NAME FROM $TABLE_EMPLOYEE"
@JvmField
val MAPPER = { cursor: SqlCursor ->
Employee(cursor.getString(0)!!, cursor.getString(1)!!)
}
}
}
private fun getLong(cursor: SqlCursor): Long {
check(cursor.next())
return cursor.getLong(0)!!
}
| apache-2.0 | 8fd795442872ae01d49aeb959ee967d1 | 27.866667 | 131 | 0.652656 | 3.638655 | false | false | false | false |
stripe/stripe-android | paymentsheet/src/main/java/com/stripe/android/paymentsheet/viewmodels/PaymentOptionsStateMapper.kt | 1 | 2223 | package com.stripe.android.paymentsheet.viewmodels
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.distinctUntilChanged
import com.stripe.android.model.PaymentMethod
import com.stripe.android.paymentsheet.PaymentOptionsState
import com.stripe.android.paymentsheet.PaymentOptionsStateFactory
import com.stripe.android.paymentsheet.model.PaymentSelection
import com.stripe.android.paymentsheet.model.SavedSelection
internal class PaymentOptionsStateMapper(
private val paymentMethods: LiveData<List<PaymentMethod>>,
private val isGooglePayReady: LiveData<Boolean>,
private val isLinkEnabled: LiveData<Boolean>,
private val initialSelection: LiveData<SavedSelection>,
private val currentSelection: LiveData<PaymentSelection?>,
private val isNotPaymentFlow: Boolean,
) {
operator fun invoke(): LiveData<PaymentOptionsState> {
return MediatorLiveData<PaymentOptionsState>().apply {
listOf(
paymentMethods,
currentSelection,
initialSelection,
isGooglePayReady,
isLinkEnabled,
).forEach { source ->
addSource(source) {
val newState = createPaymentOptionsState()
if (newState != null) {
value = newState
}
}
}
}.distinctUntilChanged()
}
@Suppress("ReturnCount")
private fun createPaymentOptionsState(): PaymentOptionsState? {
val paymentMethods = paymentMethods.value ?: return null
val initialSelection = initialSelection.value ?: return null
val isGooglePayReady = isGooglePayReady.value ?: return null
val isLinkEnabled = isLinkEnabled.value ?: return null
val currentSelection = currentSelection.value
return PaymentOptionsStateFactory.create(
paymentMethods = paymentMethods,
showGooglePay = isGooglePayReady && isNotPaymentFlow,
showLink = isLinkEnabled && isNotPaymentFlow,
initialSelection = initialSelection,
currentSelection = currentSelection,
)
}
}
| mit | 7fe90fd44b9ad3b2cb586d23b66879eb | 38 | 68 | 0.680612 | 5.959786 | false | false | false | false |
stripe/stripe-android | payments-core/src/test/java/com/stripe/android/model/BinRangeTest.kt | 1 | 4592 | package com.stripe.android.model
import com.google.common.truth.Truth.assertThat
import com.stripe.android.cards.CardNumber
import kotlin.test.Test
class BinRangeTest {
@Test
fun `BinRange should match expected ranges`() {
val binRange = BinRange(low = "134", high = "167")
assertThat(binRange.matches(CardNumber.Unvalidated("")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("0")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("1")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("2")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("00")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("13")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("14")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("16")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("20")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("133")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("134")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("135")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("167")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("168")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("1244")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("1340")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("1344")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("1444")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("1670")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("1679")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("1680")))
.isFalse()
}
@Test
fun `BinRange should handle leading zeroes`() {
val binRange = BinRange(low = "004", high = "017")
assertThat(binRange.matches(CardNumber.Unvalidated("")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("0")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("1")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("00")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("01")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("10")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("20")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("000")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("002")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("004")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("009")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("014")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("017")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("019")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("020")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("100")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("0000")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("0021")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("0044")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("0098")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("0143")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("0173")))
.isTrue()
assertThat(binRange.matches(CardNumber.Unvalidated("0195")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("0202")))
.isFalse()
assertThat(binRange.matches(CardNumber.Unvalidated("1004")))
.isFalse()
}
}
| mit | 888046b3ea186c088631b30649f9522a | 37.588235 | 68 | 0.616507 | 4.596597 | false | false | false | false |
noloman/keddit | app/src/main/java/me/manulorenzo/keddit/adapter/NewsDelegateAdapter.kt | 1 | 1222 | package me.manulorenzo.keddit.adapter
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import kotlinx.android.synthetic.main.news_item.view.*
import me.manulorenzo.keddit.R
import me.manulorenzo.keddit.model.RedditNewsItem
import me.manulorenzo.keddit.util.getFriendlyTime
import me.manulorenzo.keddit.util.inflate
import me.manulorenzo.keddit.util.loadImage
/**
* Created by Manuel Lorenzo on 04/11/2016.
*/
class NewsDelegateAdapter : ViewTypeDelegateAdapter {
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: ViewType) {
holder as TurnsViewHolder
holder.bind(item as RedditNewsItem)
}
override fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder {
return TurnsViewHolder(parent)
}
class TurnsViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(parent.inflate(R.layout.news_item)) {
fun bind(item: RedditNewsItem) = with(itemView) {
img_thumbnail.loadImage(item.thumbnail)
description.text = item.title
author.text = item.author
comments.text = "${item.numComments} comments"
time.text = item.created.getFriendlyTime()
}
}
} | mit | 21a74f34507e0fcbc483e01796777c5e | 34.970588 | 108 | 0.730769 | 4.046358 | false | false | false | false |
andimage/PCBridge | src/main/kotlin/com/projectcitybuild/repositories/PlayerUUIDRepository.kt | 1 | 1929 | package com.projectcitybuild.repositories
import com.projectcitybuild.core.extensions.toDashFormattedUUID
import com.projectcitybuild.core.infrastructure.network.APIClient
import com.projectcitybuild.core.infrastructure.network.APIRequestFactory
import com.projectcitybuild.entities.responses.MojangPlayer
import org.bukkit.Server
import java.util.UUID
import javax.inject.Inject
open class PlayerUUIDRepository @Inject constructor(
private val server: Server,
private val apiRequestFactory: APIRequestFactory,
private val apiClient: APIClient,
) {
class PlayerNotFoundException : Exception()
// TODO: cache with expiry time
private val mojangPlayerCache = HashMap<String, MojangPlayer>()
suspend fun get(playerName: String): UUID? {
val onlinePlayerUUID = server.getPlayer(playerName)?.uniqueId
if (onlinePlayerUUID != null) {
return onlinePlayerUUID
}
return try {
val mojangPlayer = getMojangPlayer(playerName = playerName)
UUID.fromString(mojangPlayer.uuid.toDashFormattedUUID())
} catch (e: PlayerNotFoundException) {
null
}
}
private suspend fun getMojangPlayer(playerName: String, at: Long? = null): MojangPlayer {
val cacheHit = mojangPlayerCache[playerName]
if (cacheHit != null) {
return cacheHit
}
val mojangApi = apiRequestFactory.mojang.mojangApi
return apiClient.execute {
try {
val player = mojangApi.getMojangPlayer(playerName, timestamp = at)
?: throw PlayerNotFoundException()
mojangPlayerCache[playerName] = player
player
} catch (e: KotlinNullPointerException) {
// Hacky workaround to catch 204 HTTP errors (username not found)
throw PlayerNotFoundException()
}
}
}
}
| mit | 2f0ca08a237bb5bc727120b3ba660ac3 | 34.072727 | 93 | 0.672369 | 4.946154 | false | false | false | false |
sirdesmond/changecalculator | master-service/src/test/kotlin/acceptance/AcceptanceTest.kt | 1 | 3077 | package acceptance
import com.fasterxml.jackson.databind.ObjectMapper
import com.github.tomakehurst.wiremock.client.WireMock
import com.github.tomakehurst.wiremock.junit.WireMockRule
import com.jayway.restassured.RestAssured
import com.jayway.restassured.internal.mapping.Jackson2Mapper
import org.hamcrest.Matchers
import org.junit.Before
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.boot.context.embedded.LocalServerPort
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.junit4.SpringRunner
import sirdesmond.Application
import sirdesmond.When
import sirdesmond.domain.Response
/**
* Created by kofikyei on 11/17/16.
*/
@RunWith(SpringRunner::class)
@SpringBootTest(classes = arrayOf(Application::class), webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("system")
class AcceptanceTest {
@Rule @JvmField
val rule = WireMockRule(8089)
@LocalServerPort
var port: Int= 0
@Before
fun setup() { RestAssured.port = port }
@Test
fun `should return optimal change for valid requests`() {
val expectedResponse = Response(
silver_dollar = 12,
half_dollar = 1,
quarter = 1,
dime = 1,
nickel = 0,
penny = 0
)
WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/optimalChange/12.85"))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type","application/json")
.withBody(ObjectMapper().writeValueAsString(expectedResponse)))
)
RestAssured.given()
.When()
.get("/change/12.85")
.then()
.body("silver_dollar", Matchers.equalTo(12))
.body("half_dollar", Matchers.equalTo(1))
.body("quarter", Matchers.equalTo(1))
.body("dime", Matchers.equalTo(1))
.body("nickel", Matchers.equalTo(0))
.body("penny", Matchers.equalTo(0))
.statusCode(200)
}
@Test
fun `should return invalid amount error if amount is not valid`() {
val expectedResponse = mapOf("message" to INVALID_AMOUNT)
WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/optimalChange/invalid_amount"))
.willReturn(WireMock.aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(ObjectMapper().writeValueAsString(expectedResponse)))
)
RestAssured.given()
.When()
.get("/change/invalid_amount")
.then()
.body("message", Matchers.equalTo(INVALID_AMOUNT))
.statusCode(200)
}
companion object{
const val INVALID_AMOUNT = "invalid amount provided!"
}
} | mit | e0c5f76fbf8270da905d50414512b4c9 | 31.4 | 114 | 0.625284 | 4.599402 | false | true | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/refactoring/introduceConstant/ui.kt | 3 | 5346 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring.introduceConstant
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.markup.HighlighterLayer
import com.intellij.openapi.editor.markup.HighlighterTargetArea
import com.intellij.openapi.editor.markup.MarkupModel
import com.intellij.openapi.editor.markup.RangeHighlighter
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.JBPopupListener
import com.intellij.openapi.ui.popup.LightweightWindowEvent
import com.intellij.psi.PsiElement
import org.jetbrains.annotations.TestOnly
import org.rust.lang.core.psi.RsExpr
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.RsModItem
import org.rust.lang.core.psi.ext.block
import org.rust.openapiext.isUnitTestMode
import java.awt.Component
import javax.swing.DefaultListCellRenderer
import javax.swing.JList
class Highlighter(private val editor: Editor) : JBPopupListener {
private var highlighter: RangeHighlighter? = null
private val attributes = EditorColorsManager.getInstance().globalScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)
fun onSelect(candidate: InsertionCandidate) {
dropHighlighter()
val markupModel: MarkupModel = editor.markupModel
val textRange = candidate.parent.textRange
highlighter = markupModel.addRangeHighlighter(
textRange.startOffset, textRange.endOffset, HighlighterLayer.SELECTION - 1, attributes,
HighlighterTargetArea.EXACT_RANGE)
}
override fun onClosed(event: LightweightWindowEvent) {
dropHighlighter()
}
private fun dropHighlighter() {
highlighter?.dispose()
}
}
fun showInsertionChooser(
editor: Editor,
expr: RsExpr,
callback: (InsertionCandidate) -> Unit
) {
val candidates = findInsertionCandidates(expr)
if (isUnitTestMode) {
callback(MOCK!!.chooseInsertionPoint(expr, candidates))
} else {
val highlighter = Highlighter(editor)
JBPopupFactory.getInstance()
.createPopupChooserBuilder(candidates)
.setRenderer(object : DefaultListCellRenderer() {
override fun getListCellRendererComponent(list: JList<*>?,
value: Any,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean): Component {
val candidate = value as InsertionCandidate
val text = candidate.description()
return super.getListCellRendererComponent(list, text, index, isSelected, cellHasFocus)
}
})
.setItemSelectedCallback { value: InsertionCandidate? ->
if (value == null) return@setItemSelectedCallback
highlighter.onSelect(value)
}
.setTitle("Choose scope to introduce constant ${expr.text}")
.setMovable(true)
.setResizable(false)
.setRequestFocus(true)
.setItemChosenCallback { it?.let { callback(it) } }
.addListener(highlighter)
.createPopup()
.showInBestPositionFor(editor)
}
}
interface ExtractConstantUi {
fun chooseInsertionPoint(expr: RsExpr, candidates: List<InsertionCandidate>): InsertionCandidate
}
data class InsertionCandidate(val context: PsiElement, val parent: PsiElement, val anchor: PsiElement) {
fun description(): String = when (val element = this.context) {
is RsFunction -> "fn ${element.name}"
is RsModItem -> "mod ${element.name}"
is RsFile -> "file"
else -> error("unreachable")
}
}
private fun findInsertionCandidates(expr: RsExpr): List<InsertionCandidate> {
var parent: PsiElement = expr
var anchor: PsiElement = expr
val points = mutableListOf<InsertionCandidate>()
fun getAnchor(parent: PsiElement, anchor: PsiElement): PsiElement {
var found = anchor
while (found.parent != parent) {
found = found.parent
}
return found
}
var moduleVisited = false
while (parent !is RsFile) {
parent = parent.parent
when (parent) {
is RsFunction -> {
if (!moduleVisited) {
parent.block?.let {
points.add(InsertionCandidate(parent, it, getAnchor(it, anchor)))
anchor = parent
}
}
}
is RsModItem, is RsFile -> {
points.add(InsertionCandidate(parent, parent, getAnchor(parent, anchor)))
anchor = parent
moduleVisited = true
}
}
}
return points
}
var MOCK: ExtractConstantUi? = null
@TestOnly
fun withMockExtractConstantChooser(mock: ExtractConstantUi, f: () -> Unit) {
MOCK = mock
try {
f()
} finally {
MOCK = null
}
}
| mit | cfa8394908a55e6c4104b00b6b94599a | 34.879195 | 128 | 0.636738 | 5.072106 | false | false | false | false |
cauchymop/goblob | goblobBase/src/test/java/com/cauchymop/goblob/model/GameRepositoryTest.kt | 1 | 2649 | package com.cauchymop.goblob.model
import any
import com.cauchymop.goblob.proto.PlayGameData
import com.google.common.truth.Truth.assertThat
import dagger.Lazy
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class GameRepositoryTest {
@Mock
private lateinit var analytics: Analytics
@Mock
private lateinit var gameRepositoryImplementationDelegate: GameRepositoryImplementationDelegate
private lateinit var gameCache: PlayGameData.GameList.Builder
private val gameDatas = GameDatas()
private lateinit var gameRepository: GameRepository
@Before
fun setUp() {
gameCache = PlayGameData.GameList.newBuilder()
gameRepository = object : GameRepository(analytics = analytics,
playerOneDefaultName = Lazy { "Pipo" },
playerTwoDefaultName = "Bimbo",
gameDatas = gameDatas,
gameCache = gameCache),
GameRepositoryImplementationDelegate by gameRepositoryImplementationDelegate {}
}
@After
fun tearDown() {
verify(gameRepositoryImplementationDelegate, atLeast(0)).log(any())
verifyNoMoreInteractions(analytics, gameRepositoryImplementationDelegate)
}
@Test
fun commitGameChanges_localGame() {
val black = gameDatas.createGamePlayer("pipo", "player1", true)
val white = gameDatas.createGamePlayer("bimbo", "player2", true)
val localGame = gameDatas.createNewGameData("pizza", PlayGameData.GameType.LOCAL, black, white)
assertThat(gameCache.gamesMap.get("pizza")).isNull()
gameRepository.commitGameChanges(localGame)
assertThat(gameCache.gamesMap.get("pizza")).isEqualTo(localGame)
verify(gameRepositoryImplementationDelegate).forceCacheRefresh()
}
@Test
fun commitGameChanges_remoteGame() {
val black = gameDatas.createGamePlayer("pipo", "player1", true)
val white = gameDatas.createGamePlayer("bimbo", "player2", true)
val remoteGame = gameDatas.createNewGameData("pizza", PlayGameData.GameType.REMOTE, black, white)
assertThat(gameCache.gamesMap.get("pizza")).isNull()
gameRepository.commitGameChanges(remoteGame)
assertThat(gameCache.gamesMap.get("pizza")).isEqualTo(remoteGame)
verify(gameRepositoryImplementationDelegate).forceCacheRefresh()
verify(gameRepositoryImplementationDelegate).publishRemoteGameState(remoteGame)
}
}
interface GameRepositoryImplementationDelegate {
fun forceCacheRefresh()
fun publishRemoteGameState(gameData: PlayGameData.GameData): Boolean
fun log(message: String)
}
| apache-2.0 | 0b8057c2d307eb13bd33c29e19ccea91 | 31.703704 | 101 | 0.774632 | 4.279483 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/DragLinearLayout.kt | 2 | 24849 | package com.habitrpg.android.habitica.ui.views
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.util.Log
import android.util.SparseArray
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.ViewTreeObserver.OnPreDrawListener
import android.widget.LinearLayout
import android.widget.ScrollView
import androidx.core.content.ContextCompat
import com.habitrpg.android.habitica.R
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
// Adapted from https://github.com/justasm/DragLinearLayout
/**
* A LinearLayout that supports children Views that can be dragged and swapped around.
* See [.addDragView],
* [.addDragView],
* [.setViewDraggable], and
* [.removeDragView].
*
*
* Currently, no error-checking is done on standard [.addView] and
* [.removeView] calls, so avoid using these with children previously
* declared as draggable to prevent memory leaks and/or subtle bugs. Pull requests welcome!
*/
open class DragLinearLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : LinearLayout(context, attrs) {
private val nominalDistanceScaled: Float
private var swapListener: OnViewSwapListener? = null
private val draggableChildren: SparseArray<DraggableChild>
private val draggedItem: DragItem
private val slop: Int
private var downY = -1
private var activePointerId = INVALID_POINTER_ID
private val dragTopShadowDrawable: Drawable?
private val dragBottomShadowDrawable: Drawable?
private val dragShadowHeight: Int
private var containerScrollView: ScrollView? = null
/**
* Sets the height from upper / lower edge at which a container [android.widget.ScrollView],
* if one is registered via [.setContainerScrollView],
* is scrolled.
*/
var scrollSensitiveHeight: Int = 0
private var dragUpdater: Runnable? = null
/**
* Use with [com.habitrpg.android.habitica.ui.views.DragLinearLayout.setOnViewSwapListener]
* to listen for draggable view swaps.
*/
interface OnViewSwapListener {
/**
* Invoked right before the two items are swapped due to a drag event.
* After the swap, the firstView will be in the secondPosition, and vice versa.
*
*
* No guarantee is made as to which of the two has a lesser/greater position.
*/
fun onSwap(firstView: View?, firstPosition: Int, secondView: View, secondPosition: Int)
}
private class DraggableChild {
/**
* If non-null, a reference to an on-going position animation.
*/
var swapAnimation: ValueAnimator? = null
fun endExistingAnimation() {
swapAnimation?.end()
}
fun cancelExistingAnimation() {
swapAnimation?.cancel()
}
}
/**
* Holds state information about the currently dragged item.
*
*
* Rough lifecycle:
* * #startDetectingOnPossibleDrag - #detecting == true
* * if drag is recognised, #onDragStart - #dragging == true
* * if drag ends, #onDragStop - #dragging == false, #settling == true
* * if gesture ends without drag, or settling finishes, #stopDetecting - #detecting == false
*/
private inner class DragItem {
var view: View? = null
private var startVisibility: Int = 0
var viewDrawable: BitmapDrawable? = null
var position: Int = 0
var startTop: Int = 0
var height: Int = 0
var totalDragOffset: Int = 0
var targetTopOffset: Int = 0
var settleAnimation: ValueAnimator? = null
var detecting: Boolean = false
var dragging: Boolean = false
init {
stopDetecting()
}
fun startDetectingOnPossibleDrag(view: View, position: Int) {
this.view = view
this.startVisibility = view.visibility
this.viewDrawable = getDragDrawable(view)
this.position = position
this.startTop = view.top
this.height = view.height
this.totalDragOffset = 0
this.targetTopOffset = 0
this.settleAnimation = null
this.detecting = true
}
fun onDragStart() {
view?.visibility = View.INVISIBLE
this.dragging = true
}
fun setTotalOffset(offset: Int) {
totalDragOffset = offset
updateTargetTop()
}
fun updateTargetTop() {
targetTopOffset = startTop - (view?.top ?: 0) + totalDragOffset
}
fun onDragStop() {
this.dragging = false
}
fun settling(): Boolean {
return null != settleAnimation
}
fun stopDetecting() {
this.detecting = false
if (null != view) view?.visibility = startVisibility
view = null
startVisibility = -1
viewDrawable = null
position = -1
startTop = -1
height = -1
totalDragOffset = 0
targetTopOffset = 0
if (null != settleAnimation) settleAnimation?.end()
settleAnimation = null
}
}
init {
orientation = VERTICAL
draggableChildren = SparseArray()
draggedItem = DragItem()
val vc = ViewConfiguration.get(context)
slop = vc.scaledTouchSlop
val resources = resources
dragTopShadowDrawable = ContextCompat.getDrawable(context, R.drawable.ab_solid_shadow_holo_flipped)
dragBottomShadowDrawable = ContextCompat.getDrawable(context, R.drawable.ab_solid_shadow_holo)
dragShadowHeight = resources.getDimensionPixelSize(R.dimen.downwards_drop_shadow_height)
scrollSensitiveHeight = (DEFAULT_SCROLL_SENSITIVE_AREA_HEIGHT_DP * resources.displayMetrics.density + 0.5f).toInt()
nominalDistanceScaled = (NOMINAL_DISTANCE * resources.displayMetrics.density + 0.5f).toInt().toFloat()
}
override fun setOrientation(orientation: Int) {
// enforce VERTICAL orientation; remove if HORIZONTAL support is ever added
if (HORIZONTAL == orientation) {
throw IllegalArgumentException("DragLinearLayout must be VERTICAL.")
}
super.setOrientation(orientation)
}
/**
* Makes the child a candidate for dragging. Must be an existing child of this layout.
*/
fun setViewDraggable(child: View, dragHandle: View) {
if (this === child.parent) {
dragHandle.setOnTouchListener(DragHandleOnTouchListener(child))
draggableChildren.put(indexOfChild(child), DraggableChild())
} else {
Log.e(LOG_TAG, "$child is not a child, cannot make draggable.")
}
}
/**
* Makes the child a candidate for dragging. Must be an existing child of this layout.
*/
fun removeViewDraggable(child: View) {
if (this === child.parent) {
draggableChildren.remove(indexOfChild(child))
draggableChildren.put(indexOfChild(child), DraggableChild())
}
}
override fun removeAllViews() {
super.removeAllViews()
draggableChildren.clear()
}
/**
* See [com.habitrpg.android.habitica.ui.views.DragLinearLayout.OnViewSwapListener].
*/
fun setOnViewSwapListener(swapListener: OnViewSwapListener) {
this.swapListener = swapListener
}
/**
* A linear relationship b/w distance and duration, bounded.
*/
private fun getTranslateAnimationDuration(distance: Float): Long {
return min(MAX_SWITCH_DURATION, max(MIN_SWITCH_DURATION, (NOMINAL_SWITCH_DURATION * abs(distance) / nominalDistanceScaled).toLong()))
}
/**
* Initiates a new [.draggedItem] unless the current one is still
* [com.habitrpg.android.habitica.ui.views.DragLinearLayout.DragItem.detecting].
*/
private fun startDetectingDrag(child: View) {
if (draggedItem.detecting)
return // existing drag in process, only one at a time is allowed
val position = indexOfChild(child)
// complete any existing animations, both for the newly selected child and the previous dragged one
draggableChildren.get(position).endExistingAnimation()
draggedItem.startDetectingOnPossibleDrag(child, position)
containerScrollView?.requestDisallowInterceptTouchEvent(true)
}
private fun startDrag() {
// remove layout transition, it conflicts with drag animation
// we will restore it after drag animation end, see onDragStop()
layoutTransition = layoutTransition
if (layoutTransition != null) {
layoutTransition = null
}
draggedItem.onDragStart()
requestDisallowInterceptTouchEvent(true)
}
/**
* Animates the dragged item to its final resting position.
*/
private fun onDragStop() {
draggedItem.settleAnimation = ValueAnimator.ofFloat(
draggedItem.totalDragOffset.toFloat(),
(draggedItem.totalDragOffset - draggedItem.targetTopOffset).toFloat()
)
.setDuration(getTranslateAnimationDuration(draggedItem.targetTopOffset.toFloat()))
draggedItem.settleAnimation?.addUpdateListener(
ValueAnimator.AnimatorUpdateListener { animation ->
if (!draggedItem.detecting) return@AnimatorUpdateListener // already stopped
draggedItem.setTotalOffset((animation.animatedValue as? Float)?.toInt() ?: 0)
val shadowAlpha = ((1 - animation.animatedFraction) * 255).toInt()
if (null != dragTopShadowDrawable) dragTopShadowDrawable.alpha = shadowAlpha
dragBottomShadowDrawable?.alpha = shadowAlpha
invalidate()
}
)
draggedItem.settleAnimation?.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator) {
draggedItem.onDragStop()
}
override fun onAnimationEnd(animation: Animator) {
if (!draggedItem.detecting) {
return // already stopped
}
draggedItem.settleAnimation = null
draggedItem.stopDetecting()
if (null != dragTopShadowDrawable) dragTopShadowDrawable.alpha = 255
dragBottomShadowDrawable?.alpha = 255
// restore layout transition
if (layoutTransition != null && layoutTransition == null) {
layoutTransition = layoutTransition
}
}
})
draggedItem.settleAnimation?.start()
}
/**
* Updates the dragged item with the given total offset from its starting position.
* Evaluates and executes draggable view swaps.
*/
private fun onDrag(offset: Int) {
draggedItem.setTotalOffset(offset)
invalidate()
val currentTop = draggedItem.startTop + draggedItem.totalDragOffset
handleContainerScroll(currentTop)
val belowPosition = nextDraggablePosition(draggedItem.position)
val abovePosition = previousDraggablePosition(draggedItem.position)
val belowView = getChildAt(belowPosition)
val aboveView = getChildAt(abovePosition)
val isBelow = belowView != null && currentTop + draggedItem.height > belowView.top + belowView.height / 2
val isAbove = aboveView != null && currentTop < aboveView.top + aboveView.height / 2
if (isBelow || isAbove) {
val switchView = if (isBelow) belowView else aboveView
// swap elements
val originalPosition = draggedItem.position
val switchPosition = if (isBelow) belowPosition else abovePosition
draggableChildren.get(switchPosition).cancelExistingAnimation()
val switchViewStartY = switchView.y
if (null != swapListener) {
swapListener?.onSwap(draggedItem.view, draggedItem.position, switchView, switchPosition)
}
if (isBelow) {
removeViewAt(originalPosition)
removeViewAt(switchPosition - 1)
addView(belowView, originalPosition)
addView(draggedItem.view, switchPosition)
} else {
removeViewAt(switchPosition)
removeViewAt(originalPosition - 1)
addView(draggedItem.view, switchPosition)
addView(aboveView, originalPosition)
}
draggedItem.position = switchPosition
val switchViewObserver = switchView.viewTreeObserver
switchViewObserver.addOnPreDrawListener(object : OnPreDrawListener {
override fun onPreDraw(): Boolean {
switchViewObserver.removeOnPreDrawListener(this)
val switchAnimator = ObjectAnimator.ofFloat(switchView, "y", switchViewStartY, switchView.top.toFloat())
.setDuration(getTranslateAnimationDuration(switchView.top - switchViewStartY))
switchAnimator.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator) {
draggableChildren.get(originalPosition).swapAnimation = switchAnimator
}
override fun onAnimationEnd(animation: Animator) {
draggableChildren.get(originalPosition).swapAnimation = null
}
})
switchAnimator.start()
return true
}
})
val observer = draggedItem.view!!.viewTreeObserver
observer.addOnPreDrawListener(object : OnPreDrawListener {
override fun onPreDraw(): Boolean {
observer.removeOnPreDrawListener(this)
draggedItem.updateTargetTop()
// TODO test if still necessary..
// because draggedItem#view#getTop() is only up-to-date NOW
// (and not right after the #addView() swaps above)
// we may need to update an ongoing settle animation
if (draggedItem.settling()) {
Log.d(LOG_TAG, "Updating settle animation")
draggedItem.settleAnimation!!.removeAllListeners()
draggedItem.settleAnimation!!.cancel()
onDragStop()
}
return true
}
})
}
}
private fun previousDraggablePosition(position: Int): Int {
val startIndex = draggableChildren.indexOfKey(position)
return if (startIndex < 1 || startIndex > draggableChildren.size()) -1 else draggableChildren.keyAt(startIndex - 1)
}
private fun nextDraggablePosition(position: Int): Int {
val startIndex = draggableChildren.indexOfKey(position)
return if (startIndex < -1 || startIndex > draggableChildren.size() - 2) -1 else draggableChildren.keyAt(startIndex + 1)
}
private fun handleContainerScroll(currentTop: Int) {
if (null != containerScrollView) {
val startScrollY = containerScrollView!!.scrollY
val absTop = top - startScrollY + currentTop
val height = containerScrollView!!.height
val delta: Int
delta = when {
absTop < scrollSensitiveHeight -> {
(-MAX_DRAG_SCROLL_SPEED * smootherStep(scrollSensitiveHeight.toFloat(), 0f, absTop.toFloat())).toInt()
}
absTop > height - scrollSensitiveHeight -> {
(MAX_DRAG_SCROLL_SPEED * smootherStep((height - scrollSensitiveHeight).toFloat(), height.toFloat(), absTop.toFloat())).toInt()
}
else -> {
0
}
}
containerScrollView?.removeCallbacks(dragUpdater)
containerScrollView?.smoothScrollBy(0, delta)
dragUpdater = Runnable {
if (draggedItem.dragging && startScrollY != containerScrollView!!.scrollY) {
onDrag(draggedItem.totalDragOffset + delta)
}
}
containerScrollView?.post(dragUpdater)
}
}
override fun dispatchDraw(canvas: Canvas) {
super.dispatchDraw(canvas)
if (draggedItem.detecting && (draggedItem.dragging || draggedItem.settling())) {
canvas.save()
canvas.translate(0f, draggedItem.totalDragOffset.toFloat())
draggedItem.viewDrawable?.draw(canvas)
val left = draggedItem.viewDrawable?.bounds?.left ?: 0
val right = draggedItem.viewDrawable?.bounds?.right ?: 0
val top = draggedItem.viewDrawable?.bounds?.top ?: 0
val bottom = draggedItem.viewDrawable?.bounds?.bottom ?: 0
dragBottomShadowDrawable?.setBounds(left, bottom, right, bottom + dragShadowHeight)
dragBottomShadowDrawable?.draw(canvas)
if (null != dragTopShadowDrawable) {
dragTopShadowDrawable.setBounds(left, top - dragShadowHeight, right, top)
dragTopShadowDrawable.draw(canvas)
}
canvas.restore()
}
}
/*
* Note regarding touch handling:
* In general, we have three cases -
* 1) User taps outside any children.
* #onInterceptTouchEvent receives DOWN
* #onTouchEvent receives DOWN
* draggedItem.detecting == false, we return false and no further events are received
* 2) User taps on non-interactive drag handle / child, e.g. TextView or ImageView.
* #onInterceptTouchEvent receives DOWN
* DragHandleOnTouchListener (attached to each draggable child) #onTouch receives DOWN
* #startDetectingDrag is called, draggedItem is now detecting
* view does not handle touch, so our #onTouchEvent receives DOWN
* draggedItem.detecting == true, we #startDrag() and proceed to handle the drag
* 3) User taps on interactive drag handle / child, e.g. Button.
* #onInterceptTouchEvent receives DOWN
* DragHandleOnTouchListener (attached to each draggable child) #onTouch receives DOWN
* #startDetectingDrag is called, draggedItem is now detecting
* view handles touch, so our #onTouchEvent is not called yet
* #onInterceptTouchEvent receives ACTION_MOVE
* if dy > touch slop, we assume user wants to drag and intercept the event
* #onTouchEvent receives further ACTION_MOVE events, proceed to handle the drag
*
* For cases 2) and 3), lifting the active pointer at any point in the sequence of events
* triggers #onTouchEnd and the draggedItem, if detecting, is #stopDetecting.
*/
override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
if (draggedItem.detecting) return false // an existing item is (likely) settling
downY = event.y.toInt()
activePointerId = event.getPointerId(0)
}
MotionEvent.ACTION_MOVE -> {
if (!draggedItem.detecting) return false
if (INVALID_POINTER_ID == activePointerId) return false
val y = event.y
val dy = y - downY
if (abs(dy) > slop) {
startDrag()
return true
}
return false
}
MotionEvent.ACTION_POINTER_UP -> {
run {
val pointerIndex = event.actionIndex
val pointerId = event.getPointerId(pointerIndex)
if (pointerId != activePointerId)
return false // if active pointer, fall through and cancel!
}
run {
onTouchEnd()
if (draggedItem.detecting) draggedItem.stopDetecting()
return false
}
}
MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
onTouchEnd()
if (draggedItem.detecting) draggedItem.stopDetecting()
}
}
return false
}
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
if (!draggedItem.detecting || draggedItem.settling()) return false
startDrag()
return true
}
MotionEvent.ACTION_MOVE -> {
if (!draggedItem.dragging) return false
if (INVALID_POINTER_ID == activePointerId) return false
val pointerIndex = event.findPointerIndex(activePointerId)
val lastEventY = event.getY(pointerIndex).toInt()
val deltaY = lastEventY - downY
onDrag(deltaY)
return true
}
MotionEvent.ACTION_POINTER_UP -> {
run {
val pointerIndex = event.actionIndex
val pointerId = event.getPointerId(pointerIndex)
if (pointerId != activePointerId)
return false // if active pointer, fall through and cancel!
}
run {
onTouchEnd()
if (draggedItem.dragging) {
onDragStop()
} else if (draggedItem.detecting) {
draggedItem.stopDetecting()
}
return true
}
}
MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
onTouchEnd()
if (draggedItem.dragging) {
onDragStop()
} else if (draggedItem.detecting) {
draggedItem.stopDetecting()
}
return true
}
}
return false
}
private fun onTouchEnd() {
downY = -1
activePointerId = INVALID_POINTER_ID
}
private inner class DragHandleOnTouchListener(private val view: View) : OnTouchListener {
override fun onTouch(v: View, event: MotionEvent): Boolean {
view.performClick()
if (MotionEvent.ACTION_DOWN == event.actionMasked) {
startDetectingDrag(view)
}
return false
}
}
private fun getDragDrawable(view: View): BitmapDrawable {
val top = view.top
val left = view.left
val bitmap = getBitmapFromView(view)
val drawable = BitmapDrawable(resources, bitmap)
drawable.bounds = Rect(left, top, left + view.width, top + view.height)
return drawable
}
companion object {
private val LOG_TAG = DragLinearLayout::class.java.simpleName
private const val NOMINAL_SWITCH_DURATION: Long = 150
private const val MIN_SWITCH_DURATION = NOMINAL_SWITCH_DURATION
private const val MAX_SWITCH_DURATION = NOMINAL_SWITCH_DURATION * 2
private const val NOMINAL_DISTANCE = 20f
private const val INVALID_POINTER_ID = -1
private const val DEFAULT_SCROLL_SENSITIVE_AREA_HEIGHT_DP = 48
private const val MAX_DRAG_SCROLL_SPEED = 16
/**
* By Ken Perlin. See [Smoothstep - Wikipedia](http://en.wikipedia.org/wiki/Smoothstep).
*/
private fun smootherStep(edge1: Float, edge2: Float, `val`: Float): Float {
var value = `val`
value = max(0f, min((value - edge1) / (edge2 - edge1), 1f))
return value * value * value * (value * (value * 6 - 15) + 10)
}
/**
* @return a bitmap showing a screenshot of the view passed in.
*/
private fun getBitmapFromView(view: View): Bitmap {
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
view.draw(canvas)
return bitmap
}
}
}
| gpl-3.0 | 828cc1e577bcb023ea15b04bc45812d4 | 36.937405 | 146 | 0.606061 | 5.054719 | false | false | false | false |
androidx/androidx | health/connect/connect-client/src/main/java/androidx/health/connect/client/records/SpeedRecord.kt | 3 | 5287 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.health.connect.client.records
import androidx.health.connect.client.aggregate.AggregateMetric
import androidx.health.connect.client.records.metadata.Metadata
import androidx.health.connect.client.units.Velocity
import androidx.health.connect.client.units.metersPerSecond
import java.time.Instant
import java.time.ZoneOffset
/**
* Captures the user's speed, e.g. during running or cycling. Each record represents a series of
* measurements.
*/
public class SpeedRecord(
override val startTime: Instant,
override val startZoneOffset: ZoneOffset?,
override val endTime: Instant,
override val endZoneOffset: ZoneOffset?,
override val samples: List<Sample>,
override val metadata: Metadata = Metadata.EMPTY,
) : SeriesRecord<SpeedRecord.Sample> {
init {
require(!startTime.isAfter(endTime)) { "startTime must not be after endTime." }
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is SpeedRecord) return false
if (startTime != other.startTime) return false
if (startZoneOffset != other.startZoneOffset) return false
if (endTime != other.endTime) return false
if (endZoneOffset != other.endZoneOffset) return false
if (samples != other.samples) return false
if (metadata != other.metadata) return false
return true
}
/*
* Generated by the IDE: Code -> Generate -> "equals() and hashCode()".
*/
override fun hashCode(): Int {
var result = startTime.hashCode()
result = 31 * result + (startZoneOffset?.hashCode() ?: 0)
result = 31 * result + endTime.hashCode()
result = 31 * result + (endZoneOffset?.hashCode() ?: 0)
result = 31 * result + samples.hashCode()
result = 31 * result + metadata.hashCode()
return result
}
companion object {
private const val SPEED_TYPE_NAME = "SpeedSeries"
private const val SPEED_FIELD_NAME = "speed"
private val MAX_SPEED = 1000_000.metersPerSecond
/**
* Metric identifier to retrieve average speed from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val SPEED_AVG: AggregateMetric<Velocity> =
AggregateMetric.doubleMetric(
dataTypeName = SPEED_TYPE_NAME,
aggregationType = AggregateMetric.AggregationType.AVERAGE,
fieldName = SPEED_FIELD_NAME,
mapper = Velocity::metersPerSecond,
)
/**
* Metric identifier to retrieve minimum speed from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val SPEED_MIN: AggregateMetric<Velocity> =
AggregateMetric.doubleMetric(
dataTypeName = SPEED_TYPE_NAME,
aggregationType = AggregateMetric.AggregationType.MINIMUM,
fieldName = SPEED_FIELD_NAME,
mapper = Velocity::metersPerSecond,
)
/**
* Metric identifier to retrieve maximum speed from
* [androidx.health.connect.client.aggregate.AggregationResult].
*/
@JvmField
val SPEED_MAX: AggregateMetric<Velocity> =
AggregateMetric.doubleMetric(
dataTypeName = SPEED_TYPE_NAME,
aggregationType = AggregateMetric.AggregationType.MAXIMUM,
fieldName = SPEED_FIELD_NAME,
mapper = Velocity::metersPerSecond,
)
}
/**
* Represents a single measurement of the speed, a scalar magnitude.
*
* @param time The point in time when the measurement was taken.
* @param speed Speed in [Velocity] unit. Valid range: 0-1000000 meters/sec.
*
* @see SpeedRecord
*/
public class Sample(
val time: Instant,
val speed: Velocity,
) {
init {
speed.requireNotLess(other = speed.zero(), name = "speed")
speed.requireNotMore(other = MAX_SPEED, name = "speed")
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Sample) return false
if (time != other.time) return false
if (speed != other.speed) return false
return true
}
override fun hashCode(): Int {
var result = time.hashCode()
result = 31 * result + speed.hashCode()
return result
}
}
}
| apache-2.0 | 6fb8d44f32d45d5cdfc6f06ebc84d83f | 34.013245 | 96 | 0.627766 | 4.771661 | false | false | false | false |
Ztiany/AndroidBase | lib_base/src/main/java/com/android/base/kotlin/TextViewEx.kt | 1 | 4142 | package com.android.base.kotlin
import android.graphics.drawable.Drawable
import android.support.annotation.DrawableRes
import android.text.Editable
import android.text.TextWatcher
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.android.base.interfaces.adapter.TextWatcherAdapter
inline fun TextView.textWatcher(init: KTextWatcher.() -> Unit) = addTextChangedListener(KTextWatcher().apply(init))
class KTextWatcher : TextWatcher {
val TextView.isEmpty
get() = text.isEmpty()
val TextView.isNotEmpty
get() = text.isNotEmpty()
val TextView.isBlank
get() = text.isBlank()
val TextView.isNotBlank
get() = text.isNotBlank()
private var _beforeTextChanged: ((CharSequence?, Int, Int, Int) -> Unit)? = null
private var _onTextChanged: ((CharSequence?, Int, Int, Int) -> Unit)? = null
private var _afterTextChanged: ((Editable?) -> Unit)? = null
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
_beforeTextChanged?.invoke(s, start, count, after)
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
_onTextChanged?.invoke(s, start, before, count)
}
override fun afterTextChanged(s: Editable?) {
_afterTextChanged?.invoke(s)
}
fun beforeTextChanged(listener: (CharSequence?, Int, Int, Int) -> Unit) {
_beforeTextChanged = listener
}
fun onTextChanged(listener: (CharSequence?, Int, Int, Int) -> Unit) {
_onTextChanged = listener
}
fun afterTextChanged(listener: (Editable?) -> Unit) {
_afterTextChanged = listener
}
}
fun TextView.topDrawable(@DrawableRes id: Int) {
this.setCompoundDrawablesWithIntrinsicBounds(0, id, 0, 0)
}
fun TextView.leftDrawable(@DrawableRes id: Int) {
this.setCompoundDrawablesWithIntrinsicBounds(id, 0, 0, 0)
}
fun TextView.rightDrawable(@DrawableRes id: Int) {
this.setCompoundDrawablesWithIntrinsicBounds(0, 0, id, 0)
}
fun TextView.bottomDrawable(@DrawableRes id: Int) {
this.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, id)
}
fun TextView.topDrawable(drawable: Drawable, retain: Boolean = false) {
if (retain) {
val compoundDrawables = this.compoundDrawables
this.setCompoundDrawablesWithIntrinsicBounds(compoundDrawables[0], drawable, compoundDrawables[2], compoundDrawables[3])
} else {
this.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null)
}
}
fun TextView.leftDrawable(drawable: Drawable, retain: Boolean = false) {
if (retain) {
val compoundDrawables = this.compoundDrawables
this.setCompoundDrawablesWithIntrinsicBounds(drawable, compoundDrawables[1], compoundDrawables[2], compoundDrawables[3])
} else {
this.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null)
}
}
fun TextView.rightDrawable(drawable: Drawable, retain: Boolean = false) {
if (retain) {
val compoundDrawables = this.compoundDrawables
this.setCompoundDrawablesWithIntrinsicBounds(compoundDrawables[0], compoundDrawables[1], drawable, compoundDrawables[3])
} else {
this.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null)
}
}
fun TextView.bottomDrawable(drawable: Drawable, retain: Boolean = false) {
if (retain) {
val compoundDrawables = this.compoundDrawables
this.setCompoundDrawablesWithIntrinsicBounds(compoundDrawables[0], compoundDrawables[1], compoundDrawables[2], drawable)
} else {
this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, drawable)
}
}
fun TextView.clearComponentDrawable() {
this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
}
fun Button.enableByEditText(et: EditText, checker: (s: CharSequence?) -> Boolean = { it -> !it.isNullOrEmpty() }) {
val btn = this
et.addTextChangedListener(object : TextWatcherAdapter {
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
btn.isEnabled = checker(s)
}
})
} | apache-2.0 | ac1fda44275f582dcf153f90c8b3ab91 | 33.239669 | 128 | 0.711733 | 4.531729 | false | false | false | false |
kirtan403/K4Kotlin | k4kotlin-core/src/main/java/com/livinglifetechway/k4kotlin/core/Log.kt | 1 | 1265 | package com.livinglifetechway.k4kotlin.core
import android.util.Log
/**
* Returns class name. Useful for Log Tags
*/
val Any.TAG: String
get() = this::class.java.simpleName
/**
* Logs a debug message
* @param msg object to log
*/
inline fun <reified T> T.debug(msg: Any?, throwable: Throwable? = null) = Log.d(this!!.TAG, msg.toString(), throwable)
/**
* Logs a info message
* @param msg object to log
*/
inline fun <reified T> T.info(msg: Any?, throwable: Throwable? = null) = Log.i(this!!.TAG, msg.toString(), throwable)
/**
* Logs a verbose message
* @param msg object to log
*/
inline fun <reified T> T.verbose(msg: Any?, throwable: Throwable? = null) = Log.v(this!!.TAG, msg.toString(), throwable)
/**
* Logs a warning message
* @param msg object to log
*/
inline fun <reified T> T.warning(msg: Any?, throwable: Throwable? = null) = Log.w(this!!.TAG, msg.toString(), throwable)
/**
* Logs an error message
* @param msg object to log
*/
inline fun <reified T> T.err(msg: Any?, throwable: Throwable? = null) = Log.e(this!!.TAG, msg.toString(), throwable)
/**
* Logs a wtf message
* @param msg object to log
*/
inline fun <reified T> T.wtf(msg: Any?, throwable: Throwable? = null) = Log.wtf(this!!.TAG, msg.toString(), throwable) | apache-2.0 | f2d86cf88618d4d40327edaee0ea66c3 | 25.93617 | 120 | 0.666403 | 3.235294 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/forum/TopicFragment.kt | 1 | 3641 | package me.proxer.app.forum
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.mikepenz.iconics.utils.IconicsMenuInflaterUtil
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import me.proxer.app.GlideApp
import me.proxer.app.R
import me.proxer.app.base.PagedContentFragment
import me.proxer.app.profile.ProfileActivity
import me.proxer.app.util.extension.toPrefixedUrlOrNull
import me.proxer.app.util.extension.unsafeLazy
import me.proxer.library.enums.Device
import me.proxer.library.util.ProxerUrls
import me.proxer.library.util.ProxerUtils
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
import kotlin.properties.Delegates
/**
* @author Ruben Gees
*/
class TopicFragment : PagedContentFragment<ParsedPost>() {
companion object {
fun newInstance() = TopicFragment().apply {
arguments = bundleOf()
}
}
override val isSwipeToRefreshEnabled = false
override val hostingActivity: TopicActivity
get() = activity as TopicActivity
override val viewModel by viewModel<TopicViewModel> { parametersOf(id, resources) }
override val layoutManager by unsafeLazy { LinearLayoutManager(context) }
override var innerAdapter by Delegates.notNull<PostAdapter>()
private val id: String
get() = hostingActivity.id
private var topic: String?
get() = hostingActivity.topic
set(value) {
hostingActivity.topic = value
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
innerAdapter = PostAdapter()
innerAdapter.profileClickSubject
.autoDisposable(this.scope())
.subscribe { (view, post) ->
ProfileActivity.navigateTo(
requireActivity(), post.userId, post.username, post.image,
if (view.drawable != null && post.image.isNotBlank()) view else null
)
}
setHasOptionsMenu(true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
innerAdapter.glide = GlideApp.with(this)
viewModel.metaData.observe(viewLifecycleOwner, Observer {
it?.let { topic = it.subject }
})
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
IconicsMenuInflaterUtil.inflate(inflater, requireContext(), R.menu.fragment_topic, menu, true)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.show_in_browser -> {
val url = (activity?.intent?.dataString ?: "").toPrefixedUrlOrNull()
if (url != null) {
val mobileUrl = url.newBuilder()
.setQueryParameter("device", ProxerUtils.getSafeApiEnumName(Device.MOBILE))
.build()
showPage(mobileUrl, true)
} else {
viewModel.metaData.value?.categoryId?.also { categoryId ->
showPage(ProxerUrls.forumWeb(categoryId, id, Device.MOBILE), true)
}
}
}
}
return super.onOptionsItemSelected(item)
}
}
| gpl-3.0 | a29838139881d9984601e5881f7afe50 | 31.508929 | 102 | 0.664378 | 4.92027 | false | false | false | false |
ligee/kotlin-jupyter | src/main/kotlin/org/jetbrains/kotlinx/jupyter/dependencies/RemoteResolverWrapper.kt | 1 | 2409 | package org.jetbrains.kotlinx.jupyter.dependencies
import java.io.File
import kotlin.script.experimental.api.ResultWithDiagnostics
import kotlin.script.experimental.api.SourceCode
import kotlin.script.experimental.dependencies.ExternalDependenciesResolver
import kotlin.script.experimental.dependencies.RepositoryCoordinates
class RemoteResolverWrapper(private val remoteResolver: ExternalDependenciesResolver) :
ExternalDependenciesResolver by remoteResolver {
override fun acceptsRepository(repositoryCoordinates: RepositoryCoordinates): Boolean {
return hasRepository(repositoryCoordinates) ||
remoteResolver.acceptsRepository(repositoryCoordinates)
}
override fun addRepository(repositoryCoordinates: RepositoryCoordinates, options: ExternalDependenciesResolver.Options, sourceCodeLocation: SourceCode.LocationWithId?): ResultWithDiagnostics<Boolean> {
val repository = getRepository(repositoryCoordinates) ?: repositoryCoordinates
return remoteResolver.addRepository(repository, options, sourceCodeLocation)
}
companion object {
private class Shortcut(val shortcut: String, pathGetter: () -> String) {
val path = pathGetter()
}
private val HOME_PATH = System.getProperty("user.home") ?: "~"
private const val PREFIX = "*"
private val repositories: Map<String, Shortcut> =
listOf(
Shortcut("mavenLocal") {
// Simplified version, without looking in XML files
val path = System.getProperty("maven.repo.local")
?: "$HOME_PATH/.m2/repository"
path.toURLString()
},
Shortcut("ivyLocal") {
val path = "$HOME_PATH/.ivy2/cache"
path.toURLString()
},
).associateBy {
"$PREFIX${it.shortcut}"
}
fun hasRepository(repository: RepositoryCoordinates): Boolean {
return repositories.containsKey(repository.string)
}
fun getRepository(repository: RepositoryCoordinates): RepositoryCoordinates? {
return repositories[repository.string]?.path?.let { RepositoryCoordinates(it) }
}
private fun String.toURLString(): String {
return File(this).toURI().toURL().toString()
}
}
}
| apache-2.0 | e2ec4151a6263d1e88c793610d46dbb3 | 41.263158 | 205 | 0.664176 | 5.537931 | false | false | false | false |
PropaFramework/Propa | src/test/kotlin/testComponent.kt | 1 | 1893 | import io.propa.framework.component.PropaComponent
import io.propa.framework.component.PropaComponentBuilder
import io.propa.framework.component.invoke
import io.propa.framework.di.PropaInject
import io.propa.framework.di.PropaService
import io.propa.framework.dom.PropaTemplate
import io.propa.framework.dom.div
import io.propa.framework.external.require
import io.propa.framework.snabbdom.plusAssign
/**
* Created by gbaldeck on 5/5/2017.
*/
class LastComponent: PropaComponent(){
companion object: PropaComponentBuilder<LastComponent>
val service: TestService by PropaInject()
// var detect by PropaDetect<String?>(null)
override fun template(): PropaTemplate = {
div {
classes += "this"
// detect = ""
+"NO styles"
div {
classes += "is"
+"styles"
div {
classes += "cool"
+service.test
}
}
}
}
}
class TestComponent: PropaComponent() {
companion object: PropaComponentBuilder<TestComponent>
var setMe: String? = null
val jsConstructor = this::class.js
override var stylesheet: String? = require("resources/styles/test.css")
init {
classes += "red"
}
override fun template():PropaTemplate = {
div {
classes += "awesome"
+"Hells to the yeah"
}
setMe?.let { div { +it } }
LastComponent { inheritStyle = true }
}
}
class EntryComponent: PropaComponent() {
companion object: PropaComponentBuilder<EntryComponent>
override var stylesheet: String? = require("resources/styles/test.css")
init {
classes += "hello"
}
override fun template(): PropaTemplate = {
TestComponent{ classes += "test";
inheritStyle = false}
TestComponent {
classes += "test"
setMe = "Other test component"
inheritStyle = true
}
}
}
class TestService: PropaService {
val test = "It works!"
} | mit | b8d91fb8c106cff8eb30afab5832c9b4 | 21.547619 | 73 | 0.664025 | 3.801205 | false | true | false | false |
felipebz/sonar-plsql | zpa-core/src/main/kotlin/org/sonar/plsqlopen/TokenLocation.kt | 1 | 1974 | /**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plsqlopen
import com.felipebz.flr.api.Token
class TokenLocation private constructor(
private val line: Int,
private val column: Int,
private val endLine: Int,
private val endColumn: Int
) {
fun line() = line
fun column() = column
fun endLine() = endLine
fun endColumn() = endColumn
companion object {
private val pattern = Regex("\\R")
fun from(token: Token): TokenLocation {
val lineCount: Int
var lastLineLength = 0
if (token.value.contains(pattern)) {
val lines = pattern.split(token.value)
lineCount = lines.size
lastLineLength = lines[lines.size - 1].length
} else {
lineCount = 1
}
var endLineOffset = token.column + token.value.length
val endLine = token.line + lineCount - 1
if (endLine != token.line) {
endLineOffset = lastLineLength
}
return TokenLocation(token.line, token.column, endLine, endLineOffset)
}
}
}
| lgpl-3.0 | 2b654e387ce03ca356ef1c2421c110d1 | 30.333333 | 82 | 0.64387 | 4.527523 | false | false | false | false |
moallemi/gradle-advanced-build-version | src/test/kotlin/me/moallemi/gradle/advancedbuildversion/gradleextensions/FileOutputConfigTest.kt | 1 | 6164 | /*
* Copyright 2020 Reza Moallemi
*
* 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.moallemi.gradle.advancedbuildversion.gradleextensions
import com.android.build.gradle.api.ApplicationVariant
import com.android.build.gradle.api.BaseVariantOutput
import com.android.build.gradle.internal.api.BaseVariantOutputImpl
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.slot
import io.mockk.verify
import junit.framework.Assert.assertEquals
import org.gradle.api.Action
import org.gradle.api.DomainObjectSet
import org.gradle.api.Project
import org.junit.After
import org.junit.Test
class FileOutputConfigTest {
private val project: Project = mockk {
every { name } returns APP_NAME
every { rootProject.name } returns PROJECT_NAME
}
private val variants: DomainObjectSet<ApplicationVariant> = mockk()
private val variant: ApplicationVariant = mockk {
every { flavorName } returns FLAVOR_NAME
every { buildType.name } returns BUILD_TYPE
every { versionName } returns VERSION_NAME
every { versionCode } returns VERSION_CODE
}
private val fileOutputConfig = FileOutputConfig(project)
@After
fun tearDown() {
clearAllMocks()
}
@Test
fun `must not rename apk by default`() {
val variants: DomainObjectSet<ApplicationVariant> = mockk()
fileOutputConfig.renameOutputApkIfPossible(variants)
verify(exactly = 0) {
variants.all(any<Action<in ApplicationVariant>>())
}
}
@Test
fun `must not rename apk if renameOutput = false`() {
val variants: DomainObjectSet<ApplicationVariant> = mockk()
fileOutputConfig.renameOutput(false)
fileOutputConfig.renameOutputApkIfPossible(variants)
verify(exactly = 0) {
variants.all(any<Action<in ApplicationVariant>>())
}
}
@Test
fun `must rename apk if renameOutput = true and FLAVOR_NAME is not null`() {
val variantsSlot = slot<Action<in ApplicationVariant>>()
every { variants.all(capture(variantsSlot)) } answers { variantsSlot.captured.execute(variant) }
val baseVariantOutputSlot = slot<String>()
val baseVariantOutput: BaseVariantOutputImpl = mockk {
every { outputFileName = capture(baseVariantOutputSlot) } just runs
}
val outputsSlot = slot<Action<BaseVariantOutput>>()
every { variant.outputs.all(capture(outputsSlot)) } answers { outputsSlot.captured.execute(baseVariantOutput) }
fileOutputConfig.renameOutput(true)
fileOutputConfig.renameOutputApkIfPossible(variants)
verify {
variants.all(any<Action<in ApplicationVariant>>())
variant.outputs.all(any<Action<BaseVariantOutput>>())
}
val apkFileName = "$APP_NAME-$FLAVOR_NAME-$BUILD_TYPE-$VERSION_NAME.apk"
assertEquals(apkFileName, baseVariantOutputSlot.captured)
}
@Test
fun `must rename apk if renameOutput = true and FLAVOR_NAME is null`() {
every { variant.flavorName } returns null
val variantsSlot = slot<Action<in ApplicationVariant>>()
every { variants.all(capture(variantsSlot)) } answers { variantsSlot.captured.execute(variant) }
val baseVariantOutputSlot = slot<String>()
val baseVariantOutput: BaseVariantOutputImpl = mockk {
every { outputFileName = capture(baseVariantOutputSlot) } just runs
}
val outputsSlot = slot<Action<BaseVariantOutput>>()
every { variant.outputs.all(capture(outputsSlot)) } answers { outputsSlot.captured.execute(baseVariantOutput) }
fileOutputConfig.renameOutput(true)
fileOutputConfig.renameOutputApkIfPossible(variants)
verify {
variants.all(any<Action<in ApplicationVariant>>())
variant.outputs.all(any<Action<BaseVariantOutput>>())
}
val apkFileName = "$APP_NAME-$BUILD_TYPE-$VERSION_NAME.apk"
assertEquals(apkFileName, baseVariantOutputSlot.captured)
}
@Test
fun `must rename apk if renameOutput = true and nameFormat MyApp-google-play-VERSION-NAME`() {
every { variant.flavorName } returns null
val variantsSlot = slot<Action<in ApplicationVariant>>()
every { variants.all(capture(variantsSlot)) } answers { variantsSlot.captured.execute(variant) }
val baseVariantOutputSlot = slot<String>()
val baseVariantOutput: BaseVariantOutputImpl = mockk {
every { outputFileName = capture(baseVariantOutputSlot) } just runs
}
val outputsSlot = slot<Action<BaseVariantOutput>>()
every { variant.outputs.all(capture(outputsSlot)) } answers { outputsSlot.captured.execute(baseVariantOutput) }
fileOutputConfig.renameOutput(true)
fileOutputConfig.nameFormat("MyApp-google-play-\$versionName")
fileOutputConfig.renameOutputApkIfPossible(variants)
verify {
variants.all(any<Action<in ApplicationVariant>>())
variant.outputs.all(any<Action<BaseVariantOutput>>())
}
val apkFileName = "MyApp-google-play-$VERSION_NAME.apk"
assertEquals(apkFileName, baseVariantOutputSlot.captured)
}
companion object {
private const val APP_NAME = "APP_NAME"
private const val PROJECT_NAME = "PROJECT_NAME"
private const val FLAVOR_NAME = "FLAVOR_NAME"
private const val BUILD_TYPE = "BUILD_TYPE"
private const val VERSION_NAME = "1.2.3.4"
private const val VERSION_CODE = 1234
}
}
| apache-2.0 | 9eb6e0bf1e4351686c0078052a066511 | 35.258824 | 119 | 0.692083 | 4.453757 | false | true | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/query/s9api/binding/trace/InstructionInfo.kt | 1 | 3168 | /*
* Copyright (C) 2019-2020 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.trace
import uk.co.reecedunn.intellij.plugin.core.reflection.getMethodOrNull
import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.Location
import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.QName
import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.om.StructuredQName
open class InstructionInfo(val saxonObject: Any, private val `class`: Class<*>) : Location {
private val locationClass: Class<*> by lazy {
if (`class`.getMethodOrNull("getLocation") == null)
`class` // Saxon 9
else
`class`.classLoader.loadClass("net.sf.saxon.s9api.Location") // Saxon 10
}
private val location: Any by lazy {
`class`.getMethodOrNull("getLocation")?.invoke(saxonObject) ?: saxonObject
}
override fun getSystemId(): String? {
val id = locationClass.getMethod("getSystemId").invoke(location) as String?
// Saxon <= 9.6 report "*module with no systemId*" for the script being run.
return if (id == "*module with no systemId*") null else id
}
override fun getPublicId(): String? = locationClass.getMethod("getPublicId").invoke(location) as String?
override fun getLineNumber(): Int = locationClass.getMethod("getLineNumber").invoke(location) as Int
override fun getColumnNumber(): Int = locationClass.getMethod("getColumnNumber").invoke(location) as Int
fun getObjectName(): QName? {
val qname = `class`.getMethod("getObjectName").invoke(saxonObject)
return qname?.let { StructuredQName(it, `class`.classLoader.loadClass("net.sf.saxon.om.StructuredQName")) }
}
override fun toString(): String = saxonObject.toString()
override fun hashCode(): Int {
// NOTE: Using saxonObject.hashCode results in ClauseInfo objects not to be grouped.
var result = systemId.hashCode()
result = 31 * result + publicId.hashCode()
result = 31 * result + lineNumber.hashCode()
result = 31 * result + columnNumber.hashCode()
return result
}
override fun equals(other: Any?): Boolean {
if (other !is InstructionInfo) return false
// NOTE: Using saxonObject.equals results in ClauseInfo objects not to be grouped.
return when {
systemId != other.systemId -> false
publicId != other.publicId -> false
lineNumber != other.lineNumber -> false
columnNumber != other.columnNumber -> false
else -> true
}
}
}
| apache-2.0 | be3c6c55f8c0c121692a17559672084f | 41.24 | 115 | 0.6875 | 4.327869 | false | false | false | false |
jiaminglu/kotlin-native | shared/src/main/kotlin/org/jetbrains/kotlin/konan/target/TargetProperties.kt | 1 | 1487 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.konan.properties
import org.jetbrains.kotlin.konan.target.*
fun Properties.hostString(name: String): String?
= this.propertyString(name, TargetManager.host.targetSuffix)
fun Properties.hostList(name: String): List<String>
= this.propertyList(name, TargetManager.host.targetSuffix)
fun Properties.targetString(name: String, target: KonanTarget): String?
= this.propertyString(name, target.targetSuffix)
fun Properties.targetList(name: String, target: KonanTarget): List<String>
= this.propertyList(name, target.targetSuffix)
fun Properties.hostTargetString(name: String, target: KonanTarget): String?
= this.propertyString(name, hostTargetSuffix(TargetManager.host, target))
fun Properties.hostTargetList(name: String, target: KonanTarget): List<String>
= this.propertyList(name, hostTargetSuffix(TargetManager.host, target))
| apache-2.0 | 6bb4e025810db773bf77ef227a1df87c | 39.189189 | 78 | 0.767989 | 3.954787 | false | false | false | false |
Archinamon/GradleAspectJ-Android | android-gradle-aspectj/src/main/kotlin/com/archinamon/api/AspectJWeaver.kt | 1 | 5841 | package com.archinamon.api
import com.archinamon.utils.logBuildParametersAdapted
import com.archinamon.utils.logExtraAjcArgumentAlreadyExists
import org.aspectj.bridge.IMessage
import org.aspectj.bridge.MessageHandler
import org.aspectj.tools.ajc.Main
import org.gradle.api.GradleException
import org.gradle.api.Project
import java.io.File
import java.util.*
import java.util.concurrent.CyclicBarrier
internal class AspectJWeaver(val project: Project) {
private val errorReminder = "Look into %s file for details"
var compilationLogFile: String? = null
internal set(name) {
if (name?.length!! > 0) {
field = project.buildDir.absolutePath + File.separator + name
}
}
var transformLogFile: String? = null
internal set(name) {
if (name?.length!! > 0) {
field = project.buildDir.absolutePath + File.separator + name
}
}
var encoding: String? = null
var weaveInfo: Boolean = false
var debugInfo: Boolean = false
var addSerialVUID: Boolean = false
var noInlineAround: Boolean = false
var ignoreErrors: Boolean = false
var breakOnError: Boolean = false
var experimental: Boolean = false
var ajcArgs = LinkedHashSet<String>()
@Suppress("SetterBackingFieldAssignment")
var ajSources: MutableSet<File> = LinkedHashSet()
internal set(ajSources) {
ajSources.forEach { field.add(it) }
}
var aspectPath: MutableSet<File> = LinkedHashSet()
var inPath: MutableSet<File> = LinkedHashSet()
var classPath: MutableSet<File> = LinkedHashSet()
var bootClasspath: String? = null
var sourceCompatibility: String? = null
var targetCompatibility: String? = null
var destinationDir: String? = null
internal fun doWeave() {
val log = prepareLogger()
//http://www.eclipse.org/aspectj/doc/released/devguide/ajc-ref.html
val args = mutableListOf(
"-encoding", encoding,
"-source", sourceCompatibility,
"-target", targetCompatibility,
"-d", destinationDir,
"-bootclasspath", bootClasspath,
"-classpath", classPath.joinToString(separator = File.pathSeparator)
)
if (ajSources.isNotEmpty()) {
args + "-sourceroots" + ajSources.joinToString(separator = File.pathSeparator)
}
if (inPath.isNotEmpty()) {
args + "-inpath" + inPath.joinToString(separator = File.pathSeparator)
}
if (aspectPath.isNotEmpty()) {
args + "-aspectpath" + aspectPath.joinToString(separator = File.pathSeparator)
}
if (getLogFile().isNotBlank()) {
args + "-log" + getLogFile()
}
if (debugInfo) {
args + "-g"
}
if (weaveInfo) {
args + "-showWeaveInfo"
}
if (addSerialVUID) {
args + "-XaddSerialVersionUID"
}
if (noInlineAround) {
args + "-XnoInline"
}
if (ignoreErrors) {
args + "-proceedOnError" + "-noImportError"
}
if (experimental) {
args + "-XhasMember" + "-Xjoinpoints:synchronization,arrayconstruction"
}
if (ajcArgs.isNotEmpty()) {
ajcArgs.forEach { extra ->
if (extra.startsWith('-') && args.contains(extra)) {
logExtraAjcArgumentAlreadyExists(extra)
log.writeText("[warning] Duplicate argument found while composing ajc config! Build may be corrupted.\n\n")
}
args + extra
}
}
log.writeText("Full ajc build args: ${args.joinToString()}\n\n")
logBuildParametersAdapted(args, log.name)
runBlocking {
val handler = MessageHandler(true)
Main().run(args.toTypedArray(), handler)
for (message in handler.getMessages(null, true)) {
when (message.kind) {
IMessage.ERROR -> {
log.writeText("[error]" + message?.message + "${message?.thrown}\n\n")
if (breakOnError) throw GradleException (errorReminder.format(getLogFile()))
}
IMessage.FAIL, IMessage.ABORT -> {
log.writeText("[error]" + message?.message + "${message?.thrown}\n\n")
throw GradleException (message.message)
}
IMessage.INFO, IMessage.DEBUG, IMessage.WARNING -> {
log.writeText("[warning]" + message?.message + "${message?.thrown}\n\n")
if (getLogFile().isNotBlank()) log.writeText("${errorReminder.format(getLogFile())}\n\n")
}
}
}
detectErrors()
}
}
private fun getLogFile(): String {
return compilationLogFile ?: transformLogFile!!
}
private fun prepareLogger(): File {
val lf = project.file(getLogFile())
if (lf.exists()) {
lf.delete()
}
return lf
}
private fun detectErrors() {
val lf: File = project.file(getLogFile())
if (lf.exists()) {
lf.readLines().reversed().forEach { line ->
if (line.contains("[error]") && breakOnError) {
throw GradleException ("$line\n${errorReminder.format(getLogFile())}")
}
}
}
}
private inline operator fun <reified E> MutableCollection<in E>.plus(elem: E): MutableCollection<in E> {
this.add(elem)
return this
}
private companion object {
fun runBlocking(action: () -> Unit) = synchronized(Companion::class, action)
}
} | apache-2.0 | 62f202ce31bd61431247231fa34e4e73 | 30.75 | 127 | 0.568225 | 4.639396 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.