repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
53 values
size
stringlengths
2
6
content
stringlengths
73
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
977
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
yukuku/androidbible
Alkitab/src/main/java/yuku/alkitab/base/util/Appearances.kt
1
3376
package yuku.alkitab.base.util import android.graphics.Typeface import android.text.SpannableStringBuilder import android.text.Spanned import android.text.method.LinkMovementMethod import android.text.style.UnderlineSpan import android.util.TypedValue import android.widget.TextView import androidx.core.text.underline import yuku.alkitab.base.S object Appearances { @JvmStatic fun applyMarkerSnippetContentAndAppearance(t: TextView, reference: String, verseText: CharSequence, textSizeMult: Float) { val sb = SpannableStringBuilder().apply { underline { append(reference) } append(" ") append(verseText) } t.text = sb applyTextAppearance(t, textSizeMult) } @JvmStatic fun applyTextAppearance(t: TextView, fontSizeMultiplier: Float) { val applied = S.applied() t.setTypeface(applied.fontFace, applied.fontBold) t.setTextSize(TypedValue.COMPLEX_UNIT_DIP, applied.fontSize2dp * fontSizeMultiplier) t.includeFontPadding = false t.setTextColor(applied.fontColor) t.setLinkTextColor(applied.fontColor) t.setLineSpacing(0f, applied.lineSpacingMult) } @JvmStatic fun applyPericopeTitleAppearance(t: TextView, fontSizeMultiplier: Float) { val applied = S.applied() t.setTypeface(applied.fontFace, Typeface.BOLD) t.setTextSize(TypedValue.COMPLEX_UNIT_DIP, applied.fontSize2dp * fontSizeMultiplier) t.setTextColor(applied.fontColor) t.setLineSpacing(0f, applied.lineSpacingMult) } @JvmStatic fun applyPericopeParallelTextAppearance(t: TextView, fontSizeMultiplier: Float) { val applied = S.applied() t.typeface = applied.fontFace t.setTextSize(TypedValue.COMPLEX_UNIT_DIP, applied.fontSize2dp * 0.8235294f * fontSizeMultiplier) t.movementMethod = LinkMovementMethod.getInstance() t.setTextColor(applied.fontColor) t.setLinkTextColor(applied.fontColor) t.setLineSpacing(0f, applied.lineSpacingMult) } @JvmStatic fun applySearchResultReferenceAppearance(t: TextView, sb: SpannableStringBuilder, textSizeMult: Float) { applyMarkerTitleTextAppearance(t, textSizeMult) sb.setSpan(UnderlineSpan(), 0, sb.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) t.text = sb t.setLineSpacing(0f, S.applied().lineSpacingMult) } @JvmStatic fun applyMarkerTitleTextAppearance(t: TextView, textSizeMult: Float) { val applied = S.applied() t.setTypeface(applied.fontFace, applied.fontBold) t.setTextSize(TypedValue.COMPLEX_UNIT_DIP, applied.fontSize2dp * 1.2f * textSizeMult) t.setTextColor(applied.fontColor) } @JvmStatic fun applyMarkerDateTextAppearance(t: TextView, textSizeMult: Float) { val applied = S.applied() t.setTextSize(TypedValue.COMPLEX_UNIT_DIP, applied.fontSize2dp * 0.8f * textSizeMult) t.setTextColor(applied.fontColor) } @JvmStatic fun applyVerseNumberAppearance(t: TextView, textSizeMult: Float) { val applied = S.applied() t.setTypeface(applied.fontFace, applied.fontBold) t.setTextSize(TypedValue.COMPLEX_UNIT_DIP, applied.fontSize2dp * 0.7f * textSizeMult) t.includeFontPadding = false t.setTextColor(applied.verseNumberColor) } }
apache-2.0
b057d395f41d0ccfd056ee11d1c9a5ea
35.301075
126
0.708531
4.430446
false
false
false
false
MimiReader/mimi-reader
mimi-app/src/main/java/com/emogoth/android/phone/mimi/fourchan/models/archives/FoolFuukaThread.kt
1
5895
package com.emogoth.android.phone.mimi.fourchan.models.archives import com.mimireader.chanlib.interfaces.ArchiveConverter import com.mimireader.chanlib.models.ArchivedChanPost import com.mimireader.chanlib.models.ArchivedChanThread import java.util.* class FoolFuukaThreadConverter(val thread: Map<String, FoolFuukaPosts>) : ArchiveConverter { override fun toArchivedThread(board: String, threadId: Long, name: String, domain: String): ArchivedChanThread { if (thread.size != 1) { throw Exception("Thread map should only contain one item") } val posts = ArrayList<ArchivedChanPost>() for (threadEntry in thread) { val threadPosts = threadEntry.value posts.add(toArchivedPost(threadPosts.op)) if (threadPosts.posts != null) { for (foolfuukaPost in threadPosts.posts) { posts.add(toArchivedPost(foolfuukaPost.value)) } } } return ArchivedChanThread(board, threadId, posts, name, domain) } fun toArchivedPost(foolFuukaPost: Post): ArchivedChanPost { val post = ArchivedChanPost() post.isClosed = foolFuukaPost.locked.toBoolean() post.isSticky = foolFuukaPost.sticky.toBoolean() post.com = normalizeComment(foolFuukaPost.comment_processed) post.time = foolFuukaPost.timestamp post.sub = foolFuukaPost.title post.no = foolFuukaPost.num.toLong() post.name = foolFuukaPost.name post.trip = foolFuukaPost.trip post.capcode = foolFuukaPost.capcode post.trollCountry = foolFuukaPost.poster_country post.country = foolFuukaPost.poster_country post.countryName = foolFuukaPost.poster_country_name post.resto = foolFuukaPost.thread_num.toInt() if (foolFuukaPost.media != null) { post.mediaLink = foolFuukaPost.media.remote_media_link ?: foolFuukaPost.media.media_link post.thumbLink = foolFuukaPost.media.thumb_link post.thumbnailHeight = foolFuukaPost.media.preview_h.toInt() post.thumbnailWidth = foolFuukaPost.media.preview_w.toInt() post.width = foolFuukaPost.media.media_w.toInt() post.height = foolFuukaPost.media.media_h.toInt() post.fsize = foolFuukaPost.media.media_size.toInt() post.filename = foolFuukaPost.media.media_filename val lastDotPos = foolFuukaPost.media.media_filename.lastIndexOf('.') val tim: String val ext: String if (lastDotPos > 0) { tim = foolFuukaPost.media.media_filename.substring(0, lastDotPos - 1) ext = foolFuukaPost.media.media_filename.substring(lastDotPos) } else { tim = foolFuukaPost.media.media_filename ext = ".???" } post.tim = tim post.ext = ext } return post } private fun normalizeComment(com: String): String { val quoteLink = "class=\"quotelink\"" var updatedComment = com.replace("greentext", "quote") updatedComment = updatedComment.replace("class=\"backlink\"", quoteLink) updatedComment = updatedComment.replace("class=\"backlink op\"", quoteLink) updatedComment = updatedComment.replace("\n", "") updatedComment = updatedComment.replace("<br />", "<br>") var cursor = 0 var quoteLinkStart = updatedComment.indexOf(quoteLink) while (quoteLinkStart >= 0) { val quoteLinkEnd = updatedComment.indexOf('>', quoteLinkStart) updatedComment = updatedComment.removeRange(quoteLinkStart + quoteLink.length, quoteLinkEnd) cursor = quoteLinkEnd quoteLinkStart = updatedComment.indexOf(quoteLink, cursor) } return updatedComment } } data class FoolFuukaPosts( val op: Post, val posts: Map<String, Post> = HashMap() ) data class Board( val name: String, val shortname: String ) data class Media( val banned: String, val exif: Any, val media: String, val media_filename: String, val media_filename_processed: String, val media_h: String, val media_hash: String, val media_id: String, val media_link: String?, val media_orig: String, val media_size: String, val media_status: String, val media_w: String, val preview_h: String, val preview_op: String, val preview_orig: String, val preview_reply: Any, val preview_w: String, val remote_media_link: String?, val safe_media_hash: String, val spoiler: String, val thumb_link: String?, val total: String ) data class Post( val board: Board, val capcode: String, val comment: String, val comment_processed: String, val comment_sanitized: String, val deleted: String, val doc_id: String, val email: String, val email_processed: String, val formatted: Boolean, val fourchan_date: String, val locked: String, val media: Media?, val name: String, val name_processed: String, val nimages: Any, val nreplies: Any, val num: String, val op: String, val poster_country: String, val poster_country_name: String, val poster_country_name_processed: String, val poster_hash: String, val poster_hash_processed: String, val sticky: String, val subnum: String, val thread_num: String, val timestamp: Long, val timestamp_expired: String, val title: String, val title_processed: String, val trip: String, val trip_processed: String )
apache-2.0
248cf48f90f68b257132bb07fdacbc47
34.518072
116
0.620356
4.541602
false
false
false
false
CherepanovAleksei/BinarySearchTree
src/BinaryTree/BinTree.kt
1
3655
/** * * by Cherepanov Aleksei (PI-171) * * [email protected] * **/ package BinaryTree import Interfaces.Tree class BinarySearchTree<K:Comparable<K>,V>: Tree<K, V>, Iterable<BinNode<K, V>>{ private var root: BinNode<K, V>? = null override fun insert(key:K,value:V) { val newNode = BinNode(key, value) if (this.root == null){ this.root = newNode return } var buff = root var parent:BinNode<K,V>? while (true){ parent=buff if(newNode.key > parent!!.key){ buff=parent.right if (buff == null){ parent.right=newNode newNode.parent=parent return } }else if(newNode.key < buff!!.key){ buff=parent.left if (buff == null){ parent.left=newNode newNode.parent=parent return } }else if(newNode.key == buff.key){ buff.value=newNode.value return } } } override fun delete(key:K){ val delNode = searchNode(key) ?: return if (delNode.left == null){ transplant(delNode,delNode.right) } else if (delNode.right == null) { transplant(delNode,delNode.left) } else { val y=searchMin(delNode.right) if (y?.parent != delNode){ transplant(y,y?.right) y?.right=delNode.right y?.right?.parent=y } transplant(delNode,y) y?.left=delNode.left y?.left?.parent=y } } private fun transplant(u: BinNode<K,V>?,v: BinNode<K,V>?){ if (u?.parent ==null) this.root=v else if(u == u.parent!!.left) u.parent!!.left=v else u.parent?.right=v if (v!=null) v.parent= u?.parent } override fun search(key: K)=searchNode(key)?.value private fun searchNode(key: K, node: BinNode<K,V>?=root): BinNode<K,V>? { if(node==null) return null if(key == node.key)return node if(key < node.key) return searchNode(key, node.left) else return searchNode(key, node.right) } private fun searchMax(node: BinNode<K, V>?=root): BinNode<K, V>? { var max = node while (max?.right != null) { max = max.right } return max } private fun searchMin(node: BinNode<K, V>?=root): BinNode<K, V>? { var min = node while (min?.left != null) { min = min.left } return min } override fun iterator(): Iterator<BinNode<K, V>> { return (object : Iterator<BinNode<K, V>> { var node = searchMax() var next = searchMax() val last = searchMin() override fun hasNext(): Boolean { return node != null && node!!.key >= last!!.key } override fun next(): BinNode<K, V> { next = node node = nextSmaller(node) return next!! } }) } private fun nextSmaller(node: BinNode<K, V>?): BinNode<K, V>?{ var smaller = node ?: return null if ((smaller.left != null)) { return searchMax(smaller.left) } else if ((smaller == smaller.parent?.left)) { while (smaller == smaller?.parent?.left) { smaller = smaller?.parent!! } } return smaller.parent } }
mit
ee71e6eae51974184fd11ea1f2725818
27.115385
79
0.482079
4.181922
false
false
false
false
ArdentDiscord/ArdentKotlin
src/main/kotlin/commands/games/Games.kt
1
5460
package commands.games /* import events.Category import events.Category.GAMES import events.Command import main.test import main.waiter import net.dv8tion.jda.api.entities.TextChannel import net.dv8tion.jda.api.entities.User import net.dv8tion.jda.api.events.message.MessageReceivedEvent import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent import translation.tr import utils.* import utils.discord.getData import utils.discord.send import utils.discord.toUser import utils.functionality.* import java.awt.Color import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit val invites = ConcurrentHashMap<String, Game>() val questions = mutableListOf<TriviaQuestion>() class BetGame(channel: TextChannel, creator: String) : Game(GameType.BETTING, channel, creator, 1, false) { private val rounds = mutableListOf<Round>() override fun onStart() { doRound(creator.toUser()!!) } private fun doRound(user: User) { val data = user.getData() channel.send("bet.how_much").apply(data.gold) waiter.waitForMessage(Settings(user.id, channel.id), { message -> val content = message.contentRaw.removePrefix("/bet ").replace("bet ", "") if (content.equals("cancel", true) ){ channel.send("games.cancel") cancel(user) } else { val bet = if (content.contains("%")) content.removeSuffix("%").toDoubleOrNull()?.div(100)?.times(data.gold)?.toInt() else content.toIntOrNull() if (bet != null) { if (bet > data.gold || bet <= 0) { channel.send("bet.invalid_amount") doRound(user) return@waitForMessage } else { channel.selectFromList(channel.guild.getMember(user)!!, "bet.embed_title", mutableListOf("color.black"), "color.red", { selection, _ -> val suit = BlackjackGame.Hand(false, end = false).generate().suit val won = when (suit) { BlackjackGame.Suit.HEART, BlackjackGame.Suit.DIAMOND -> selection == 1 else -> selection == 0 } if (won) { data.gold += bet channel.send("Congrats, you won - the suit was []! I've added **[] gold** to your profile - new balance: **[] gold**".apply(suit, bet, data.gold.format())) } else { data.gold -= bet channel.send("Sorry, you lost - the suit was [] :( I've removed **[] gold** from your profile - new balance: **[] gold**".apply(suit, bet, data.gold.format())) } .database.update(data) rounds.add(Round(won, bet.toDouble(), suit)) channel.send("bet.go_again") Sender.waitForMessage({ it.author.id == user.id && it.guild.id == channel.guild.id && it.channel.id == channel.id }, { if (it.message.contentRaw.startsWith("y", true)) doRound(user) else { channel.send("bet.end") val gameData = GameDataBetting(gameId, creator, startTime!!, rounds) cleanup(gameData) } }, { channel.send("bet.end") val gameData = GameDataBetting(gameId, creator, startTime!!, rounds) cleanup(gameData) }) }, failure = { if (rounds.size == 0) { channel.send("games.invalid_response_cancel") cancel(user) } else { channel.send("games.invalid_response_end_game") val gameData = GameDataBetting(gameId, creator, startTime!!, rounds) cleanup(gameData) } } ) } } else { if (rounds.size == 0) { channel.send("games.invalid_response_cancel") cancel(user) } else { channel.send("games.invalid_response_end_game") val gameData = GameDataBetting(gameId, creator, startTime!!, rounds) cleanup(gameData) } } } }, { cancel(user) }, time = 20) } data class Round(val won: Boolean, val betAmount: Double, val suit: BlackjackGame.Suit) } class BetCommand : Command(GAMES, "bet", "placeholder") { override fun executeBase(arguments: MutableList<String>, event: MessageReceivedEvent) { val member = event.member if (member!!.isInGameOrLobby()) event.channel.send("games.already_in_game".tr(event, member.asMention)) else BetGame(event.textChannel, member.user.id).startEvent() } } */
apache-2.0
d96bb71c37cb0ab9b2fa35b73c899ba1
46.077586
191
0.501282
4.954628
false
false
false
false
cashapp/sqldelight
sqldelight-idea-plugin/src/main/kotlin/app/cash/sqldelight/intellij/run/RunSqlAction.kt
1
2149
package app.cash.sqldelight.intellij.run import app.cash.sqldelight.core.compiler.model.BindableQuery import app.cash.sqldelight.core.lang.psi.StmtIdentifier import app.cash.sqldelight.core.lang.util.range import app.cash.sqldelight.core.lang.util.rawSqlText import app.cash.sqldelight.dialect.api.ConnectionManager import com.alecstrong.sql.psi.core.psi.SqlStmt import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import org.jetbrains.annotations.VisibleForTesting import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespace @VisibleForTesting internal class RunSqlAction( private val stmt: SqlStmt, private val connectionManager: ConnectionManager, private val project: Project = stmt.project, private val executor: SqlDelightStatementExecutor = SqlDelightStatementExecutor( project, connectionManager, ), private val dialogFactory: ArgumentsInputDialog.Factory = ArgumentsInputDialogFactoryImpl(), ) : AnAction() { override fun actionPerformed(e: AnActionEvent) { val parameters = findParameters(stmt) val replacements = if (parameters.isEmpty()) { emptyList() } else { val dialog = dialogFactory.create(project, parameters) if (!dialog.showAndGet() || dialog.result.any { it.value.isEmpty() }) return dialog.result.map { p -> p.range to p.value } } val sqlStmt = stmt.rawSqlText(replacements).trim().replace("\\s+".toRegex(), " ") val identifier = stmt.getPrevSiblingIgnoringWhitespace() as? StmtIdentifier executor.execute(sqlStmt, identifier) } private fun findParameters( sqlStmt: SqlStmt, ): List<SqlParameter> { val bindableQuery = object : BindableQuery(null, sqlStmt) { override val id = 0 } val argumentList: List<IntRange> = bindableQuery.arguments .flatMap { it.bindArgs } .map { it.range } val parameters: List<String> = bindableQuery.parameters.map { it.name } return argumentList.zip(parameters) { range, name -> SqlParameter( name = name, range = range, ) } } }
apache-2.0
ad87f604972543490eaabe9b96c97144
36.701754
94
0.741275
4.298
false
false
false
false
isuPatches/WiseFy
wisefysample/src/androidTest/java/com/isupatches/wisefysample/internal/preferences/InMemorySearchStore.kt
1
1570
package com.isupatches.wisefysample.internal.preferences import com.isupatches.wisefysample.internal.models.SearchType internal class InMemorySearchStore : SearchStore { private var lastUsedRegex: String = "" private var searchType: SearchType = SearchType.ACCESS_POINT private var returnFullList: Boolean = true private var filterDuplicates: Boolean = true private var timeout: Int = 1 override fun clear() { lastUsedRegex = "" searchType = SearchType.ACCESS_POINT returnFullList = true filterDuplicates = true timeout = 1 } /* * Last Used Regex */ override fun getLastUsedRegex() = lastUsedRegex override fun setLastUsedRegex(lastUsedRegex: String) { this.lastUsedRegex = lastUsedRegex } /* * Search Type */ override fun getSearchType() = searchType override fun setSearchType(searchType: SearchType) { this.searchType = searchType } /* * Return Full List */ override fun shouldReturnFullList() = returnFullList override fun setReturnFullList(returnFullList: Boolean) { this.returnFullList = returnFullList } /* * Filter Duplicates */ override fun shouldFilterDuplicates() = filterDuplicates override fun setFilterDuplicates(filterDuplicates: Boolean) { this.filterDuplicates = filterDuplicates } /* * Timeout */ override fun getTimeout() = timeout override fun setTimeout(timeout: Int) { this.timeout = timeout } }
apache-2.0
e945da81e33a1618dec68bf13c68f880
23.153846
65
0.666879
5
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/mark/canvas/CanvasKit.kt
1
2525
package com.tamsiree.rxui.view.mark.canvas import android.graphics.* import android.graphics.drawable.Drawable import androidx.annotation.ColorInt import androidx.annotation.Px import com.tamsiree.rxui.view.mark.model.Coordinate import com.tamsiree.rxui.view.mark.model.ParentMetrics object CanvasKit { /** * Draws a backdrop rectangle with a given paint on the receiving canvas */ internal fun Canvas.drawBackdropRectangle(parentMetrics: ParentMetrics, canvasY: Float, paint: Paint) { val (parentWidth, parentHeight) = parentMetrics save() translate(0F, canvasY) clipRect(0F, 0F, parentWidth, parentHeight) drawRect(0F, 0F, parentWidth, parentHeight, paint) restore() } /** * Draws a backdrop circle with a given animated value on the receiving canvas */ internal fun Canvas.drawBackdropCircle( parentMetrics: ParentMetrics, canvasY: Float, paint: Paint, centerCoordinate: Coordinate, radius: Float) { val (parentWidth, parentHeight) = parentMetrics val (cX, cY) = centerCoordinate save() translate(0F, canvasY) clipRect(0F, 0F, parentWidth, parentHeight) drawCircle(cX, cY, radius, paint) restore() } /** * Draws a drawable on the canvas at the input coordinates */ internal fun Canvas.drawDrawable( canvasY: Float, centerCoordinate: Coordinate, drawable: Drawable, @ColorInt colorInt: Int, @Px iconSizePx: Int, circularClipRadius: Float?) { if (circularClipRadius != null && circularClipRadius <= 0f) { return } val (centerX, centerY) = centerCoordinate val left = centerX - (0.5 * iconSizePx) val top = centerY - (0.5 * iconSizePx) val right = left + iconSizePx val bottom = top + iconSizePx val bounds = Rect( left.toInt(), top.toInt(), right.toInt(), bottom.toInt()) drawable.bounds = bounds save() translate(0F, canvasY) if (circularClipRadius != null) { clipPath(Path().apply { addCircle(centerX, centerY, circularClipRadius, Path.Direction.CCW) }) } drawable.setColorFilter(colorInt, PorterDuff.Mode.SRC_IN) drawable.draw(this) restore() } }
apache-2.0
f27b27d1d0d1fef514e353bfe1e55aac
29.804878
106
0.596436
4.737336
false
false
false
false
openstreetview/android
app/src/main/java/com/telenav/osv/data/collector/phonedata/collector/MobileDataCollector.kt
1
3581
package com.telenav.osv.data.collector.phonedata.collector import android.content.Context import android.net.ConnectivityManager import android.net.NetworkInfo import android.os.Handler import android.telephony.TelephonyManager import androidx.annotation.StringDef import com.telenav.osv.data.collector.datatype.datatypes.MobileDataObject import com.telenav.osv.data.collector.datatype.util.LibraryUtil import com.telenav.osv.data.collector.phonedata.manager.PhoneDataListener /** * MobileDataCollector class retrieves information about mobile data connection */ class MobileDataCollector(private val context: Context, phoneDataListener: PhoneDataListener?, notifyHandler: Handler?) : PhoneCollector(phoneDataListener, notifyHandler) { /** * Retrieve information about mobile data connection and sent it to the client * The method is called once when the service is started */ fun sendMobileDataInformation() { val connectionType = StringBuilder() if (isMobileConnected) { connectionType.append(networkOperatorName).append(" ").append(networkClass) } else { connectionType.append("Mobile data is not available") } onNewSensorEvent(MobileDataObject(connectionType.toString(), LibraryUtil.PHONE_SENSOR_READ_SUCCESS)) } /** * Returns the type of the connection: 2G, 3G, 4G * * @return */ @get:NetworkType val networkClass: String get() { val mTelephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager val networkType = mTelephonyManager.networkType return when (networkType) { TelephonyManager.NETWORK_TYPE_GPRS, TelephonyManager.NETWORK_TYPE_EDGE, TelephonyManager.NETWORK_TYPE_CDMA, TelephonyManager.NETWORK_TYPE_1xRTT, TelephonyManager.NETWORK_TYPE_IDEN -> NETWORK_2G TelephonyManager.NETWORK_TYPE_UMTS, TelephonyManager.NETWORK_TYPE_EVDO_0, TelephonyManager.NETWORK_TYPE_EVDO_A, TelephonyManager.NETWORK_TYPE_HSDPA, TelephonyManager.NETWORK_TYPE_HSUPA, TelephonyManager.NETWORK_TYPE_HSPA, TelephonyManager.NETWORK_TYPE_EVDO_B, TelephonyManager.NETWORK_TYPE_EHRPD, TelephonyManager.NETWORK_TYPE_HSPAP -> NETWORK_3G TelephonyManager.NETWORK_TYPE_LTE -> NETWORK_4G else -> UNKNOWN_NETWORK } } /** * @return true, if mobile is connected */ private val isMobileConnected: Boolean get() { var info: NetworkInfo? = null val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager if (cm != null) { info = cm.activeNetworkInfo } return info != null && info.isConnected && info.type == ConnectivityManager.TYPE_MOBILE } /** * @return network operator name (carrier info) */ private val networkOperatorName: String get() { val manager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager return manager.networkOperatorName } @kotlin.annotation.Retention(AnnotationRetention.SOURCE) @StringDef(NETWORK_2G, NETWORK_3G, NETWORK_4G, UNKNOWN_NETWORK) internal annotation class NetworkType companion object { /** * BleConstants used for identify the mobile data connection */ const val NETWORK_4G = "4G" const val NETWORK_3G = "3G" const val NETWORK_2G = "2G" const val UNKNOWN_NETWORK = "UNKNOWN_CELLULAR" } }
lgpl-3.0
0753e07fd88f553c737290bdb167899e
42.156627
362
0.695895
4.761968
false
false
false
false
wendigo/chrome-reactive-kotlin
src/main/kotlin/pl/wendigo/chrome/api/runtime/Domain.kt
1
44743
package pl.wendigo.chrome.api.runtime import kotlinx.serialization.json.Json /** * Runtime domain exposes JavaScript runtime by means of remote evaluation and mirror objects. Evaluation results are returned as mirror object that expose object type, string representation and unique identifier that can be used for further object reference. Original objects are maintained in memory unless they are either explicitly released or are released along with the other objects in their object group. * * @link Protocol [Runtime](https://chromedevtools.github.io/devtools-protocol/tot/Runtime) domain documentation. */ class RuntimeDomain internal constructor(connection: pl.wendigo.chrome.protocol.ProtocolConnection) : pl.wendigo.chrome.protocol.Domain( "Runtime", """Runtime domain exposes JavaScript runtime by means of remote evaluation and mirror objects. Evaluation results are returned as mirror object that expose object type, string representation and unique identifier that can be used for further object reference. Original objects are maintained in memory unless they are either explicitly released or are released along with the other objects in their object group.""", connection ) { /** * Add handler to promise with given promise object id. * * @link Protocol [Runtime#awaitPromise](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-awaitPromise) method documentation. */ fun awaitPromise(input: AwaitPromiseRequest): io.reactivex.rxjava3.core.Single<AwaitPromiseResponse> = connection.request("Runtime.awaitPromise", Json.encodeToJsonElement(AwaitPromiseRequest.serializer(), input), AwaitPromiseResponse.serializer()) /** * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. * * @link Protocol [Runtime#callFunctionOn](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-callFunctionOn) method documentation. */ fun callFunctionOn(input: CallFunctionOnRequest): io.reactivex.rxjava3.core.Single<CallFunctionOnResponse> = connection.request("Runtime.callFunctionOn", Json.encodeToJsonElement(CallFunctionOnRequest.serializer(), input), CallFunctionOnResponse.serializer()) /** * Compiles expression. * * @link Protocol [Runtime#compileScript](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-compileScript) method documentation. */ fun compileScript(input: CompileScriptRequest): io.reactivex.rxjava3.core.Single<CompileScriptResponse> = connection.request("Runtime.compileScript", Json.encodeToJsonElement(CompileScriptRequest.serializer(), input), CompileScriptResponse.serializer()) /** * Disables reporting of execution contexts creation. * * @link Protocol [Runtime#disable](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-disable) method documentation. */ fun disable(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Runtime.disable", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Discards collected exceptions and console API calls. * * @link Protocol [Runtime#discardConsoleEntries](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-discardConsoleEntries) method documentation. */ fun discardConsoleEntries(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Runtime.discardConsoleEntries", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Enables reporting of execution contexts creation by means of `executionContextCreated` event. When the reporting gets enabled the event will be sent immediately for each existing execution context. * * @link Protocol [Runtime#enable](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-enable) method documentation. */ fun enable(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Runtime.enable", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Evaluates expression on global object. * * @link Protocol [Runtime#evaluate](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-evaluate) method documentation. */ fun evaluate(input: EvaluateRequest): io.reactivex.rxjava3.core.Single<EvaluateResponse> = connection.request("Runtime.evaluate", Json.encodeToJsonElement(EvaluateRequest.serializer(), input), EvaluateResponse.serializer()) /** * Returns the isolate id. * * @link Protocol [Runtime#getIsolateId](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getIsolateId) method documentation. */ @pl.wendigo.chrome.protocol.Experimental fun getIsolateId(): io.reactivex.rxjava3.core.Single<GetIsolateIdResponse> = connection.request("Runtime.getIsolateId", null, GetIsolateIdResponse.serializer()) /** * Returns the JavaScript heap usage. It is the total usage of the corresponding isolate not scoped to a particular Runtime. * * @link Protocol [Runtime#getHeapUsage](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getHeapUsage) method documentation. */ @pl.wendigo.chrome.protocol.Experimental fun getHeapUsage(): io.reactivex.rxjava3.core.Single<GetHeapUsageResponse> = connection.request("Runtime.getHeapUsage", null, GetHeapUsageResponse.serializer()) /** * Returns properties of a given object. Object group of the result is inherited from the target object. * * @link Protocol [Runtime#getProperties](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getProperties) method documentation. */ fun getProperties(input: GetPropertiesRequest): io.reactivex.rxjava3.core.Single<GetPropertiesResponse> = connection.request("Runtime.getProperties", Json.encodeToJsonElement(GetPropertiesRequest.serializer(), input), GetPropertiesResponse.serializer()) /** * Returns all let, const and class variables from global scope. * * @link Protocol [Runtime#globalLexicalScopeNames](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-globalLexicalScopeNames) method documentation. */ fun globalLexicalScopeNames(input: GlobalLexicalScopeNamesRequest): io.reactivex.rxjava3.core.Single<GlobalLexicalScopeNamesResponse> = connection.request("Runtime.globalLexicalScopeNames", Json.encodeToJsonElement(GlobalLexicalScopeNamesRequest.serializer(), input), GlobalLexicalScopeNamesResponse.serializer()) /** * * * @link Protocol [Runtime#queryObjects](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-queryObjects) method documentation. */ fun queryObjects(input: QueryObjectsRequest): io.reactivex.rxjava3.core.Single<QueryObjectsResponse> = connection.request("Runtime.queryObjects", Json.encodeToJsonElement(QueryObjectsRequest.serializer(), input), QueryObjectsResponse.serializer()) /** * Releases remote object with given id. * * @link Protocol [Runtime#releaseObject](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-releaseObject) method documentation. */ fun releaseObject(input: ReleaseObjectRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Runtime.releaseObject", Json.encodeToJsonElement(ReleaseObjectRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Releases all remote objects that belong to a given group. * * @link Protocol [Runtime#releaseObjectGroup](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-releaseObjectGroup) method documentation. */ fun releaseObjectGroup(input: ReleaseObjectGroupRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Runtime.releaseObjectGroup", Json.encodeToJsonElement(ReleaseObjectGroupRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Tells inspected instance to run if it was waiting for debugger to attach. * * @link Protocol [Runtime#runIfWaitingForDebugger](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-runIfWaitingForDebugger) method documentation. */ fun runIfWaitingForDebugger(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Runtime.runIfWaitingForDebugger", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Runs script with given id in a given context. * * @link Protocol [Runtime#runScript](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-runScript) method documentation. */ fun runScript(input: RunScriptRequest): io.reactivex.rxjava3.core.Single<RunScriptResponse> = connection.request("Runtime.runScript", Json.encodeToJsonElement(RunScriptRequest.serializer(), input), RunScriptResponse.serializer()) /** * Enables or disables async call stacks tracking. * * @link Protocol [Runtime#setAsyncCallStackDepth](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-setAsyncCallStackDepth) method documentation. */ fun setAsyncCallStackDepth(input: SetAsyncCallStackDepthRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Runtime.setAsyncCallStackDepth", Json.encodeToJsonElement(SetAsyncCallStackDepthRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * * * @link Protocol [Runtime#setCustomObjectFormatterEnabled](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-setCustomObjectFormatterEnabled) method documentation. */ @pl.wendigo.chrome.protocol.Experimental fun setCustomObjectFormatterEnabled(input: SetCustomObjectFormatterEnabledRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Runtime.setCustomObjectFormatterEnabled", Json.encodeToJsonElement(SetCustomObjectFormatterEnabledRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * * * @link Protocol [Runtime#setMaxCallStackSizeToCapture](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-setMaxCallStackSizeToCapture) method documentation. */ @pl.wendigo.chrome.protocol.Experimental fun setMaxCallStackSizeToCapture(input: SetMaxCallStackSizeToCaptureRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Runtime.setMaxCallStackSizeToCapture", Json.encodeToJsonElement(SetMaxCallStackSizeToCaptureRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Terminate current or next JavaScript execution. Will cancel the termination when the outer-most script execution ends. * * @link Protocol [Runtime#terminateExecution](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-terminateExecution) method documentation. */ @pl.wendigo.chrome.protocol.Experimental fun terminateExecution(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Runtime.terminateExecution", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * If executionContextId is empty, adds binding with the given name on the global objects of all inspected contexts, including those created later, bindings survive reloads. Binding function takes exactly one argument, this argument should be string, in case of any other input, function throws an exception. Each binding function call produces Runtime.bindingCalled notification. * * @link Protocol [Runtime#addBinding](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-addBinding) method documentation. */ @pl.wendigo.chrome.protocol.Experimental fun addBinding(input: AddBindingRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Runtime.addBinding", Json.encodeToJsonElement(AddBindingRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * This method does not remove binding function from global object but unsubscribes current runtime agent from Runtime.bindingCalled notifications. * * @link Protocol [Runtime#removeBinding](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-removeBinding) method documentation. */ @pl.wendigo.chrome.protocol.Experimental fun removeBinding(input: RemoveBindingRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Runtime.removeBinding", Json.encodeToJsonElement(RemoveBindingRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Notification is issued every time when binding is called. */ fun bindingCalled(): io.reactivex.rxjava3.core.Flowable<BindingCalledEvent> = connection.events("Runtime.bindingCalled", BindingCalledEvent.serializer()) /** * Issued when console API was called. */ fun consoleAPICalled(): io.reactivex.rxjava3.core.Flowable<ConsoleAPICalledEvent> = connection.events("Runtime.consoleAPICalled", ConsoleAPICalledEvent.serializer()) /** * Issued when unhandled exception was revoked. */ fun exceptionRevoked(): io.reactivex.rxjava3.core.Flowable<ExceptionRevokedEvent> = connection.events("Runtime.exceptionRevoked", ExceptionRevokedEvent.serializer()) /** * Issued when exception was thrown and unhandled. */ fun exceptionThrown(): io.reactivex.rxjava3.core.Flowable<ExceptionThrownEvent> = connection.events("Runtime.exceptionThrown", ExceptionThrownEvent.serializer()) /** * Issued when new execution context is created. */ fun executionContextCreated(): io.reactivex.rxjava3.core.Flowable<ExecutionContextCreatedEvent> = connection.events("Runtime.executionContextCreated", ExecutionContextCreatedEvent.serializer()) /** * Issued when execution context is destroyed. */ fun executionContextDestroyed(): io.reactivex.rxjava3.core.Flowable<ExecutionContextDestroyedEvent> = connection.events("Runtime.executionContextDestroyed", ExecutionContextDestroyedEvent.serializer()) /** * Issued when all executionContexts were cleared in browser */ fun executionContextsCleared(): io.reactivex.rxjava3.core.Flowable<pl.wendigo.chrome.protocol.RawEvent> = connection.events("Runtime.executionContextsCleared", pl.wendigo.chrome.protocol.RawEvent.serializer()) /** * Issued when object should be inspected (for example, as a result of inspect() command line API call). */ fun inspectRequested(): io.reactivex.rxjava3.core.Flowable<InspectRequestedEvent> = connection.events("Runtime.inspectRequested", InspectRequestedEvent.serializer()) } /** * Represents request frame that can be used with [Runtime#awaitPromise](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-awaitPromise) operation call. * * Add handler to promise with given promise object id. * @link [Runtime#awaitPromise](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-awaitPromise) method documentation. * @see [RuntimeDomain.awaitPromise] */ @kotlinx.serialization.Serializable data class AwaitPromiseRequest( /** * Identifier of the promise. */ val promiseObjectId: RemoteObjectId, /** * Whether the result is expected to be a JSON object that should be sent by value. */ val returnByValue: Boolean? = null, /** * Whether preview should be generated for the result. */ val generatePreview: Boolean? = null ) /** * Represents response frame that is returned from [Runtime#awaitPromise](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-awaitPromise) operation call. * Add handler to promise with given promise object id. * * @link [Runtime#awaitPromise](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-awaitPromise) method documentation. * @see [RuntimeDomain.awaitPromise] */ @kotlinx.serialization.Serializable data class AwaitPromiseResponse( /** * Promise result. Will contain rejected value if promise was rejected. */ val result: RemoteObject, /** * Exception details if stack strace is available. */ val exceptionDetails: ExceptionDetails? = null ) /** * Represents request frame that can be used with [Runtime#callFunctionOn](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-callFunctionOn) operation call. * * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. * @link [Runtime#callFunctionOn](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-callFunctionOn) method documentation. * @see [RuntimeDomain.callFunctionOn] */ @kotlinx.serialization.Serializable data class CallFunctionOnRequest( /** * Declaration of the function to call. */ val functionDeclaration: String, /** * Identifier of the object to call function on. Either objectId or executionContextId should be specified. */ val objectId: RemoteObjectId? = null, /** * Call arguments. All call arguments must belong to the same JavaScript world as the target object. */ val arguments: List<CallArgument>? = null, /** * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides `setPauseOnException` state. */ val silent: Boolean? = null, /** * Whether the result is expected to be a JSON object which should be sent by value. */ val returnByValue: Boolean? = null, /** * Whether preview should be generated for the result. */ @pl.wendigo.chrome.protocol.Experimental val generatePreview: Boolean? = null, /** * Whether execution should be treated as initiated by user in the UI. */ val userGesture: Boolean? = null, /** * Whether execution should `await` for resulting value and return once awaited promise is resolved. */ val awaitPromise: Boolean? = null, /** * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. */ val executionContextId: ExecutionContextId? = null, /** * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. */ val objectGroup: String? = null ) /** * Represents response frame that is returned from [Runtime#callFunctionOn](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-callFunctionOn) operation call. * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. * * @link [Runtime#callFunctionOn](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-callFunctionOn) method documentation. * @see [RuntimeDomain.callFunctionOn] */ @kotlinx.serialization.Serializable data class CallFunctionOnResponse( /** * Call result. */ val result: RemoteObject, /** * Exception details. */ val exceptionDetails: ExceptionDetails? = null ) /** * Represents request frame that can be used with [Runtime#compileScript](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-compileScript) operation call. * * Compiles expression. * @link [Runtime#compileScript](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-compileScript) method documentation. * @see [RuntimeDomain.compileScript] */ @kotlinx.serialization.Serializable data class CompileScriptRequest( /** * Expression to compile. */ val expression: String, /** * Source url to be set for the script. */ val sourceURL: String, /** * Specifies whether the compiled script should be persisted. */ val persistScript: Boolean, /** * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. */ val executionContextId: ExecutionContextId? = null ) /** * Represents response frame that is returned from [Runtime#compileScript](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-compileScript) operation call. * Compiles expression. * * @link [Runtime#compileScript](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-compileScript) method documentation. * @see [RuntimeDomain.compileScript] */ @kotlinx.serialization.Serializable data class CompileScriptResponse( /** * Id of the script. */ val scriptId: ScriptId? = null, /** * Exception details. */ val exceptionDetails: ExceptionDetails? = null ) /** * Represents request frame that can be used with [Runtime#evaluate](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-evaluate) operation call. * * Evaluates expression on global object. * @link [Runtime#evaluate](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-evaluate) method documentation. * @see [RuntimeDomain.evaluate] */ @kotlinx.serialization.Serializable data class EvaluateRequest( /** * Expression to evaluate. */ val expression: String, /** * Symbolic group name that can be used to release multiple objects. */ val objectGroup: String? = null, /** * Determines whether Command Line API should be available during the evaluation. */ val includeCommandLineAPI: Boolean? = null, /** * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides `setPauseOnException` state. */ val silent: Boolean? = null, /** * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. This is mutually exclusive with `uniqueContextId`, which offers an alternative way to identify the execution context that is more reliable in a multi-process environment. */ val contextId: ExecutionContextId? = null, /** * Whether the result is expected to be a JSON object that should be sent by value. */ val returnByValue: Boolean? = null, /** * Whether preview should be generated for the result. */ @pl.wendigo.chrome.protocol.Experimental val generatePreview: Boolean? = null, /** * Whether execution should be treated as initiated by user in the UI. */ val userGesture: Boolean? = null, /** * Whether execution should `await` for resulting value and return once awaited promise is resolved. */ val awaitPromise: Boolean? = null, /** * Whether to throw an exception if side effect cannot be ruled out during evaluation. This implies `disableBreaks` below. */ @pl.wendigo.chrome.protocol.Experimental val throwOnSideEffect: Boolean? = null, /** * Terminate execution after timing out (number of milliseconds). */ @pl.wendigo.chrome.protocol.Experimental val timeout: TimeDelta? = null, /** * Disable breakpoints during execution. */ @pl.wendigo.chrome.protocol.Experimental val disableBreaks: Boolean? = null, /** * Setting this flag to true enables `let` re-declaration and top-level `await`. Note that `let` variables can only be re-declared if they originate from `replMode` themselves. */ @pl.wendigo.chrome.protocol.Experimental val replMode: Boolean? = null, /** * The Content Security Policy (CSP) for the target might block 'unsafe-eval' which includes eval(), Function(), setTimeout() and setInterval() when called with non-callable arguments. This flag bypasses CSP for this evaluation and allows unsafe-eval. Defaults to true. */ @pl.wendigo.chrome.protocol.Experimental val allowUnsafeEvalBlockedByCSP: Boolean? = null, /** * An alternative way to specify the execution context to evaluate in. Compared to contextId that may be reused accross processes, this is guaranteed to be system-unique, so it can be used to prevent accidental evaluation of the expression in context different than intended (e.g. as a result of navigation accross process boundaries). This is mutually exclusive with `contextId`. */ @pl.wendigo.chrome.protocol.Experimental val uniqueContextId: String? = null ) /** * Represents response frame that is returned from [Runtime#evaluate](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-evaluate) operation call. * Evaluates expression on global object. * * @link [Runtime#evaluate](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-evaluate) method documentation. * @see [RuntimeDomain.evaluate] */ @kotlinx.serialization.Serializable data class EvaluateResponse( /** * Evaluation result. */ val result: RemoteObject, /** * Exception details. */ val exceptionDetails: ExceptionDetails? = null ) /** * Represents response frame that is returned from [Runtime#getIsolateId](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getIsolateId) operation call. * Returns the isolate id. * * @link [Runtime#getIsolateId](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getIsolateId) method documentation. * @see [RuntimeDomain.getIsolateId] */ @kotlinx.serialization.Serializable data class GetIsolateIdResponse( /** * The isolate id. */ val id: String ) /** * Represents response frame that is returned from [Runtime#getHeapUsage](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getHeapUsage) operation call. * Returns the JavaScript heap usage. It is the total usage of the corresponding isolate not scoped to a particular Runtime. * * @link [Runtime#getHeapUsage](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getHeapUsage) method documentation. * @see [RuntimeDomain.getHeapUsage] */ @kotlinx.serialization.Serializable data class GetHeapUsageResponse( /** * Used heap size in bytes. */ val usedSize: Double, /** * Allocated heap size in bytes. */ val totalSize: Double ) /** * Represents request frame that can be used with [Runtime#getProperties](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getProperties) operation call. * * Returns properties of a given object. Object group of the result is inherited from the target object. * @link [Runtime#getProperties](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getProperties) method documentation. * @see [RuntimeDomain.getProperties] */ @kotlinx.serialization.Serializable data class GetPropertiesRequest( /** * Identifier of the object to return properties for. */ val objectId: RemoteObjectId, /** * If true, returns properties belonging only to the element itself, not to its prototype chain. */ val ownProperties: Boolean? = null, /** * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. */ @pl.wendigo.chrome.protocol.Experimental val accessorPropertiesOnly: Boolean? = null, /** * Whether preview should be generated for the results. */ @pl.wendigo.chrome.protocol.Experimental val generatePreview: Boolean? = null ) /** * Represents response frame that is returned from [Runtime#getProperties](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getProperties) operation call. * Returns properties of a given object. Object group of the result is inherited from the target object. * * @link [Runtime#getProperties](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getProperties) method documentation. * @see [RuntimeDomain.getProperties] */ @kotlinx.serialization.Serializable data class GetPropertiesResponse( /** * Object properties. */ val result: List<PropertyDescriptor>, /** * Internal object properties (only of the element itself). */ val internalProperties: List<InternalPropertyDescriptor>? = null, /** * Object private properties. */ val privateProperties: List<PrivatePropertyDescriptor>? = null, /** * Exception details. */ val exceptionDetails: ExceptionDetails? = null ) /** * Represents request frame that can be used with [Runtime#globalLexicalScopeNames](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-globalLexicalScopeNames) operation call. * * Returns all let, const and class variables from global scope. * @link [Runtime#globalLexicalScopeNames](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-globalLexicalScopeNames) method documentation. * @see [RuntimeDomain.globalLexicalScopeNames] */ @kotlinx.serialization.Serializable data class GlobalLexicalScopeNamesRequest( /** * Specifies in which execution context to lookup global scope variables. */ val executionContextId: ExecutionContextId? = null ) /** * Represents response frame that is returned from [Runtime#globalLexicalScopeNames](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-globalLexicalScopeNames) operation call. * Returns all let, const and class variables from global scope. * * @link [Runtime#globalLexicalScopeNames](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-globalLexicalScopeNames) method documentation. * @see [RuntimeDomain.globalLexicalScopeNames] */ @kotlinx.serialization.Serializable data class GlobalLexicalScopeNamesResponse( /** * */ val names: List<String> ) /** * Represents request frame that can be used with [Runtime#queryObjects](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-queryObjects) operation call. * * * @link [Runtime#queryObjects](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-queryObjects) method documentation. * @see [RuntimeDomain.queryObjects] */ @kotlinx.serialization.Serializable data class QueryObjectsRequest( /** * Identifier of the prototype to return objects for. */ val prototypeObjectId: RemoteObjectId, /** * Symbolic group name that can be used to release the results. */ val objectGroup: String? = null ) /** * Represents response frame that is returned from [Runtime#queryObjects](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-queryObjects) operation call. * * * @link [Runtime#queryObjects](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-queryObjects) method documentation. * @see [RuntimeDomain.queryObjects] */ @kotlinx.serialization.Serializable data class QueryObjectsResponse( /** * Array with objects. */ val objects: RemoteObject ) /** * Represents request frame that can be used with [Runtime#releaseObject](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-releaseObject) operation call. * * Releases remote object with given id. * @link [Runtime#releaseObject](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-releaseObject) method documentation. * @see [RuntimeDomain.releaseObject] */ @kotlinx.serialization.Serializable data class ReleaseObjectRequest( /** * Identifier of the object to release. */ val objectId: RemoteObjectId ) /** * Represents request frame that can be used with [Runtime#releaseObjectGroup](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-releaseObjectGroup) operation call. * * Releases all remote objects that belong to a given group. * @link [Runtime#releaseObjectGroup](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-releaseObjectGroup) method documentation. * @see [RuntimeDomain.releaseObjectGroup] */ @kotlinx.serialization.Serializable data class ReleaseObjectGroupRequest( /** * Symbolic object group name. */ val objectGroup: String ) /** * Represents request frame that can be used with [Runtime#runScript](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-runScript) operation call. * * Runs script with given id in a given context. * @link [Runtime#runScript](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-runScript) method documentation. * @see [RuntimeDomain.runScript] */ @kotlinx.serialization.Serializable data class RunScriptRequest( /** * Id of the script to run. */ val scriptId: ScriptId, /** * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. */ val executionContextId: ExecutionContextId? = null, /** * Symbolic group name that can be used to release multiple objects. */ val objectGroup: String? = null, /** * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides `setPauseOnException` state. */ val silent: Boolean? = null, /** * Determines whether Command Line API should be available during the evaluation. */ val includeCommandLineAPI: Boolean? = null, /** * Whether the result is expected to be a JSON object which should be sent by value. */ val returnByValue: Boolean? = null, /** * Whether preview should be generated for the result. */ val generatePreview: Boolean? = null, /** * Whether execution should `await` for resulting value and return once awaited promise is resolved. */ val awaitPromise: Boolean? = null ) /** * Represents response frame that is returned from [Runtime#runScript](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-runScript) operation call. * Runs script with given id in a given context. * * @link [Runtime#runScript](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-runScript) method documentation. * @see [RuntimeDomain.runScript] */ @kotlinx.serialization.Serializable data class RunScriptResponse( /** * Run result. */ val result: RemoteObject, /** * Exception details. */ val exceptionDetails: ExceptionDetails? = null ) /** * Represents request frame that can be used with [Runtime#setAsyncCallStackDepth](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-setAsyncCallStackDepth) operation call. * * Enables or disables async call stacks tracking. * @link [Runtime#setAsyncCallStackDepth](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-setAsyncCallStackDepth) method documentation. * @see [RuntimeDomain.setAsyncCallStackDepth] */ @kotlinx.serialization.Serializable data class SetAsyncCallStackDepthRequest( /** * Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async call stacks (default). */ val maxDepth: Int ) /** * Represents request frame that can be used with [Runtime#setCustomObjectFormatterEnabled](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-setCustomObjectFormatterEnabled) operation call. * * * @link [Runtime#setCustomObjectFormatterEnabled](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-setCustomObjectFormatterEnabled) method documentation. * @see [RuntimeDomain.setCustomObjectFormatterEnabled] */ @kotlinx.serialization.Serializable data class SetCustomObjectFormatterEnabledRequest( /** * */ val enabled: Boolean ) /** * Represents request frame that can be used with [Runtime#setMaxCallStackSizeToCapture](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-setMaxCallStackSizeToCapture) operation call. * * * @link [Runtime#setMaxCallStackSizeToCapture](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-setMaxCallStackSizeToCapture) method documentation. * @see [RuntimeDomain.setMaxCallStackSizeToCapture] */ @kotlinx.serialization.Serializable data class SetMaxCallStackSizeToCaptureRequest( /** * */ val size: Int ) /** * Represents request frame that can be used with [Runtime#addBinding](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-addBinding) operation call. * * If executionContextId is empty, adds binding with the given name on the global objects of all inspected contexts, including those created later, bindings survive reloads. Binding function takes exactly one argument, this argument should be string, in case of any other input, function throws an exception. Each binding function call produces Runtime.bindingCalled notification. * @link [Runtime#addBinding](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-addBinding) method documentation. * @see [RuntimeDomain.addBinding] */ @kotlinx.serialization.Serializable data class AddBindingRequest( /** * */ val name: String, /** * If specified, the binding would only be exposed to the specified execution context. If omitted and `executionContextName` is not set, the binding is exposed to all execution contexts of the target. This parameter is mutually exclusive with `executionContextName`. */ val executionContextId: ExecutionContextId? = null, /** * If specified, the binding is exposed to the executionContext with matching name, even for contexts created after the binding is added. See also `ExecutionContext.name` and `worldName` parameter to `Page.addScriptToEvaluateOnNewDocument`. This parameter is mutually exclusive with `executionContextId`. */ @pl.wendigo.chrome.protocol.Experimental val executionContextName: String? = null ) /** * Represents request frame that can be used with [Runtime#removeBinding](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-removeBinding) operation call. * * This method does not remove binding function from global object but unsubscribes current runtime agent from Runtime.bindingCalled notifications. * @link [Runtime#removeBinding](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-removeBinding) method documentation. * @see [RuntimeDomain.removeBinding] */ @kotlinx.serialization.Serializable data class RemoveBindingRequest( /** * */ val name: String ) /** * Notification is issued every time when binding is called. * * @link [Runtime#bindingCalled](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-bindingCalled) event documentation. */ @kotlinx.serialization.Serializable data class BindingCalledEvent( /** * */ val name: String, /** * */ val payload: String, /** * Identifier of the context where the call was made. */ val executionContextId: ExecutionContextId ) : pl.wendigo.chrome.protocol.Event { override fun domain() = "Runtime" override fun eventName() = "bindingCalled" } /** * Issued when console API was called. * * @link [Runtime#consoleAPICalled](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-consoleAPICalled) event documentation. */ @kotlinx.serialization.Serializable data class ConsoleAPICalledEvent( /** * Type of the call. */ val type: String, /** * Call arguments. */ val args: List<RemoteObject>, /** * Identifier of the context where the call was made. */ val executionContextId: ExecutionContextId, /** * Call timestamp. */ val timestamp: Timestamp, /** * Stack trace captured when the call was made. The async stack chain is automatically reported for the following call types: `assert`, `error`, `trace`, `warning`. For other types the async call chain can be retrieved using `Debugger.getStackTrace` and `stackTrace.parentId` field. */ val stackTrace: StackTrace? = null, /** * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. */ val context: String? = null ) : pl.wendigo.chrome.protocol.Event { override fun domain() = "Runtime" override fun eventName() = "consoleAPICalled" } /** * Issued when unhandled exception was revoked. * * @link [Runtime#exceptionRevoked](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-exceptionRevoked) event documentation. */ @kotlinx.serialization.Serializable data class ExceptionRevokedEvent( /** * Reason describing why exception was revoked. */ val reason: String, /** * The id of revoked exception, as reported in `exceptionThrown`. */ val exceptionId: Int ) : pl.wendigo.chrome.protocol.Event { override fun domain() = "Runtime" override fun eventName() = "exceptionRevoked" } /** * Issued when exception was thrown and unhandled. * * @link [Runtime#exceptionThrown](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-exceptionThrown) event documentation. */ @kotlinx.serialization.Serializable data class ExceptionThrownEvent( /** * Timestamp of the exception. */ val timestamp: Timestamp, /** * */ val exceptionDetails: ExceptionDetails ) : pl.wendigo.chrome.protocol.Event { override fun domain() = "Runtime" override fun eventName() = "exceptionThrown" } /** * Issued when new execution context is created. * * @link [Runtime#executionContextCreated](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-executionContextCreated) event documentation. */ @kotlinx.serialization.Serializable data class ExecutionContextCreatedEvent( /** * A newly created execution context. */ val context: ExecutionContextDescription ) : pl.wendigo.chrome.protocol.Event { override fun domain() = "Runtime" override fun eventName() = "executionContextCreated" } /** * Issued when execution context is destroyed. * * @link [Runtime#executionContextDestroyed](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-executionContextDestroyed) event documentation. */ @kotlinx.serialization.Serializable data class ExecutionContextDestroyedEvent( /** * Id of the destroyed context */ val executionContextId: ExecutionContextId ) : pl.wendigo.chrome.protocol.Event { override fun domain() = "Runtime" override fun eventName() = "executionContextDestroyed" } /** * Issued when object should be inspected (for example, as a result of inspect() command line API call). * * @link [Runtime#inspectRequested](https://chromedevtools.github.io/devtools-protocol/tot/Runtime#event-inspectRequested) event documentation. */ @kotlinx.serialization.Serializable data class InspectRequestedEvent( /** * */ @kotlinx.serialization.SerialName("object") val _object: RemoteObject, /** * */ val hints: kotlinx.serialization.json.JsonElement ) : pl.wendigo.chrome.protocol.Event { override fun domain() = "Runtime" override fun eventName() = "inspectRequested" }
apache-2.0
cbcbec771ce29c1fefe7871d14305c20
38.421145
401
0.741457
4.701871
false
false
false
false
exponent/exponent
packages/expo-print/android/src/main/java/expo/modules/print/PrintModule.kt
2
5469
package expo.modules.print import android.content.Context import android.os.Bundle import android.print.PrintAttributes import android.print.PrintDocumentAdapter import android.print.PrintManager import expo.modules.core.ExportedModule import expo.modules.core.ModuleRegistry import expo.modules.core.Promise import expo.modules.core.interfaces.ActivityProvider import expo.modules.core.interfaces.ExpoMethod import java.io.File import java.io.IOException class PrintModule(context: Context) : ExportedModule(context) { private val ORIENTATION_PORTRAIT = "portrait" private val ORIENTATION_LANDSCAPE = "landscape" private val jobName = "Printing" private lateinit var moduleRegistry: ModuleRegistry override fun onCreate(moduleRegistry: ModuleRegistry) { this.moduleRegistry = moduleRegistry } override fun getName(): String { return "ExponentPrint" } override fun getConstants(): MutableMap<String, Any?> { return hashMapOf( "Orientation" to hashMapOf( "portrait" to ORIENTATION_PORTRAIT, "landscape" to ORIENTATION_LANDSCAPE ) ) } @ExpoMethod fun print(options: Map<String?, Any?>, promise: Promise) { val html = if (options.containsKey("html")) { options["html"] as String? } else { null } val uri = if (options.containsKey("uri")) { options["uri"] as String? } else { null } if (html != null) { // Renders HTML to PDF and then prints try { val renderTask = PrintPDFRenderTask(context, options, moduleRegistry) renderTask.render( null, object : PrintPDFRenderTask.Callbacks() { override fun onRenderFinished(document: PrintDocumentAdapter, outputFile: File?, numberOfPages: Int) { printDocumentToPrinter(document, options) promise.resolve(null) } override fun onRenderError(errorCode: String?, errorMessage: String?, exception: Exception?) { promise.reject(errorCode, errorMessage, exception) } } ) } catch (e: Exception) { promise.reject("E_CANNOT_PRINT", "There was an error while trying to print HTML.", e) } } else { // Prints from given URI (file path or base64 data URI starting with `data:*;base64,`) try { val pda = PrintDocumentAdapter(context, promise, uri) printDocumentToPrinter(pda, options) promise.resolve(null) } catch (e: Exception) { promise.reject("E_CANNOT_PRINT", "There was an error while trying to print a file.", e) } } } @ExpoMethod fun printToFileAsync(options: Map<String?, Any?>, promise: Promise) { val filePath: String try { filePath = FileUtils.generateFilePath(context) } catch (e: IOException) { promise.reject("E_PRINT_FAILED", "An unknown I/O exception occurred.", e) return } val renderTask = PrintPDFRenderTask(context, options, moduleRegistry) renderTask.render( filePath, object : PrintPDFRenderTask.Callbacks() { override fun onRenderFinished(document: PrintDocumentAdapter, outputFile: File?, numberOfPages: Int) { val uri = FileUtils.uriFromFile(outputFile).toString() var base64: String? = null if (options.containsKey("base64") && (options["base64"] as Boolean? == true)) { try { base64 = outputFile?.let { FileUtils.encodeFromFile(it) } } catch (e: IOException) { promise.reject("E_PRINT_BASE64_FAILED", "An error occurred while encoding PDF file to base64 string.", e) return } } promise.resolve( Bundle().apply { putString("uri", uri) putInt("numberOfPages", numberOfPages) if (base64 != null) putString("base64", base64) } ) } override fun onRenderError(errorCode: String?, errorMessage: String?, exception: Exception?) { promise.reject(errorCode, errorMessage, exception) } } ) } private fun printDocumentToPrinter(document: PrintDocumentAdapter, options: Map<String?, Any?>) { val printManager = moduleRegistry .getModule(ActivityProvider::class.java) .currentActivity ?.getSystemService(Context.PRINT_SERVICE) as? PrintManager val attributes = getAttributesFromOptions(options) printManager?.print(jobName, document, attributes.build()) } private fun getAttributesFromOptions(options: Map<String?, Any?>): PrintAttributes.Builder { val orientation = if (options.containsKey("orientation")) { options["orientation"] as String? } else { null } val builder = PrintAttributes.Builder() // @tsapeta: Unfortunately these attributes might be ignored on some devices or Android versions, // in other words it might not change the default orientation in the print dialog, // however the user can change it there. if (ORIENTATION_LANDSCAPE == orientation) { builder.setMediaSize(PrintAttributes.MediaSize.UNKNOWN_LANDSCAPE) } else { builder.setMediaSize(PrintAttributes.MediaSize.UNKNOWN_PORTRAIT) } // @tsapeta: It should just copy the document without adding extra margins, // document's margins can be controlled by @page block in CSS. builder.setMinMargins(PrintAttributes.Margins.NO_MARGINS) return builder } }
bsd-3-clause
5956b86138a49caa09d00e7d02af82c2
34.512987
119
0.662278
4.638677
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/ide/template/postfix/WhileNotPostfixTemplateTest.kt
4
2909
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.template.postfix class WhileNotPostfixTemplateTest : RsPostfixTemplateTest(WhileNotExpressionPostfixTemplate()) { fun `test not boolean expr 1`() = doTestNotApplicable(""" fn main() { let a = 4; a.whilenot/*caret*/ } """) fun `test not boolean expr 2`() = doTestNotApplicable(""" fn func() -> i32 { 1234 } fn main() { func().whilenot/*caret*/ } """) fun `test boolean expr`() = doTest(""" fn main() { let a = 4 == 2; a.whilenot/*caret*/ } """, """ fn main() { let a = 4 == 2; while !a {/*caret*/} } """) fun `test negated boolean expr`() = doTest(""" fn main() { let a = 4 == 2; !a.whilenot/*caret*/ } """, """ fn main() { let a = 4 == 2; while a {/*caret*/} } """) fun `test fun arg`() = doTest(""" fn foo(a: bool) { a.whilenot/*caret*/ } """, """ fn foo(a: bool) { while !a {/*caret*/} } """) fun `test simple eq expr`() = doTest(""" fn main() { true == true.whilenot/*caret*/ } """, """ fn main() { while true != true {/*caret*/} } """) fun `test selector`() = doTest(""" fn main() { let a = if (true) { 42 < 43.whilenot/*caret*/ } else { false == true }; } """, """ fn main() { let a = if (true) { while 42 >= 43 {/*caret*/} } else { false == true }; } """) fun `test call`() = doTest(""" fn func() -> bool { false } fn main() { func().whilenot/*caret*/ } """, """ fn func() -> bool { false } fn main() { while !func() {/*caret*/} } """) fun `test bin operators bool`() { val cases = listOf( Pair("1 == 2", "1 != 2"), Pair("1 != 2", "1 == 2"), Pair("1 <= 2", "1 > 2"), Pair("1 >= 2", "1 < 2"), Pair("1 < 2", "1 >= 2"), Pair("1 > 2", "1 <= 2"), Pair("!(1 == 2)", "1 == 2"), Pair("(1 == 2)", "!(1 == 2)") ) for (case in cases) { doTest(""" fn main() { ${case.first}.whilenot/*caret*/ } """, """ fn main() { while ${case.second} {/*caret*/} } """) } } }
mit
2dc1587ac8f48d1f574e7c5be5dea33b
21.376923
96
0.344792
4.367868
false
true
false
false
tasomaniac/OpenLinkWith
app/src/main/java/com/tasomaniac/openwith/settings/Settings.kt
1
830
package com.tasomaniac.openwith.settings import androidx.annotation.StringRes import androidx.annotation.XmlRes import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat abstract class Settings( val fragment: PreferenceFragmentCompat ) : SettingsView { val context get() = fragment.requireContext() val activity get() = fragment.requireActivity() fun addPreferencesFromResource(@XmlRes resId: Int) = fragment.addPreferencesFromResource(resId) fun removePreference(preference: Preference) = fragment.preferenceScreen.removePreference(preference) fun findPreference(@StringRes keyResource: Int): Preference = fragment.run { findPreference(getString(keyResource))!! } fun String.isKeyEquals(@StringRes keyRes: Int) = fragment.getString(keyRes) == this }
apache-2.0
5bfcd95e6a429e1cd3369331ee9afc7b
33.583333
105
0.785542
5.220126
false
false
false
false
VKCOM/vk-android-sdk
core/src/main/java/com/vk/api/sdk/auth/VKAuthManager.kt
1
5641
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ package com.vk.api.sdk.auth import android.app.Activity import android.content.Context import android.content.Intent import android.util.Log import com.vk.api.sdk.R import com.vk.api.sdk.VK import com.vk.api.sdk.VKKeyValueStorage import com.vk.api.sdk.exceptions.VKApiCodes import com.vk.api.sdk.exceptions.VKAuthException import com.vk.api.sdk.extensions.showToast import com.vk.api.sdk.utils.VKUtils internal class VKAuthManager(private val keyValueStorage: VKKeyValueStorage) { fun createVKClientAuthIntent(params: VKAuthParams) = Intent(VK_APP_AUTH_ACTION, null).apply { setPackage(VK_APP_PACKAGE_ID) putExtras(params.toExtraBundle()) } fun onActivityResult( context: Context, requestCode: Int, resultCode: Int, data: Intent?, callback: VKAuthCallback, showErrorToast: Boolean ): Boolean { if (requestCode != VK_APP_AUTH_CODE) { return false } if (data == null) { callback.onLoginFailed(VKAuthException()) return true } val result: VKAuthenticationResult = processResult(data) if (resultCode != Activity.RESULT_OK || result is VKAuthenticationResult.Failed) { val loginError = (result as? VKAuthenticationResult.Failed)?.exception ?: obtainExceptionFromIntent(data) callback.onLoginFailed(loginError) if (showErrorToast && !loginError.isCanceled) { context.showToast(R.string.vk_message_login_error) } } else { (result as? VKAuthenticationResult.Success)?.let { storeLoginResult(it) callback.onLogin(it.token) } } return true } fun processResult(result: Intent?): VKAuthenticationResult { result ?: return VKAuthenticationResult.Failed(VKAuthException(authError = "No result from caller provided")) val tokenParams: MutableMap<String, String>? when { result.hasExtra(VK_EXTRA_TOKEN_DATA) -> { // Token received via webview val tokenInfo = result.getStringExtra(VK_EXTRA_TOKEN_DATA) tokenParams = VKUtils.explodeQueryString(tokenInfo) } result.extras != null -> { // Token received via VK app tokenParams = HashMap() for (key in result.extras!!.keySet()) { tokenParams[key] = result.extras!!.get(key).toString() } } else -> tokenParams = null } return if (tokenParams != null && tokenParams[VK_AUTH_ERROR] == null) { try { VKAuthenticationResult.Success(VKAccessToken(tokenParams)) } catch (e: Exception) { Log.e(VKAuthManager::class.java.simpleName, "Failed to get VK token", e) VKAuthenticationResult.Failed(VKAuthException(authError = "Auth failed due to exception: ${e.message}")) } } else { VKAuthenticationResult.Failed(obtainExceptionFromIntent(result)) } } fun storeLoginResult(result: VKAuthenticationResult.Success) { result.token.save(keyValueStorage) VK.apiManager.setCredentials(result.token.accessToken, result.token.secret, result.token.expiresInSec, result.token.createdMs) } fun isLoggedIn(): Boolean { val token = getCurrentToken() return token != null && token.isValid } fun getCurrentToken(): VKAccessToken? { return VKAccessToken.restore(keyValueStorage) } fun clearAccessToken() { VKAccessToken.remove(keyValueStorage) } private fun obtainExceptionFromIntent(intent: Intent): VKAuthException { val webViewError = intent.extras?.getInt(VKApiCodes.EXTRA_VW_LOGIN_ERROR) ?: 0 val authError = intent.extras?.getString(VKApiCodes.EXTRA_AUTH_ERROR) return VKAuthException(webViewError, authError) } companion object { const val VK_APP_PACKAGE_ID = "com.vkontakte.android" const val VK_APP_AUTH_ACTION = "com.vkontakte.android.action.SDK_AUTH" const val VK_EXTRA_TOKEN_DATA = "extra-token-data" const val VK_AUTH_ERROR = "error" private const val VK_APP_AUTH_CODE = 282 } }
mit
227ff62c4ef907e5532a01905d7ecf9e
38.454545
134
0.639248
4.689111
false
false
false
false
yusaka39/reversi
game/src/main/kotlin/io/github/yusaka39/reversi/game/Board.kt
1
4081
package io.github.yusaka39.reversi.game import io.github.yusaka39.reversi.game.constants.Sides class Board : Cloneable { companion object { private val INITIAL_BOARD = listOf( listOf(null, null, null, null, null, null, null, null), listOf(null, null, null, null, null, null, null, null), listOf(null, null, null, null, null, null, null, null), listOf(null, null, null, Sides.BLACK, Sides.WHITE, null, null, null), listOf(null, null, null, Sides.WHITE, Sides.BLACK, null, null, null), listOf(null, null, null, null, null, null, null, null), listOf(null, null, null, null, null, null, null, null), listOf(null, null, null, null, null, null, null, null) ) private val SEARCH_STRATEGIES: List<(Grid) -> Grid> = listOf( { it -> Grid(it.x + 1, it.y + 1) }, { it -> Grid(it.x + 1, it.y) }, { it -> Grid(it.x + 1, it.y - 1) }, { it -> Grid(it.x, it.y + 1) }, { it -> Grid(it.x, it.y - 1) }, { it -> Grid(it.x - 1, it.y - 1) }, { it -> Grid(it.x - 1, it.y) }, { it -> Grid(it.x - 1, it.y + 1) } ) } var boardAsList: List<List<Sides?>> = INITIAL_BOARD private set fun getSideOfGrid(grid: Grid) = if(grid.isValid()) this.boardAsList[grid.y][grid.x] else null private fun hasReverseTargetForStrategy(f: (Grid) -> Grid, grid: Grid, side: Sides): Boolean { val opposite = side.reverse() var pointed = f(grid) if (this.getSideOfGrid(pointed) != opposite) { return false } while (this.getSideOfGrid(pointed) == opposite) { pointed = f(pointed) } return this.getSideOfGrid(pointed) == side } fun canPut(side: Sides): Boolean { for (y in 0 until 8) { for (x in 0 until 8) { val g = Grid(x, y) val sideOfGrid = this.getSideOfGrid(g) if (sideOfGrid != null) { continue } SEARCH_STRATEGIES.forEach { if (hasReverseTargetForStrategy(it, g, side)) { return true } } } } return false } fun put(side: Sides, grid: Grid) { tailrec fun getReversingGridForStrategy(getNext: (Grid) -> Grid, g: Grid, acc: List<Grid>) : List<Grid> { if (!g.isValid()) { return emptyList() } val sideOfGrid = this.boardAsList[g.y][g.x] return when(sideOfGrid) { side -> acc null -> emptyList() else -> getReversingGridForStrategy(getNext, getNext(g), acc + listOf(g)) } } val reverseTargetGrids = SEARCH_STRATEGIES.map { getReversingGridForStrategy(it, it(grid), emptyList()) }.flatten() + listOf(grid) this.boardAsList = this.boardAsList.mapIndexed { y, list -> list.mapIndexed { x, sideOfGrid -> if (reverseTargetGrids.contains(Grid(x, y))) { side } else { sideOfGrid } } } } fun getCountForSide(side: Sides) = this.boardAsList.map { it.count { it == side } }.sum() fun getValidMoves(side: Sides): List<Grid> { val grids = (0 until 8).map { y -> (0 until 8).map { x -> Grid(x, y) } }.flatten() return grids.filter { g -> this.getSideOfGrid(g) == null && SEARCH_STRATEGIES.any { this.hasReverseTargetForStrategy(it, g, side) } } } override public fun clone(): Board { return Board().apply { this.boardAsList = [email protected] } } } data class Grid(val x: Int, val y: Int) { fun isValid() = 0 <= this.x && this.x <= 7 && 0 <= this.y && this.y <= 7 }
mit
e8242635328871e6548cef189d94f951
34.495652
98
0.495957
3.954457
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/psi/impl/xpath/XPathSimpleForBindingPsiImpl.kt
1
2853
/* * Copyright (C) 2019-2021 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.xpath.psi.impl.xpath import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.SearchScope import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.core.sequences.filterIsElementType import uk.co.reecedunn.intellij.plugin.xdm.types.XdmSequenceType import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathEQName import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathSimpleForBinding import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmExpression import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.flwor.XpmBindingCollectionType import xqt.platform.intellij.xpath.XPathTokenProvider class XPathSimpleForBindingPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XPathSimpleForBinding, XpmSyntaxValidationElement { // region PsiElement override fun getUseScope(): SearchScope = LocalSearchScope(parent.parent) // endregion // region XpmVariableBinding override val variableName: XsQNameValue? get() = children().filterIsInstance<XPathEQName>().firstOrNull() // endregion // region XpmCollectionBinding override val variableType: XdmSequenceType? get() = children().filterIsInstance<XdmSequenceType>().firstOrNull() override val bindingExpression: XpmExpression? get() = children().filterIsInstance<XpmExpression>().firstOrNull() // endregion // region XpmForBinding override val bindingCollectionType: XpmBindingCollectionType get() = when (parent.children().filterIsElementType(XPathTokenProvider.KMember).firstOrNull()) { null -> XpmBindingCollectionType.SequenceItem else -> XpmBindingCollectionType.ArrayMember } // endregion // region XpmSyntaxValidationElement override val conformanceElement: PsiElement get() = findChildByType(XPathTokenProvider.KMember) ?: this // endregion }
apache-2.0
7c6e5cb5b7068b4d0798099585211840
38.082192
104
0.771819
4.692434
false
false
false
false
HabitRPG/habitica-android
wearos/src/main/java/com/habitrpg/wearos/habitica/ui/viewHolders/tasks/HabitViewHolder.kt
1
2272
package com.habitrpg.wearos.habitica.ui.viewHolders.tasks import android.content.res.ColorStateList import android.view.View import androidx.core.content.ContextCompat import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.RowHabitBinding import com.habitrpg.wearos.habitica.models.tasks.Task import com.habitrpg.wearos.habitica.ui.views.TaskTextView class HabitViewHolder(itemView: View) : TaskViewHolder(itemView) { private val binding = RowHabitBinding.bind(itemView) override val titleView: TaskTextView get() = binding.title init { binding.habitButton.setOnClickListener { onTaskScore?.invoke() } } override fun bind(data: Task) { super.bind(data) if (data.up == true && data.down == true) { binding.habitButtonIcon.setBackgroundResource(R.drawable.habit_diagonal) binding.habitButtonIcon.setImageResource(R.drawable.watch_habit_posneg) } else { binding.habitButtonIcon.setBackgroundResource(R.drawable.habit_button_round) if (data.down == true) { binding.habitButtonIcon.setImageResource(R.drawable.watch_habit_negative) } else { binding.habitButtonIcon.setImageResource(R.drawable.watch_habit_positive) } } if (data.up != true && data.down != true) { binding.habitButton.backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(itemView.context, R.color.watch_gray_100)) binding.habitButtonIcon.backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(itemView.context, R.color.watch_gray_5)) binding.habitButtonIcon.imageTintList = ColorStateList.valueOf(ContextCompat.getColor(itemView.context, R.color.watch_gray_100)) } else { binding.habitButton.backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(itemView.context, data.lightTaskColor)) binding.habitButtonIcon.backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(itemView.context, data.mediumTaskColor)) binding.habitButtonIcon.imageTintList = ColorStateList.valueOf(ContextCompat.getColor(itemView.context, R.color.white)) } } }
gpl-3.0
f66f276fc1a2214f0678ed4f9e3f7062
48.413043
143
0.71963
4.684536
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/codegen/coroutines/controlFlow_finally6.kt
1
1148
import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* open class EmptyContinuation(override val context: CoroutineContext = EmptyCoroutineContext) : Continuation<Any?> { companion object : EmptyContinuation() override fun resume(value: Any?) {} override fun resumeWithException(exception: Throwable) { throw exception } } suspend fun s1(): Int = suspendCoroutineOrReturn { x -> println("s1") x.resumeWithException(Error("error")) COROUTINE_SUSPENDED } fun f1(): Int { println("f1") return 117 } fun f2(): Int { println("f2") return 1 } fun f3(x: Int, y: Int): Int { println("f3") return x + y } fun builder(c: suspend () -> Unit) { c.startCoroutine(EmptyContinuation) } fun main(args: Array<String>) { var result = 0 builder { try { try { result = s1() } catch (t: ClassCastException) { result = f2() } finally { println("finally") } } catch(t: Error) { println(t.message) } } println(result) }
apache-2.0
36dd166a42ad2e0a96931d3ba5870aab
20.277778
115
0.585366
4.144404
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/presentation/course_list/mapper/CourseListUserStateMapper.kt
1
18206
package org.stepik.android.presentation.course_list.mapper import org.stepic.droid.util.DateTimeHelper import ru.nobird.android.core.model.PagedList import ru.nobird.android.core.model.mutate import ru.nobird.android.core.model.insert import ru.nobird.android.core.model.slice import ru.nobird.android.core.model.filterNot import ru.nobird.android.core.model.plus import ru.nobird.android.core.model.transform import org.stepik.android.domain.course_list.model.CourseListItem import org.stepik.android.domain.course_list.model.UserCourseQuery import org.stepik.android.domain.course_list.model.UserCoursesLoaded import org.stepik.android.domain.user_courses.model.UserCourse import org.stepik.android.presentation.course_list.CourseListUserView import org.stepik.android.presentation.course_list.CourseListView import java.util.Date import javax.inject.Inject import kotlin.collections.filterNot class CourseListUserStateMapper @Inject constructor( private val courseListStateMapper: CourseListStateMapper ) { companion object { private const val PAGE_SIZE = 20 } /** * Fetch courses */ fun mapToFetchCoursesSuccess(state: CourseListUserView.State, items: PagedList<CourseListItem.Data>, isNewItems: Boolean): CourseListUserView.State { val courseListViewState = (state as? CourseListUserView.State.Data) ?.courseListViewState ?: return state val newCourseListViewState = // todo перенести в CourseListStateMapper и абстрагироваться от user courses when (courseListViewState) { /** * Empty может быть еще когда пользователь отписался от курса или переместил в архив */ CourseListView.State.Loading, CourseListView.State.Empty, CourseListView.State.NetworkError -> if (items.isNotEmpty() && state.userCourses.isNotEmpty()) { val pagedItems = PagedList(items, page = items.page, hasNext = items.size < state.userCourses.size) CourseListView.State.Content(pagedItems, pagedItems) } else { CourseListView.State.Empty } is CourseListView.State.Content -> { val itemsMap = items.associateBy { it.course.id } /** * в случае next page надо учесть * перемещенные элементы * load more placeholder * * как отличить next page от подгрузки элементов c remote? - нужен параметр для отличия этих кейсов - [isNewItems] */ if (isNewItems) { // [startIndex] - индекс последнего (для которого есть CourseListItem.Data) элемента в user courses val startIndex = courseListViewState .courseListItems // проверяем, что последний элемент placeholder пагинации .takeIf { (it.lastOrNull() as? CourseListItem.PlaceHolder)?.courseId == -1L } ?.findLast { it is CourseListItem.Data || it is CourseListItem.PlaceHolder && it.courseId != -1L } ?.let { when (it) { is CourseListItem.Data -> it.course.id is CourseListItem.PlaceHolder -> it.courseId is CourseListItem.ViewAll -> null is CourseListItem.SimilarCourses -> null is CourseListItem.SimilarAuthors -> null } } ?.let { lastCourseId -> state.userCourses.indexOfFirst { it.course == lastCourseId } } ?.takeIf { it >= 0 } if (startIndex != null) { // новый хвост из Data элементов в порядке id в user courses val newDataItems: List<CourseListItem.Data> = state .userCourses .slice(from = startIndex + 1) .mapNotNull { itemsMap[it.course] } courseListViewState .copy( courseListDataItems = courseListViewState.courseListDataItems + PagedList(newDataItems, hasNext = startIndex + 1 < state.userCourses.size), courseListItems = courseListViewState.courseListItems.slice(to = courseListViewState.courseListItems.size - 1) + newDataItems ) } else { courseListViewState } } else { // тут мы просто обновляем элементы новыми с REMOTE порядок должен быть и так верным courseListStateMapper.mergeWithUpdatedItems(courseListViewState, itemsMap) } } else -> courseListViewState } return state.copy(courseListViewState = newCourseListViewState) } fun mapToFetchCoursesError(state: CourseListUserView.State): CourseListUserView.State { val courseListViewState = (state as? CourseListUserView.State.Data) ?.courseListViewState ?: return state val newCourseListViewState = when (courseListViewState) { CourseListView.State.Loading, CourseListView.State.Empty, CourseListView.State.NetworkError -> CourseListView.State.NetworkError is CourseListView.State.Content -> courseListViewState .copy( courseListItems = courseListViewState.courseListItems.dropLastWhile { it is CourseListItem.PlaceHolder && it.courseId == -1L } ) else -> courseListViewState } return state.copy(courseListViewState = newCourseListViewState) } fun getNextPageCourseIds(userCourses: List<UserCourse>, courseListViewState: CourseListView.State.Content): List<Long>? { if (!courseListViewState.courseListDataItems.hasNext || (courseListViewState.courseListItems.last() as? CourseListItem.PlaceHolder)?.courseId == -1L) { return null } val offset = courseListViewState.courseListItems.size return userCourses .slice(offset, offset + PAGE_SIZE) .map(UserCourse::course) } /** * Continue course */ fun mergeWithCourseContinue(state: CourseListUserView.State, courseId: Long): Pair<CourseListUserView.State, Boolean> { val userCourses = (state as? CourseListUserView.State.Data) ?.userCourses ?: return state to false val index = userCourses.indexOfFirst { it.course == courseId } var isNeedLoadCourse = false return if (index > 0) { // if index == 0 we do not need to update state val newUserCourses = userCourses.mutate { add(0, removeAt(index).copy(lastViewed = Date(DateTimeHelper.nowUtc()))) } val newCourseListViewState = with(state.courseListViewState) { if (this is CourseListView.State.Content) { val courseListDataIndex = courseListDataItems.indexOfFirst { it.course.id == courseId } val newCourseListDataItems = if (courseListDataIndex > 0) { PagedList(courseListDataItems.mutate { add(0, removeAt(courseListDataIndex)) }, hasNext = courseListDataItems.hasNext) } else { courseListDataItems } val newCourseListItems = if (index in courseListItems.indices) { courseListItems.mutate { add(0, removeAt(index)) } } else { isNeedLoadCourse = true listOf(CourseListItem.PlaceHolder(courseId)) + courseListItems } copy(newCourseListDataItems, newCourseListItems) } else { this } } state.copy(userCourses = newUserCourses, courseListViewState = newCourseListViewState) to isNeedLoadCourse } else { state to isNeedLoadCourse } } /** * Enrollments */ fun mergeWithEnrolledCourse(state: CourseListUserView.State, courseId: Long): Pair<CourseListUserView.State, Boolean> = if (state is CourseListUserView.State.Data && with(state.userCourseQuery) { isFavorite != true && isArchived != true } // in this case course do not match userCourseQuery ) { addUserCourseToTop(state, UserCourse(user = 0, course = courseId, lastViewed = Date(DateTimeHelper.nowUtc()))) } else { state to false } fun mergeWithRemovedCourse(state: CourseListUserView.State, courseId: Long): CourseListUserView.State = if (state is CourseListUserView.State.Data) { val userCourses = state.userCourses.filterNot { it.course == courseId } val courseListViewState = when (state.courseListViewState) { is CourseListView.State.Content -> if (userCourses.isEmpty()) { CourseListView.State.Empty } else { state.courseListViewState.copy( state.courseListViewState.courseListDataItems .filterNot { it.course.id == courseId }, state.courseListViewState.courseListItems .filterNot { it is CourseListItem.Data && it.course.id == courseId || it is CourseListItem.PlaceHolder && it.courseId == courseId } ) } else -> state.courseListViewState } state.copy(userCourses = userCourses, courseListViewState = courseListViewState) } else { state } /** * Course placeholders */ fun mergeWithPlaceholderSuccess(state: CourseListUserView.State, courseListItem: CourseListItem.Data): CourseListUserView.State = if (state is CourseListUserView.State.Data && state.courseListViewState is CourseListView.State.Content) { val listState = state.courseListViewState /** * Нам нужно вставить в courseListDataItems, но так как courseListDataItems не содержит плейсхолдеров * то нам нужно понять куда вставить в courseListDataItems. * Для этого мы находим предшесвующий вставляемуму элемент и вставляем после него. */ var previousCourseId = -1L val courseListItems = listState .courseListItems .map { item -> if (item is CourseListItem.PlaceHolder && item.courseId == courseListItem.course.id) { courseListItem } else { if (item is CourseListItem.Data) { previousCourseId = item.course.id } item } } val indexOfPreviousCourseItem = if (previousCourseId == -1L) { -1 } else { listState.courseListDataItems.indexOfFirst { it.course.id == previousCourseId } } val courseListDataItems = if (indexOfPreviousCourseItem == -1) { listState.courseListDataItems } else { listState.courseListDataItems.transform { insert(courseListItem, pos = indexOfPreviousCourseItem + 1) } } state.copy(courseListViewState = listState.copy(courseListDataItems, courseListItems)) } else { state } fun mergeWithUserCourse(state: CourseListUserView.State, userCourse: UserCourse): Pair<CourseListUserView.State, Boolean> = if (state is CourseListUserView.State.Data) { if (userCourse.isMatchQuery(state.userCourseQuery)) { /* - понять куда его вставить - обновить user courses Варианты: 1) Помещать элементы в начало списка - нужно при паблишинге сортировать по дате - при обновлении списка элемент уедет вниз 2) При вхождении в видимую область помещать элемент на свое место, иначе в конец списка - проблемы аналогично верхним (но так как обычно не больше 2х страниц, то скорее всего у большинства всё будет ок) - если мы помещаем элемент в конец списка, то нарушается порядок и потом непонятно куда класть следующий 3) Помещать элемент на свое место и подгружать при попадании в область видимости - элемент на своем месте - нарушается предикат, что user courses 1 к 1 соотвествуют courseListItems, так как теперь могут быть разрывы победил вариант 1, так как все варианты с trade off, но первый проще всего сделать */ if (state.userCourses.any { it.course == userCourse.course }) { // если такой уже есть, то ничего не трогаем state.copy(courseListViewState = courseListStateMapper.mapToUserCourseUpdate(state.courseListViewState, userCourse)) to false } else { addUserCourseToTop(state, userCourse) } } else { mergeWithRemovedCourse(state, userCourse.course) to false } } else { state to false } private fun addUserCourseToTop(state: CourseListUserView.State.Data, userCourse: UserCourse): Pair<CourseListUserView.State, Boolean> { val userCourseWrapper = listOf(userCourse) val coursePlaceholder = listOf(CourseListItem.PlaceHolder(userCourse.course)) val isNeedLoadCourse = state.courseListViewState == CourseListView.State.Empty || state.courseListViewState is CourseListView.State.Content val (userCourses, courseListViewState) = when (state.courseListViewState) { CourseListView.State.Empty -> userCourseWrapper to CourseListView.State.Content(PagedList(emptyList()), coursePlaceholder) is CourseListView.State.Content -> Pair( userCourseWrapper + state.userCourses, state.courseListViewState.copy(courseListItems = coursePlaceholder + state.courseListViewState.courseListItems) ) else -> state.userCourses to state.courseListViewState } return state.copy(userCourses = userCourses, courseListViewState = courseListViewState) to isNeedLoadCourse } fun getLatestCourseToPublish(state: CourseListUserView.State.Data): UserCoursesLoaded = if (state.courseListViewState is CourseListView.State.Content) { val userCoursesMap = state.userCourses.associateBy(UserCourse::course) state.courseListViewState.courseListDataItems .maxBy { userCoursesMap[it.course.id]?.time ?: 0L } ?.let(UserCoursesLoaded::FirstCourse) ?: UserCoursesLoaded.Empty } else { UserCoursesLoaded.Empty } private val UserCourse.time: Long get() = lastViewed?.time ?: 0 private fun UserCourse.isMatchQuery(userCourseQuery: UserCourseQuery): Boolean = (userCourseQuery.isFavorite == null || userCourseQuery.isFavorite == this.isFavorite) && (userCourseQuery.isArchived == null || userCourseQuery.isArchived == this.isArchived) }
apache-2.0
0404dd81ecbc2a72f45b402f9edb81c2
44.790885
175
0.557351
5.717777
false
false
false
false
DavidHamm/wizard-pager
lib/src/main/kotlin/com/hammwerk/wizardpager/core/BranchPage.kt
1
1202
package com.hammwerk.wizardpager.core open class BranchPage(title: String, fragmentName: String) : Page(title, fragmentName, true) { protected var branches = mutableListOf<Branch>() var onBranchSelected: ((BranchPage) -> Unit)? = null val choices: Array<String?> get() { if (branches.size < 2) { throw TwoBranchesRequiredException() } return branches.map { it.name }.toTypedArray() } val selectedBranchIndex: Int? get() { val selectedBranchIndex = branches.indexOf(selectedBranch) return when { selectedBranchIndex != -1 -> selectedBranchIndex else -> null } } var selectedBranch: Branch? = null get() = when { branches.size >= 2 -> field else -> throw TwoBranchesRequiredException() } private set fun addBranch(branchName: String, vararg pages: Page) { branches.add(Branch(branchName).apply { this.pages = arrayOf(*pages) }) } fun selectBranch(index: Int) { if (branches.size < 2) { throw TwoBranchesRequiredException() } if (branches[index] != selectedBranch) { selectedBranch = branches[index] completed = true onBranchSelected?.let { it(this) } } } class TwoBranchesRequiredException : RuntimeException() }
mit
081d464a16012f7cd94d77c82b0cdf2b
24.041667
73
0.693844
3.664634
false
false
false
false
jdiazcano/modulartd
editor/core/src/main/kotlin/com/jdiazcano/modulartd/ui/widgets/ResourcePicker.kt
1
2066
package com.jdiazcano.modulartd.ui.widgets import com.github.salomonbrys.kodein.instance import com.jdiazcano.modulartd.ResourceManager import com.jdiazcano.modulartd.beans.Resource import com.jdiazcano.modulartd.beans.ResourceType import com.jdiazcano.modulartd.bus.Bus import com.jdiazcano.modulartd.bus.BusTopic import com.jdiazcano.modulartd.injections.kodein import com.jdiazcano.modulartd.utils.clickListener import com.kotcrab.vis.ui.layout.GridGroup import com.kotcrab.vis.ui.widget.VisDialog import com.kotcrab.vis.ui.widget.VisScrollPane class ResourcePicker(title: String) : VisDialog(title) { var listeners: MutableList<(Resource) -> Unit> = arrayListOf() var resourceGrid: GridGroup = GridGroup(60f, 7f) init { val sp = VisScrollPane(resourceGrid) sp.setScrollingDisabled(true, false) contentTable.add(sp).expand().fill() addCloseButton() closeOnEscape() isResizable = true setSize(500F, 400F) centerWindow() } fun pickResource(type: ResourceType) { buildTable(type) Bus.post(fadeIn(), BusTopic.NEW_DIALOG) toFront() } fun buildTable(type: ResourceType) { resourceGrid.clearChildren() val resources = kodein.instance<ResourceManager>().getResourcesByType(type) resources.forEach { resource -> val view = ResourceView(resource) view.clickListener { _, _, _ -> listeners.forEach { it(resource) } fadeOut() } resourceGrid.addActor(view) } invalidate() } fun addPickListener(listener: (Resource) -> Unit) { this.listeners.add(listener) } } /** * Creates a simple dialog for a ResourcePicker with a custom listener so you don't have to actually know all the * insiders of the ResourcePicker */ fun pickResource(title: String, type: ResourceType, listener: (Resource) -> Unit) { val picker = ResourcePicker(title) picker.addPickListener(listener) picker.pickResource(type) }
apache-2.0
f1769fec03201f7295d6b4c77ed10028
28.528571
113
0.685866
4.277433
false
false
false
false
Zackratos/PureMusic
app/src/main/kotlin/org/zack/music/main/list/SongListFragment.kt
1
3151
package org.zack.music.main.list import android.support.v7.widget.LinearLayoutManager import kotlinx.android.synthetic.main.fragment_song_list.* import org.zack.music.BaseFragment import org.zack.music.R import org.zack.music.tools.RxBus import org.zack.music.bean.SongInfo import org.zack.music.event.PlaySong import org.zack.music.event.Status import org.zack.music.main.MainFragment /** * * Created by zackratos on 18-5-11. */ class SongListFragment : BaseFragment() { companion object { fun newInstance(): SongListFragment { return SongListFragment() } } override fun layoutId(): Int { return R.layout.fragment_song_list } private var songListAdapter: SongListAdapter? = null override fun initEventAndData() { rv_song_list.layoutManager = LinearLayoutManager(activity) // 接收音乐加载完成事件 /* val loadDisposable = RxBus.getInstance().toObservable(SongsLoaded::class.java) .subscribe { songListAdapter = SongListAdapter(this, it.songs) rv_song_list.adapter = songListAdapter // 音乐加载完成接收成功后通知 service 发送状态事件 val parent = parentFragment as MainFragment parent.sendStatus() } addDisposable(loadDisposable) val statusDisposable = RxBus.getInstance().toObservable(Status::class.java) .filter { it.config.position != -1 } .subscribe { rv_song_list.scrollToPosition(it.config.position) songListAdapter?.currentPosition = it.config.position songListAdapter?.notifyItemChanged(it.config.position) } addDisposable(statusDisposable)*/ val statusDisposable = RxBus.getInstance().toObservable(Status::class.java) .subscribe { songListAdapter = SongListAdapter(this, it.songs) rv_song_list.adapter = songListAdapter val position = it.config.position if (position != -1) { rv_song_list.scrollToPosition(position) songListAdapter?.currentPosition = position songListAdapter?.notifyItemChanged(position) } } addDisposable(statusDisposable) val playDisposable = RxBus.getInstance().toObservable(PlaySong::class.java) .subscribe { rv_song_list.scrollToPosition(it.songInfo.position) songListAdapter?.currentPosition = it.songInfo.position songListAdapter?.lastPosition = it.lastPosition songListAdapter?.notifyItemChanged(it.songInfo.position) songListAdapter?.notifyItemChanged(it.lastPosition) } addDisposable(playDisposable) } fun startPlaySong(songInfo: SongInfo) { val parent = parentFragment as MainFragment parent.startPlaySong(songInfo, true) } }
apache-2.0
4bf3897962c393a96201357f2f342b40
34.563218
88
0.612027
5.198319
false
true
false
false
rolandvitezhu/TodoCloud
app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/fragment/TodoListFragment.kt
1
11727
package com.rolandvitezhu.todocloud.ui.activity.main.fragment import android.content.Context import android.content.DialogInterface import android.os.Bundle import android.view.* import androidx.appcompat.view.ActionMode import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.rolandvitezhu.todocloud.R import com.rolandvitezhu.todocloud.app.AppController import com.rolandvitezhu.todocloud.app.AppController.Companion.instance import com.rolandvitezhu.todocloud.app.AppController.Companion.isDraggingEnabled import com.rolandvitezhu.todocloud.data.Todo import com.rolandvitezhu.todocloud.database.TodoCloudDatabaseDao import com.rolandvitezhu.todocloud.databinding.FragmentTodolistBinding import com.rolandvitezhu.todocloud.ui.activity.main.MainActivity import com.rolandvitezhu.todocloud.ui.activity.main.adapter.TodoAdapter import com.rolandvitezhu.todocloud.ui.activity.main.dialogfragment.ConfirmDeleteDialogFragment import com.rolandvitezhu.todocloud.ui.activity.main.dialogfragment.SortTodoListDialogFragment import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.ListsViewModel import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.PredefinedListsViewModel import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.TodosViewModel import kotlinx.android.synthetic.main.layout_recyclerview_todolist.view.* import kotlinx.coroutines.launch import java.util.* import javax.inject.Inject class TodoListFragment : Fragment(), DialogInterface.OnDismissListener { @Inject lateinit var todoCloudDatabaseDao: TodoCloudDatabaseDao @Inject lateinit var todoAdapter: TodoAdapter var actionMode: ActionMode? = null private val todosViewModel by lazy { activity?.let { ViewModelProvider(it).get(TodosViewModel::class.java) } } private val listsViewModel by lazy { activity?.let { ViewModelProvider(it).get(ListsViewModel::class.java) } } private val predefinedListsViewModel by lazy { activity?.let { ViewModelProvider(it).get(PredefinedListsViewModel::class.java) } } private var swipedTodoAdapterPosition: Int? = null override fun onAttach(context: Context) { super.onAttach(context) Objects.requireNonNull(instance)?.appComponent?.fragmentComponent()?.create()?.inject(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) todosViewModel?.todos?.observe( this, Observer { todos -> todos?.let { todoAdapter.update(it.toMutableList()) } todoAdapter.notifyDataSetChanged() } ) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val fragmentTodoListBinding: FragmentTodolistBinding = FragmentTodolistBinding.inflate(inflater, container, false) val view: View = fragmentTodoListBinding.root prepareRecyclerView() applySwipeToDismissAndDragToReorder(view) fragmentTodoListBinding.lifecycleOwner = this fragmentTodoListBinding.todoListFragment = this fragmentTodoListBinding.executePendingBindings() return view } override fun onResume() { super.onResume() setActionBarTitle() } private fun prepareRecyclerView() { isDraggingEnabled = true } private fun applySwipeToDismissAndDragToReorder(view: View) { val simpleItemTouchCallback: ItemTouchHelper.SimpleCallback = object : ItemTouchHelper.SimpleCallback( 0, ItemTouchHelper.START ) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { val todos: List<Todo?> = todoAdapter.getTodos() val fromPosition = viewHolder.adapterPosition val toPosition = target.adapterPosition // We swap the position of the todos on the list by moving them. We swap the // position values of the moved todos. if (fromPosition < toPosition) { for (i in fromPosition until toPosition) { swapItems(todos, i, i + 1) } } else { for (i in fromPosition downTo toPosition + 1) { swapItems(todos, i, i - 1) } } todoAdapter.notifyItemMoved(viewHolder.adapterPosition, target.adapterPosition) return true } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val swipedTodo = getSwipedTodo(viewHolder) swipedTodoAdapterPosition = viewHolder.adapterPosition swipedTodoAdapterPosition?.let { openConfirmDeleteTodosDialog(swipedTodo, it) } } override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int { val dragFlags: Int val swipeFlags: Int if (AppController.isActionMode()) { dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN swipeFlags = 0 } else { dragFlags = 0 swipeFlags = ItemTouchHelper.START } return ItemTouchHelper.Callback.makeMovementFlags(dragFlags, swipeFlags) } override fun isLongPressDragEnabled(): Boolean { return false } } val itemTouchHelper = ItemTouchHelper(simpleItemTouchCallback) itemTouchHelper.attachToRecyclerView(view.recyclerview_todolist) todoAdapter.itemTouchHelper = itemTouchHelper } /** * Change the todo position values. */ private fun swapItems(todos: List<Todo?>, fromPosition: Int, toPosition: Int) { val todoFrom = todos[fromPosition] val todoTo = todos[toPosition] if (todoFrom != null && todoTo != null) { val tempTodoToPosition = todoFrom.position todoFrom.position = todoTo.position todoTo.position = tempTodoToPosition todoFrom.dirty = true todoTo.dirty = true Collections.swap(todos, fromPosition, toPosition) lifecycleScope.launch { persistSwappedItems(todoFrom, todoTo) } } } /** * Update the position value of the todo items in the database as well and fix the duplications * of the positions if there are. */ private suspend fun persistSwappedItems(todoFrom: Todo?, todoTo: Todo?) { todoFrom?.let{ todoCloudDatabaseDao.updateTodo(it) } todoTo?.let{ todoCloudDatabaseDao.updateTodo(it) } todoCloudDatabaseDao.fixTodoPositions() } private fun getSwipedTodo(viewHolder: RecyclerView.ViewHolder): Todo { val swipedTodoAdapterPosition = viewHolder.adapterPosition return todoAdapter.getTodo(swipedTodoAdapterPosition) } fun areSelectedItems(): Boolean { return todoAdapter.selectedItemCount > 0 } fun isActionMode() = actionMode != null fun openModifyTodoFragment(childViewAdapterPosition: Int) { todosViewModel?.initToModifyTodo(todoAdapter.getTodo(childViewAdapterPosition)) (activity as MainActivity?)?.openModifyTodoFragment(this, null) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.fragment_todolist, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menuitem_todolist_sort -> openSortTodoListDialogFragment() } return super.onOptionsItemSelected(item) } private fun openSortTodoListDialogFragment() { val sortTodoListDialogFragment = SortTodoListDialogFragment() sortTodoListDialogFragment.setTargetFragment(this, 0) sortTodoListDialogFragment.show(parentFragmentManager, "SortTodoListDialogFragment") } private fun setActionBarTitle() { (activity as MainActivity?)?.onSetActionBarTitle(todosViewModel?.todosTitle) } val callback: ActionMode.Callback = object : ActionMode.Callback { override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { setTodoListActionMode(mode) mode.menuInflater.inflate(R.menu.layout_appbar_todolist, menu) return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { val title = prepareTitle() actionMode?.title = title todoAdapter.notifyDataSetChanged() return true } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { when (item.itemId) { R.id.menuitem_layoutappbartodolist_delete -> openConfirmDeleteTodosDialog() } return true } override fun onDestroyActionMode(mode: ActionMode) { todoAdapter.clearSelection() setTodoListActionMode(null) todoAdapter.notifyDataSetChanged() } private fun prepareTitle(): String { val selectedItemCount = todoAdapter.selectedItemCount return selectedItemCount.toString() + " " + getString(R.string.all_selected) } } private fun setTodoListActionMode(actionMode: ActionMode?) { this.actionMode = actionMode AppController.setActionMode(actionMode) } private fun openConfirmDeleteTodosDialog() { val selectedTodos = todoAdapter.selectedTodos val arguments = Bundle() arguments.putString("itemType", "todo") arguments.putParcelableArrayList("itemsToDelete", selectedTodos) openConfirmDeleteDialogFragment(arguments) } private fun openConfirmDeleteTodosDialog(swipedTodo: Todo, swipedTodoAdapterPosition: Int) { val selectedTodos = ArrayList<Todo>() selectedTodos.add(swipedTodo) val arguments = Bundle() arguments.putString("itemType", "todo") arguments.putParcelableArrayList("itemsToDelete", selectedTodos) openConfirmDeleteDialogFragment(arguments) } private fun openConfirmDeleteDialogFragment(arguments: Bundle) { val confirmDeleteDialogFragment = ConfirmDeleteDialogFragment() confirmDeleteDialogFragment.setTargetFragment(this, 0) confirmDeleteDialogFragment.arguments = arguments confirmDeleteDialogFragment.show(parentFragmentManager, "ConfirmDeleteDialogFragment") } fun onFABClick() { actionMode?.finish() ([email protected] as MainActivity?)?. onOpenCreateTodoFragment(this@TodoListFragment) } override fun onDismiss(dialog: DialogInterface?) { if (swipedTodoAdapterPosition != null) todoAdapter.notifyItemChanged(swipedTodoAdapterPosition!!) else todoAdapter.notifyDataSetChanged() } /** * Finish the action mode, if the fragment is in action mode. */ fun finishActionMode() { actionMode?.finish() } }
mit
87ae46efc592869ff705a3fc81521a7d
36.832258
113
0.671868
5.762654
false
false
false
false
jgrandja/spring-security
config/src/test/kotlin/org/springframework/security/config/web/servlet/LogoutDslTests.kt
2
10124
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.config.web.servlet import io.mockk.every import io.mockk.mockkObject import io.mockk.verify import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.mock.web.MockHttpSession import org.springframework.security.authentication.TestingAuthenticationToken import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf import org.springframework.security.web.authentication.logout.LogoutHandler import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler import org.springframework.security.web.context.HttpSessionSecurityContextRepository import org.springframework.security.web.util.matcher.AntPathRequestMatcher import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.post /** * Tests for [LogoutDsl] * * @author Eleftheria Stein */ @ExtendWith(SpringTestContextExtension::class) class LogoutDslTests { @JvmField val spring = SpringTestContext(this) @Autowired lateinit var mockMvc: MockMvc @Test fun `logout when custom logout url then custom url used`() { this.spring.register(CustomLogoutUrlConfig::class.java).autowire() this.mockMvc.post("/custom/logout") { with(csrf()) }.andExpect { status { isFound() } redirectedUrl("/login?logout") } } @EnableWebSecurity open class CustomLogoutUrlConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { logout { logoutUrl = "/custom/logout" } } } } @Test fun `logout when custom logout request matcher then custom request matcher used`() { this.spring.register(CustomLogoutRequestMatcherConfig::class.java).autowire() this.mockMvc.post("/custom/logout") { with(csrf()) }.andExpect { status { isFound() } redirectedUrl("/login?logout") } } @EnableWebSecurity open class CustomLogoutRequestMatcherConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { logout { logoutRequestMatcher = AntPathRequestMatcher("/custom/logout") } } } } @Test fun `logout when custom success url then redirects to success url`() { this.spring.register(SuccessUrlConfig::class.java).autowire() this.mockMvc.post("/logout") { with(csrf()) }.andExpect { status { isFound() } redirectedUrl("/login") } } @EnableWebSecurity open class SuccessUrlConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { logout { logoutSuccessUrl = "/login" } } } } @Test fun `logout when custom success handler then redirects to success url`() { this.spring.register(SuccessHandlerConfig::class.java).autowire() this.mockMvc.post("/logout") { with(csrf()) }.andExpect { status { isFound() } redirectedUrl("/") } } @EnableWebSecurity open class SuccessHandlerConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { logout { logoutSuccessHandler = SimpleUrlLogoutSuccessHandler() } } } } @Test fun `logout when permit all then logout allowed`() { this.spring.register(PermitAllConfig::class.java).autowire() this.mockMvc.post("/custom/logout") { with(csrf()) }.andExpect { status { isFound() } redirectedUrl("/login?logout") } } @EnableWebSecurity open class PermitAllConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { authorizeRequests { authorize(anyRequest, authenticated) } logout { logoutUrl = "/custom/logout" permitAll() } } } } @Test fun `logout when clear authentication false then authentication not cleared`() { this.spring.register(ClearAuthenticationFalseConfig::class.java).autowire() val currentContext = SecurityContextHolder.createEmptyContext() currentContext.authentication = TestingAuthenticationToken("user", "password", "ROLE_USER") val currentSession = MockHttpSession() currentSession.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, currentContext) this.mockMvc.post("/logout") { with(csrf()) session = currentSession }.andExpect { status { isFound() } redirectedUrl("/login?logout") } assertThat(currentContext.authentication).isNotNull } @EnableWebSecurity open class ClearAuthenticationFalseConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { logout { clearAuthentication = false } } } } @Test fun `logout when invalidate http session false then session not invalidated`() { this.spring.register(InvalidateHttpSessionFalseConfig::class.java).autowire() val currentSession = MockHttpSession() this.mockMvc.post("/logout") { with(csrf()) session = currentSession }.andExpect { status { isFound() } redirectedUrl("/login?logout") } assertThat(currentSession.isInvalid).isFalse() } @EnableWebSecurity open class InvalidateHttpSessionFalseConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { logout { invalidateHttpSession = false } } } } @Test fun `logout when delete cookies then cookies are cleared`() { this.spring.register(DeleteCookiesConfig::class.java).autowire() this.mockMvc.post("/logout") { with(csrf()) }.andExpect { status { isFound() } redirectedUrl("/login?logout") cookie { maxAge("remove", 0) } } } @EnableWebSecurity open class DeleteCookiesConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { logout { deleteCookies("remove") } } } } @Test fun `logout when default logout success handler for request then custom handler used`() { this.spring.register(DefaultLogoutSuccessHandlerForConfig::class.java).autowire() this.mockMvc.post("/logout/default") { with(csrf()) }.andExpect { status { isFound() } redirectedUrl("/login?logout") } this.mockMvc.post("/logout/custom") { with(csrf()) }.andExpect { status { isFound() } redirectedUrl("/") } } @EnableWebSecurity open class DefaultLogoutSuccessHandlerForConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { logout { logoutRequestMatcher = AntPathRequestMatcher("/logout/**") defaultLogoutSuccessHandlerFor(SimpleUrlLogoutSuccessHandler(), AntPathRequestMatcher("/logout/custom")) } } } } @Test fun `logout when custom logout handler then custom handler used`() { this.spring.register(CustomLogoutHandlerConfig::class.java).autowire() mockkObject(CustomLogoutHandlerConfig.HANDLER) every { CustomLogoutHandlerConfig.HANDLER.logout(any(), any(), any()) } returns Unit this.mockMvc.post("/logout") { with(csrf()) } verify(exactly = 1) { CustomLogoutHandlerConfig.HANDLER.logout(any(), any(), any()) } } @EnableWebSecurity open class CustomLogoutHandlerConfig : WebSecurityConfigurerAdapter() { companion object { val HANDLER: LogoutHandler = LogoutHandler { _, _, _ -> } } override fun configure(http: HttpSecurity) { http { logout { addLogoutHandler(HANDLER) } } } } }
apache-2.0
733230e8e50c048406054f43ce8d4358
31.242038
124
0.620308
5.4197
false
true
false
false
Maccimo/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/utils.kt
1
4585
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.dsl.builder.impl import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.util.NlsContexts import com.intellij.ui.TitledSeparator import com.intellij.ui.ToolbarDecorator import com.intellij.ui.dsl.UiDslException import com.intellij.ui.dsl.builder.Cell import com.intellij.ui.dsl.builder.DslComponentProperty import com.intellij.ui.dsl.builder.HyperlinkEventAction import com.intellij.ui.dsl.builder.SpacingConfiguration import com.intellij.ui.dsl.builder.components.DslLabel import com.intellij.ui.dsl.builder.components.DslLabelType import com.intellij.ui.dsl.builder.components.SegmentedButtonToolbar import com.intellij.ui.dsl.gridLayout.Gaps import com.intellij.ui.dsl.gridLayout.GridLayoutComponentProperty import org.jetbrains.annotations.ApiStatus import javax.swing.* import javax.swing.text.JTextComponent /** * Internal component properties for UI DSL */ @ApiStatus.Internal internal enum class DslComponentPropertyInternal { /** * Removes standard bottom gap from label */ LABEL_NO_BOTTOM_GAP, /** * A mark that component is a cell label, see [Cell.label] * * Value: true */ CELL_LABEL } /** * [JPanel] descendants that should use default vertical gaps around similar to other standard components like labels, text fields etc */ private val DEFAULT_VERTICAL_GAP_COMPONENTS = setOf( SegmentedButtonComponent::class, SegmentedButtonToolbar::class, TextFieldWithBrowseButton::class, TitledSeparator::class ) /** * Throws exception instead of logging warning. Useful while forms building to avoid layout mistakes */ private const val FAIL_ON_WARN = false private val LOG = Logger.getInstance("Jetbrains UI DSL") /** * Components that can have assigned labels */ private val ALLOWED_LABEL_COMPONENTS = listOf( JComboBox::class, JSlider::class, JSpinner::class, JTable::class, JTextComponent::class, JTree::class, SegmentedButtonComponent::class, SegmentedButtonToolbar::class ) internal val JComponent.origin: JComponent get() { return when (this) { is TextFieldWithBrowseButton -> textField else -> this } } internal fun prepareVisualPaddings(component: JComponent): Gaps { val insets = component.insets val customVisualPaddings = component.getClientProperty(DslComponentProperty.VISUAL_PADDINGS) as? Gaps if (customVisualPaddings == null) { return Gaps(top = insets.top, left = insets.left, bottom = insets.bottom, right = insets.right) } component.putClientProperty(GridLayoutComponentProperty.SUB_GRID_AUTO_VISUAL_PADDINGS, false) return customVisualPaddings } internal fun getComponentGaps(left: Int, right: Int, component: JComponent, spacing: SpacingConfiguration): Gaps { val top = getDefaultVerticalGap(component, spacing) var bottom = top if (component is JLabel && component.getClientProperty(DslComponentPropertyInternal.LABEL_NO_BOTTOM_GAP) == true) { bottom = 0 } return Gaps(top = top, left = left, bottom = bottom, right = right) } /** * Returns default top and bottom gap for [component]. All non [JPanel] components or * [DEFAULT_VERTICAL_GAP_COMPONENTS] have default vertical gap, zero otherwise */ internal fun getDefaultVerticalGap(component: JComponent, spacing: SpacingConfiguration): Int { val noDefaultVerticalGap = component is JPanel && component.getClientProperty(ToolbarDecorator.DECORATOR_KEY) == null && !DEFAULT_VERTICAL_GAP_COMPONENTS.any { clazz -> clazz.isInstance(component) } return if (noDefaultVerticalGap) 0 else spacing.verticalComponentGap } internal fun createComment(@NlsContexts.Label text: String, maxLineLength: Int, action: HyperlinkEventAction): DslLabel { val result = DslLabel(DslLabelType.COMMENT) result.action = action result.maxLineLength = maxLineLength result.text = text return result } internal fun isAllowedLabel(cell: CellBaseImpl<*>?): Boolean { return cell is CellImpl<*> && ALLOWED_LABEL_COMPONENTS.any { clazz -> clazz.isInstance(cell.component.origin) } } internal fun labelCell(label: JLabel, cell: CellBaseImpl<*>?) { if (isAllowedLabel(cell)) { label.labelFor = (cell as CellImpl<*>).component.origin } } internal fun warn(message: String) { if (FAIL_ON_WARN) { throw UiDslException(message) } else { LOG.warn(message) } }
apache-2.0
3138cba751394449fbcbb3e87ce6652b
32.467153
158
0.757252
4.345972
false
false
false
false
ihmcrobotics/ihmc-build
src/test/kotlin/us/ihmc/build/NexusRESTAPITest.kt
1
5221
package us.ihmc.build import kong.unirest.Unirest import kong.unirest.json.JSONObject import org.gradle.api.GradleException import java.io.ByteArrayInputStream import javax.xml.parsers.DocumentBuilderFactory fun main() { val nexusUsername = "username" val nexusPassword = "password" var continuationToken = "first_page" val requestUrl = "https://nexus.ihmc.us/service/rest/v1/search?repository=proprietary-releases&maven.groupId=us.ihmc" val matches = arrayListOf<JSONObject>() val documentBuilderFactory = DocumentBuilderFactory.newInstance() while (continuationToken != "no_more_pages") { Unirest.get(if (continuationToken == "first_page") requestUrl else "$requestUrl&continuationToken=$continuationToken") .basicAuth(nexusUsername, nexusPassword) .asJson() .ifSuccess { response -> val bodyObject: JSONObject = response.body.`object` if (bodyObject.isNull("continuationToken")) continuationToken = "no_more_pages" else continuationToken = bodyObject.getString("continuationToken") val items = bodyObject.getJSONArray("items") for (item in items) { val assets = (item as JSONObject).getJSONArray("assets") for (asset in assets) { val assetObject = asset as JSONObject val path = assetObject.getString("path") if (path.matches(Regex(".*"))) { matches.add(assetObject) if (path == "us/ihmc/impulse-series-4-controller/0.1.1/impulse-series-4-controller-0.1.1.pom") { var bytes: ByteArray? = null val downloadUrl = asset.getString("downloadUrl") Unirest.get(downloadUrl) .basicAuth(nexusUsername, nexusPassword) .asBytes() .ifSuccess { response -> bytes = response.body val inputStream = ByteArrayInputStream(bytes) try { val documentBuilder = documentBuilderFactory.newDocumentBuilder() val document = documentBuilder.parse(inputStream); val dependencyTags = document.getElementsByTagName("dependency") for (i in 0 until dependencyTags.length) { val dependencyGroupId = dependencyTags.item(i).childNodes.item(1).textContent val dependencyArtifactId = dependencyTags.item(i).childNodes.item(3).textContent val dependencyVersion = dependencyTags.item(i).childNodes.item(5).textContent println(dependencyGroupId) println(dependencyArtifactId) println(dependencyVersion) } } catch (e: Exception) { e.printStackTrace() } } .ifFailure { response -> throw GradleException("Problem authenticating or retrieving item from Nexus: $downloadUrl. " + "Try logging into https://nexus.ihmc.us with the credentials used " + "(nexusUsername and nexusPassword properties) and see if the item is there.") } } } } } } .ifFailure { response -> throw GradleException("Problem authenticating or retrieving item from Nexus: $requestUrl. " + "Try logging into https://nexus.ihmc.us with the credentials used " + "(nexusUsername and nexusPassword properties) and see if the item is there.") } } for (match in matches) { println(match) } }
apache-2.0
e47bb3f635a69c961ffbab3763b2e53e
56.373626
142
0.422716
7.251389
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/commands/NormalCommand.kt
1
3486
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.commands import com.maddyhome.idea.vim.KeyHandler import com.maddyhome.idea.vim.api.BufferPosition import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.command.VimStateMachine import com.maddyhome.idea.vim.ex.ranges.Ranges import com.maddyhome.idea.vim.helper.exitVisualMode import com.maddyhome.idea.vim.helper.mode import com.maddyhome.idea.vim.helper.vimStateMachine import com.maddyhome.idea.vim.vimscript.model.ExecutionResult data class NormalCommand(val ranges: Ranges, val argument: String) : Command.SingleExecution(ranges, argument) { override val argFlags = flags( RangeFlag.RANGE_OPTIONAL, ArgumentFlag.ARGUMENT_OPTIONAL, Access.WRITABLE, Flag.SAVE_VISUAL ) override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult { var useMappings = true var argument = argument if (argument.startsWith("!")) { useMappings = false argument = argument.substring(1) } val commandState = editor.vimStateMachine val rangeUsed = ranges.size() != 0 when (editor.mode) { VimStateMachine.Mode.VISUAL -> { editor.exitVisualMode() if (!rangeUsed) { val selectionStart = injector.markGroup.getMark(editor, '<')!! editor.currentCaret().moveToBufferPosition(BufferPosition(selectionStart.line, selectionStart.col)) } } VimStateMachine.Mode.CMD_LINE -> injector.processGroup.cancelExEntry(editor, false) VimStateMachine.Mode.INSERT, VimStateMachine.Mode.REPLACE -> editor.exitInsertMode(context, OperatorArguments(false, 1, commandState.mode, commandState.subMode)) VimStateMachine.Mode.SELECT -> editor.exitSelectModeNative(false) VimStateMachine.Mode.OP_PENDING, VimStateMachine.Mode.COMMAND -> Unit VimStateMachine.Mode.INSERT_NORMAL -> Unit VimStateMachine.Mode.INSERT_VISUAL -> Unit VimStateMachine.Mode.INSERT_SELECT -> Unit } val range = getLineRange(editor, editor.primaryCaret()) for (line in range.startLine..range.endLine) { if (rangeUsed) { // Move caret to the first position on line if (editor.lineCount() < line) { break } val startOffset = editor.getLineStartOffset(line) editor.currentCaret().moveToOffset(startOffset) } // Perform operations val keys = injector.parser.stringToKeys(argument) val keyHandler = KeyHandler.getInstance() keyHandler.reset(editor) for (key in keys) { keyHandler.handleKey(editor, key, context, useMappings, true) } // Exit if state leaves as insert or cmd_line val mode = commandState.mode if (mode == VimStateMachine.Mode.CMD_LINE) { injector.processGroup.cancelExEntry(editor, false) } if (mode == VimStateMachine.Mode.INSERT || mode == VimStateMachine.Mode.REPLACE) { editor.exitInsertMode(context, OperatorArguments(false, 1, commandState.mode, commandState.subMode)) } } return ExecutionResult.Success } }
mit
6e88846f16699c1157f90b669810ecb9
37.733333
167
0.720023
4.390428
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/change/change/ChangeCharacterAction.kt
1
3278
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.action.change.change import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.getLeadingCharacterOffset import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.lineLength import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.diagnostic.debug import com.maddyhome.idea.vim.diagnostic.vimLogger import com.maddyhome.idea.vim.handler.ChangeEditorActionHandler import com.maddyhome.idea.vim.helper.enumSetOf import java.util.* class ChangeCharacterAction : ChangeEditorActionHandler.ForEachCaret() { override val type: Command.Type = Command.Type.CHANGE override val argumentType: Argument.Type = Argument.Type.DIGRAPH override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_ALLOW_DIGRAPH) override fun execute( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument?, operatorArguments: OperatorArguments, ): Boolean { return argument != null && changeCharacter(editor, caret, operatorArguments.count1, argument.character) } } private val logger = vimLogger<ChangeCharacterAction>() /** * Replace each of the next count characters with the character ch * * @param editor The editor to change * @param caret The caret to perform action on * @param count The number of characters to change * @param ch The character to change to * @return true if able to change count characters, false if not */ private fun changeCharacter(editor: VimEditor, caret: VimCaret, count: Int, ch: Char): Boolean { val col = caret.getBufferPosition().column // TODO: Is this correct? Should we really use only current caret? We have a caret as an argument val len = editor.lineLength(editor.currentCaret().getBufferPosition().line) val offset = caret.offset.point if (len - col < count) { return false } // Special case - if char is newline, only add one despite count var num = count var space: String? = null if (ch == '\n') { num = 1 space = editor.getLeadingWhitespace(editor.offsetToBufferPosition(offset).line) logger.debug { "space='$space'" } } val repl = StringBuilder(count) for (i in 0 until num) { repl.append(ch) } injector.changeGroup.replaceText(editor, offset, offset + count, repl.toString()) // Indent new line if we replaced with a newline if (ch == '\n') { injector.changeGroup.insertText(editor, caret, offset + 1, space!!) var slen = space.length if (slen == 0) { slen++ } caret.moveToInlayAwareOffset(offset + slen) } return true } private fun VimEditor.getLeadingWhitespace(line: Int): String { val start: Int = getLineStartOffset(line) val end: Int = getLeadingCharacterOffset(line, 0) return text().subSequence(start, end).toString() }
mit
0fc0be60558a4aa9a177444f0048ae51
33.87234
107
0.744356
3.963724
false
false
false
false
android/connectivity-samples
UwbRanging/app/src/main/java/com/google/apps/hellouwb/ui/theme/Color.kt
1
916
/* * * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.google.apps.hellouwb.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
apache-2.0
7adbe0aa4c3ec6cadc4427ffbb86c676
30.586207
75
0.751092
3.496183
false
false
false
false
kelsos/mbrc
app/src/main/kotlin/com/kelsos/mbrc/repository/ModelInitializer.kt
1
1222
package com.kelsos.mbrc.repository import com.kelsos.mbrc.di.modules.AppDispatchers import com.kelsos.mbrc.domain.isEmpty import com.kelsos.mbrc.model.MainDataModel import kotlinx.coroutines.withContext import timber.log.Timber import java.io.FileNotFoundException import javax.inject.Inject import javax.inject.Singleton @Singleton class ModelInitializer @Inject constructor( private val model: MainDataModel, private val cache: ModelCache, private val dispatchers: AppDispatchers ) { private var done = false suspend fun initialize() { if (done) { return } done = true try { withContext(dispatchers.io) { if (model.trackInfo.isEmpty()) { model.trackInfo = cache.restoreInfo() Timber.v("Loaded trackinfo") } if (model.coverPath.isEmpty()) { model.coverPath = cache.restoreCover() Timber.v("Loaded cover") } } } catch (e: Exception) { onLoadError(e) done = false } } private fun onLoadError(it: Throwable?) { if (it is FileNotFoundException) { Timber.v("No state was previously stored") } else { Timber.v(it, "Error while loading the state") } } }
gpl-3.0
93b6b1017be6b22d7272c6566b900eb2
21.218182
51
0.664484
4.100671
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/benchmark/AbstractCompletionBenchmarkAction.kt
1
8605
// 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.actions.internal.benchmark import com.intellij.codeInsight.AutoPopupController import com.intellij.codeInsight.completion.CompletionType import com.intellij.codeInsight.navigation.NavigationUtil import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageType import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.wm.WindowManager import com.intellij.psi.PsiDocumentManager import com.intellij.psi.search.FileTypeIndex import com.intellij.psi.search.GlobalSearchScope import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBTextField import com.intellij.uiDesigner.core.GridConstraints import kotlinx.coroutines.* import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleOrigin import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfoOrNull import org.jetbrains.kotlin.idea.completion.CompletionBenchmarkSink import org.jetbrains.kotlin.idea.core.moveCaret import org.jetbrains.kotlin.idea.core.util.EDT import org.jetbrains.kotlin.idea.base.psi.getLineCount import org.jetbrains.kotlin.idea.core.util.toPsiFile import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.psi.KtFile import java.util.* import javax.swing.JFileChooser import javax.swing.JPanel abstract class AbstractCompletionBenchmarkAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val benchmarkSink = CompletionBenchmarkSink.enableAndGet() val scenario = createBenchmarkScenario(project, benchmarkSink) ?: return GlobalScope.launch(EDT) { scenario.doBenchmark() CompletionBenchmarkSink.disable() } } internal abstract fun createBenchmarkScenario( project: Project, benchmarkSink: CompletionBenchmarkSink.Impl ): AbstractCompletionBenchmarkScenario? companion object { fun showPopup(project: Project, @Nls text: String) { val statusBar = WindowManager.getInstance().getStatusBar(project) JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(text, MessageType.ERROR, null) .setFadeoutTime(5000) .createBalloon().showInCenterOf(statusBar.component) } internal fun <T> List<T>.randomElement(random: Random): T? = if (this.isNotEmpty()) this[random.nextInt(this.size)] else null internal fun <T : Any> List<T>.shuffledSequence(random: Random): Sequence<T> = generateSequence { this.randomElement(random) }.distinct() internal fun collectSuitableKotlinFiles(project: Project, filePredicate: (KtFile) -> Boolean): MutableList<KtFile> { val scope = GlobalSearchScope.allScope(project) fun KtFile.isUsableForBenchmark(): Boolean { val moduleInfo = this.moduleInfoOrNull ?: return false if (this.isCompiled || !this.isWritable || this.isScript()) return false return moduleInfo.moduleOrigin == ModuleOrigin.MODULE } val kotlinVFiles = FileTypeIndex.getFiles(KotlinFileType.INSTANCE, scope) return kotlinVFiles .asSequence() .mapNotNull { vfile -> (vfile.toPsiFile(project) as? KtFile) } .filterTo(mutableListOf()) { it.isUsableForBenchmark() && filePredicate(it) } } internal fun JPanel.addBoxWithLabel(@Nls tooltip: String, @Nls label: String = "$tooltip:", default: String, i: Int): JBTextField { this.add(JBLabel(label), GridConstraints().apply { row = i; column = 0 }) val textField = JBTextField().apply { text = default toolTipText = tooltip } this.add(textField, GridConstraints().apply { row = i; column = 1; fill = GridConstraints.FILL_HORIZONTAL }) return textField } } override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = isApplicationInternalMode() } } internal abstract class AbstractCompletionBenchmarkScenario( val project: Project, private val benchmarkSink: CompletionBenchmarkSink.Impl, val random: Random = Random(), private val timeout: Long = 15000 ) { sealed class Result { abstract fun toCSV(stringBuilder: StringBuilder) open class SuccessResult(val lines: Int, val filePath: String, val first: Long, val full: Long) : Result() { override fun toCSV(stringBuilder: StringBuilder): Unit = with(stringBuilder) { append(filePath) append(", ") append(lines) append(", ") append(first) append(", ") append(full) } } class ErrorResult(val filePath: String) : Result() { override fun toCSV(stringBuilder: StringBuilder): Unit = with(stringBuilder) { append(filePath) append(", ") append(", ") append(", ") } } } protected suspend fun typeAtOffsetAndGetResult(text: String, offset: Int, file: KtFile): Result { NavigationUtil.openFileWithPsiElement(file.navigationElement, false, true) val document = PsiDocumentManager.getInstance(project).getDocument(file) ?: return Result.ErrorResult("${file.virtualFile.path}:O$offset") val location = "${file.virtualFile.path}:${document.getLineNumber(offset)}" val editor = EditorFactory.getInstance().getEditors(document, project).firstOrNull() ?: return Result.ErrorResult(location) delay(500) editor.moveCaret(offset, scrollType = ScrollType.CENTER) delay(500) CommandProcessor.getInstance().executeCommand(project, { runWriteAction { document.insertString(editor.caretModel.offset, "\n$text\n") PsiDocumentManager.getInstance(project).commitDocument(document) } editor.moveCaret(editor.caretModel.offset + text.length + 1) AutoPopupController.getInstance(project).scheduleAutoPopup(editor, CompletionType.BASIC, null) }, "InsertTextAndInvokeCompletion", "completionBenchmark") val result = try { withTimeout(timeout) { collectResult(file, location) } } catch (_: CancellationException) { Result.ErrorResult(location) } CommandProcessor.getInstance().executeCommand(project, { runWriteAction { document.deleteString(offset, offset + text.length + 2) PsiDocumentManager.getInstance(project).commitDocument(document) } }, "RevertToOriginal", "completionBenchmark") delay(100) return result } private suspend fun collectResult(file: KtFile, location: String): Result { val results = benchmarkSink.channel.receive() return Result.SuccessResult(file.getLineCount(), location, results.firstFlush, results.full) } protected fun saveResults(allResults: List<Result>) { val jfc = JFileChooser() val result = jfc.showSaveDialog(null) if (result == JFileChooser.APPROVE_OPTION) { val file = jfc.selectedFile file.writeText(buildString { appendLine("n, file, lines, ff, full") var i = 0 allResults.forEach { append(i++) append(", ") it.toCSV(this) appendLine() } }) } AbstractCompletionBenchmarkAction.showPopup(project, KotlinBundle.message("title.done")) } abstract suspend fun doBenchmark() }
apache-2.0
063e775efdca105cab0b6d19d93aa88b
40.370192
158
0.675305
5.070713
false
false
false
false
android/play-billing-samples
TrivialDriveKotlin/app/src/main/java/com/sample/android/trivialdrivesample/db/GameStateModel.kt
1
2414
/* * Copyright (C) 2021 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sample.android.trivialdrivesample.db import android.app.Application import androidx.room.Room import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.withContext class GameStateModel(application: Application) { private val db: GameStateDatabase private val gameStateDao: GameStateDao private val gasTankLevel: Flow<Int> private val defaultDispatcher: CoroutineDispatcher = Dispatchers.IO suspend fun decrementGas(minLevel: Int): Int { return withContext(defaultDispatcher) { gameStateDao.decrement(GAS_LEVEL, minLevel) } } suspend fun incrementGas(maxLevel: Int): Int { return withContext(defaultDispatcher) { gameStateDao.increment(GAS_LEVEL, maxLevel) } } fun gasTankLevel(): Flow<Int> { return gasTankLevel } companion object { private const val GAS_LEVEL = "gas" } init { // This creates our DB and populates our game state database with the initial state of // a full tank db = Room.databaseBuilder( application, GameStateDatabase::class.java, "GameState.db" ) .createFromAsset("database/initialgamestate.db") .build() gameStateDao = db.gameStateDao() // this causes the gasTankLevel from our Room database to behave more like LiveData gasTankLevel = gameStateDao[GAS_LEVEL].distinctUntilChanged().shareIn(CoroutineScope(Dispatchers.Main), SharingStarted.Lazily, 1) } }
apache-2.0
12fb0cf72744bfa5c6d46ef354bcca97
33.985507
137
0.718724
4.714844
false
false
false
false
efficios/jabberwocky
javeltrace/src/main/kotlin/com/efficios/jabberwocky/javeltrace/TimegraphExample.kt
2
2347
/* * Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]> * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ @file:JvmName("TimegraphExample") package com.efficios.jabberwocky.javeltrace import com.efficios.jabberwocky.common.TimeRange import com.efficios.jabberwocky.ctf.trace.CtfTrace import com.efficios.jabberwocky.lttng.kernel.views.timegraph.threads.ThreadsModelProvider import com.efficios.jabberwocky.project.TraceProject import com.efficios.jabberwocky.views.timegraph.view.json.RenderToJson import com.google.common.primitives.Longs import java.nio.file.Files import java.nio.file.Paths /** * Example of a standalone program generating the JSON for the Threads * timegraph model for a given trace and time range. */ fun main(args: Array<String>) { /* Parse the command-line parameters */ if (args.size < 4) { printUsage() return } val tracePath = args[0] val renderStart = Longs.tryParse(args[1]) val renderEnd = Longs.tryParse(args[2]) val resolution = Longs.tryParse(args[3]) if (renderStart == null || renderEnd == null || resolution == null) { printUsage() return } /* Create the trace project */ val projectPath = Files.createTempDirectory("project") val trace = CtfTrace(Paths.get(tracePath)) val project = TraceProject.ofSingleTrace("MyProject", projectPath, trace) /* Query for a timegraph render for the requested time range */ val modelProvider = ThreadsModelProvider() val stateModelProvider = modelProvider.stateProvider modelProvider.traceProject = project val range = TimeRange.of(renderStart, renderEnd) val treeRender = modelProvider.getTreeRender() val renders = stateModelProvider.getAllStateRenders(treeRender, range, resolution, null) RenderToJson.printRenderToStdout(renders) /* Cleanup */ projectPath.toFile().deleteRecursively() } private fun printUsage() { System.err.println("Cannot parse command-line arguments.") System.err.println("Usage: java -jar <jarname>.jar [TRACE PATH] [RENDER START TIME] [RENDER END TIME] [RESOLUTION]") }
epl-1.0
b2488414e0997f71892e2a46df70e1b8
34.044776
120
0.737537
4.176157
false
false
false
false
siarhei-luskanau/android-iot-doorbell
di/di_dagger/di_dagger_image_list/src/main/kotlin/siarhei/luskanau/iot/doorbell/dagger/imagelist/ImageListBuilderModule.kt
1
1306
package siarhei.luskanau.iot.doorbell.dagger.imagelist import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentFactory import androidx.lifecycle.ViewModelProvider import dagger.Module import dagger.Provides import siarhei.luskanau.iot.doorbell.common.AppNavigation import siarhei.luskanau.iot.doorbell.dagger.common.CommonComponent import siarhei.luskanau.iot.doorbell.dagger.common.DaggerFragmentFactory import siarhei.luskanau.iot.doorbell.ui.imagelist.ImageListFragment import siarhei.luskanau.iot.doorbell.ui.imagelist.ImageListViewModel import javax.inject.Provider @Module class ImageListBuilderModule { @Provides fun provideFragmentFactory( providers: MutableMap<Class<out Fragment>, Provider<Fragment>> ): FragmentFactory = DaggerFragmentFactory( providers ) @Provides fun provideImageListFragment( appNavigation: AppNavigation, commonComponent: CommonComponent ) = ImageListFragment { fragment: Fragment -> val viewModelFactory = ImageListViewModelFactory( commonComponent = commonComponent, appNavigation = appNavigation, args = fragment.arguments ) ViewModelProvider(fragment, viewModelFactory) .get(ImageListViewModel::class.java) } }
mit
2ce5ecf780319b473d67d896a8f1575a
33.368421
72
0.764165
5.18254
false
false
false
false
efficios/jabberwocky
jabberwockd/src/main/kotlin/com/efficios/jabberwocky/jabberwockd/handlers/DebugHandler.kt
2
2479
/* * Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]> * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.efficios.jabberwocky.jabberwockd.handlers import com.sun.net.httpserver.Headers import com.sun.net.httpserver.HttpExchange import com.sun.net.httpserver.HttpHandler class DebugHandler : HttpHandler { override fun handle(t: HttpExchange) { /* * <ol><li>{@link #getRequestMethod()} to determine the command * <li>{@link #getRequestHeaders()} to examine the request headers (if needed) * <li>{@link #getRequestBody()} returns a {@link java.io.InputStream} for reading the request body. * After reading the request body, the stream is close. * <li>{@link #getResponseHeaders()} to set any response headers, except content-length * <li>{@link #sendResponseHeaders(int,long)} to send the response headers. Must be called before * next step. * <li>{@link #getResponseBody()} to get a {@link java.io.OutputStream} to send the response body. * When the response body has been written, the stream must be closed to terminate the exchange. * </ol> */ val requestMethod = t.requestMethod val requestHeaders = t.requestHeaders val requestBody = t.requestBody val requestBodyString = requestBody.bufferedReader().use { it.readText() } println("Request URI = ${t.requestURI}") println("Request method = $requestMethod") println("Request headers = ${requestHeaders.prettyPrint()}") println("Request body = $requestBodyString") println("Local address = ${t.localAddress}") println("Remote address = ${t.remoteAddress}") println("----------") // val responseHeaders = t.responseHeaders // responseHeaders.set(...) val response = "This is the response" val responseArray = response.toByteArray() t.sendResponseHeaders(200, responseArray.size.toLong()) val responseBody = t.responseBody responseBody.write(responseArray) responseBody.close() } } private fun Headers.prettyPrint(): String { return map { "${it.key} = ${it.value}" }.joinToString(separator = ",\n ") }
epl-1.0
a7fcdde0991e1954d19c4dcfeb4aa4da
40.333333
108
0.668011
4.590741
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ComposedIdSoftRefEntityImpl.kt
2
8495
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.MutableEntityStorage import com.intellij.workspaceModel.storage.SymbolicEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.SoftLinkable 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.indices.WorkspaceMutableIndex import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ComposedIdSoftRefEntityImpl(val dataSource: ComposedIdSoftRefEntityData) : ComposedIdSoftRefEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override val myName: String get() = dataSource.myName override val link: NameId get() = dataSource.link override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: ComposedIdSoftRefEntityData?) : ModifiableWorkspaceEntityBase<ComposedIdSoftRefEntity, ComposedIdSoftRefEntityData>( result), ComposedIdSoftRefEntity.Builder { constructor() : this(ComposedIdSoftRefEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ComposedIdSoftRefEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // 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 (!getEntityData().isMyNameInitialized()) { error("Field ComposedIdSoftRefEntity#myName should be initialized") } if (!getEntityData().isLinkInitialized()) { error("Field ComposedIdSoftRefEntity#link 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 ComposedIdSoftRefEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.myName != dataSource.myName) this.myName = dataSource.myName if (this.link != dataSource.link) this.link = dataSource.link if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var myName: String get() = getEntityData().myName set(value) { checkModificationAllowed() getEntityData(true).myName = value changedProperty.add("myName") } override var link: NameId get() = getEntityData().link set(value) { checkModificationAllowed() getEntityData(true).link = value changedProperty.add("link") } override fun getEntityClass(): Class<ComposedIdSoftRefEntity> = ComposedIdSoftRefEntity::class.java } } class ComposedIdSoftRefEntityData : WorkspaceEntityData.WithCalculableSymbolicId<ComposedIdSoftRefEntity>(), SoftLinkable { lateinit var myName: String lateinit var link: NameId fun isMyNameInitialized(): Boolean = ::myName.isInitialized fun isLinkInitialized(): Boolean = ::link.isInitialized override fun getLinks(): Set<SymbolicEntityId<*>> { val result = HashSet<SymbolicEntityId<*>>() result.add(link) return result } override fun index(index: WorkspaceMutableIndex<SymbolicEntityId<*>>) { index.index(this, link) } override fun updateLinksIndex(prev: Set<SymbolicEntityId<*>>, index: WorkspaceMutableIndex<SymbolicEntityId<*>>) { // TODO verify logic val mutablePreviousSet = HashSet(prev) val removedItem_link = mutablePreviousSet.remove(link) if (!removedItem_link) { index.index(this, link) } for (removed in mutablePreviousSet) { index.remove(this, removed) } } override fun updateLink(oldLink: SymbolicEntityId<*>, newLink: SymbolicEntityId<*>): Boolean { var changed = false val link_data = if (link == oldLink) { changed = true newLink as NameId } else { null } if (link_data != null) { link = link_data } return changed } override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ComposedIdSoftRefEntity> { val modifiable = ComposedIdSoftRefEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): ComposedIdSoftRefEntity { return getCached(snapshot) { val entity = ComposedIdSoftRefEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun symbolicId(): SymbolicEntityId<*> { return ComposedId(myName, link) } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ComposedIdSoftRefEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ComposedIdSoftRefEntity(myName, link, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ComposedIdSoftRefEntityData if (this.entitySource != other.entitySource) return false if (this.myName != other.myName) return false if (this.link != other.link) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ComposedIdSoftRefEntityData if (this.myName != other.myName) return false if (this.link != other.link) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + myName.hashCode() result = 31 * result + link.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + myName.hashCode() result = 31 * result + link.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.add(NameId::class.java) collector.sameForAllEntities = true } }
apache-2.0
7ff6380d796a8705648dc4546d21eb9d
31.547893
140
0.724544
5.289539
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-remote-driver/src/main/kotlin/com/onyx/network/rmi/OnyxRMIClient.kt
1
2432
package com.onyx.network.rmi import com.onyx.network.NetworkClient import com.onyx.network.rmi.data.RMIRequest import java.lang.reflect.InvocationHandler import java.lang.reflect.Method import java.lang.reflect.Proxy import java.util.* /** * Created by Tim Osborn on 6/27/16. * * * The purpose of this is to serve as a thin client for retrieving proxy remote instances from the server * * @since 1.2.0 */ class OnyxRMIClient : NetworkClient() { // Local Cache of Remote Objects private val registeredObjects = HashMap<String, Any>() /** * Get a Remote Proxy Object * * @param remoteId Instance name of the registered object * @param type The class type of what you are trying to get * @return Instance of the remote proxy object * @since 1.2.0 */ fun getRemoteObject(remoteId: String, type: Class<*>): Any? { // Return the registered Object if (registeredObjects.containsKey(remoteId)) return registeredObjects[remoteId] // Create an array to feed to the Proxy factory val interfaces = arrayOfNulls<Class<*>>(1) interfaces[0] = type val instance = Proxy.newProxyInstance(type.classLoader, interfaces, RMIClientInvocationHandler(type, remoteId)) // Add it to the local cache registeredObjects.put(remoteId, instance) return instance } /** * This class is added in order to support tracking of methods. * Rather than sending in the string value of a method, this is optimized * to use the sorted index of a method so the packet is reduced from * a string to a single byte. * * @since 1.3.0 */ private inner class RMIClientInvocationHandler internal constructor(type: Class<*>, internal val remoteId: String) : InvocationHandler { internal var methods: MutableList<Method> = ArrayList() init { val methodArray = type.declaredMethods this.methods = Arrays.asList(*methodArray) this.methods.sortBy { it.toString() } } @Throws(Throwable::class) override fun invoke(proxy: Any, method: Method, args: Array<Any?>): Any? { val request = RMIRequest(remoteId, methods.indexOf(method).toByte(), args) val result = send(request) if (result is Exception) throw result return result } } }
agpl-3.0
3624aa184ec398cd053e4626ec120e95
31
140
0.652961
4.470588
false
false
false
false
mvmike/min-cal-widget
app/src/main/kotlin/cat/mvmike/minimalcalendarwidget/domain/configuration/item/Colour.kt
1
2598
// Copyright (c) 2016, Miquel Martí <[email protected]> // See LICENSE for licensing information package cat.mvmike.minimalcalendarwidget.domain.configuration.item import android.content.Context import android.os.Build import cat.mvmike.minimalcalendarwidget.R import cat.mvmike.minimalcalendarwidget.infrastructure.resolver.SystemResolver enum class Colour( val displayString: Int, private val darkThemeHexColour: Int, private val lightThemeHexColour: Int ) { SYSTEM_ACCENT( displayString = R.string.system_accent, darkThemeHexColour = R.color.instances_system_accent_light, lightThemeHexColour = R.color.instances_system_accent_dark ) { override fun isAvailable() = SystemResolver.getRuntimeSDK() >= Build.VERSION_CODES.S }, CYAN( displayString = R.string.cyan, darkThemeHexColour = R.color.instances_cyan, lightThemeHexColour = R.color.instances_cyan ), MINT( displayString = R.string.mint, darkThemeHexColour = R.color.instances_mint, lightThemeHexColour = R.color.instances_mint ), BLUE( displayString = R.string.blue, darkThemeHexColour = R.color.instances_blue, lightThemeHexColour = R.color.instances_blue ), GREEN( displayString = R.string.green, darkThemeHexColour = R.color.instances_green, lightThemeHexColour = R.color.instances_green ), YELLOW( displayString = R.string.yellow, darkThemeHexColour = R.color.instances_yellow, lightThemeHexColour = R.color.instances_yellow ), BLACK( displayString = R.string.black, darkThemeHexColour = R.color.instances_black, lightThemeHexColour = R.color.instances_black ), WHITE( displayString = R.string.white, darkThemeHexColour = R.color.instances_white, lightThemeHexColour = R.color.instances_white ); open fun isAvailable() = true fun getInstancesColour(isToday: Boolean, widgetTheme: Theme) = when (isToday) { true -> R.color.instances_today else -> when (widgetTheme) { Theme.DARK -> darkThemeHexColour Theme.LIGHT -> lightThemeHexColour } } } fun getAvailableColors() = Colour.values().filter { it.isAvailable() } fun Colour.getDisplayValue(context: Context) = context.getString(this.displayString).replaceFirstChar { it.uppercase() } fun getColourDisplayValues(context: Context) = getAvailableColors() .map { it.getDisplayValue(context) } .toTypedArray()
bsd-3-clause
818277e0e2ed77986a1229568f4c58ca
32.294872
92
0.683096
4.572183
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/util/sorting.kt
1
1727
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.util import java.util.Comparator fun <T> Comparator<in T>.lexicographical(): Comparator<in Iterable<T>> = Comparator { left, right -> // Zipping limits the compared parts to the shorter list, then we perform a component-wise comparison // Short-circuits if any component of the left side is smaller or greater left.zip(right).fold(0) { acc, (a, b) -> if (acc != 0) return@Comparator acc else this.compare(a, b) }.let { // When all the parts are equal, the longer list wins (is greater) if (it == 0) { left.count() - right.count() } else { // Still required if the last part was not equal, the short-circuiting does not cover that it } } } /** * This is the lowest version value we will let users choose, to make our lives easier. */ private val MC_1_8_8 = SemanticVersion.release(1, 8, 8) fun <T> sortVersions(versions: Collection<T>, convert: (T) -> String = {it.toString()}): List<T> { if (versions.isEmpty()) { return listOf() } return versions.asSequence() .map { convert(it) to it } .map { SemanticVersion.parse(it.first) to it.second } .sortedByDescending { it.first } .filter { it.first >= MC_1_8_8 } .map { it.second } .toList() } fun getMajorVersion(version: String): String { val index = version.lastIndexOf('.') return if (index != -1 && index != version.indexOf('.')) { version.substring(0, index) } else { version } }
mit
da5edd60959422dede4281727219fbbe
30.4
116
0.595252
3.803965
false
false
false
false
google/android-fhir
datacapture/src/test/java/com/google/android/fhir/datacapture/QuestionnaireItemReviewAdapterTest.kt
1
3163
/* * 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.android.fhir.datacapture import android.os.Build import com.google.android.fhir.datacapture.validation.Valid import com.google.android.fhir.datacapture.views.QuestionnaireItemViewItem import com.google.common.truth.Truth.assertThat import org.hl7.fhir.r4.model.Questionnaire import org.hl7.fhir.r4.model.QuestionnaireResponse import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [Build.VERSION_CODES.P]) class QuestionnaireItemReviewAdapterTest { @Test fun `submitting empty list to adapter should return itemCount zero`() { val questionnaireItemReviewAdapter = QuestionnaireItemReviewAdapter() questionnaireItemReviewAdapter.submitList(listOf()) assertThat(questionnaireItemReviewAdapter.itemCount).isEqualTo(0) } @Test fun `submitting single items to adapter should return itemCount one`() { val questionnaireItemReviewAdapter = QuestionnaireItemReviewAdapter() questionnaireItemReviewAdapter.submitList( listOf( QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent() .setType(Questionnaire.QuestionnaireItemType.GROUP), QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = Valid, answersChangedCallback = { _, _, _ -> }, ) ) ) assertThat(questionnaireItemReviewAdapter.itemCount).isEqualTo(1) } @Test fun `submitting multiple items to adapter should return itemCount greater than zero`() { val questionnaireItemReviewAdapter = QuestionnaireItemReviewAdapter() questionnaireItemReviewAdapter.submitList( listOf( QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent() .setType(Questionnaire.QuestionnaireItemType.GROUP), QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = Valid, answersChangedCallback = { _, _, _ -> }, ), QuestionnaireItemViewItem( Questionnaire.QuestionnaireItemComponent() .setType(Questionnaire.QuestionnaireItemType.DISPLAY), QuestionnaireResponse.QuestionnaireResponseItemComponent(), validationResult = Valid, answersChangedCallback = { _, _, _ -> }, ) ) ) assertThat(questionnaireItemReviewAdapter.itemCount).isEqualTo(2) assertThat(questionnaireItemReviewAdapter.itemCount).isGreaterThan(0) } }
apache-2.0
e277c0dbc9dde62a7e937b5b1e58f250
36.654762
90
0.741701
5.510453
false
true
false
false
Kerooker/rpg-npc-generator
app/src/test/java/io/kotest/android/SharedPreferences.kt
1
1751
package io.kotest.android import android.content.Context import android.content.SharedPreferences import androidx.test.core.app.ApplicationProvider inline fun <reified T: Any> withSharedPreferences( sharedPreferencesName: String, key: String, value: T, context: Context = ApplicationProvider.getApplicationContext(), mode: Int = Context.MODE_PRIVATE, block: (context: Context) -> Unit ) { val sharedPreferences = context.getSharedPreferences(sharedPreferencesName, mode) val previous = sharedPreferences.getPrevious<T>(key) sharedPreferences.edit().put(key, value).commit() block(context) sharedPreferences.edit().put(key, previous).commit() } inline fun <reified T> SharedPreferences.getPrevious(key: String): T? { return if (contains(key)) { when (T::class) { String::class -> getString(key, null) MutableSet::class -> getStringSet(key, null) Boolean::class -> getBoolean(key, false) Int::class -> getInt(key, 0) Float::class -> getFloat(key, 0f) Long::class -> getLong(key, 0) else -> throw IllegalArgumentException() } as T } else null } inline fun <reified T> SharedPreferences.Editor.put(key: String, value: T?): SharedPreferences.Editor { return if(value == null) remove(key) else { when (value) { is String -> putString(key, value) is MutableSet<*> -> putStringSet(key, value as MutableSet<String>) is Boolean -> putBoolean(key, value) is Int -> putInt(key, value) is Float -> putFloat(key, value) is Long -> putLong(key, value) else -> throw IllegalArgumentException() } } }
apache-2.0
bc76485a7e8d350eb7172d4073ee638e
33.333333
103
0.639063
4.455471
false
false
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/featureStatistics/actions/DumpFeaturesAndTipsAction.kt
3
3285
// 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.featureStatistics.actions import com.intellij.featureStatistics.ProductivityFeaturesRegistry import com.intellij.ide.util.TipAndTrickBean import com.intellij.ide.util.TipUIUtil import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.project.DumbAware import com.intellij.openapi.util.io.FileUtil import com.intellij.util.ResourceUtil import java.awt.datatransfer.StringSelection class DumpFeaturesAndTipsAction : AnAction(), DumbAware { override fun actionPerformed(e: AnActionEvent) { ProductivityFeaturesRegistry.getInstance()?.let { featuresRegistry -> val tips = TipAndTrickBean.EP_NAME.extensionList.associateBy { it.fileName }.toMutableMap() val rows = mutableListOf<FeatureTipRow>() for (featureId in featuresRegistry.featureIds) { val featureTipRow = FeatureTipRow(featureId) featuresRegistry.getFeatureDescriptor(featureId)?.let { feature -> featureTipRow.name = feature.displayName featureTipRow.group = feature.groupId TipUIUtil.getTip(feature)?.let { tip -> featureTipRow.tipFile = tip.fileName featureTipRow.tipFileExists = tipFileExists(tip) tips.remove(tip.fileName) } } rows.add(featureTipRow) } for (tip in tips.values) { rows.add(FeatureTipRow(tipFile = tip.fileName, tipFileExists = tipFileExists(tip))) } val output = StringBuilder() output.appendLine(FeatureTipRow.HEADER) for (row in rows.sortedWith(compareBy(nullsLast()) { it.group })) { output.appendLine(row.toString()) } CopyPasteManager.getInstance().setContents(StringSelection(output.toString())) } } private fun tipFileExists(tip: TipAndTrickBean): Boolean { if (FileUtil.exists(tip.fileName)) return true val tipLoader = tip.pluginDescriptor?.pluginClassLoader ?: DumpFeaturesAndTipsAction::class.java.classLoader return ResourceUtil.getResourceAsStream(tipLoader, "/tips/", tip.fileName) != null } private data class FeatureTipRow(var id: String? = null, var name: String? = null, var group: String? = null, var tipFile: String? = null, var tipFileExists: Boolean = false) { companion object { private const val EMPTY_VALUE = "NONE" private const val FILE_NOT_FOUND = "FILE NOT FOUND" const val HEADER = "Feature ID;Name;Group ID;Tip File;Tip File Problem" } override fun toString(): String = "${handleEmpty(id)};${handleEmpty(name)};${handleEmpty(group)};${handleEmpty(tipFile)};${tipFileProblem()}" private fun handleEmpty(value: String?) = value ?: EMPTY_VALUE private fun tipFileProblem() = if (tipFileExists) "" else FILE_NOT_FOUND } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } }
apache-2.0
ce6b188fb36f573727cddcff53a59dbd
42.813333
140
0.697108
4.74026
false
false
false
false
sanjoydesk/FrameworkBenchmarks
frameworks/Kotlin/hexagon/src/main/kotlin/co/there4/hexagon/BenchmarkStorage.kt
1
2453
package co.there4.hexagon import co.there4.hexagon.repository.MongoIdRepository import co.there4.hexagon.repository.mongoCollection import java.lang.System.getenv import co.there4.hexagon.settings.SettingsManager.setting import co.there4.hexagon.repository.mongoDatabase import kotlin.reflect.KProperty1 internal val FORTUNE_MESSAGES = setOf( "fortune: No such file or directory", "A computer scientist is someone who fixes things that aren't broken.", "After enough decimal places, nobody gives a damn.", "A bad random number generator: 1, 1, 1, 1, 1, 4.33e+67, 1, 1, 1", "A computer program does what you tell it to do, not what you want it to do.", "Emacs is a nice operating system, but I prefer UNIX. — Tom Christaensen", "Any program that runs right is obsolete.", "A list is only as strong as its weakest link. — Donald Knuth", "Feature: A bug with seniority.", "Computers make very fast, very accurate mistakes.", "<script>alert(\"This should not be displayed in a browser alert box.\");</script>", "フレームワークのベンチマーク" ) internal val DB_ROWS = 10000 private val DB_HOST = getenv("DBHOST") ?: "localhost" private val DB = setting<String>("database") ?: "hello_world" private val WORLD: String = setting<String>("worldCollection") ?: "world" private val FORTUNE: String = setting<String>("fortuneCollection") ?: "fortune" private val database = mongoDatabase("mongodb://$DB_HOST/$DB") internal val worldRepository = repository(WORLD, World::_id) internal val fortuneRepository = repository(FORTUNE, Fortune::_id) // TODO Find out why it fails when creating index '_id' with background: true private inline fun <reified T : Any> repository(name: String, key: KProperty1<T, Int>) = MongoIdRepository(T::class, mongoCollection(name, database), key, indexOrder = null) internal fun initialize() { if (fortuneRepository.isEmpty()) { val fortunes = FORTUNE_MESSAGES.mapIndexed { ii, fortune -> Fortune(ii + 1, fortune) } fortuneRepository.insertManyObjects(fortunes) } if (worldRepository.isEmpty()) { val world = (1..DB_ROWS).map { World(it, it) } worldRepository.insertManyObjects(world) } } internal fun findFortunes() = fortuneRepository.findObjects().toList() internal fun findWorld() = worldRepository.find(rnd()) internal fun replaceWorld(newWorld: World) { worldRepository.replaceObject(newWorld) }
bsd-3-clause
bd433201bcc8a197ae16c65fc4f7f26e
39.35
94
0.724081
3.782813
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/ec2/src/main/kotlin/com/kotlin/ec2/DescribeVPCs.kt
1
1749
// snippet-sourcedescription:[DescribeVPCs.kt demonstrates how to get information about all the Amazon Elastic Compute Cloud (Amazon EC2) VPCs.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[Amazon EC2] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.ec2 // snippet-start:[ec2.kotlin.describe_vpc.import] import aws.sdk.kotlin.services.ec2.Ec2Client import aws.sdk.kotlin.services.ec2.model.DescribeVpcsRequest import kotlin.system.exitProcess // snippet-end:[ec2.kotlin.describe_vpc.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: <vpcId> Where: vpcId - A VPC ID that you can obtain from the AWS Management Console (for example, vpc-xxxxxf2f). """ if (args.size != 1) { println(usage) exitProcess(0) } val vpcId = args[0] describeEC2Vpcs(vpcId) } // snippet-start:[ec2.kotlin.describe_vpc.main] suspend fun describeEC2Vpcs(vpcId: String) { val request = DescribeVpcsRequest { vpcIds = listOf(vpcId) } Ec2Client { region = "us-west-2" }.use { ec2 -> val response = ec2.describeVpcs(request) response.vpcs?.forEach { vpc -> println("Found VPC with id ${vpc.vpcId} VPC state ${vpc.state} and tenancy ${vpc.instanceTenancy}") } } } // snippet-end:[ec2.kotlin.describe_vpc.main]
apache-2.0
31045531ab6811a20e9deb3c5a746a66
27.15
144
0.668954
3.584016
false
false
false
false
PokeAPI/pokekotlin
src/test/kotlin/me/sargunvohra/lib/pokekotlin/test/EndpointTest.kt
2
1985
package me.sargunvohra.lib.pokekotlin.test import com.google.gson.Gson import kotlin.collections.HashMap import kotlin.reflect.full.declaredMemberFunctions import kotlin.test.assertEquals import me.sargunvohra.lib.pokekotlin.client.PokeApi import okhttp3.OkHttpClient import okhttp3.Request import org.junit.Test class EndpointTest { private val httpClient = OkHttpClient() private val gson = Gson() @Test fun checkAllEndpoints() { // call the mock API to get a list of resource endpoints val json = httpClient .newCall(Request.Builder() .get() .url(MockServer.url) .build()) .execute() .body()!! .string() // parse the expected resources using the list val expectedSingleResources = gson .fromJson<HashMap<String, String>>(json, HashMap::class.java).keys .map { endpointName -> endpointName.split('-') .joinToString(separator = "") { it.capitalize() } } .toSet() val expectedListResources = expectedSingleResources .map { it + "List" } .toSet() + "PokemonEncounterList" // use reflection to determine the actual resources in the client val actualResources = PokeApi::class .declaredMemberFunctions .map { it.name.removePrefix("get") } .groupBy { it.endsWith("List") } val actualSingleResources = actualResources.getValue(false).toSet() val actualListResources = actualResources.getValue(true).toSet() // make sure the resources in the client match the ones in the API assertEquals(expectedSingleResources.sorted(), actualSingleResources.sorted()) assertEquals(expectedListResources.sorted(), actualListResources.sorted()) } }
apache-2.0
53e82fc51672852d3472bdef371f6c63
32.083333
86
0.60403
5.307487
false
true
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/sponge/color/SpongeColorLineMarkerProvider.kt
1
2380
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.sponge.color import com.demonwav.mcdev.insight.ColorLineMarkerProvider import com.demonwav.mcdev.insight.setColor import com.intellij.codeInsight.daemon.GutterIconNavigationHandler import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.LineMarkerProvider import com.intellij.codeInsight.daemon.NavigateAction import com.intellij.psi.PsiElement import com.intellij.psi.PsiExpressionList import com.intellij.psi.PsiLiteralExpression import com.intellij.psi.PsiNewExpression import com.intellij.psi.impl.source.tree.JavaElementType import com.intellij.psi.util.PsiUtilBase import com.intellij.ui.ColorChooser import java.awt.Color class SpongeColorLineMarkerProvider : LineMarkerProvider { override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? { val pair = element.findColor() ?: return null val info = SpongeColorInfo(element, pair.first, pair.second) NavigateAction.setNavigateAction(info, "Change color", null) return info } override fun collectSlowLineMarkers(elements: List<PsiElement>, result: Collection<LineMarkerInfo<*>>) {} private class SpongeColorInfo( element: PsiElement, color: Color, workElement: PsiElement ) : ColorLineMarkerProvider.ColorInfo( element, color, GutterIconNavigationHandler handler@{ _, _ -> if (!element.isWritable) { return@handler } val editor = PsiUtilBase.findEditor(element) ?: return@handler val c = ColorChooser.chooseColor(editor.component, "Choose Color", color, false) if (c != null) { when (workElement) { is PsiLiteralExpression -> workElement.setColor(c.rgb and 0xFFFFFF) is PsiExpressionList -> workElement.setColor(c.red, c.green, c.blue) is PsiNewExpression -> { val list = workElement.getNode().findChildByType(JavaElementType.EXPRESSION_LIST) as PsiExpressionList? list?.setColor(c.red, c.green, c.blue) } } } } ) }
mit
9b56783592b99eb130344ea546223865
33.492754
109
0.669748
4.877049
false
false
false
false
georocket/georocket
src/main/kotlin/io/georocket/ogcapifeatures/views/xml/LandingPage.kt
1
766
package io.georocket.ogcapifeatures.views.xml import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement import io.georocket.ogcapifeatures.views.Views @JacksonXmlRootElement(namespace = XML_NAMESPACE_CORE) data class LandingPage( @JacksonXmlProperty(localName = "Title", namespace = XML_NAMESPACE_CORE) val title: String, @JacksonXmlProperty(localName = "Description", namespace = XML_NAMESPACE_CORE) val description: String, @JacksonXmlElementWrapper(useWrapping = false) @JacksonXmlProperty(localName = "Link", namespace = XML_NAMESPACE_ATOM) val links: List<Views.Link> )
apache-2.0
6c3bb0013cb7eb31c066a0d47ea57e2d
39.315789
80
0.815927
4.27933
false
false
false
false
outbrain/ob1k
ob1k-crud/src/main/java/com/outbrain/ob1k/crud/model/Model.kt
1
575
package com.outbrain.ob1k.crud.model class Model(total: Int = 0, data: List<EntityDescription> = emptyList()) : Entities<EntityDescription>(total, data) { fun <T> withEntity(type: Class<T>) = withEntity(type.toDescription(total)) fun withEntity(it: EntityDescription) = Model(total + 1, data + it) operator fun invoke(resourceName: String) = data.find { resourceName == it.resourceName } operator fun invoke(resourceName: String, fieldName: String) = this(resourceName)?.invoke(fieldName) fun getByTable(table: String) = data.find { table == it.table } }
apache-2.0
6bf9e12740a37882ec5b189d7d89aba5
63
117
0.725217
3.75817
false
false
false
false
deso88/TinyGit
src/main/kotlin/hamburg/remme/tinygit/domain/service/CommitDetailsService.kt
1
1641
package hamburg.remme.tinygit.domain.service import hamburg.remme.tinygit.Refreshable import hamburg.remme.tinygit.Service import hamburg.remme.tinygit.domain.Commit import hamburg.remme.tinygit.domain.File import hamburg.remme.tinygit.domain.Repository import hamburg.remme.tinygit.execute import hamburg.remme.tinygit.git.gitDiffTree import hamburg.remme.tinygit.observableList import javafx.beans.property.SimpleStringProperty import javafx.concurrent.Task @Service class CommitDetailsService(service: CommitLogService) : Refreshable { val commitStatus = observableList<File>() val commitDetails = SimpleStringProperty() private val detailsRenderer = DetailsRenderer() private lateinit var repository: Repository private var task: Task<*>? = null init { service.activeCommit.addListener { _, _, it -> update(it) } } override fun onRefresh(repository: Repository) { this.repository = repository } override fun onRepositoryChanged(repository: Repository) { this.repository = repository } override fun onRepositoryDeselected() { task?.cancel() commitDetails.set("") commitStatus.clear() } private fun update(commit: Commit?) { task?.cancel() commit?.let { task = object : Task<List<File>>() { override fun call() = gitDiffTree(repository, it) override fun succeeded() { commitDetails.set(detailsRenderer.render(it)) commitStatus.setAll(value) } }.execute() } ?: commitStatus.clear() } }
bsd-3-clause
b6461284fa6cf991d535551aaa5826d6
28.836364
69
0.674589
4.742775
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/StorageIndexes.kt
2
13581
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl import com.google.common.collect.HashBiMap import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.external.ExternalEntityMappingImpl import com.intellij.workspaceModel.storage.impl.external.MutableExternalEntityMappingImpl import com.intellij.workspaceModel.storage.impl.indices.EntityStorageInternalIndex import com.intellij.workspaceModel.storage.impl.indices.MultimapStorageIndex import com.intellij.workspaceModel.storage.impl.indices.PersistentIdInternalIndex import com.intellij.workspaceModel.storage.impl.indices.VirtualFileIndex import com.intellij.workspaceModel.storage.impl.indices.VirtualFileIndex.MutableVirtualFileIndex.Companion.VIRTUAL_FILE_INDEX_ENTITY_SOURCE_PROPERTY internal open class StorageIndexes( // List of IDs of entities that use this particular persistent id internal open val softLinks: MultimapStorageIndex, internal open val virtualFileIndex: VirtualFileIndex, internal open val entitySourceIndex: EntityStorageInternalIndex<EntitySource>, internal open val persistentIdIndex: PersistentIdInternalIndex, internal open val externalMappings: Map<String, ExternalEntityMappingImpl<*>> ) { constructor(softLinks: MultimapStorageIndex, virtualFileIndex: VirtualFileIndex, entitySourceIndex: EntityStorageInternalIndex<EntitySource>, persistentIdIndex: PersistentIdInternalIndex ) : this(softLinks, virtualFileIndex, entitySourceIndex, persistentIdIndex, emptyMap()) companion object { val EMPTY = StorageIndexes(MultimapStorageIndex(), VirtualFileIndex(), EntityStorageInternalIndex(false), PersistentIdInternalIndex(), HashMap()) } fun toMutable(): MutableStorageIndexes { val copiedSoftLinks = MultimapStorageIndex.MutableMultimapStorageIndex.from(softLinks) val copiedVirtualFileIndex = VirtualFileIndex.MutableVirtualFileIndex.from(virtualFileIndex) val copiedEntitySourceIndex = EntityStorageInternalIndex.MutableEntityStorageInternalIndex.from(entitySourceIndex) val copiedPersistentIdIndex = PersistentIdInternalIndex.MutablePersistentIdInternalIndex.from(persistentIdIndex) val copiedExternalMappings = MutableExternalEntityMappingImpl.fromMap(externalMappings) return MutableStorageIndexes(copiedSoftLinks, copiedVirtualFileIndex, copiedEntitySourceIndex, copiedPersistentIdIndex, copiedExternalMappings) } fun assertConsistency(storage: AbstractEntityStorage) { assertEntitySourceIndex(storage) assertPersistentIdIndex(storage) // TODO Should we get this back? // assertSoftLinksIndex(storage) virtualFileIndex.assertConsistency() // Assert external mappings for ((_, mappings) in externalMappings) { for ((id, _) in mappings.index) { assert(storage.entityDataById(id) != null) { "Missing entity by id: $id" } } } } /* private fun assertSoftLinksIndex(storage: AbstractEntityStorage) { // XXX skipped size check storage.entitiesByType.entityFamilies.forEachIndexed { i, family -> if (family == null) return@forEachIndexed if (family.entities.firstOrNull { it != null } !is SoftLinkable) return@forEachIndexed var mutableId = createEntityId(0, i) family.entities.forEach { data -> if (data == null) return@forEach mutableId = mutableId.copy(arrayId = data.id) val expectedLinks = softLinks.getEntriesById(mutableId) if (data is ModuleEntityData) { assertModuleSoftLinks(data, expectedLinks) } else { val actualLinks = (data as SoftLinkable).getLinks() assert(expectedLinks.size == actualLinks.size) { "Different sizes: $expectedLinks, $actualLinks" } assert(expectedLinks.all { it in actualLinks }) { "Different sets: $expectedLinks, $actualLinks" } } } } } */ // XXX: Hack to speed up module links assertion /* private fun assertModuleSoftLinks(entityData: ModuleEntityData, expectedLinks: Set<PersistentEntityId<*>>) { val actualRefs = HashSet<Any>(entityData.dependencies.size) entityData.dependencies.forEach { dependency -> when (dependency) { is ModuleDependencyItem.Exportable.ModuleDependency -> { assert(dependency.module in expectedLinks) actualRefs += dependency.module } is ModuleDependencyItem.Exportable.LibraryDependency -> { assert(dependency.library in expectedLinks) actualRefs += dependency.library } else -> Unit } } assert(actualRefs.size == expectedLinks.size) } */ private fun assertPersistentIdIndex(storage: AbstractEntityStorage) { var expectedSize = 0 storage.entitiesByType.entityFamilies.forEachIndexed { i, family -> if (family == null) return@forEachIndexed if (family.entities.firstOrNull { it != null }?.persistentId() == null) return@forEachIndexed var mutableId = createEntityId(0, i) family.entities.forEach { data -> if (data == null) return@forEach mutableId = mutableId.copy(arrayId = data.id) val expectedPersistentId = persistentIdIndex.getEntryById(mutableId) assert(expectedPersistentId == data.persistentId()) { "Entity $data isn't found in persistent id index. PersistentId: ${data.persistentId()}, Id: $mutableId. Expected entity source: $expectedPersistentId" } expectedSize++ } } assert(expectedSize == persistentIdIndex.index.size) { "Incorrect size of persistent id index. Expected: $expectedSize, actual: ${persistentIdIndex.index.size}" } } private fun assertEntitySourceIndex(storage: AbstractEntityStorage) { var expectedSize = 0 storage.entitiesByType.entityFamilies.forEachIndexed { i, family -> if (family == null) return@forEachIndexed // Optimization to skip useless conversion of classes var mutableId = createEntityId(0, i) family.entities.forEach { data -> if (data == null) return@forEach mutableId = mutableId.copy(arrayId = data.id) val expectedEntitySource = entitySourceIndex.getEntryById(mutableId) assert(expectedEntitySource == data.entitySource) { "Entity $data isn't found in entity source index. Entity source: ${data.entitySource}, Id: $mutableId. Expected entity source: $expectedEntitySource" } expectedSize++ } } assert(expectedSize == entitySourceIndex.index.size) { "Incorrect size of entity source index. Expected: $expectedSize, actual: ${entitySourceIndex.index.size}" } } } internal class MutableStorageIndexes( override val softLinks: MultimapStorageIndex.MutableMultimapStorageIndex, override val virtualFileIndex: VirtualFileIndex.MutableVirtualFileIndex, override val entitySourceIndex: EntityStorageInternalIndex.MutableEntityStorageInternalIndex<EntitySource>, override val persistentIdIndex: PersistentIdInternalIndex.MutablePersistentIdInternalIndex, override val externalMappings: MutableMap<String, MutableExternalEntityMappingImpl<*>> ) : StorageIndexes(softLinks, virtualFileIndex, entitySourceIndex, persistentIdIndex, externalMappings) { fun <T : WorkspaceEntity> entityAdded(entityData: WorkspaceEntityData<T>) { val pid = entityData.createEntityId() // Update soft links index if (entityData is SoftLinkable) { entityData.index(softLinks) } val entitySource = entityData.entitySource entitySourceIndex.index(pid, entitySource) entityData.persistentId()?.let { persistentId -> persistentIdIndex.index(pid, persistentId) } entitySource.virtualFileUrl?.let { virtualFileIndex.index(pid, VIRTUAL_FILE_INDEX_ENTITY_SOURCE_PROPERTY, it) } } fun entityRemoved(entityId: EntityId) { entitySourceIndex.index(entityId) persistentIdIndex.index(entityId) virtualFileIndex.removeRecordsByEntityId(entityId) externalMappings.values.forEach { it.remove(entityId) } } fun updateSoftLinksIndex(softLinkable: SoftLinkable) { softLinkable.index(softLinks) } fun removeFromSoftLinksIndex(softLinkable: SoftLinkable) { val pid = (softLinkable as WorkspaceEntityData<*>).createEntityId() for (link in softLinkable.getLinks()) { softLinks.remove(pid, link) } } fun updateIndices(oldEntityId: EntityId, newEntityData: WorkspaceEntityData<*>, builder: AbstractEntityStorage) { val newEntityId = newEntityData.createEntityId() virtualFileIndex.updateIndex(oldEntityId, newEntityId, builder.indexes.virtualFileIndex) entitySourceIndex.index(newEntityId, newEntityData.entitySource) builder.indexes.persistentIdIndex.getEntryById(oldEntityId)?.also { persistentIdIndex.index(newEntityId, it) } } fun <T : WorkspaceEntity> simpleUpdateSoftReferences(copiedData: WorkspaceEntityData<T>, modifiableEntity: ModifiableWorkspaceEntityBase<*>?) { val pid = copiedData.createEntityId() if (copiedData is SoftLinkable) { // if (modifiableEntity is ModifiableModuleEntity && !modifiableEntity.dependencyChanged) return // if (modifiableEntity is ModifiableModuleEntity) return copiedData.updateLinksIndex(this.softLinks.getEntriesById(pid), this.softLinks) } } fun applyExternalMappingChanges(diff: MutableEntityStorageImpl, replaceMap: HashBiMap<NotThisEntityId, ThisEntityId>, target: MutableEntityStorageImpl) { diff.indexes.externalMappings.keys.asSequence().filterNot { it in externalMappings.keys }.forEach { externalMappings[it] = MutableExternalEntityMappingImpl<Any>() } diff.indexes.externalMappings.forEach { (identifier, index) -> val mapping = externalMappings[identifier] if (mapping != null) { mapping.applyChanges(index, replaceMap, target) if (mapping.index.isEmpty()) { externalMappings.remove(identifier) } } } } @Suppress("UNCHECKED_CAST") fun updateExternalMappingForEntityId(replaceWithEntityId: EntityId, targetEntityId: EntityId, replaceWithIndexes: StorageIndexes) { replaceWithIndexes.externalMappings.forEach { (mappingId, mapping) -> val data = mapping.index[replaceWithEntityId] ?: return@forEach val externalMapping = externalMappings[mappingId] if (externalMapping == null) { val newMapping = MutableExternalEntityMappingImpl<Any>() newMapping.add(targetEntityId, data) externalMappings[mappingId] = newMapping } else { externalMapping as MutableExternalEntityMappingImpl<Any> externalMapping.add(targetEntityId, data) } } } fun <T : WorkspaceEntity> updatePersistentIdIndexes(builder: MutableEntityStorageImpl, updatedEntity: WorkspaceEntity, beforePersistentId: PersistentEntityId<*>?, copiedData: WorkspaceEntityData<T>, modifiableEntity: ModifiableWorkspaceEntityBase<*>? = null) { val entityId = (updatedEntity as WorkspaceEntityBase).id if (updatedEntity is WorkspaceEntityWithPersistentId) { val newPersistentId = updatedEntity.persistentId if (beforePersistentId != null && beforePersistentId != newPersistentId) { persistentIdIndex.index(entityId, newPersistentId) updateComposedIds(builder, beforePersistentId, newPersistentId) } } simpleUpdateSoftReferences(copiedData, modifiableEntity) } private fun updateComposedIds(builder: MutableEntityStorageImpl, beforePersistentId: PersistentEntityId<*>, newPersistentId: PersistentEntityId<*>) { val idsWithSoftRef = HashSet(this.softLinks.getIdsByEntry(beforePersistentId)) for (entityId in idsWithSoftRef) { val originalEntityData = builder.getOriginalEntityData(entityId) as WorkspaceEntityData<WorkspaceEntity> val originalParentsData = builder.getOriginalParents(entityId.asChild()) val entity = builder.entitiesByType.getEntityDataForModification(entityId) as WorkspaceEntityData<WorkspaceEntity> val editingBeforePersistentId = entity.persistentId() (entity as SoftLinkable).updateLink(beforePersistentId, newPersistentId) // Add an entry to changelog builder.changeLog.addReplaceEvent(entityId, entity, originalEntityData, originalParentsData, emptyList(), emptySet(), emptyMap()) // TODO :: Avoid updating of all soft links for the dependent entity builder.indexes.updatePersistentIdIndexes(builder, entity.createEntity(builder), editingBeforePersistentId, entity) } } fun removeExternalMapping(identifier: String) { externalMappings[identifier]?.clearMapping() } fun toImmutable(): StorageIndexes { val copiedLinks = this.softLinks.toImmutable() val newVirtualFileIndex = virtualFileIndex.toImmutable() val newEntitySourceIndex = entitySourceIndex.toImmutable() val newPersistentIdIndex = persistentIdIndex.toImmutable() val newExternalMappings = MutableExternalEntityMappingImpl.toImmutable(externalMappings) return StorageIndexes(copiedLinks, newVirtualFileIndex, newEntitySourceIndex, newPersistentIdIndex, newExternalMappings) } }
apache-2.0
096ff87d68bbb57eeb026ca17c907705
45.831034
214
0.733746
5.538744
false
false
false
false
JetBrains/intellij-community
plugins/settings-sync/src/com/intellij/settingsSync/SettingsSynchronizer.kt
1
5873
package com.intellij.settingsSync import com.intellij.ide.ApplicationInitializedListener import com.intellij.openapi.application.ApplicationActivationListener import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.IdeFrame import com.intellij.settingsSync.migration.SettingsRepositoryToSettingsSyncMigration import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.concurrency.annotations.RequiresEdt import kotlinx.coroutines.CoroutineScope import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit internal class SettingsSynchronizer : ApplicationInitializedListener, ApplicationActivationListener, SettingsSyncEnabledStateListener, SettingsSyncCategoriesChangeListener { private val executorService = AppExecutorUtil.createBoundedScheduledExecutorService("Settings Sync Update", 1) private val autoSyncDelay get() = Registry.intValue("settingsSync.autoSync.frequency.sec", 60).toLong() private var scheduledFuture: ScheduledFuture<*>? = null // accessed only from the EDT override suspend fun execute(asyncScope: CoroutineScope) { if (ApplicationManager.getApplication().isHeadlessEnvironment || !isSettingsSyncEnabledByKey()) { return } SettingsSyncEvents.getInstance().addEnabledStateChangeListener(this) if (isSettingsSyncEnabledInSettings()) { executorService.schedule(initializeSyncing(SettingsSyncBridge.InitMode.JustInit), 0, TimeUnit.SECONDS) return } if (!SettingsSyncSettings.getInstance().migrationFromOldStorageChecked) { SettingsSyncSettings.getInstance().migrationFromOldStorageChecked = true val migration = MIGRATION_EP.extensionList.firstOrNull { it.isLocalDataAvailable(PathManager.getConfigDir()) } if (migration != null) { LOG.info("Found migration from an old storage via ${migration.javaClass.simpleName}") executorService.schedule(initializeSyncing(SettingsSyncBridge.InitMode.MigrateFromOldStorage(migration)), 0, TimeUnit.SECONDS) SettingsSyncSettings.getInstance().syncEnabled = true SettingsSyncEventsStatistics.MIGRATED_FROM_OLD_PLUGIN.log() } else { SettingsRepositoryToSettingsSyncMigration.migrateIfNeeded(executorService) } } } override fun applicationActivated(ideFrame: IdeFrame) { if (!isSettingsSyncEnabledByKey() || !isSettingsSyncEnabledInSettings() || !SettingsSyncMain.isAvailable()) { return } if (autoSyncDelay > 0 && scheduledFuture == null) { scheduledFuture = setupSyncingByTimer() } if (Registry.`is`("settingsSync.autoSync.on.focus", true)) { scheduleSyncingOnAppFocus() } } override fun applicationDeactivated(ideFrame: IdeFrame) { stopSyncingByTimer() } private fun initializeSyncing(initMode: SettingsSyncBridge.InitMode): Runnable = Runnable { LOG.info("Initializing settings sync") val settingsSyncMain = SettingsSyncMain.getInstance() settingsSyncMain.controls.bridge.initialize(initMode) SettingsSyncEvents.getInstance().addCategoriesChangeListener(this) syncSettings() } override fun enabledStateChanged(syncEnabled: Boolean) { if (syncEnabled) { SettingsSyncEvents.getInstance().addCategoriesChangeListener(this) // actual start of the sync is handled inside SettingsSyncEnabler } else { SettingsSyncEvents.getInstance().removeCategoriesChangeListener(this) stopSyncingByTimer() SettingsSyncMain.getInstance().disableSyncing() } } override fun categoriesStateChanged() { SettingsSyncEvents.getInstance().fireSettingsChanged(SyncSettingsEvent.LogCurrentSettings) } private fun scheduleSyncingOnAppFocus() { executorService.schedule(Runnable { LOG.debug("Syncing settings on app focus") syncSettings() }, 0, TimeUnit.SECONDS) } @RequiresEdt private fun setupSyncingByTimer(): ScheduledFuture<*> { val delay = autoSyncDelay return executorService.scheduleWithFixedDelay(Runnable { LOG.debug("Syncing settings by timer") syncSettings() }, delay, delay, TimeUnit.SECONDS) } private fun syncSettings() { val syncControls = SettingsSyncMain.getInstance().controls syncSettings(syncControls.remoteCommunicator, syncControls.updateChecker) } @RequiresEdt private fun stopSyncingByTimer() { if (scheduledFuture != null) { scheduledFuture!!.cancel(true) scheduledFuture = null } } companion object { private val LOG = logger<SettingsSynchronizer>() private val MIGRATION_EP = ExtensionPointName.create<SettingsSyncMigration>("com.intellij.settingsSyncMigration") @RequiresBackgroundThread internal fun syncSettings(remoteCommunicator: SettingsSyncRemoteCommunicator, updateChecker: SettingsSyncUpdateChecker) { when (remoteCommunicator.checkServerState()) { is ServerState.UpdateNeeded -> { LOG.info("Updating from server") updateChecker.scheduleUpdateFromServer() // the push will happen automatically after updating and merging (if there is anything to merge) } ServerState.FileNotExists -> { LOG.info("No file on server") } ServerState.UpToDate -> { LOG.debug("Updating settings is not needed, will check if push is needed") SettingsSyncEvents.getInstance().fireSettingsChanged(SyncSettingsEvent.PingRequest) } is ServerState.Error -> { // error already logged in checkServerState, we schedule update } } } } }
apache-2.0
ea5a5b7c534fd20dca42c9f87ffad8be
38.16
173
0.756002
5.443003
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceNotNullAssertionWithElvisReturnInspection.kt
1
4437
// 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.inspections import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.getParentLambdaLabelName import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypes import org.jetbrains.kotlin.psi.psiUtil.getTopmostParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.isNullable import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class ReplaceNotNullAssertionWithElvisReturnInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = postfixExpressionVisitor(fun(postfix) { if (postfix.baseExpression == null) return val operationReference = postfix.operationReference if (operationReference.getReferencedNameElementType() != KtTokens.EXCLEXCL) return if ((postfix.getTopmostParentOfType<KtParenthesizedExpression>() ?: postfix).parent is KtReturnExpression) return val parent = postfix.getParentOfTypes(true, KtLambdaExpression::class.java, KtNamedFunction::class.java) if (parent !is KtNamedFunction && parent !is KtLambdaExpression) return val context = postfix.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) val (isNullable, returnLabelName) = when (parent) { is KtNamedFunction -> { val returnType = parent.descriptor(context)?.returnType ?: return val isNullable = returnType.isNullable() if (!returnType.isUnit() && !isNullable) return isNullable to null } is KtLambdaExpression -> { val functionLiteral = parent.functionLiteral val returnType = functionLiteral.descriptor(context)?.returnType ?: return if (!returnType.isUnit()) return val lambdaLabelName = functionLiteral.bodyBlockExpression?.getParentLambdaLabelName() ?: return false to lambdaLabelName } else -> return } if (context.diagnostics.forElement(operationReference).any { it.factory == Errors.UNNECESSARY_NOT_NULL_ASSERTION }) return holder.registerProblem( postfix.operationReference, KotlinBundle.message("replace.with.return"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, ReplaceWithElvisReturnFix(isNullable, returnLabelName) ) }) private fun KtFunction.descriptor(context: BindingContext): FunctionDescriptor? { return context[BindingContext.DECLARATION_TO_DESCRIPTOR, this] as? FunctionDescriptor } private class ReplaceWithElvisReturnFix( private val returnNull: Boolean, private val returnLabelName: String? ) : LocalQuickFix, LowPriorityAction { override fun getName() = KotlinBundle.message("replace.with.elvis.return.fix.text", if (returnNull) " null" else "") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val postfix = descriptor.psiElement.parent as? KtPostfixExpression ?: return val base = postfix.baseExpression ?: return val psiFactory = KtPsiFactory(project) postfix.replaced( psiFactory.createExpressionByPattern( "$0 ?: return$1$2", base, returnLabelName?.let { "@$it" } ?: "", if (returnNull) " null" else "" ) ) } } }
apache-2.0
9f5853deb640dad2a6d6291229b71c54
48.311111
130
0.711742
5.391252
false
false
false
false
JetBrains/intellij-community
plugins/git4idea/src/git4idea/index/vfs/GitIndexVirtualFileBaseContentProvider.kt
1
1613
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.index.vfs import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.history.VcsRevisionNumber import com.intellij.openapi.vcs.impl.VcsBaseContentProvider import com.intellij.openapi.vcs.impl.LineStatusTrackerBaseContentUtil import com.intellij.openapi.vfs.VirtualFile import git4idea.GitContentRevision import git4idea.GitRevisionNumber import git4idea.index.* import git4idea.repo.GitRepositoryManager class GitIndexVirtualFileBaseContentProvider(private val project: Project) : VcsBaseContentProvider { override fun isSupported(file: VirtualFile): Boolean = file is GitIndexVirtualFile override fun getBaseRevision(file: VirtualFile): VcsBaseContentProvider.BaseContent? { val indexFile = file as? GitIndexVirtualFile ?: return null val status = GitStageTracker.getInstance(project).status(indexFile) ?: return null if (!status.has(ContentVersion.HEAD)) return null val headPath = status.path(ContentVersion.HEAD) val currentRevisionNumber = currentRevisionNumber(indexFile.root) ?: return null return LineStatusTrackerBaseContentUtil.createBaseContent(project, GitContentRevision.createRevision(headPath, currentRevisionNumber, project)) } private fun currentRevisionNumber(root: VirtualFile): VcsRevisionNumber? { val currentRevision = GitRepositoryManager.getInstance(project).getRepositoryForRootQuick(root)?.currentRevision return currentRevision?.let { GitRevisionNumber(it) } } }
apache-2.0
bcc56b6a348ca0dc4a6d6eaebeb051af
47.909091
147
0.819591
4.963077
false
false
false
false
JetBrains/intellij-community
java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaInheritorsCodeVisionProvider.kt
1
3169
// 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 com.intellij.codeInsight.daemon.impl import com.intellij.codeInsight.codeVision.CodeVisionRelativeOrdering import com.intellij.codeInsight.hints.codeVision.InheritorsCodeVisionProvider import com.intellij.java.JavaBundle import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.editor.Editor import com.intellij.pom.java.LanguageLevel import com.intellij.psi.* import com.intellij.psi.util.PsiUtil import java.awt.event.MouseEvent class JavaInheritorsCodeVisionProvider : InheritorsCodeVisionProvider() { companion object { const val ID = "java.inheritors" } override fun acceptsFile(file: PsiFile): Boolean = file.language == JavaLanguage.INSTANCE override fun acceptsElement(element: PsiElement): Boolean = element is PsiClass && element !is PsiTypeParameter || element is PsiMethod override fun getHint(element: PsiElement, file: PsiFile): String? { if (element is PsiClass && element !is PsiTypeParameter) { val inheritors = JavaTelescope.collectInheritingClasses(element) if (inheritors > 0) { val isInterface: Boolean = element.isInterface return if (isInterface) JavaBundle.message("code.vision.implementations.hint", inheritors) else JavaBundle.message("code.vision.inheritors.hint", inheritors) } } else if (element is PsiMethod) { val overrides = JavaTelescope.collectOverridingMethods(element) if (overrides > 0) { val isAbstractMethod = isAbstractMethod(element) return if (isAbstractMethod) JavaBundle.message("code.vision.implementations.hint", overrides) else JavaBundle.message("code.vision.overrides.hint", overrides) } } return null } override fun logClickToFUS(element: PsiElement, hint: String) { val location = if (element is PsiClass) JavaCodeVisionUsageCollector.CLASS_LOCATION else JavaCodeVisionUsageCollector.METHOD_LOCATION JavaCodeVisionUsageCollector.IMPLEMENTATION_CLICKED_EVENT_ID.log(element.project, location) } override fun handleClick(editor: Editor, element: PsiElement, event: MouseEvent?) { val markerType = if (element is PsiClass) MarkerType.SUBCLASSED_CLASS else MarkerType.OVERRIDDEN_METHOD val navigationHandler = markerType.navigationHandler if (element is PsiNameIdentifierOwner) { navigationHandler.navigate(event, element.nameIdentifier) } } override val relativeOrderings: List<CodeVisionRelativeOrdering> get() = emptyList() override val id: String get() = ID private fun isAbstractMethod(method: PsiMethod): Boolean { if (method.hasModifierProperty(PsiModifier.ABSTRACT)) { return true } val aClass = method.containingClass return aClass != null && aClass.isInterface && !isDefaultMethod(aClass, method) } private fun isDefaultMethod(aClass: PsiClass, method: PsiMethod): Boolean { return method.hasModifierProperty(PsiModifier.DEFAULT) && PsiUtil.getLanguageLevel(aClass).isAtLeast(LanguageLevel.JDK_1_8) } }
apache-2.0
1f2c2049754c080b63bec5ae11b65bb5
41.837838
158
0.757337
4.722802
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/ui/layout/migLayout/componentConstraints.kt
2
3615
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.layout.migLayout import com.intellij.openapi.actionSystem.ActionToolbar import com.intellij.openapi.ui.ComponentWithBrowseButton import com.intellij.ui.SeparatorComponent import com.intellij.ui.layout.* import com.intellij.util.ui.JBUI import net.miginfocom.layout.BoundSize import net.miginfocom.layout.CC import net.miginfocom.layout.ConstraintParser import java.awt.Component import javax.swing.* import javax.swing.text.JTextComponent internal fun overrideFlags(cc: CC, flags: Array<out CCFlags>) { for (flag in flags) { when (flag) { //CCFlags.wrap -> isWrap = true CCFlags.grow -> cc.grow() CCFlags.growX -> { cc.growX(1000f) } CCFlags.growY -> cc.growY(1000f) // If you have more than one component in a cell the alignment keywords will not work since the behavior would be indeterministic. // You can however accomplish the same thing by setting a gap before and/or after the components. // That gap may have a minimum size of 0 and a preferred size of a really large value to create a "pushing" gap. // There is even a keyword for this: "push". So "gapleft push" will be the same as "align right" and work for multi-component cells as well. //CCFlags.right -> horizontal.gapBefore = BoundSize(null, null, null, true, null) CCFlags.push -> cc.push() CCFlags.pushX -> cc.pushX() CCFlags.pushY -> cc.pushY() } } } internal class DefaultComponentConstraintCreator(private val spacing: SpacingConfiguration) { private val shortTextSizeSpec = ConstraintParser.parseBoundSize("${spacing.shortTextWidth}px!", false, true) private val mediumTextSizeSpec = ConstraintParser.parseBoundSize("${spacing.shortTextWidth}px::${spacing.maxShortTextWidth}px", false, true) val vertical1pxGap: BoundSize = ConstraintParser.parseBoundSize("${JBUI.scale(1)}px!", true, false) val horizontalUnitSizeGap = gapToBoundSize(spacing.unitSize, true) fun addGrowIfNeeded(cc: CC, component: Component, spacing: SpacingConfiguration) { when { component is ComponentWithBrowseButton<*> -> { // yes, no max width. approved by UI team (all path fields stretched to the width of the window) cc.minWidth("${spacing.maxShortTextWidth}px") cc.growX() } component is JTextField && component.columns != 0 -> return component is JTextComponent || component is SeparatorComponent || component is ComponentWithBrowseButton<*> -> { cc.growX() //.pushX() } component is JScrollPane || component.isPanelWithToolbar() -> { // no need to use pushX - default pushX for cell is 100. avoid to configure more than need cc.grow() .pushY() } component is JScrollPane -> { val view = component.viewport.view if (view is JTextArea && view.rows == 0) { // set min size to 2 lines (yes, for some reasons it means that rows should be set to 3) view.rows = 3 } } } } fun applyGrowPolicy(cc: CC, growPolicy: GrowPolicy) { cc.horizontal.size = when (growPolicy) { GrowPolicy.SHORT_TEXT -> shortTextSizeSpec GrowPolicy.MEDIUM_TEXT -> mediumTextSizeSpec } } } private fun Component.isPanelWithToolbar(): Boolean { return this is JPanel && componentCount == 1 && (getComponent(0) as? JComponent)?.getClientProperty(ActionToolbar.ACTION_TOOLBAR_PROPERTY_KEY) != null }
apache-2.0
913aa153139d80c7027508051bb44798
39.177778
146
0.696819
4.318996
false
false
false
false
square/okio
okio/src/commonMain/kotlin/okio/-Util.kt
1
7118
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okio import okio.internal.HEX_DIGIT_CHARS import kotlin.native.concurrent.SharedImmutable internal fun checkOffsetAndCount(size: Long, offset: Long, byteCount: Long) { if (offset or byteCount < 0 || offset > size || size - offset < byteCount) { throw ArrayIndexOutOfBoundsException("size=$size offset=$offset byteCount=$byteCount") } } /* ktlint-disable no-multi-spaces indent */ internal fun Short.reverseBytes(): Short { val i = toInt() and 0xffff val reversed = (i and 0xff00 ushr 8) or (i and 0x00ff shl 8) return reversed.toShort() } internal fun Int.reverseBytes(): Int { return (this and -0x1000000 ushr 24) or (this and 0x00ff0000 ushr 8) or (this and 0x0000ff00 shl 8) or (this and 0x000000ff shl 24) } internal fun Long.reverseBytes(): Long { return (this and -0x100000000000000L ushr 56) or (this and 0x00ff000000000000L ushr 40) or (this and 0x0000ff0000000000L ushr 24) or (this and 0x000000ff00000000L ushr 8) or (this and 0x00000000ff000000L shl 8) or (this and 0x0000000000ff0000L shl 24) or (this and 0x000000000000ff00L shl 40) or (this and 0x00000000000000ffL shl 56) } /* ktlint-enable no-multi-spaces indent */ internal inline infix fun Int.leftRotate(bitCount: Int): Int { return (this shl bitCount) or (this ushr (32 - bitCount)) } internal inline infix fun Long.rightRotate(bitCount: Int): Long { return (this ushr bitCount) or (this shl (64 - bitCount)) } @Suppress("NOTHING_TO_INLINE") // Syntactic sugar. internal inline infix fun Byte.shr(other: Int): Int = toInt() shr other @Suppress("NOTHING_TO_INLINE") // Syntactic sugar. internal inline infix fun Byte.shl(other: Int): Int = toInt() shl other @Suppress("NOTHING_TO_INLINE") // Syntactic sugar. internal inline infix fun Byte.and(other: Int): Int = toInt() and other @Suppress("NOTHING_TO_INLINE") // Syntactic sugar. internal inline infix fun Byte.and(other: Long): Long = toLong() and other @Suppress("NOTHING_TO_INLINE") // Pending `kotlin.experimental.xor` becoming stable internal inline infix fun Byte.xor(other: Byte): Byte = (toInt() xor other.toInt()).toByte() @Suppress("NOTHING_TO_INLINE") // Syntactic sugar. internal inline infix fun Int.and(other: Long): Long = toLong() and other @Suppress("NOTHING_TO_INLINE") // Syntactic sugar. internal inline fun minOf(a: Long, b: Int): Long = minOf(a, b.toLong()) @Suppress("NOTHING_TO_INLINE") // Syntactic sugar. internal inline fun minOf(a: Int, b: Long): Long = minOf(a.toLong(), b) internal fun arrayRangeEquals( a: ByteArray, aOffset: Int, b: ByteArray, bOffset: Int, byteCount: Int ): Boolean { for (i in 0 until byteCount) { if (a[i + aOffset] != b[i + bOffset]) return false } return true } internal fun Byte.toHexString(): String { val result = CharArray(2) result[0] = HEX_DIGIT_CHARS[this shr 4 and 0xf] result[1] = HEX_DIGIT_CHARS[this and 0xf] // ktlint-disable no-multi-spaces return result.concatToString() } internal fun Int.toHexString(): String { if (this == 0) return "0" // Required as code below does not handle 0 val result = CharArray(8) result[0] = HEX_DIGIT_CHARS[this shr 28 and 0xf] result[1] = HEX_DIGIT_CHARS[this shr 24 and 0xf] result[2] = HEX_DIGIT_CHARS[this shr 20 and 0xf] result[3] = HEX_DIGIT_CHARS[this shr 16 and 0xf] result[4] = HEX_DIGIT_CHARS[this shr 12 and 0xf] result[5] = HEX_DIGIT_CHARS[this shr 8 and 0xf] // ktlint-disable no-multi-spaces result[6] = HEX_DIGIT_CHARS[this shr 4 and 0xf] // ktlint-disable no-multi-spaces result[7] = HEX_DIGIT_CHARS[this and 0xf] // ktlint-disable no-multi-spaces // Find the first non-zero index var i = 0 while (i < result.size) { if (result[i] != '0') break i++ } return result.concatToString(i, result.size) } internal fun Long.toHexString(): String { if (this == 0L) return "0" // Required as code below does not handle 0 val result = CharArray(16) result[ 0] = HEX_DIGIT_CHARS[(this shr 60 and 0xf).toInt()] // ktlint-disable no-multi-spaces result[ 1] = HEX_DIGIT_CHARS[(this shr 56 and 0xf).toInt()] // ktlint-disable no-multi-spaces result[ 2] = HEX_DIGIT_CHARS[(this shr 52 and 0xf).toInt()] // ktlint-disable no-multi-spaces result[ 3] = HEX_DIGIT_CHARS[(this shr 48 and 0xf).toInt()] // ktlint-disable no-multi-spaces result[ 4] = HEX_DIGIT_CHARS[(this shr 44 and 0xf).toInt()] // ktlint-disable no-multi-spaces result[ 5] = HEX_DIGIT_CHARS[(this shr 40 and 0xf).toInt()] // ktlint-disable no-multi-spaces result[ 6] = HEX_DIGIT_CHARS[(this shr 36 and 0xf).toInt()] // ktlint-disable no-multi-spaces result[ 7] = HEX_DIGIT_CHARS[(this shr 32 and 0xf).toInt()] // ktlint-disable no-multi-spaces result[ 8] = HEX_DIGIT_CHARS[(this shr 28 and 0xf).toInt()] // ktlint-disable no-multi-spaces result[ 9] = HEX_DIGIT_CHARS[(this shr 24 and 0xf).toInt()] // ktlint-disable no-multi-spaces result[10] = HEX_DIGIT_CHARS[(this shr 20 and 0xf).toInt()] result[11] = HEX_DIGIT_CHARS[(this shr 16 and 0xf).toInt()] result[12] = HEX_DIGIT_CHARS[(this shr 12 and 0xf).toInt()] result[13] = HEX_DIGIT_CHARS[(this shr 8 and 0xf).toInt()] // ktlint-disable no-multi-spaces result[14] = HEX_DIGIT_CHARS[(this shr 4 and 0xf).toInt()] // ktlint-disable no-multi-spaces result[15] = HEX_DIGIT_CHARS[(this and 0xf).toInt()] // ktlint-disable no-multi-spaces // Find the first non-zero index var i = 0 while (i < result.size) { if (result[i] != '0') break i++ } return result.concatToString(i, result.size) } // Work around a problem where Kotlin/JS IR can't handle default parameters on expect functions // that depend on the receiver. We use well-known, otherwise-impossible values here and must check // for them in the receiving function, then swap in the true default value. // https://youtrack.jetbrains.com/issue/KT-45542 @SharedImmutable internal val DEFAULT__new_UnsafeCursor = Buffer.UnsafeCursor() internal fun resolveDefaultParameter(unsafeCursor: Buffer.UnsafeCursor): Buffer.UnsafeCursor { if (unsafeCursor === DEFAULT__new_UnsafeCursor) return Buffer.UnsafeCursor() return unsafeCursor } internal val DEFAULT__ByteString_size = -1234567890 internal fun ByteString.resolveDefaultParameter(position: Int): Int { if (position == DEFAULT__ByteString_size) return size return position } internal fun ByteArray.resolveDefaultParameter(sizeParam: Int): Int { if (sizeParam == DEFAULT__ByteString_size) return size return sizeParam }
apache-2.0
8fcbbb92d3d35acd271552351a03d116
37.684783
98
0.707081
3.478983
false
false
false
false
Kotlin/kotlinx.coroutines
ui/kotlinx-coroutines-android/android-unit-tests/test/ordered/tests/FirstRobolectricTest.kt
1
1619
/* * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package ordered.tests import kotlinx.coroutines.* import kotlinx.coroutines.test.* import org.junit.Test import org.junit.runner.* import org.robolectric.* import org.robolectric.annotation.* import org.robolectric.shadows.* import kotlin.test.* @RunWith(RobolectricTestRunner::class) @Config(manifest = Config.NONE, sdk = [28]) @LooperMode(LooperMode.Mode.LEGACY) open class FirstRobolectricTest { @Test fun testComponent() { // Note that main is not set at all val component = TestComponent() checkComponent(component) } @Test fun testComponentAfterReset() { // Note that main is not set at all val component = TestComponent() Dispatchers.setMain(Dispatchers.Unconfined) Dispatchers.resetMain() checkComponent(component) } @Test fun testDelay() { val component = TestComponent() val mainLooper = ShadowLooper.getShadowMainLooper() mainLooper.pause() component.launchDelayed() mainLooper.runToNextTask() assertFalse(component.delayedLaunchCompleted) mainLooper.runToNextTask() assertTrue(component.delayedLaunchCompleted) } private fun checkComponent(component: TestComponent) { val mainLooper = ShadowLooper.getShadowMainLooper() mainLooper.pause() component.launchSomething() assertFalse(component.launchCompleted) mainLooper.unPause() assertTrue(component.launchCompleted) } }
apache-2.0
700f9cd2da45609ff2f065783665f149
27.910714
102
0.691785
4.747801
false
true
false
false
VREMSoftwareDevelopment/WiFiAnalyzer
app/src/test/kotlin/com/vrem/wifianalyzer/wifi/band/WiFiChannelCountryTest.kt
1
5084
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.vrem.wifianalyzer.wifi.band import com.vrem.wifianalyzer.wifi.band.WiFiChannelCountry.Companion.find import org.junit.After import org.junit.Assert.* import org.junit.Before import org.junit.Test import java.util.* class WiFiChannelCountryTest { private val currentLocale: Locale = Locale.getDefault() @Before fun setUp() { Locale.setDefault(Locale.US) } @After fun tearDown() { Locale.setDefault(currentLocale) } @Test fun testChannelAvailableWithTrue() { assertTrue(find(Locale.US.country).channelAvailableGHZ2(1)) assertTrue(find(Locale.US.country).channelAvailableGHZ2(11)) assertTrue(find(Locale.US.country).channelAvailableGHZ5(36)) assertTrue(find(Locale.US.country).channelAvailableGHZ5(165)) assertTrue(find(Locale.UK.country).channelAvailableGHZ2(1)) assertTrue(find(Locale.UK.country).channelAvailableGHZ2(13)) assertTrue(find(Locale.UK.country).channelAvailableGHZ5(36)) assertTrue(find(Locale.UK.country).channelAvailableGHZ5(140)) } @Test fun testChannelAvailableWithGHZ2() { assertFalse(find(Locale.US.country).channelAvailableGHZ2(0)) assertFalse(find(Locale.US.country).channelAvailableGHZ2(12)) assertFalse(find(Locale.UK.country).channelAvailableGHZ2(0)) assertFalse(find(Locale.UK.country).channelAvailableGHZ2(14)) } @Test fun testChannelAvailableWithGHZ5() { assertTrue(find(Locale.US.country).channelAvailableGHZ5(36)) assertTrue(find(Locale.US.country).channelAvailableGHZ5(165)) assertTrue(find(Locale.UK.country).channelAvailableGHZ5(36)) assertTrue(find(Locale.UK.country).channelAvailableGHZ5(140)) assertTrue(find("AE").channelAvailableGHZ5(36)) assertTrue(find("AE").channelAvailableGHZ5(64)) } @Test fun testChannelAvailableWithGHZ6() { assertTrue(find(Locale.US.country).channelAvailableGHZ6(1)) assertTrue(find(Locale.US.country).channelAvailableGHZ6(93)) assertTrue(find(Locale.UK.country).channelAvailableGHZ6(1)) assertTrue(find(Locale.UK.country).channelAvailableGHZ6(93)) assertTrue(find("AE").channelAvailableGHZ6(1)) assertTrue(find("AE").channelAvailableGHZ6(93)) } @Test fun testFindCorrectlyPopulatesGHZ() { // setup val expectedCountryCode = Locale.US.country val expectedGHZ2: Set<Int> = WiFiChannelCountryGHZ2().findChannels(expectedCountryCode) val expectedGHZ5: Set<Int> = WiFiChannelCountryGHZ5().findChannels(expectedCountryCode) val expectedGHZ6: Set<Int> = WiFiChannelCountryGHZ6().findChannels(expectedCountryCode) // execute val actual: WiFiChannelCountry = find(expectedCountryCode) // validate assertEquals(expectedCountryCode, actual.countryCode()) assertArrayEquals(expectedGHZ2.toTypedArray(), actual.channelsGHZ2().toTypedArray()) assertArrayEquals(expectedGHZ5.toTypedArray(), actual.channelsGHZ5().toTypedArray()) assertArrayEquals(expectedGHZ6.toTypedArray(), actual.channelsGHZ6().toTypedArray()) } @Test fun testFindCorrectlyPopulatesCountryCodeAndName() { // setup val expected = Locale.SIMPLIFIED_CHINESE val expectedCountryCode = expected.country // execute val actual: WiFiChannelCountry = find(expectedCountryCode) // validate assertEquals(expectedCountryCode, actual.countryCode()) assertNotEquals(expected.displayCountry, actual.countryName(expected)) assertEquals(expected.getDisplayCountry(expected), actual.countryName(expected)) } @Test fun testCountryName() { // setup val fixture = WiFiChannelCountry(Locale.US) val expected = "United States" // execute & validate val actual = fixture.countryName(Locale.US) // execute & validate assertEquals(expected, actual) } @Test fun testCountryNameUnknown() { // setup val fixture = WiFiChannelCountry(Locale("XYZ")) val expected = "-Unknown" // execute & validate val actual = fixture.countryName(Locale.US) // execute & validate assertEquals(expected, actual) } }
gpl-3.0
3075e745080083087358967c864bfc95
37.522727
95
0.704563
4.638686
false
true
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-data/src/main/kotlin/slatekit/data/sql/vendors/Sqlite.kt
1
2854
package slatekit.data.sql.vendors import slatekit.common.data.DataType import slatekit.data.Mapper import slatekit.data.core.Meta import slatekit.data.core.Table import slatekit.data.encoders.* import slatekit.data.sql.* object SqliteDialect : Dialect(encodeChar = '"') { } /** * Sqlite based dialect, this has limited data types * see: https://www.sqlite.org/datatype3.html * 1. null * 2. integer * 3. real * 4. text * 5. blob * * ENUM * enum -> int * * Dates * local date -> int * local time -> int * local datetime -> long epoch millis * zoned datetime -> long epoch millis * * UUIDS * uuid -> string * upid -> string */ open class SqliteProvider<TId, T>(val meta: Meta<TId, T>, val mapper: Mapper<TId, T>) : Provider<TId, T> where TId: kotlin.Comparable<TId>, T: Any { override val dialect: Dialect = SqliteDialect /** * The insert statement can be */ override val insert = Insert<TId, T>(SqliteDialect, meta, mapper) override val update = Update<TId, T>(SqliteDialect, meta, mapper) override fun select(table: Table): slatekit.query.Select = Builders.Select(dialect, meta.table.name, { name -> mapper.datatype(name)}, { name -> mapper.column(name) }) override fun delete(table: Table): slatekit.query.Delete = Builders.Delete(dialect, meta.table.name, { name -> mapper.datatype(name)}, { name -> mapper.column(name) }) override fun patch (table: Table): slatekit.query.Update = Builders.Patch(dialect, meta.table.name, { name -> mapper.datatype(name)}, { name -> mapper.column(name) }) } /** * Stores all the encoders for all supported data types * This converts the following: * * short -> int * long -> real * float -> real * local date -> int * local time -> int * local datetime -> long epoch millis * zoned datetime -> long epoch millis */ open class SqliteEncoders<TId, T>(utc:Boolean) : Encoders<TId, T>(utc) where TId: kotlin.Comparable<TId>, T:Any { override val bools = BoolEncoder(DataType.DTInt) override val shorts = ShortEncoder(DataType.DTInt) override val ints = IntEncoder(DataType.DTLong) override val localDates = LocalDateEncoder(DataType.DTInt) override val localTimes = LocalTimeEncoder(DataType.DTInt) override val localDateTimes = LocalDateTimeEncoder(DataType.DTLong) override val zonedDateTimes = ZonedDateTimeEncoder(DataType.DTLong, utc) override val dateTimes = DateTimeEncoder(DataType.DTLong, utc) override val instants = InstantEncoder(DataType.DTLong) override val enums = EnumEncoder(DataType.DTInt) } fun String.sqliteIfNotExists(table:String):String { return this.replace("\"$table\"", "IF NOT EXISTS \"$table\"") }
apache-2.0
530514ef68c8b380cb417c4bf82175dc
34.675
171
0.662579
3.914952
false
false
false
false
Raizlabs/DBFlow
lib/src/main/kotlin/com/dbflow5/query/BaseModelQueriable.kt
1
4338
package com.dbflow5.query import android.os.Handler import com.dbflow5.adapter.RetrievalAdapter import com.dbflow5.adapter.queriable.ListModelLoader import com.dbflow5.adapter.queriable.SingleModelLoader import com.dbflow5.config.FlowLog import com.dbflow5.config.FlowManager import com.dbflow5.config.retrievalAdapter import com.dbflow5.database.DatabaseWrapper import com.dbflow5.query.list.FlowCursorList import com.dbflow5.query.list.FlowQueryList import com.dbflow5.sql.Query /** * Description: Provides a base implementation of [ModelQueriable] to simplify a lot of code. It provides the * default implementation for convenience. */ abstract class BaseModelQueriable<TModel : Any> /** * Constructs new instance of this class and is meant for subclasses only. * * @param table the table that belongs to this query. */ protected constructor(table: Class<TModel>) : BaseQueriable<TModel>(table), ModelQueriable<TModel>, Query { private val retrievalAdapter: RetrievalAdapter<TModel> by lazy { FlowManager.getRetrievalAdapter(table) } private var cachingEnabled = true private var _cacheListModelLoader: ListModelLoader<TModel>? = null protected val listModelLoader: ListModelLoader<TModel> get() = if (cachingEnabled) { retrievalAdapter.listModelLoader } else { retrievalAdapter.nonCacheableListModelLoader } protected val singleModelLoader: SingleModelLoader<TModel> get() = if (cachingEnabled) { retrievalAdapter.singleModelLoader } else { retrievalAdapter.nonCacheableSingleModelLoader } override fun disableCaching() = apply { cachingEnabled = false } override fun queryList(databaseWrapper: DatabaseWrapper): MutableList<TModel> { val query = query FlowLog.log(FlowLog.Level.V, "Executing query: $query") return listModelLoader.load(databaseWrapper, query)!! } override fun querySingle(databaseWrapper: DatabaseWrapper): TModel? { val query = query FlowLog.log(FlowLog.Level.V, "Executing query: $query") return singleModelLoader.load(databaseWrapper, query) } override fun cursorList(databaseWrapper: DatabaseWrapper): FlowCursorList<TModel> = FlowCursorList.Builder(modelQueriable = this, databaseWrapper = databaseWrapper).build() override fun flowQueryList(databaseWrapper: DatabaseWrapper): FlowQueryList<TModel> = FlowQueryList.Builder(modelQueriable = this, databaseWrapper = databaseWrapper).build() override fun executeUpdateDelete(databaseWrapper: DatabaseWrapper): Long = compileStatement(databaseWrapper).use { it.executeUpdateDelete() } override fun <QueryClass : Any> queryCustomList(queryModelClass: Class<QueryClass>, databaseWrapper: DatabaseWrapper) : MutableList<QueryClass> { val query = query FlowLog.log(FlowLog.Level.V, "Executing query: $query") return getListQueryModelLoader(queryModelClass).load(databaseWrapper, query)!! } override fun <QueryClass : Any> queryCustomSingle(queryModelClass: Class<QueryClass>, databaseWrapper: DatabaseWrapper) : QueryClass? { val query = query FlowLog.log(FlowLog.Level.V, "Executing query: $query") return getSingleQueryModelLoader(queryModelClass).load(databaseWrapper, query) } protected fun <T : Any> getListQueryModelLoader(table: Class<T>): ListModelLoader<T> = if (cachingEnabled) { table.retrievalAdapter.listModelLoader } else { table.retrievalAdapter.nonCacheableListModelLoader } protected fun <T : Any> getSingleQueryModelLoader(table: Class<T>): SingleModelLoader<T> = if (cachingEnabled) { table.retrievalAdapter.singleModelLoader } else { table.retrievalAdapter.nonCacheableSingleModelLoader } } /** * Constructs a flowQueryList allowing a custom [Handler]. */ fun <T : Any> ModelQueriable<T>.flowQueryList(databaseWrapper: DatabaseWrapper, refreshHandler: Handler) = FlowQueryList.Builder(modelQueriable = this, databaseWrapper = databaseWrapper, refreshHandler = refreshHandler).build()
mit
785333fe006d2b45260ccab6a389fc58
38.798165
109
0.710235
5.067757
false
false
false
false
mpcjanssen/simpletask-android
app/src/main/java/nl/mpcjanssen/simpletask/task/TodoList.kt
1
14514
package nl.mpcjanssen.simpletask.task import android.app.Activity import android.content.Intent import android.os.CountDownTimer import android.os.SystemClock import android.util.Log import nl.mpcjanssen.simpletask.* import nl.mpcjanssen.simpletask.remote.FileStore import nl.mpcjanssen.simpletask.remote.IFileStore import nl.mpcjanssen.simpletask.util.* import java.io.File import java.util.* import java.util.concurrent.CopyOnWriteArrayList import kotlin.collections.ArrayList /** * Implementation of the in memory representation of the Todo list * uses an ActionQueue to ensure modifications and access of the underlying todo list are * sequential. If this is not done properly the result is a likely ConcurrentModificationException. * @author Mark Janssen */ class TodoList(val config: Config) { private var timer: CountDownTimer? = null private var mLists: MutableList<String>? = null private var mTags: MutableList<String>? = null private var todoItems = emptyList<Task>().toMutableList() val pendingEdits = HashSet<Task>() internal val tag = TodoList::class.java.simpleName init { config.todoList?.let { todoItems.addAll(it.asSequence()) } } fun add(items: List<Task>, atEnd: Boolean) { Log.d(tag, "Add task ${items.size} atEnd: $atEnd") val updatedItems = items.map { item -> Interpreter.onAddCallback(item) ?: item } if (atEnd) { todoItems.addAll(updatedItems) } else { todoItems.addAll(0, updatedItems) } } fun add(t: Task, atEnd: Boolean) { add(listOf(t), atEnd) } fun removeAll(tasks: List<Task>) { Log.d(tag, "Remove") pendingEdits.removeAll(tasks) todoItems.removeAll(tasks) } fun size(): Int { return todoItems.size } val priorities: ArrayList<Priority> get() { val res = HashSet<Priority>() todoItems.forEach { res.add(it.priority) } val ret = ArrayList(res) ret.sort() return ret } val contexts: List<String> get() { val lists = mLists if (lists != null) { return lists } val res = HashSet<String>() todoItems.forEach { t -> t.lists?.let {res.addAll(it)} } val newLists = res.toMutableList() mLists = newLists return newLists } val projects: List<String> get() { val tags = mTags if (tags != null) { return tags } val res = HashSet<String>() todoItems.forEach { t -> t.tags?.let {res.addAll(it)} } val newTags = res.toMutableList() mTags = newTags return newTags } fun uncomplete(items: List<Task>) { Log.d(tag, "Uncomplete") items.forEach { it.markIncomplete() } } fun complete(tasks: List<Task>, keepPrio: Boolean, extraAtEnd: Boolean) { Log.d(tag, "Complete") for (task in tasks) { val extra = task.markComplete(todayAsString) if (extra != null) { if (extraAtEnd) { todoItems.add(extra) } else { todoItems.add(0, extra) } } if (!keepPrio) { task.priority = Priority.NONE } } } fun prioritize(tasks: List<Task>, prio: Priority) { Log.d(tag, "Complete") tasks.map { it.priority = prio } } fun defer(deferString: String, tasks: List<Task>, dateType: DateType) { Log.d(tag, "Defer") tasks.forEach { when (dateType) { DateType.DUE -> it.deferDueDate(deferString, todayAsString) DateType.THRESHOLD -> it.deferThresholdDate(deferString, todayAsString) } } } fun update(org: Collection<Task>, updated: List<Task>, addAtEnd: Boolean) { val smallestSize = org.zip(updated) { orgTask, updatedTask -> val idx = todoItems.indexOf(orgTask) if (idx != -1) { updatedTask.id = orgTask.id todoItems[idx] = updatedTask } else { todoItems.add(updatedTask) } 1 }.size removeAll(org.toMutableList().drop(smallestSize)) add(updated.toMutableList().drop(smallestSize), addAtEnd) } val selectedTasks: List<Task> get() { return todoItems.toList().filter { it.selected } } val fileFormat : String = todoItems.toList().joinToString(separator = "\n", transform = { it.inFileFormat(config.useUUIDs) }) fun notifyTasklistChanged(todoFile: File, save: Boolean, refreshMainUI: Boolean = true, forceKeepSelection: Boolean = false) { Log.d(tag, "Notified changed") if (save) { save(FileStore, todoFile, eol = config.eol) } if (selectedTasks.isEmpty()) { broadcastRefreshSelection(TodoApplication.app.localBroadCastManager) } else if (!config.hasKeepSelection && !forceKeepSelection) { clearSelection() } mLists = null mTags = null if (refreshMainUI) { broadcastTasklistChanged(TodoApplication.app.localBroadCastManager) } else { broadcastRefreshWidgets(TodoApplication.app.localBroadCastManager) } } private fun startAddTaskActivity(act: Activity, prefill: String) { Log.d(tag, "Start add/edit task activity") val intent = Intent(act, AddTask::class.java) intent.putExtra(Constants.EXTRA_PREFILL_TEXT, prefill) act.startActivity(intent) } fun getMultiComparator(filter: Query, caseSensitive: Boolean): MultiComparator { val sorts = filter.getSort(config.defaultSorts) return MultiComparator(sorts, TodoApplication.app.today, caseSensitive, filter.createIsThreshold, filter.luaModule) } fun getSortedTasks(filter: Query, caseSensitive: Boolean): Pair<List<Task>, Int> { Log.d(tag, "Getting sorted and filtered tasks") val start = SystemClock.elapsedRealtime() val comp = getMultiComparator(filter, caseSensitive) val listCopy = todoItems.toList() val taskCount = listCopy.size val itemsToSort = if (comp.fileOrder) { listCopy } else { listCopy.reversed() } val sortedItems = itemsToSort.sortedWith(comp.comparator) val result = filter.applyFilter(sortedItems, showSelected = true) val end = SystemClock.elapsedRealtime() Log.d(tag, "Sorting and filtering tasks took ${end - start} ms") return Pair(result, taskCount) } fun reload(reason: String = "") { FileStoreActionQueue.add("Reload") { Log.d(tag, "Reload: $reason") val todoFile = config.todoFile if (config.changesPending && FileStore.isOnline) { Log.i(tag, "Not loading, changes pending") Log.i(tag, "Saving instead of loading") save(FileStore, todoFile, eol = config.eol) } else { reloadaction(todoFile) } } } private fun reloadaction(file: File) { Log.d(tag, "Executing reloadaction") broadcastFileSyncStart(TodoApplication.app.localBroadCastManager) val needSync = FileStore.needSync(file) if (needSync) { Log.i(tag, "Remote version is different, sync") try { val items = FileStore.loadTasksFromFile(file) val newTodoItems = items.map { Task(it) }.toMutableList() synchronized(todoItems) { Log.d(tag, "Fill todolist with ${items.size} items") todoItems = newTodoItems config.todoList = todoItems.toList() } // Update cache // Backup FileStoreActionQueue.add("Backup") { Backupper.backup(file, items) } notifyTasklistChanged(file, save = false, refreshMainUI = true) } catch (e: Exception) { Log.e(tag, "TodoList load failed: ${file.path}", e) showToastShort(TodoApplication.app, "Loading of todo file failed") } Log.i(tag, "TodoList loaded from filestore") } else { Log.i(tag, "Remote version is same, load from cache") } broadcastFileSyncDone(TodoApplication.app.localBroadCastManager) } private fun save(fileStore: IFileStore, todoFile: File, eol: String) { Log.d(tag, "Save: ${todoFile.path}") config.changesPending = true broadcastUpdateStateIndicator(TodoApplication.app.localBroadCastManager) val lines = todoItems.toList().let { config.todoList = it it.map { it.inFileFormat(config.useUUIDs) } } // Update cache FileStoreActionQueue.add("Backup") { Backupper.backup(todoFile, lines) } runOnMainThread { timer?.apply { cancel() } val saveAction = { FileStoreActionQueue.add("Save") { broadcastFileSyncStart(TodoApplication.app.localBroadCastManager) try { Log.i(tag, "Saving todo list, size ${lines.size}") val newFile = fileStore.saveTasksToFile(todoFile, lines, eol = eol).canonicalPath if (config.changesPending) { // Remove the red bar config.changesPending = false broadcastUpdateStateIndicator(TodoApplication.app.localBroadCastManager) } if (newFile != todoFile.canonicalPath) { // The file was written under another name // Usually this means the was a conflict. Log.i(tag, "Filename was changed remotely. New name is: $newFile") showToastLong(TodoApplication.app, "Filename was changed remotely. New name is: $newFile") TodoApplication.app.switchTodoFile(File(newFile)) } } catch (e: Exception) { Log.e(tag, "TodoList save to ${todoFile.path} failed", e) config.changesPending = true if (fileStore.isOnline) { showToastShort(TodoApplication.app, "Saving of todo file failed") } } broadcastFileSyncDone(TodoApplication.app.localBroadCastManager) } } val idleSeconds = TodoApplication.config.idleBeforeSaveSeconds timer = object : CountDownTimer(idleSeconds * 1000L, 1000) { override fun onFinish() { Log.d(tag, "Executing pending Save") saveAction() } override fun onTick(p0: Long) { Log.d(tag, "Scheduled save in $p0") } }.start() } } fun archive(todoFile: File, doneFile: File, tasks: List<Task>, eol: String) { Log.d(tag, "Archive ${tasks.size} tasks") FileStoreActionQueue.add("Append to file") { broadcastFileSyncStart(TodoApplication.app.localBroadCastManager) try { FileStore.appendTaskToFile(doneFile, tasks.map {it.inFileFormat(useUUIDs = TodoApplication.config.useUUIDs)}, eol) removeAll(tasks) notifyTasklistChanged(todoFile, save = true, refreshMainUI = true) } catch (e: Exception) { Log.e(tag, "Task archiving failed", e) showToastShort(TodoApplication.app, "Task archiving failed") } broadcastFileSyncDone(TodoApplication.app.localBroadCastManager) } } fun moveAbove(other: Task, itemToMove: Task) { val oldIndex = todoItems.indexOf(itemToMove) todoItems.removeAt(oldIndex) val newIndex = todoItems.indexOf(other) todoItems.add(newIndex, itemToMove) } fun moveBelow(other: Task, itemToMove: Task) { val oldIndex = todoItems.indexOf(itemToMove) todoItems.removeAt(oldIndex) val newIndex = todoItems.indexOf(other) + 1 todoItems.add(newIndex, itemToMove) } fun isSelected(item: Task): Boolean = item.selected fun numSelected(): Int { return todoItems.toList().count { it.selected } } fun selectTasks(items: List<Task>) { Log.d(tag, "Select") items.forEach { selectTask(it) } broadcastRefreshSelection(TodoApplication.app.localBroadCastManager) } private fun selectTask(item: Task?) { item?.selected = true } private fun unSelectTask(item: Task) { item.selected = false } fun unSelectTasks(items: List<Task>) { Log.d(tag, "Unselect") items.forEach { unSelectTask(it) } broadcastRefreshSelection(TodoApplication.app.localBroadCastManager) } fun clearSelection() { Log.d(tag, "Clear selection") todoItems.iterator().forEach { it.selected = false } broadcastRefreshSelection(TodoApplication.app.localBroadCastManager) } fun getTaskIndex(t: Task): Int { return todoItems.indexOf(t) } fun getTaskAt(idx: Int): Task? { return todoItems.getOrNull(idx) } fun getTaskWithId(id: String): Task? { return todoItems.find { it.id == id } } fun each (callback : (Task) -> Unit) { todoItems.forEach { callback.invoke(it) } } fun editTasks(from: Activity, tasks: List<Task>, prefill: String) { Log.d(tag, "Edit tasks") pendingEdits.addAll(tasks) startAddTaskActivity(from, prefill) } fun clearPendingEdits() { Log.d(tag, "Clear selection") pendingEdits.clear() } }
gpl-3.0
29057eedbf465334891d4094bb910726
30.620915
130
0.568003
4.743137
false
false
false
false
anthonycr/Bonsai
library/src/main/java/com/anthonycr/bonsai/Maybe.kt
1
9384
/* * Copyright (C) 2017 Anthony C. Restaino * <p/> * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.anthonycr.bonsai /** * A Reactive Streams Kotlin implementation of a publisher that might emit an item, or a completion * event, or an exception. One of these events is guaranteed to emitted by this observable. This * class allows work to be done on a certain thread and then allows the item to be emitted on a * different thread. * * It allows the caller of this class to create a single task that could emit a single item or * complete, or emit an error. * * @param [T] the type that the [Maybe] will emit. */ class Maybe<T> private constructor(private val onSubscribe: (Subscriber<T>) -> Unit) { companion object { /** * Creates a [Maybe] that doesn't emit an item. */ @JvmStatic fun <R> empty() = Maybe<R>({ it.onComplete() }) /** * Creates a [Maybe] that emits the provided item. */ @JvmStatic fun <R> just(value: R) = Maybe<R>({ it.onSuccess(value) }) /** * Creates a [Maybe] that lazily executes the block and emits the value returned by it, or a * completion event if no item was returned. */ @JvmStatic fun <R> defer(block: () -> R?) = Maybe<R>({ subscriber -> block()?.let { subscriber.onSuccess(it) } ?: subscriber.onComplete() }) /** * Creates a [Maybe] that requires the creator to manually notify of item emission, * completion, or error events. If fine grained control over the emission lifecycle is not * needed, [defer] offers a less error prone way to create a similar [Maybe]. */ @JvmStatic fun <R> create(block: (Subscriber<R>) -> Unit) = Maybe(block) @JvmStatic private fun <R> performSubscribe(subscriptionScheduler: Scheduler, observationScheduler: Scheduler, onSubscribe: (Subscriber<R>) -> Unit, onSuccess: (R) -> Unit, onComplete: () -> Unit, onError: (Throwable) -> Unit): Subscription { val composingSubscriber = ComposingSubscriber(onSuccess, onComplete, onError) val schedulingSubscriber = SchedulingSubscriber(observationScheduler, composingSubscriber) subscriptionScheduler.execute { try { onSubscribe(schedulingSubscriber) } catch (exception: Exception) { if (exception is ReactiveEventException) { throw exception } else { if (schedulingSubscriber.isUnsubscribed()) { throw ReactiveEventException("Exception thrown after unsubscribe", exception) } else { schedulingSubscriber.onError(exception) } } } } return schedulingSubscriber } } interface Subscriber<in T> { fun onSuccess(t: T) fun onComplete() fun onError(throwable: Throwable) } private class ComposingSubscriber<in T>(private val onSuccess: (T) -> Unit, private val onComplete: () -> Unit, private val onError: (Throwable) -> Unit) : Subscriber<T> { override fun onSuccess(t: T) = onSuccess.invoke(t) override fun onComplete() = onComplete.invoke() override fun onError(throwable: Throwable) = onError.invoke(throwable) } private class SchedulingSubscriber<in T>(private val scheduler: Scheduler, private var composingSubscriber: ComposingSubscriber<T>?) : Subscriber<T>, Subscription { private var onSuccessExecuted = false private var onCompleteExecuted = false private var onErrorExecuted = false override fun unsubscribe() { composingSubscriber = null } override fun isUnsubscribed() = composingSubscriber == null override fun onSuccess(t: T) = scheduler.execute { requireCondition(!onSuccessExecuted) { "onSuccess must not be called multiple times" } requireCondition(!onErrorExecuted) { "onSuccess must not be called after onError" } requireCondition(!onCompleteExecuted) { "onSuccess must not be called after onComplete" } onSuccessExecuted = true composingSubscriber?.onSuccess(t) unsubscribe() } override fun onComplete() = scheduler.execute { requireCondition(!onCompleteExecuted) { "onComplete must not be called multiple times" } requireCondition(!onErrorExecuted) { "onComplete must not be called after onError" } requireCondition(!onSuccessExecuted) { "onComplete must not be called after onSuccess" } onCompleteExecuted = true composingSubscriber?.onComplete() unsubscribe() } override fun onError(throwable: Throwable) = scheduler.execute { requireCondition(!onErrorExecuted) { "onError must not be called multiple times" } requireCondition(!onSuccessExecuted) { "onError must not be called after onSuccess" } requireCondition(!onCompleteExecuted) { "onError must not be called after onComplete" } onErrorExecuted = true composingSubscriber?.onError(throwable) unsubscribe() } } private var subscriptionScheduler = Schedulers.immediate() private var observationScheduler = Schedulers.immediate() /** * Causes the [Maybe] to perform work on the provided [Scheduler]. If no [Scheduler] is * provided, then the work is performed synchronously. */ fun subscribeOn(scheduler: Scheduler): Maybe<T> { subscriptionScheduler = scheduler return this } /** * Causes the [Maybe] to run emission events on the provided [Scheduler]. If no [Scheduler] is * provided, then the events are emitted on the [Scheduler] provided by [subscribeOn]. */ fun observeOn(scheduler: Scheduler): Maybe<T> { observationScheduler = scheduler return this } /** * Maps from the current [Maybe] of type [T] to a new [Maybe] of type [R]. * * @param [R] the type to be emitted by the new [Maybe]. */ fun <R> map(map: (T) -> R): Maybe<R> { return create<R>({ newOnSubscribe -> performSubscribe( Schedulers.immediate(), Schedulers.immediate(), onSubscribe, onSuccess = { newOnSubscribe.onSuccess(map(it)) }, onComplete = { newOnSubscribe.onComplete() }, onError = { newOnSubscribe.onError(it) } ) }).subscribeOn(subscriptionScheduler) .observeOn(observationScheduler) } /** * Filters the [Maybe] using the filter provided to this function. */ fun filter(predicate: (T) -> Boolean): Maybe<T> { return Maybe.create<T> { newOnSubscribe -> performSubscribe( Schedulers.immediate(), Schedulers.immediate(), onSubscribe, onSuccess = { item -> if (predicate(item)) { newOnSubscribe.onSuccess(item) } else { newOnSubscribe.onComplete() } }, onComplete = { newOnSubscribe.onComplete() }, onError = { newOnSubscribe.onError(it) } ) }.subscribeOn(subscriptionScheduler) .observeOn(observationScheduler) } /** * Subscribes the consumer to receive next, completion, and error events. If no [onError] is * provided and an error is emitted, then an exception is thrown. */ @JvmOverloads fun subscribe(onSuccess: (T) -> Unit = {}, onComplete: () -> Unit = {}, onError: (Throwable) -> Unit = { throw ReactiveEventException("No error handler supplied", it) }) = performSubscribe(subscriptionScheduler, observationScheduler, onSubscribe, onSuccess, onComplete, onError) }
apache-2.0
3653afa08effffdafe79186a08e21f16
39.804348
134
0.587702
5.313703
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/service/GHPRDetailsServiceImpl.kt
8
5679
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.data.service import com.intellij.collaboration.async.CompletableFutureUtil.submitIOTask import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import org.jetbrains.plugins.github.api.GHGQLRequests import org.jetbrains.plugins.github.api.GHRepositoryCoordinates import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.GithubApiRequests import org.jetbrains.plugins.github.api.data.GHLabel import org.jetbrains.plugins.github.api.data.GHUser import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequest import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestRequestedReviewer import org.jetbrains.plugins.github.api.data.pullrequest.GHTeam import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.pullrequest.GHNotFoundException import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier import org.jetbrains.plugins.github.pullrequest.data.service.GHServiceUtil.logError import org.jetbrains.plugins.github.util.CollectionDelta import java.util.concurrent.CompletableFuture class GHPRDetailsServiceImpl(private val progressManager: ProgressManager, private val requestExecutor: GithubApiRequestExecutor, private val repository: GHRepositoryCoordinates) : GHPRDetailsService { private val serverPath = repository.serverPath private val repoPath = repository.repositoryPath override fun loadDetails(progressIndicator: ProgressIndicator, pullRequestId: GHPRIdentifier): CompletableFuture<GHPullRequest> = progressManager.submitIOTask(progressIndicator) { requestExecutor.execute(it, GHGQLRequests.PullRequest.findOne(repository, pullRequestId.number)) ?: throw GHNotFoundException("Pull request ${pullRequestId.number} does not exist") }.logError(LOG, "Error occurred while loading PR details") override fun updateDetails(indicator: ProgressIndicator, pullRequestId: GHPRIdentifier, title: String?, description: String?) : CompletableFuture<GHPullRequest> = progressManager.submitIOTask(indicator) { requestExecutor.execute(it, GHGQLRequests.PullRequest.update(repository, pullRequestId.id, title, description)) }.logError(LOG, "Error occurred while loading PR details") override fun adjustReviewers(indicator: ProgressIndicator, pullRequestId: GHPRIdentifier, delta: CollectionDelta<GHPullRequestRequestedReviewer>) = progressManager.submitIOTask(indicator) { it.text = GithubBundle.message("pull.request.details.adjusting.reviewers") val removedItems = delta.removedItems if (removedItems.isNotEmpty()) { it.text2 = GithubBundle.message("pull.request.removing.reviewers") requestExecutor.execute(it, GithubApiRequests.Repos.PullRequests.Reviewers .remove(serverPath, repoPath.owner, repoPath.repository, pullRequestId.number, removedItems.filterIsInstance(GHUser::class.java).map { it.login }, removedItems.filterIsInstance(GHTeam::class.java).map { it.slug })) } val newItems = delta.newItems if (newItems.isNotEmpty()) { it.text2 = GithubBundle.message("pull.request.adding.reviewers") requestExecutor.execute(it, GithubApiRequests.Repos.PullRequests.Reviewers .add(serverPath, repoPath.owner, repoPath.repository, pullRequestId.number, newItems.filterIsInstance(GHUser::class.java).map { it.login }, newItems.filterIsInstance(GHTeam::class.java).map { it.slug })) } } .logError(LOG, "Error occurred while adjusting the list of reviewers") override fun adjustAssignees(indicator: ProgressIndicator, pullRequestId: GHPRIdentifier, delta: CollectionDelta<GHUser>) = progressManager.submitIOTask(indicator) { it.text = GithubBundle.message("pull.request.details.adjusting.assignees") requestExecutor.execute(it, GithubApiRequests.Repos.Issues.updateAssignees(serverPath, repoPath.owner, repoPath.repository, pullRequestId.number.toString(), delta.newCollection.map { it.login })) return@submitIOTask } .logError(LOG, "Error occurred while adjusting the list of assignees") override fun adjustLabels(indicator: ProgressIndicator, pullRequestId: GHPRIdentifier, delta: CollectionDelta<GHLabel>) = progressManager.submitIOTask(indicator) { it.text = GithubBundle.message("pull.request.details.adjusting.labels") requestExecutor.execute(indicator, GithubApiRequests.Repos.Issues.Labels .replace(serverPath, repoPath.owner, repoPath.repository, pullRequestId.number.toString(), delta.newCollection.map { it.name })) return@submitIOTask }.logError(LOG, "Error occurred while adjusting the list of labels") companion object { private val LOG = logger<GHPRDetailsService>() } }
apache-2.0
bf1720435e4bc7fa6c995e64048d416a
60.73913
140
0.703997
5.439655
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/receivers/NotificationPublisher.kt
1
7381
package com.habitrpg.android.habitica.receivers import android.app.Notification import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat import androidx.core.content.edit import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.data.TaskRepository import com.habitrpg.android.habitica.data.UserRepository import com.habitrpg.android.habitica.helpers.AmplitudeManager import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.helpers.TaskAlarmManager import com.habitrpg.android.habitica.models.tasks.Task import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.activities.MainActivity import io.reactivex.functions.BiFunction import io.reactivex.functions.Consumer import io.realm.RealmResults import java.util.* import javax.inject.Inject @Suppress("DEPRECATION") //https://gist.github.com/BrandonSmith/6679223 class NotificationPublisher : BroadcastReceiver() { @Inject lateinit var taskRepository: TaskRepository @Inject lateinit var userRepository: UserRepository @Inject lateinit var sharedPreferences: SharedPreferences private var wasInjected = false private var context: Context? = null override fun onReceive(context: Context, intent: Intent) { this.context = context if (!wasInjected) { wasInjected = true HabiticaBaseApplication.userComponent?.inject(this) } val additionalData = HashMap<String, Any>() additionalData["identifier"] = "daily_reminder" AmplitudeManager.sendEvent("receive notification", AmplitudeManager.EVENT_CATEGORY_BEHAVIOUR, AmplitudeManager.EVENT_HITTYPE_EVENT, additionalData) var wasInactive = false //Show special notification if user hasn't logged in for a week if (sharedPreferences.getLong("lastAppLaunch", Date().time) < (Date().time - 604800000L)) { wasInactive = true sharedPreferences.edit { putBoolean("preventDailyReminder", true) } } else { TaskAlarmManager.scheduleDailyReminder(context) } val checkDailies = intent.getBooleanExtra(CHECK_DAILIES, false) if (checkDailies) { taskRepository.getTasks(Task.TYPE_DAILY).firstElement().zipWith(userRepository.getUser().firstElement(), BiFunction<RealmResults<Task>, User, Pair<RealmResults<Task>, User>> { tasks, user -> return@BiFunction Pair(tasks, user) }).subscribe(Consumer { pair -> var showNotifications = false for (task in pair.first) { if (task?.checkIfDue() == true) { showNotifications = true break } } if (showNotifications) { notify(intent, buildNotification(wasInactive, pair.second.authentication?.timestamps?.createdAt)) } }, RxErrorHandler.handleEmptyError()) } else { notify(intent, buildNotification(wasInactive)) } } private fun notify(intent: Intent, notification: Notification?) { val notificationManager = context?.let { NotificationManagerCompat.from(it) } val id = intent.getIntExtra(NOTIFICATION_ID, 0) notification?.let { notificationManager?.notify(id, it) } } private fun buildNotification(wasInactive: Boolean, registrationDate: Date? = null): Notification? { val thisContext = context ?: return null val notification: Notification val builder = NotificationCompat.Builder(thisContext, "default") builder.setContentTitle(thisContext.getString(R.string.reminder_title)) var notificationText = getRandomDailyTip() if (registrationDate != null) { val registrationCal = Calendar.getInstance() registrationCal.time = registrationDate val todayCal = Calendar.getInstance() val isSameDay = (registrationCal.get(Calendar.YEAR) == todayCal.get(Calendar.YEAR) && registrationCal.get(Calendar.DAY_OF_YEAR) == todayCal.get(Calendar.DAY_OF_YEAR) ) val isPreviousDay = (registrationCal.get(Calendar.YEAR) == todayCal.get(Calendar.YEAR) && registrationCal.get(Calendar.DAY_OF_YEAR) == (todayCal.get(Calendar.DAY_OF_YEAR) - 1) ) if (isSameDay) { builder.setContentTitle(thisContext.getString(R.string.same_day_reminder_title)) notificationText = thisContext.getString(R.string.same_day_reminder_text) } else if (isPreviousDay) { builder.setContentTitle(thisContext.getString(R.string.next_day_reminder_title)) notificationText = thisContext.getString(R.string.next_day_reminder_text) } } if (wasInactive) { builder.setContentText(thisContext.getString(R.string.week_reminder_title)) notificationText = thisContext.getString(R.string.week_reminder_text) } builder.setStyle(NotificationCompat.BigTextStyle().bigText(notificationText)) builder.setSmallIcon(R.drawable.ic_gryphon_white) val notificationIntent = Intent(thisContext, MainActivity::class.java) notificationIntent.putExtra("notificationIdentifier", "daily_reminder") notificationIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP val intent = PendingIntent.getActivity(thisContext, 0, notificationIntent, 0) builder.setContentIntent(intent) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder.color = ContextCompat.getColor(thisContext, R.color.brand_300) } notification = builder.build() notification.defaults = notification.defaults or Notification.DEFAULT_LIGHTS notification.flags = notification.flags or (Notification.FLAG_AUTO_CANCEL or Notification.FLAG_SHOW_LIGHTS) return notification } private fun getRandomDailyTip(): String { val thisContext = context ?: return "" val index = Random().nextInt(4) return when (index) { 0 -> thisContext.getString(R.string.daily_tip_0) 1 -> thisContext.getString(R.string.daily_tip_1) 2 -> thisContext.getString(R.string.daily_tip_2) 3 -> thisContext.getString(R.string.daily_tip_3) 4 -> thisContext.getString(R.string.daily_tip_4) 5 -> thisContext.getString(R.string.daily_tip_5) 6 -> thisContext.getString(R.string.daily_tip_6) 7 -> thisContext.getString(R.string.daily_tip_7) 8 -> thisContext.getString(R.string.daily_tip_8) 9 -> thisContext.getString(R.string.daily_tip_9) else -> "" } } companion object { var NOTIFICATION_ID = "notification-id" var CHECK_DAILIES = "check-dailies" } }
gpl-3.0
8b1ee588c3df42ba59a66333b1cfe771
43.197605
202
0.676331
4.737484
false
false
false
false
ian-pi/kotlin-koans
src/ii_collections/_15_AllAnyAndOtherPredicates.kt
1
1147
package ii_collections fun example2(list: List<Int>) { val isZero: (Int) -> Boolean = { it == 0 } val hasZero: Boolean = list.any(isZero) val allZeros: Boolean = list.all(isZero) val numberOfZeros: Int = list.count(isZero) val firstPositiveNumber: Int? = list.firstOrNull { it > 0 } } fun Customer.isFrom(city: City): Boolean { // Return true if the customer is from the given city return this.city == city; } fun Shop.checkAllCustomersAreFrom(city: City): Boolean { // Return true if all customers are from the given city return this.customers.all { it.isFrom(city) } } fun Shop.hasCustomerFrom(city: City): Boolean { // Return true if there is at least one customer from the given city return this.customers.any { it.isFrom(city) } } fun Shop.countCustomersFrom(city: City): Int { // Return the number of customers from the given city return this.customers.filter { it.isFrom(city) }.size } fun Shop.findAnyCustomerFrom(city: City): Customer? { // Return a customer who lives in the given city, or null if there is none return this.customers.firstOrNull {it.isFrom(city)} }
mit
b6b1df0c0a8128b8a6c1516682c69ded
28.410256
78
0.6966
3.724026
false
false
false
false
leafclick/intellij-community
platform/workspaceModel-ide/src/com/intellij/workspace/legacyBridge/intellij/LegacyBridgeModifiableModuleModel.kt
1
8946
package com.intellij.workspace.legacyBridge.intellij import com.google.common.collect.HashBiMap import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.module.ModifiableModuleModel import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleWithNameAlreadyExists import com.intellij.openapi.module.impl.getModuleNameByFilePath import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.projectModel.ProjectModelBundle import com.intellij.util.PathUtil import com.intellij.workspace.api.* import com.intellij.workspace.ide.JpsFileEntitySource import com.intellij.workspace.ide.WorkspaceModel import com.intellij.workspace.ide.storagePlace import com.intellij.workspace.legacyBridge.libraries.libraries.LegacyBridgeModifiableBase internal class LegacyBridgeModifiableModuleModel( private val project: Project, private val moduleManager: LegacyBridgeModuleManagerComponent, diff: TypedEntityStorageBuilder ) : LegacyBridgeModifiableBase(diff), ModifiableModuleModel { override fun getProject(): Project = project private val myModulesToAdd = HashBiMap.create<String, LegacyBridgeModule>() private val myModulesToDispose = HashBiMap.create<String, LegacyBridgeModule>() private val myNewNameToModule = HashBiMap.create<String, LegacyBridgeModule>() // TODO Add cache? override fun getModules(): Array<Module> { val modules = moduleManager.modules.toMutableList() modules.removeAll(myModulesToDispose.values) modules.addAll(myModulesToAdd.values) return modules.toTypedArray() } override fun newModule(filePath: String, moduleTypeId: String): Module = newModule(filePath, moduleTypeId, null) override fun newNonPersistentModule(moduleName: String, moduleTypeId: String): Module { val moduleEntity = diff.addModuleEntity( name = moduleName, dependencies = listOf(ModuleDependencyItem.ModuleSourceDependency), source = object : EntitySource {} ) val module = LegacyBridgeModuleImpl(moduleEntity.persistentId(), moduleName, project, null, entityStoreOnDiff, diff) myModulesToAdd[moduleName] = module module.init {} module.setModuleType(moduleTypeId) return module } override fun newModule(filePath: String, moduleTypeId: String, options: MutableMap<String, String>?): Module { // TODO Handle filePath, add correct iml source with a path // TODO Must be in sync with module loading. It is not now val canonicalPath = FileUtil.toSystemIndependentName(FileUtil.resolveShortWindowsName(filePath)) val existingModule = getModuleByFilePath(canonicalPath) if (existingModule != null) { return existingModule } val moduleName = getModuleNameByFilePath(canonicalPath) if (findModuleByName(moduleName) != null) { throw ModuleWithNameAlreadyExists("Module already exists: $moduleName", moduleName) } // TODO get entity source from ProjectModelExternalSource instead val entitySource = JpsFileEntitySource.FileInDirectory(VirtualFileUrlManager.fromPath(PathUtil.getParentPath(canonicalPath)), project.storagePlace!!) val moduleEntity = diff.addModuleEntity( name = moduleName, dependencies = listOf(ModuleDependencyItem.ModuleSourceDependency), source = entitySource ) val moduleInstance = moduleManager.createModuleInstance(moduleEntity, entityStoreOnDiff, diff = diff, isNew = true) myModulesToAdd[moduleName] = moduleInstance moduleInstance.setModuleType(moduleTypeId) // TODO Don't forget to store options in module entities if (options != null) { for ((key, value) in options) { @Suppress("DEPRECATION") moduleInstance.setOption(key, value) } } return moduleInstance } private fun getModuleByFilePath(filePath: String): LegacyBridgeModule? { for (module in modules) { val sameFilePath = when (SystemInfo.isFileSystemCaseSensitive) { true -> module.moduleFilePath == filePath false -> module.moduleFilePath.equals(filePath, ignoreCase = true) } if (sameFilePath) { return module as LegacyBridgeModule } } return null } // TODO Actually load module content override fun loadModule(filePath: String): Module = newModule(filePath, "", null) override fun disposeModule(module: Module) { module as LegacyBridgeModule if (findModuleByName(module.name) == null) { error("Module '${module.name}' is not found. Probably it's already disposed.") } if (myModulesToAdd.inverse().remove(module) != null) { Disposer.dispose(module) } myNewNameToModule.inverse().remove(module) myModulesToDispose[module.name] = module } override fun findModuleByName(name: String): Module? { val addedModule = myModulesToAdd[name] if (addedModule != null) return addedModule if (myModulesToDispose.containsKey(name)) return null val newNameModule = myNewNameToModule[name] if (newNameModule != null) return null return moduleManager.findModuleByName(name) } override fun dispose() { assertModelIsLive() ApplicationManager.getApplication().assertWriteAccessAllowed() for (moduleToAdd in myModulesToAdd.values) { Disposer.dispose(moduleToAdd) } myModulesToAdd.clear() myModulesToDispose.clear() myNewNameToModule.clear() } override fun isChanged(): Boolean = myModulesToAdd.isNotEmpty() || myModulesToDispose.isNotEmpty() || myNewNameToModule.isNotEmpty() override fun commit() { val diff = collectChanges() WorkspaceModel.getInstance(project).updateProjectModel { it.addDiff(diff) } } fun collectChanges(): TypedEntityStorageBuilder { ApplicationManager.getApplication().assertWriteAccessAllowed() val storage = entityStoreOnDiff.current for (moduleToDispose in myModulesToDispose.values) { val moduleEntity = storage.resolve(moduleToDispose.moduleEntityId) ?: error("Could not find module to remove by id: ${moduleToDispose.moduleEntityId}") diff.removeEntity(moduleEntity) } moduleManager.setNewModuleInstances(myModulesToAdd.values.toList()) for (entry in myNewNameToModule.entries) { val entity = storage.resolve(entry.value.moduleEntityId) ?: error("Unable to resolve module by id: ${entry.value.moduleEntityId}") diff.modifyEntity(ModifiableModuleEntity::class.java, entity) { name = entry.key } } return diff } override fun renameModule(module: Module, newName: String) { module as LegacyBridgeModule val oldModule = findModuleByName(newName) myNewNameToModule.inverse().remove(module) myNewNameToModule.remove(newName) if (module.name != newName) { // if renaming to itself, forget it altogether myNewNameToModule[newName] = module } if (oldModule != null) { throw ModuleWithNameAlreadyExists(ProjectModelBundle.message("module.already.exists.error", newName), newName) } } override fun getModuleToBeRenamed(newName: String): Module? = myNewNameToModule[newName] override fun getNewName(module: Module): String? = myNewNameToModule.inverse()[module] override fun getActualName(module: Module): String = getNewName(module) ?: module.name override fun getModuleGroupPath(module: Module): Array<String>? = LegacyBridgeModuleManagerComponent.getModuleGroupPath(module, entityStoreOnDiff) override fun hasModuleGroups(): Boolean = LegacyBridgeModuleManagerComponent.hasModuleGroups(entityStoreOnDiff) override fun setModuleGroupPath(module: Module, groupPath: Array<out String>?) { val moduleId = (module as LegacyBridgeModule).moduleEntityId val storage = entityStoreOnDiff.current val moduleEntity = storage.resolve(moduleId) ?: error("Could not resolve module by moduleId: $moduleId") val moduleGroupEntity = moduleEntity.groupPath val groupPathList = groupPath?.toList() // TODO How to deduplicate with ModuleCustomImlDataEntity ? if (moduleGroupEntity?.path != groupPathList) { when { moduleGroupEntity == null && groupPathList != null -> diff.addModuleGroupPathEntity( module = moduleEntity, path = groupPathList, source = moduleEntity.entitySource ) moduleGroupEntity == null && groupPathList == null -> Unit moduleGroupEntity != null && groupPathList == null -> diff.removeEntity(moduleGroupEntity) moduleGroupEntity != null && groupPathList != null -> diff.modifyEntity(ModifiableModuleGroupPathEntity::class.java, moduleGroupEntity) { path = groupPathList } else -> error("Should not be reached") } } } }
apache-2.0
592014383c7c2d8dc087240cbfcd29ef
33.945313
153
0.738654
5.216327
false
false
false
false
siosio/intellij-community
plugins/markdown/src/org/intellij/plugins/markdown/google/utils/GoogleCredentialUtils.kt
1
2593
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.google.utils import com.fasterxml.jackson.databind.ObjectMapper import com.google.api.client.auth.oauth2.Credential import com.google.api.client.auth.oauth2.TokenResponse import com.google.api.client.googleapis.auth.oauth2.GoogleCredential import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import org.intellij.plugins.markdown.MarkdownNotifier.notifyNetworkProblems import org.intellij.plugins.markdown.google.authorization.GoogleCredentials import org.intellij.plugins.markdown.google.authorization.GoogleOAuthService import java.io.IOException import java.net.URL object GoogleCredentialUtils { data class GoogleAppCredentials(val clientId: String, val clientSecret: String) private val LOG = logger<GoogleOAuthService>() /** * Credentials for Installed application from google console. * Note: In this context, the client secret is obviously not treated as a secret. * These credentials are fine to be public: https://developers.google.com/identity/protocols/oauth2#installed */ fun getGoogleAppCredentials(project: Project): GoogleAppCredentials? { val googleAppCredUrl = "https://www.jetbrains.com/config/markdown.json" try { val credentials = ObjectMapper().readTree(URL(googleAppCredUrl)).get("google").get("auth") val clientId = credentials.get("secret-id").asText() val clientSecret = credentials.get("client-secret").asText() return GoogleAppCredentials(clientId, clientSecret) } catch (e: IOException) { notifyNetworkProblems(project) LOG.error("Can't get google app credentials from https://www.jetbrains.com/config/markdown.json", e) return null } } /** * Converts internal GoogleCredentials to Credentials that the Google API can work with */ fun createCredentialsForGoogleApi(credentials: GoogleCredentials): Credential { val tokenResponse = getTokenResponse(credentials) return GoogleCredential().setFromTokenResponse(tokenResponse) } /** * Converts GoogleCredentials to TokenResponse to further get the Credential needed to work with the Drive API */ private fun getTokenResponse(credentials: GoogleCredentials): TokenResponse = TokenResponse().apply { accessToken = credentials.accessToken tokenType = credentials.tokenType scope = credentials.scope expiresInSeconds = credentials.expiresIn } }
apache-2.0
479f552470a8f50ec005b4b03dd75f22
40.15873
158
0.775164
4.622103
false
false
false
false
idea4bsd/idea4bsd
plugins/settings-repository/src/RepositoryManager.kt
4
4061
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository import com.intellij.openapi.progress.ProgressIndicator import gnu.trove.THashSet import java.io.InputStream import java.util.* interface RepositoryManager { fun createRepositoryIfNeed(): Boolean /** * Think twice before use */ fun deleteRepository() fun isRepositoryExists(): Boolean fun getUpstream(): String? fun hasUpstream(): Boolean /** * Return error message if failed */ fun setUpstream(url: String?, branch: String? = null) fun read(path: String): InputStream? /** * Returns false if file is not written (for example, due to ignore rules). */ fun write(path: String, content: ByteArray, size: Int): Boolean fun delete(path: String): Boolean fun processChildren(path: String, filter: (name: String) -> Boolean, processor: (name: String, inputStream: InputStream) -> Boolean) /** * Not all implementations support progress indicator (will not be updated on progress). * * syncType will be passed if called before sync. * * If fixStateIfCannotCommit, repository state will be fixed before commit. */ fun commit(indicator: ProgressIndicator? = null, syncType: SyncType? = null, fixStateIfCannotCommit: Boolean = true): Boolean fun getAheadCommitsCount(): Int fun commit(paths: List<String>) fun push(indicator: ProgressIndicator? = null) fun fetch(indicator: ProgressIndicator? = null): Updater fun pull(indicator: ProgressIndicator? = null): UpdateResult? fun has(path: String): Boolean fun resetToTheirs(indicator: ProgressIndicator): UpdateResult? fun resetToMy(indicator: ProgressIndicator, localRepositoryInitializer: (() -> Unit)?): UpdateResult? fun canCommit(): Boolean interface Updater { fun merge(): UpdateResult? // valid only if merge was called before val definitelySkipPush: Boolean } } interface UpdateResult { val changed: Collection<String> val deleted: Collection<String> } val EMPTY_UPDATE_RESULT = ImmutableUpdateResult(Collections.emptySet(), Collections.emptySet()) data class ImmutableUpdateResult(override val changed: Collection<String>, override val deleted: Collection<String>) : UpdateResult { fun toMutable(): MutableUpdateResult = MutableUpdateResult(changed, deleted) } class MutableUpdateResult(changed: Collection<String>, deleted: Collection<String>) : UpdateResult { override val changed = THashSet(changed) override val deleted = THashSet(deleted) fun add(result: UpdateResult?): MutableUpdateResult { if (result != null) { add(result.changed, result.deleted) } return this } fun add(newChanged: Collection<String>, newDeleted: Collection<String>): MutableUpdateResult { changed.removeAll(newDeleted) deleted.removeAll(newChanged) changed.addAll(newChanged) deleted.addAll(newDeleted) return this } fun addChanged(newChanged: Collection<String>): MutableUpdateResult { deleted.removeAll(newChanged) changed.addAll(newChanged) return this } } fun UpdateResult?.isEmpty(): Boolean = this == null || (changed.isEmpty() && deleted.isEmpty()) fun UpdateResult?.concat(result: UpdateResult?): UpdateResult? { if (result.isEmpty()) { return this } else if (isEmpty()) { return result } else { this!! return MutableUpdateResult(changed, deleted).add(result!!) } } class AuthenticationException(cause: Throwable) : RuntimeException(cause.message, cause)
apache-2.0
9adc7181ee2546a22b66f3d9e5349a34
27.808511
134
0.730362
4.53743
false
false
false
false
siosio/intellij-community
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/ContinuationHolder.kt
1
6215
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.coroutine.proxy import com.intellij.debugger.engine.JavaValue import com.sun.jdi.ObjectReference import com.sun.jdi.VMDisconnectedException import org.jetbrains.kotlin.idea.debugger.coroutine.data.* import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror.* import org.jetbrains.kotlin.idea.debugger.coroutine.util.isAbstractCoroutine import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger import org.jetbrains.kotlin.idea.debugger.evaluate.DefaultExecutionContext class ContinuationHolder private constructor(val context: DefaultExecutionContext) { private val debugMetadata: DebugMetadata? = DebugMetadata.instance(context) private val locationCache = LocationCache(context) private val debugProbesImpl = DebugProbesImpl.instance(context) private val javaLangObjectToString = JavaLangObjectToString(context) private val log by logger fun extractCoroutineInfoData(continuation: ObjectReference): CoroutineInfoData? { try { val consumer = mutableListOf<CoroutineStackFrameItem>() val continuationStack = debugMetadata?.fetchContinuationStack(continuation, context) ?: return null for (frame in continuationStack.coroutineStack) { val coroutineStackFrame = createStackFrameItem(frame) if (coroutineStackFrame != null) consumer.add(coroutineStackFrame) } val lastRestoredFrame = continuationStack.coroutineStack.lastOrNull() return findCoroutineInformation(lastRestoredFrame?.baseContinuationImpl?.coroutineOwner, consumer) } catch (e: VMDisconnectedException) { } catch (e: Exception) { log.warn("Error while looking for stack frame", e) } return null } private fun findCoroutineInformation( coroutineOwner: ObjectReference?, stackFrameItems: List<CoroutineStackFrameItem> ): CoroutineInfoData? { val creationStackTrace = mutableListOf<CreationCoroutineStackFrameItem>() val realState = if (coroutineOwner?.type()?.isAbstractCoroutine() == true) { state(coroutineOwner) ?: return null } else { val ci = debugProbesImpl?.getCoroutineInfo(coroutineOwner, context) if (ci != null) { if (ci.creationStackTrace != null) for (index in ci.creationStackTrace.indices) { val frame = ci.creationStackTrace[index] val ste = frame.stackTraceElement() val location = locationCache.createLocation(ste) creationStackTrace.add(CreationCoroutineStackFrameItem(ste, location, index == 0)) } CoroutineNameIdState.instance(ci) } else { CoroutineNameIdState(CoroutineInfoData.DEFAULT_COROUTINE_NAME, "-1", State.UNKNOWN, null) } } return CoroutineInfoData(realState, stackFrameItems, creationStackTrace) } fun state(value: ObjectReference?): CoroutineNameIdState? { value ?: return null val standaloneCoroutine = StandaloneCoroutine.instance(context) ?: return null val standAloneCoroutineMirror = standaloneCoroutine.mirror(value, context) if (standAloneCoroutineMirror?.context is MirrorOfCoroutineContext) { val id = standAloneCoroutineMirror.context.id val name = standAloneCoroutineMirror.context.name ?: CoroutineInfoData.DEFAULT_COROUTINE_NAME val toString = javaLangObjectToString.mirror(value, context) // trying to get coroutine information by calling JobSupport.toString(), ${nameString()}{${stateString(state)}}@$hexAddress val r = """\w+\{(\w+)}@([\w\d]+)""".toRegex() val matcher = r.toPattern().matcher(toString) if (matcher.matches()) { val state = stateOf(matcher.group(1)) val hexAddress = matcher.group(2) return CoroutineNameIdState(name, id?.toString() ?: hexAddress, state, standAloneCoroutineMirror.context.dispatcher) } } return null } private fun createStackFrameItem( frame: MirrorOfStackFrame ): DefaultCoroutineStackFrameItem? { val stackTraceElement = frame.baseContinuationImpl.stackTraceElement?.stackTraceElement() ?: return null val locationClass = context.findClassSafe(stackTraceElement.className) ?: return null val generatedLocation = locationCache.createLocation(locationClass, stackTraceElement.methodName, stackTraceElement.lineNumber) val spilledVariables = frame.baseContinuationImpl.spilledValues(context) return DefaultCoroutineStackFrameItem(generatedLocation, spilledVariables) } companion object { val log by logger fun instance(context: DefaultExecutionContext) = ContinuationHolder(context) private fun stateOf(state: String?): State = when (state) { "Active" -> State.RUNNING "Cancelling" -> State.SUSPENDED_CANCELLING "Completing" -> State.SUSPENDED_COMPLETING "Cancelled" -> State.CANCELLED "Completed" -> State.COMPLETED "New" -> State.NEW else -> State.UNKNOWN } } } fun MirrorOfBaseContinuationImpl.spilledValues(context: DefaultExecutionContext): List<JavaValue> { return fieldVariables.map { it.toJavaValue(that, context) } } fun FieldVariable.toJavaValue(continuation: ObjectReference, context: DefaultExecutionContext): JavaValue { val valueDescriptor = ContinuationVariableValueDescriptorImpl( context, continuation, fieldName, variableName ) return JavaValue.create( null, valueDescriptor, context.evaluationContext, context.debugProcess.xdebugProcess!!.nodeManager, false ) }
apache-2.0
1fdb1bb4b72d5ac2874512be29e55b46
45.729323
158
0.675784
5.409051
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/mapMax.kt
2
374
// API_VERSION: 1.4 // WITH_RUNTIME data class OrderItem(val name: String, val price: Double, val count: Int) fun main() { val order = listOf<OrderItem>( OrderItem("Cake", price = 10.0, count = 1), OrderItem("Coffee", price = 2.5, count = 3), OrderItem("Tea", price = 1.5, count = 2) ) val max = order.map<caret> { it.price }.max()!! }
apache-2.0
0a6ae097f679aa4b81b866a3df19cce5
25.785714
73
0.582888
3.224138
false
false
false
false
jwren/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/KotlinSearchSupport.kt
3
8495
// 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 import com.intellij.openapi.components.service import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.psi.* import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.SearchScope import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.DataClassResolver import org.jetbrains.kotlin.resolve.ImportPath interface KotlinSearchUsagesSupport { interface ConstructorCallHandle { fun referencedTo(element: KtElement): Boolean } companion object { fun getInstance(project: Project): KotlinSearchUsagesSupport = project.service() val KtParameter.dataClassComponentMethodName: String? get() = getInstance(project).dataClassComponentMethodName(this) val KtExpression.hasType: Boolean get() = getInstance(project).hasType(this) val PsiClass.isSamInterface: Boolean get() = getInstance(project).isSamInterface(this) fun <T : PsiNamedElement> List<T>.filterDataClassComponentsIfDisabled(kotlinOptions: KotlinReferencesSearchOptions): List<T> { fun PsiNamedElement.isComponentElement(): Boolean { if (this !is PsiMethod) return false val dataClassParent = ((parent as? KtLightClass)?.kotlinOrigin as? KtClass)?.isData() == true if (!dataClassParent) return false if (!Name.isValidIdentifier(name)) return false val nameIdentifier = Name.identifier(name) if (!DataClassResolver.isComponentLike(nameIdentifier)) return false return true } return if (kotlinOptions.searchForComponentConventions) this else filter { !it.isComponentElement() } } fun PsiReference.isCallableOverrideUsage(declaration: KtNamedDeclaration): Boolean = getInstance(declaration.project).isCallableOverrideUsage(this, declaration) fun PsiReference.isUsageInContainingDeclaration(declaration: KtNamedDeclaration): Boolean = getInstance(declaration.project).isUsageInContainingDeclaration(this, declaration) fun PsiReference.isExtensionOfDeclarationClassUsage(declaration: KtNamedDeclaration): Boolean = getInstance(declaration.project).isExtensionOfDeclarationClassUsage(this, declaration) fun PsiElement.getReceiverTypeSearcherInfo(isDestructionDeclarationSearch: Boolean): ReceiverTypeSearcherInfo? = getInstance(project).getReceiverTypeSearcherInfo(this, isDestructionDeclarationSearch) fun KtFile.forceResolveReferences(elements: List<KtElement>) = getInstance(project).forceResolveReferences(this, elements) fun PsiFile.scriptDefinitionExists(): Boolean = getInstance(project).scriptDefinitionExists(this) fun KtFile.getDefaultImports(): List<ImportPath> = getInstance(project).getDefaultImports(this) fun forEachKotlinOverride( ktClass: KtClass, members: List<KtNamedDeclaration>, scope: SearchScope, searchDeeply: Boolean, processor: (superMember: PsiElement, overridingMember: PsiElement) -> Boolean ): Boolean = getInstance(ktClass.project).forEachKotlinOverride(ktClass, members, scope, searchDeeply, processor) fun PsiMethod.forEachOverridingMethod( scope: SearchScope = runReadAction { useScope() }, processor: (PsiMethod) -> Boolean ): Boolean = getInstance(project).forEachOverridingMethod(this, scope, processor) fun findDeepestSuperMethodsNoWrapping(method: PsiElement): List<PsiElement> = getInstance(method.project).findDeepestSuperMethodsNoWrapping(method) fun findTypeAliasByShortName(shortName: String, project: Project, scope: GlobalSearchScope): Collection<KtTypeAlias> = getInstance(project).findTypeAliasByShortName(shortName, project, scope) fun isInProjectSource(element: PsiElement, includeScriptsOutsideSourceRoots: Boolean = false): Boolean = getInstance(element.project).isInProjectSource(element, includeScriptsOutsideSourceRoots) fun KtDeclaration.isOverridable(): Boolean = getInstance(project).isOverridable(this) fun KtClass.isInheritable(): Boolean = getInstance(project).isInheritable(this) @NlsSafe fun formatJavaOrLightMethod(method: PsiMethod): String = getInstance(method.project).formatJavaOrLightMethod(method) @NlsSafe fun formatClass(classOrObject: KtClassOrObject): String = getInstance(classOrObject.project).formatClass(classOrObject) fun KtDeclaration.expectedDeclarationIfAny(): KtDeclaration? = getInstance(project).expectedDeclarationIfAny(this) fun KtDeclaration.isExpectDeclaration(): Boolean = getInstance(project).isExpectDeclaration(this) fun KtDeclaration.actualsForExpected(module: Module? = null): Set<KtDeclaration> = getInstance(project).actualsForExpected(this, module) fun PsiElement.canBeResolvedWithFrontEnd(): Boolean = getInstance(project).canBeResolvedWithFrontEnd(this) fun createConstructorHandle(ktDeclaration: KtDeclaration): ConstructorCallHandle = getInstance(ktDeclaration.project).createConstructorHandle(ktDeclaration) fun createConstructorHandle(psiMethod: PsiMethod): ConstructorCallHandle = getInstance(psiMethod.project).createConstructorHandle(psiMethod) } fun actualsForExpected(declaration: KtDeclaration, module: Module? = null): Set<KtDeclaration> fun dataClassComponentMethodName(element: KtParameter): String? fun hasType(element: KtExpression): Boolean fun isSamInterface(psiClass: PsiClass): Boolean fun isCallableOverrideUsage(reference: PsiReference, declaration: KtNamedDeclaration): Boolean fun isCallableOverride(subDeclaration: KtDeclaration, superDeclaration: PsiNamedElement): Boolean fun isUsageInContainingDeclaration(reference: PsiReference, declaration: KtNamedDeclaration): Boolean fun isExtensionOfDeclarationClassUsage(reference: PsiReference, declaration: KtNamedDeclaration): Boolean fun getReceiverTypeSearcherInfo(psiElement: PsiElement, isDestructionDeclarationSearch: Boolean): ReceiverTypeSearcherInfo? fun forceResolveReferences(file: KtFile, elements: List<KtElement>) fun scriptDefinitionExists(file: PsiFile): Boolean fun getDefaultImports(file: KtFile): List<ImportPath> fun forEachKotlinOverride( ktClass: KtClass, members: List<KtNamedDeclaration>, scope: SearchScope, searchDeeply: Boolean, processor: (superMember: PsiElement, overridingMember: PsiElement) -> Boolean ): Boolean fun forEachOverridingMethod( method: PsiMethod, scope: SearchScope, processor: (PsiMethod) -> Boolean ): Boolean fun findDeepestSuperMethodsNoWrapping(method: PsiElement): List<PsiElement> fun findSuperMethodsNoWrapping(method: PsiElement): List<PsiElement> fun findTypeAliasByShortName(shortName: String, project: Project, scope: GlobalSearchScope): Collection<KtTypeAlias> fun isInProjectSource(element: PsiElement, includeScriptsOutsideSourceRoots: Boolean = false): Boolean fun isOverridable(declaration: KtDeclaration): Boolean fun isInheritable(ktClass: KtClass): Boolean fun formatJavaOrLightMethod(method: PsiMethod): String fun formatClass(classOrObject: KtClassOrObject): String fun expectedDeclarationIfAny(declaration: KtDeclaration): KtDeclaration? fun isExpectDeclaration(declaration: KtDeclaration): Boolean fun canBeResolvedWithFrontEnd(element: PsiElement): Boolean fun createConstructorHandle(ktDeclaration: KtDeclaration): ConstructorCallHandle fun createConstructorHandle(psiMethod: PsiMethod): ConstructorCallHandle }
apache-2.0
8b3e751ef44597545a898b29f4e1e26e
42.78866
158
0.743732
5.940559
false
false
false
false
androidx/androidx
camera/camera-video/src/androidTest/java/androidx/camera/video/AudioChecker.kt
3
3915
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.camera.video import android.content.Context import androidx.annotation.RequiresApi import androidx.camera.core.CameraSelector import androidx.camera.core.Logger import androidx.camera.core.impl.utils.executor.CameraXExecutors import androidx.camera.testing.CameraUtil import androidx.camera.video.internal.AudioSource import androidx.camera.video.internal.FakeBufferProvider import androidx.camera.video.internal.config.AudioSourceSettingsCamcorderProfileResolver import androidx.camera.video.internal.encoder.FakeInputBuffer import androidx.concurrent.futures.await import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.runBlocking @RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java class AudioChecker { companion object { private const val TAG = "AudioChecker" fun canAudioSourceBeStarted( context: Context, cameraSelector: CameraSelector, qualitySelector: QualitySelector ): Boolean { return try { checkAudioSourceCanBeStarted(context, cameraSelector, qualitySelector) Logger.i(TAG, "Audio source can be started.") true } catch (t: Throwable) { Logger.i(TAG, "Audio source failed to start.", t) false } } private fun checkAudioSourceCanBeStarted( context: Context, cameraSelector: CameraSelector, qualitySelector: QualitySelector ) = runBlocking { // Get audio source settings from CamcorderProfile val cameraInfo = CameraUtil.createCameraUseCaseAdapter(context, cameraSelector).cameraInfo val videoCapabilities = VideoCapabilities.from(cameraInfo) val quality = qualitySelector.getPrioritizedQualities(cameraInfo).first() // Get a config using the default audio spec. val audioSourceSettings = AudioSourceSettingsCamcorderProfileResolver( AudioSpec.builder().build(), videoCapabilities.getProfile(quality)!! ).get() val audioSource = AudioSource(audioSourceSettings, CameraXExecutors.ioExecutor(), null) try { val completable = CompletableDeferred<Any?>() audioSource.setAudioSourceCallback(CameraXExecutors.directExecutor(), object : AudioSource.AudioSourceCallback { override fun onSilenced(silenced: Boolean) { // Ignore } override fun onError(t: Throwable) { completable.completeExceptionally(t) } }) val fakeBufferProvider = FakeBufferProvider { completable.complete(null) FakeInputBuffer() } audioSource.setBufferProvider(fakeBufferProvider) fakeBufferProvider.setActive(true) audioSource.start() completable.await() } finally { audioSource.release().await() } } } }
apache-2.0
84f9258e0396502a31987a24c6b91bdb
39.371134
99
0.638825
5.748899
false
false
false
false
jwren/intellij-community
plugins/github/src/org/jetbrains/plugins/github/util/GithubUtil.kt
1
6500
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.util import com.intellij.concurrency.JobScheduler import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.util.Couple import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.Pair import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.EventDispatcher import git4idea.repo.GitRemote import git4idea.repo.GitRepository import org.jetbrains.annotations.ApiStatus import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager import com.intellij.collaboration.ui.SimpleEventListener import java.io.IOException import java.net.UnknownHostException import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit import kotlin.properties.ObservableProperty import kotlin.reflect.KProperty /** * Various utility methods for the GutHub plugin. */ object GithubUtil { @JvmField val LOG: Logger = Logger.getInstance("github") @NlsSafe const val SERVICE_DISPLAY_NAME: String = "GitHub" @NlsSafe const val ENTERPRISE_SERVICE_DISPLAY_NAME: String = "GitHub Enterprise" const val GIT_AUTH_PASSWORD_SUBSTITUTE: String = "x-oauth-basic" @JvmStatic fun addCancellationListener(run: () -> Unit): ScheduledFuture<*> { return JobScheduler.getScheduler().scheduleWithFixedDelay(run, 1000, 300, TimeUnit.MILLISECONDS) } private fun addCancellationListener(indicator: ProgressIndicator, thread: Thread): ScheduledFuture<*> { return addCancellationListener { if (indicator.isCanceled) thread.interrupt() } } @Throws(IOException::class) @JvmStatic fun <T> runInterruptable(indicator: ProgressIndicator, task: ThrowableComputable<T, IOException>): T { var future: ScheduledFuture<*>? = null try { val thread = Thread.currentThread() future = addCancellationListener(indicator, thread) return task.compute() } finally { future?.cancel(true) Thread.interrupted() } } @NlsSafe @JvmStatic fun getErrorTextFromException(e: Throwable): String { return if (e is UnknownHostException) { "Unknown host: " + e.message } else StringUtil.notNullize(e.message, "Unknown error") } /** * Splits full commit message into subject and description in GitHub style: * First line becomes subject, everything after first line becomes description * Also supports empty line that separates subject and description * * @param commitMessage full commit message * @return couple of subject and description based on full commit message */ @JvmStatic fun getGithubLikeFormattedDescriptionMessage(commitMessage: String?): Couple<String> { //Trim original val message = commitMessage?.trim { it <= ' ' } ?: "" if (message.isEmpty()) { return Couple.of("", "") } val firstLineEnd = message.indexOf("\n") val subject: String val description: String if (firstLineEnd > -1) { //Subject is always first line subject = message.substring(0, firstLineEnd).trim { it <= ' ' } //Description is all text after first line, we also trim it to remove empty lines on start of description description = message.substring(firstLineEnd + 1).trim { it <= ' ' } } else { //If we don't have any line separators and cannot detect description, //we just assume that it is one-line commit and use full message as subject with empty description subject = message description = "" } return Couple.of(subject, description) } object Delegates { inline fun <T> equalVetoingObservable(initialValue: T, crossinline onChange: (newValue: T) -> Unit) = object : ObservableProperty<T>(initialValue) { override fun beforeChange(property: KProperty<*>, oldValue: T, newValue: T) = newValue == null || oldValue != newValue override fun afterChange(property: KProperty<*>, oldValue: T, newValue: T) = onChange(newValue) } fun <T> observableField(initialValue: T, dispatcher: EventDispatcher<SimpleEventListener>): ObservableProperty<T> { return object : ObservableProperty<T>(initialValue) { override fun afterChange(property: KProperty<*>, oldValue: T, newValue: T) = dispatcher.multicaster.eventOccurred() } } } @JvmStatic @Deprecated("{@link GithubGitHelper}", ReplaceWith("GithubGitHelper.findGitRepository(project, file)", "org.jetbrains.plugins.github.util.GithubGitHelper")) @ApiStatus.ScheduledForRemoval fun getGitRepository(project: Project, file: VirtualFile?): GitRepository? { return GithubGitHelper.findGitRepository(project, file) } @Suppress("MemberVisibilityCanBePrivate") @JvmStatic @Deprecated("{@link GithubGitHelper}") private fun findGithubRemoteUrl(repository: GitRepository): String? { val remote = findGithubRemote(repository) ?: return null return remote.getSecond() } @Suppress("MemberVisibilityCanBePrivate") @JvmStatic @Deprecated("{@link org.jetbrains.plugins.github.api.GithubServerPath}, {@link GithubGitHelper}") private fun findGithubRemote(repository: GitRepository): Pair<GitRemote, String>? { val server = GithubAuthenticationManager.getInstance().getSingleOrDefaultAccount(repository.project)?.server ?: return null var githubRemote: Pair<GitRemote, String>? = null for (gitRemote in repository.remotes) { for (remoteUrl in gitRemote.urls) { if (server.matches(remoteUrl)) { val remoteName = gitRemote.name if ("github" == remoteName || "origin" == remoteName) { return Pair.create(gitRemote, remoteUrl) } if (githubRemote == null) { githubRemote = Pair.create(gitRemote, remoteUrl) } break } } } return githubRemote } @Suppress("DeprecatedCallableAddReplaceWith") @JvmStatic @Deprecated("{@link org.jetbrains.plugins.github.api.GithubServerPath}") @ApiStatus.ScheduledForRemoval fun isRepositoryOnGitHub(repository: GitRepository): Boolean { return findGithubRemoteUrl(repository) != null } }
apache-2.0
1cad13e71803705b5799865f0382c39f
36.790698
140
0.718615
4.754938
false
false
false
false
eviera/kotlin-koans
src/ii_collections/_15_AllAnyAndOtherPredicates.kt
1
1121
package ii_collections fun example2(list: List<Int>) { val isZero: (Int) -> Boolean = { it == 0 } val hasZero: Boolean = list.any(isZero) val allZeros: Boolean = list.all(isZero) val numberOfZeros: Int = list.count(isZero) val firstPositiveNumber: Int? = list.firstOrNull { it > 0 } } fun Customer.isFrom(city: City): Boolean { // Return true if the customer is from the given city return this.city == city } fun Shop.checkAllCustomersAreFrom(city: City): Boolean { // Return true if all customers are from the given city return customers.all{ it.isFrom(city) } } fun Shop.hasCustomerFrom(city: City): Boolean { // Return true if there is at least one customer from the given city return customers.any { it.isFrom(city) } } fun Shop.countCustomersFrom(city: City): Int { // Return the number of customers from the given city return customers.count { it.isFrom(city) } } fun Shop.findAnyCustomerFrom(city: City): Customer? { // Return a customer who lives in the given city, or null if there is none return customers.firstOrNull { it.isFrom(city) } }
mit
07de9058f5bc950518b09d5de0aafe30
27.74359
78
0.694023
3.749164
false
false
false
false
GunoH/intellij-community
plugins/kotlin/completion/impl-k1/src/org/jetbrains/kotlin/idea/completion/OverridesCompletion.kt
4
4453
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion import com.intellij.icons.AllIcons import com.intellij.psi.PsiElement import com.intellij.ui.RowIcon import org.jetbrains.kotlin.backend.common.descriptors.isSuspend import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.KotlinDescriptorIconProvider import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.completion.DescriptorBasedDeclarationLookupObject import org.jetbrains.kotlin.idea.core.overrideImplement.OverrideMembersHandler import org.jetbrains.kotlin.idea.core.overrideImplement.generateMember import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType class OverridesCompletion( private val collector: LookupElementsCollector, private val lookupElementFactory: BasicLookupElementFactory ) { private val PRESENTATION_RENDERER = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withOptions { modifiers = emptySet() includeAdditionalModifiers = false } fun complete(position: PsiElement, declaration: KtCallableDeclaration?) { val isConstructorParameter = position.getNonStrictParentOfType<KtPrimaryConstructor>() != null val classOrObject = position.getNonStrictParentOfType<KtClassOrObject>() ?: return val members = OverrideMembersHandler(isConstructorParameter).collectMembersToGenerate(classOrObject) for (memberObject in members) { val descriptor = memberObject.descriptor if (declaration != null && !canOverride(descriptor, declaration)) continue if (isConstructorParameter && descriptor !is PropertyDescriptor) continue var lookupElement = lookupElementFactory.createLookupElement(descriptor) var text = "override " + PRESENTATION_RENDERER.render(descriptor) if (descriptor is FunctionDescriptor) { text += " {...}" } val baseClass = descriptor.containingDeclaration as ClassDescriptor val baseClassName = baseClass.name.asString() val baseIcon = (lookupElement.`object` as DescriptorBasedDeclarationLookupObject).getIcon(0) val isImplement = descriptor.modality == Modality.ABSTRACT val additionalIcon = if (isImplement) AllIcons.Gutter.ImplementingMethod else AllIcons.Gutter.OverridingMethod val icon = RowIcon(baseIcon, additionalIcon) val baseClassDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(position.project, baseClass) val baseClassIcon = KotlinDescriptorIconProvider.getIcon(baseClass, baseClassDeclaration, 0) lookupElement = OverridesCompletionLookupElementDecorator( lookupElement, declaration, text, isImplement, icon, baseClassName, baseClassIcon, isConstructorParameter, memberObject.descriptor.isSuspend, generateMember = { memberObject.generateMember(classOrObject, copyDoc = false) }, shortenReferences = ShortenReferences.DEFAULT::process, ) lookupElement.assignPriority(if (isImplement) ItemPriority.IMPLEMENT else ItemPriority.OVERRIDE) collector.addElement(lookupElement) } } private fun canOverride(descriptorToOverride: CallableMemberDescriptor, declaration: KtCallableDeclaration): Boolean { when (declaration) { is KtFunction -> return descriptorToOverride is FunctionDescriptor is KtValVarKeywordOwner -> { if (descriptorToOverride !is PropertyDescriptor) return false return if (declaration.valOrVarKeyword?.node?.elementType == KtTokens.VAL_KEYWORD) { !descriptorToOverride.isVar } else { true // var can override either var or val } } else -> return false } } }
apache-2.0
4afadaac92a55ee36f988ac87def64c3
43.979798
158
0.70155
5.87467
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/maven/src/org/jetbrains/kotlin/idea/maven/inspections/KotlinMavenUnresolvedReferenceQuickFixProvider.kt
3
4637
// 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.maven.inspections import com.intellij.codeInsight.daemon.QuickFixActionRegistrar import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixProvider import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.SmartPsiElementPointer import com.intellij.psi.xml.XmlFile import org.jetbrains.idea.maven.dom.MavenDomUtil import org.jetbrains.idea.maven.indices.MavenArtifactSearchDialog import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.idea.maven.utils.MavenArtifactScope import org.jetbrains.kotlin.idea.core.isInTestSourceContentKotlinAware import org.jetbrains.kotlin.idea.maven.KotlinMavenBundle import org.jetbrains.kotlin.idea.maven.PomFile import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.psi.KtImportDirective import org.jetbrains.kotlin.psi.KtSimpleNameExpression import org.jetbrains.kotlin.psi.KtTypeReference import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.psi.psiUtil.getParentOfType class KotlinMavenUnresolvedReferenceQuickFixProvider : UnresolvedReferenceQuickFixProvider<KtSimpleNameReference>() { override fun getReferenceClass(): Class<KtSimpleNameReference> = KtSimpleNameReference::class.java override fun registerFixes(ref: KtSimpleNameReference, registrar: QuickFixActionRegistrar) { val module = ModuleUtilCore.findModuleForPsiElement(ref.expression) ?: return if (!MavenProjectsManager.getInstance(module.project).isMavenizedModule(module)) { return } val expression = ref.expression val importDirective = expression.getParentOfType<KtImportDirective>(true) val name = if (importDirective != null) { if (importDirective.isAllUnder) { null } else { importDirective.importedFqName?.asString() } } else { val typeReference = expression.getParentOfType<KtTypeReference>(true) val referenced = typeReference?.text ?: expression.getReferencedName() expression.containingKtFile .importDirectives .firstOrNull { !it.isAllUnder && it.aliasName == referenced || it.importedFqName?.shortName()?.asString() == referenced } ?.let { it.importedFqName?.asString() } ?: referenced } if (name != null) { registrar.register(AddMavenDependencyQuickFix(name, expression.createSmartPointer())) } } } class AddMavenDependencyQuickFix( val className: String, private val smartPsiElementPointer: SmartPsiElementPointer<KtSimpleNameExpression> ) : IntentionAction, LowPriorityAction { override fun getText() = KotlinMavenBundle.message("fix.add.maven.dependency.name") override fun getFamilyName() = text override fun startInWriteAction() = false override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?) = smartPsiElementPointer.element.let { it != null && it.isValid } && file != null && MavenDomUtil.findContainingProject(file) != null override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { if (editor == null || file == null) { return } val virtualFile = file.originalFile.virtualFile ?: return val mavenProject = MavenDomUtil.findContainingProject(file) ?: return val xmlFile = PsiManager.getInstance(project).findFile(mavenProject.file) as? XmlFile ?: return val ids = MavenArtifactSearchDialog.searchForClass(project, className) if (ids.isEmpty()) return runWriteAction { val isTestSource = ProjectRootManager.getInstance(project).fileIndex.isInTestSourceContentKotlinAware(virtualFile) val scope = if (isTestSource) MavenArtifactScope.TEST else null PomFile.forFileOrNull(xmlFile)?.let { pom -> ids.forEach { pom.addDependency(it, scope) } } } } }
apache-2.0
88973fcf52127d8a487fa825166b27f8
44.460784
158
0.732586
5.239548
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/GHPRGraphFileHistory.kt
10
2772
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.data import com.intellij.openapi.diff.impl.patch.TextFilePatch import com.intellij.util.castSafelyTo import org.jetbrains.plugins.github.api.data.GHCommit import java.util.concurrent.ConcurrentHashMap class GHPRGraphFileHistory(private val commitsMap: Map<String, GHCommitWithPatches>, private val lastCommit: GHCommit, private val finalFilePath: String) : GHPRFileHistory { private val containsCache = ConcurrentHashMap<Pair<String, String>, Boolean>() override fun contains(commitSha: String, filePath: String): Boolean = containsCache.getOrPut(commitSha to filePath) { val lastCommitWithPatches = commitsMap[lastCommit.oid] ?: return@getOrPut false isSameFile(lastCommitWithPatches, finalFilePath, commitSha, filePath) } private fun isSameFile(knownCommit: GHCommitWithPatches, knownFilePath: String, commitSha: String, filePath: String): Boolean { if (knownCommit.cumulativePatches.none { it.castSafelyTo<TextFilePatch>()?.filePath == knownFilePath }) return false val newKnownFilePath = knownCommit.commitPatches.find { it.castSafelyTo<TextFilePatch>()?.filePath == knownFilePath }?.beforeFileName if (knownCommit.sha == commitSha && (knownFilePath == filePath || newKnownFilePath == filePath)) return true val knownParents = knownCommit.commit.parents.mapNotNull { commitsMap[it.oid] } return knownParents.any { isSameFile(it, newKnownFilePath ?: knownFilePath, commitSha, filePath) } } override fun compare(commitSha1: String, commitSha2: String): Int { TODO("Not supported for now") /*if (commitSha1 == commitSha2) return 0 val commit1 = commitsMap[commitSha1] ?: error("Invalid commit sha: $commitSha1") val commit2 = commitsMap[commitSha2] ?: error("Invalid commit sha: $commitSha2") // check if commitSha2 is a parent of commitSha1 for (commit in Traverser.forGraph(commitsGraph).depthFirstPreOrder(commit1.commit)) { if (commit == commit2.commit) return 1 } // check if commitSha1 is a parent of commitSha2 for (commit in Traverser.forGraph(commitsGraph).depthFirstPreOrder(commit2.commit)) { if (commit == commit1.commit) return -1 } // We break contract here by returning -2 for unconnected commits return -2*/ } override fun getPatches(parent: String, child: String, includeFirstKnownPatch: Boolean, includeLastPatch: Boolean): List<TextFilePatch> { TODO("Not supported for now") } companion object { private val TextFilePatch.filePath get() = (afterName ?: beforeName)!! } }
apache-2.0
1f6b8226a6802d01942cd3f017f87357
46.793103
140
0.738456
4.351648
false
false
false
false
smmribeiro/intellij-community
plugins/devkit/devkit-kotlin-tests/testData/inspections/internal/PsiType.kt
9
1499
package com.intellij.psi abstract class PsiType { companion object { //@JvmField val VOID = PsiPrimitiveType() //@JvmField val NULL = PsiPrimitiveType() //@JvmField val EMPTY_ARRAY = arrayOf<PsiType>() } open fun test() { if (EMPTY_ARRAY === EMPTY_ARRAY) {} //if (VOID !== NULL) {} // TODO add @JvmField } } class PsiPrimitiveType : PsiType() { override fun test() { if (this === this) {} if (this !== this) {} val first: PsiPrimitiveType = PsiPrimitiveType() val second: PsiPrimitiveType? = PsiPrimitiveType() if (this === second) {} if (second !== this) {} if (<warning descr="'PsiPrimitiveType' instances should be compared by 'equals()', not '=='">first === second</warning>) {} if (<warning descr="'PsiPrimitiveType' instances should be compared by 'equals()', not '=='">first !== second</warning>) {} if (<warning descr="'PsiPrimitiveType' instances should be compared by 'equals()', not '=='">second === first</warning>) {} if (<warning descr="'PsiPrimitiveType' instances should be compared by 'equals()', not '=='">second !== first</warning>) {} val third: MyPsiPrimitiveType = first if (<warning descr="'PsiPrimitiveType' instances should be compared by 'equals()', not '=='">third === first</warning>) {} if (<warning descr="'PsiPrimitiveType' instances should be compared by 'equals()', not '=='">third !== first</warning>) {} } } typealias MyPsiPrimitiveType = PsiPrimitiveType
apache-2.0
ea21f8dae65cf8c25e3f7855f008bcd8
31.608696
127
0.637091
4.728707
false
false
false
false
BenWoodworth/FastCraft
fastcraft-bukkit/bukkit-1.13/src/main/kotlin/net/benwoodworth/fastcraft/bukkit/recipe/FcIngredient_Bukkit_1_13.kt
1
1352
package net.benwoodworth.fastcraft.bukkit.recipe import net.benwoodworth.fastcraft.bukkit.world.FcItemStack_Bukkit import net.benwoodworth.fastcraft.bukkit.world.bukkit import net.benwoodworth.fastcraft.platform.world.FcItemStack import org.bukkit.inventory.RecipeChoice import java.util.* open class FcIngredient_Bukkit_1_13 protected constructor( final override val slotIndex: Int, fcItemStackOperations: FcItemStack.Operations, ) : FcIngredient_Bukkit, FcItemStack_Bukkit.Operations by fcItemStackOperations.bukkit { private lateinit var recipeChoice: RecipeChoice init { require(slotIndex in 0..8) } constructor( slotIndex: Int, recipeChoice: RecipeChoice, fcItemStackOperations: FcItemStack.Operations, ) : this( slotIndex = slotIndex, fcItemStackOperations = fcItemStackOperations, ) { this.recipeChoice = recipeChoice } override fun matches(itemStack: FcItemStack): Boolean { return recipeChoice.test(itemStack.itemStack) } override fun equals(other: Any?): Boolean { return other is FcIngredient_Bukkit_1_13 && slotIndex == other.slotIndex && recipeChoice == other.recipeChoice } override fun hashCode(): Int { return Objects.hash(slotIndex, recipeChoice) } }
gpl-3.0
19dce30cebaba7e52c1fb052f3c2d201
29.044444
67
0.707101
4.970588
false
false
false
false
softappeal/yass
kotlin/yass/main/ch/softappeal/yass/transport/ContextMessageSerializer.kt
1
814
package ch.softappeal.yass.transport import ch.softappeal.yass.remote.* import ch.softappeal.yass.serialize.* private val context = ThreadLocal<Any?>() var cmsContext: Any? get() = context.get() set(value) = context.set(value) class ContextMessageSerializer( private val contextSerializer: Serializer, private val messageSerializer: Serializer ) : Serializer { override fun read(reader: Reader): Message { cmsContext = contextSerializer.read(reader) return messageSerializer.read(reader) as Message } /** Sets context to null. */ override fun write(writer: Writer, value: Any?) { try { contextSerializer.write(writer, cmsContext) } finally { cmsContext = null } messageSerializer.write(writer, value) } }
bsd-3-clause
a1c7af1e48277e9b8305ef53eec6bb86
27.068966
88
0.673219
4.472527
false
false
false
false
like5188/Common
common/src/main/java/com/like/common/view/banner/BaseBannerPagerAdapter.kt
1
786
package com.like.common.view.banner import android.content.Context import android.support.v4.view.PagerAdapter import android.view.View import android.view.ViewGroup abstract class BaseBannerPagerAdapter(val context: Context) : PagerAdapter() { override fun getCount(): Int = Int.MAX_VALUE override fun isViewFromObject(view: View?, `object`: Any?): Boolean = view == `object` override fun instantiateItem(container: ViewGroup?, position: Int): Any { val view = getView(container, position) container?.addView(view) return view } override fun destroyItem(container: ViewGroup?, position: Int, `object`: Any?) { container?.removeView(`object` as View) } abstract fun getView(container: ViewGroup?, position: Int): View }
apache-2.0
2cf8073985ddc4020b24dd3ee2bd0446
31.75
90
0.71374
4.391061
false
false
false
false
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/dynarek2/target/x64/X64Builder.kt
1
14074
package com.soywiz.dynarek2.target.x64 // http://ref.x86asm.net/coder64.html open class X64Builder : BaseBuilder() { fun retn() = bytes(0xc3) // MMX fun addss(dst: RegXmm, src: RegXmm) = bytes(0xF3, 0x0F, 0x58, 0xC0 or (dst.olindex shl 3) or (src.olindex shl 0)) fun mulss(dst: RegXmm, src: RegXmm) = bytes(0xF3, 0x0F, 0x59, 0xC0 or (dst.olindex shl 3) or (src.olindex shl 0)) fun subss(dst: RegXmm, src: RegXmm) = bytes(0xF3, 0x0F, 0x5C, 0xC0 or (dst.olindex shl 3) or (src.olindex shl 0)) fun divss(dst: RegXmm, src: RegXmm) = bytes(0xF3, 0x0F, 0x5E, 0xC0 or (dst.olindex shl 3) or (src.olindex shl 0)) fun readMem(reg: RegXmm, base: Reg64, offset: Int) = //bytes(0x67, 0xF3, 0x0F, 0x10, 0x80 or (reg.olindex shl 3) or ((base.olindex) shl 0)).also { int(offset) } bytes(0xF3, 0x0F, 0x10, 0x80 or (reg.olindex shl 3) or ((base.olindex) shl 0)).also { int(offset) } fun writeMem(reg: RegXmm, base: Reg64, offset: Int) = //bytes(0x67, 0xF3, 0x0F, 0x11, 0x80 or (reg.olindex shl 3) or ((base.olindex) shl 0)).also { int(offset) } bytes(0xF3, 0x0F, 0x11, 0x80 or (reg.olindex shl 3) or ((base.olindex) shl 0)).also { int(offset) } // MEM fun writeMem(reg: Reg8, base: Reg64, offset: Int) = bytes(0x88, 0x80 or (reg.olindex shl 3) or (base.olindex shl 0)).also { int(offset) } fun writeMem(reg: Reg16, base: Reg64, offset: Int) = bytes(0x66, 0x89, 0x80 or (reg.olindex shl 3) or (base.olindex shl 0)).also { int(offset) } fun writeMem(reg: Reg32, base: Reg64, offset: Int) = bytes(0x89, 0x80 or (reg.olindex shl 3) or (base.olindex shl 0)).also { int(offset) } fun readMem(reg: Reg8, base: Reg64, offset: Int) = bytes(0x8A, 0x80 or (reg.olindex shl 3) or (base.olindex shl 0)).also { int(offset) } fun readMem(reg: Reg16, base: Reg64, offset: Int) = bytes(0x66, 0x8B, 0x80 or (reg.olindex shl 3) or (base.olindex shl 0)).also { int(offset) } fun readMem(reg: Reg32, base: Reg64, offset: Int) = bytes(0x8B, 0x80 or (reg.olindex shl 3) or (base.olindex shl 0)).also { int(offset) } fun writeMem(reg: Reg64, base: Reg64, offset: Int) { bytes(if (reg.extended) 0x4C else 0x48, 0x89, 0x80 or (reg.lindex shl 3) or (base.lindex shl 0)).also { int(offset) } } fun readMem(reg: Reg64, base: Reg64, offset: Int) { bytes(if (reg.extended) 0x4C else 0x48, 0x8B, 0x80 or (reg.lindex shl 3) or (base.lindex shl 0)).also { int(offset) } } fun movEaxEbpOffset(offset: Int) { bytes(0x8b, 0x85) int(offset) } fun cpuid(kind: Int) { movEax(kind) cpuid() } fun cpuid() { bytes(0x0F, 0xA2) } fun xchg(a: Reg64, b: Reg64) { if (a == b) error("no effect") if (a.index > b.index) return xchg(b, a) if (a != Reg64.RAX) error("Only allow RAX to exchange") bytes(0x48, 0x90 or (b.index shl 0)) } private fun _C0(dst: Reg32, src: Reg32) = 0b11_000_000 or (src.index shl 3) or (dst.index shl 0) private fun _C0(dst: Reg64, src: Reg64) = _C0(dst.to32(), src.to32()) fun add(dst: Reg32, src: Reg32) = bytes(0x01, _C0(dst, src)) fun or(dst: Reg32, src: Reg32) = bytes(0x09, _C0(dst, src)) fun and(dst: Reg32, src: Reg32): Unit = bytes(0x21, _C0(dst, src)) fun xor(dst: Reg32, src: Reg32): Unit = bytes(0x31, _C0(dst, src)) fun sub(dst: Reg32, src: Reg32) = bytes(0x29, _C0(dst, src)) val Int.fitsByte: Boolean get() = this.toByte().toInt() == this.toInt() fun sub(dst: Reg64, size: Int) { if (size.fitsByte) { bytes(0x48, 0x83, 0xE8 or (dst.olindex)) bytes(size) } else { bytes(0x48, 0x81, 0xE8 or (dst.olindex)) int(size) } } fun add(dst: Reg64, size: Int) { if (size.fitsByte) { bytes(0x48, 0x83, 0xC0 or (dst.olindex), size) } else { error("Doesn't fit byte") } } fun shl(dst: Reg32, src: Reg32): Unit = TODO() fun shr(dst: Reg32, src: Reg32): Unit = TODO() fun ushr(dst: Reg32, src: Reg32): Unit = TODO() fun shl(dst: Reg32, shift: Reg8): Unit { if (shift != Reg8.CL) error("Unsupported") bytes(0xD3, 0xE0 or dst.olindex) } fun shr(dst: Reg32, shift: Reg8): Unit { if (shift != Reg8.CL) error("Unsupported") bytes(0xD3, 0xF8 or dst.olindex) } fun ushr(dst: Reg32, shift: Reg8): Unit { if (shift != Reg8.CL) error("Unsupported") bytes(0xD3, 0xE8 or dst.olindex) } fun _mul(src: Reg32, signed: Boolean): Unit { if (src.extended) bytes(0x41) val sor = if (signed) 0x8 else 0 bytes(0xf7, 0xe0 or sor or (src.lindex shl 0)) } fun _div(src: Reg32, signed: Boolean): Unit { if (src.extended) bytes(0x49) val sor = if (signed) 0x8 else 0 bytes(0xf7, 0xf0 or sor or (src.lindex shl 0)) } fun mul(src: Reg32): Unit = _mul(src, signed = false) fun div(src: Reg32): Unit = _div(src, signed = false) fun imul(src: Reg32): Unit = _mul(src, signed = true) fun idiv(src: Reg32): Unit = _div(src, signed = true) fun mul(src: Reg64) = bytes(0x48).also { mul(Reg32(src.index)) } fun add(dst: Reg64, src: Reg64) = bytes(0x48).also { add(Reg32(dst.index), Reg32(src.index)) } fun mov(dst: Reg64, src: Reg64) { if (dst == src) return if (dst.index >= 8) TODO("Upper registers not implemented") bytes(0x48, 0x89, _C0(dst, src)) } fun mov(dst: Reg32, value: Int) = bytes(0xb8 + dst.index).also { int(value) } fun push(r: Reg64) { if (r.index < 8) { bytes(0x50 + r.index) } else { bytes(0x41, 0x50 + r.index - 7) } } fun pushRAX() = push(Reg64.RAX) fun pushRBX() = push(Reg64.RBX) fun popRAX() = pop(Reg64.RAX) fun popRBX() = pop(Reg64.RBX) fun pop(r: Reg64) { if (r.index < 8) { bytes(0x58 + r.index) } else { bytes(0x41, 0x58 + r.index - 7) } } fun cmp(l: Reg32, r: Reg32) = bytes(0x39, 0xC0 or (l.olindex shl 0) or (r.olindex shl 3)) fun cmp(l: Reg64, r: Reg64) = bytes(0x48).also { cmp(l.to32(), r.to32()) } fun cmp(l: Reg32, r: Int) { if (l == Reg32.EAX) { bytes(0x3D) int(r) } else { TODO() } } //fun jc(label: Label) = bytes(0x0F, 0x82).also { patch32(label) } fun je(label: Label) = bytes(0x0F, 0x84).also { patch32(label) } fun jne(label: Label) = bytes(0x0F, 0x85).also { patch32(label) } fun jl(label: Label) = bytes(0x0F, 0x8C).also { patch32(label) } fun jge(label: Label) = bytes(0x0F, 0x8D).also { patch32(label) } fun jle(label: Label) = bytes(0x0F, 0x8E).also { patch32(label) } fun jg(label: Label) = bytes(0x0F, 0x8F).also { patch32(label) } fun call(reg: Reg64) = bytes(0xFF, 0xD0 + reg.olindex) fun callAbsolute(value: Long) { mov(Reg64.RAX, value) call(Reg64.RAX) } fun call(label: Label) = bytes(0xe8).also { patch32(label) } fun jmp(label: Label) = bytes(0xe9).also { patch32(label) } fun patch32(label: Label) = patch(label, 4) fun nop() = bytes(0x90) fun movEax(value: Int) = mov(Reg32.EAX, value) fun movEdi(value: Int) = mov(Reg32.EDI, value) fun mov(reg: Reg64, value: Long) { bytes(0x48, 0xb8 or reg.olindex) long(value) } fun syscall() { bytes(0x0F, 0x05) } } open class BaseBuilder { private var pos = 0 private var data = ByteArray(1024) fun getBytes(): ByteArray { patch() return data.copyOf(pos) } private fun patch() { val oldpos = pos try { for (patch in patches) { val label = patch.label val relative = (label.offset - patch.offset) - patch.incr pos = patch.offset int(relative) } } finally { pos = oldpos } } private val patches = arrayListOf<Patch>() fun patch(label: Label, incr: Int = 4, size: Int = incr) { patches += Patch(label, pos, incr) for (n in 0 until size) bytes(0) } fun place(label: Label) { label.offset = pos } class Patch(val label: Label, val offset: Int, val incr: Int) class Label { var offset: Int = -1 } fun bytes(v: Int) { if (pos >= data.size) { data = data.copyOf(((data.size + 2) * 2)) } data[pos++] = v.toByte() } fun bytes(a: Int, b: Int) = run { bytes(a); bytes(b) } fun bytes(a: Int, b: Int, c: Int) = run { bytes(a); bytes(b); bytes(c) } fun bytes(a: Int, b: Int, c: Int, d: Int) = run { bytes(a); bytes(b); bytes(c); bytes(d) } fun bytes(a: Int, b: Int, c: Int, d: Int, e: Int) = run { bytes(a); bytes(b); bytes(c); bytes(d); bytes(e) } fun short(v: Int) { bytes((v ushr 0) and 0xFF, (v ushr 8) and 0xFF) } fun int(v: Int) { short((v ushr 0) and 0xFFFF) short((v ushr 16) and 0xFFFF) } fun long(v: Long) { int((v ushr 0).toInt()) int((v ushr 32).toInt()) } } inline class Reg8(val index: Int) { companion object { val AL = Reg8(0) val CL = Reg8(1) val DL = Reg8(2) val BL = Reg8(3) } val extended get() = index >= 8 val lindex get() = index and 0x7 val olindex get() = if (extended) error("Unsupported extended") else lindex } inline class Reg16(val index: Int) { companion object { val AX = Reg16(0) val CX = Reg16(1) val DX = Reg16(2) val BX = Reg16(3) val SP = Reg16(4) val BP = Reg16(5) val SI = Reg16(6) val DI = Reg16(7) } val extended get() = index >= 8 val lindex get() = index and 0x7 val olindex get() = if (extended) error("Unsupported extended") else lindex fun to32() = Reg32(index) fun to64() = Reg64(index) } inline class Reg32(val index: Int) { companion object { val EAX = Reg32(0) val ECX = Reg32(1) val EDX = Reg32(2) val EBX = Reg32(3) val ESP = Reg32(4) val EBP = Reg32(5) val ESI = Reg32(6) val EDI = Reg32(7) val R8D = Reg32(8) val R9D = Reg32(9) val R10D = Reg32(10) val R11D = Reg32(11) val R12D = Reg32(12) val R13D = Reg32(13) val R14D = Reg32(14) val R15D = Reg32(15) val REGS = arrayOf(EAX, ECX, EDX, EBX) } val extended get() = index >= 8 val lindex get() = index and 0x7 val olindex get() = if (extended) error("Unsupported extended") else lindex fun to16() = Reg16(index) fun to64() = Reg64(index) } inline class Reg64(val index: Int) { companion object { val RAX = Reg64(0b0_000) val RCX = Reg64(0b0_001) val RDX = Reg64(0b0_010) val RBX = Reg64(0b0_011) val RSP = Reg64(0b0_100) val RBP = Reg64(0b0_101) val RSI = Reg64(0b0_110) val RDI = Reg64(0b0_111) // Extended val R8 = Reg64(0b1_000) val R9 = Reg64(0b1_001) val R10 = Reg64(0b1_010) val R11 = Reg64(0b1_011) val R12 = Reg64(0b1_100) val R13 = Reg64(0b1_101) val R14 = Reg64(0b1_110) val R15 = Reg64(0b1_111) } val extended get() = index >= 8 val lindex get() = index and 0b111 val olindex get() = if (extended) error("Unsupported extended") else lindex fun to16() = Reg16(index) fun to32() = Reg32(index) } inline class RegXmm(val index: Int) { companion object { val XMM0 = RegXmm(0) val XMM1 = RegXmm(1) val XMM2 = RegXmm(2) val XMM3 = RegXmm(3) val XMM4 = RegXmm(4) val XMM5 = RegXmm(5) val XMM6 = RegXmm(6) val XMM7 = RegXmm(7) val XMM8 = RegXmm(8) val XMM9 = RegXmm(9) val XMM10 = RegXmm(10) val XMM11 = RegXmm(11) val XMM12 = RegXmm(12) val XMM13 = RegXmm(13) val XMM14 = RegXmm(14) val XMM15 = RegXmm(15) } val extended get() = index >= 8 val lindex get() = index and 0x7 val olindex get() = if (extended) error("Unsupported extended") else lindex fun to16() = Reg16(index) fun to32() = Reg32(index) } /* import kotlinx.cinterop.* import platform.posix.* fun main(args: Array<String>) { val code = ExecutableData(byteArrayOf(0xb8.toByte(), 0x07, 0, 0, 0, 0xc3.toByte())) // MOV EAX, 1; RETN val func = code.ptr.reinterpret<CFunction<() -> Int>>() println("Hello: " + func()) } class ExecutableData(data: ByteArray) { val len = data.size //val len = getpagesize() val ptr = mmap( null, len.toLong(), PROT_READ or PROT_WRITE or PROT_EXEC, MAP_ANONYMOUS or MAP_SHARED, -1, 0 )?.reinterpret<ByteVar>() ?: error("Couldn't reserve memory") init { for (n in 0 until data.size) ptr[n] = data[n] } fun free() { munmap(ptr, len.toLong()) } } */ /* // https://msdn.microsoft.com/en-us/library/9z1stfyw.aspx Register Status Use RAX Volatile Return value register RCX Volatile First integer argument RDX Volatile Second integer argument R8 Volatile Third integer argument R9 Volatile Fourth integer argument R10:R11 Volatile Must be preserved as needed by caller; used in syscall/sysret instructions R12:R15 Nonvolatile Must be preserved by callee RDI Nonvolatile Must be preserved by callee RSI Nonvolatile Must be preserved by callee RBX Nonvolatile Must be preserved by callee RBP Nonvolatile May be used as a frame pointer; must be preserved by callee RSP Nonvolatile Stack pointer XMM0, YMM0 Volatile First FP argument; first vector-type argument when __vectorcall is used XMM1, YMM1 Volatile Second FP argument; second vector-type argument when __vectorcall is used XMM2, YMM2 Volatile Third FP argument; third vector-type argument when __vectorcall is used XMM3, YMM3 Volatile Fourth FP argument; fourth vector-type argument when __vectorcall is used XMM4, YMM4 Volatile Must be preserved as needed by caller; fifth vector-type argument when __vectorcall is used XMM5, YMM5 Volatile Must be preserved as needed by caller; sixth vector-type argument when __vectorcall is used XMM6:XMM15, YMM6:YMM15 Nonvolatile (XMM), Volatile (upper half of YMM) Must be preserved as needed by callee. YMM registers must be preserved as needed by caller. */
mit
4025594bf8712138d31ddacab921d778
30.698198
162
0.603808
2.811988
false
false
false
false
Litote/kmongo
kmongo-shared/src/main/kotlin/org/litote/kmongo/util/PatternUtil.kt
1
2597
/* * Copyright (C) 2016/2022 Litote * * 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.litote.kmongo.util import java.util.HashMap import java.util.regex.Pattern /** * Provides pattern options copied from mongo [PatternCodec]. */ object PatternUtil { /** * Returns pattern options as string. */ fun getOptionsAsString(pattern: Pattern): String { var flags = pattern.flags() val buf = StringBuilder() for (flag in RegexFlag.values()) { if (pattern.flags() and flag.javaFlag > 0) { buf.append(flag.flagChar) flags -= flag.javaFlag } } require(flags <= 0) { "some flags could not be recognized." } return buf.toString() } private const val GLOBAL_FLAG = 256 private enum class RegexFlag( val javaFlag: Int, val flagChar: Char, val unsupported: String? ) { CANON_EQ( Pattern.CANON_EQ, 'c', "Pattern.CANON_EQ" ), UNIX_LINES(Pattern.UNIX_LINES, 'd', "Pattern.UNIX_LINES"), GLOBAL( GLOBAL_FLAG, 'g', null ), CASE_INSENSITIVE( Pattern.CASE_INSENSITIVE, 'i', null ), MULTILINE(Pattern.MULTILINE, 'm', null), DOTALL( Pattern.DOTALL, 's', "Pattern.DOTALL" ), LITERAL( Pattern.LITERAL, 't', "Pattern.LITERAL" ), UNICODE_CASE( Pattern.UNICODE_CASE, 'u', "Pattern.UNICODE_CASE" ), COMMENTS(Pattern.COMMENTS, 'x', null); companion object { private val BY_CHARACTER: MutableMap<Char, RegexFlag> = HashMap() fun getByCharacter(ch: Char): RegexFlag? { return BY_CHARACTER[ch] } init { for (flag in values()) { BY_CHARACTER[flag.flagChar] = flag } } } } }
apache-2.0
9606fc5e5a7ab7cc94e5fd984b11bcce
26.0625
77
0.546785
4.386824
false
false
false
false
javalite/activejdbc
activejdbc-kt/src/test/kt/org/javalite/activejdbc/utils/KtJdbcProperties.kt
1
925
/* * COPYRIGHT © ITAMETIS - TOUS DROITS RÉSERVÉS * Pour plus d'information veuillez contacter : [email protected] */ package org.javalite.activejdbc.utils import java.io.IOException import java.util.Properties object KtJdbcProperties { val driver:String val url:String val user:String val password:String val db:String init { try { val properties = Properties() properties.load(KtJdbcProperties::class.java.getResourceAsStream("/jdbc.properties")) driver = properties.getProperty("jdbc.driver") ?: "" url = properties.getProperty("jdbc.url") ?: "" user = properties.getProperty("jdbc.user") ?: "" password = properties.getProperty("jdbc.password") ?: "" db = properties.getProperty("db") ?: "" } catch (ex:IOException) { throw RuntimeException(ex) } } }
apache-2.0
5da267efccf3fc5330d09b73278a6a7c
27.8125
97
0.62039
4.171946
false
false
false
false
OpenConference/OpenConference-android
app/src/main/java/com/openconference/model/database/InstantParcelableTypeAdapter.kt
1
678
package com.openconference.model.database import android.os.Parcel import com.ryanharter.auto.value.parcel.TypeAdapter import org.threeten.bp.Instant /** * A TypeAdapter for Auto-Value parcelable plugin * * @author Hannes Dorfmann */ class InstantParcelableTypeAdapter : TypeAdapter<Instant> { private val NULL_VALUE = -1L; override fun toParcel(value: Instant?, dest: Parcel) { if (value == null) dest.writeLong(NULL_VALUE) else dest.writeLong(value.toEpochMilli()) } override fun fromParcel(parcel: Parcel): Instant? { val ms = parcel.readLong() return if (ms == NULL_VALUE) null else Instant.ofEpochMilli(ms) } }
apache-2.0
8b934e4057b547ad9ca3647f9ebb92c5
21.633333
59
0.702065
3.874286
false
false
false
false
cretz/asmble
compiler/src/main/kotlin/asmble/run/jvm/ModuleBuilder.kt
1
2733
package asmble.run.jvm import asmble.ast.Node import asmble.compile.jvm.* import asmble.util.Logger import org.objectweb.asm.ClassReader import org.objectweb.asm.ClassVisitor import org.objectweb.asm.Opcodes interface ModuleBuilder<T : Module> { fun build(imports: Module.ImportResolver, mod: Node.Module, className: String, name: String?): T class Compiled( val packageName: String = "", val logger: Logger = Logger.Print(Logger.Level.OFF), val classLoader: SimpleClassLoader = SimpleClassLoader(Compiled::class.java.classLoader, logger), val adjustContext: (ClsContext) -> ClsContext = { it }, val includeBinaryInCompiledClass: Boolean = false, val defaultMaxMemPages: Int = 1 ) : ModuleBuilder<Module.Compiled> { override fun build( imports: Module.ImportResolver, mod: Node.Module, className: String, name: String? ): Module.Compiled { val ctx = ClsContext( packageName = packageName, className = className, mod = mod, logger = logger, includeBinary = includeBinaryInCompiledClass ).let(adjustContext) AstToAsm.fromModule(ctx) return Module.Compiled(mod, classLoader.fromBuiltContext(ctx), name, ctx.mem, imports, defaultMaxMemPages) } open class SimpleClassLoader( parent: ClassLoader, logger: Logger, val splitWhenTooLarge: Boolean = true ) : ClassLoader(parent), Logger by logger { fun fromBuiltContext(ctx: ClsContext): Class<*> { trace { "Computing frames for ASM class:\n" + ctx.cls.toAsmString() } val writer = if (splitWhenTooLarge) AsmToBinary else AsmToBinary.noSplit return writer.fromClassNode(ctx.cls).let { bytes -> debug { "ASM class:\n" + bytes.asClassNode().toAsmString() } val prefix = if (ctx.packageName.isNotEmpty()) ctx.packageName + "." else "" defineClass("$prefix${ctx.className}", bytes, 0, bytes.size) } } fun addClass(bytes: ByteArray) { // Just get the name var className = "" ClassReader(bytes).accept(object : ClassVisitor(Opcodes.ASM5) { override fun visit(a: Int, b: Int, name: String, c: String?, d: String?, e: Array<out String>?) { className = name.replace('/', '.') } }, ClassReader.SKIP_CODE) defineClass(className, bytes, 0, bytes.size) } } } }
mit
2ce688112f5025eec5a5fe08168e1969
41.061538
118
0.578485
4.736568
false
false
false
false
kishmakov/Kitchen
clients/jetpack/src/main/kotlin/io/magnaura/clients/jetpack/view/CanvasView.kt
1
908
package io.magnaura.clients.jetpack.view import androidx.compose.foundation.Text import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import io.magnaura.clients.jetpack.model.Canvas val CANVAS_BACKGROUND = Color(0x0FF0F0F0) @Composable fun CanvasView(canvas: Canvas) { val canvasModifier = Modifier .background(CANVAS_BACKGROUND) .fillMaxWidth() .fillMaxHeight() Row(modifier = canvasModifier) { Text( canvas.text, color = Color.DarkGray, fontSize = 72.sp, modifier = Modifier.padding( horizontal = 100.dp, vertical = 100.dp ) ) } }
gpl-3.0
5c06bf57cdedb803df2d6956fc032090
26.545455
47
0.679515
4.146119
false
false
false
false
dfernandez79/swtlin
builder/src/main/kotlin/swtlin/Shell.kt
1
1408
package swtlin import org.eclipse.swt.widgets.Control import org.eclipse.swt.widgets.Shell import swtlin.core.ControlBuilder import swtlin.core.ControlBuilderContainer import swtlin.core.IdentifiedControlBuilderContainer fun Shell.children(block: ShellChildrenDescription.() -> Unit): Shell { val description = ShellChildrenDescription(this) description.block() description.createChildren() return this } class ShellChildrenDescription(private val shell: Shell) : ControlBuilderContainer { private val container = IdentifiedControlBuilderContainer() private var _layout: LayoutDescription? = null var layout: LayoutDescription set (value) { _layout = value } get() { if (_layout != null) { return _layout!! } else if (shell.layout != null) { return shell.layout.toLayoutDescription() } else { return NullLayoutDescription } } override fun add(id: String?, builder: ControlBuilder<*>) { container.add(id, builder) } fun size(width: Int, height: Int) { shell.setSize(width, height) } fun createChildren() { val refs = mutableMapOf<String, Control>() val pairs = container.children.map { it.builder to it.createControl(shell, refs) } layout.layout(shell, pairs, refs) } }
apache-2.0
2d5c2fd738ec57b0e8f7b0148dae02d0
28.957447
90
0.647727
4.601307
false
false
false
false
vsch/SmartData
src/com/vladsch/smart/SmartSegmentedCharSequence.kt
1
13257
/* * Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.vladsch.smart import java.util.* open class SmartSegmentedCharSequence : SmartCharSequenceBase<SmartCharSequence>, TrackingCharSequenceMarkerHolder { protected val myVersion: SmartVersion protected val myCacheVersion: SmartDependentRunnableVersionHolder private var myLengths = IntArray(0) private var myVariableContent: Boolean = false val segments: List<SmartCharSequence> private var myLastSegment: Int? = null private var myLengthSpan: Int = 0 override fun addStats(stats: SmartCharSequence.Stats) { var maxNesting = 0 for (segment in segments) { var childStats = SmartCharSequence.Stats() segment.addStats(childStats) stats.segments += childStats.segments maxNesting.minLimit(childStats.nesting) } stats.nesting = maxNesting + 1 } constructor(vararg charSequences: CharSequence) { val smartCharSequences = smartList(charSequences.toList()) segments = smartCharSequences myVersion = SmartDependentVersionHolder(segments) myCacheVersion = SmartDependentRunnableVersionHolder(this, Runnable { computeCachedData() }) } constructor(charSequences: Collection<CharSequence>) { segments = smartList(charSequences) myVersion = SmartDependentVersionHolder(segments) myCacheVersion = SmartDependentRunnableVersionHolder(this, Runnable { computeCachedData() }) } internal fun computeCachedData() { val lengths = IntArray(segments.size + 1) var length = 0 var i = 1 lengths[0] = 0 var variableContent = false for (charSequence in segments) { length += charSequence.length lengths[i++] = length if (!variableContent) { variableContent = charSequence.version.isMutable } } myLengths = lengths myVariableContent = variableContent myLastSegment = 0 i = 1 while (i < lengths.size) i = i.shl(1) myLengthSpan = i } val isVariableContent: Boolean get() { myCacheVersion.nextVersion() return myVariableContent } override val length: Int get() { myCacheVersion.nextVersion() return myLengths[myLengths.size - 1] } public override fun charAtImpl(index: Int): Char { val i = getCharSequenceIndex(index) if (i >= 0) { myLastSegment = i return segments[i][index - myLengths[i]] } throw IndexOutOfBoundsException("charAt(" + index + ") is not within underlying char sequence range [0, " + myLengths[myLengths.size - 1]) } override fun getVersion(): SmartVersion { return myVersion } fun getSequence(segmentIndex: Int): SmartCharSequence { myCacheVersion.nextVersion() return segments[segmentIndex] } fun startIndex(segmentIndex: Int): Int { myCacheVersion.nextVersion() return myLengths[segmentIndex] } fun endIndex(segmentIndex: Int): Int { myCacheVersion.nextVersion() return myLengths[segmentIndex + 1] } fun length(segmentIndex: Int): Int { myCacheVersion.nextVersion() return myLengths[segmentIndex + 1] - myLengths[segmentIndex] } fun lastIndex(segmentIndex: Int): Int { myCacheVersion.nextVersion() return if (myLengths[segmentIndex + 1] > myLengths[segmentIndex]) myLengths[segmentIndex + 1] - 1 else myLengths[segmentIndex] } override fun getMarkers(id: String?): List<TrackedLocation> { myCacheVersion.nextVersion() if (myVariableContent) { val markers = ArrayList<TrackedLocation>() val iMax = segments.size for (i in 0..iMax - 1) { val charSequence = segments[i] if (charSequence is SmartCharSequenceMarker && (id == null || id == charSequence.id)) { val index = myLengths[i] var trackedLocation = TrackedLocation(index, 0, charSequence) if (index > 0) { // have real previous val prevLocation = trackedSourceLocation(index - 1) trackedLocation = trackedLocation.withPrevClosest(prevLocation.index, prevLocation.offset, prevLocation.source) } if (myLengths[i + 1] < length) { // there is a next real segment after the marker val nextIndex = myLengths[i + 1] val nextLocation = trackedSourceLocation(nextIndex) trackedLocation = trackedLocation.withPrevClosest(nextLocation.index, nextLocation.offset, nextLocation.source) } markers.add(trackedLocation) } else { val locations = charSequence.getMarkers(id) if (!locations.isEmpty()) { // re-map for (location in locations) { markers.add(location.withIndex(myLengths[i] + location.index).withPrevClosest(myLengths[i] + location.prevIndex).withNextClosest(myLengths[i] + location.nextIndex)) } } } } if (!markers.isEmpty()) return markers } return TrackedLocation.EMPTY_LIST } override fun getCharsImpl(dst: CharArray, dstOffset: Int) { myCacheVersion.nextVersion() val iMax = segments.size for (i in 0..iMax - 1) { segments[i].getChars(dst, dstOffset + myLengths[i]) } } override fun getSourceLocations(sources: ArrayList<Any>, locations: ArrayList<Range>, sourceLocations: ArrayList<Range>) { super.getSourceLocations(sources, locations, sourceLocations) } protected fun getCharSequenceIndex(index: Int): Int { var lastSegment = myLastSegment if (lastSegment != null) { if (index >= myLengths[lastSegment] && index < myLengths[lastSegment + 1]) return lastSegment // see if it is next or previous if (lastSegment + 2 <= myLengths.lastIndex && index >= myLengths[lastSegment + 1] && index < myLengths[lastSegment + 2]) { lastSegment++ myLastSegment = lastSegment return lastSegment } if (lastSegment > 0 && index >= myLengths[lastSegment - 1] && index < myLengths[lastSegment]) { lastSegment-- myLastSegment = lastSegment return lastSegment } } else { // need to update indices myCacheVersion.nextVersion() } return adjustBinaryIndex(getIndexBinary(index)) // return getIndexLinear(index) // val result = getIndexLinear(index) // var fastResult = getIndexBinary(index) // // if (result != fastResult) { // println("result:$result != fastResult:$fastResult") // assert(result == fastResult, { "result:$result != fastResult:$fastResult" }) // } // // return result } internal fun getIndexLinear(index: Int): Int { for (i in 1..myLengths.size - 1) { if (index < myLengths[i] || index == myLengths[i] && i + 1 == myLengths.size) { return i - 1 } } return -1 } internal fun adjustBinaryIndex(index: Int): Int { @Suppress("NAME_SHADOWING") var index = index // since we can have 0 length segments we need to skip them if (index < 0) return index while (index + 1 < myLengths.size - 1 && myLengths[index] == myLengths[index + 1]) index++ return if (index >= myLengths.size - 1) -1 else index } internal fun getIndexBinary(index: Int): Int { val iMax = myLengths.size if (iMax >= 0) { var i = myLengthSpan.shr(1) - 1 var span = myLengthSpan.shr(2) loop@ while (true) { val len = myLengths[i] if (index <= len) { if (span == 0 || index == len) { return if (index == len && i < iMax - 1) i else i - 1 } i -= span span /= 2 } else { if (span == 0) { return i } i += span span /= 2 while (i >= iMax) { if (span == 0) break@loop i -= span span /= 2 } } } } return -1 } override fun properSubSequence(startIndex: Int, endIndex: Int): SmartCharSequence { val iStart = getCharSequenceIndex(startIndex) val iEnd = getCharSequenceIndex(endIndex) if (iStart >= 0 && iEnd >= 0 && iStart <= iEnd) { if (iStart == iEnd) { // subSequence of one of the sequences return segments[iStart].subSequence(startIndex - myLengths[iStart], endIndex - myLengths[iStart]) } else if (iStart == 0 && startIndex == 0 && iEnd == myLengths.size - 2 && endIndex == myLengths[iEnd + 1]) { // just a copy of us return this } else { // partial of our sequence val trackingSequences = trackingSequences(segments, iStart, startIndex - myLengths[iStart], iEnd, endIndex - myLengths[iEnd]) if (trackingSequences.size == 1) { return trackingSequences[0] } else { return SmartSegmentedCharSequence(trackingSequences) } } } // won't happen but we leave it in throw IndexOutOfBoundsException("subSequence($startIndex, $endIndex) is not within sequence list range of [0, $length)") } override fun flattened(sequences: ArrayList<SmartCharSequence>) { for (charSequence in segments) { charSequence.flattened(sequences) } } override fun trackedSourceLocation(index: Int): TrackedLocation { val i = getCharSequenceIndex(index) if (i >= 0) { val trackedLocation = segments[i].trackedSourceLocation(index - myLengths[i]) if (myLengths[i] == 0) return trackedLocation return trackedLocation.withIndex(trackedLocation.index + myLengths[i]) .withPrevClosest(trackedLocation.prevIndex + myLengths[i]) .withNextClosest(trackedLocation.nextIndex + myLengths[i]) } throw IndexOutOfBoundsException("charAt(" + index + ") is not within underlying char sequence range [0, " + myLengths[myLengths.size - 1]) } override fun trackedLocation(source: Any?, offset: Int): TrackedLocation? { var i = 0 myCacheVersion.nextVersion() for (charSequence in segments) { val trackedLocation = charSequence.trackedLocation(source, offset) if (trackedLocation != null) { if (myLengths[i] == 0) return trackedLocation else return trackedLocation.withIndex(trackedLocation.index + myLengths[i]) .withPrevClosest(trackedLocation.prevIndex + myLengths[i]) .withNextClosest(trackedLocation.nextIndex + myLengths[i]) } i++ } return null } override fun splicedWith(other: CharSequence?): SmartCharSequence? { if (other == null) return null val merged = segments[segments.size - 1].splicedWith(other) if (merged != null) { val smartCharSequences = ArrayList<SmartCharSequence>(segments.size) if (segments.size > 1) System.arraycopy(segments, 0, smartCharSequences, 0, segments.size - 1) smartCharSequences[segments.size - 1] = merged return SmartSegmentedCharSequence(smartCharSequences) } return null } }
apache-2.0
2f752a12765879da9ae496ad573f9aa1
37.094828
192
0.579241
5.211085
false
false
false
false
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/data/user/UserRepository.kt
1
3249
package mil.nga.giat.mage.data.user import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.util.Log import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import mil.nga.giat.mage.network.api.UserService import mil.nga.giat.mage.sdk.datastore.user.Event import mil.nga.giat.mage.sdk.datastore.user.User import mil.nga.giat.mage.sdk.datastore.user.UserHelper import mil.nga.giat.mage.sdk.utils.MediaUtility import okhttp3.ResponseBody import java.io.File import javax.inject.Inject class UserRepository @Inject constructor( @ApplicationContext private val context: Context, private val userService: UserService ) { private val userHelper = UserHelper.getInstance(context) suspend fun syncIcons(event: Event) = withContext(Dispatchers.IO) { val users = userHelper.getUsersInEvent(event) for (user in users) { try { syncIcon(user) } catch (e: Exception) { Log.e(LOG_NAME, "Error syncing user icon", e) } } } private suspend fun syncIcon(user: User) { val path = "${MediaUtility.getUserIconDirectory(context)}/${user.id}.png" val file = File(path) if (file.exists()) { file.delete() } val response = userService.getIcon(user.remoteId) val body = response.body() if (response.isSuccessful && body != null) { saveIcon(body, file) compressIcon(file) userHelper.setIconPath(user, path) } } private fun saveIcon(body: ResponseBody, file: File) { body.let { it.byteStream().use { input -> file.outputStream().use { output -> input.copyTo(output) } } } } private fun compressIcon(file: File) { val sampleSize = getSampleSize(file) file.inputStream().use { inputStream -> val options = BitmapFactory.Options() options.inSampleSize = sampleSize val bitmap = BitmapFactory.decodeStream(inputStream, null, options) bitmap?.let { file.outputStream().use { outputStream -> it.compress(Bitmap.CompressFormat.PNG, 100, outputStream) } } } } private fun getSampleSize(file: File): Int { val options = BitmapFactory.Options() options.inJustDecodeBounds = true return file.inputStream().use { inputStream -> BitmapFactory.decodeStream(inputStream, null, options) val height = options.outHeight val width = options.outWidth var inSampleSize = 1 if (height > MAX_DIMENSION || width > MAX_DIMENSION) { // Calculate the largest inSampleSize value that is a power of 2 and will ensure // height and width is smaller than the max image we can process while (height / inSampleSize >= MAX_DIMENSION && height / inSampleSize >= MAX_DIMENSION) { inSampleSize *= 2 } } inSampleSize } } companion object { private val LOG_NAME = UserRepository::class.java.name private const val MAX_DIMENSION = 200 } }
apache-2.0
300c150d7f7a743d724507b5d54476b8
30.862745
102
0.646661
4.475207
false
false
false
false
vhromada/Catalog-Spring
src/test/kotlin/cz/vhromada/catalog/web/common/SeasonUtils.kt
1
2341
package cz.vhromada.catalog.web.common import cz.vhromada.catalog.entity.Season import cz.vhromada.catalog.web.fo.SeasonFO import cz.vhromada.common.entity.Language import org.assertj.core.api.SoftAssertions.assertSoftly /** * A class represents utility class for seasons. * * @author Vladimir Hromada */ object SeasonUtils { /** * Returns FO for season. * * @return FO for season */ fun getSeasonFO(): SeasonFO { return SeasonFO(id = CatalogUtils.ID, number = CatalogUtils.NUMBER.toString(), startYear = CatalogUtils.YEAR.toString(), endYear = (CatalogUtils.YEAR + 1).toString(), language = Language.EN, subtitles = listOf(Language.CZ), note = CatalogUtils.NOTE, position = CatalogUtils.POSITION) } /** * Returns season. * * @return season */ fun getSeason(): Season { return Season(id = CatalogUtils.ID, number = CatalogUtils.NUMBER, startYear = CatalogUtils.YEAR, endYear = CatalogUtils.YEAR + 1, language = Language.EN, subtitles = listOf(Language.CZ), note = CatalogUtils.NOTE, position = CatalogUtils.POSITION) } /** * Asserts season deep equals. * * @param expected expected FO for season * @param actual actual season */ fun assertSeasonDeepEquals(expected: SeasonFO?, actual: Season?) { assertSoftly { it.assertThat(expected).isNotNull it.assertThat(actual).isNotNull } assertSoftly { it.assertThat(actual!!.id).isEqualTo(expected!!.id) it.assertThat(actual.number).isEqualTo(Integer.parseInt(expected.number)) it.assertThat(actual.startYear).isEqualTo(Integer.parseInt(expected.startYear)) it.assertThat(actual.endYear).isEqualTo(Integer.parseInt(expected.endYear)) it.assertThat<Language>(actual.language).isEqualTo(expected.language) it.assertThat<Language>(actual.subtitles).isEqualTo(expected.subtitles) it.assertThat(actual.note).isEqualTo(expected.note) it.assertThat(actual.position).isEqualTo(expected.position) } } }
mit
d5077c6205d5b9b532102d809f4d9133
32.442857
91
0.612132
4.738866
false
false
false
false
google-developer-training/android-demos
DonutTracker/NavigationUI/app/src/main/java/com/android/samples/donuttracker/coffee/CoffeeList.kt
2
2737
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.samples.donuttracker.coffee import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.app.NotificationManagerCompat import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.navigation.findNavController import androidx.navigation.fragment.findNavController import com.android.samples.donuttracker.databinding.CoffeeListBinding import com.android.samples.donuttracker.storage.SnackDatabase /** * Fragment containing the RecyclerView which shows the current list of coffees being tracked. */ class CoffeeList : Fragment() { private lateinit var coffeeListViewModel: CoffeeListViewModel private val adapter = CoffeeListAdapter( onEdit = { coffee -> findNavController().navigate( CoffeeListDirections.actionCoffeeListToCoffeeEntryDialogFragment(coffee.id) ) }, onDelete = { coffee -> NotificationManagerCompat.from(requireContext()).cancel(coffee.id.toInt()) coffeeListViewModel.delete(coffee) } ) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return CoffeeListBinding.inflate(inflater, container, false).root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val binding = CoffeeListBinding.bind(view) val coffeeDao = SnackDatabase.getDatabase(requireContext()).coffeeDao() coffeeListViewModel = ViewModelProvider(this, CoffeeViewModelFactory(coffeeDao)) .get(CoffeeListViewModel::class.java) coffeeListViewModel.coffeeList.observe(viewLifecycleOwner) { coffees -> adapter.submitList(coffees) } binding.recyclerView.adapter = adapter binding.fab.setOnClickListener { fabView -> fabView.findNavController().navigate( CoffeeListDirections.actionCoffeeListToCoffeeEntryDialogFragment() ) } } }
apache-2.0
9a6097241903688c943617d5e2975d85
35.013158
94
0.722689
5.040516
false
false
false
false
artfable/telegram-api-java
src/main/kotlin/com/artfable/telegram/api/Chat.kt
1
781
package com.artfable.telegram.api import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty /** * @author artfable * 22.01.17 */ @JsonIgnoreProperties(ignoreUnknown = true) data class Chat( @JsonProperty("id") val id: Long, @JsonProperty("type") val type: ChatType, @JsonProperty("title") val title: String? = null, @JsonProperty("username") val username: String? = null, @JsonProperty("first_name") val firstName: String? = null, @JsonProperty("last_name") val lastName: String? = null, @JsonProperty("all_members_are_administrators") val allMembersAreAdministrators: Boolean? = null ) //type String “private”, “group”, “supergroup” or “channel”
mit
192bff498626304335158c57eea5a0f8
33.818182
104
0.700654
3.984375
false
false
false
false
Sevran/DnDice
app/src/main/java/io/deuxsept/dndice/Utils/SwipeableRecyclerViewTouchListener.kt
1
15450
package io.deuxsept.dndice.Utils /* * Copyright 2013 Google Inc. * Copyright 2015 Bruno Romeu Nunes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.graphics.Rect import android.os.SystemClock import android.support.v7.widget.RecyclerView import android.view.MotionEvent import android.view.VelocityTracker import android.view.View import android.view.ViewConfiguration import android.view.ViewGroup import android.widget.ListView import java.util.ArrayList import java.util.Collections /** * A [View.OnTouchListener] that makes the list items in a [android.support.v7.widget.RecyclerView] * dismissable by swiping. * * * * Example usage: * * * * SwipeDismissRecyclerViewTouchListener touchListener = * new SwipeDismissRecyclerViewTouchListener( * listView, * new SwipeDismissRecyclerViewTouchListener.OnDismissCallback() { * public void onDismiss(ListView listView, int[] reverseSortedPositions) { * for (int position : reverseSortedPositions) { * adapter.remove(adapter.getItem(position)); * } * adapter.notifyDataSetChanged(); * } * }); * listView.setOnTouchListener(touchListener); * listView.setOnScrollListener(touchListener.makeScrollListener()); * * * * * This class Requires API level 12 or later due to use of [ ]. */ class SwipeableRecyclerViewTouchListener /** * Constructs a new swipe touch listener for the given android.support.v7.widget.RecyclerView * @param RecyclerView The recycler view whose items should be dismissable by swiping. * * * @param Listener The listener for the swipe events. */ (private val mRecyclerView: RecyclerView, private val mFgID: Int, private val mBgID: Int, private val mSwipeListener: SwipeableRecyclerViewTouchListener.SwipeListener) : RecyclerView.OnItemTouchListener { override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) { } // Cached ViewConfiguration and system-wide constant values private val mSlop: Int private val mMinFlingVelocity: Int private val mMaxFlingVelocity: Int private val ANIMATION_FAST: Long = 300 private val ANIMATION_WAIT: Long = 300 private var mViewWidth = 1 // 1 and not 0 to prevent dividing by zero // Transient properties private val mPendingDismisses = ArrayList<PendingDismissData>() private var mDismissAnimationRefCount = 0 private var mDownX: Float = 0.toFloat() private var mDownY: Float = 0.toFloat() private var mSwiping: Boolean = false private var mSwipingSlop: Int = 0 private var mVelocityTracker: VelocityTracker? = null private var mDownPosition: Int = 0 private var mDownView: View? = null private var mPaused: Boolean = false private var mFinalDelta: Float = 0.toFloat() // Foreground view (to be swiped) // background view (to show) private var mFgView: View? = null private var mBgView: View? = null init { val vc = ViewConfiguration.get(mRecyclerView.context) mSlop = vc.scaledTouchSlop mMinFlingVelocity = vc.scaledMinimumFlingVelocity * 16 mMaxFlingVelocity = vc.scaledMaximumFlingVelocity /** * This will ensure that this SwipeableRecyclerViewTouchListener is paused during list view scrolling. * If a scroll listener is already assigned, the caller should still pass scroll changes through * to this listener. */ mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) { setEnabled(newState != RecyclerView.SCROLL_STATE_DRAGGING) } override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { } }) } /** * Enables or disables (pauses or resumes) watching for swipe-to-dismiss gestures. * @param enabled Whether or not to watch for gestures. */ fun setEnabled(enabled: Boolean) { mPaused = !enabled } override fun onInterceptTouchEvent(rv: RecyclerView, motionEvent: MotionEvent): Boolean { return handleTouchEvent(motionEvent) } override fun onTouchEvent(rv: RecyclerView, motionEvent: MotionEvent) { handleTouchEvent(motionEvent) } private fun handleTouchEvent(motionEvent: MotionEvent): Boolean { if (mViewWidth < 2) { mViewWidth = mRecyclerView.width } when (motionEvent.actionMasked) { MotionEvent.ACTION_DOWN -> { if (!mPaused) { // Find the child view that was touched (perform a hit test) val rect = Rect() val childCount = mRecyclerView.childCount val listViewCoords = IntArray(2) mRecyclerView.getLocationOnScreen(listViewCoords) val x = motionEvent.rawX.toInt() - listViewCoords[0] val y = motionEvent.rawY.toInt() - listViewCoords[1] var child: View for (i in 0..childCount - 1) { child = mRecyclerView.getChildAt(i) child.getHitRect(rect) if (rect.contains(x, y)) { mDownView = child break } } if (mDownView != null) { mDownX = motionEvent.rawX mDownY = motionEvent.rawY mDownPosition = mRecyclerView.getChildAdapterPosition(mDownView) mVelocityTracker = VelocityTracker.obtain() mVelocityTracker!!.addMovement(motionEvent) mFgView = mDownView!!.findViewById(mFgID) } } } MotionEvent.ACTION_CANCEL -> { if (mVelocityTracker != null) { if (mDownView != null && mSwiping) { // cancel mFgView!!.animate().translationX(0f).setDuration(ANIMATION_FAST).setListener(null) } mVelocityTracker!!.recycle() mVelocityTracker = null mDownX = 0f mDownY = 0f mDownView = null mDownPosition = ListView.INVALID_POSITION mSwiping = false mBgView = null } } MotionEvent.ACTION_UP -> { if (mVelocityTracker != null) { mFinalDelta = motionEvent.rawX - mDownX mVelocityTracker!!.addMovement(motionEvent) mVelocityTracker!!.computeCurrentVelocity(1000) val velocityX = mVelocityTracker!!.xVelocity val absVelocityX = Math.abs(velocityX) val absVelocityY = Math.abs(mVelocityTracker!!.yVelocity) var dismiss = false var dismissRight = false if (Math.abs(mFinalDelta) > mViewWidth / 2 && mSwiping) { dismiss = true dismissRight = mFinalDelta > 0 } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity && absVelocityY < absVelocityX && mSwiping) { // dismiss only if flinging in the same direction as dragging dismiss = velocityX < 0 == mFinalDelta < 0 dismissRight = mVelocityTracker!!.xVelocity > 0 } if (dismiss && mDownPosition != ListView.INVALID_POSITION && mSwipeListener.canSwipe(mDownPosition)) { // dismiss val downView = mDownView // mDownView gets null'd before animation ends val downPosition = mDownPosition ++mDismissAnimationRefCount mBgView!!.animate().alpha(1f).duration = ANIMATION_FAST mFgView!!.animate().translationX((if (dismissRight) mViewWidth else -mViewWidth).toFloat()).setDuration(ANIMATION_FAST).setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { performDismiss(downView!!, downPosition) } }) } else { // cancel mFgView!!.animate().translationX(0f).setDuration(ANIMATION_FAST).setListener(null) } mVelocityTracker!!.recycle() mVelocityTracker = null mDownX = 0f mDownY = 0f mDownView = null mDownPosition = ListView.INVALID_POSITION mSwiping = false mBgView = null } } MotionEvent.ACTION_MOVE -> { if (mVelocityTracker != null && !mPaused) { mVelocityTracker!!.addMovement(motionEvent) val deltaX = motionEvent.rawX - mDownX val deltaY = motionEvent.rawY - mDownY if ((!mSwiping && Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) && deltaX >= 0) { mSwiping = true mSwipingSlop = if (deltaX > 0) mSlop else -mSlop } if (mSwiping) { if (mBgView == null) { mBgView = mDownView!!.findViewById(mBgID) mBgView!!.visibility = View.VISIBLE } mFgView!!.translationX = deltaX - mSwipingSlop return true } } } } return false } private fun performDismiss(dismissView: View, dismissPosition: Int) { // Animate the dismissed list item to zero-height and fire the dismiss callback when // all dismissed list item animations have completed. This triggers layout on each animation // frame; in the future we may want to do something smarter and more performant. val backgroundView = dismissView.findViewById(mBgID) val lp = dismissView.layoutParams val originalHeight = dismissView.height val deleteAble = booleanArrayOf(true) val animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(ANIMATION_FAST) animator.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { --mDismissAnimationRefCount if (mDismissAnimationRefCount > 0) return mDismissAnimationRefCount = 0 // No active animations, process all pending dismisses. // Sort by descending position Collections.sort(mPendingDismisses) val dismissPositions = IntArray(mPendingDismisses.size) for (i in mPendingDismisses.indices.reversed()) { dismissPositions[i] = mPendingDismisses[i].position } mSwipeListener.onDismissedBySwipe(mRecyclerView, dismissPositions) // Reset mDownPosition to avoid MotionEvent.ACTION_UP trying to start a dismiss // animation with a stale position mDownPosition = ListView.INVALID_POSITION var lparams: ViewGroup.LayoutParams for (pendingDismiss in mPendingDismisses) { // Reset view presentation pendingDismiss.view.findViewById(mFgID).translationX = 0f lparams = pendingDismiss.view.layoutParams lparams.height = originalHeight pendingDismiss.view.layoutParams = lparams } // Send a cancel event val time = SystemClock.uptimeMillis() val cancelEvent = MotionEvent.obtain(time, time, MotionEvent.ACTION_CANCEL, 0f, 0f, 0) mRecyclerView.dispatchTouchEvent(cancelEvent) mPendingDismisses.clear() } }) // Animate the dismissed list item to zero-height animator.addUpdateListener { valueAnimator -> lp.height = valueAnimator.animatedValue as Int dismissView.layoutParams = lp } val pendingDismissData = PendingDismissData(dismissPosition, dismissView) mPendingDismisses.add(pendingDismissData) //fade out background view backgroundView.animate().alpha(0f).setDuration(ANIMATION_WAIT).setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { if (deleteAble[0]) animator.start() } }) //cancel animate when click(actually touch) background view. backgroundView.setOnTouchListener { v, event -> when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { deleteAble[0] = false --mDismissAnimationRefCount mPendingDismisses.remove(pendingDismissData) backgroundView.playSoundEffect(0) backgroundView.setOnTouchListener(null) } } false } } /** * The callback interface used by [SwipeableRecyclerViewTouchListener] to inform its client * about a swipe of one or more list item positions. */ interface SwipeListener { /** * Called to determine whether the given position can be swiped. */ fun canSwipe(position: Int): Boolean /** * Called when the item has been dismissed by swiping to the left. * @param recyclerView The originating android.support.v7.widget.RecyclerView. * * * @param reverseSortedPositions An array of positions to dismiss, sorted in descending * * order for convenience. */ fun onDismissedBySwipe(recyclerView: RecyclerView, reverseSortedPositions: IntArray) } internal inner class PendingDismissData(var position: Int, var view: View) : Comparable<PendingDismissData> { override fun compareTo(other: PendingDismissData): Int { // Sort by descending position return other.position - position } } }
mit
93c41ee8c62e2827acb344b723397dcf
39.76781
192
0.589385
5.773543
false
false
false
false
Kotlin/dokka
plugins/base/src/main/kotlin/renderers/html/SearchbarDataInstaller.kt
1
4937
package org.jetbrains.dokka.base.renderers.html import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import org.jetbrains.dokka.Platform import org.jetbrains.dokka.base.renderers.sourceSets import org.jetbrains.dokka.base.templating.AddToSearch import org.jetbrains.dokka.links.DRI import org.jetbrains.dokka.model.DisplaySourceSet import org.jetbrains.dokka.model.dfs import org.jetbrains.dokka.model.withDescendants import org.jetbrains.dokka.pages.* import org.jetbrains.dokka.plugability.DokkaContext import org.jetbrains.dokka.transformers.pages.PageTransformer data class SearchRecord( val name: String, val description: String? = null, val location: String, val searchKeys: List<String> = listOf(name) ) { companion object } open class SearchbarDataInstaller(val context: DokkaContext) : PageTransformer { data class DRIWithSourceSets(val dri: DRI, val sourceSet: Set<DisplaySourceSet>) data class SignatureWithId(val driWithSourceSets: DRIWithSourceSets, val displayableSignature: String) { constructor(dri: DRI, page: ContentPage) : this( DRIWithSourceSets(dri, page.sourceSets()), getSymbolSignature(page, dri)?.let { flattenToText(it) } ?: page.name) val id: String get() = with(driWithSourceSets.dri) { listOfNotNull( packageName, classNames, callable?.name ).joinToString(".") } } private val mapper = jacksonObjectMapper() open fun generatePagesList(pages: List<SignatureWithId>, locationResolver: DriResolver): List<SearchRecord> = pages.map { pageWithId -> createSearchRecord( name = pageWithId.displayableSignature, description = pageWithId.id, location = resolveLocation(locationResolver, pageWithId.driWithSourceSets).orEmpty(), searchKeys = listOf( pageWithId.id.substringAfterLast("."), pageWithId.displayableSignature, pageWithId.id, ) ) }.sortedWith(compareBy({ it.name }, { it.description })) open fun createSearchRecord( name: String, description: String?, location: String, searchKeys: List<String> ): SearchRecord = SearchRecord(name, description, location, searchKeys) open fun processPage(page: PageNode): List<SignatureWithId> = when (page) { is ContentPage -> page.takeIf { page !is ModulePageNode && page !is PackagePageNode }?.dri ?.map { dri -> SignatureWithId(dri, page) }.orEmpty() else -> emptyList() } private fun resolveLocation(locationResolver: DriResolver, driWithSourceSets: DRIWithSourceSets): String? = locationResolver(driWithSourceSets.dri, driWithSourceSets.sourceSet).also { location -> if (location.isNullOrBlank()) context.logger.warn("Cannot resolve path for ${driWithSourceSets.dri}") } override fun invoke(input: RootPageNode): RootPageNode { val signatureWithIds = input.withDescendants().fold(emptyList<SignatureWithId>()) { pageList, page -> pageList + processPage(page) } val page = RendererSpecificResourcePage( name = "scripts/pages.json", children = emptyList(), strategy = RenderingStrategy.DriLocationResolvableWrite { resolver -> val content = signatureWithIds.run { generatePagesList(this, resolver) } if (context.configuration.delayTemplateSubstitution) { mapper.writeValueAsString(AddToSearch(context.configuration.moduleName, content)) } else { mapper.writeValueAsString(content) } }) return input.modified(children = input.children + page) } } private fun getSymbolSignature(page: ContentPage, dri: DRI) = page.content.dfs { it.dci.kind == ContentKind.Symbol && it.dci.dri.contains(dri) } private fun flattenToText(node: ContentNode): String { fun getContentTextNodes(node: ContentNode, sourceSetRestriction: DisplaySourceSet): List<ContentText> = when (node) { is ContentText -> listOf(node) is ContentComposite -> node.children .filter { sourceSetRestriction in it.sourceSets } .flatMap { getContentTextNodes(it, sourceSetRestriction) } .takeIf { node.dci.kind != ContentKind.Annotations && node.dci.kind != ContentKind.Source } .orEmpty() else -> emptyList() } val sourceSetRestriction = node.sourceSets.find { it.platform == Platform.common } ?: node.sourceSets.first() return getContentTextNodes(node, sourceSetRestriction).joinToString("") { it.text } }
apache-2.0
703668bda51a7ea714ecf7737c4f7540
41.205128
113
0.64918
5.02238
false
false
false
false
tinypass/piano-sdk-for-android
id/id/src/main/java/io/piano/android/id/models/PianoUserInfo.kt
1
908
package io.piano.android.id.models class PianoUserInfo( val formName: String ) { internal val customFields = mutableMapOf<String, String>() fun customField(name: String, value: String) = apply { customFields[name] = value } fun customField(name: String, value: Boolean) = apply { customFields[name] = value.toString() } fun customField(name: String, value: Int) = apply { customFields[name] = value.toString() } fun customField(name: String, value: Double) = apply { customFields[name] = value.toString() } fun customField(name: String, value: Collection<String>) = apply { customFields[name] = value.joinToString(prefix = "[", postfix = "]") { """"$it"""" } } } internal fun PianoUserInfo.toProfileUpdateRequest() = ProfileUpdateRequest( formName, customFields.map { CustomField(fieldName = it.key, value = it.value) } )
apache-2.0
b70115a116ee28fc3d994186f8bc6809
40.272727
99
0.661894
4.108597
false
false
false
false
italoag/qksms
presentation/src/main/java/com/moez/QKSMS/feature/backup/BackupPresenter.kt
3
5729
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QKSMS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.feature.backup import android.content.Context import com.moez.QKSMS.R import com.moez.QKSMS.common.Navigator import com.moez.QKSMS.common.base.QkPresenter import com.moez.QKSMS.common.util.DateFormatter import com.moez.QKSMS.common.util.extensions.makeToast import com.moez.QKSMS.interactor.PerformBackup import com.moez.QKSMS.manager.BillingManager import com.moez.QKSMS.manager.PermissionManager import com.moez.QKSMS.repository.BackupRepository import com.uber.autodispose.android.lifecycle.scope import com.uber.autodispose.autoDisposable import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.withLatestFrom import io.reactivex.subjects.BehaviorSubject import io.reactivex.subjects.Subject import java.util.concurrent.TimeUnit import javax.inject.Inject class BackupPresenter @Inject constructor( private val backupRepo: BackupRepository, private val billingManager: BillingManager, private val context: Context, private val dateFormatter: DateFormatter, private val navigator: Navigator, private val performBackup: PerformBackup, private val permissionManager: PermissionManager ) : QkPresenter<BackupView, BackupState>(BackupState()) { private val storagePermissionSubject: Subject<Boolean> = BehaviorSubject.createDefault(permissionManager.hasStorage()) init { disposables += backupRepo.getBackupProgress() .sample(16, TimeUnit.MILLISECONDS) .distinctUntilChanged() .subscribe { progress -> newState { copy(backupProgress = progress) } } disposables += backupRepo.getRestoreProgress() .sample(16, TimeUnit.MILLISECONDS) .distinctUntilChanged() .subscribe { progress -> newState { copy(restoreProgress = progress) } } disposables += storagePermissionSubject .distinctUntilChanged() .switchMap { backupRepo.getBackups() } .doOnNext { backups -> newState { copy(backups = backups) } } .map { backups -> backups.map { it.date }.max() ?: 0L } .map { lastBackup -> when (lastBackup) { 0L -> context.getString(R.string.backup_never) else -> dateFormatter.getDetailedTimestamp(lastBackup) } } .startWith(context.getString(R.string.backup_loading)) .subscribe { lastBackup -> newState { copy(lastBackup = lastBackup) } } disposables += billingManager.upgradeStatus .subscribe { upgraded -> newState { copy(upgraded = upgraded) } } } override fun bindIntents(view: BackupView) { super.bindIntents(view) view.activityVisible() .map { permissionManager.hasStorage() } .autoDisposable(view.scope()) .subscribe(storagePermissionSubject) view.restoreClicks() .withLatestFrom( backupRepo.getBackupProgress(), backupRepo.getRestoreProgress(), billingManager.upgradeStatus) { _, backupProgress, restoreProgress, upgraded -> when { !upgraded -> context.makeToast(R.string.backup_restore_error_plus) backupProgress.running -> context.makeToast(R.string.backup_restore_error_backup) restoreProgress.running -> context.makeToast(R.string.backup_restore_error_restore) !permissionManager.hasStorage() -> view.requestStoragePermission() else -> view.selectFile() } } .autoDisposable(view.scope()) .subscribe() view.restoreFileSelected() .autoDisposable(view.scope()) .subscribe { view.confirmRestore() } view.restoreConfirmed() .withLatestFrom(view.restoreFileSelected()) { _, backup -> backup } .autoDisposable(view.scope()) .subscribe { backup -> RestoreBackupService.start(context, backup.path) } view.stopRestoreClicks() .autoDisposable(view.scope()) .subscribe { view.stopRestore() } view.stopRestoreConfirmed() .autoDisposable(view.scope()) .subscribe { backupRepo.stopRestore() } view.fabClicks() .withLatestFrom(billingManager.upgradeStatus) { _, upgraded -> upgraded } .autoDisposable(view.scope()) .subscribe { upgraded -> when { !upgraded -> navigator.showQksmsPlusActivity("backup_fab") !permissionManager.hasStorage() -> view.requestStoragePermission() upgraded -> performBackup.execute(Unit) } } } }
gpl-3.0
3bca5aba967467996ef185fb667b58d1
41.444444
122
0.627509
5.106061
false
false
false
false
asarkar/spring
touchstone/src/main/kotlin/execution/junit/JUnitExecutor.kt
1
3830
package org.abhijitsarkar.touchstone.execution.junit import org.slf4j.LoggerFactory import org.springframework.batch.core.ExitStatus import org.springframework.batch.core.StepContribution import org.springframework.batch.core.scope.context.ChunkContext import org.springframework.batch.core.step.tasklet.Tasklet import org.springframework.batch.repeat.RepeatStatus import java.io.ByteArrayOutputStream import java.io.PrintStream import java.nio.charset.StandardCharsets import java.util.Locale /** * @author Abhijit Sarkar */ class TestFailedException(override val message: String? = null, val exitCode: Int) : RuntimeException(message) class JUnitExecutor( private val junit: JUnitProperties, private val junitLauncher: JUnitLauncher ) : Tasklet { companion object { private val LOGGER = LoggerFactory.getLogger(JUnitExecutor::class.java) const val EXECUTION_RESULT_KEY = "touchstone.junit.executionResult" } override fun execute(contribution: StepContribution, chunkContext: ChunkContext): RepeatStatus { val args = mutableListOf<String>() if (junit.help) args += "--help" if (junit.disableAnsiColors) args += "--disable-ansi-colors" args += "--details" args += junit.details.name.toLowerCase(Locale.ENGLISH) args += "--details-theme" args += junit.detailsTheme.name.toLowerCase(Locale.ENGLISH) args += "--reports-dir" args += junit.reportsDir junit.selectUri.forEach { args += "--select-uri" args += it } junit.selectFile.forEach { args += "--select-file" args += it } junit.selectDirectory.forEach { args += "--select-directory" args += it } junit.selectPackage.forEach { args += "--select-package" args += it } junit.selectClass.forEach { args += "--select-class" args += it } junit.selectMethod.forEach { args += "--select-method" args += it } junit.selectResource.forEach { args += "--select-resource" args += it } junit.includeClassname.forEach { args += "--include-classname" args += it } junit.excludeClassname.forEach { args += "--exclude-classname" args += it } junit.includePackage.forEach { args += "--include-package" args += it } junit.excludePackage.forEach { args += "--exclude-package" args += it } junit.includeTag.forEach { args += "--include-tag" args += it } junit.excludeTag.forEach { args += "--exclude-tag" args += it } junit.config.forEach { args += "--config" args += "${it.key}=${it.value}" } LOGGER.info("Test args: {}", args) val out = ByteArrayOutputStream() val err = ByteArrayOutputStream() val p1 = PrintStream(out) val p2 = PrintStream(err) val result = junitLauncher.launch(p1, p2, args.toTypedArray()) if (out.size() > 0) { LOGGER.info("{}", out.toString(StandardCharsets.UTF_8.name())) } if (err.size() > 0) { LOGGER.error("{}", err.toString(StandardCharsets.UTF_8.name())) } p1.close() p2.close() chunkContext.stepContext.stepExecution.executionContext.put(EXECUTION_RESULT_KEY, result) if (result.exitCode != 0) { contribution.exitStatus = ExitStatus.FAILED } return RepeatStatus.FINISHED } }
gpl-3.0
549f9c44f5f93afe6a3392b6b2f6335f
26.561151
110
0.572585
4.564958
false
false
false
false
Yubyf/QuoteLock
app/src/main/java/com/crossbowffs/quotelock/modules/custom/app/CustomQuoteConfigFragment.kt
1
6245
package com.crossbowffs.quotelock.modules.custom.app import android.content.DialogInterface import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.ContextMenu import android.view.MenuItem import android.view.View import android.view.WindowManager import android.widget.Toast import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import com.crossbowffs.quotelock.R import com.crossbowffs.quotelock.api.QuoteData import com.crossbowffs.quotelock.components.BaseQuoteListFragment import com.crossbowffs.quotelock.components.ContextMenuRecyclerView import com.crossbowffs.quotelock.components.QuoteListAdapter import com.crossbowffs.quotelock.modules.custom.database.CustomQuoteEntity import com.crossbowffs.quotelock.modules.custom.database.customQuoteDatabase import com.crossbowffs.quotelock.utils.ioScope import com.google.android.material.appbar.MaterialToolbar import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.textfield.TextInputEditText import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext /** * @author Yubyf */ class CustomQuoteConfigFragment : BaseQuoteListFragment<CustomQuoteEntity>() { @Suppress("UNCHECKED_CAST") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requireActivity().findViewById<MaterialToolbar>(R.id.toolbar) .setOnMenuItemClickListener { if (it.itemId == R.id.create_quote) { showEditQuoteDialog(-1) } true } lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { customQuoteDatabase.dao().getAll().collect { (recyclerView.adapter as? QuoteListAdapter<CustomQuoteEntity>)?.submitList(it) scrollToPosition() } } } } override fun onCreateContextMenu( menu: ContextMenu, v: View, menuInfo: ContextMenu.ContextMenuInfo?, ) { super.onCreateContextMenu(menu, v, menuInfo) requireActivity().menuInflater.inflate(R.menu.custom_quote_context, menu) } override fun onContextItemSelected(item: MenuItem): Boolean { val info = item.menuInfo as? ContextMenuRecyclerView.ContextMenuInfo info?.let { val rowId = it.id val itemId = item.itemId if (itemId == R.id.edit_quote) { showEditQuoteDialog(rowId) return true } else if (itemId == R.id.delete_quote) { deleteQuote(rowId) return true } } return super.onContextItemSelected(item) } private fun queryQuote(rowId: Long): QuoteData? { if (rowId < 0) { return null } return runBlocking { customQuoteDatabase.dao().getById(rowId).firstOrNull()?.let { QuoteData(it.text, it.source) } } } private fun persistQuote(rowId: Long, text: String, source: String) { ioScope.launch { if (rowId >= 0) { customQuoteDatabase.dao() .update(CustomQuoteEntity(rowId.toInt(), text, source)) } else { customQuoteDatabase.dao() .insert(CustomQuoteEntity(text = text, source = source)) } withContext(Dispatchers.Main) { Toast.makeText(requireContext(), R.string.module_custom_saved_quote, Toast.LENGTH_SHORT) .show() } } } private fun deleteQuote(rowId: Long) { ioScope.launch { customQuoteDatabase.dao().delete(rowId) withContext(Dispatchers.Main) { Toast.makeText(requireContext(), R.string.module_custom_deleted_quote, Toast.LENGTH_SHORT) .show() } } } private fun showEditQuoteDialog(rowId: Long) { val dialogView = layoutInflater.inflate(R.layout.dialog_custom_quote, null) val textEditText = dialogView.findViewById<TextInputEditText>(R.id.dialog_custom_quote_text) val sourceEditText = dialogView.findViewById<TextInputEditText>(R.id.dialog_custom_quote_source) val dialog = MaterialAlertDialogBuilder(requireContext()) .setTitle(R.string.module_custom_enter_quote) .setView(dialogView) .setPositiveButton(R.string.save) { _, _ -> persistQuote( rowId, textEditText.text.toString(), sourceEditText.text.toString() ) } .setNegativeButton(R.string.cancel, null) .setBackgroundInsetTop(0) .setBackgroundInsetBottom(0) .create() dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) dialog.show() val watcher: TextWatcher = object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {} override fun afterTextChanged(s: Editable) { val button = dialog.getButton(DialogInterface.BUTTON_POSITIVE) val canSave = !textEditText.text.isNullOrEmpty() button.isEnabled = canSave } } textEditText.addTextChangedListener(watcher) sourceEditText.addTextChangedListener(watcher) val quote = queryQuote(rowId) ?: QuoteData() textEditText.setText(quote.quoteText) sourceEditText.setText(quote.quoteSource) } override fun showDetailPage(): Boolean = false override fun goToDetailPage() = Unit /* no-op */ }
mit
62738e4a2a85ab8974b0303566c63c4f
36.854545
98
0.635709
5.064882
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/libanki/importer/Anki2Importer.kt
1
35532
/*************************************************************************************** * Copyright (c) 2012 Norbert Nagold <[email protected]> * * Copyright (c) 2016 Houssam Salem <[email protected]> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.libanki.importer import android.text.TextUtils import com.ichi2.anki.R import com.ichi2.anki.exception.ConfirmModSchemaException import com.ichi2.anki.exception.ImportExportException import com.ichi2.libanki.* import com.ichi2.libanki.Collection import com.ichi2.libanki.Consts.CARD_QUEUE import com.ichi2.libanki.Consts.CARD_TYPE import com.ichi2.libanki.Consts.CARD_TYPE_LRN import com.ichi2.libanki.Consts.CARD_TYPE_NEW import com.ichi2.libanki.Consts.CARD_TYPE_REV import com.ichi2.libanki.Consts.QUEUE_TYPE_DAY_LEARN_RELEARN import com.ichi2.libanki.Consts.QUEUE_TYPE_NEW import com.ichi2.libanki.Consts.QUEUE_TYPE_REV import com.ichi2.libanki.Storage.collection import com.ichi2.libanki.utils.TimeManager import com.ichi2.utils.HashUtil import com.ichi2.utils.KotlinCleanup import timber.log.Timber import java.io.BufferedInputStream import java.io.ByteArrayOutputStream import java.io.File import java.io.FileInputStream import java.io.IOException import java.util.Arrays import java.util.Locale import java.util.regex.Matcher @KotlinCleanup("IDE-lint") @KotlinCleanup("remove !!") @KotlinCleanup("lateinit") @KotlinCleanup("make col non-null") open class Anki2Importer(col: Collection?, file: String) : Importer(col!!, file) { private val mDeckPrefix: String? private val mAllowUpdate: Boolean private var mDupeOnSchemaChange: Boolean private class NoteTriple(val nid: NoteId, val mod: Long, val mid: NoteTypeId) private var mNotes: MutableMap<String, NoteTriple>? = null private var mDecks: MutableMap<Long, Long>? = null private var mModelMap: MutableMap<Long, Long>? = null private var mIgnoredGuids: MutableSet<String>? = null var dupes = 0 private set var added = 0 private set var updated = 0 private set /** If importing SchedV1 into SchedV2 we need to reset the learning cards */ private var mMustResetLearning = false @Throws(ImportExportException::class) override fun run() { publishProgress(0, 0, 0) try { _prepareFiles() try { _import() } finally { src.close(false) } } catch (e: Exception) { Timber.e(e, "Exception while importing") throw ImportExportException(e.message) } } private fun _prepareFiles() { val importingV2 = file.endsWith(".anki21") mMustResetLearning = false dst = mCol src = collection(context, file) if (!importingV2 && mCol.schedVer() != 1) { // any scheduling included? if (src.db.queryScalar("select 1 from cards where queue != $QUEUE_TYPE_NEW limit 1") > 0) { mMustResetLearning = true } } } private fun _import() { mDecks = HashUtil.HashMapInit(src.decks.count()) try { // Use transactions for performance and rollbacks in case of error dst.db.database.beginTransaction() dst.media.db!!.database.beginTransaction() if (!TextUtils.isEmpty(mDeckPrefix)) { val id = dst.decks.id_safe(mDeckPrefix!!) dst.decks.select(id) } Timber.i("Preparing Import") _prepareTS() _prepareModels() Timber.i("Importing notes") _importNotes() Timber.i("Importing Cards") _importCards() Timber.i("Importing Media") _importStaticMedia() publishProgress(100, 100, 25) Timber.i("Performing post-import") _postImport() publishProgress(100, 100, 50) dst.db.database.setTransactionSuccessful() dst.media.db!!.database.setTransactionSuccessful() } catch (err: Exception) { Timber.e(err, "_import() exception") throw err } finally { // endTransaction throws about invalid transaction even when you check first! DB.safeEndInTransaction(dst.db) DB.safeEndInTransaction(dst.media.db!!) } Timber.i("Performing vacuum/analyze") try { dst.db.execute("vacuum") } catch (e: Exception) { Timber.w(e) // This is actually not fatal but can fail since vacuum takes so much space // Allow the import to succeed but recommend the user run check database log.add( res.getString( R.string.import_succeeded_but_check_database, e.localizedMessage ) ) } publishProgress(100, 100, 65) try { dst.db.execute("analyze") } catch (e: Exception) { Timber.w(e) // This is actually not fatal but can fail // Allow the import to succeed but recommend the user run check database log.add( res.getString( R.string.import_succeeded_but_check_database, e.localizedMessage ) ) } publishProgress(100, 100, 75) } /** * Notes * *********************************************************** */ private fun _importNotes() { val noteCount = dst.noteCount() // build guid -> (id,mod,mid) hash & map of existing note ids mNotes = HashUtil.HashMapInit(noteCount) val existing: MutableSet<Long> = HashUtil.HashSetInit(noteCount) dst.db.query("select id, guid, mod, mid from notes").use { cur -> while (cur.moveToNext()) { val id = cur.getLong(0) val guid = cur.getString(1) val mod = cur.getLong(2) val mid = cur.getLong(3) mNotes!![guid] = NoteTriple(id, mod, mid) existing.add(id) } } // we ignore updates to changed schemas. we need to note the ignored // guids, so we avoid importing invalid cards mIgnoredGuids = HashSet() // iterate over source collection val nbNoteToImport = src.noteCount() val add = ArrayList<Array<Any>>(nbNoteToImport) var totalAddCount = 0 val thresExecAdd = 1000 val update = ArrayList<Array<Any>>(nbNoteToImport) var totalUpdateCount = 0 val thresExecUpdate = 1000 val dirty = ArrayList<Long>(nbNoteToImport) var totalDirtyCount = 0 val thresExecDirty = 1000 val usn = dst.usn() var dupes = 0 val dupesIgnored = ArrayList<String>(nbNoteToImport) dst.db.database.beginTransaction() try { src.db.database.query( "select id, guid, mid, mod, tags, flds, sfld, csum, flags, data from notes", null ).use { cur -> // Counters for progress updates val total = cur.count val largeCollection = total > 200 val onePercent = total / 100 var i = 0 while (cur.moveToNext()) { // turn the db result into a mutable list var nid = cur.getLong(0) val guid = cur.getString(1) var mid = cur.getLong(2) val mod = cur.getLong(3) val tags = cur.getString(4) var flds = cur.getString(5) val sfld = cur.getString(6) val csum = cur.getLong(7) val flag = cur.getInt(8) val data = cur.getString(9) val shouldAddAndNewMid = _uniquifyNote(guid, mid) val shouldAdd = shouldAddAndNewMid.first mid = shouldAddAndNewMid.second if (shouldAdd) { // ensure nid is unique while (existing.contains(nid)) { nid += 999 } existing.add(nid) // bump usn // update media references in case of dupes flds = _mungeMedia(mid, flds) add.add(arrayOf(nid, guid, mid, mod, usn, tags, flds, sfld, csum, flag, data)) dirty.add(nid) // note we have the added guid mNotes!![guid] = NoteTriple(nid, mod, mid) } else { // a duplicate or changed schema - safe to update? dupes += 1 if (mAllowUpdate) { val n = mNotes!!.get(guid) val oldNid = n!!.nid val oldMod = n.mod val oldMid = n.mid // will update if incoming note more recent if (oldMod < mod) { // safe if note types identical if (oldMid == mid) { // incoming note should use existing id nid = oldNid flds = _mungeMedia(mid, flds) update.add(arrayOf(nid, guid, mid, mod, usn, tags, flds, sfld, csum, flag, data)) dirty.add(nid) } else { val modelName = mCol.models.get(oldMid)!!.getString("name") val commaSeparatedFields = flds.replace('\u001f', ',') dupesIgnored.add("$modelName: $commaSeparatedFields") mIgnoredGuids!!.add(guid) } } } } i++ // add to col partially, so as to avoid OOM if (add.size >= thresExecAdd) { totalAddCount += add.size addNotes(add) add.clear() Timber.d("add notes: %d", totalAddCount) } // add to col partially, so as to avoid OOM if (update.size >= thresExecUpdate) { totalUpdateCount += update.size updateNotes(update) update.clear() Timber.d("update notes: %d", totalUpdateCount) } // add to col partially, so as to avoid OOM if (dirty.size >= thresExecDirty) { totalDirtyCount += dirty.size dst.updateFieldCache(dirty) dst.tags.registerNotes(dirty) dirty.clear() Timber.d("dirty notes: %d", totalDirtyCount) } if (total != 0 && (!largeCollection || i % onePercent == 0)) { // Calls to publishProgress are reasonably expensive due to res.getString() publishProgress(i * 100 / total, 0, 0) } } publishProgress(100, 0, 0) // summarize partial add/update/dirty results for total values totalAddCount += add.size totalUpdateCount += update.size totalDirtyCount += dirty.size if (dupes > 0) { log.add(res.getString(R.string.import_update_details, totalUpdateCount, dupes)) if (!dupesIgnored.isEmpty()) { log.add(res.getString(R.string.import_update_ignored)) } } // export info for calling code this.dupes = dupes added = totalAddCount updated = totalUpdateCount Timber.d("add notes total: %d", totalAddCount) Timber.d("update notes total: %d", totalUpdateCount) Timber.d("dirty notes total: %d", totalDirtyCount) // add to col (for last chunk) addNotes(add) add.clear() updateNotes(update) update.clear() dst.db.database.setTransactionSuccessful() } } finally { DB.safeEndInTransaction(dst.db) } dst.updateFieldCache(dirty) dst.tags.registerNotes(dirty) } private fun addNotes(add: List<Array<Any>>) { dst.db.executeManyNoTransaction( "insert or replace into notes values (?,?,?,?,?,?,?,?,?,?,?)", add ) } private fun updateNotes(update: List<Array<Any>>) { dst.db.executeManyNoTransaction("insert or replace into notes values (?,?,?,?,?,?,?,?,?,?,?)", update) } // determine if note is a duplicate, and adjust mid and/or guid as required // returns true if note should be added and its mid private fun _uniquifyNote(origGuid: String, srcMid: Long): Pair<Boolean, Long> { val dstMid = _mid(srcMid) // duplicate Schemas? if (srcMid == dstMid) { return Pair(!mNotes!!.containsKey(origGuid), srcMid) } // differing schemas and note doesn't exist? if (!mNotes!!.containsKey(origGuid)) { return Pair(true, dstMid) } // schema changed; don't import mIgnoredGuids!!.add(origGuid) return Pair(false, dstMid) } /* Models *********************************************************** Models in the two decks may share an ID but not a schema, so we need to compare the field & template signature rather than just rely on ID. If the schemas don't match, we increment the mid and try again, creating a new model if necessary. */ /** Prepare index of schema hashes. */ private fun _prepareModels() { mModelMap = HashUtil.HashMapInit(src.models.count()) } /** Return local id for remote MID. */ private fun _mid(srcMid: Long): Long { // already processed this mid? if (mModelMap!!.containsKey(srcMid)) { return mModelMap!![srcMid]!! } var mid = srcMid val srcModel = src.models.get(srcMid) val srcScm = src.models.scmhash(srcModel!!) while (true) { // missing from target col? if (!dst.models.have(mid)) { // copy it over val model = srcModel.deepClone().apply { put("id", mid) put("mod", TimeManager.time.intTime()) put("usn", mCol.usn()) } dst.models.update(model) break } // there's an existing model; do the schemas match? val dstModel = dst.models.get(mid) val dstScm = dst.models.scmhash(dstModel!!) if (srcScm == dstScm) { // they do; we can reuse this mid val model = srcModel.deepClone().apply { put("id", mid) put("mod", TimeManager.time.intTime()) put("usn", mCol.usn()) } dst.models.update(model) break } // as they don't match, try next id mid += 1 } // save map and return new mid mModelMap!![srcMid] = mid return mid } /* * Decks * *********************************************************** */ /** Given did in src col, return local id. */ @KotlinCleanup("use scope function") private fun _did(did: DeckId): Long { // already converted? if (mDecks!!.containsKey(did)) { return mDecks!![did]!! } // get the name in src val g = src.decks.get(did) var name = g.getString("name") // if there's a prefix, replace the top level deck if (!TextUtils.isEmpty(mDeckPrefix)) { val parts = listOf(*Decks.path(name)) val tmpname = TextUtils.join("::", parts.subList(1, parts.size)) name = mDeckPrefix!! if (!TextUtils.isEmpty(tmpname)) { name += "::$tmpname" } } // Manually create any parents so we can pull in descriptions var head: String? = "" val parents = listOf(*Decks.path(name)) for (parent in parents.subList(0, parents.size - 1)) { if (!TextUtils.isEmpty(head)) { head += "::" } head += parent val idInSrc = src.decks.id_safe(head!!) _did(idInSrc) } // create in local val newid = dst.decks.id_safe(name) // pull conf over if (g.has("conf") && g.getLong("conf") != 1L) { val conf = src.decks.getConf(g.getLong("conf")) dst.decks.save(conf!!) dst.decks.updateConf(conf) val g2 = dst.decks.get(newid) g2.put("conf", g.getLong("conf")) dst.decks.save(g2) } // save desc val deck = dst.decks.get(newid) deck.put("desc", g.getString("desc")) dst.decks.save(deck) // add to deck map and return mDecks!![did] = newid return newid } /** * Cards * *********************************************************** */ private fun _importCards() { if (mMustResetLearning) { try { src.changeSchedulerVer(2) } catch (e: ConfirmModSchemaException) { throw RuntimeException( "Changing the scheduler of an import should not cause schema modification", e ) } } // build map of guid -> (ord -> cid) and used id cache /* * Since we can't use a tuple as a key in Java, we resort to indexing twice with nested maps. * Python: (guid, ord) -> cid * Java: guid -> ord -> cid */ val nbCard = dst.cardCount() val cardsByGuid: MutableMap<String, MutableMap<Int, Long>> = HashUtil.HashMapInit(nbCard) val existing: MutableSet<Long> = HashUtil.HashSetInit(nbCard) dst.db.query( "select f.guid, c.ord, c.id from cards c, notes f " + "where c.nid = f.id" ).use { cur -> while (cur.moveToNext()) { val guid = cur.getString(0) val ord = cur.getInt(1) val cid = cur.getLong(2) existing.add(cid) if (cardsByGuid.containsKey(guid)) { cardsByGuid[guid]!![ord] = cid } else { val map: MutableMap<Int, Long> = HashMap() // The size is at most the number of card type in the note type. map[ord] = cid cardsByGuid[guid] = map } } } // loop through src val nbCardsToImport = src.cardCount() val cards: MutableList<Array<Any>> = ArrayList(nbCardsToImport) var totalCardCount = 0 val thresExecCards = 1000 val revlog: MutableList<Array<Any>> = ArrayList(src.sched.logCount()) var totalRevlogCount = 0 val thresExecRevlog = 1000 val usn = dst.usn() val aheadBy = (src.sched.today - dst.sched.today).toLong() dst.db.database.beginTransaction() try { src.db.query( "select f.guid, c.id, c.did, c.ord, c.type, c.queue, c.due, c.ivl, c.factor, c.reps, c.lapses, c.left, c.odue, c.odid, c.flags, c.data from cards c, notes f " + "where c.nid = f.id" ).use { cur -> // Counters for progress updates val total = cur.count val largeCollection = total > 200 val onePercent = total / 100 var i = 0 while (cur.moveToNext()) { val guid = cur.getString(0) var cid = cur.getLong(1) val scid = cid // To keep track of card id in source var did = cur.getLong(2) val ord = cur.getInt(3) @CARD_TYPE var type = cur.getInt(4) @CARD_QUEUE var queue = cur.getInt(5) var due = cur.getLong(6) val ivl = cur.getLong(7) val factor = cur.getLong(8) val reps = cur.getInt(9) val lapses = cur.getInt(10) val left = cur.getInt(11) var odue = cur.getLong(12) var odid = cur.getLong(13) val flags = cur.getInt(14) val data = cur.getString(15) if (mIgnoredGuids!!.contains(guid)) { continue } // does the card's note exist in dst col? if (!mNotes!!.containsKey(guid)) { continue } // does the card already exist in the dst col? if (cardsByGuid.containsKey(guid) && cardsByGuid[guid]!!.containsKey(ord)) { // fixme: in future, could update if newer mod time continue } // ensure the card id is unique while (existing.contains(cid)) { cid += 999 } existing.add(cid) // update cid, nid, etc val nid = mNotes!![guid]!!.nid did = _did(did) val mod = TimeManager.time.intTime() // review cards have a due date relative to collection if (queue == QUEUE_TYPE_REV || queue == QUEUE_TYPE_DAY_LEARN_RELEARN || type == CARD_TYPE_REV) { due -= aheadBy } // odue needs updating too if (odue != 0L) { odue -= aheadBy } // if odid true, convert card from filtered to normal if (odid != 0L) { // odid odid = 0 // odue due = odue odue = 0 // queue if (type == CARD_TYPE_LRN) { // type queue = QUEUE_TYPE_NEW } else { queue = type } // type if (type == CARD_TYPE_LRN) { type = CARD_TYPE_NEW } } cards.add(arrayOf(cid, nid, did, ord, mod, usn, type, queue, due, ivl, factor, reps, lapses, left, odue, odid, flags, data)) src.db.query("select * from revlog where cid = $scid").use { cur2 -> while (cur2.moveToNext()) { val rev = arrayOf<Any>( cur2.getLong(0), cur2.getLong(1), cur2.getInt(2), cur2.getInt(3), cur2.getLong(4), cur2.getLong(5), cur2.getLong(6), cur2.getLong(7), cur2.getInt(8) ) rev[1] = cid rev[2] = dst.usn() revlog.add(rev) } } i++ // apply card changes partially if (cards.size >= thresExecCards) { totalCardCount += cards.size insertCards(cards) cards.clear() Timber.d("add cards: %d", totalCardCount) } // apply revlog changes partially if (revlog.size >= thresExecRevlog) { totalRevlogCount += revlog.size insertRevlog(revlog) revlog.clear() Timber.d("add revlog: %d", totalRevlogCount) } if (total != 0 && (!largeCollection || i % onePercent == 0)) { publishProgress(100, i * 100 / total, 0) } } publishProgress(100, 100, 0) // count total values totalCardCount += cards.size totalRevlogCount += revlog.size Timber.d("add cards total: %d", totalCardCount) Timber.d("add revlog total: %d", totalRevlogCount) // apply (for last chunk) insertCards(cards) cards.clear() insertRevlog(revlog) revlog.clear() cardCount = totalCardCount dst.db.database.setTransactionSuccessful() } } finally { DB.safeEndInTransaction(dst.db) } } private fun insertCards(cards: List<Array<Any>>) { dst.db.executeManyNoTransaction( "insert or ignore into cards values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", cards ) } private fun insertRevlog(revlog: List<Array<Any>>) { dst.db.executeManyNoTransaction( "insert or ignore into revlog values (?,?,?,?,?,?,?,?,?)", revlog ) } /** * Media * *********************************************************** */ // note: this func only applies to imports of .anki2. For .apkg files, the // apkg importer does the copying private fun _importStaticMedia() { // Import any '_foo' prefixed media files regardless of whether // they're used on notes or not val dir = src.media.dir() if (!File(dir).exists()) { return } for (f in File(dir).listFiles()!!) { val fname = f.name if (fname.startsWith("_") && !dst.media.have(fname)) { try { _srcMediaData(fname).use { data -> _writeDstMedia(fname, data!!) } } catch (e: IOException) { Timber.w(e, "Failed to close stream") } } } } private fun _mediaData(fname: String, directory: String): BufferedInputStream? { var dir: String? = directory if (dir == null) { dir = src.media.dir() } val path = File(dir, fname).absolutePath return try { BufferedInputStream(FileInputStream(path), MEDIAPICKLIMIT * 2) } catch (e: IOException) { Timber.w(e) null } } /** * Data for FNAME in src collection. */ protected open fun _srcMediaData(fname: String): BufferedInputStream? { return _mediaData(fname, src.media.dir()) } /** * Data for FNAME in dst collection. */ private fun _dstMediaData(fname: String): BufferedInputStream? { return _mediaData(fname, dst.media.dir()) } private fun _writeDstMedia(fname: String, data: BufferedInputStream) { try { val path = File(dst.media.dir(), Utils.nfcNormalized(fname)).absolutePath Utils.writeToFile(data, path) // Mark file addition to media db (see note in Media.java) dst.media.markFileAdd(fname) } catch (e: IOException) { // the user likely used subdirectories Timber.e(e, "Error copying file %s.", fname) // If we are out of space, we should re-throw if (e.cause != null && e.cause!!.message!!.contains("No space left on device")) { // we need to let the user know why we are failing Timber.e("We are out of space, bubbling up the file copy exception") throw RuntimeException(e) } } } // running splitFields() on every note is fairly expensive and actually not necessary private fun _mungeMedia(mid: NoteTypeId, fields: String): String { var _fields = fields for (p in Media.REGEXPS) { val m = p.matcher(_fields) val sb = StringBuffer() val fnameIdx = Media.indexOfFname(p) while (m.find()) { val fname = m.group(fnameIdx)!! try { val srcData = _srcMediaData(fname) val dstData = _dstMediaData(fname) if (srcData == null) { // file was not in source, ignore m.appendReplacement(sb, Matcher.quoteReplacement(m.group(0)!!)) continue } // if model-local file exists from a previous import, use that val split = Utils.splitFilename(fname) val name = split[0] val ext = split[1] val lname = String.format(Locale.US, "%s_%s%s", name, mid, ext) if (dst.media.have(lname)) { m.appendReplacement( sb, Matcher.quoteReplacement(m.group(0)!!.replace(fname, lname)) ) continue } else if (dstData == null || compareMedia( srcData, dstData ) ) { // if missing or the same, pass unmodified // need to copy? if (dstData == null) { _writeDstMedia(fname, srcData) } m.appendReplacement(sb, Matcher.quoteReplacement(m.group(0)!!)) continue } // exists but does not match, so we need to dedupe _writeDstMedia(lname, srcData) m.appendReplacement( sb, Matcher.quoteReplacement(m.group(0)!!.replace(fname, lname)) ) } catch (e: IOException) { Timber.w(e, "Failed to close stream") } } m.appendTail(sb) _fields = sb.toString() } return _fields } /** * Post-import cleanup * *********************************************************** */ private fun _postImport() { for (did in mDecks!!.values) { mCol.sched.maybeRandomizeDeck(did) } // make sure new position is correct dst.set_config("nextPos", dst.db.queryLongScalar("select max(due)+1 from cards where type = $CARD_TYPE_NEW")) dst.save() } /** * The methods below are not in LibAnki. * *********************************************************** */ private fun compareMedia(lhis: BufferedInputStream, rhis: BufferedInputStream): Boolean { val lhbytes = _mediaPick(lhis) val rhbytes = _mediaPick(rhis) return Arrays.equals(lhbytes, rhbytes) } /** * Return the contents of the given input stream, limited to Anki2Importer.MEDIAPICKLIMIT bytes This is only used * for comparison of media files with the limited resources of mobile devices */ private fun _mediaPick(inputStream: BufferedInputStream): ByteArray? { return try { val baos = ByteArrayOutputStream(MEDIAPICKLIMIT * 2) val buf = ByteArray(MEDIAPICKLIMIT) var readLen: Int var readSoFar = 0 inputStream.mark(MEDIAPICKLIMIT * 2) while (true) { readLen = inputStream.read(buf) baos.write(buf) if (readLen == -1) { break } readSoFar += readLen if (readSoFar > MEDIAPICKLIMIT) { break } } inputStream.reset() val result = ByteArray(MEDIAPICKLIMIT) System.arraycopy( baos.toByteArray(), 0, result, 0, Math.min(baos.size(), MEDIAPICKLIMIT) ) result } catch (e: IOException) { Timber.w(e) null } } /** * @param notesDone Percentage of notes complete. * @param cardsDone Percentage of cards complete. * @param postProcess Percentage of remaining tasks complete. */ protected fun publishProgress(notesDone: Int, cardsDone: Int, postProcess: Int) { progress?.publishProgress(res.getString(R.string.import_progress, notesDone, cardsDone, postProcess)) } /* The methods below are only used for testing. */ fun setDupeOnSchemaChange(b: Boolean) { mDupeOnSchemaChange = b } companion object { private const val MEDIAPICKLIMIT = 1024 } init { @KotlinCleanup("combined declaration and initialization") needMapper = false mDeckPrefix = null mAllowUpdate = true mDupeOnSchemaChange = false } }
gpl-3.0
f05a6256ca7c281212720175d6eb1881
39.377273
176
0.47681
4.966038
false
false
false
false
bs616/Note
app/src/main/java/com/dev/bins/note/ui/SettingsActivity.kt
1
3697
package com.dev.bins.note.ui import android.app.ActivityManager import android.app.NotificationManager import android.app.PendingIntent import android.content.Intent import android.os.Bundle import android.support.v4.app.NotificationCompat import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.MotionEvent import android.view.View import android.widget.RemoteViews import android.widget.Toast import com.dev.bins.note.R import com.dev.bins.note.service.CopyService import com.dev.bins.note.views.OptionSwitch import butterknife.ButterKnife import butterknife.InjectView class SettingsActivity : AppCompatActivity() { @InjectView(R.id.switch_service) internal var switchService: OptionSwitch? = null @InjectView(R.id.toolbar) internal var toolbar: Toolbar? = null @InjectView(R.id.notification) internal var notification: OptionSwitch? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) ButterKnife.inject(this) initToolbar() switchService!!.setmSwitch(isServiceWork) switchService!!.setOnClickListener { val isSwitch = switchService!!.isSwitch switchService!!.setmSwitch(!isSwitch) val intent = Intent(applicationContext, CopyService::class.java) if (!isSwitch) { startService(intent) } else { stopService(intent) } } notification!!.setOnClickListener { val mBuilder = NotificationCompat.Builder(applicationContext) .setSmallIcon(R.mipmap.ic_add_white) .setContentTitle("My notification") .setContentText("Hello World!") val resultIntent = Intent(applicationContext, CopyService::class.java) resultIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK val resultPendingIntent = PendingIntent.getService( applicationContext, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT ) // mBuilder.setContentIntent(resultPendingIntent); val views = RemoteViews(packageName, R.layout.notification_layout) views.setOnClickPendingIntent(R.id.nf_switch, resultPendingIntent) mBuilder.setContent(views) val mNotificationId = 1 val mNotifyMgr = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager mNotifyMgr.notify(mNotificationId, mBuilder.build()) Toast.makeText(this@SettingsActivity, "嘿嘿还没有实现的功能!", Toast.LENGTH_SHORT).show() } } private fun initToolbar() { setSupportActionBar(toolbar) supportActionBar!!.setDisplayHomeAsUpEnabled(true) toolbar!!.setNavigationOnClickListener { finish() } } private val isServiceWork: Boolean get() { var isWork = false val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val runningServices = activityManager.getRunningServices(40) if (runningServices.size <= 0) return false for (runningService in runningServices) { val name = runningService.service.className.toString() if (name == "com.dev.bins.note.service.CopyService") { isWork = true break } } return isWork } }
apache-2.0
4d00ef4f780b66b8167d0ca68f0dd34b
33.364486
98
0.65189
5.157083
false
false
false
false