repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
pagecloud/fitcloud-bot
src/main/kotlin/com/pagecloud/slack/Routes.kt
1
3279
package com.pagecloud.slack import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.stereotype.Component import org.springframework.web.reactive.function.BodyInserters.fromObject import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.server.* import org.springframework.web.reactive.function.server.RequestPredicates.GET import org.springframework.web.reactive.function.server.RequestPredicates.POST import org.springframework.web.reactive.function.server.RouterFunctions.route import org.springframework.web.reactive.function.server.ServerResponse.* import reactor.core.publisher.Mono /** * @author Edward Smith */ @Component class Router(val slackProperties: SlackProperties) : RouterFunction<ServerResponse> { val webClient: WebClient = WebClient.create() override fun route(request: ServerRequest): Mono<HandlerFunction<ServerResponse>> { return route(POST("/notify/{channel}"), notifyChannel()).and( route(POST("/notify"), notifyChannel())).and( route(GET("/**"), sayHello())) .route(request) } fun sayHello() = HandlerFunction { req -> ok().contentType(MediaType.APPLICATION_JSON).body(fromObject("Hello!")) } fun notifyChannel() = HandlerFunction { req -> req.bodyToMono<IncomingMessage>().flatMap { incoming -> if (incoming.apiKey == "someApiKey") { val channel = req.pathVariables().getOrElse("channel", { "#general" }) val message = SlackMessage( username = incoming.username, channel = if (channel[0] == '#' || channel[0] =='@') channel else "#$channel", text = incoming.text, attachments = listOf( Attachment( title = incoming.title, text = incoming.details ) ) ) webClient.post() .uri(slackProperties.webhookUrl!!) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .syncBody(message) .exchange() .flatMap { response -> if (response.statusCode().is2xxSuccessful) ok().build() else status(HttpStatus.INTERNAL_SERVER_ERROR).build() } } else { status(HttpStatus.FORBIDDEN).build() } }.onErrorResume { badRequest().build() } } } data class IncomingMessage(val apiKey: String, val text: String, val title: String, val details: String, val username: String = "eng-notifications") data class SlackMessage(val username: String, val channel: String, val text: String, val attachments: List<Attachment>, val markdwn: Boolean = true) data class Attachment(val title: String, val text: String)
unlicense
07caa344cbc9fda32043bc6d982713e0
39.9875
98
0.57853
5.2464
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/ui/views/viewer/MediaUri.kt
1
1530
package com.pr0gramm.app.ui.views.viewer import android.content.Context import android.net.Uri import com.pr0gramm.app.feed.FeedItem import com.pr0gramm.app.services.UriHelper import com.pr0gramm.app.util.isLocalFile import java.util.* /** */ data class MediaUri(val id: Long, val baseUri: Uri, val mediaType: MediaUri.MediaType, val delay: Boolean = false) { fun withDelay(value: Boolean): MediaUri { return copy(delay = value) } val isLocalFile: Boolean = baseUri.isLocalFile override fun toString(): String { return baseUri.toString() } enum class MediaType { IMAGE, VIDEO, GIF } companion object { /** * Returns a media uri and guesses the media type from the uri. */ fun of(id: Long, uri: Uri): MediaUri { val name = uri.lastPathSegment ?: throw IllegalArgumentException("uri must have a file component") var type = MediaType.IMAGE if (name.lowercase(Locale.getDefault()).endsWith(".gif")) type = MediaType.GIF if (name.lowercase(Locale.getDefault()).matches(".*\\.(webm|mpe?g|mp4)".toRegex())) type = MediaType.VIDEO return MediaUri(id, uri, type) } fun of(id: Long, uri: String): MediaUri { return of(id, Uri.parse(uri)) } fun of(context: Context, item: FeedItem): MediaUri { return of(item.id, UriHelper.of(context).media(item)) } } }
mit
74a3ac9bfd398e1aec958bc51489e462
25.37931
116
0.605229
4.069149
false
false
false
false
ykrank/S1-Next
app/src/main/java/me/ykrank/s1next/data/db/BlackWordDbWrapper.kt
1
2350
package me.ykrank.s1next.data.db import android.database.Cursor import io.reactivex.Single import me.ykrank.s1next.App import me.ykrank.s1next.data.db.dbmodel.BlackWord import me.ykrank.s1next.data.db.dbmodel.BlackWordDao import me.ykrank.s1next.data.db.dbmodel.DaoSession /** * 对黑名单数据库的操作包装 * Created by AdminYkrank on 2016/2/23. */ class BlackWordDbWrapper internal constructor(private val appDaoSessionManager: AppDaoSessionManager) { private val blackWordDao: BlackWordDao get() = session.blackWordDao private val session: DaoSession get() = appDaoSessionManager.daoSession val blackWordCursor: Single<Cursor> get() = Single.just(blackWordDao.queryBuilder()) .map { builder -> builder.buildCursor().query() } fun getAllBlackWord(limit: Int, offset: Int): List<BlackWord> { return blackWordDao.queryBuilder() .limit(limit) .offset(offset) .list() } fun getAllNotNormalBlackWord(): List<BlackWord> { return blackWordDao.queryBuilder() .where(BlackWordDao.Properties.Stat.notEq(BlackWord.NORMAL)) .list() } fun fromBlackWordCursor(cursor: Cursor): BlackWord { return blackWordDao.readEntity(cursor, 0) } fun count(): Long { return blackWordDao.count(); } fun getBlackWord(word: String): BlackWord? { return blackWordDao.queryBuilder() .where(BlackWordDao.Properties.Word.eq(word)) .unique() } fun saveBlackWord(blackWord: BlackWord) { if (blackWord.id == null) { blackWordDao.insert(blackWord) } else { blackWordDao.update(blackWord) } } fun delBlackWord(blackWord: BlackWord) { blackWordDao.delete(blackWord) } fun delBlackWords(blackWords: List<BlackWord>) { blackWordDao.deleteInTx(blackWords) } fun saveDefaultBlackWord(word: String) { val blackWord = BlackWord() blackWord.word = word blackWord.stat = BlackWord.HIDE blackWord.timestamp = System.currentTimeMillis() saveBlackWord(blackWord) } companion object { val instance: BlackWordDbWrapper get() = App.appComponent.blackWordDbWrapper } }
apache-2.0
d8b429168dc2a0f196ea3ca3eb590032
27.365854
103
0.648323
4.052265
false
false
false
false
die-tageszeitung/tazapp-android
tazapp/src/main/java/de/thecode/android/tazreader/start/ReportErrorFragment.kt
1
2418
package de.thecode.android.tazreader.start import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.preference.Preference import androidx.preference.SwitchPreferenceCompat import de.thecode.android.tazreader.R import de.thecode.android.tazreader.data.TazSettings import de.thecode.android.tazreader.preferences.PreferenceFragmentCompat import de.thecode.android.tazreader.reporterror.ErrorReporter import de.thecode.android.tazreader.reporterror.RequestFileLogDialog class ReportErrorFragment : PreferenceFragmentCompat() { private val logFileListener = TazSettings.OnPreferenceChangeListener<Boolean> { logFileWritePreference?.isChecked = it } val settings: TazSettings by lazy { TazSettings.getInstance(context) } private var logFileWritePreference : SwitchPreferenceCompat? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { (activity as StartActivity).onUpdateDrawer(this) val view = super.onCreateView(inflater, container, savedInstanceState) view?.setBackgroundColor(ContextCompat.getColor(inflater.context, R.color.start_fragment_background)) return view } override fun onCreatePreferencesFix(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.report_error_preferences) logFileWritePreference = findPreference(getString(R.string.pref_key_log_file)) as SwitchPreferenceCompat? val reportErrorPreference = findPreference<Preference>(getString(R.string.pref_key_report_error)) reportErrorPreference?.setOnPreferenceClickListener { if (settings.isWriteLogfile) context?.let { context -> ErrorReporter.sendErrorMail(context) } else if (isAdded) { parentFragmentManager.let { RequestFileLogDialog.newInstance().show(it, RequestFileLogDialog.DIALOG_FILELOG_REQUEST) } } true } } override fun onResume() { super.onResume() settings.addOnPreferenceChangeListener(TazSettings.PREFKEY.LOGFILE, logFileListener ) } override fun onPause() { settings.removeOnPreferenceChangeListener { logFileListener } super.onPause() } }
agpl-3.0
53e67221bde3bd776b5625fbf854d3f5
38
116
0.743176
4.875
false
false
false
false
cedardevs/onestop
buildSrc/src/main/kotlin/utils.kt
1
3133
import java.time.Instant import java.time.format.DateTimeFormatter import java.time.temporal.TemporalAccessor import java.util.* // constants object License { const val GPL20: String = "GPL-2.0" } object Versions { // this must be a valid semantic version for some downstream commands // like `npm version ${version}` that expect such a format, but having // a default allows us to spot when a published docker image was created locally, for example const val DEFAULT: String = "0.0.0" // https://www.opencontainers.org/ // https://github.com/opencontainers/image-spec/blob/master/annotations.md#annotations const val LABEL_SCHEMA: String = "1.0" const val NODE: String = "14.17.0" const val NPM: String = "8.4.1" const val ELASTIC: String = "7.17.5" const val CONFLUENT: String = "5.4.0" const val KAFKA: String = "2.4.0" const val SPRING_KAFKA: String = "2.4.1.RELEASE" const val AVRO: String = "1.9.1" const val GROOVY: String = "3.0.9" const val SPOCK: String = "2.2-M1-groovy-3.0" const val ELASTIC_SERVER: String = "7.17.5" // When changed update references to ElasticsearchVersion and ./circleci/config.yml. This used by TestContainers. const val TEST_CONTAINERS: String = "1.16.3" const val OPEN_SAML = "3.4.3" const val LOGBACK = "1.2.8" const val SLF4J = "1.7.28" const val JAVAX_SERVLET_API = "4.0.1" const val JUNIT = "4.12" const val AUTH0_JAVA_JWT = "3.4.1" const val PAC4J = "3.8.3" const val SNAKE_YAML = "1.30" const val REACTOR_BOM = "Dysprosium-SR7" const val JSONP = "2.0.0-RC2" const val JACKSON_CORE = "2.10.0" // A lot of other dependencies bring this in though. const val ONESTOP_SCHEMAS: String = "0.7.5" } // data classes data class Author( val name: String, val email: String, val website: String ) // utility functions fun environment(variable: String, default: String = ""): String { return (System.getenv(variable) ?: default).trim() } fun formatAuthors(authors: Collection<Author>, pretty: Boolean = false): String { // Your Name <[email protected]> (http://example.com) val multipleAuthors: Boolean = authors.size > 1 val prefix: String = if (pretty && multipleAuthors) "\n" else "" val separator: CharSequence = if(pretty) "\n" else ", " val formattedAuthors: String = authors.joinToString(separator = separator) { (name, email, website) -> val formatted = "$name <${email}> (${website})" formatted.prependIndent(if(pretty && multipleAuthors) "\t- " else "") } return prefix+formattedAuthors } fun printMap(map: Map<String, String>) { var n = 0 for((k,_) in map) { n = if (k.length > n) k.length else n } for ((k, v) in map) { println(String.format("> %-" + n + "s = %s", k, v)) } } // convert ISO 8601 string to a Date object fun parseDateISO(date: String): Date { val timeFormatter: DateTimeFormatter = DateTimeFormatter.ISO_DATE_TIME val accessor: TemporalAccessor = timeFormatter.parse(date) return Date.from(Instant.from(accessor)) }
gpl-2.0
a480a1325153919f4fa97c975600b78a
33.054348
161
0.655602
3.315344
false
false
false
false
tomhenne/Jerusalem
src/test/java/routing/RouterTest.kt
1
2111
package routing import de.esymetric.jerusalem.ownDataRepresentation.Node import de.esymetric.jerusalem.ownDataRepresentation.geoData.Position import de.esymetric.jerusalem.ownDataRepresentation.geoData.importExport.KML import de.esymetric.jerusalem.routing.Router import de.esymetric.jerusalem.routing.RoutingType import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertTrue import java.io.File import java.util.* class RouterTest { fun makeRoute( router: Router, lat1: Double, lng1: Double, lat2: Double, lng2: Double, name: String, dataDirectoryPath: String ): Map<RoutingType, List<Node>?> { val map = mutableMapOf<RoutingType, List<Node>?>() for (rt in RoutingType.values()) map[rt] = makeRoute( router, rt.name, lat1, lng1, lat2, lng2, name, dataDirectoryPath ) return map } fun makeRoute( router: Router, routingType: String, lat1: Double, lng1: Double, lat2: Double, lng2: Double, name: String, dataDirectoryPath: String ) : List<Node>? { println("---------------------------------------------") println("Computing Route $name ($routingType)") println("---------------------------------------------") val route = router .findRoute(routingType, lat1, lng1, lat2, lng2) assertNotNull(route) if (route == null) { println( "ERROR: no route found for " + name + " (" + routingType + ")" ) return null } println() val kml = KML() val trackPts = Vector<Position>() for (n in route) { val p = Position() p.latitude = n.lat p.longitude = n.lng trackPts.add(p) } kml.trackPositions = trackPts kml.save( dataDirectoryPath + File.separatorChar + name + "-" + routingType + ".kml" ) assertTrue(trackPts.size > 10) return route } }
apache-2.0
0216e99b5f33620cb1771f499aaf6407
33.064516
76
0.564661
4.425577
false
false
false
false
clangen/musikcube
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/browse/fragment/BrowseFragment.kt
1
3978
package io.casey.musikcube.remote.ui.browse.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.viewpager2.widget.ViewPager2 import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.tabs.TabLayout import com.google.android.material.tabs.TabLayoutMediator import io.casey.musikcube.remote.R import io.casey.musikcube.remote.ui.browse.adapter.BrowseFragmentAdapter import io.casey.musikcube.remote.ui.browse.constant.Browse import io.casey.musikcube.remote.ui.shared.activity.IFabConsumer import io.casey.musikcube.remote.ui.shared.activity.IFilterable import io.casey.musikcube.remote.ui.shared.activity.ITitleProvider import io.casey.musikcube.remote.ui.shared.activity.ITransportObserver import io.casey.musikcube.remote.ui.shared.fragment.BaseFragment import io.casey.musikcube.remote.ui.shared.mixin.PlaybackMixin class BrowseFragment: BaseFragment(), ITransportObserver, IFilterable, ITitleProvider { private lateinit var adapter: BrowseFragmentAdapter private lateinit var playback: PlaybackMixin override val title: String get() = getString(R.string.app_name) override fun onCreate(savedInstanceState: Bundle?) { playback = mixin(PlaybackMixin()) super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.browse_fragment, container, false).apply { val fab = findViewById<FloatingActionButton>(R.id.fab) val pager = findViewById<ViewPager2>(R.id.view_pager) val tabs = findViewById<TabLayout>(R.id.tab_layout) val showFabIfNecessary = { pos: Int -> adapter.fragmentAt(pos)?.let { when (it is IFabConsumer) { true -> { when (it.fabVisible) { true -> fab.show() false -> fab.hide() } } false -> fab.hide() } } } fab.setOnClickListener { (adapter.fragmentAt(pager.currentItem) as? IFabConsumer)?.onFabPress(fab) } adapter = BrowseFragmentAdapter( appCompatActivity, playback, this@BrowseFragment, R.id.content_container) adapter.onFragmentInstantiated = { pos -> if (pos == pager.currentItem) { showFabIfNecessary(pos) } } pager.isSaveEnabled = false pager.adapter = adapter pager.offscreenPageLimit = adapter.itemCount pager.registerOnPageChangeCallback(object: ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { showFabIfNecessary(position) } }) TabLayoutMediator(tabs, pager, true) { tab, position -> tab.text = adapter.getPageTitle(position) }.attach() val initialIndex = adapter.indexOf( extras.getString(Browse.Extras.INITIAL_CATEGORY_TYPE)) pager.setCurrentItem(initialIndex, false) pager.post { showFabIfNecessary(pager.currentItem) } } override fun onTransportChanged() = adapter.onTransportChanged() override val addFilterToToolbar: Boolean get() = true override fun setFilter(filter: String) { adapter.filter = filter } companion object { const val TAG = "BrowseFragment" fun create(extras: Bundle): BrowseFragment = BrowseFragment().apply { arguments = extras } } }
bsd-3-clause
4ae474a053bd6e919d8eef535c86fc28
35.504587
116
0.624686
4.991217
false
false
false
false
dafi/photoshelf
app/src/main/java/com/ternaryop/photoshelf/db/Importer.kt
1
2643
package com.ternaryop.photoshelf.db import android.content.Context import android.widget.Toast import com.ternaryop.photoshelf.R import com.ternaryop.tumblr.android.TumblrManager import com.ternaryop.tumblr.getFollowers import com.ternaryop.utils.dropbox.DropboxManager import com.ternaryop.utils.dropbox.copyFile import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.BufferedWriter import java.io.File import java.io.FileWriter import java.io.PrintWriter import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale class Importer constructor(val context: Context) { fun importFile(importPath: String, contextFileName: String) { try { copyFileToContext(importPath, contextFileName) Toast.makeText(context, context.getString(R.string.importSuccess), Toast.LENGTH_LONG).show() } catch (e: Exception) { Toast.makeText(context, e.localizedMessage, Toast.LENGTH_LONG).show() } } private fun copyFileToContext(fullPath: String, contextFileName: String) { context.openFileOutput(contextFileName, 0).use { out -> File(fullPath).forEachBlock { buffer, bytesRead -> out.write(buffer, 0, bytesRead) } } } suspend fun syncExportTotalUsersToCSV(exportPath: String, blogName: String) = withContext(Dispatchers.IO) { // do not overwrite the entire file but append to the existing one PrintWriter(BufferedWriter(FileWriter(exportPath, true))).use { pw -> val time = ISO_8601_DATE.format(Calendar.getInstance().timeInMillis) val totalUsers = TumblrManager.getInstance(context).getFollowers(blogName).totalUsers pw.println("$time;$blogName;$totalUsers") pw.flush() DropboxManager.getInstance(context).copyFile(exportPath) } } interface ImportProgressInfo<T> { var progress: Int var max: Int var items: MutableList<T> } class SimpleImportProgressInfo<T>( override var max: Int = 0, val list: MutableList<T> = mutableListOf() ) : ImportProgressInfo<T> { override var progress: Int = 0 override var items: MutableList<T> = mutableListOf() override fun toString(): String = "progress $progress max $max items $items" } val totalUsersPath: String get() = context.filesDir.absolutePath + File.separator + TOTAL_USERS_FILE_NAME companion object { private const val TOTAL_USERS_FILE_NAME = "totalUsers.csv" private val ISO_8601_DATE = SimpleDateFormat("yyyy-MM-dd", Locale.US) } }
mit
ddd29b22b697fd2439b7be3eb02a2d5f
35.708333
111
0.700341
4.311582
false
false
false
false
nemerosa/ontrack
ontrack-repository-impl/src/main/java/net/nemerosa/ontrack/repository/BranchFavouriteJdbcRepository.kt
1
1839
package net.nemerosa.ontrack.repository import net.nemerosa.ontrack.repository.support.AbstractJdbcRepository import org.springframework.stereotype.Repository import javax.sql.DataSource @Repository class BranchFavouriteJdbcRepository( dataSource: DataSource ) : AbstractJdbcRepository(dataSource), BranchFavouriteRepository { override fun getFavouriteBranches(accountId: Int): List<Int> { return namedParameterJdbcTemplate!!.queryForList( """ SELECT B.ID FROM BRANCHES B INNER JOIN BRANCH_FAVOURITES BF ON BF.BRANCHID = B.ID WHERE BF.ACCOUNTID = :accountId """, params("accountId", accountId), Int::class.java ) } override fun isBranchFavourite(accountId: Int, branchId: Int): Boolean { return getFirstItem( "SELECT ID FROM BRANCH_FAVOURITES WHERE ACCOUNTID = :account AND BRANCHID = :branch", params("account", accountId).addValue("branch", branchId), Int::class.java ) != null } override fun setBranchFavourite(accountId: Int, branchId: Int, favourite: Boolean) { if (favourite) { if (!isBranchFavourite(accountId, branchId)) { namedParameterJdbcTemplate!!.update( "INSERT INTO BRANCH_FAVOURITES(ACCOUNTID, BRANCHID) VALUES (:account, :branch)", params("account", accountId).addValue("branch", branchId) ) } } else { namedParameterJdbcTemplate!!.update( "DELETE FROM BRANCH_FAVOURITES WHERE ACCOUNTID = :account AND BRANCHID = :branch", params("account", accountId).addValue("branch", branchId) ) } } }
mit
0aede8cd4ff271cf0dd5d9458629e071
38.12766
104
0.60087
5.108333
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/lang/refactoring/extractFunction/RsExtractFunctionConfig.kt
1
1984
package org.rust.lang.refactoring.extractFunction import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.rust.ide.utils.findStatementsInRange import org.rust.lang.core.psi.RsFunction import org.rust.lang.core.psi.RsImplItem import org.rust.lang.core.psi.ext.parentOfType import org.rust.lang.core.psi.ext.selfParameter class RsExtractFunctionConfig(val file: PsiFile, start: Int, end: Int) { var implType = RsWrapperType.Function var anchor: RsFunction? = null var elements: List<PsiElement> = emptyList() var name = "" var visibilityLevelPublic = false init { init(start, end) } private fun init(start: Int, end: Int) { elements = findStatementsInRange(file, start, end).asList() if (elements.isEmpty()) return val first = elements.first() val last = elements.last() // check element should be a part of one block val parentOfFirst = first.parentOfType<RsFunction>() ?: return anchor = last.parentOfType<RsFunction>() ?: return if (parentOfFirst != anchor) { return } // find wrapper parent type of selection: fun / method / trait impl method val impl = parentOfFirst.parent as? RsImplItem? if (impl != null) { if (impl.traitRef != null) { if (parentOfFirst.selfParameter == null) { implType = RsWrapperType.TraitFunction } else { implType = RsWrapperType.TraitMethod } } else { if (parentOfFirst.selfParameter == null) { implType = RsWrapperType.ImplFunction } else { implType = RsWrapperType.ImplMethod } } } //TODO: Find possible input and output parameter } fun isMethod() = implType == RsWrapperType.TraitMethod || implType == RsWrapperType.ImplMethod }
mit
76f65130c6e27d448f587120b36dc7b5
32.627119
85
0.612399
4.379691
false
false
false
false
olonho/carkot
translator/src/main/kotlin/org/kotlinnative/translator/codegens/PropertyCodegen.kt
1
1487
package org.kotlinnative.translator.codegens import org.jetbrains.kotlin.js.descriptorUtils.nameIfStandardType import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.resolve.BindingContext import org.kotlinnative.translator.TranslationState import org.kotlinnative.translator.VariableManager import org.kotlinnative.translator.llvm.LLVMBuilder import org.kotlinnative.translator.llvm.LLVMInstanceOfStandardType import org.kotlinnative.translator.llvm.LLVMVariable import org.kotlinnative.translator.llvm.LLVMVariableScope class PropertyCodegen(val state: TranslationState, val variableManager: VariableManager, val property: KtProperty, val codeBuilder: LLVMBuilder) { fun generate() { val varInfo = state.bindingContext.get(BindingContext.VARIABLE, property)?.compileTimeInitializer ?: return val kotlinType = varInfo.type val value = varInfo.value if (kotlinType.nameIfStandardType != null) { val variableType = LLVMInstanceOfStandardType(property.name ?: return, kotlinType, state = state).type val variable = LLVMVariable(property.name.toString(), variableType, property.name.toString(), LLVMVariableScope()) variableManager.addGlobalVariable(property.name.toString(), variable) codeBuilder.defineGlobalVariable(variable, variableType.parseArg(value.toString())) variable.pointer++ } } }
mit
e90e9da4e0e9c6adb8f57fd08f3a60a9
44.090909
126
0.742434
4.973244
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/util/MemberReference.kt
1
4714
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.util import com.demonwav.mcdev.platform.mixin.reference.MixinSelector import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.intellij.psi.PsiClass import com.intellij.psi.PsiField import com.intellij.psi.PsiMethod import java.io.Serializable import java.lang.reflect.Type /** * Represents a reference to a class member (a method or a field). It may * resolve to multiple members if [matchAllNames] or [matchAllDescs] is set or if the member is * not full qualified. */ data class MemberReference( val name: String, val descriptor: String? = null, override val owner: String? = null, val matchAllNames: Boolean = false, val matchAllDescs: Boolean = false ) : Serializable, MixinSelector { init { assert(owner?.contains('/') != true) } val withoutOwner get() = if (this.owner == null) { this } else { MemberReference(this.name, this.descriptor, null, this.matchAllNames, this.matchAllDescs) } override val methodDescriptor = descriptor?.takeIf { it.contains("(") } override val fieldDescriptor = descriptor?.takeUnless { it.contains("(") } override val displayName = name override fun canEverMatch(name: String): Boolean { return matchAllNames || this.name == name } private fun matchOwner(clazz: String): Boolean { assert(!clazz.contains('.')) return this.owner == null || this.owner == clazz.replace('/', '.') } override fun matchField(owner: String, name: String, desc: String): Boolean { assert(!owner.contains('.')) return (this.matchAllNames || this.name == name) && matchOwner(owner) && (this.descriptor == null || this.descriptor == desc) } override fun matchMethod(owner: String, name: String, desc: String): Boolean { assert(!owner.contains('.')) return (this.matchAllNames || this.name == name) && matchOwner(owner) && (this.descriptor == null || this.descriptor == desc) } object Deserializer : JsonDeserializer<MemberReference> { override fun deserialize(json: JsonElement, type: Type, ctx: JsonDeserializationContext): MemberReference { val ref = json.asString val className = ref.substringBefore('#') val methodName = ref.substring(className.length + 1, ref.indexOf("(")) val methodDesc = ref.substring(className.length + methodName.length + 1) return MemberReference(methodName, methodDesc, className) } } } // Class fun PsiClass.findMethods(member: MixinSelector, checkBases: Boolean = false): Sequence<PsiMethod> { val methods = if (checkBases) { allMethods.asSequence() } else { methods.asSequence() } + constructors return methods.filter { member.matchMethod(it, this) } } fun PsiClass.findField(selector: MixinSelector, checkBases: Boolean = false): PsiField? { val fields = if (checkBases) { allFields.toList() } else { fields.toList() } return fields.firstOrNull { selector.matchField(it, this) } } // Method val PsiMethod.memberReference get() = MemberReference(internalName, descriptor) val PsiMethod.qualifiedMemberReference get() = MemberReference(internalName, descriptor, containingClass?.fullQualifiedName) fun PsiMethod.getQualifiedMemberReference(owner: PsiClass): MemberReference { return getQualifiedMemberReference(owner.fullQualifiedName) } fun PsiMethod.getQualifiedMemberReference(owner: String?): MemberReference { return MemberReference(internalName, descriptor, owner) } fun PsiMethod?.isSameReference(reference: PsiMethod?): Boolean = this != null && (this === reference || qualifiedMemberReference == reference?.qualifiedMemberReference) // Field val PsiField.simpleMemberReference get() = MemberReference(name) val PsiField.memberReference get() = MemberReference(name, descriptor) val PsiField.simpleQualifiedMemberReference get() = MemberReference(name, null, containingClass!!.fullQualifiedName) val PsiField.qualifiedMemberReference get() = MemberReference(name, descriptor, containingClass!!.fullQualifiedName) fun PsiField.getQualifiedMemberReference(owner: PsiClass): MemberReference { return getQualifiedMemberReference(owner.fullQualifiedName) } fun PsiField.getQualifiedMemberReference(owner: String?): MemberReference { return MemberReference(name, descriptor, owner) }
mit
a65d703140f407ca2f7ea1bd58ba19f0
31.965035
115
0.698982
4.603516
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/sponge/SpongeModuleType.kt
1
1685
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.sponge import com.demonwav.mcdev.asset.PlatformAssets import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.platform.AbstractModuleType import com.demonwav.mcdev.platform.PlatformType import com.demonwav.mcdev.platform.sponge.generation.SpongeEventGenerationPanel import com.demonwav.mcdev.platform.sponge.util.SpongeConstants import com.demonwav.mcdev.util.CommonColors import com.intellij.psi.PsiClass object SpongeModuleType : AbstractModuleType<SpongeModule>("org.spongepowered", "spongeapi") { private const val ID = "SPONGE_MODULE_TYPE" private val IGNORED_ANNOTATIONS = listOf( SpongeConstants.LISTENER_ANNOTATION, SpongeConstants.PLUGIN_ANNOTATION, SpongeConstants.JVM_PLUGIN_ANNOTATION ) private val LISTENER_ANNOTATIONS = listOf(SpongeConstants.LISTENER_ANNOTATION) init { CommonColors.applyStandardColors(colorMap, SpongeConstants.TEXT_COLORS) } override val platformType = PlatformType.SPONGE override val icon = PlatformAssets.SPONGE_ICON override val id = ID override val ignoredAnnotations = IGNORED_ANNOTATIONS override val listenerAnnotations = LISTENER_ANNOTATIONS override val isEventGenAvailable = true override fun generateModule(facet: MinecraftFacet) = SpongeModule(facet) override fun getDefaultListenerName(psiClass: PsiClass): String = defaultNameForSubClassEvents(psiClass) override fun getEventGenerationPanel(chosenClass: PsiClass) = SpongeEventGenerationPanel(chosenClass) }
mit
f5821d38d53b0e22992bdae3f0f069b0
34.851064
108
0.786944
4.541779
false
false
false
false
hummatli/MAHAds
app-cross-promoter/src/main/java/com/mobapphome/appcrosspromoter/commons/Extensions.kt
2
2182
package com.mobapphome.appcrosspromoter.commons import android.content.Context import android.graphics.PorterDuff import android.graphics.Typeface import android.graphics.drawable.Drawable import android.support.v4.content.ContextCompat import android.text.method.LinkMovementMethod import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.AnimationUtils import android.widget.ImageView import android.widget.TextView /** * Created by settar on 6/23/17. */ fun TextView.decorateAsLink() { this.movementMethod = LinkMovementMethod.getInstance() } fun TextView.setFontTextView(fontName: String?) = if (fontName != null) { try { val font = Typeface.createFromAsset(context.assets, fontName) typeface = font } catch (r: RuntimeException) { Log.e("test", "Error " + r.message) } } else { } fun ViewGroup.inflate(layoutRes: Int): View = LayoutInflater.from(context).inflate(layoutRes, this, false) fun View.makeVisible() { visibility = View.VISIBLE } fun View.makeInvisible() { visibility = View.INVISIBLE } fun View.makeGone() { visibility = View.GONE } fun View.isVisible(): Boolean = visibility == View.VISIBLE fun View.isGone(): Boolean = visibility == View.GONE fun View.isInVisible(): Boolean = visibility == View.INVISIBLE fun ImageView.setColorFilterCompat(color: Int, mode: PorterDuff.Mode = PorterDuff.Mode.SRC_IN) { setColorFilter(ContextCompat.getColor(context, color), mode) } fun Context.getDrawableWithColorFilter(id: Int, color: Int, mode: PorterDuff.Mode = PorterDuff.Mode.SRC_IN): Drawable { val drawable = ContextCompat.getDrawable(this, id) drawable!!.setColorFilter(ContextCompat.getColor(this, color), mode) return drawable } fun View.startAnimationFillAfter(id: Int, fillAfter: Boolean = true){ val animRotate = AnimationUtils.loadAnimation(context, id) animRotate.fillAfter = fillAfter //For the textview to remain at the same place after the rotation animation = animRotate startAnimation(animRotate) }
apache-2.0
8857b590171d1f5c86f5a9cdfeb8a4c8
28.90411
119
0.730522
4.236893
false
false
false
false
bozaro/git-as-svn
src/test/kotlin/svnserver/SvnTestServer.kt
1
11752
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver import org.eclipse.jgit.api.Git import org.eclipse.jgit.api.errors.GitAPIException import org.eclipse.jgit.internal.storage.file.FileRepository import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.lib.Repository import org.tmatesoft.sqljet.core.internal.SqlJetPagerJournalMode import org.tmatesoft.svn.core.SVNURL import org.tmatesoft.svn.core.auth.BasicAuthenticationManager import org.tmatesoft.svn.core.internal.delta.SVNDeltaCompression import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions import org.tmatesoft.svn.core.internal.wc.SVNFileUtil import org.tmatesoft.svn.core.internal.wc17.SVNWCContext import org.tmatesoft.svn.core.io.SVNRepository import org.tmatesoft.svn.core.io.SVNRepositoryFactory import org.tmatesoft.svn.core.wc2.SvnOperationFactory import svnserver.config.* import svnserver.config.LocalUserDBConfig.UserEntry import svnserver.context.LocalContext import svnserver.context.SharedContext import svnserver.ext.gitlfs.LocalLfsConfig import svnserver.ext.gitlfs.storage.LfsStorage import svnserver.ext.gitlfs.storage.LfsStorageFactory import svnserver.ext.gitlfs.storage.memory.LfsMemoryStorage import svnserver.ext.web.config.WebServerConfig import svnserver.repository.RepositoryMapping import svnserver.repository.VcsAccess import svnserver.repository.git.EmptyDirsSupport import svnserver.repository.git.GitRepository import svnserver.repository.git.RepositoryFormat import svnserver.repository.git.push.GitPushEmbedded import svnserver.server.SvnServer import svnserver.tester.SvnTester import java.nio.file.Path import java.util.* import java.util.function.Function /** * Test subversion server. * * @author Artem V. Navrotskiy <[email protected]> */ class SvnTestServer private constructor( repository: Repository, branch: String?, prefix: String, safeBranch: Boolean, userDBConfig: UserDBConfig?, mappingConfigCreator: Function<Path, RepositoryMappingConfig>?, anonymousRead: Boolean, lfsMode: LfsMode, emptyDirs: EmptyDirsSupport, vararg shared: SharedConfig ) : SvnTester { val tempDirectory: Path val repository: Repository private var testBranch: String private val prefix: String private val server: SvnServer private val svnFactories = ArrayList<SvnOperationFactory>() private val safeBranch: Boolean private fun cleanupBranches(repository: Repository) { val branches = ArrayList<String>() for (ref in repository.refDatabase.getRefsByPrefix(Constants.R_HEADS + TEST_BRANCH_PREFIX)) { branches.add(ref.name.substring(Constants.R_HEADS.length)) } if (branches.isNotEmpty()) { for (branch in branches) { log.info("Cleanup branch: {}", branch) try { Git(repository) .branchDelete() .setBranchNames(branch) .setForce(true) .call() } catch (e: GitAPIException) { log.error("Cleanup branch: $branch", e) } } } } val context: SharedContext get() = server.sharedContext override val url: SVNURL get() = getUrl(true) fun getUrl(withPrefix: Boolean): SVNURL { return SVNURL.create("svn", null, BIND_HOST, server.port, if (withPrefix) prefix else "", true) } override fun openSvnRepository(): SVNRepository { return openSvnRepository(USER_NAME, PASSWORD) } fun openSvnRepository(username: String, password: String): SVNRepository { return openSvnRepository(url, username, password) } override fun close() { shutdown(0) if (safeBranch) { Git(repository) .branchDelete() .setBranchNames(testBranch) .setForce(true) .call() } for (factory in svnFactories) { factory.dispose() } svnFactories.clear() repository.close() TestHelper.deleteDirectory(tempDirectory) } fun shutdown(millis: Int) { server.shutdown(millis.toLong()) } fun createOperationFactory(): SvnOperationFactory { return createOperationFactory(USER_NAME, PASSWORD) } private fun createOperationFactory(username: String, password: String): SvnOperationFactory { val wcContext = SVNWCContext(DefaultSVNOptions(tempDirectory.toFile(), true), null) wcContext.setSqliteTemporaryDbInMemory(true) wcContext.setSqliteJournalMode(SqlJetPagerJournalMode.MEMORY) val factory = SvnOperationFactory(wcContext) factory.authenticationManager = BasicAuthenticationManager.newInstance(username, password.toCharArray()) svnFactories.add(factory) return factory } fun startShutdown() { server.startShutdown() } enum class LfsMode { None, Memory, Local } private class TestRepositoryConfig(private val git: Repository, private val branch: String, private val prefix: String, private val anonymousRead: Boolean, private val emptyDirs: EmptyDirsSupport) : RepositoryMappingConfig { override fun create(context: SharedContext, canUseParallelIndexing: Boolean): RepositoryMapping<GitRepository> { val local = LocalContext(context, "test") local.add(VcsAccess::class.java, if (anonymousRead) VcsAccessEveryone.instance else VcsAccessNoAnonymous.instance) val repository = GitRepositoryConfig.createRepository( local, LfsStorageFactory.tryCreateStorage(local), git, GitPushEmbedded(local, null, false), setOf(branch), true, emptyDirs, RepositoryFormat.Latest ) return object : RepositoryMapping<GitRepository> { override val mapping: NavigableMap<String, GitRepository> get() = TreeMap(Collections.singletonMap(prefix, repository)) } } } companion object { const val USER_NAME_NO_MAIL = "nomail" const val PASSWORD = "passw0rd" const val USER_NAME = "tester" private val log = TestHelper.logger private const val REAL_NAME = "Test User" private const val EMAIL = "[email protected]" private const val TEST_BRANCH_PREFIX = "test_" fun openSvnRepository(url: SVNURL, username: String, password: String): SVNRepository { val repo = SVNRepositoryFactory.create(url) repo.authenticationManager = BasicAuthenticationManager.newInstance(username, password.toCharArray()) return repo } fun createEmpty(): SvnTestServer { return createEmpty(null, false, LfsMode.Memory, EmptyDirsSupport.Disabled) } fun createEmpty(userDBConfig: UserDBConfig?, anonymousRead: Boolean, lfsMode: LfsMode, emptyDirs: EmptyDirsSupport, vararg shared: SharedConfig): SvnTestServer { return createEmpty(userDBConfig, null, anonymousRead, lfsMode, emptyDirs, *shared) } fun createEmpty(userDBConfig: UserDBConfig?, mappingConfigCreator: Function<Path, RepositoryMappingConfig>?, anonymousRead: Boolean, lfsMode: LfsMode, emptyDirs: EmptyDirsSupport, vararg shared: SharedConfig): SvnTestServer { return SvnTestServer(TestHelper.emptyRepository(), Constants.MASTER, "", false, userDBConfig, mappingConfigCreator, anonymousRead, lfsMode, emptyDirs, *shared) } fun createEmpty(userDBConfig: UserDBConfig?, mappingConfigCreator: Function<Path, RepositoryMappingConfig>?, anonymousRead: Boolean, lfsMode: LfsMode, vararg shared: SharedConfig): SvnTestServer { return createEmpty(userDBConfig, mappingConfigCreator, anonymousRead, lfsMode, EmptyDirsSupport.Disabled, *shared) } fun createEmpty(userDBConfig: UserDBConfig?, anonymousRead: Boolean, lfsMode: LfsMode, vararg shared: SharedConfig): SvnTestServer { return createEmpty(userDBConfig, null, anonymousRead, lfsMode, EmptyDirsSupport.Disabled, *shared) } fun createEmpty(emptyDirs: EmptyDirsSupport): SvnTestServer { return createEmpty(null, false, LfsMode.Memory, emptyDirs) } fun createEmpty(userDBConfig: UserDBConfig?, anonymousRead: Boolean, vararg shared: SharedConfig): SvnTestServer { return createEmpty(userDBConfig, null, anonymousRead, LfsMode.Memory, EmptyDirsSupport.Disabled, *shared) } fun createMasterRepository(): SvnTestServer { return SvnTestServer(FileRepository(TestHelper.findGitPath().toFile()), null, "", true, null, null, true, LfsMode.Memory, EmptyDirsSupport.Disabled) } private const val BIND_HOST = "127.0.0.2" } init { SVNFileUtil.setSleepForTimestamp(false) this.repository = repository this.safeBranch = safeBranch tempDirectory = TestHelper.createTempDir("git-as-svn") val srcBranch = branch ?: repository.branch if (safeBranch) { cleanupBranches(repository) testBranch = TEST_BRANCH_PREFIX + UUID.randomUUID().toString().replace("-".toRegex(), "").substring(0, 8) Git(repository) .branchCreate() .setName(testBranch) .setStartPoint(srcBranch) .call() } else { testBranch = srcBranch } this.prefix = "$prefix/$testBranch" val config = Config(BIND_HOST, 0) config.compressionLevel = SVNDeltaCompression.None config.cacheConfig = MemoryCacheConfig() when (lfsMode) { LfsMode.Local -> { config.shared.add(WebServerConfig(0)) config.shared.add(LocalLfsConfig(tempDirectory.resolve("lfs").toString(), false)) } LfsMode.Memory -> { config.shared.add(SharedConfig { context: SharedContext -> context.add(LfsStorageFactory::class.java, object : LfsStorageFactory { override fun createStorage(context: LocalContext): LfsStorage { return LfsMemoryStorage() } }) }) } LfsMode.None -> Unit } if (mappingConfigCreator != null) { config.repositoryMapping = mappingConfigCreator.apply(tempDirectory) } else { config.repositoryMapping = TestRepositoryConfig(repository, testBranch, prefix, anonymousRead, emptyDirs) } if (userDBConfig != null) { config.userDB = userDBConfig } else { config.userDB = LocalUserDBConfig( arrayOf( UserEntry(USER_NAME, REAL_NAME, EMAIL, PASSWORD), UserEntry(USER_NAME_NO_MAIL, REAL_NAME, null, PASSWORD) ) ) } Collections.addAll(config.shared, *shared) server = SvnServer(tempDirectory, config) server.start() log.info("Temporary server started (url: {}, path: {}, branch: {} as {})", url, repository.directory, srcBranch, testBranch) log.info("Temporary directory: {}", tempDirectory) } }
gpl-2.0
6183abcec6996d01d2c88ce272abace9
41.121864
233
0.665844
4.614056
false
true
false
false
traversals/kapsule
samples/android/src/main/java/net/gouline/kapsule/demo/App.kt
1
1846
/* * Copyright 2017 Mike Gouline * * 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 net.gouline.kapsule.demo import android.app.Application import android.content.Context import net.gouline.kapsule.demo.di.MainAndroidModule import net.gouline.kapsule.demo.di.MainDataModule import net.gouline.kapsule.demo.di.Module import net.gouline.kapsule.transitive /** * Custom application class. */ open class App : Application() { companion object { /** * Retrieves module from any context. */ fun module(context: Context) = (context.applicationContext as App).module } @Suppress("LeakingThis") private val module = createModule() open protected fun createModule() = Module( android = MainAndroidModule(this), data = MainDataModule(this)) .transitive() }
mit
1894fee6ec08826f8547778cdd32f4a0
45.15
463
0.746479
4.721228
false
false
false
false
dewarder/Android-Kotlin-Commons
akommons-bindings-common-test/src/main/java/com/dewarder/akommons/binding/common/string/BaseStringTest.kt
1
3740
package com.dewarder.akommons.binding.common.string import android.content.res.Resources import com.dewarder.akommons.binding.common.get import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.ExpectedException import kotlin.reflect.KProperty abstract class BaseStringTest { @get:Rule val exceptionRule = ExpectedException.none() private lateinit var stringRequiredExist: KProperty<String> private lateinit var stringRequiredAbsent: KProperty<String> private lateinit var stringOptionalExist: KProperty<String?> private lateinit var stringOptionalAbsent: KProperty<String?> private lateinit var stringsRequiredExist: KProperty<List<String>> private lateinit var stringsRequiredAbsent: KProperty<List<String>> private lateinit var stringsOptionalExist: KProperty<List<String?>> private lateinit var stringsOptionalAbsent: KProperty<List<String?>> private lateinit var stringsRequiredFirstExistSecondAbsent: KProperty<List<String>> private lateinit var stringsOptionalFirstExistSecondAbsent: KProperty<List<String?>> abstract fun getTestableString(): TestableString @Before fun init() { getTestableString().let { stringRequiredExist = it::stringRequiredExist stringRequiredAbsent = it::stringRequiredAbsent stringOptionalExist = it::stringOptionalExist stringOptionalAbsent = it::stringOptionalAbsent stringsRequiredExist = it::stringsRequiredExist stringsRequiredAbsent = it::stringsRequiredAbsent stringsOptionalExist = it::stringsOptionalExist stringsOptionalAbsent = it::stringsOptionalAbsent stringsRequiredFirstExistSecondAbsent = it::stringsRequiredFirstExistSecondAbsent stringsOptionalFirstExistSecondAbsent = it::stringsOptionalFirstExistSecondAbsent } } @Test fun testOneStringRequiredExist() { assertEquals(stringRequiredExist.get(), "test1") } @Test fun testOneStringRequiredAbsent() { exceptionRule.expect(Resources.NotFoundException::class.java) stringRequiredAbsent.get() } @Test fun testOneStringOptionalExist() { assertEquals(stringOptionalExist.get(), "test1") } @Test fun testOneStringOptionalAbsent() { assertNull(stringOptionalAbsent.get()) } @Test fun testManyStringsRequiredExist() { val list = stringsRequiredExist.get() assertEquals(list.size, 2) assertEquals(list.first(), "test1") assertEquals(list.last(), "test2") } @Test fun testManyStringsRequiredAbsent() { exceptionRule.expect(Resources.NotFoundException::class.java) stringsRequiredAbsent.get() } @Test fun testManyStringsOptionalExist() { val list = stringsOptionalExist.get() assertEquals(list.size, 2) assertEquals(list.first(), "test1") assertEquals(list.last(), "test2") } @Test fun testManyStringsOptionalAbsent() { val list = stringsOptionalAbsent.get() assertEquals(list.size, 2) assertNull(list.first()) assertNull(list.last()) } @Test fun testManyStringsRequiredFirstExistSecondAbsent() { exceptionRule.expect(Resources.NotFoundException::class.java) stringsRequiredFirstExistSecondAbsent.get() } @Test fun testManyStringsOptionalFirstExistSecondAbsent() { val list = stringsOptionalFirstExistSecondAbsent.get() assertEquals(list.size, 2) assertEquals(list.first(), "test1") assertNull(list.last()) } }
apache-2.0
5d1ec2d74781c07c15c157234fd0f7e4
32.106195
93
0.713102
5.252809
false
true
false
false
edvin/tornadofx
src/main/java/tornadofx/DataGrid.kt
1
29206
@file:Suppress("UNCHECKED_CAST") package tornadofx import com.sun.javafx.scene.control.behavior.BehaviorBase import com.sun.javafx.scene.control.behavior.CellBehaviorBase import com.sun.javafx.scene.control.skin.CellSkinBase import com.sun.javafx.scene.control.skin.VirtualContainerBase import javafx.beans.InvalidationListener import javafx.beans.property.* import javafx.beans.value.ChangeListener import javafx.beans.value.ObservableValue import javafx.collections.FXCollections import javafx.collections.ListChangeListener import javafx.collections.ObservableList import javafx.collections.WeakListChangeListener import javafx.css.* import javafx.event.EventTarget import javafx.geometry.Pos import javafx.scene.Node import javafx.scene.control.* import javafx.scene.control.SelectionMode.MULTIPLE import javafx.scene.control.SelectionMode.SINGLE import javafx.scene.input.* import javafx.scene.layout.HBox import javafx.scene.layout.StackPane import java.util.* import kotlin.reflect.KClass fun <T> EventTarget.datagrid( items: List<T>? = null, scope: Scope = FX.defaultScope, op: DataGrid<T>.() -> Unit = {} ) = DataGrid<T>().attachTo(this, op){ it.scope = scope if (items is ObservableList<T>) it.items = items else if (items is List<T>) it.items.setAll(items) } class DataGridPaginator<T>(private val sourceItems: ObservableList<T>, itemsPerPage: Int = 20): HBox() { val itemsPerPageProperty = SimpleIntegerProperty(itemsPerPage) var itemsPerPage by itemsPerPageProperty val items = FXCollections.observableArrayList<T>() private val listChangeTrigger = SimpleObjectProperty(UUID.randomUUID()) val pageCountProperty = integerBinding(itemsPerPageProperty, sourceItems) { Math.max(1, Math.ceil(sourceItems.size.toDouble() / itemsPerPageProperty.value.toDouble()).toInt()) } val pageCount by pageCountProperty val currentPageProperty = SimpleIntegerProperty(1) var currentPage by currentPageProperty private val listChangeListener = ListChangeListener<T> { listChangeTrigger.value = UUID.randomUUID() setItemsForPage() // Check that the current page is still valid, or regenerate buttons while (currentPage > pageCount) currentPage -= 1 } private val currentFromIndex: Int get() = itemsPerPage * (currentPage - 1) private val currentToIndex: Int get() = Math.min(currentFromIndex + itemsPerPage, sourceItems.size) init { spacing = 5.0 alignment = Pos.CENTER currentPageProperty.onChange { setItemsForPage() } pageCountProperty.onChange { generatePageButtons() } sourceItems.addListener(listChangeListener) generatePageButtons() setItemsForPage() } private fun setItemsForPage() { items.setAll(sourceItems.subList(currentFromIndex, currentToIndex)) } private fun generatePageButtons() { children.clear() togglegroup { // TODO: Support pagination for pages IntRange(1, pageCount).forEach { pageNo -> // TODO: Allow customization of togglebutton graphic/text togglebutton(pageNo.toString()) { whenSelected { currentPage = pageNo } } } } } } @Suppress("unused") class DataGrid<T>(items: ObservableList<T>) : Control() { constructor() : this(FXCollections.observableArrayList()) constructor(items: List<T>) : this(FXCollections.observableArrayList(items)) private val FACTORY = StyleablePropertyFactory<DataGrid<T>>(Control.getClassCssMetaData()) internal var graphicCache = mutableMapOf<T, Node>() val itemsProperty = SimpleListProperty<T>(this, "items", items) var items: ObservableList<T> get() = itemsProperty.get(); set(value) = itemsProperty.set(value) val cellFactoryProperty = SimpleObjectProperty<(DataGrid<T>) -> DataGridCell<T>>(this, "cellFactory") var cellFactory: ((DataGrid<T>) -> DataGridCell<T>)? get() = cellFactoryProperty.get(); set(value) = cellFactoryProperty.set(value) val cellFormatProperty by lazy { SimpleObjectProperty<(DataGridCell<T>.(T) -> Unit)>() } var cellFormat: ((DataGridCell<T>).(T) -> Unit)? get() = cellFormatProperty.get(); set(value) = cellFormatProperty.set(value) fun cellFormat(cellFormat: (DataGridCell<T>).(T) -> Unit) { this.cellFormat = cellFormat } val scopeProperty = SimpleObjectProperty<Scope>() var scope: Scope? by scopeProperty val cellCacheProperty by lazy { SimpleObjectProperty<((T) -> Node)>() } var cellCache: ((T) -> Node)? get() = cellCacheProperty.get(); set(value) = cellCacheProperty.set(value) /** * Assign a Node to the graphic property of this cell. The graphic is cached and will be reused * for whatever cell is currently displaying the current item. Cells will in their life cycle be * used to display serveral different items, but using this function will make sure that there is * never a mismatch between the cached graphic node and the item it was created for. */ fun cellCache(cachedGraphic: (T) -> Node) { this.cellCache = cachedGraphic } val cellFragmentProperty by lazy { SimpleObjectProperty<KClass<DataGridCellFragment<T>>>() } var cellFragment by cellFragmentProperty fun cellFragment(fragment: KClass<DataGridCellFragment<T>>) { properties["tornadofx.cellFragment"] = fragment } inline fun <reified C : DataGridCellFragment<T>> cellFragment() { properties["tornadofx.cellFragment"] = C::class } val cellWidthProperty: StyleableObjectProperty<Number> = FACTORY.createStyleableNumberProperty(this, "cellWidth", "-fx-cell-width", { it.cellWidthProperty }, 150.0) as StyleableObjectProperty<Number> var cellWidth: Double get() = cellWidthProperty.value as Double; set(value) { cellWidthProperty.value = value } val maxCellsInRowProperty: StyleableObjectProperty<Number> = FACTORY.createStyleableNumberProperty(this, "maxCellsInRow", "-fx-max-cells-in-row", { it.maxCellsInRowProperty }, Int.MAX_VALUE) as StyleableObjectProperty<Number> var maxCellsInRow: Int get() = maxCellsInRowProperty.value.toInt(); set(value) { maxCellsInRowProperty.value = value } val maxRowsProperty: StyleableObjectProperty<Number> = FACTORY.createStyleableNumberProperty(this, "maxRows", "-fx-max-rows", { it.maxRowsProperty }, Int.MAX_VALUE) as StyleableObjectProperty<Number> var maxRows: Int get() = maxRowsProperty.value.toInt(); set(value) { maxRowsProperty.value = value } val cellHeightProperty: StyleableObjectProperty<Number> = FACTORY.createStyleableNumberProperty(this, "cellHeight", "-fx-cell-height", { it.cellHeightProperty }, 150.0) as StyleableObjectProperty<Number> var cellHeight: Double get() = cellHeightProperty.value as Double; set(value) { cellHeightProperty.value = value } val horizontalCellSpacingProperty: StyleableProperty<Number> = FACTORY.createStyleableNumberProperty(this, "horizontalCellSpacing", "-fx-horizontal-cell-spacing", { it.horizontalCellSpacingProperty }, 8.0) var horizontalCellSpacing: Double get() = horizontalCellSpacingProperty.value as Double; set(value) { horizontalCellSpacingProperty.value = value } val verticalCellSpacingProperty: StyleableProperty<Number> = FACTORY.createStyleableNumberProperty(this, "verticalCellSpacing", "-fx-vertical-cell-spacing", { it.verticalCellSpacingProperty }, 8.0) var verticalCellSpacing: Double get() = verticalCellSpacingProperty.value as Double; set(value) { verticalCellSpacingProperty.value = value } val selectionModel = DataGridSelectionModel(this) val focusModel = DataGridFocusModel(this) var singleSelect: Boolean get() = selectionModel.selectionMode == SINGLE; set(value) { selectionModel.selectionMode = if (value) SINGLE else MULTIPLE } var multiSelect: Boolean get() = selectionModel.selectionMode == MULTIPLE; set(value) { selectionModel.selectionMode = if (value) MULTIPLE else SINGLE } override fun createDefaultSkin() = DataGridSkin(this) override fun getUserAgentStylesheet(): String = DataGrid::class.java.getResource("datagrid.css").toExternalForm() override fun getControlCssMetaData(): MutableList<CssMetaData<out Styleable, *>>? = FACTORY.cssMetaData // Called when the items list changes structurally private val itemsChangeListener = InvalidationListener { selectionModel.clearSelectionAndReapply() (skin as? DataGridSkin<T>)?.handleControlPropertyChanged("ITEMS") } // Called when the items list is swapped for a new private val itemPropertyChangeListener = ChangeListener<ObservableList<T>> { _, oldList, newList -> selectionModel.clearSelectionAndReapply() if (oldList != null) { oldList.removeListener(itemsChangeListener) // Keep cache for elements in present in the new list oldList.filterNot { it in newList }.forEach { graphicCache.remove(it) } } else { graphicCache.clear() } newList.addListener(itemsChangeListener) (skin as? DataGridSkin<T>)?.handleControlPropertyChanged("ITEMS") } val selectedItem: T? get() = this.selectionModel.selectedItem fun onUserSelect(clickCount: Int = 2, action: (T) -> Unit) { val isSelected = { event: InputEvent -> !selectionModel.isEmpty } addEventFilter(MouseEvent.MOUSE_CLICKED) { event -> if (event.clickCount == clickCount && isSelected(event)) action(selectedItem!!) } addEventFilter(KeyEvent.KEY_PRESSED) { event -> if (event.code == KeyCode.ENTER && !event.isMetaDown && isSelected(event)) action(selectedItem!!) } } init { addClass(Stylesheet.datagrid) itemsProperty.addListener(itemPropertyChangeListener) items.addListener(itemsChangeListener) } } open class DataGridCell<T>(val dataGrid: DataGrid<T>) : IndexedCell<T>() { var cache: Node? = null var updating = false private var fresh = true private var cellFragment: DataGridCellFragment<T>? = null init { addClass(Stylesheet.datagridCell) // Update cell content when index changes indexProperty().onChange { if (it == -1) clearCellFragment() if (!updating) doUpdateItem() } } internal fun doUpdateItem() { val totalCount = dataGrid.items.size val item = if (index !in 0 until totalCount) null else dataGrid.items[index] val cacheProvider = dataGrid.cellCache if (item != null) { if (cacheProvider != null) cache = dataGrid.graphicCache.getOrPut(item, { cacheProvider(item) }) updateItem(item, false) } else { cache = null updateItem(null, true) } // Preemptive update of selected state val isActuallySelected = index in dataGrid.selectionModel.selectedIndices if (!isSelected && isActuallySelected) updateSelected(true) else if (isSelected && !isActuallySelected) updateSelected(false) } override fun updateItem(item: T?, empty: Boolean) { super.updateItem(item, empty) if (item == null || empty) { graphic = null text = null clearCellFragment() } else { val formatter = dataGrid.cellFormat if (fresh) { val cellFragmentType = dataGrid.properties["tornadofx.cellFragment"] as KClass<DataGridCellFragment<T>>? cellFragment = if (cellFragmentType != null) find(cellFragmentType, dataGrid.scope ?: FX.defaultScope) else null fresh = false } cellFragment?.apply { editingProperty.cleanBind(editingProperty()) itemProperty.value = item cellProperty.value = this@DataGridCell graphic = root } if (cache != null) { graphic = StackPane(cache) formatter?.invoke(this, item) } else { if (formatter != null) formatter.invoke(this, item) else if (graphic == null) graphic = StackPane(Label(item.toString())) } } } private fun clearCellFragment() { cellFragment?.apply { cellProperty.value = null itemProperty.value = null editingProperty.unbind() editingProperty.value = false } } override fun createDefaultSkin() = DataGridCellSkin(this) } abstract class DataGridCellFragment<T> : ItemFragment<T>() { val cellProperty: ObjectProperty<DataGridCell<T>?> = SimpleObjectProperty() var cell by cellProperty val editingProperty = SimpleBooleanProperty(false) val editing by editingProperty open fun startEdit() { cell?.startEdit() } open fun commitEdit(newValue: T) { cell?.commitEdit(newValue) } open fun cancelEdit() { cell?.cancelEdit() } open fun onEdit(op: () -> Unit) { editingProperty.onChange { if (it) op() } } } class DataGridCellBehavior<T>(control: DataGridCell<T>) : CellBehaviorBase<DataGridCell<T>>(control, emptyList()) { override fun getFocusModel() = control.dataGrid.focusModel override fun getCellContainer() = control override fun edit(cell: DataGridCell<T>?) { // No editing support for now } override fun getSelectionModel() = control.dataGrid.selectionModel override fun doSelect(x: Double, y: Double, button: MouseButton?, clickCount: Int, shiftDown: Boolean, shortcutDown: Boolean) { // I don't understand what the anchor is for yet, so to keep `focusedIndex = getAnchor(cellContainer, fm.getFocusedIndex())` // from returning something else than the currently focused index, I make sure "isDefaultAnchor" is set to true. // Must understand anchor and revisit this control.properties["isDefaultAnchor"] = true super.doSelect(x, y, button, clickCount, shiftDown, shortcutDown) } } class DataGridCellSkin<T>(control: DataGridCell<T>) : CellSkinBase<DataGridCell<T>, DataGridCellBehavior<T>>(control, DataGridCellBehavior(control)) class DataGridFocusModel<T>(val dataGrid: DataGrid<T>) : FocusModel<T>() { override fun getModelItem(index: Int) = if (index in 0 until itemCount) dataGrid.items[index] else null override fun getItemCount() = dataGrid.items.size } open class DataGridRow<T>(val dataGrid: DataGrid<T>, val dataGridSkin: DataGridSkin<T>) : IndexedCell<T>() { init { addClass(Stylesheet.datagridRow) // Report row as not empty when it's populated indexProperty().addListener(InvalidationListener { updateItem(null, index == -1) }) } override fun createDefaultSkin() = DataGridRowSkin(this) } class DataGridRowSkin<T>(control: DataGridRow<T>) : CellSkinBase<DataGridRow<T>, BehaviorBase<DataGridRow<T>>>(control, BehaviorBase(control, emptyList())) { private var lastUpdatedCells = -1..-1 init { // Remove default label from CellSkinBase children.clear() updateCells() registerChangeListener(skinnable.indexProperty(), "INDEX") registerChangeListener(skinnable.widthProperty(), "WIDTH") registerChangeListener(skinnable.heightProperty(), "HEIGHT") } override fun handleControlPropertyChanged(p: String) { super.handleControlPropertyChanged(p) when (p) { "INDEX" -> updateCells() "WIDTH" -> updateCells() "HEIGHT" -> updateCells() } } /** * This routine is copied from the GridView in ControlsFX. */ private fun updateCells() { val rowIndex = skinnable.index if (rowIndex > -1) { val dataGrid = skinnable.dataGrid val maxCellsInRow = (dataGrid.skin as DataGridSkin<*>).computeMaxCellsInRow() val totalCellsInGrid = dataGrid.items.size val startCellIndex = rowIndex * maxCellsInRow val endCellIndex = startCellIndex + maxCellsInRow - 1 var cacheIndex = 0 lastUpdatedCells = (startCellIndex..endCellIndex).also { if (it == lastUpdatedCells) return } var cellIndex = startCellIndex while (cellIndex <= endCellIndex) { if (cellIndex < totalCellsInGrid) { var cell = getCellAtIndex(cacheIndex) if (cell == null) { cell = createCell() children.add(cell) } cell.updating = true cell.updateIndex(-1) cell.updating = false cell.updateIndex(cellIndex) } else { break }// we are going out of bounds -> exist the loop cellIndex++ cacheIndex++ } // In case we are re-using a row that previously had more cells than // this one, we need to remove the extra cells that remain children.remove(cacheIndex, children.size) } } private fun createCell() = skinnable.dataGrid.cellFactory?.invoke(skinnable.dataGrid) ?: DataGridCell<T>(skinnable.dataGrid) @Suppress("UNCHECKED_CAST") fun getCellAtIndex(index: Int): DataGridCell<T>? { if (index < children.size) return children[index] as DataGridCell<T>? return null } override fun computeMaxHeight(width: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double): Double { val dataGrid = skinnable.dataGrid return dataGrid.cellHeight * (dataGrid.skin as DataGridSkin<*>).itemCount } override fun computePrefHeight(width: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double): Double { val dataGrid = skinnable.dataGrid return dataGrid.cellHeight + (dataGrid.verticalCellSpacing * 2) } override fun computePrefWidth(height: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double): Double { val dataGrid = skinnable.dataGrid return (dataGrid.cellWidth + dataGrid.horizontalCellSpacing * 2) * skinnable.dataGridSkin.computeMaxCellsInRow() } override fun layoutChildren(x: Double, y: Double, w: Double, h: Double) { val dataGrid = skinnable.dataGrid val cellWidth = dataGrid.cellWidth val cellHeight = dataGrid.cellHeight val horizontalCellSpacing = dataGrid.horizontalCellSpacing val verticalCellSpacing = dataGrid.verticalCellSpacing var xPos = 0.0 for (child in children) { child.resizeRelocate(xPos + horizontalCellSpacing, y + verticalCellSpacing, cellWidth, cellHeight) xPos += cellWidth + (horizontalCellSpacing * 2) } } } class DataGridSelectionModel<T>(val dataGrid: DataGrid<T>) : MultipleSelectionModel<T>() { private val selectedIndicies: ObservableList<Int> = FXCollections.observableArrayList() private val selectedItems: ObservableList<T> = FXCollections.observableArrayList() fun getCellAt(index: Int): DataGridCell<T>? { val skin = dataGrid.skin as DataGridSkin<T> val cellsPerRow = skin.computeMaxCellsInRow() val rowIndex = index / cellsPerRow val row = skin.getRow(rowIndex) ?: return null val indexInRow = index - (rowIndex * cellsPerRow) val children = row.childrenUnmodifiable return if (children.size > indexInRow) children[indexInRow] as DataGridCell<T>? else null } init { // Instead of attaching listeners to all cells, distribute selected status directly val selectedIndicesListener = ListChangeListener<Int> { c -> while (c.next()) { if (c.wasAdded()) c.addedSubList.forEach { index -> val cell = getCellAt(index) if (cell != null && !cell.isSelected) { cell.updating = true cell.updateSelected(true) cell.doUpdateItem() cell.updating = false } } if (c.wasRemoved()) c.removed.forEach { index -> val cell = getCellAt(index) if (cell != null && cell.isSelected) { cell.updating = true cell.updateSelected(false) cell.doUpdateItem() cell.updating = false } } } } selectedIndices.addListener(selectedIndicesListener) } override fun selectPrevious() { select(selectedIndex - 1) } override fun selectFirst() { select(0) } override fun selectLast() { select(dataGrid.items.lastIndex) } override fun getSelectedIndices() = selectedIndicies override fun clearAndSelect(index: Int) { selectedIndicies.clear() selectedItems.clear() select(index) } override fun getSelectedItems() = selectedItems override fun selectNext() { select(selectedIndex + 1) } override fun selectAll() { selectedIndicies.clear() selectedItems.clear() dataGrid.items.forEachIndexed { index, item -> selectedIndicies.add(index) selectedItems.add(item) } select(dataGrid.items.lastIndex) } override fun clearSelection(index: Int) { if (index in selectedIndicies) { selectedIndicies.remove(index) selectedItems.remove(dataGrid.items[index]) } if (selectedIndex == index) { selectedIndex = -1 selectedItem = null } } override fun clearSelection() { selectedIndicies.clear() selectedItems.clear() selectedItem = null selectedIndex = -1 } override fun isEmpty() = selectedIndicies.isEmpty() override fun selectIndices(index: Int, vararg indices: Int) { select(index) indices.forEach { select(it) } } override fun isSelected(index: Int) = index in selectedIndicies override fun select(obj: T) { val index = dataGrid.items.indexOf(obj) select(index) } override fun select(index: Int) { if (index !in dataGrid.items.indices) return selectedIndex = index selectedItem = dataGrid.items[index] if (selectionMode == SINGLE) { selectedIndicies.removeAll { it != index } selectedItems.removeAll { it != selectedItem } } if (index !in selectedIndicies) { selectedIndicies.add(index) selectedItems.add(selectedItem) dataGrid.focusModel.focus(index) } } /** * Clear selection and reapply for the items that are still in the list */ fun clearSelectionAndReapply() { val currentItems = selectedItems.toList() val currentIndexes = selectedIndicies.toList() val selectedItemsToIndex = (currentItems zip currentIndexes).toMap() clearSelection() for (item in currentItems) { val index = dataGrid.items.indexOf(item) if (index > -1) { select(index) } else { // If item is gone, select the item at the same index position select(selectedItemsToIndex[item]!!) } } } } @Suppress("UNCHECKED_CAST") class DataGridSkin<T>(control: DataGrid<T>) : VirtualContainerBase<DataGrid<T>, BehaviorBase<DataGrid<T>>, DataGridRow<T>>(control, BehaviorBase(control, emptyList())) { private val gridViewItemsListener = ListChangeListener<T> { updateRowCount() skinnable.requestLayout() } private val weakGridViewItemsListener = WeakListChangeListener(gridViewItemsListener) init { updateItems() flow.id = "virtual-flow" flow.isPannable = false flow.isFocusTraversable = false flow.setCreateCell { createCell() } children.add(flow) updateRowCount() registerChangeListener(control.itemsProperty, "ITEMS") registerChangeListener(control.cellFactoryProperty, "CELL_FACTORY") registerChangeListener(control.parentProperty(), "PARENT") registerChangeListener(control.cellHeightProperty as ObservableValue<Number>, "CELL_HEIGHT") registerChangeListener(control.cellWidthProperty as ObservableValue<Number>, "CELL_WIDTH") registerChangeListener(control.horizontalCellSpacingProperty as ObservableValue<Number>, "HORIZONZAL_CELL_SPACING") registerChangeListener(control.verticalCellSpacingProperty as ObservableValue<Number>, "VERTICAL_CELL_SPACING") registerChangeListener(control.widthProperty(), "WIDTH_PROPERTY") registerChangeListener(control.heightProperty(), "HEIGHT_PROPERTY") focusOnClick() } private fun focusOnClick() { skinnable.addEventFilter(MouseEvent.MOUSE_PRESSED) { if (!skinnable.isFocused && skinnable.isFocusTraversable) skinnable.requestFocus() } } override public fun handleControlPropertyChanged(p: String?) { super.handleControlPropertyChanged(p) when (p) { "ITEMS" -> updateItems() "CELL_FACTORY" -> flow.recreateCells() "CELL_HEIGHT" -> flow.recreateCells() "CELL_WIDTH" -> { updateRowCount() flow.recreateCells() } "HORIZONZAL_CELL_SPACING" -> { updateRowCount() flow.recreateCells() } "VERTICAL_CELL_SPACING" -> flow.recreateCells() "PARENT" -> { if (skinnable.parent != null && skinnable.isVisible) skinnable.requestLayout() } "WIDTH_PROPERTY" -> updateRowCount() "HEIGHT_PROPERTY" -> updateRowCount() } } override fun getItemCount() = Math.ceil(skinnable.items.size.toDouble() / computeMaxCellsInRow()).toInt() /** * Compute the maximum number of cells per row. If the calculated number of cells would result in * more than the configured maxRow rows, the maxRow setting takes presedence and overrides the maxCellsInRow */ fun computeMaxCellsInRow(): Int { val maxCellsInRow = Math.min(Math.max(Math.floor(computeRowWidth() / computeCellWidth()).toInt(), 1), skinnable.maxCellsInRow) val neededRows = Math.ceil(skinnable.items.size.toDouble() / maxCellsInRow) return if (neededRows > skinnable.maxRows) (skinnable.items.size.toDouble() / skinnable.maxRows).toInt() else maxCellsInRow } fun computeRowWidth() = skinnable.width - 14 // Account for scrollbar private fun computeCellWidth() = skinnable.cellWidth + skinnable.horizontalCellSpacing * 2 override fun computePrefHeight(width: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double) = 500.0 override fun computePrefWidth(height: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double) = 500.0 override fun updateRowCount() { if (flow == null) return val oldCount = flow.cellCount val newCount = itemCount if (newCount != oldCount) { flow.cellCount = newCount flow.rebuildCells() } else { flow.reconfigureCells() } updateRows(newCount) } override fun createCell() = DataGridRow(skinnable, this) private fun updateItems() { skinnable.items.removeListener(weakGridViewItemsListener) skinnable.items.addListener(weakGridViewItemsListener) updateRowCount() flow.recreateCells() skinnable.requestLayout() } private fun updateRows(rowCount: Int) { for (i in 0..rowCount - 1) getRow(i)?.updateIndex(i) } fun getRow(index: Int) = flow.getVisibleCell(index) override fun layoutChildren(x: Double, y: Double, w: Double, h: Double) { val x1 = skinnable.insets.left val y1 = skinnable.insets.top val w1 = skinnable.width - (skinnable.insets.left + skinnable.insets.right) val h1 = skinnable.height - (skinnable.insets.top + skinnable.insets.bottom) flow.resizeRelocate(x1, y1, w1, h1) } } fun <T> DataGrid<T>.bindSelected(property: Property<T>) { selectionModel.selectedItemProperty().onChange { property.value = it } } fun <T> DataGrid<T>.bindSelected(model: ItemViewModel<T>) = this.bindSelected(model.itemProperty) fun <T> DataGrid<T>.asyncItems(func: () -> Collection<T>) = task { func() } success { items.setAll(it) }
apache-2.0
23ffe71dcdc39427a542f9006ed79487
37.078227
229
0.652537
4.589252
false
false
false
false
donald-w/Anki-Android
AnkiDroid/src/test/java/com/ichi2/ui/KeyPickerTest.kt
1
2750
/* * Copyright (c) 2021 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.ui import androidx.test.ext.junit.runners.AndroidJUnit4 import com.ichi2.anki.RobolectricTest import com.ichi2.anki.dialogs.KeySelectionDialogBuilder import com.ichi2.testutils.KeyEventUtils import org.hamcrest.CoreMatchers.* import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class KeyPickerTest : RobolectricTest() { private var mKeyPicker: KeyPicker = KeyPicker.inflate(targetContext) @Test fun test_normal_binding() { assertThat(mKeyPicker.getBinding(), nullValue()) mKeyPicker.dispatchKeyEvent(getVKey()) assertThat(mKeyPicker.getBinding(), not(nullValue())) } @Test fun invalid_binding_keeps_null_value() { assertThat(mKeyPicker.getBinding(), nullValue()) mKeyPicker.dispatchKeyEvent(getInvalidEvent()) assertThat(mKeyPicker.getBinding(), nullValue()) } @Test fun invalid_binding_keeps_same_value() { mKeyPicker.dispatchKeyEvent(getVKey()) val binding = mKeyPicker.getBinding() assertThat(binding, not(nullValue())) mKeyPicker.dispatchKeyEvent(getInvalidEvent()) assertThat(mKeyPicker.getBinding(), sameInstance(binding)) } @Test fun user_specified_validation() { // We don't want shift/alt as a single keypress - this stops them being used as modifier keys val leftShiftPress = KeyEventUtils.leftShift() mKeyPicker.setKeycodeValidation(KeySelectionDialogBuilder.disallowModifierKeyCodes()) mKeyPicker.dispatchKeyEvent(leftShiftPress) assertThat(mKeyPicker.getBinding(), nullValue()) // now turn it off and ensure it wasn't a fluke mKeyPicker.setKeycodeValidation { true } mKeyPicker.dispatchKeyEvent(leftShiftPress) assertThat(mKeyPicker.getBinding(), notNullValue()) } private fun getVKey() = KeyEventUtils.getVKey() private fun getInvalidEvent() = KeyEventUtils.getInvalid() }
gpl-3.0
b47425a5242c022ff5fe9fd2bb1b3051
33.375
101
0.724364
4.317111
false
true
false
false
grozail/kovision
src/main/kotlin/vision/imgproc/Smoothing.kt
1
910
package vision.imgproc import org.opencv.core.Mat import org.opencv.core.Size import org.opencv.imgproc.Imgproc fun Mat.blur(level: Int, destination: Mat = Mat()): Mat { val oddLevel = (level * 2 + 1).toDouble() Imgproc.blur(this, destination, Size(oddLevel, oddLevel)) return destination } fun Mat.GaussianBlur(level: Int, sigmaX: Double = 0.0, destination: Mat = Mat()): Mat { val oddLevel = (level * 2 + 1).toDouble() Imgproc.GaussianBlur(this, destination, Size(oddLevel, oddLevel), sigmaX) return destination } fun Mat.medianBlur(level: Int, destination: Mat = Mat()): Mat { val oddLevel = level * 2 + 1 Imgproc.medianBlur(this, destination, oddLevel) return destination } fun Mat.bilateralFilter(level: Int, destination: Mat = Mat()): Mat { val oddLevel = level * 2 + 1 Imgproc.bilateralFilter(this, destination, oddLevel, oddLevel * 2.0, oddLevel / 2.0) return destination }
mit
a16b1ffe635cf630b6a9a6216fdf1307
30.413793
87
0.716484
3.261649
false
false
false
false
cashapp/sqldelight
extensions/android-paging3/src/test/java/app/cash/sqldelight/paging3/KeyedQueryPagingSourceTest.kt
1
6664
package app.cash.sqldelight.paging3 import androidx.paging.PagingConfig import androidx.paging.PagingSource.LoadParams.Refresh import androidx.paging.PagingSource.LoadResult import androidx.paging.PagingState import app.cash.sqldelight.Query import app.cash.sqldelight.Transacter import app.cash.sqldelight.TransacterImpl import app.cash.sqldelight.db.SqlCursor import app.cash.sqldelight.db.SqlDriver import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import kotlin.coroutines.EmptyCoroutineContext import kotlin.test.assertEquals import kotlin.test.assertNull @ExperimentalCoroutinesApi class KeyedQueryPagingSourceTest { private lateinit var driver: SqlDriver private lateinit var transacter: Transacter @Before fun before() { driver = JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY) driver.execute(null, "CREATE TABLE testTable(value INTEGER PRIMARY KEY)", 0) (0L until 10L).forEach { this.insert(it) } transacter = object : TransacterImpl(driver) {} } @Test fun `aligned page exhaustion gives correct results`() { val source = KeyedQueryPagingSource( queryProvider = this::query, pageBoundariesProvider = this::pageBoundaries, transacter = transacter, context = EmptyCoroutineContext, ) runBlocking { val expected = (0L until 10L).chunked(2).iterator() var nextKey: Long? = null do { val results = source.load(Refresh(nextKey, 2, false)) nextKey = (results as LoadResult.Page).nextKey assertEquals(expected = expected.next(), actual = results.data) } while (nextKey != null) } } @Test fun `misaligned page exhastion gives correct results`() { val source = KeyedQueryPagingSource( queryProvider = this::query, pageBoundariesProvider = this::pageBoundaries, transacter = transacter, context = EmptyCoroutineContext, ) runBlocking { val expected = (0L until 10L).chunked(3).iterator() var nextKey: Long? = null do { val results = source.load(Refresh(nextKey, 3, false)) nextKey = (results as LoadResult.Page).nextKey assertEquals(expected = expected.next(), actual = results.data) } while (nextKey != null) } } @Test fun `requesting a page with anchor not in step passes`() { val source = KeyedQueryPagingSource( queryProvider = this::query, pageBoundariesProvider = this::pageBoundaries, transacter = transacter, context = EmptyCoroutineContext, ) val results = runBlocking { source.load(Refresh(key = 5L, loadSize = 2, false)) } assertEquals(listOf(5L), (results as LoadResult.Page).data) } @Test fun `misaligned last page has correct data`() { val source = KeyedQueryPagingSource( queryProvider = this::query, pageBoundariesProvider = this::pageBoundaries, transacter = transacter, context = EmptyCoroutineContext, ) val results = runBlocking { source.load(Refresh(key = 9L, loadSize = 3, false)) } assertEquals(expected = listOf(9L), (results as LoadResult.Page).data) assertEquals(expected = 6L, results.prevKey) assertEquals(expected = null, results.nextKey) } @Test fun `invoking getRefreshKey before first load returns null key`() { val source = KeyedQueryPagingSource( queryProvider = this::query, pageBoundariesProvider = this::pageBoundaries, transacter = transacter, context = EmptyCoroutineContext, ) assertNull( source.getRefreshKey( PagingState( emptyList(), null, PagingConfig(3), 0, ), ), ) } @Test fun `invoking getRefreshKey with loaded first page returns correct result`() { val source = KeyedQueryPagingSource( queryProvider = this::query, pageBoundariesProvider = this::pageBoundaries, transacter = transacter, context = EmptyCoroutineContext, ) val results = runBlocking { source.load(Refresh(key = null, loadSize = 3, false)) } val refreshKey = source.getRefreshKey( PagingState( listOf(results as LoadResult.Page), null, PagingConfig(3), 0, ), ) assertEquals(0L, refreshKey) } @Test fun `invoking getRefreshKey with single loaded middle page returns correct result`() { val source = KeyedQueryPagingSource( queryProvider = this::query, pageBoundariesProvider = this::pageBoundaries, transacter = transacter, context = EmptyCoroutineContext, ) val results = runBlocking { source.load(Refresh(key = 6L, loadSize = 3, false)) } val refreshKey = source.getRefreshKey( PagingState( listOf(results as LoadResult.Page), null, PagingConfig(3), 0, ), ) assertEquals(6L, refreshKey) } private fun pageBoundaries(anchor: Long?, limit: Long): Query<Long> { val sql = """ |SELECT value |FROM ( | SELECT | value, | CASE | WHEN (row_number() OVER(ORDER BY value ASC) - 1) % ? = 0 THEN 1 | WHEN value = ? THEN 1 | ELSE 0 | END page_boundary | FROM testTable | ORDER BY value ASC |) |WHERE page_boundary = 1; """.trimMargin() return object : Query<Long>({ cursor -> cursor.getLong(0)!! }) { override fun <R> execute(mapper: (SqlCursor) -> R) = driver.executeQuery(identifier = 3, sql = sql, mapper = mapper, parameters = 2) { bindLong(0, limit) bindLong(1, anchor) } override fun addListener(listener: Listener) = Unit override fun removeListener(listener: Listener) = Unit } } private fun query(beginInclusive: Long, endExclusive: Long?): Query<Long> { val sql = """ |SELECT value FROM testTable |WHERE value >= :1 AND (value < :2 OR :2 IS NULL) |ORDER BY value ASC; """.trimMargin() return object : Query<Long>( { cursor -> cursor.getLong(0)!! }, ) { override fun <R> execute(mapper: (SqlCursor) -> R) = driver.executeQuery(identifier = 2, sql = sql, mapper = mapper, parameters = 2) { bindLong(0, beginInclusive) bindLong(1, endExclusive) } override fun addListener(listener: Listener) = Unit override fun removeListener(listener: Listener) = Unit } } private fun insert(value: Long, db: SqlDriver = driver) { db.execute(0, "INSERT INTO testTable (value) VALUES (?)", 1) { bindLong(0, value) } } }
apache-2.0
e662c3123ebf9efd8c789e8147e5f455
29.995349
140
0.659514
4.389987
false
true
false
false
openstreetview/android
app/src/main/java/com/telenav/osv/data/collector/obddata/manager/OBDSensorManager.kt
1
13542
package com.telenav.osv.data.collector.obddata.manager import com.telenav.osv.data.collector.datatype.EventDataListener import com.telenav.osv.data.collector.datatype.ObdConnectionListener import com.telenav.osv.data.collector.datatype.datatypes.BaseObject import com.telenav.osv.data.collector.datatype.datatypes.VinObject import com.telenav.osv.data.collector.datatype.util.LibraryUtil import com.telenav.osv.data.collector.datatype.util.LibraryUtil.ObdSensors import com.telenav.osv.data.collector.datatype.util.LibraryUtil.ObdSensorsFrequency import com.telenav.osv.data.collector.datatype.util.LibraryUtil.ObdSourceListener import com.telenav.osv.data.collector.obddata.AbstractClientDataTransmission import timber.log.Timber import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.locks.Lock import java.util.concurrent.locks.ReentrantLock /** * */ class OBDSensorManager private constructor() { private var abstractClientDataTransmission: AbstractClientDataTransmission? = null /** * vehicle id will always be collected at the beginning of collection, * and stored inside this variable */ private var vehicleId: String? = null private val obdListenerMap: MutableMap<EventDataListener, MutableList<String>> = ConcurrentHashMap() private val obdConnectionListeners: MutableList<ObdConnectionListener> = CopyOnWriteArrayList() /** * makes sure that if the client subscribes to/un-subscribes from multiple * sensors at a time, the threads which register these sensors will run sequentially */ private val multipleSubscribingLock: Lock /** * Used to determine the frequency for each sensor */ private val sensorFrequencies: MutableMap<String, Int> = HashMap() val obdDataListener: ObdDataListener = object : ObdDataListener { override fun onSensorChanged(baseObject: BaseObject<*>) { notifyListeners(baseObject) } override fun onConnectionStateChanged(dataSource: String, statusCode: Int) { notifyConnectionStateChanged(dataSource, statusCode) } /** * when the connection is stopped, clear the connection and data listener from the sensor manager * @param source */ override fun onConnectionStopped(source: String) { clearListeners() } override fun onInitializationFailedWarning() { notifyListenersInitializationFailed() } override fun requestSensorFrequencies(): MutableMap<String, Int> { return sensorFrequencies } override fun clearListeners() { obdConnectionListeners.clear() obdListenerMap.clear() } /** * when the initialization procedure does not detect the OBD version, a * warning should be sent to the listeners */ private fun notifyListenersInitializationFailed() { for ((key) in obdListenerMap) { val baseObject: BaseObject<*> = BaseObject<Any?>(null, LibraryUtil.OBD_INITIALIZATION_FAILURE) key.onNewEvent(baseObject) } } private fun notifyConnectionStateChanged(@ObdSourceListener source: String, statusCode: Int) { for (obdListener in obdConnectionListeners) { obdListener.onConnectionStateChanged(null, source, statusCode) } } /** * when a sensor value was collected, notify all the listeners of that sensor * * @param sensor - the object containing sensor information */ private fun notifyListeners(sensor: BaseObject<*>) { if (obdListenerMap.isNotEmpty()) { for ((key) in obdListenerMap) { //the vehicle id will be sent to all sensor listeners if (sensor is VinObject) { key.onNewEvent(sensor) vehicleId = sensor.vin } key.onNewEvent(sensor) } } else { //if there is no listener yet, and vehicle id was collected, store it into a variable if (sensor is VinObject) { vehicleId = sensor.vin } } } } fun addConnectionListener(obdConnectionListener: ObdConnectionListener) { val clazz: Class<*> = obdConnectionListener.javaClass val iterator: Iterator<ObdConnectionListener> = obdConnectionListeners.iterator() while (iterator.hasNext()) { val connectionListener = iterator.next() if (connectionListener.javaClass == clazz) { obdConnectionListeners.remove(connectionListener) } } obdConnectionListeners.add(obdConnectionListener) } fun getObdConnectionListeners(): MutableList<ObdConnectionListener> { return obdConnectionListeners } /** * sets the frequency for a sensor * @param type - the type of sensor * @param frequency - the desired frequency */ fun setSensorFrequency(@ObdSensors type: String?, @ObdSensorsFrequency frequency: Int) { if (type != null && isSensorListened(type)) { sensorFrequencies[type] = frequency //if the frequency is changed during collection, notify the collecting thread abstractClientDataTransmission?.onCollectionThreadRestartRequired() } } /** * subscribes a listener to receive the values collected by a sensor * NOTE: this method must be called BEFORE the collection has started * @param listener - the class which listens for sensor events * @param sensor - the collected sensor */ fun registerSensor(listener: EventDataListener, @ObdSensors sensor: String) { if (!obdListenerMap.containsKey(listener)) { obdListenerMap[listener] = ArrayList(listOf(sensor)) } else { val sensors = obdListenerMap[listener] //check if the sensor has already been added to the listener if (!sensors!!.contains(sensor)) { sensors.add(sensor) } obdListenerMap[listener] = sensors } } /** * subscribes another sensor to the list of sensor to be collected for a listener * NOTE: this method must be called AFTER the collection has started * @param listener - the class which listens for sensor events * @param sensor - the collected sensor */ fun subscribeSensor(listener: EventDataListener, @ObdSensors sensor: String) { val subscriberRunnable: Runnable = SubscriberRunnable(listener, sensor, ACTION_SUBSCRIBE) Thread(subscriberRunnable).start() } /** * unsubscribes a listener from receiving sensor events * @param listener - the class which listens for sensor events */ @Synchronized fun unregisterListener(listener: EventDataListener?) { obdListenerMap.remove(listener) } fun unsubscribeSensor(listener: EventDataListener, @ObdSensors sensor: String) { val unsubscriberRunnable: Runnable = SubscriberRunnable(listener, sensor, ACTION_UNSUBSCRIBE) Thread(unsubscriberRunnable).start() } /** * retrieves all sensor event listeners * @return - a list of listeners */ val obdListeners: MutableList<EventDataListener> get() { val result: MutableList<EventDataListener> = ArrayList() for ((key) in obdListenerMap) { result.add(key) } return result } /** * retrieves whether or not a listener is listening for a specific sensor * @param listener - the sensor listener * @param sensorType - the listened sensor * @return - true if listener is registered for sensor, false otherwise */ fun isListenerRegisteredForSensor(listener: EventDataListener?, sensorType: String?): Boolean { return if (obdListenerMap.containsKey(listener)) { obdListenerMap[listener]!!.contains(sensorType) } else { false } } /** * checks whether or not a specific sensor is listened by any listener * @param sensorType - the type of sensor * @return true if the sensor is listened by a listener, false otherwise */ fun isSensorListened(sensorType: String?): Boolean { for ((_, value) in obdListenerMap) { if (value!!.contains(sensorType)) { return true } } return false } /** * retrieves a list of the sensor which need to be collected for different listeners * @return - the list of desired sensors */ val listOfDesiredSensors: MutableList<String> get() { val result: MutableList<String> = ArrayList() for ((_, value) in obdListenerMap) { for (sensor in value!!) { if (!result.contains(sensor)) { result.add(sensor) } } } return result } fun getAbstractClientDataTransmission(): AbstractClientDataTransmission? { return abstractClientDataTransmission } fun setAbstractClientDataTransmission(abstractClientDataTransmission: AbstractClientDataTransmission) { this.abstractClientDataTransmission = abstractClientDataTransmission //when the transmission object has been added, automatically add it as a listener for connection events //this way, when the client stops the connection, the object knows it has to stop its running service addConnectionListener(abstractClientDataTransmission) } /** * inner class that handles the thread which notifies the obd that a new sensor will be collected/a sensor will no longer be collected */ private inner class SubscriberRunnable internal constructor(var listener: EventDataListener, var sensor: String, var action: String) : Runnable { override fun run() { //acquire lock to prevent other threads from subscribing sensors at the same time multipleSubscribingLock.lock() pauseCollection() when (action) { ACTION_SUBSCRIBE -> onSubscribeAction() ACTION_UNSUBSCRIBE -> onUnsubscribeAction() else -> Timber.tag(TAG).e("Subscribe/unsubscribe invalid action") } multipleSubscribingLock.unlock() //release the lock associated with this thread resumeCollection() Thread.currentThread().interrupt() } @Synchronized fun pauseCollection() { AbstractClientDataTransmission.Companion.shouldCollect = false } @Synchronized fun resumeCollection() { AbstractClientDataTransmission.Companion.shouldCollect = true } fun onSubscribeAction() { if (sensor == LibraryUtil.VEHICLE_ID) { notifyVehicleIdRequested(listener) } else { registerSensor(listener, sensor) //when a new sensor has been subscribed, the collecting thread should restart, so //that the frequency vector will be updated if (abstractClientDataTransmission != null) { } abstractClientDataTransmission?.onCollectionThreadRestartRequired() } } fun onUnsubscribeAction() { unregisterSensor(listener, sensor) } /** * called when vehicle id was requested after collection started */ private fun notifyVehicleIdRequested(listener: EventDataListener) { if (!obdListenerMap.containsKey(listener)) { obdListenerMap[listener] = ArrayList() } val vinObject = VinObject(vehicleId, LibraryUtil.OBD_READ_SUCCESS) obdDataListener.onSensorChanged(vinObject) } /** * un-subscribes a listener to receive the values collected by a sensor * NOTE: this method must be called BEFORE the collection has started * @param listener - the class which listens for sensor events * @param sensor - the collected sensor */ private fun unregisterSensor(listener: EventDataListener, @ObdSensors sensor: String) { if (!obdListenerMap.containsKey(listener)) { return } val sensors = obdListenerMap[listener] //check if the list contains the sensor to be unregistered if (sensors!!.contains(sensor)) { sensors.remove(sensor) } obdListenerMap[listener] = sensors //un-subscribe the sensor from Logshed uploading too for ((key, registeredSensors) in obdListenerMap) { registeredSensors!!.remove(sensor) obdListenerMap[key] = registeredSensors } } } companion object { private val TAG = OBDSensorManager::class.java.simpleName private const val ACTION_SUBSCRIBE = "subscribe" private const val ACTION_UNSUBSCRIBE = "unsubscribe" val instance = OBDSensorManager() } init { multipleSubscribingLock = ReentrantLock() } }
lgpl-3.0
85d2683d4fec24d412409152e9bf2784
37.257062
149
0.639123
5.304348
false
false
false
false
werelord/nullpod
nullpodApp/src/main/kotlin/com/cyrix/nullpod/nullPodApp.kt
1
1666
/** * * Copyright 2017 Joel Braun * * This file is part of nullPod. * * nullPod 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. * * nullPod 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 nullPod. If not, see <http://www.gnu.org/licenses/>. */ package com.cyrix.nullpod import android.app.Application import android.content.Intent import android.os.Build import com.cyrix.util.CxLogger import com.cyrix.util.debug import com.cyrix.util.function class nullPodApp : Application() { val log = CxLogger<nullPodApp>() override fun onCreate() { log.function() if (BuildConfig.internalTest) { //Stetho.initializeWithDefaults(this) } // todo: context.startForegroundService?? val npServiceIntent = Intent(applicationContext, NullpodService::class.java) // start the service: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val res = applicationContext.startForegroundService(npServiceIntent) log.debug { "started service: $res" } } else { val res = startService(npServiceIntent) log.debug { "started service: $res" } } super.onCreate() } }
gpl-3.0
04c22687d62daae6d5df80d1d2ab0be6
28.245614
84
0.683073
4.165
false
false
false
false
varpeti/Suli
Android/work/varpe8/homeworks/08/HF08/app/src/main/java/ml/varpeti/hf08/Main.kt
1
7249
package ml.varpeti.hf08 import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.SurfaceTexture import android.hardware.camera2.CameraManager import android.os.Bundle import android.os.Environment import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.util.Log import android.view.TextureView import android.view.View import android.widget.Toast import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.ml.vision.FirebaseVision import com.google.firebase.ml.vision.common.FirebaseVisionImage import com.google.gson.Gson import kotlinx.android.synthetic.main.main.* import java.io.File import java.io.FileWriter import java.io.IOException import java.util.* class Main : AppCompatActivity() { var myCamera : MyCamera? = null private lateinit var database: FirebaseDatabase private lateinit var reference: DatabaseReference val ex = Environment.getExternalStorageDirectory() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main) database = FirebaseDatabase.getInstance() reference = database.getReference("BIs") checkPermission() val bm = BitmapFactory.decodeResource(resources, R.raw.qr01) mineInfoFromBitmap(bm) } private fun checkPermission() { //Jogok meglétének ellenőrzése, ha nincs kérünk (szép sorba) when { ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED -> ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA),0) ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED -> ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),0) ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED -> ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),0) else -> Thread(Runnable(function = { startPreview() }), "startPreviewAsync").start() } } private fun startPreview() { //findViewById<>() a gyengéknek való :D preview.surfaceTextureListener = object : TextureView.SurfaceTextureListener { override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture?, width: Int, height: Int) {} override fun onSurfaceTextureUpdated(surface: SurfaceTexture?) {} override fun onSurfaceTextureDestroyed(surface: SurfaceTexture?): Boolean { return true } @SuppressLint("MissingPermission") override fun onSurfaceTextureAvailable(surface: SurfaceTexture?, width: Int, height: Int) { // Ha elérhető kisterameljük a preview viewra val cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager val cameraId = cameraManager.cameraIdList.first() myCamera = MyCamera(preview, width, height) cameraManager.openCamera(cameraId, myCamera, null) } } } override fun onPause() { super.onPause() // Bezárjuk a kamerát ha nem kell if (myCamera != null) { myCamera!!.close() } finish() } // Tapintásra (megpróbálja) kibányásszni a bar/qr kódot fun cheees(v : View) { val myBitmap = preview.bitmap /*val location = File(ex.absolutePath + "/HF08") //Külön mappa location.mkdir() val dest = File(location, System.currentTimeMillis().toString() + ".png") //png lesz try { val fos = FileOutputStream(dest) myBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos) fos.flush() fos.close() } catch (e: IOException) { Log.e("error", e.message) e.printStackTrace() }*/ //Előző kép beállítása prev.setImageBitmap(myBitmap) mineInfoFromBitmap(myBitmap) } private fun mineInfoFromBitmap(bitmap:Bitmap) { val image = FirebaseVisionImage.fromBitmap(bitmap) val detector = FirebaseVision.getInstance().visionBarcodeDetector detector.detectInImage(image).addOnSuccessListener{ barcodes -> for (barcode in barcodes) { val date = Date() //Date val rawValue = barcode.rawValue //Information val format = barcode.format // Type of the code val type = barcode.valueType // Type of the value val msg = "$rawValue $format $type $date" Log.i("|||", msg) Toast.makeText(this, msg, Toast.LENGTH_LONG).show() //Store history val barcodeinfo = BarcodeInfo(rawValue, format, type, date) val barcodeInfos = HashMap<String, Any>() barcodeInfos[UUID.randomUUID().toString()] = barcodeinfo reference.updateChildren(barcodeInfos) // Save as Json using Gson val gson = Gson() val json = gson.toJson(barcodeinfo) Log.i("|||", json) val writer: FileWriter // Write a file. try { val location = File(ex.absolutePath + "/HF08") //Külön mappa location.mkdir() writer = FileWriter(ex.absolutePath + "/HF08/${System.currentTimeMillis()}.json") writer.write(json) writer.close() } catch (e:IOException) { e.printStackTrace() } } }.addOnFailureListener { e -> e.printStackTrace() //TODO better ex handling Log.i("|||","fail") } Log.i("|||","mine") } // Ha kértünk jogot: override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { when (requestCode) { 0 -> { //Ha üres a grantResults akkor nem kaptuk meg if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // YEAH van jogunk, recreate() hogy menjen tovább recreate() } else { // Nem kell jog, minek az? Az app se kell: finish() } return } // Egyéb requestek else -> { // Ignoráljuk őket } } } }
unlicense
81472ec81470f5af461f4fccff8634c9
31.633484
230
0.608292
4.735391
false
false
false
false
Widgetlabs/fleet
fleet/unit-resources/src/main/kotlin/eu/widgetlabs/fleet/units/UnitExtension.kt
1
7549
package eu.widgetlabs.fleet.units import android.content.res.Resources fun CompassDirection.getAbbreviation(resources: Resources): String { return resources.getStringArray(R.array.fleet_distance_directions)[ordinal] } fun Unit.getAbbreviation(resources: Resources): String = resources.getString(when (this) { is LengthUnit -> when (this) { LengthUnit.METERS -> R.string.fleet_distance_unit_meters_abbreviation LengthUnit.KILOMETERS -> R.string.fleet_distance_unit_kilometers_abbreviation LengthUnit.FEET -> R.string.fleet_distance_unit_feets_abbreviation LengthUnit.MILES -> R.string.fleet_distance_unit_miles_abbreviation LengthUnit.CENTIMETER -> R.string.fleet_distance_unit_centimeter_abbreviation else -> R.string.fleet_distance_unit_inch_abbreviation } is PressureUnit -> when (this) { PressureUnit.INCH_PER_MERCURY -> R.string.fleet_pressure_unit_inch_mercury_abbreviation else -> R.string.fleet_pressure_unit_millibars_abbreviation } is SpeedUnit -> when (this) { SpeedUnit.KILOMETERS_PER_HOUR -> R.string.fleet_speed_unit_kilometers_abbreviation SpeedUnit.MILES_PER_HOUR -> R.string.fleet_speed_unit_miles_abbreviation else -> R.string.fleet_speed_unit_knots_abbreviation } is TemperatureUnit -> when (this) { TemperatureUnit.CELSIUS -> R.string.fleet_temperature_unit_celsius_abbreviation else -> R.string.fleet_temperature_unit_fahrenheit_abbreviation } is TimeUnit -> when (this) { TimeUnit.MILLISECONDS -> R.string.fleet_time_unit_milliseconds_abbreviation TimeUnit.MINUTES -> R.string.fleet_time_unit_minutes_abbreviation else -> R.string.fleet_time_unit_seconds_abbreviation } is WeightUnit -> when (this) { WeightUnit.GRAMS -> R.string.fleet_weight_unit_grams_abbreviation else -> R.string.fleet_weight_unit_kilograms_abbreviation } else -> throw IllegalArgumentException("unkown unit class ${javaClass.name}") }) fun Unit.getPluralName(resources: Resources): String = resources.getString(when (this) { is LengthUnit -> when (this) { LengthUnit.METERS -> R.string.fleet_distance_unit_meters_plural LengthUnit.KILOMETERS -> R.string.fleet_distance_unit_kilometers_plural LengthUnit.FEET -> R.string.fleet_distance_unit_feets_plural LengthUnit.MILES -> R.string.fleet_distance_unit_miles_plural LengthUnit.CENTIMETER -> R.string.fleet_distance_unit_centimeter_plural else -> R.string.fleet_distance_unit_inch_plural } is PressureUnit -> when (this) { PressureUnit.INCH_PER_MERCURY -> R.string.fleet_pressure_unit_inch_mercury_plural else -> R.string.fleet_pressure_unit_millibars_plural } is SpeedUnit -> when (this) { SpeedUnit.KILOMETERS_PER_HOUR -> R.string.fleet_speed_unit_kilometers_plural SpeedUnit.MILES_PER_HOUR -> R.string.fleet_speed_unit_miles_plural else -> R.string.fleet_speed_unit_knots_plural } is TemperatureUnit -> when (this) { TemperatureUnit.CELSIUS -> R.string.fleet_temperature_unit_celsius_plural else -> R.string.fleet_temperature_unit_fahrenheit_plural } is TimeUnit -> when (this) { TimeUnit.MILLISECONDS -> R.string.fleet_time_unit_milliseconds_plural TimeUnit.MINUTES -> R.string.fleet_time_unit_minutes_plural else -> R.string.fleet_time_unit_seconds_plural } is WeightUnit -> when (this) { WeightUnit.GRAMS -> R.string.fleet_weight_unit_grams_plural else -> R.string.fleet_weight_unit_kilograms_abbreviation } else -> throw IllegalArgumentException("unkown unit class ${javaClass.name}") }) fun Unit.getSingularName(resources: Resources): String = resources.getString(when (this) { is LengthUnit -> when (this) { LengthUnit.METERS -> R.string.fleet_distance_unit_meters_singular LengthUnit.KILOMETERS -> R.string.fleet_distance_unit_kilometers_singular LengthUnit.FEET -> R.string.fleet_distance_unit_feets_singular LengthUnit.MILES -> R.string.fleet_distance_unit_miles_singular LengthUnit.CENTIMETER -> R.string.fleet_distance_unit_centimeter_singular else -> R.string.fleet_distance_unit_inch_singular } is PressureUnit -> when (this) { PressureUnit.INCH_PER_MERCURY -> R.string.fleet_pressure_unit_inch_mercury_singular else -> R.string.fleet_pressure_unit_millibars_singular } is SpeedUnit -> when (this) { SpeedUnit.KILOMETERS_PER_HOUR -> R.string.fleet_speed_unit_kilometers_singular SpeedUnit.MILES_PER_HOUR -> R.string.fleet_speed_unit_miles_singular else -> R.string.fleet_speed_unit_knots_singular } is TemperatureUnit -> when (this) { TemperatureUnit.CELSIUS -> R.string.fleet_temperature_unit_celsius_singular else -> R.string.fleet_temperature_unit_fahrenheit_singular } is TimeUnit -> when (this) { TimeUnit.MILLISECONDS -> R.string.fleet_time_unit_milliseconds_singular TimeUnit.MINUTES -> R.string.fleet_time_unit_minutes_singular else -> R.string.fleet_time_unit_seconds_singular } is WeightUnit -> when (this) { WeightUnit.GRAMS -> R.string.fleet_weight_unit_grams_singular else -> R.string.fleet_weight_unit_kilograms_plural } else -> throw IllegalArgumentException("unkown unit class ${javaClass.name}") }) fun Unit.getSymbol(resources: Resources): String? = when (this) { LengthUnit.FEET -> resources.getString(R.string.fleet_distance_unit_feets_symbol) LengthUnit.INCH -> resources.getString(R.string.fleet_distance_unit_inch_symbol) PressureUnit.INCH_PER_MERCURY -> resources.getString(R.string.fleet_pressure_unit_inch_mercury_symbol) else -> null } fun LengthUnit.Companion.shortString(resources: Resources, unit: LengthUnit): String { return unitString(resources, unit, UnitLength.SHORT, false) } fun unitString(resources: Resources, unit: LengthUnit, length: UnitLength, plural: Boolean): String = when (length) { UnitLength.FULL -> when (unit) { LengthUnit.METERS -> resources.getQuantityString(R.plurals.fleet_distance_unit_meter, if (plural) 2 else 1) LengthUnit.KILOMETERS -> resources.getQuantityString(R.plurals.fleet_distance_unit_kilometer, if (plural) 2 else 1) LengthUnit.FEET -> resources.getQuantityString(R.plurals.fleet_distance_unit_feet, if (plural) 2 else 1) LengthUnit.MILES -> resources.getQuantityString(R.plurals.fleet_distance_unit_mile, if (plural) 2 else 1) else -> "?" } UnitLength.SHORT -> when (unit) { LengthUnit.METERS -> resources.getString(R.string.fleet_distance_unit_meter) LengthUnit.KILOMETERS -> resources.getString(R.string.fleet_distance_unit_kilometer) LengthUnit.FEET -> resources.getString(R.string.fleet_distance_unit_feet) LengthUnit.MILES -> resources.getString(R.string.fleet_distance_unit_mile) else -> "?" } else -> "?" }
mit
597bf564917feeb82187720ffd291235
33.474886
123
0.65969
4.036898
false
false
false
false
slartus/4pdaClient-plus
topic/topic-data/src/main/java/org/softeg/slartus/forpdaplus/topic/data/screens/attachments/models/TopicAttachmentResponse.kt
1
840
package org.softeg.slartus.forpdaplus.topic.data.screens.attachments.models import ru.softeg.slartus.forum.api.TopicAttachment data class TopicAttachmentResponse( val id: String? = null, val iconUrl: String? = null, val url: String? = null, val name: String? = null, val date: String? = null, val size: String? = null, val postUrl: String? = null ) class TopicAttachmentsResponse(list: List<TopicAttachmentResponse>) : List<TopicAttachmentResponse> by list fun TopicAttachmentResponse.mapToTopicAttachmentOrNull(): TopicAttachment? { return TopicAttachment( id = id ?: return null, url = url ?: return null, iconUrl = iconUrl.orEmpty(), name = name ?: "not parsed", date = date.orEmpty(), size = size.orEmpty(), postUrl = postUrl.orEmpty() ) }
apache-2.0
2b81fcf7d93180d8f764ae351b2fff94
29.035714
107
0.671429
4.057971
false
false
false
false
Mashape/httpsnippet
test/fixtures/output/kotlin/okhttp/full.kt
1
476
val client = OkHttpClient() val mediaType = MediaType.parse("application/x-www-form-urlencoded") val body = RequestBody.create(mediaType, "foo=bar") val request = Request.Builder() .url("http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value") .post(body) .addHeader("cookie", "foo=bar; bar=baz") .addHeader("accept", "application/json") .addHeader("content-type", "application/x-www-form-urlencoded") .build() val response = client.newCall(request).execute()
mit
e5eccb0ea3cd59950baae9b83b276758
35.615385
68
0.718487
3.282759
false
false
false
false
slartus/4pdaClient-plus
domain-user-profile/src/main/java/ru/slartus/domain_user_profile/parsers/UserProfileParser.kt
1
1596
package ru.slartus.domain_user_profile.parsers import android.os.Bundle import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import org.jsoup.Jsoup import org.softeg.slartus.forpdaplus.core.entities.UserProfile import org.softeg.slartus.forpdaplus.core.interfaces.Parser import org.softeg.slartus.forpdaplus.core.services.UserProfileService import org.softeg.slartus.hosthelper.HostHelper import ru.slartus.domain_user_profile.entities.UserProfileImpl import java.util.regex.Pattern import javax.inject.Inject class UserProfileParser @Inject constructor() : Parser<UserProfile?> { override val id: String get() = UserProfileParser::class.java.simpleName private val _data = MutableStateFlow<UserProfile?>(null) override val data get() = _data.asStateFlow() override fun isOwn(url: String, args: Bundle?): Boolean { return args?.containsKey(UserProfileService.ARG_USER_ID) == true && checkUrlRegex.matcher(url).find() } override suspend fun parse(page: String, args: Bundle?): UserProfile? { val id = args?.getString(UserProfileService.ARG_USER_ID) val jsoupDocument = Jsoup.parse(page, HostHelper.schemedHost) val userNick = jsoupDocument.select("div.user-box > h1").first()?.text() id ?: return null return UserProfileImpl(id, userNick) } companion object { private val checkUrlRegex by lazy { Pattern.compile( """showuser=\d+""", Pattern.CASE_INSENSITIVE ) } } }
apache-2.0
58e0971f767eb6f9e95c824af1d0ac12
35.295455
80
0.703008
4.372603
false
false
false
false
stripe/stripe-android
paymentsheet/src/main/java/com/stripe/android/paymentsheet/addresselement/AddressElementPrimaryButton.kt
1
3308
package com.stripe.android.paymentsheet.addresselement import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.ButtonDefaults import androidx.compose.material.ContentAlpha import androidx.compose.material.LocalContentAlpha import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.dp import com.stripe.android.ui.core.PaymentsTheme import com.stripe.android.ui.core.getBackgroundColor import com.stripe.android.ui.core.getBorderStrokeColor import com.stripe.android.ui.core.getOnBackgroundColor @Composable internal fun AddressElementPrimaryButton( isEnabled: Boolean, text: String, onButtonClick: () -> Unit ) { // We need to use PaymentsTheme.primaryButtonStyle instead of MaterialTheme // because of the rules API for primary button. val context = LocalContext.current val background = Color(PaymentsTheme.primaryButtonStyle.getBackgroundColor(context)) val onBackground = Color(PaymentsTheme.primaryButtonStyle.getOnBackgroundColor(context)) val borderStroke = BorderStroke( PaymentsTheme.primaryButtonStyle.shape.borderStrokeWidth.dp, Color(PaymentsTheme.primaryButtonStyle.getBorderStrokeColor(context)) ) val shape = RoundedCornerShape( PaymentsTheme.primaryButtonStyle.shape.cornerRadius ) val fontFamily = PaymentsTheme.primaryButtonStyle.typography.fontFamily val textStyle = TextStyle( fontFamily = if (fontFamily != null) FontFamily(Font(fontFamily)) else FontFamily.Default, fontSize = PaymentsTheme.primaryButtonStyle.typography.fontSize ) CompositionLocalProvider( LocalContentAlpha provides if (isEnabled) ContentAlpha.high else ContentAlpha.disabled ) { Box( modifier = Modifier .fillMaxWidth() .padding(vertical = 16.dp), contentAlignment = Alignment.Center ) { TextButton( onClick = onButtonClick, modifier = Modifier .fillMaxWidth() .height(44.dp), enabled = isEnabled, shape = shape, border = borderStroke, colors = ButtonDefaults.buttonColors( backgroundColor = background, disabledBackgroundColor = background ) ) { Text( text = text, color = onBackground.copy(alpha = LocalContentAlpha.current), style = textStyle ) } } } }
mit
3395181609c1c52d01c827a86d9d8ab1
38.855422
98
0.708283
5.184953
false
false
false
false
AndroidX/androidx
compose/foundation/foundation/integration-tests/foundation-demos/src/main/java/androidx/compose/foundation/demos/text/ComposeTextAccessibility.kt
3
3131
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.demos.text import androidx.compose.material.Text import androidx.compose.foundation.layout.Column import androidx.compose.runtime.Composable import androidx.compose.ui.text.ExperimentalTextApi import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.UrlAnnotation import androidx.compose.ui.text.VerbatimTtsAnnotation import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.intl.LocaleList import androidx.compose.ui.text.withAnnotation import androidx.compose.ui.tooling.preview.Preview @OptIn(ExperimentalTextApi::class) @Preview @Composable fun TextAccessibilityDemo() { Column { TagLine("Text to speech with different locales.") Text( text = buildAnnotatedString { pushStyle(SpanStyle(localeList = LocaleList("en-us"))) append("Hello!\n") pop() pushStyle(SpanStyle(localeList = LocaleList("en-gb"))) append("Hello!\n") pop() pushStyle(SpanStyle(localeList = LocaleList("fr"))) append("Bonjour!\n") pop() pushStyle(SpanStyle(localeList = LocaleList("tr-TR"))) append("Merhaba!\n") pop() pushStyle(SpanStyle(localeList = LocaleList("ja-JP"))) append("こんにちは!\n") pop() pushStyle(SpanStyle(localeList = LocaleList("zh"))) append("你好!") pop() }, style = TextStyle(fontSize = fontSize8) ) TagLine("VerbatimTtsAnnotation ") Text( text = buildAnnotatedString { append("This word is read verbatim: ") pushTtsAnnotation(VerbatimTtsAnnotation(verbatim = "hello")) append("hello\n") pop() append("This word is read normally: hello") }, style = TextStyle(fontSize = fontSize8) ) TagLine("UrlAnnotation") Text( text = buildAnnotatedString { append("This word is a link: ") withAnnotation(UrlAnnotation("https://google.com")) { append("Google\n") } append("This word is not a link: google.com") }, style = TextStyle(fontSize = fontSize8) ) } }
apache-2.0
e002ebb9d4a6ae43d5311a4e973ecdb1
35.255814
76
0.610523
4.916404
false
false
false
false
thanksmister/androidthings-mqtt-alarm-panel
app/src/main/java/com/thanksmister/iot/mqtt/alarmpanel/network/MailGunApi.kt
1
3150
/* * <!-- * ~ Copyright (c) 2017. ThanksMister 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.thanksmister.iot.mqtt.alarmpanel.network import android.graphics.Bitmap import android.util.Base64 import com.facebook.stetho.okhttp3.StethoInterceptor import com.google.gson.Gson import com.google.gson.GsonBuilder import org.json.JSONObject import java.io.ByteArrayOutputStream import java.util.concurrent.TimeUnit import okhttp3.MediaType import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.Response import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class MailGunApi(domain: String, private val apiKey: String) { private val service: MailGunRequest init { val base_url = "https://api.mailgun.net/v3/$domain/" val logging = HttpLoggingInterceptor() logging.level = HttpLoggingInterceptor.Level.HEADERS val httpClient = OkHttpClient.Builder() .addInterceptor(logging) .connectTimeout(10000, TimeUnit.SECONDS) .readTimeout(10000, TimeUnit.SECONDS) .addNetworkInterceptor(StethoInterceptor()) .build() val gson = GsonBuilder() .create() val retrofit = Retrofit.Builder() .client(httpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl(base_url) .build() service = retrofit.create(MailGunRequest::class.java) } fun emailImages(from: String, to: String, subject: String, text: String, bitmap: Bitmap): Call<JSONObject> { val clientIdAndSecret = "api" + ":" + apiKey val authorizationHeader = BASIC + " " + Base64.encodeToString(clientIdAndSecret.toByteArray(), Base64.NO_WRAP) val service = service val stream = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.PNG, 75, stream) val byteArray = stream.toByteArray() return service.sendMailAttachment(authorizationHeader, RequestBody.create(MediaType.parse("text/plain"), from), RequestBody.create(MediaType.parse("text/plain"), to), RequestBody.create(MediaType.parse("text/plain"), subject), RequestBody.create(MediaType.parse("text/plain"), text), RequestBody.create(MediaType.parse("image/*"), byteArray)) } companion object { private val BASIC = "Basic" } }
apache-2.0
c13e20b6c276b85bea879da0e12ffad5
32.88172
118
0.671429
4.442877
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/utils/evaluation/ConstExpr.kt
3
3602
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.utils.evaluation import org.rust.lang.core.psi.ext.BinaryOperator import org.rust.lang.core.psi.ext.UnaryOperator import org.rust.lang.core.types.TypeFlags import org.rust.lang.core.types.consts.Const import org.rust.lang.core.types.consts.CtUnevaluated import org.rust.lang.core.types.consts.CtUnknown import org.rust.lang.core.types.consts.CtValue import org.rust.lang.core.types.infer.TypeFoldable import org.rust.lang.core.types.infer.TypeFolder import org.rust.lang.core.types.infer.TypeVisitor import org.rust.lang.core.types.ty.* fun ConstExpr<*>.toConst(): Const = when (this) { is ConstExpr.Constant -> const is ConstExpr.Value -> CtValue(this) is ConstExpr.Error -> CtUnknown else -> CtUnevaluated(this) } sealed class ConstExpr<T : Ty>(val flags: TypeFlags = 0) : TypeFoldable<ConstExpr<T>> { abstract val expectedTy: T? data class Unary<T : Ty>( val operator: UnaryOperator, val expr: ConstExpr<T>, override val expectedTy: T ) : ConstExpr<T>(expr.flags) { override fun superFoldWith(folder: TypeFolder): Unary<T> = Unary(operator, expr.foldWith(folder), expectedTy) override fun superVisitWith(visitor: TypeVisitor): Boolean = expr.visitWith(visitor) } data class Binary<T : Ty>( val left: ConstExpr<T>, val operator: BinaryOperator, val right: ConstExpr<T>, override val expectedTy: T ) : ConstExpr<T>(left.flags or right.flags) { override fun superFoldWith(folder: TypeFolder): Binary<T> = Binary(left.foldWith(folder), operator, right.foldWith(folder), expectedTy) override fun superVisitWith(visitor: TypeVisitor): Boolean = left.visitWith(visitor) || right.visitWith(visitor) } data class Constant<T : Ty>( val const: Const, override val expectedTy: T ) : ConstExpr<T>(const.flags) { override fun superFoldWith(folder: TypeFolder): Constant<T> = Constant(const.foldWith(folder), expectedTy) override fun superVisitWith(visitor: TypeVisitor): Boolean = const.visitWith(visitor) } sealed class Value<T : Ty> : ConstExpr<T>() { override fun superFoldWith(folder: TypeFolder): Value<T> = this override fun superVisitWith(visitor: TypeVisitor): Boolean = false data class Bool(val value: Boolean) : Value<TyBool>() { override val expectedTy: TyBool = TyBool.INSTANCE override fun toString(): String = value.toString() } data class Integer(val value: Long, override val expectedTy: TyInteger) : Value<TyInteger>() { override fun toString(): String = value.toString() } data class Float(val value: Double, override val expectedTy: TyFloat) : Value<TyFloat>() { override fun toString(): String = value.toString() } data class Char(val value: String) : Value<TyChar>() { override val expectedTy: TyChar = TyChar.INSTANCE override fun toString(): String = value } data class Str(val value: String, override val expectedTy: TyReference) : Value<TyReference>() { override fun toString(): String = value } } class Error<T : Ty> : ConstExpr<T>() { override val expectedTy: T? = null override fun superFoldWith(folder: TypeFolder): ConstExpr<T> = this override fun superVisitWith(visitor: TypeVisitor): Boolean = false } }
mit
67a55cf77964bab7a4762c7ce7487406
38.152174
120
0.669073
4.074661
false
false
false
false
androidx/androidx
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/KspMethodType.kt
3
2908
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.room.compiler.processing.ksp import androidx.room.compiler.processing.XMethodType import androidx.room.compiler.processing.XSuspendMethodType import androidx.room.compiler.processing.XType import com.squareup.javapoet.TypeVariableName internal sealed class KspMethodType( env: KspProcessingEnv, override val origin: KspMethodElement, containing: KspType? ) : KspExecutableType(env, origin, containing), XMethodType { override val typeVariableNames: List<TypeVariableName> by lazy { origin.declaration.typeParameters.map { val typeParameterBounds = it.bounds.map { it.asJTypeName(env.resolver) }.toList().toTypedArray() TypeVariableName.get( it.name.asString(), *typeParameterBounds ) } } private class KspNormalMethodType( env: KspProcessingEnv, origin: KspMethodElement, containing: KspType? ) : KspMethodType(env, origin, containing) { override val returnType: XType by lazy { origin.declaration.returnKspType( env = env, containing = containing ) } } private class KspSuspendMethodType( env: KspProcessingEnv, origin: KspMethodElement, containing: KspType? ) : KspMethodType(env, origin, containing), XSuspendMethodType { override val returnType: XType // suspend functions always return Any?, no need to call asMemberOf get() = origin.returnType override fun getSuspendFunctionReturnType(): XType { // suspend functions work w/ continuation so it is always boxed return env.wrap( ksType = origin.declaration.returnTypeAsMemberOf( ksType = containing?.ksType ), allowPrimitives = false ) } } companion object { fun create( env: KspProcessingEnv, origin: KspMethodElement, containing: KspType? ) = if (origin.isSuspendFunction()) { KspSuspendMethodType(env, origin, containing) } else { KspNormalMethodType(env, origin, containing) } } }
apache-2.0
d22313d740ff97126ec5183130529d77
33.211765
79
0.64271
4.987993
false
false
false
false
androidx/androidx
glance/glance/src/androidMain/kotlin/androidx/glance/semantics/SemanticsProperties.kt
3
3935
/* * 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.glance.semantics /** * General semantics properties, mainly used for accessibility and testing. * * Each property is intended to be set by the respective SemanticsPropertyReceiver extension instead * of used directly. */ object SemanticsProperties { /** * @see SemanticsPropertyReceiver.contentDescription */ val ContentDescription = SemanticsPropertyKey<List<String>>( name = "ContentDescription", mergePolicy = { parentValue, childValue -> parentValue?.toMutableList()?.also { it.addAll(childValue) } ?: childValue } ) } /** * SemanticsPropertyKey is the infrastructure for setting key/value pairs inside semantics block in * a type-safe way. Each key has one particular statically defined value type T. */ class SemanticsPropertyKey<T>( /** * The name of the property. Should be the same as the constant from shich it is accessed. */ val name: String, internal val mergePolicy: (T?, T) -> T? = { parentValue, childValue -> parentValue ?: childValue } ) { fun merge(parentValue: T?, childValue: T): T? { return mergePolicy(parentValue, childValue) } } /** * SemanticsPropertyReceiver is the scope provided by semantics {} blocks, letting you set key/value * pairs primarily via extension functions. */ interface SemanticsPropertyReceiver { operator fun <T> set(key: SemanticsPropertyKey<T>, value: T) } /** * Developer-set content description of the semantics node, for use in testing, accessibility and * similar use cases. */ var SemanticsPropertyReceiver.contentDescription: String /** * Throws [UnsupportedOperationException]. Should not be called. */ get() { throw UnsupportedOperationException( "You cannot retrieve a semantics property directly" ) } set(value) { set(SemanticsProperties.ContentDescription, listOf(value)) } /** * Describes the semantics information associated with the owning component. */ class SemanticsConfiguration : SemanticsPropertyReceiver { private val props: MutableMap<SemanticsPropertyKey<*>, Any?> = mutableMapOf() override fun <T> set(key: SemanticsPropertyKey<T>, value: T) { props[key] = value } /** * Retrieves the value for the given property, if one has been set, * If a value has not been set, throws [IllegalStateException] */ // Unavoidable, guaranteed by [set] @Suppress("UNCHECKED_CAST") operator fun <T> get(key: SemanticsPropertyKey<T>): T { return props.getOrElse(key) { throw java.lang.IllegalStateException("Key not present: $key") } as T } /** * Retrieves the value for the given property, if one has been set, * If a value has not been set, returns the provided default value. */ // Unavoidable, guaranteed by [set] @Suppress("UNCHECKED_CAST") fun <T> getOrElseNullable(key: SemanticsPropertyKey<T>, defaultValue: () -> T?): T? { return props.getOrElse(key, defaultValue) as T? } /** * Retrieves the value for the given property, if one has been set, * If a value has not been set, returns null */ fun <T> getOrNull(key: SemanticsPropertyKey<T>): T? { return getOrElseNullable(key) { null } } }
apache-2.0
4301d777a9b73064b91223c0305c6586
32.931034
100
0.684879
4.486887
false
false
false
false
angelgladin/Photo_Exif_Toolkit
app/src/main/kotlin/com/angelgladin/photoexiftoolkit/activity/HomeActivity.kt
1
5503
/** * Photo EXIF Toolkit for Android. * * Copyright (C) 2017 Ángel Iván Gladín García * * 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.angelgladin.photoexiftoolkit.activity import android.Manifest import android.app.AlertDialog import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import com.angelgladin.photoexiftoolkit.R import com.angelgladin.photoexiftoolkit.extension.getPathFromUri import com.angelgladin.photoexiftoolkit.extension.showSnackbar import com.angelgladin.photoexiftoolkit.presenter.HomePresenter import com.angelgladin.photoexiftoolkit.util.Constants import com.angelgladin.photoexiftoolkit.view.HomeView import com.karumi.dexter.Dexter import com.karumi.dexter.MultiplePermissionsReport import com.karumi.dexter.PermissionToken import com.karumi.dexter.listener.PermissionRequest import com.karumi.dexter.listener.multi.MultiplePermissionsListener import kotlinx.android.synthetic.main.activity_home.* import kotlinx.android.synthetic.main.content_home.* class HomeActivity : AppCompatActivity(), HomeView { companion object { val PICK_IMAGE_REQUEST = 666 } val presenter = HomePresenter(this) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) setSupportActionBar(toolbar) setupUiListeners() } private fun setupUiListeners() { card_view_from_gallery.setOnClickListener { requestPermissionsAndOpenGallery() } } private fun requestPermissionsAndOpenGallery() { Dexter.withActivity(this) .withPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION) .withListener(object : MultiplePermissionsListener { override fun onPermissionsChecked(report: MultiplePermissionsReport) { if (report.areAllPermissionsGranted()) presenter.getPhotoFromGallery() } override fun onPermissionRationaleShouldBeShown(permissions: MutableList<PermissionRequest>, token: PermissionToken) { AlertDialog.Builder(this@HomeActivity).setTitle(R.string.app_name) .setMessage(R.string.permission_rationale_message) .setNegativeButton(android.R.string.cancel, { dialog, _ -> dialog.dismiss() token.cancelPermissionRequest() }) .setPositiveButton(android.R.string.ok, { dialog, _ -> dialog.dismiss() token.continuePermissionRequest() }) .setOnDismissListener({ token.cancelPermissionRequest() }) .show() } }) .check() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.data != null) { val selectedImage = data.data val pathFile = selectedImage.getPathFromUri(this) presenter.launchPhotoDetailActivity(pathFile) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { R.id.action_about_developer -> { presenter.aboutDeveloper() true } R.id.action_about_app -> { presenter.aboutApp() true } else -> super.onOptionsItemSelected(item) } override fun getContext(): Context = this override fun destroy() { } override fun openGallery() { val photoPickerIntent = Intent(Intent.ACTION_PICK) photoPickerIntent.type = "image/*" startActivityForResult(photoPickerIntent, PICK_IMAGE_REQUEST) } override fun showAboutDeveloperDialog() { coordinator_layout.showSnackbar(R.string.not_implemented_yet) } override fun showAboutAppDialog() { coordinator_layout.showSnackbar(R.string.not_implemented_yet) } override fun launchPhotoDetailActivity(pathFile: String?) { val intent = Intent(this, PhotoDetailActivity::class.java) intent.putExtra(Constants.PATH_FILE_KEY, pathFile) startActivity(intent) } }
gpl-3.0
5514dd17744a2baa9a9c7dd929599268
36.664384
138
0.654483
5.063536
false
false
false
false
klazuka/intellij-elm
src/main/kotlin/org/elm/ide/refactoring/nameSuggestions.kt
1
2825
package org.elm.ide.refactoring import com.intellij.psi.codeStyle.NameUtil import org.elm.lang.core.psi.ElmExpressionTag import org.elm.lang.core.psi.elements.ElmFieldAccessExpr import org.elm.lang.core.psi.elements.ElmFunctionCallExpr import org.elm.lang.core.psi.elements.ElmValueExpr import org.elm.lang.core.resolve.scope.ExpressionScope import org.elm.lang.core.toElmLowerId import org.elm.lang.core.types.* data class SuggestedNames(val default: String, val all: LinkedHashSet<String>) /** * Return at least one suggestion for a name that describes the receiver expression. */ fun ElmExpressionTag.suggestedNames(): SuggestedNames { val names = LinkedHashSet<String>() val ty = findTy() when { this is ElmFunctionCallExpr -> { // suggest based on function call (e.g. suggest "books" for expr: `getBooks "shakespeare" library`) val target = target if (target is ElmValueExpr) { names.addName(target.referenceName) } } this is ElmFieldAccessExpr -> { // suggest the last field in a record field access chain (e.g. "title" in expr `model.currentPage.title`) names.addName(this.lowerCaseIdentifier.text) } } // if present, suggest type alias (useful for records which often have a descriptive alias name) ty?.alias?.name?.let { names.addName(it) } // suggest based on the type of the expression ty?.suggestedTyName()?.let { names.addName(it) } // filter-out any suggestion which would conflict with a name that is already in lexical scope val usedNames = ExpressionScope(this).getVisibleValues().mapNotNullTo(HashSet()) { it.name } val defaultName = suggestDefault(names, usedNames) names.removeAll(usedNames) return SuggestedNames(defaultName, names) } private fun Ty.suggestedTyName(): String? = when (this) { TyInt -> "i" TyFloat -> "d" TyShader -> "shader" is TyFunction -> "f" is TyUnion -> name.toElmLowerId() is TyRecord -> "record" is TyTuple -> "tuple" is TyVar -> name else -> null } private fun suggestDefault(names: LinkedHashSet<String>, usedNames: Set<String>): String { val default = names.firstOrNull() ?: "x" if (default !in usedNames) return default return (1..100).asSequence() .map { "$default$it" } .firstOrNull { it !in usedNames } ?: "x" } private fun LinkedHashSet<String>.addName(name: String?) { if (name == null) return // Generate variants on compound words (e.g. "selectedItem" -> ["item", "selectedItem"]) NameUtil.getSuggestionsByName(name, "", "", false, false, false) .mapTo(this) { it.toElmLowerId() } }
mit
484395f100dc0e06cbd20acee428c58f
34.3125
117
0.650619
4.047278
false
false
false
false
westnordost/osmagent
app/src/main/java/de/westnordost/streetcomplete/quests/car_wash_type/AddCarWashTypeForm.kt
1
1872
package de.westnordost.streetcomplete.quests.car_wash_type import android.os.Bundle import android.view.View import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.quests.AImageListQuestAnswerFragment import de.westnordost.streetcomplete.view.ImageSelectAdapter import de.westnordost.streetcomplete.view.Item class AddCarWashTypeForm : AImageListQuestAnswerFragment<AddCarWashTypeForm.CarWashOption, CarWashType>() { override val items = listOf( Item(CarWashOption.AUTOMATED, R.drawable.car_wash_automated, R.string.quest_carWashType_automated), Item(CarWashOption.SELF_SERVICE, R.drawable.car_wash_self_service, R.string.quest_carWashType_selfService), Item(CarWashOption.SERVICE, R.drawable.car_wash_service, R.string.quest_carWashType_service) ) override val itemsPerRow = 3 override val maxSelectableItems = 3 override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) imageSelector.listeners.add(object : ImageSelectAdapter.OnItemSelectionListener { override fun onIndexSelected(index: Int) { // service is exclusive with everything else if (index == 2) { imageSelector.deselect(0) imageSelector.deselect(1) } else { imageSelector.deselect(2) } } override fun onIndexDeselected(index: Int) {} }) } override fun onClickOk(selectedItems: List<CarWashOption>) { applyAnswer(CarWashType( isSelfService = selectedItems.contains(CarWashOption.SELF_SERVICE), isAutomated = selectedItems.contains(CarWashOption.AUTOMATED) )) } enum class CarWashOption { AUTOMATED, SELF_SERVICE, SERVICE } }
gpl-3.0
38503e61bb81793812aa34477ca4432d
37.204082
115
0.691239
4.543689
false
false
false
false
hitoshura25/Media-Player-Omega-Android
app/src/test/java/com/vmenon/mpo/viewmodel/HomeViewModelTest.kt
1
1099
package com.vmenon.mpo.viewmodel import androidx.appcompat.app.AppCompatActivity import com.vmenon.mpo.auth.domain.biometrics.PromptRequest import com.vmenon.mpo.test.TestCoroutineRule import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify @ExperimentalCoroutinesApi class HomeViewModelTest { @get:Rule val testCoroutineRule = TestCoroutineRule() val viewModel = HomeViewModel() @Before fun setup() { viewModel.biometricsManager = mock() viewModel.authService = mock() viewModel.navigationController = mock() } @Test fun promptForBiometricsAfterEnrollmentCallsBiometricManager() { testCoroutineRule.runBlockingTest { val request = mock<PromptRequest>() val activity = mock<AppCompatActivity>() viewModel.promptForBiometricsAfterEnrollment(activity, request) verify(viewModel.biometricsManager).requestBiometricPrompt(activity, request) } } }
apache-2.0
cc406b467c7ddc6207c96fa54f5553c4
29.555556
89
0.742493
4.90625
false
true
false
false
android/tv-samples
ReferenceAppKotlin/app/src/main/java/com/android/tv/reference/browse/VideoCardPresenter.kt
1
3187
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tv.reference.browse import android.content.res.Resources import android.view.LayoutInflater import android.view.ViewGroup import androidx.leanback.widget.Presenter import com.android.tv.reference.R import com.android.tv.reference.databinding.PresenterVideoCardBinding import com.android.tv.reference.shared.datamodel.Video import com.android.tv.reference.shared.datamodel.VideoType import com.squareup.picasso.Picasso /** * Presents a [Video] as an [ImageCardView] with descriptive text based on the Video's type. */ class VideoCardPresenter : Presenter() { override fun onCreateViewHolder(parent: ViewGroup): ViewHolder { val context = parent.context val binding = PresenterVideoCardBinding.inflate(LayoutInflater.from(context), parent, false) // Set the image size ahead of time since loading can take a while. val resources = context.resources binding.root.setMainImageDimensions( resources.getDimensionPixelSize(R.dimen.image_card_width), resources.getDimensionPixelSize(R.dimen.image_card_height)) return ViewHolder(binding.root) } override fun onBindViewHolder(viewHolder: ViewHolder, item: Any?) { checkNotNull(item) val video = item as Video val binding = PresenterVideoCardBinding.bind(viewHolder.view) binding.root.titleText = video.name binding.root.contentText = getContentText(binding.root.resources, video) Picasso.get().load(video.thumbnailUri).placeholder(R.drawable.image_placeholder) .error(R.drawable.image_placeholder).into(binding.root.mainImageView) } override fun onUnbindViewHolder(viewHolder: ViewHolder) { val binding = PresenterVideoCardBinding.bind(viewHolder.view) binding.root.mainImage = null } /** * Returns a string to display as the "content" for an [ImageCardView]. * * Since Watch Next behavior differs for episodes, movies, and clips, this string makes it * more clear which [VideoType] each [Video] is. For example, clips are never included in * Watch Next. */ private fun getContentText(resources: Resources, video: Video): String { return when (video.videoType) { VideoType.EPISODE -> resources.getString(R.string.content_type_season_episode, video.seasonNumber, video.episodeNumber) VideoType.MOVIE -> resources.getString(R.string.content_type_movie) VideoType.CLIP -> resources.getString(R.string.content_type_clip) } } }
apache-2.0
840eb55c309a4a4dbbb1d198bcefd62a
40.934211
100
0.71823
4.476124
false
false
false
false
Heiner1/AndroidAPS
database/src/main/java/info/nightscout/androidaps/database/transactions/SyncNsExtendedBolusTransaction.kt
1
3665
package info.nightscout.androidaps.database.transactions import info.nightscout.androidaps.database.entities.ExtendedBolus import info.nightscout.androidaps.database.interfaces.end import kotlin.math.abs /** * Sync the Extended bolus from NS */ class SyncNsExtendedBolusTransaction(private val extendedBolus: ExtendedBolus) : Transaction<SyncNsExtendedBolusTransaction.TransactionResult>() { override fun run(): TransactionResult { val result = TransactionResult() if (extendedBolus.duration != 0L) { // not ending event val current: ExtendedBolus? = extendedBolus.interfaceIDs.nightscoutId?.let { database.extendedBolusDao.findByNSId(it) } if (current != null) { // nsId exists, allow only invalidation if (current.isValid && !extendedBolus.isValid) { current.isValid = false database.extendedBolusDao.updateExistingEntry(current) result.invalidated.add(current) } if (current.duration != extendedBolus.duration) { current.duration = extendedBolus.duration current.amount = extendedBolus.amount database.extendedBolusDao.updateExistingEntry(current) result.updatedDuration.add(current) } return result } // not known nsId val running = database.extendedBolusDao.getExtendedBolusActiveAt(extendedBolus.timestamp).blockingGet() if (running != null && abs(running.timestamp - extendedBolus.timestamp) < 1000 && running.interfaceIDs.nightscoutId == null) { // allow missing milliseconds // the same record, update nsId only running.interfaceIDs.nightscoutId = extendedBolus.interfaceIDs.nightscoutId database.extendedBolusDao.updateExistingEntry(running) result.updatedNsId.add(running) } else if (running != null) { // another running record. end current and insert new val pctRun = (extendedBolus.timestamp - running.timestamp) / running.duration.toDouble() running.amount *= pctRun running.end = extendedBolus.timestamp database.extendedBolusDao.updateExistingEntry(running) database.extendedBolusDao.insertNewEntry(extendedBolus) result.ended.add(running) result.inserted.add(extendedBolus) } else { database.extendedBolusDao.insertNewEntry(extendedBolus) result.inserted.add(extendedBolus) } return result } else { // ending event val running = database.extendedBolusDao.getExtendedBolusActiveAt(extendedBolus.timestamp).blockingGet() if (running != null) { val pctRun = (extendedBolus.timestamp - running.timestamp) / running.duration.toDouble() running.amount *= pctRun running.end = extendedBolus.timestamp database.extendedBolusDao.updateExistingEntry(running) result.ended.add(running) } } return result } class TransactionResult { val updatedNsId = mutableListOf<ExtendedBolus>() val updatedDuration = mutableListOf<ExtendedBolus>() val inserted = mutableListOf<ExtendedBolus>() val invalidated = mutableListOf<ExtendedBolus>() val ended = mutableListOf<ExtendedBolus>() } }
agpl-3.0
cd47b97513f5d81a10a0e973c70e6db7
43.168675
168
0.618281
5.744514
false
false
false
false
onoderis/failchat
src/main/kotlin/failchat/youtube/LiveChatRequest.kt
2
1629
package failchat.youtube import com.fasterxml.jackson.databind.node.ArrayNode import com.fasterxml.jackson.databind.node.JsonNodeFactory import com.fasterxml.jackson.databind.node.ObjectNode data class LiveChatRequest( val context: Context = Context(), val continuation: String ) { data class Context( val client: Client = Client(), val request: Request = Request(), val user: ObjectNode = JsonNodeFactory.instance.objectNode(), val clientScreenNonce: String = "MC4xNzQ1MzczNjgyNTc0MTI1" ) data class Client( val hl: String = "en-GB", val gl: String = "RU", val visitorData: String = "CgtvaTIycV9CTXMwSSjUiOP5BQ%3D%3D", val userAgent: String = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0,gzip(gfe)", val clientName: String = "WEB", val clientVersion: String = "2.20200814.00.00", val osName: String = "Windows", val osVersion: String = "10.0", val browserName: String = "Firefox", val browserVersion: String = "79.0", val screenWidthPoints: Int = 1920, val screenHeightPoints: Int = 362, val screenPixelDensity: Int = 1, val utcOffsetMinutes: Int = 180, val userInterfaceTheme: String = "USER_INTERFACE_THEME_LIGHT" ) data class Request( val internalExperimentFlags: ArrayNode = JsonNodeFactory.instance.arrayNode(), val consistencyTokenJars: ArrayNode = JsonNodeFactory.instance.arrayNode() ) }
gpl-3.0
57b290b55fb4b353039713196547022b
38.731707
127
0.629834
4.082707
false
false
false
false
Maccimo/intellij-community
platform/configuration-store-impl/src/ComponentStoreWithExtraComponents.kt
2
4960
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.configurationStore import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.application.impl.coroutineDispatchingContext import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.ServiceDescriptor import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.serviceContainer.ComponentManagerImpl import com.intellij.util.SmartList import com.intellij.util.concurrency.SynchronizedClearableLazy import com.intellij.util.containers.ContainerUtil import com.intellij.util.lang.CompoundRuntimeException import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch // A way to remove obsolete component data. internal val OBSOLETE_STORAGE_EP = ExtensionPointName<ObsoleteStorageBean>("com.intellij.obsoleteStorage") abstract class ComponentStoreWithExtraComponents : ComponentStoreImpl() { @Suppress("DEPRECATION") private val settingsSavingComponents = ContainerUtil.createLockFreeCopyOnWriteList<com.intellij.openapi.components.SettingsSavingComponent>() protected abstract val serviceContainer: ComponentManagerImpl private val asyncSettingsSavingComponents = SynchronizedClearableLazy { val result = mutableListOf<SettingsSavingComponent>() serviceContainer.processInitializedComponentsAndServices { if (it is SettingsSavingComponent) { result.add(it) } } result } final override fun initComponent(component: Any, serviceDescriptor: ServiceDescriptor?, pluginId: PluginId?) { if (component is @Suppress("DEPRECATION") com.intellij.openapi.components.SettingsSavingComponent) { settingsSavingComponents.add(component) } else if (component is SettingsSavingComponent) { @Suppress("UNUSED_VARIABLE") //this is needed to work around bug in Kotlin compiler (KT-42826) val result = asyncSettingsSavingComponents.drop() } super.initComponent(component, serviceDescriptor, pluginId) } override fun unloadComponent(component: Any) { if (component is SettingsSavingComponent) { asyncSettingsSavingComponents.drop() } super.unloadComponent(component) } internal suspend fun saveSettingsSavingComponentsAndCommitComponents(result: SaveResult, forceSavingAllSettings: Boolean, saveSessionProducerManager: SaveSessionProducerManager) { coroutineScope { // expects EDT launch(AppUIExecutor.onUiThread().expireWith(serviceContainer).coroutineDispatchingContext()) { val errors = SmartList<Throwable>() for (settingsSavingComponent in settingsSavingComponents) { runAndCollectException(errors) { settingsSavingComponent.save() } } result.addErrors(errors) } launch { val errors = SmartList<Throwable>() for (settingsSavingComponent in asyncSettingsSavingComponents.value) { runAndCollectException(errors) { settingsSavingComponent.save() } } result.addErrors(errors) } } // SchemeManager (asyncSettingsSavingComponent) must be saved before saving components (component state uses scheme manager in an ipr project, so, we must save it before) // so, call it sequentially, not inside coroutineScope commitComponentsOnEdt(result, forceSavingAllSettings, saveSessionProducerManager) } override fun commitComponents(isForce: Boolean, session: SaveSessionProducerManager, errors: MutableList<Throwable>) { // ensure that this task will not interrupt regular saving LOG.runAndLogException { commitObsoleteComponents(session, false) } super.commitComponents(isForce, session, errors) } internal open fun commitObsoleteComponents(session: SaveSessionProducerManager, isProjectLevel: Boolean) { for (bean in OBSOLETE_STORAGE_EP.iterable) { if (bean.isProjectLevel != isProjectLevel) { continue } val storage = (storageManager as? StateStorageManagerImpl)?.getOrCreateStorage(bean.file ?: continue, RoamingType.DISABLED) if (storage != null) { for (componentName in bean.components) { session.getProducer(storage)?.setState(null, componentName, null) } } } } } private inline fun <T> runAndCollectException(errors: MutableList<Throwable>, runnable: () -> T): T? { try { return runnable() } catch (e: ProcessCanceledException) { throw e } catch (e: CompoundRuntimeException) { errors.addAll(e.exceptions) return null } catch (e: Throwable) { errors.add(e) return null } }
apache-2.0
b78a138105253c3ee4f3ff68b25a69fa
37.75
174
0.742742
5.265393
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/widget/views/ViewsWidgetListViewModel.kt
1
5519
package org.wordpress.android.ui.stats.refresh.lists.widget.views import androidx.annotation.LayoutRes import kotlinx.coroutines.runBlocking import org.wordpress.android.R import org.wordpress.android.fluxc.model.stats.LimitMode import org.wordpress.android.fluxc.model.stats.LimitMode.Top import org.wordpress.android.fluxc.model.stats.time.VisitsAndViewsModel.PeriodData import org.wordpress.android.fluxc.network.utils.StatsGranularity.DAYS import org.wordpress.android.fluxc.store.SiteStore import org.wordpress.android.fluxc.store.stats.time.VisitsAndViewsStore import org.wordpress.android.ui.prefs.AppPrefsWrapper import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ValueItem.State.NEGATIVE import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ValueItem.State.NEUTRAL import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ValueItem.State.POSITIVE import org.wordpress.android.ui.stats.refresh.lists.sections.granular.usecases.OVERVIEW_ITEMS_TO_LOAD import org.wordpress.android.ui.stats.refresh.lists.sections.granular.usecases.OverviewMapper import org.wordpress.android.ui.stats.refresh.lists.widget.configuration.StatsColorSelectionViewModel.Color import org.wordpress.android.ui.stats.refresh.utils.MILLION import org.wordpress.android.ui.stats.refresh.utils.ONE_THOUSAND import org.wordpress.android.ui.stats.refresh.utils.StatsDateFormatter import org.wordpress.android.viewmodel.ResourceProvider import javax.inject.Inject const val LIST_ITEM_COUNT = 7 class ViewsWidgetListViewModel @Inject constructor( private val siteStore: SiteStore, private val visitsAndViewsStore: VisitsAndViewsStore, private val overviewMapper: OverviewMapper, private val resourceProvider: ResourceProvider, private val statsDateFormatter: StatsDateFormatter, private val appPrefsWrapper: AppPrefsWrapper ) { private var siteId: Int? = null private var colorMode: Color = Color.LIGHT private var isWideView: Boolean = true private var appWidgetId: Int? = null private val mutableData = mutableListOf<ListItemUiModel>() val data: List<ListItemUiModel> = mutableData fun start(siteId: Int, colorMode: Color, isWideView: Boolean, appWidgetId: Int) { this.siteId = siteId this.colorMode = colorMode this.isWideView = isWideView this.appWidgetId = appWidgetId } fun onDataSetChanged(onError: (appWidgetId: Int) -> Unit) { siteId?.apply { val site = siteStore.getSiteByLocalId(this) if (site != null) { runBlocking { visitsAndViewsStore.fetchVisits(site, DAYS, Top(OVERVIEW_ITEMS_TO_LOAD)) } val visitsAndViewsModel = visitsAndViewsStore.getVisits( site, DAYS, LimitMode.All ) val periods = visitsAndViewsModel?.dates?.asReversed() ?: listOf() val uiModels = periods.mapIndexed { index, periodData -> buildListItemUiModel(index, periodData, periods, site.id) }.take(LIST_ITEM_COUNT) if (uiModels != data) { mutableData.clear() mutableData.addAll(uiModels) appWidgetId?.let { appPrefsWrapper.setAppWidgetHasData(true, it) } } } else { appWidgetId?.let { nonNullAppWidgetId -> onError(nonNullAppWidgetId) } } } } private fun buildListItemUiModel( position: Int, selectedItem: PeriodData, periods: List<PeriodData>, localSiteId: Int ): ListItemUiModel { val layout = when (colorMode) { Color.DARK -> R.layout.stats_views_widget_item_dark Color.LIGHT -> R.layout.stats_views_widget_item_light } val previousItem = periods.getOrNull(position + 1) val isCurrentDay = position == 0 val startValue = if (isWideView) MILLION else ONE_THOUSAND val uiModel = overviewMapper.buildTitle(selectedItem, previousItem, 0, isCurrentDay, startValue) val key = if (isCurrentDay) { resourceProvider.getString(R.string.stats_insights_today_stats) } else { statsDateFormatter.printDate(periods[position].period) } val isPositiveChangeVisible = uiModel.state == POSITIVE && isWideView && !uiModel.change.isNullOrEmpty() val isNegativeChangeVisible = uiModel.state == NEGATIVE && isWideView && !uiModel.change.isNullOrEmpty() val isNeutralChangeVisible = uiModel.state == NEUTRAL && isWideView && !uiModel.change.isNullOrEmpty() return ListItemUiModel( layout, key, uiModel.value, isPositiveChangeVisible, isNegativeChangeVisible, isNeutralChangeVisible, uiModel.change, selectedItem.period, localSiteId ) } data class ListItemUiModel( @LayoutRes val layout: Int, val key: String, val value: String, val isPositiveChangeVisible: Boolean, val isNegativeChangeVisible: Boolean, val isNeutralChangeVisible: Boolean, val change: String? = null, val period: String, val localSiteId: Int ) }
gpl-2.0
a4f379e6998ef7c6d028f290997445b8
42.456693
112
0.668418
4.665258
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/tests/testData/slicer/outflow/diamondHierarchyMiddleClassFun.kt
13
318
// FLOW: OUT interface A { fun foo() = 1 } open class B : A { override fun foo() = <caret>2 } interface C : A { override fun foo() = 3 } class D : B(), C { override fun foo() = 4 } fun test(a: A, b: B, c: C, d: D) { val x = a.foo() val y = b.foo() val z = c.foo() val u = d.foo() }
apache-2.0
0bf0909c67d3358da462fc5fddf69c3d
12.291667
34
0.474843
2.503937
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinJvmAnnotationInJavaInspection.kt
1
1684
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.JavaElementVisitor import com.intellij.psi.PsiAnnotation import org.jetbrains.kotlin.idea.base.resources.KotlinBundle class KotlinJvmAnnotationInJavaInspection : LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : JavaElementVisitor() { private val KOTLIN_JVM_PACKAGE = "kotlin.jvm." override fun visitAnnotation(annotation: PsiAnnotation) { val qualifiedName = annotation.qualifiedName ?: return if (qualifiedName.startsWith(KOTLIN_JVM_PACKAGE)) { val annotationName = qualifiedName.removePrefix(KOTLIN_JVM_PACKAGE) holder.registerProblem( annotation, KotlinBundle.message("inspection.kotlin.jvm.annotation.in.java.description", "@$annotationName"), RemoveAnnotationFix() ) } } } private class RemoveAnnotationFix : LocalQuickFix { override fun getFamilyName() = KotlinBundle.message("fix.remove.annotation.text") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { descriptor.psiElement.delete() } } }
apache-2.0
441f3353ea0f6a5a744e1547ab3a1996
44.513514
158
0.71734
5.312303
false
false
false
false
GunoH/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/findUsageUtils.kt
3
2900
// 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.findUsages import com.intellij.find.findUsages.FindUsagesManager import com.intellij.find.findUsages.FindUsagesOptions import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.impl.light.LightMemberReference import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.usageView.UsageInfo import com.intellij.util.Query import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.toLightElements import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.psi.KtConstructor import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtPsiUtil import org.jetbrains.kotlin.utils.SmartList import org.jetbrains.kotlin.utils.addIfNotNull fun KtDeclaration.processAllExactUsages( options: FindUsagesOptions, processor: (UsageInfo) -> Unit ) { fun elementsToCheckReferenceAgainst(reference: PsiReference): List<PsiElement> { if (reference is KtReference) return listOf(this) return SmartList<PsiElement>().also { list -> list += this list += toLightElements() if (this is KtConstructor<*>) { list.addIfNotNull(getContainingClassOrObject().toLightClass()) } } } FindUsagesManager(project).getFindUsagesHandler(this, true)?.processElementUsages( this, { usageInfo -> val reference = usageInfo.reference ?: return@processElementUsages true if (reference is LightMemberReference || elementsToCheckReferenceAgainst(reference).any { reference.isReferenceTo(it) }) { processor(usageInfo) } true }, options ) } fun KtDeclaration.processAllUsages( options: FindUsagesOptions, processor: (UsageInfo) -> Unit ) { val findUsagesHandler = KotlinFindUsagesHandlerFactory(project).createFindUsagesHandler(this, true) findUsagesHandler.processElementUsages( this, { processor(it) true }, options ) } object ReferencesSearchScopeHelper { fun search(declaration: KtDeclaration, defaultScope: SearchScope? = null): Query<PsiReference> { val enclosingElement = KtPsiUtil.getEnclosingElementForLocalDeclaration(declaration) return when { enclosingElement != null -> ReferencesSearch.search(declaration, LocalSearchScope(enclosingElement)) defaultScope != null -> ReferencesSearch.search(declaration, defaultScope) else -> ReferencesSearch.search(declaration) } } }
apache-2.0
e95b5c7246090603b75373e5b25d3472
37.171053
158
0.724138
5.034722
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/ModificationNotifier.kt
9
2473
// 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.ide.bookmark import com.intellij.ide.bookmark.ui.BookmarksView import com.intellij.openapi.application.invokeLater import com.intellij.openapi.project.Project import com.intellij.openapi.wm.ToolWindowId.BOOKMARKS import com.intellij.openapi.wm.ToolWindowManager import java.util.concurrent.atomic.AtomicLong internal class ModificationNotifier(private val project: Project) : BookmarksListener { private val modification = AtomicLong() val count get() = modification.get() private val publisher get() = when { !project.isOpen || project.isDisposed -> null else -> project.messageBus.syncPublisher(BookmarksListener.TOPIC) } internal fun selectLater(select: (BookmarksView) -> Unit) = invokeLater { val window = if (project.isDisposed) null else ToolWindowManager.getInstance(project).getToolWindow(BOOKMARKS) val view = window?.contentManagerIfCreated?.selectedContent?.component as? BookmarksView view?.let { if (it.isShowing) select(it) } } internal var snapshot: List<BookmarkOccurrence>? = null private fun notifyLater(notify: (BookmarksListener) -> Unit) { snapshot = null // cleanup cached snapshot modification.incrementAndGet() invokeLater { publisher?.let(notify) } } override fun groupsSorted() = notifyLater { it.groupsSorted() } override fun groupAdded(group: BookmarkGroup) = notifyLater { it.groupAdded(group) } override fun groupRemoved(group: BookmarkGroup) = notifyLater { it.groupRemoved(group) } override fun groupRenamed(group: BookmarkGroup) = notifyLater { it.groupRenamed(group) } override fun bookmarksSorted(group: BookmarkGroup) = notifyLater { it.bookmarksSorted(group) } override fun bookmarkAdded(group: BookmarkGroup, bookmark: Bookmark) = notifyLater { it.bookmarkAdded(group, bookmark) } override fun bookmarkRemoved(group: BookmarkGroup, bookmark: Bookmark) = notifyLater { it.bookmarkRemoved(group, bookmark) } override fun bookmarkChanged(group: BookmarkGroup, bookmark: Bookmark) = notifyLater { it.bookmarkChanged(group, bookmark) } override fun bookmarkTypeChanged(bookmark: Bookmark) = notifyLater { it.bookmarkTypeChanged(bookmark) } override fun defaultGroupChanged(old: BookmarkGroup?, new: BookmarkGroup?) = notifyLater { it.defaultGroupChanged(old, new) } }
apache-2.0
0467d036a84a42b719508ba0a4e4b79c
52.76087
158
0.772341
4.4082
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/emoji/EmojiSource.kt
2
5819
package org.thoughtcrime.securesms.emoji import android.net.Uri import androidx.annotation.WorkerThread import org.thoughtcrime.securesms.components.emoji.Emoji import org.thoughtcrime.securesms.components.emoji.EmojiPageModel import org.thoughtcrime.securesms.components.emoji.StaticEmojiPageModel import org.thoughtcrime.securesms.components.emoji.parsing.EmojiDrawInfo import org.thoughtcrime.securesms.components.emoji.parsing.EmojiTree import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.util.ScreenDensity import java.io.InputStream import java.util.concurrent.CountDownLatch import java.util.concurrent.atomic.AtomicReference /** * The entry point for the application to request Emoji data for custom emojis. */ class EmojiSource( val decodeScale: Float, private val emojiData: EmojiData, private val emojiPageFactory: EmojiPageFactory ) : EmojiData by emojiData { val variationsToCanonical: Map<String, String> by lazy { val map = mutableMapOf<String, String>() for (page: EmojiPageModel in dataPages) { for (emoji: Emoji in page.displayEmoji) { for (variation: String in emoji.variations) { map[variation] = emoji.value } } } map } val canonicalToVariations: Map<String, List<String>> by lazy { val map = mutableMapOf<String, List<String>>() for (page: EmojiPageModel in dataPages) { for (emoji: Emoji in page.displayEmoji) { map[emoji.value] = emoji.variations } } map } val maxEmojiLength: Int by lazy { dataPages.map { it.emoji.map(String::length) } .flatten() .maxOrZero() } val emojiTree: EmojiTree by lazy { val tree = EmojiTree() dataPages .filter { it.spriteUri != null } .forEach { page -> val emojiPage = emojiPageFactory(page.spriteUri!!) var overallIndex = 0 page.displayEmoji.forEach { emoji: Emoji -> emoji.variations.forEachIndexed { variationIndex, variation -> val raw = emoji.getRawVariation(variationIndex) tree.add(variation, EmojiDrawInfo(emojiPage, overallIndex++, variation, raw, jumboPages[raw])) } } } obsolete.forEach { tree.add(it.obsolete, tree.getEmoji(it.replaceWith, 0, it.replaceWith.length)) } tree } companion object { private val emojiSource = AtomicReference<EmojiSource>() private val emojiLatch = CountDownLatch(1) @JvmStatic val latest: EmojiSource get() { emojiLatch.await() return emojiSource.get() } @JvmStatic @WorkerThread fun refresh() { emojiSource.set(getEmojiSource()) emojiLatch.countDown() } private fun getEmojiSource(): EmojiSource { return loadRemoteBasedEmojis() ?: loadAssetBasedEmojis() } private fun loadRemoteBasedEmojis(): EmojiSource? { if (SignalStore.internalValues().forceBuiltInEmoji()) { return null } val context = ApplicationDependencies.getApplication() val version = EmojiFiles.Version.readVersion(context) ?: return null val emojiData = EmojiFiles.getLatestEmojiData(context, version)?.let { it.copy( displayPages = it.displayPages + PAGE_EMOTICONS, dataPages = it.dataPages + PAGE_EMOTICONS ) } val density = ScreenDensity.xhdpiRelativeDensityScaleFactor(version.density) return emojiData?.let { EmojiSource(density, it) { uri: Uri -> EmojiPage.Disk(uri) } } } private fun loadAssetBasedEmojis(): EmojiSource { val emojiData: InputStream = ApplicationDependencies.getApplication().assets.open("emoji/emoji_data.json") emojiData.use { val parsedData: ParsedEmojiData = EmojiJsonParser.parse(it, ::getAssetsUri).getOrThrow() return EmojiSource( ScreenDensity.xhdpiRelativeDensityScaleFactor("xhdpi"), parsedData.copy( displayPages = parsedData.displayPages + PAGE_EMOTICONS, dataPages = parsedData.dataPages + PAGE_EMOTICONS ) ) { uri: Uri -> EmojiPage.Asset(uri) } } } } } private fun List<Int>.maxOrZero(): Int = maxOrNull() ?: 0 interface EmojiData { val metrics: EmojiMetrics val densities: List<String> val format: String val displayPages: List<EmojiPageModel> val dataPages: List<EmojiPageModel> val jumboPages: Map<String, String> val obsolete: List<ObsoleteEmoji> } data class ObsoleteEmoji(val obsolete: String, val replaceWith: String) data class EmojiMetrics(val rawHeight: Int, val rawWidth: Int, val perRow: Int) private fun getAssetsUri(name: String, format: String): Uri = Uri.parse("file:///android_asset/emoji/$name.$format") private val PAGE_EMOTICONS: EmojiPageModel = StaticEmojiPageModel( EmojiCategory.EMOTICONS, arrayOf( ":-)", ";-)", "(-:", ":->", ":-D", "\\o/", ":-P", "B-)", ":-$", ":-*", "O:-)", "=-O", "O_O", "O_o", "o_O", ":O", ":-!", ":-x", ":-|", ":-\\", ":-(", ":'(", ":-[", ">:-(", "^.^", "^_^", "\\(\u02c6\u02da\u02c6)/", "\u30fd(\u00b0\u25c7\u00b0 )\u30ce", "\u00af\\(\u00b0_o)/\u00af", "\u00af\\_(\u30c4)_/\u00af", "(\u00ac_\u00ac)", "(>_<)", "(\u2565\ufe4f\u2565)", "(\u261e\uff9f\u30ee\uff9f)\u261e", "\u261c(\uff9f\u30ee\uff9f\u261c)", "\u261c(\u2312\u25bd\u2312)\u261e", "(\u256f\u00b0\u25a1\u00b0)\u256f\ufe35", "\u253b\u2501\u253b", "\u252c\u2500\u252c", "\u30ce(\u00b0\u2013\u00b0\u30ce)", "(^._.^)\uff89", "\u0e05^\u2022\ufecc\u2022^\u0e05", "\u0295\u2022\u1d25\u2022\u0294", "(\u2022_\u2022)", " \u25a0-\u25a0\u00ac <(\u2022_\u2022) ", "(\u25a0_\u25a0\u00ac)", "\u01aa(\u0693\u05f2)\u200e\u01aa\u200b\u200b" ), null )
gpl-3.0
2ea63c68c1e3d730cefd3964f1f970a7
31.327778
116
0.661626
3.524531
false
false
false
false
guacamoledragon/twitch-chat
src/main/kotlin/club/guacamoledragon/plugin/kapchat/Client.kt
1
2443
package club.guacamoledragon.plugin.kapchat import io.socket.client.IO import io.socket.client.Socket import org.json.JSONObject import org.slf4j.LoggerFactory const val SOCKET_URL: String = "https://tmi-relay.nightdev.com/" class Client(val channel: String) { val logger = LoggerFactory.getLogger(this.javaClass) val socket: Socket = IO.socket(SOCKET_URL) private var onConnect: () -> Unit = {} private var onJoin: () -> Unit = {} private var onMessage: (Message) -> Unit = { msg -> } set(handler) { socket.off(Socket.EVENT_MESSAGE) socket.on(Socket.EVENT_MESSAGE, { args -> val data = args[0] if (data is JSONObject) { // TODO: Should I filter out bot messages? handler(Message.parse(data)) } }) } private var onClearChat: () -> Unit = {} set(handler) { socket.off("clearchat") socket.on("clearchat", { logger.info("Chat cleared.") handler() }) } private var onDisconnect: () -> Unit = {} init { logger.trace("Socket server: $SOCKET_URL") socket.once("ohai", { onConnect() socket.emit("join", channel) }) socket.on("much connect", { logger.info("Waiting to join channel...") socket.once("joined", { logger.info("Joined channel: $channel.") onJoin() }) }) socket.on(Socket.EVENT_DISCONNECT, { logger.info("You were disconnected from the socket server.") onDisconnect() }) } fun onConnect(handler: () -> Unit): Client { this.onConnect = handler return this } fun onJoin(handler: () -> Unit): Client { this.onJoin = handler return this } fun onMessage(handler: (Message) -> Unit): Client { this.onMessage = handler return this } fun onClearChat(handler: () -> Unit): Client { this.onClearChat = handler return this } fun onDisconnect(handler: () -> Unit): Client { this.onDisconnect = handler return this } fun connect(): Client { socket.connect() return this } fun disconnect(): Client { socket.disconnect() return this } }
apache-2.0
643f2ad76f21c2ec4026e1c6bd57d8d8
23.938776
72
0.531314
4.441818
false
false
false
false
jk1/intellij-community
platform/projectModel-api/src/com/intellij/util/jdom.kt
1
4521
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.reference.SoftReference import com.intellij.util.io.inputStream import com.intellij.util.io.outputStream import com.intellij.util.text.CharSequenceReader import org.jdom.Document import org.jdom.Element import org.jdom.JDOMException import org.jdom.Parent import org.jdom.filter.ElementFilter import org.jdom.input.SAXBuilder import org.jdom.input.sax.SAXHandler import org.xml.sax.EntityResolver import org.xml.sax.InputSource import org.xml.sax.XMLReader import java.io.* import java.nio.file.Path import javax.xml.XMLConstants private val cachedSaxBuilder = ThreadLocal<SoftReference<SAXBuilder>>() private fun getSaxBuilder(): SAXBuilder { val reference = cachedSaxBuilder.get() var saxBuilder = SoftReference.dereference<SAXBuilder>(reference) if (saxBuilder == null) { saxBuilder = object : SAXBuilder() { override fun configureParser(parser: XMLReader, contentHandler: SAXHandler?) { super.configureParser(parser, contentHandler) try { parser.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) } catch (ignore: Exception) { } } } saxBuilder.ignoringBoundaryWhitespace = true saxBuilder.ignoringElementContentWhitespace = true saxBuilder.entityResolver = EntityResolver { _, _ -> InputSource(CharArrayReader(ArrayUtil.EMPTY_CHAR_ARRAY)) } cachedSaxBuilder.set(SoftReference(saxBuilder)) } return saxBuilder } @JvmOverloads @Throws(IOException::class) fun Parent.write(file: Path, lineSeparator: String = "\n", filter: JDOMUtil.ElementOutputFilter? = null) { write(file.outputStream(), lineSeparator, filter) } @JvmOverloads fun Parent.write(output: OutputStream, lineSeparator: String = "\n", filter: JDOMUtil.ElementOutputFilter? = null) { output.bufferedWriter().use { writer -> if (this is Document) { JDOMUtil.writeDocument(this, writer, lineSeparator) } else { JDOMUtil.writeElement(this as Element, writer, JDOMUtil.createOutputter(lineSeparator, filter)) } } } @Throws(IOException::class, JDOMException::class) fun loadElement(chars: CharSequence): Element = loadElement(CharSequenceReader(chars)) @Throws(IOException::class, JDOMException::class) fun loadElement(reader: Reader): Element = loadDocument(reader).detachRootElement() @Throws(IOException::class, JDOMException::class) fun loadElement(stream: InputStream): Element = loadDocument(stream.reader()).detachRootElement() @Throws(IOException::class, JDOMException::class) fun loadElement(path: Path): Element = loadDocument(path.inputStream().bufferedReader()).detachRootElement() fun loadDocument(reader: Reader): Document = reader.use { getSaxBuilder().build(it) } fun Element?.isEmpty(): Boolean = this == null || JDOMUtil.isEmpty(this) fun Element.getOrCreate(name: String): Element { var element = getChild(name) if (element == null) { element = Element(name) addContent(element) } return element } fun Element.get(name: String): Element? = getChild(name) fun Element.element(name: String): Element { val element = Element(name) addContent(element) return element } fun Element.attribute(name: String, value: String?): Element = setAttribute(name, value) fun <T> Element.remove(name: String, transform: (child: Element) -> T): List<T> { val result = SmartList<T>() val groupIterator = getContent(ElementFilter(name)).iterator() while (groupIterator.hasNext()) { val child = groupIterator.next() result.add(transform(child)) groupIterator.remove() } return result } fun Element.toByteArray(): ByteArray { val out = BufferExposingByteArrayOutputStream(512) JDOMUtil.write(this, out, "\n") return out.toByteArray() } fun Element.addOptionTag(name: String, value: String) { val element = Element("option") element.setAttribute("name", name) element.setAttribute("value", value) addContent(element) } fun Parent.toBufferExposingByteArray(lineSeparator: String = "\n"): BufferExposingByteArrayOutputStream { val out = BufferExposingByteArrayOutputStream(512) JDOMUtil.write(this, out, lineSeparator) return out } fun Element.getAttributeBooleanValue(name: String): Boolean = java.lang.Boolean.parseBoolean(getAttributeValue(name))
apache-2.0
f5dbe6ea211a87c537994be1f3690d73
33.519084
140
0.755143
4.233146
false
false
false
false
charroch/Kevice
src/main/kotlin/vertx/DeviceVerticle.kt
1
5794
package vertx import java.io.File import future.Success import future.Failure import org.vertx.java.core.json.JsonArray import org.vertx.java.core.json.JsonObject import json.JSON import com.android.ddmlib.IShellOutputReceiver import org.vertx.java.core.http.HttpServerResponse import java.util.concurrent.TimeUnit import com.fasterxml.jackson.databind.node.TextNode import org.vertx.java.platform.Container import kotlin.properties.Delegates import org.vertx.java.core.Vertx import org.vertx.java.core.logging.Logger import org.vertx.java.core.streams.Pump import com.android.ddmlib.log.LogReceiver import adb.LogStream public class DeviceVerticle : RESTx(), WithDevice { { get("/") { request -> request?.response()?.sendFile("web/devices.html"); } get("/devices") { request -> val json = devices().fold(JsonArray()) {(j, device) -> j.addObject(device.asJsonObject()) j } l.info("will fetch from MongoDB") val s = """ { "action": "find", "collection": "devices", "matcher": { "state": "OFFLINE" } } """ v.eventBus()?.sendWithTimeout<JsonObject>("mongodb", JsonObject(s), 5000) { if (it?.succeeded()!!) { val devicesFromMongo: JsonObject = it!!.result()!!.body() as JsonObject val devices: JsonArray = devicesFromMongo.getArray("results")!! json.forEach { d -> val j = d as JsonObject; if (!j.getString("serial")?.contains("?")!!) { devices.addObject(d as JsonObject) } } request!!.response()?.headers()?.set("Content-Type", "application/json"); request.response()?.headers()?.set("Access-Control-Allow-Origin", "*"); request.response()?.end(devices.toString()); } else { l.info("No reply was received before the 5 second timeout!") } } } put("/device/:serial") {(request, device) -> request.save(File("/tmp/" + device.getSerialNumber() + ".apk")) { when(it) { is Success<*> -> { val install = device.install(it.r as File) install.onSuccess { l.info("Installed Apk correctly") } install.onFailure { l.error("failed to install", it) } }; is Failure -> println("failure") } } println("Look ma I am asynchronous") } get("/device/:serial/apilevel") {(request, device) -> json.json { obj { "sdk" to (device.getProperty("ro.build.version.sdk") ?: 0) as String } } } delete("/device/:serial/packages/:package") {(request, device, pkg) -> val log = device.uninstallPackage(pkg) if (log == null) request.response()?.setStatusCode(200)?.end() else request.response()?.setStatusCode(500)?.setStatusMessage(log)?.end() } post("/device/:serial/shell") {(request, device) -> request.response()?.headers()?.set("Access-Control-Allow-Origin", "*"); request.bodyHandler { val cmd = JSON.JSON.mapper.readTree(it.toString())?.get("command") as TextNode device.executeShellCommand(cmd.textValue(), ServerSentEventOutput(request.response()!!), 10, TimeUnit.SECONDS) //device.runEventLogService(LogReceiver(LogStream())) } } } val c: Container by Delegates.lazy { getContainer()!! } val v: Vertx by Delegates.lazy { getVertx()!! } val l: Logger by Delegates.lazy { c.logger()!! } class ServerSentEventOutput(val response: HttpServerResponse) : IShellOutputReceiver { { response.setChunked(true) response.headers()?.set("Content-Type", "text/event-stream") response.headers()?.set("Access-Control-Allow-Origin", "*"); } override fun addOutput(data: ByteArray?, offset: Int, length: Int) { if (!isCancelled() && data != null) { val s = String(data, offset, length, "UTF-8") response.write("data:" + s) } } override fun flush() { response.end(); } override fun isCancelled(): Boolean { return false } } override fun start() { routes.noMatch { it?.response()?.sendFile("web/" + java.io.File(it?.path().toString())); } val httpServer = vertx?.createHttpServer()?.requestHandler(routes); val sockJSServer = vertx!!.createSockJSServer(httpServer); val config = json.json { obj { "prefix" to "/echo" } }.let { JsonObject(it.toString()) } sockJSServer!!.installApp(config) { sock -> //devices().first.executeShellCommand() sock!!.dataHandler { b-> l.info("Received: "+b.toString()) } //Pump.createPump(sock, sock)!!.start(); } devices().forEach { d -> val stream = LogStream(d) val l = LogReceiver(stream) Thread(Runnable() { // d.runEventLogService(l) }).start() } httpServer?.listen(8081, "localhost") } }
apache-2.0
0f7a9e013789bb55be081ef5133e5c09
33.909639
126
0.514843
4.768724
false
false
false
false
ktorio/ktor
ktor-client/ktor-client-plugins/ktor-client-resources/common/src/io/ktor/client/plugins/resources/builders.kt
1
8051
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.plugins.resources import io.ktor.client.* import io.ktor.client.plugins.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.resources.* import io.ktor.client.request.delete as deleteBuilder import io.ktor.client.request.get as getBuilder import io.ktor.client.request.head as headBuilder import io.ktor.client.request.options as optionsBuilder import io.ktor.client.request.patch as patchBuilder import io.ktor.client.request.post as postBuilder import io.ktor.client.request.prepareDelete as prepareDeleteBuilder import io.ktor.client.request.prepareGet as prepareGetBuilder import io.ktor.client.request.prepareHead as prepareHeadBuilder import io.ktor.client.request.prepareOptions as prepareOptionsBuilder import io.ktor.client.request.preparePatch as preparePatchBuilder import io.ktor.client.request.preparePost as preparePostBuilder import io.ktor.client.request.preparePut as preparePutBuilder import io.ktor.client.request.prepareRequest as prepareRequestBuilder import io.ktor.client.request.put as putBuilder import io.ktor.client.request.request as requestBuilder /** * Executes a [HttpClient] GET request, with a URL built from [resource] and the information from the [builder] */ public suspend inline fun <reified T : Any> HttpClient.get( resource: T, builder: HttpRequestBuilder.() -> Unit = {} ): HttpResponse { val resources = resources() return getBuilder { href(resources.resourcesFormat, resource, url) builder() } } /** * Executes a [HttpClient] POST request, with a URL built from [resource] and the information from the [builder] */ public suspend inline fun <reified T : Any> HttpClient.post( resource: T, builder: HttpRequestBuilder.() -> Unit = {} ): HttpResponse { val resources = resources() return postBuilder { href(resources.resourcesFormat, resource, url) builder() } } /** * Executes a [HttpClient] PUT request, with a URL built from [resource] and the information from the [builder] */ public suspend inline fun <reified T : Any> HttpClient.put( resource: T, builder: HttpRequestBuilder.() -> Unit = {} ): HttpResponse { val resources = resources() return putBuilder { href(resources.resourcesFormat, resource, url) builder() } } /** * Executes a [HttpClient] DELETE request, with a URL built from [resource] and the information from the [builder] */ public suspend inline fun <reified T : Any> HttpClient.delete( resource: T, builder: HttpRequestBuilder.() -> Unit = {} ): HttpResponse { val resources = resources() return deleteBuilder { href(resources.resourcesFormat, resource, url) builder() } } /** * Executes a [HttpClient] PATCH request, with a URL built from [resource] and the information from the [builder] */ public suspend inline fun <reified T : Any> HttpClient.patch( resource: T, builder: HttpRequestBuilder.() -> Unit = {} ): HttpResponse { val resources = resources() return patchBuilder { href(resources.resourcesFormat, resource, url) builder() } } /** * Executes a [HttpClient] OPTIONS request, with a URL built from [resource] and the information from the [builder] */ public suspend inline fun <reified T : Any> HttpClient.options( resource: T, builder: HttpRequestBuilder.() -> Unit = {} ): HttpResponse { val resources = resources() return optionsBuilder { href(resources.resourcesFormat, resource, url) builder() } } /** * Executes a [HttpClient] HEAD request, with a URL built from [resource] and the information from the [builder] */ public suspend inline fun <reified T : Any> HttpClient.head( resource: T, builder: HttpRequestBuilder.() -> Unit = {} ): HttpResponse { val resources = resources() return headBuilder { href(resources.resourcesFormat, resource, url) builder() } } /** * Executes a [HttpClient] request, with a URL built from [resource] and the information from the [builder] */ public suspend inline fun <reified T : Any> HttpClient.request( resource: T, builder: HttpRequestBuilder.() -> Unit ): HttpResponse { val resources = resources() return requestBuilder { href(resources.resourcesFormat, resource, url) builder() } } /** * Prepares a [HttpClient] GET request, with a URL built from [resource] and the information from the [builder] */ public suspend inline fun <reified T : Any> HttpClient.prepareGet( resource: T, builder: HttpRequestBuilder.() -> Unit = {} ): HttpStatement { val resources = resources() return prepareGetBuilder { href(resources.resourcesFormat, resource, url) builder() } } /** * Prepares a [HttpClient] POST request, with a URL built from [resource] and the information from the [builder] */ public suspend inline fun <reified T : Any> HttpClient.preparePost( resource: T, builder: HttpRequestBuilder.() -> Unit = {} ): HttpStatement { val resources = resources() return preparePostBuilder { href(resources.resourcesFormat, resource, url) builder() } } /** * Prepares a [HttpClient] PUT request, with a URL built from [resource] and the information from the [builder] */ public suspend inline fun <reified T : Any> HttpClient.preparePut( resource: T, builder: HttpRequestBuilder.() -> Unit = {} ): HttpStatement { val resources = resources() return preparePutBuilder { href(resources.resourcesFormat, resource, url) builder() } } /** * Prepares a [HttpClient] DELETE request, with a URL built from [resource] and the information from the [builder] */ public suspend inline fun <reified T : Any> HttpClient.prepareDelete( resource: T, builder: HttpRequestBuilder.() -> Unit = {} ): HttpStatement { val resources = resources() return prepareDeleteBuilder { href(resources.resourcesFormat, resource, url) builder() } } /** * Prepares a [HttpClient] PATCH request, with a URL built from [resource] and the information from the [builder] */ public suspend inline fun <reified T : Any> HttpClient.preparePatch( resource: T, builder: HttpRequestBuilder.() -> Unit = {} ): HttpStatement { val resources = resources() return preparePatchBuilder { href(resources.resourcesFormat, resource, url) builder() } } /** * Prepares a [HttpClient] OPTIONS request, with a URL built from [resource] and the information from the [builder] */ public suspend inline fun <reified T : Any> HttpClient.prepareOptions( resource: T, builder: HttpRequestBuilder.() -> Unit = {} ): HttpStatement { val resources = resources() return prepareOptionsBuilder { href(resources.resourcesFormat, resource, url) builder() } } /** * Prepares a [HttpClient] HEAD request, with a URL built from [resource] and the information from the [builder] */ public suspend inline fun <reified T : Any> HttpClient.prepareHead( resource: T, builder: HttpRequestBuilder.() -> Unit = {} ): HttpStatement { val resources = resources() return prepareHeadBuilder { href(resources.resourcesFormat, resource, url) builder() } } /** * Prepares a [HttpClient] request, with a URL built from [resource] and the information from the [builder] */ public suspend inline fun <reified T : Any> HttpClient.prepareRequest( resource: T, builder: HttpRequestBuilder.() -> Unit = {} ): HttpStatement { val resources = resources() return prepareRequestBuilder { href(resources.resourcesFormat, resource, url) builder() } } @PublishedApi internal fun HttpClient.resources(): io.ktor.resources.Resources { return pluginOrNull(Resources) ?: throw IllegalStateException("Resources plugin is not installed") }
apache-2.0
4327ec42048779018c56b19a127720ce
30.449219
119
0.698547
4.271088
false
false
false
false
fabioCollini/ArchitectureComponentsDemo
viewlib/src/main/java/it/codingjam/github/util/ViewStateStore.kt
1
2090
package it.codingjam.github.util import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import kotlinx.coroutines.* import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flowOn class ViewStateStoreFactory( private val dispatcher: CoroutineDispatcher ) { operator fun <T : Any> invoke(initialState: T, scope: CoroutineScope) = ViewStateStore(initialState, scope, dispatcher) } class ViewStateStore<T : Any>( initialState: T, private val scope: CoroutineScope, private val dispatcher: CoroutineDispatcher ) { private val stateLiveData = MutableLiveData<T>().apply { value = initialState } private val signalsLiveData = EventsLiveData<Signal>() fun observe(owner: LifecycleOwner, observer: (T) -> Unit) = stateLiveData.observe(owner, Observer { observer(it!!) }) fun observeSignals(owner: LifecycleOwner, observer: (Signal) -> Unit) = signalsLiveData.observe(owner) { observer(it) } fun dispatchState(state: T) { scope.launch(Dispatchers.Main.immediate) { stateLiveData.value = state } } fun dispatchSignal(action: Signal) { signalsLiveData.addEvent(action) } private fun dispatch(action: Action<T>) { if (action is StateAction<T>) { stateLiveData.value = action(invoke()) } else if (action is Signal) { signalsLiveData.addEvent(action) } } fun dispatchAction(f: suspend () -> Action<T>) { // dispatchActions(flow { emit(f()) }) scope.launch { val action = withContext(dispatcher) { f() } dispatch(action) } } fun dispatchActions(flow: ActionsFlow<T>) { scope.launch { flow .flowOn(dispatcher) .collect { action -> dispatch(action) } } } operator fun invoke() = stateLiveData.value!! }
apache-2.0
626edf6097f3f2d02c32109123d8bb39
26.88
75
0.611483
4.696629
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/EXT_shader_framebuffer_fetch.kt
4
4162
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengles.templates import org.lwjgl.generator.* import opengles.* val EXT_shader_framebuffer_fetch = "EXTShaderFramebufferFetch".nativeClassGLES("EXT_shader_framebuffer_fetch", postfix = EXT) { documentation = """ Native bindings to the $registryLink extension. Conventional OpenGL blending provides a configurable series of operations that can be used to combine the output values from a fragment shader with the values already in the framebuffer. While these operations are suitable for basic image compositing, other compositing operations or operations that treat fragment output as something other than a color (normals, for instance) may not be expressible without multiple passes or render-to-texture operations. This extension provides a mechanism whereby a fragment shader may read existing framebuffer data as input. This can be used to implement compositing operations that would have been inconvenient or impossible with fixed-function blending. It can also be used to apply a function to the framebuffer color, by writing a shader which uses the existing framebuffer color as its only input. This extension provides two alternative name strings: ${ul( """ {@code GL_EXT_shader_framebuffer_fetch} guarantees full coherency between framebuffer reads and writes. If this extension string is exposed, the result of reading from the framebuffer from a fragment shader invocation is guaranteed to reflect values written by any previous overlapping samples in API primitive order, unless requested otherwise in the shader source using the noncoherent layout qualifier. """, """ {@code GL_EXT_shader_framebuffer_fetch_non_coherent} provides limited implicit coherency guarantees. Instead, the application is expected to call the #FramebufferFetchBarrierEXT() command for previous framebuffer writes to become visible to subsequent fragment shader invocations. For this extension to give well-defined results applications may have to split rendering into multiple passes separated with {@code FramebufferFetchBarrierEXT} calls. The functionality provided by this extension is requested in the shader source using the noncoherent layout qualifier. """ )} Requires ${GLES20.core}. """ IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.", "FRAGMENT_SHADER_DISCARDS_SAMPLES_EXT"..0x8A52 ) } val EXT_shader_framebuffer_fetch_non_coherent = "EXTShaderFramebufferFetchNonCoherent".nativeClassGLES("EXT_shader_framebuffer_fetch_non_coherent", postfix = EXT) { documentation = """ Native bindings to the $registryLink extension. See ${EXT_shader_framebuffer_fetch.link}. """ void( "FramebufferFetchBarrierEXT", """ Specifies a boundary between passes when reading existing framebuffer data from fragment shaders via the {@code gl_LastFragData} built-in variable. Previous framebuffer object writes regardless of the mechanism (including clears, blits and primitive rendering) are guaranteed to be visible to subsequent fragment shader invocations that read from the framebuffer once {@code FramebufferFetchBarrierEXT} is executed. If {@code EXT_shader_framebuffer_fetch} is also supported: Because the implementation guarantees coherency of framebuffer reads and writes for color outputs not explicitly marked with the noncoherent layout qualifier, calling the {@code FramebufferFetchBarrierEXT} command is not required unless the application wishes to manage memory ordering of framebuffer reads and writes explicitly, which may provide better performance on some implementations in cases where rendering can be split into multiple passes with non-self-overlapping geometry. """ ) }
bsd-3-clause
a6d707691fea748cddee520bb3a7d8f3
56.819444
164
0.734743
5.398184
false
false
false
false
bozaro/git-lfs-java
gitlfs-server/src/test/kotlin/ru/bozaro/gitlfs/server/MemoryStorage.kt
1
3727
package ru.bozaro.gitlfs.server import com.google.common.collect.ImmutableMap import com.google.common.hash.Hashing import com.google.common.io.ByteStreams import jakarta.servlet.http.HttpServletRequest import org.testng.Assert import ru.bozaro.gitlfs.client.Client.Companion.generateMeta import ru.bozaro.gitlfs.client.auth.AuthProvider import ru.bozaro.gitlfs.client.auth.CachedAuthProvider import ru.bozaro.gitlfs.client.io.StreamProvider import ru.bozaro.gitlfs.common.Constants import ru.bozaro.gitlfs.common.data.Link import ru.bozaro.gitlfs.common.data.Meta import ru.bozaro.gitlfs.common.data.Operation import ru.bozaro.gitlfs.server.ContentManager.Downloader import ru.bozaro.gitlfs.server.ContentManager.Uploader import java.io.ByteArrayInputStream import java.io.FileNotFoundException import java.io.IOException import java.io.InputStream import java.net.URI import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicInteger /** * Simple in-memory storage. * * @author Artem V. Navrotskiy */ class MemoryStorage(private val tokenMaxUsage: Int) : ContentManager { private val storage: MutableMap<String?, ByteArray> = ConcurrentHashMap() private val tokenId = AtomicInteger(0) @Throws(UnauthorizedError::class) override fun checkDownloadAccess(request: HttpServletRequest): Downloader { if (token != request.getHeader(Constants.HEADER_AUTHORIZATION)) { throw UnauthorizedError("Basic realm=\"Test\"") } return object : Downloader { @Throws(IOException::class) override fun openObject(hash: String): InputStream { val data = storage[hash] ?: throw FileNotFoundException() return ByteArrayInputStream(data) } override fun openObjectGzipped(hash: String): InputStream? { return null } } } private val token: String get() = if (tokenMaxUsage > 0) { val token = tokenId.incrementAndGet() "Bearer Token-" + token / tokenMaxUsage } else { "Bearer Token-" + tokenId.get() } @Throws(UnauthorizedError::class) override fun checkUploadAccess(request: HttpServletRequest): Uploader { if (token != request.getHeader(Constants.HEADER_AUTHORIZATION)) { throw UnauthorizedError("Basic realm=\"Test\"") } val storage = this return object : Uploader { override fun saveObject(meta: Meta, content: InputStream) { storage.saveObject(meta, content) } } } override fun getMetadata(hash: String): Meta? { val data = storage[hash] return if (data == null) null else Meta(hash, data.size.toLong()) } @Throws(IOException::class) fun saveObject(meta: Meta, content: InputStream) { val data = ByteStreams.toByteArray(content) if (meta.size >= 0) { Assert.assertEquals(meta.size, data.size.toLong()) } Assert.assertEquals(meta.oid, Hashing.sha256().hashBytes(data).toString()) storage[meta.oid] = data } @Throws(IOException::class) fun saveObject(provider: StreamProvider) { val meta = generateMeta(provider) provider.stream.use { stream -> saveObject(meta, stream) } } fun getObject(oid: String): ByteArray? { return storage[oid] } fun getAuthProvider(href: URI): AuthProvider { return object : CachedAuthProvider() { override fun getAuthUncached(operation: Operation): Link { return Link(href, ImmutableMap.of(Constants.HEADER_AUTHORIZATION, token), null) } } } }
lgpl-3.0
63e10fca09b7c23c0072870481c9a52d
34.160377
95
0.673196
4.490361
false
false
false
false
StPatrck/edac
app/src/main/java/com/phapps/elitedangerous/companion/ui/edc/EdcAuthenticateActivity.kt
1
3923
package com.phapps.elitedangerous.companion.ui.edc import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProvider import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import com.phapps.elitedangerous.companion.R import com.phapps.elitedangerous.companion.constants.Status import com.phapps.elitedangerous.companion.viewmodels.EdcAuthenticationViewModel import javax.inject.Inject class EdcAuthenticateActivity : AppCompatActivity() { private lateinit var mFieldEmail: TextView private lateinit var mFieldPassword: TextView private lateinit var mBtnAuthenticate: Button private lateinit var mFieldConfirmationCode: EditText private lateinit var mBtnConfirm: Button @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private val mViewModel: EdcAuthenticationViewModel by lazy { ViewModelProviders.of(this@EdcAuthenticateActivity) .get(EdcAuthenticationViewModel::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_edc_authenticate) mFieldEmail = findViewById(R.id.field_edc_email) mFieldPassword = findViewById(R.id.field_edc_password) mBtnAuthenticate = findViewById(R.id.btn_edc_authenticate) mBtnAuthenticate.setOnClickListener({ authenticate() }) mFieldConfirmationCode = findViewById(R.id.field_edc_confirmation_code) mBtnConfirm = findViewById(R.id.btn_edc_confirm) mBtnConfirm.setOnClickListener({ sendConfirmationCode() }) mBtnConfirm.isEnabled = true mFieldConfirmationCode.isEnabled = true mViewModel.loginResult.observe(this, Observer { newValue -> if (newValue?.status == Status.Success) { Toast.makeText(this@EdcAuthenticateActivity, "Check email for confirmation code and enter it below", Toast.LENGTH_LONG).show() mBtnConfirm.isEnabled = true mFieldConfirmationCode.isEnabled = true } else if (newValue?.status == Status.Error) { Toast.makeText(this@EdcAuthenticateActivity, "Login failed. Try again or report the problem.", Toast.LENGTH_LONG).show() } }) mViewModel.confirmationResult.observe(this, Observer { newValue -> if (newValue?.status == Status.Success) { Toast.makeText(this@EdcAuthenticateActivity, "Confirmation successful. E:D Companion Emulation active.", Toast.LENGTH_LONG).show() } else if (newValue?.status == Status.Error) { Toast.makeText(this@EdcAuthenticateActivity, "Confirmation failed. Try again or report the problem.", Toast.LENGTH_LONG).show() } }) } private fun authenticate() { if (mFieldEmail.text.isNullOrEmpty()) { mFieldEmail.error = getString(R.string.error_email_required) return } if (mFieldPassword.text.isNullOrEmpty()) { mFieldPassword.error = getString(R.string.error_password_required) return } mViewModel.setCredentials(mFieldEmail.text.toString(), mFieldPassword.text.toString()) } private fun sendConfirmationCode() { if (mFieldConfirmationCode.text.isNullOrEmpty()) { mFieldConfirmationCode.error = getString(R.string.error_edc_confirmation_code_required) return } mViewModel.setConfirmationCode(mFieldConfirmationCode.text.toString()) } }
gpl-3.0
71d1efe9f240f26008ab135db6ee86ee
39.443299
99
0.674484
4.873292
false
false
false
false
mdanielwork/intellij-community
plugins/github/src/org/jetbrains/plugins/github/util/GithubAccountsMigrationHelper.kt
1
5611
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.util import com.intellij.credentialStore.CredentialAttributes import com.intellij.ide.passwordSafe.PasswordSafe import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.ThrowableComputable import git4idea.DialogManager import org.jetbrains.annotations.CalledInAwt import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.GithubApiRequests import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.authentication.accounts.GithubAccountManager import org.jetbrains.plugins.github.authentication.ui.GithubLoginDialog import java.awt.Component import java.io.IOException internal const val GITHUB_SETTINGS_PASSWORD_KEY = "GITHUB_SETTINGS_PASSWORD_KEY" /** * Temporary helper * Will move single-account authorization data to accounts list if it was a token-based auth and clear old settings */ @Suppress("DEPRECATION") class GithubAccountsMigrationHelper internal constructor(private val settings: GithubSettings, private val passwordSafe: PasswordSafe, private val accountManager: GithubAccountManager, private val executorFactory: GithubApiRequestExecutor.Factory) { private val LOG = logger<GithubAccountsMigrationHelper>() internal fun getOldServer(): GithubServerPath? { try { if (hasOldAccount()) { return GithubServerPath.from(settings.host ?: GithubServerPath.DEFAULT_HOST) } } catch (ignore: Exception) { // it could be called from AnAction.update() } return null } private fun hasOldAccount(): Boolean { // either password-based with specified login or token based return ((settings.authType == GithubAuthData.AuthType.BASIC && settings.login != null) || (settings.authType == GithubAuthData.AuthType.TOKEN)) } /** * @return false if process was cancelled by user, true otherwise */ @CalledInAwt @JvmOverloads fun migrate(project: Project, parentComponent: Component? = null): Boolean { LOG.debug("Migrating old auth") val login = settings.login val host = settings.host val password = passwordSafe.getPassword(CredentialAttributes(GithubSettings::class.java, GITHUB_SETTINGS_PASSWORD_KEY)) val authType = settings.authType LOG.debug("Old auth data: { login: $login, host: $host, authType: $authType, password null: ${password == null} }") val hasAnyInfo = login != null || host != null || authType != null || password != null if (!hasAnyInfo) return true var dialogCancelled = false if (accountManager.accounts.isEmpty()) { val hostToUse = host ?: GithubServerPath.DEFAULT_HOST when (authType) { GithubAuthData.AuthType.TOKEN -> { LOG.debug("Migrating token auth") if (password != null) { try { val server = GithubServerPath.from(hostToUse) val progressManager = ProgressManager.getInstance() val accountName = progressManager.runProcessWithProgressSynchronously(ThrowableComputable<String, IOException> { executorFactory.create(password).execute(progressManager.progressIndicator, GithubApiRequests.CurrentUser.get(server)).login }, "Accessing Github", true, project) val account = GithubAccountManager.createAccount(accountName, server) registerAccount(account, password) } catch (e: Exception) { LOG.debug("Failed to migrate old token-based auth. Showing dialog.", e) val dialog = GithubLoginDialog(executorFactory, project, parentComponent) .withServer(hostToUse, false).withToken(password).withError(e) dialogCancelled = !registerFromDialog(dialog) } } } GithubAuthData.AuthType.BASIC -> { LOG.debug("Migrating basic auth") val dialog = GithubLoginDialog(executorFactory, project, parentComponent, message = "Password authentication is no longer supported for Github.\n" + "Personal access token can be acquired instead.") .withServer(hostToUse, false).withCredentials(login, password) dialogCancelled = !registerFromDialog(dialog) } else -> { } } } return !dialogCancelled } private fun registerFromDialog(dialog: GithubLoginDialog): Boolean { DialogManager.show(dialog) return if (dialog.isOK) { registerAccount(GithubAccountManager.createAccount(dialog.getLogin(), dialog.getServer()), dialog.getToken()) true } else false } private fun registerAccount(account: GithubAccount, token: String) { accountManager.accounts += account accountManager.updateAccountToken(account, token) LOG.debug("Registered account $account") } companion object { @JvmStatic fun getInstance(): GithubAccountsMigrationHelper = service() } }
apache-2.0
78ed84dd5900ae0c083c3aefb51d279a
42.496124
140
0.679914
5.100909
false
false
false
false
chrhsmt/Sishen
app/src/main/java/com/chrhsmt/sisheng/ui/Chart.kt
1
3815
package com.chrhsmt.sisheng.ui import android.app.Activity import android.graphics.Color import com.chrhsmt.sisheng.AudioService import com.chrhsmt.sisheng.MainActivity import com.github.mikephil.charting.charts.LineChart import com.github.mikephil.charting.components.Legend import com.github.mikephil.charting.components.YAxis import com.github.mikephil.charting.data.Entry import com.github.mikephil.charting.data.LineData import com.github.mikephil.charting.data.LineDataSet import com.github.mikephil.charting.utils.ColorTemplate /** * Created by chihiro on 2017/08/22. */ class Chart { private val AXIS_MAXIMUM = AudioService.MAX_FREQ_THRESHOLD // Maximum Hz private val AXIS_MINIMUM = 0f private var mChart: LineChart? = null fun initChartView(chart: LineChart) { this.mChart = chart // enable touch gestures this.mChart!!.setTouchEnabled(true); // enable scaling and dragging this.mChart!!.setDragEnabled(true); this.mChart!!.setScaleEnabled(true); this.mChart!!.setDrawGridBackground(false); // if disabled, scaling can be done on x- and y-axis separately this.mChart!!.setPinchZoom(true) // set an alternative background color this.mChart!!.setBackgroundColor(Color.LTGRAY) val data = LineData() data.setValueTextColor(Color.BLACK) // add empty data this.mChart!!.data = data // ラインの凡例の設定 val l = this.mChart!!.getLegend() l.form = Legend.LegendForm.LINE l.textColor = Color.BLACK val xl = this.mChart!!.getXAxis() xl.textColor = Color.BLACK //xl.setLabelsToSkip(9) val leftAxis = this.mChart!!.getAxisLeft() leftAxis.textColor = Color.BLACK leftAxis.axisMaximum = AXIS_MAXIMUM leftAxis.axisMinimum = AXIS_MINIMUM leftAxis.setDrawGridLines(true) val rightAxis = this.mChart!!.getAxisRight() rightAxis.isEnabled = false } fun addEntry(value: Float, name: String = "Default Data", color: Int = ColorTemplate.getHoloBlue()) { val data = this.mChart!!.data if (data != null) { var set = data.getDataSetByLabel(name, false) if (set == null) { set = this.createDefaultSet(name = name, color = color) data.addDataSet(set) } var checkedValue = value if (checkedValue > AXIS_MAXIMUM) { checkedValue = 0f; } data.addEntry(Entry(set.entryCount.toFloat(), checkedValue), data.getIndexOfDataSet(set)); data.notifyDataChanged() this.mChart!!.notifyDataSetChanged() this.mChart!!.setVisibleXRangeMaximum(120f) this.mChart!!.moveViewToX(set.entryCount.toFloat()) } } fun clear() { this.mChart!!.clearValues() this.mChart!!.notifyDataSetChanged() } /** * 特定のデータアセットをクリア. * @name データセット名 */ fun clearDateSet(name: String) { val set = this.mChart!!.data.getDataSetByLabel(name, false) set?.let { set.clear() } } private fun createDefaultSet(name: String = "Default Data", color: Int = ColorTemplate.getHoloBlue()): LineDataSet { val set = LineDataSet(null, name) set.axisDependency = YAxis.AxisDependency.LEFT set.color = color set.setCircleColor(color) set.lineWidth = 2f set.circleRadius = 4f set.fillAlpha = 65 set.fillColor = color set.highLightColor = Color.rgb(244, 117, 117) set.valueTextColor = Color.WHITE set.valueTextSize = 9f set.setDrawValues(false) return set } }
mit
965cce2817233c22d51f682c899f9b50
30.3
120
0.633822
4.094875
false
false
false
false
dahlstrom-g/intellij-community
plugins/git-features-trainer/src/git4idea/ift/lesson/GitQuickStartLesson.kt
1
13475
// 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 git4idea.ift.lesson import com.intellij.CommonBundle import com.intellij.dvcs.DvcsUtil import com.intellij.dvcs.ui.DvcsBundle import com.intellij.ide.actions.searcheverywhere.SearchEverywhereManagerImpl import com.intellij.ide.actions.searcheverywhere.SearchEverywhereUI import com.intellij.notification.NotificationType import com.intellij.openapi.editor.EditorModificationUtil import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.impl.EditorComponentImpl import com.intellij.openapi.project.Project import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.COMMIT_FINISHED import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vcs.ui.CommitMessage import com.intellij.openapi.wm.ToolWindowId import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.impl.status.TextPanel import com.intellij.ui.EngravedLabel import com.intellij.ui.components.JBOptionButton import com.intellij.ui.components.fields.ExtendableTextField import com.intellij.util.ui.UIUtil import com.intellij.util.ui.cloneDialog.VcsCloneDialogExtensionList import git4idea.i18n.GitBundle import git4idea.ift.GitLessonsBundle import git4idea.ift.GitLessonsUtil.gotItStep import git4idea.ift.GitLessonsUtil.openCommitWindowText import git4idea.ift.GitLessonsUtil.openPushDialogText import git4idea.ift.GitLessonsUtil.restoreByUiAndBackgroundTask import git4idea.ift.GitLessonsUtil.restoreCommitWindowStateInformer import git4idea.ift.GitLessonsUtil.showWarningIfCommitWindowClosed import git4idea.ift.GitLessonsUtil.showWarningIfModalCommitEnabled import git4idea.ift.GitLessonsUtil.showWarningIfStagingAreaEnabled import git4idea.ift.GitLessonsUtil.triggerOnCheckout import git4idea.ift.GitLessonsUtil.triggerOnNotification import git4idea.ift.GitProjectUtil import git4idea.repo.GitRepositoryManager import training.dsl.* import training.dsl.LessonUtil.adjustPopupPosition import training.dsl.LessonUtil.sampleRestoreNotification import training.ui.LearningUiHighlightingManager import training.util.LessonEndInfo import training.util.toNullableString import java.awt.Point import java.awt.Rectangle import java.awt.event.KeyEvent import javax.swing.JButton import javax.swing.JTree import javax.swing.tree.TreePath class GitQuickStartLesson : GitLesson("Git.QuickStart", GitLessonsBundle.message("git.quick.start.lesson.name")) { override val sampleFilePath = "git/puss_in_boots.yml" override val branchName = "main" private val fileToChange = sampleFilePath.substringAfterLast('/') private val textToHighlight = "green" private var backupSearchEverywhereLocation: Point? = null override val testScriptProperties = TaskTestContext.TestScriptProperties(duration = 40) override val lessonContent: LessonContext.() -> Unit = { val cloneActionText = GitBundle.message("action.Git.Clone.text") showWarningIfModalCommitEnabled() showWarningIfStagingAreaEnabled() task { text(GitLessonsBundle.message("git.quick.start.introduction")) proceedLink() } lateinit var findActionTaskId: TaskContext.TaskId task("SearchEverywhere") { findActionTaskId = taskId text(GitLessonsBundle.message("git.quick.start.find.action", strong(StringUtil.removeEllipsisSuffix(cloneActionText)), LessonUtil.rawKeyStroke(KeyEvent.VK_SHIFT), LessonUtil.actionName(it))) triggerAndBorderHighlight().component { ui: ExtendableTextField -> UIUtil.getParentOfType(SearchEverywhereUI::class.java, ui) != null } test { actions(it) } } task("Git.Clone") { before { if (backupSearchEverywhereLocation == null) { backupSearchEverywhereLocation = adjustPopupPosition(SearchEverywhereManagerImpl.LOCATION_SETTINGS_KEY) } } text(GitLessonsBundle.message("git.quick.start.type.clone", code(StringUtil.removeEllipsisSuffix(cloneActionText)))) triggerAndBorderHighlight().listItem { item -> item.toNullableString()?.contains(cloneActionText) == true } triggerStart(it) restoreByUi(delayMillis = defaultRestoreDelay) test { waitComponent(SearchEverywhereUI::class.java) type("clone") waitAndUsePreviouslyFoundListItem { jListItemFixture -> jListItemFixture.click() } } } task { triggerUI().componentPart { ui: TextFieldWithBrowseButton -> val rect = ui.visibleRect Rectangle(rect.x, rect.y, 59, rect.height) } } task { before { adjustPopupPosition("") // Clone dialog is not saving the state now } gotItStep(Balloon.Position.below, 340, GitLessonsBundle.message("git.quick.start.clone.dialog.got.it.1"), cornerToPointerDistance = 50) restoreByUi(findActionTaskId) } task { triggerUI().componentPart { ui: VcsCloneDialogExtensionList -> val size = ui.model.size val rect = ui.getCellBounds(size - 1, size - 1) Rectangle(rect.x, rect.y, 96, rect.height) } } task { gotItStep(Balloon.Position.below, 300, GitLessonsBundle.message("git.quick.start.clone.dialog.got.it.2")) restoreByUi(findActionTaskId) } val cancelButtonText = CommonBundle.getCancelButtonText() task { triggerAndFullHighlight().component { ui: JButton -> ui.text?.contains(cancelButtonText) == true } } task { text(GitLessonsBundle.message("git.quick.start.close.clone.dialog", strong(cancelButtonText)), LearningBalloonConfig(Balloon.Position.above, 300, true)) stateCheck { previous.ui?.isShowing != true } test(waitEditorToBeReady = false) { ideFrame { button(cancelButtonText).click() } } } prepareRuntimeTask { (editor as? EditorEx)?.let { editor -> EditorModificationUtil.setReadOnlyHint(editor, null) // remove hint about project modification editor.isViewer = false } } task { triggerAndFullHighlight { usePulsation = true }.component { ui: TextPanel.WithIconAndArrows -> ui.text == "main" } } lateinit var showBranchesTaskId: TaskContext.TaskId task("Git.Branches") { showBranchesTaskId = taskId text(GitLessonsBundle.message("git.quick.start.open.branches", action(it))) text(GitLessonsBundle.message("git.feature.branch.open.branches.popup.balloon"), LearningBalloonConfig(Balloon.Position.above, 0)) triggerUI().component { ui: EngravedLabel -> val repository = GitRepositoryManager.getInstance(project).repositories.first() val branchesInRepoText = DvcsBundle.message("branch.popup.vcs.name.branches.in.repo", GitBundle.message("git4idea.vcs.name"), DvcsUtil.getShortRepositoryName(repository)) ui.text?.contains(branchesInRepoText) == true } test { actions(it) } } val newBranchActionText = DvcsBundle.message("new.branch.action.text") task { triggerAndBorderHighlight().listItem { item -> item.toString().contains(newBranchActionText) } } val createButtonText = GitBundle.message("new.branch.dialog.operation.create.name") task { text(GitLessonsBundle.message("git.quick.start.choose.new.branch.item", strong(newBranchActionText))) triggerAndFullHighlight().component { ui: JButton -> ui.text?.contains(createButtonText) == true } restoreByUi(showBranchesTaskId, delayMillis = defaultRestoreDelay) test { ideFrame { jList(newBranchActionText).clickItem(newBranchActionText) } } } task { text(GitLessonsBundle.message("git.quick.start.name.new.branch", LessonUtil.rawEnter(), strong(createButtonText))) triggerOnCheckout() restoreByUiAndBackgroundTask(GitBundle.message("branch.checking.out.branch.from.process", "\\w+", "HEAD"), delayMillis = 2 * defaultRestoreDelay, showBranchesTaskId) test(waitEditorToBeReady = false) { type("newBranch") ideFrame { button(createButtonText).click() } } } prepareRuntimeTask { VcsConfiguration.getInstance(project).apply { setRecentMessages(emptyList()) } } caret(textToHighlight, select = true) task { var startOffset = -1 var line = -1 before { startOffset = editor.caretModel.offset editor.caretModel.moveToOffset(startOffset + textToHighlight.length) line = editor.document.getLineNumber(startOffset) } text(GitLessonsBundle.message("git.quick.start.modify.file", code("green"))) triggerAndBorderHighlight().componentPart l@{ ui: EditorComponentImpl -> if (ui.editor != editor) return@l null val endOffset = ui.editor.caretModel.offset if (endOffset < startOffset || ui.editor.document.getLineNumber(endOffset) != line) return@l null val startPoint = ui.editor.offsetToXY(startOffset) val endPoint = ui.editor.offsetToXY(endOffset) Rectangle(startPoint.x - 3, startPoint.y, endPoint.x - startPoint.x + 6, ui.editor.lineHeight) } stateCheck { val lineEndOffset = editor.document.getLineEndOffset(line) val color = editor.document.charsSequence.subSequence(startOffset, lineEndOffset).removeSuffix("]").trim() !textToHighlight.startsWith(color) && color.length >= 3 && !ChangeListManager.getInstance(project).allChanges.isEmpty() } proposeRestore { val caretOffset = editor.caretModel.offset if (editor.document.getLineNumber(caretOffset) != line) { sampleRestoreNotification(TaskContext.CaretRestoreProposal, previous.sample) } else null } test { for (ch in "yellow") type(ch.toString()) } } task("CheckinProject") { before { LearningUiHighlightingManager.clearHighlights() } openCommitWindowText(GitLessonsBundle.message("git.quick.start.open.commit.window")) stateCheck { ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.COMMIT)?.isVisible == true } proposeRestore { if (ChangeListManager.getInstance(project).allChanges.isEmpty()) { sampleRestoreNotification(TaskContext.ModificationRestoreProposal, previous.sample) } else null } test { actions(it) } } task { triggerAndBorderHighlight().treeItem { _: JTree, path: TreePath -> path.getPathComponent(path.pathCount - 1).toString().contains(fileToChange) } } task { gotItStep(Balloon.Position.atRight, 0, GitLessonsBundle.message("git.quick.start.commit.window.got.it")) } task { before { LearningUiHighlightingManager.clearHighlights() } val commitButtonText = GitBundle.message("commit.action.name").dropMnemonic() text(GitLessonsBundle.message("git.quick.start.perform.commit", strong(commitButtonText))) triggerAndBorderHighlight().component { _: CommitMessage -> true } triggerOnNotification { it.displayId == COMMIT_FINISHED } showWarningIfCommitWindowClosed() test { type("Edit eyes color of puss in boots") ideFrame { button { b: JBOptionButton -> b.text == commitButtonText }.click() } } } val pushButtonText = DvcsBundle.message("action.push").dropMnemonic() task { openPushDialogText(GitLessonsBundle.message("git.quick.start.open.push.dialog")) triggerAndFullHighlight().component { ui: JBOptionButton -> ui.text?.contains(pushButtonText) == true } test { actions("Vcs.Push") } } task { text(GitLessonsBundle.message("git.quick.start.perform.push", strong(pushButtonText))) text(GitLessonsBundle.message("git.click.balloon", strong(pushButtonText)), LearningBalloonConfig(Balloon.Position.above, 0, cornerToPointerDistance = 117)) triggerOnNotification { notification -> notification.groupId == "Vcs Notifications" && notification.type == NotificationType.INFORMATION } restoreByUiAndBackgroundTask(DvcsBundle.message("push.process.pushing"), delayMillis = defaultRestoreDelay) test(waitEditorToBeReady = false) { ideFrame { button { b: JBOptionButton -> b.text == pushButtonText }.click() } } } restoreCommitWindowStateInformer() } override fun prepare(project: Project) { super.prepare(project) GitProjectUtil.createRemoteProject("origin", project) } override fun onLessonEnd(project: Project, lessonEndInfo: LessonEndInfo) { LessonUtil.restorePopupPosition(project, SearchEverywhereManagerImpl.LOCATION_SETTINGS_KEY, backupSearchEverywhereLocation) backupSearchEverywhereLocation = null } override val suitableTips = listOf("VCS_general") override val helpLinks: Map<String, String> get() = mapOf( Pair(GitLessonsBundle.message("git.quick.start.help.link"), LessonUtil.getHelpLink("set-up-a-git-repository.html")), ) }
apache-2.0
ac8333618797b8cfdc92806d7b53a5b1
39.347305
158
0.717032
4.753086
false
false
false
false
mikepenz/FastAdapter
fastadapter-extensions-utils/src/main/java/com/mikepenz/fastadapter/helpers/UndoHelper.kt
1
7229
package com.mikepenz.fastadapter.helpers import android.view.View import com.google.android.material.snackbar.BaseTransientBottomBar import com.google.android.material.snackbar.Snackbar import com.mikepenz.fastadapter.FastAdapter import com.mikepenz.fastadapter.GenericItem import com.mikepenz.fastadapter.IItemAdapter import com.mikepenz.fastadapter.select.SelectExtension import java.util.* import java.util.Arrays.asList /** * Created by mikepenz on 04.01.16. * * Constructor to create the UndoHelper * * @param adapter the root FastAdapter * @param undoListener the listener which gets called when an item was really removed */ class UndoHelper<Item : GenericItem>( private val adapter: FastAdapter<Item>, private val undoListener: UndoListener<Item> ) { private var history: History? = null private var snackBarActionText = "" private var alreadyCommitted: Boolean = false private val snackBarCallback = object : Snackbar.Callback() { override fun onShown(sb: Snackbar?) { super.onShown(sb) // Reset the flag when a new Snackbar shows up alreadyCommitted = false } override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { super.onDismissed(transientBottomBar, event) // If the undo button was clicked (DISMISS_EVENT_ACTION) or // if a commit was already executed, skip it if (event == DISMISS_EVENT_ACTION || alreadyCommitted) return notifyCommit() } } var snackBar: Snackbar? = null private set /** Constructs the snackbar to be used for the undoHelper */ private var snackbarBuilder: (() -> Snackbar)? = null /** * An optional method to add a [Snackbar] of your own with custom styling. * note that using this method will override your custom action * * @param actionText the text to show for the Undo Action * @param snackbarBuilder constructs the snackbar with custom styling */ fun withSnackBar(actionText: String, snackbarBuilder: () -> Snackbar) { this.snackBarActionText = actionText this.snackbarBuilder = snackbarBuilder } /** * Convenience method to be used if you have previously set a [Snackbar] with [withSnackBar] * NOTE: No action will be executed if [withSnackBar] was not previously called. * * @param positions the positions where the items were removed * @return the snackbar or null if [withSnackBar] was not previously called */ fun remove(positions: Set<Int>): Snackbar? { val builder = this.snackbarBuilder ?: return null return remove(positions, snackBarActionText, builder) } /** * Removes items from the ItemAdapter. * * Creates a default [Snackbar] with the given information. * * @param view the view which will host the SnackBar * @param text the text to show on the SnackBar * @param actionText the text to show for the Undo Action * @param positions the positions where the items were removed * @return the generated Snackbar */ fun remove(view: View, text: String, actionText: String, @BaseTransientBottomBar.Duration duration: Int, positions: Set<Int>): Snackbar { return remove(positions, actionText) { Snackbar.make(view, text, duration) } } /** * Removes items from the ItemAdapter. * Displays the created [Snackbar] via the [snackbarBuilder], and configures the action with the given [actionText] * * @param positions the positions where the items were removed * @param actionText the text to show for the Undo Action * @param snackbarBuilder constructs the snackbar with custom styling * @return the generated Snackbar */ fun remove(positions: Set<Int>, actionText: String, snackbarBuilder: () -> Snackbar): Snackbar { if (history != null) { // Set a flag, if remove was called before the Snackbar // executed the commit -> Snackbar does not commit the new // inserted history alreadyCommitted = true notifyCommit() } val history = History() history.action = ACTION_REMOVE for (position in positions) { history.items.add(adapter.getRelativeInfo(position)) } history.items.sortWith { lhs, rhs -> Integer.valueOf(lhs.position).compareTo(rhs.position) } this.history = history doChange() // Do not execute when Snackbar shows up, instead change immediately return snackbarBuilder.invoke() .addCallback(snackBarCallback) .setAction(actionText) { undoChange() } .also { it.show() this.snackBar = it } } private fun notifyCommit() { history?.let { mHistory -> if (mHistory.action == ACTION_REMOVE) { val positions = TreeSet(Comparator<Int> { lhs, rhs -> lhs.compareTo(rhs) }) for (relativeInfo in mHistory.items) { positions.add(relativeInfo.position) } undoListener.commitRemove(positions, mHistory.items) this.history = null } } } private fun doChange() { history?.let { mHistory -> if (mHistory.action == ACTION_REMOVE) { for (i in mHistory.items.indices.reversed()) { val relativeInfo = mHistory.items[i] if (relativeInfo.adapter is IItemAdapter<*, *>) { (relativeInfo.adapter as IItemAdapter<*, *>).remove(relativeInfo.position) } } } } } private fun undoChange() { history?.let { mHistory -> if (mHistory.action == ACTION_REMOVE) { var i = 0 val size = mHistory.items.size while (i < size) { val relativeInfo = mHistory.items[i] if (relativeInfo.adapter is IItemAdapter<*, *>) { val adapter = relativeInfo.adapter as IItemAdapter<*, Item>? relativeInfo.item?.let { adapter?.addInternal(relativeInfo.position, asList(it)) if (relativeInfo.item?.isSelected == true) { val selectExtension = this.adapter.getExtension<SelectExtension<Item>>(SelectExtension::class.java) selectExtension?.select(relativeInfo.position) } } } i++ } } } history = null } interface UndoListener<Item : GenericItem> { fun commitRemove(positions: Set<Int>, removed: ArrayList<FastAdapter.RelativeInfo<Item>>) } private inner class History { var action: Int = 0 var items = ArrayList<FastAdapter.RelativeInfo<Item>>() } companion object { private const val ACTION_REMOVE = 2 } }
apache-2.0
94aa9ad0cdd84a3bd4cef8eb2afb7b06
36.071795
141
0.604648
4.911005
false
false
false
false
dahlstrom-g/intellij-community
tools/intellij.ide.starter/testSrc/com/intellij/ide/starter/tests/examples/junit4/JUnit4StarterRule.kt
2
1865
package com.intellij.ide.starter.tests.examples.junit4 import com.intellij.ide.starter.ci.CIServer import com.intellij.ide.starter.di.di import com.intellij.ide.starter.ide.IDETestContext import com.intellij.ide.starter.path.GlobalPaths import com.intellij.ide.starter.process.killOutdatedProcessesOnUnix import com.intellij.ide.starter.runner.TestContainer import com.intellij.ide.starter.utils.catchAll import com.intellij.ide.starter.utils.logOutput import com.intellij.ide.starter.utils.withIndent import org.junit.rules.ExternalResource import org.junit.runner.Description import org.junit.runners.model.Statement import org.kodein.di.direct import org.kodein.di.instance fun initStarterRule(): JUnit4StarterRule = JUnit4StarterRule(useLatestDownloadedIdeBuild = false) class JUnit4StarterRule( override var useLatestDownloadedIdeBuild: Boolean, override var allContexts: MutableList<IDETestContext> = mutableListOf(), override val setupHooks: MutableList<IDETestContext.() -> IDETestContext> = mutableListOf(), override val ciServer: CIServer = di.direct.instance() ) : ExternalResource(), TestContainer<JUnit4StarterRule> { private lateinit var testDescription: Description override fun apply(base: Statement, description: Description): Statement { testDescription = description return super.apply(base, description) } override fun before() { if (ciServer.isBuildRunningOnCI) { logOutput(buildString { appendLine("Disk usage diagnostics before test ${testDescription.displayName}") appendLine(di.direct.instance<GlobalPaths>().getDiskUsageDiagnostics().withIndent(" ")) }) } killOutdatedProcessesOnUnix() } override fun close() { for (context in allContexts) { catchAll { context.paths.close() } } } override fun after() { super.after() close() } }
apache-2.0
8ee473ce7b0c11ca603c1dd530963b17
31.155172
97
0.770509
4.219457
false
true
false
false
dahlstrom-g/intellij-community
platform/statistics/src/com/intellij/internal/statistic/eventLog/events/EventFields.kt
2
16978
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.internal.statistic.eventLog.events import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule import com.intellij.internal.statistic.service.fus.collectors.FeatureUsageCollectorExtension import com.intellij.internal.statistic.utils.PluginInfo import com.intellij.internal.statistic.utils.getPluginInfo import com.intellij.internal.statistic.utils.getPluginInfoByDescriptor import com.intellij.lang.Language import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.util.Version import org.jetbrains.annotations.NonNls import java.awt.event.KeyEvent import java.awt.event.MouseEvent import org.intellij.lang.annotations.Language as InjectedLanguage @Suppress("FunctionName") object EventFields { /** * Creates a field that will be validated by global regexp rule * @param name name of the field * @param regexpRef reference to global regexp, e.g "integer" for "{regexp#integer}" */ @JvmStatic fun StringValidatedByRegexp(@NonNls name: String, @NonNls regexpRef: String): StringEventField = StringEventField.ValidatedByRegexp(name, regexpRef) /** * Creates a field that will be validated by global enum rule * @param name name of the field * @param enumRef reference to global enum, e.g "os" for "{enum#os}" */ @JvmStatic fun StringValidatedByEnum(@NonNls name: String, @NonNls enumRef: String): StringEventField = StringEventField.ValidatedByEnum(name, enumRef) /** * Creates a field that will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule] * @param name name of the field * @param customRuleId ruleId that is accepted by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule.acceptRuleId], * e.g "class_name" for "{util#class_name}" */ @kotlin.Deprecated("Please use EventFields.StringValidatedByCustomRule(String, Class<out CustomValidationRule>)", ReplaceWith("EventFields.StringValidatedByCustomRule(name, customValidationRule)")) @JvmStatic fun StringValidatedByCustomRule(@NonNls name: String, @NonNls customRuleId: String): StringEventField = StringEventField.ValidatedByCustomRule(name, customRuleId) /** * Creates a field that will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule] * @param name name of the field * @param customValidationRule inheritor of [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule], */ @JvmStatic fun StringValidatedByCustomRule(@NonNls name: String, customValidationRule: Class<out CustomValidationRule>): StringEventField = StringEventField.ValidatedByCustomValidationRule(name, customValidationRule) /** * Creates a field that will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule]. * @param name name of the field */ inline fun <reified T : CustomValidationRule> StringValidatedByCustomRule(@NonNls name: String): StringEventField = StringValidatedByCustomRule(name, T::class.java) /** * Creates a field that allows only a specific list of values * @param name name of the field * @param allowedValues list of allowed values, e.g [ "bool", "int", "float"] */ @JvmStatic fun String(@NonNls name: String, allowedValues: List<String>): StringEventField = StringEventField.ValidatedByAllowedValues(name, allowedValues) @JvmStatic fun Int(@NonNls name: String): IntEventField = IntEventField(name) /** * Creates an int field that will be validated by regexp rule * @param name name of the field * @param regexp regular expression, e.g "-?[0-9]{1,3}" * Please choose regexp carefully to avoid reporting any sensitive data. */ @JvmStatic fun RegexpInt(@NonNls name: String, @InjectedLanguage("RegExp") @NonNls regexp: String): RegexpIntEventField = RegexpIntEventField(name, regexp) /** * Rounds integer value to the next power of two. * Use it to anonymize sensitive information like the number of files in a project. * @see com.intellij.internal.statistic.utils.StatisticsUtil.roundToPowerOfTwo */ @JvmStatic fun RoundedInt(@NonNls name: String): RoundedIntEventField = RoundedIntEventField(name) @JvmStatic fun Long(@NonNls name: String): LongEventField = LongEventField(name) /** * Rounds long value to the next power of two. * Use it to anonymize sensitive information like the number of files in a project. * @see com.intellij.internal.statistic.utils.StatisticsUtil.roundToPowerOfTwo */ @JvmStatic fun RoundedLong(@NonNls name: String): RoundedLongEventField = RoundedLongEventField(name) @JvmStatic fun Float(@NonNls name: String): FloatEventField = FloatEventField(name) @JvmStatic fun Double(@NonNls name: String): DoubleEventField = DoubleEventField(name) @JvmStatic fun Boolean(@NonNls name: String): BooleanEventField = BooleanEventField(name) @JvmStatic fun Class(@NonNls name: String): ClassEventField = ClassEventField(name) @JvmStatic @JvmOverloads fun <T : Enum<*>> Enum(@NonNls name: String, enumClass: Class<T>, transform: (T) -> String = { it.toString() }): EnumEventField<T> = EnumEventField(name, enumClass, transform) inline fun <reified T : Enum<*>> Enum(@NonNls name: String, noinline transform: (T) -> String = { it.toString() }): EnumEventField<T> = EnumEventField(name, T::class.java, transform) /** * Creates a field for a list, each element of which will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule] * @param name name of the field * @param customRuleId ruleId that is accepted by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule.acceptRuleId], * e.g "class_name" for "{util#class_name}" */ @kotlin.Deprecated("Please use EventFields.StringListValidatedByCustomRule(String, Class<out CustomValidationRule>)", ReplaceWith("EventFields.StringListValidatedByCustomRule(name, customValidationRule)")) @JvmStatic fun StringListValidatedByCustomRule(@NonNls name: String, @NonNls customRuleId: String): StringListEventField = StringListEventField.ValidatedByCustomRule(name, customRuleId) /** * Creates a field for a list, each element of which will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule] * @param name name of the field * @param customValidationRule inheritor of [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule] */ @JvmStatic fun StringListValidatedByCustomRule(@NonNls name: String, customValidationRule: Class<out CustomValidationRule>): StringListEventField = StringListEventField.ValidatedByCustomValidationRule(name, customValidationRule) /** * Creates a field for a list, each element of which will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule] * @param name name of the field */ inline fun <reified T : CustomValidationRule> StringListValidatedByCustomRule(@NonNls name: String): StringListEventField = StringListValidatedByCustomRule(name, T::class.java) /** * Creates a field for a list, each element of which will be validated by global enum rule * @param name name of the field * @param enumRef reference to global enum, e.g "os" for "{enum#os}" */ @JvmStatic fun StringListValidatedByEnum(@NonNls name: String, @NonNls enumRef: String): StringListEventField = StringListEventField.ValidatedByEnum(name, enumRef) /** * Creates a field for a list, each element of which will be validated by global regexp * @param name name of the field * @param regexpRef reference to global regexp, e.g "integer" for "{regexp#integer}" */ @JvmStatic fun StringListValidatedByRegexp(@NonNls name: String, @NonNls regexpRef: String): StringListEventField = StringListEventField.ValidatedByRegexp(name, regexpRef) /** * Creates a field for a list in which only a specific values are allowed * @param name name of the field * @param allowedValues list of allowed values, e.g [ "bool", "int", "float"] */ @JvmStatic fun StringList(@NonNls name: String, allowedValues: List<String>): StringListEventField = StringListEventField.ValidatedByAllowedValues(name, allowedValues) @JvmStatic fun LongList(@NonNls name: String): LongListEventField = LongListEventField(name) @JvmStatic fun IntList(@NonNls name: String): IntListEventField = IntListEventField(name) /** * Please choose regexp carefully to avoid reporting any sensitive data. */ @JvmStatic fun StringValidatedByInlineRegexp(@NonNls name: String, @InjectedLanguage("RegExp") @NonNls regexp: String): StringEventField = StringEventField.ValidatedByInlineRegexp(name, regexp) /** * Please choose regexp carefully to avoid reporting any sensitive data. */ @JvmStatic fun StringListValidatedByInlineRegexp(@NonNls name: String, @InjectedLanguage("RegExp") @NonNls regexp: String): StringListEventField = StringListEventField.ValidatedByInlineRegexp(name, regexp) @JvmField val InputEvent = object : PrimitiveEventField<FusInputEvent?>() { override val name = "input_event" override val validationRule: List<String> get() = listOf("{util#shortcut}") override fun addData(fuData: FeatureUsageData, value: FusInputEvent?) { if (value != null) { fuData.addInputEvent(value.inputEvent, value.place) } } } @JvmField val InputEventByAnAction = object : PrimitiveEventField<AnActionEvent?>() { override val name = "input_event" override val validationRule: List<String> get() = listOf("{util#shortcut}") override fun addData(fuData: FeatureUsageData, value: AnActionEvent?) { if (value != null) { fuData.addInputEvent(value) } } } @JvmField val InputEventByKeyEvent = object : PrimitiveEventField<KeyEvent?>() { override val name = "input_event" override val validationRule: List<String> get() = listOf("{util#shortcut}") override fun addData(fuData: FeatureUsageData, value: KeyEvent?) { if (value != null) { fuData.addInputEvent(value) } } } @JvmField val InputEventByMouseEvent = object : PrimitiveEventField<MouseEvent?>() { override val name = "input_event" override val validationRule: List<String> get() = listOf("{util#shortcut}") override fun addData(fuData: FeatureUsageData, value: MouseEvent?) { if (value != null) { fuData.addInputEvent(value) } } } @JvmField val ActionPlace = object : PrimitiveEventField<String?>() { override val name: String = "place" override val validationRule: List<String> get() = listOf("{util#place}") override fun addData(fuData: FeatureUsageData, value: String?) { fuData.addPlace(value) } } //will be replaced with ObjectEventField in the future @JvmField val PluginInfo = object : PrimitiveEventField<PluginInfo?>() { override val name: String get() = "plugin_type" override val validationRule: List<String> get() = listOf("plugin_info") override fun addData( fuData: FeatureUsageData, value: PluginInfo?, ) { fuData.addPluginInfo(value) } } @JvmField val PluginInfoByDescriptor = object : PrimitiveEventField<IdeaPluginDescriptor>() { private val delegate get() = PluginInfo override val name: String get() = delegate.name override val validationRule: List<String> get() = delegate.validationRule override fun addData( fuData: FeatureUsageData, value: IdeaPluginDescriptor, ) { delegate.addData(fuData, getPluginInfoByDescriptor(value)) } } //will be replaced with ObjectEventField in the future @JvmField val PluginInfoFromInstance = object : PrimitiveEventField<Any>() { private val delegate get() = PluginInfo override val name: String get() = delegate.name override val validationRule: List<String> get() = delegate.validationRule override fun addData( fuData: FeatureUsageData, value: Any, ) { delegate.addData(fuData, getPluginInfo(value::class.java)) } } @JvmField val AnonymizedPath = object : PrimitiveEventField<String?>() { override val validationRule: List<String> get() = listOf("{regexp#hash}") override val name = "file_path" override fun addData(fuData: FeatureUsageData, value: String?) { fuData.addAnonymizedPath(value) } } @JvmField val AnonymizedId = object : PrimitiveEventField<String?>() { override val validationRule: List<String> get() = listOf("{regexp#hash}") override val name = "anonymous_id" override fun addData(fuData: FeatureUsageData, value: String?) { value?.let { fuData.addAnonymizedId(value) } } } @JvmField val CodeWithMeClientId = object : PrimitiveEventField<String?>() { override val validationRule: List<String> get() = listOf("{regexp#hash}") override val name: String = "client_id" override fun addData(fuData: FeatureUsageData, value: String?) { fuData.addClientId(value) } } @JvmField val Language = object : PrimitiveEventField<Language?>() { override val name = "lang" override val validationRule: List<String> get() = listOf("{util#lang}") override fun addData(fuData: FeatureUsageData, value: Language?) { fuData.addLanguage(value) } } @JvmField val LanguageById = object : PrimitiveEventField<String?>() { override val name = "lang" override val validationRule: List<String> get() = listOf("{util#lang}") override fun addData(fuData: FeatureUsageData, value: String?) { fuData.addLanguage(value) } } @JvmField val FileType = object : PrimitiveEventField<FileType?>() { override val name = "file_type" override val validationRule: List<String> get() = listOf("{util#file_type}") override fun addData(fuData: FeatureUsageData, value: FileType?) { value?.let { val type = getPluginInfo(it.javaClass) if (type.isSafeToReport()) { fuData.addData("file_type", it.name) } else { fuData.addData("file_type", "third.party") } } } } @JvmField val CurrentFile = object : PrimitiveEventField<Language?>() { override val name = "current_file" override val validationRule: List<String> get() = listOf("{util#current_file}") override fun addData(fuData: FeatureUsageData, value: Language?) { fuData.addCurrentFile(value) } } @JvmField val Version = object : PrimitiveEventField<String?>() { override val name: String = "version" override val validationRule: List<String> get() = listOf("{regexp#version}") override fun addData(fuData: FeatureUsageData, value: String?) { fuData.addVersionByString(value) } } @JvmField val VersionByObject = object : PrimitiveEventField<Version?>() { override val name: String = "version" override val validationRule: List<String> get() = listOf("{regexp#version}") override fun addData(fuData: FeatureUsageData, value: Version?) { fuData.addVersion(value) } } @JvmField val Count = Int("count") @JvmField val Enabled = Boolean("enabled") @JvmField val DurationMs = LongEventField("duration_ms") @JvmField val TimeToShowMs = LongEventField("time_to_show") @JvmField val StartTime = LongEventField("start_time") /** * Logger merges successive events with identical group id, event id and event data fields except for fields listed here. * * @see com.intellij.internal.statistic.eventLog.StatisticsEventLoggerProvider.createEventsMergeStrategy */ @JvmField val FieldsIgnoredByMerge: List<EventField<*>> = arrayListOf(StartTime) @JvmStatic fun createAdditionalDataField(groupId: String, eventId: String): ObjectEventField { val additionalFields = mutableListOf<EventField<*>>() for (ext in FeatureUsageCollectorExtension.EP_NAME.extensionsIfPointIsRegistered) { if (ext.groupId == groupId && ext.eventId == eventId) { for (field in ext.extensionFields) { if (field != null) { additionalFields.add(field) } } } } return ObjectEventField("additional", *additionalFields.toTypedArray()) } }
apache-2.0
3caf25edb60da9c5e774344332ec03e1
34.970339
160
0.717811
4.679713
false
false
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/gridLayout/Gaps.kt
6
1200
// 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.gridLayout import com.intellij.ui.dsl.checkNonNegative import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBEmptyBorder import java.awt.Insets data class Gaps(val top: Int = 0, val left: Int = 0, val bottom: Int = 0, val right: Int = 0) { companion object { @JvmField val EMPTY = Gaps(0) } init { checkNonNegative("top", top) checkNonNegative("left", left) checkNonNegative("bottom", bottom) checkNonNegative("right", right) } constructor(size: Int) : this(size, size, size, size) val width: Int get() = left + right val height: Int get() = top + bottom } fun JBGaps(top: Int = 0, left: Int = 0, bottom: Int = 0, right: Int = 0): Gaps { return Gaps(JBUIScale.scale(top), JBUIScale.scale(left), JBUIScale.scale(bottom), JBUIScale.scale(right)) } fun Gaps.toJBEmptyBorder(): JBEmptyBorder { return JBEmptyBorder(top, left, bottom, right) } fun Insets.toGaps(): Gaps { return Gaps(top = top, left = left, bottom = bottom, right = right) }
apache-2.0
4a5119bd68993d30569e3c2e4c9aaa2d
28.268293
158
0.695
3.508772
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/actmain/TabletModeRecyclerView.kt
1
2557
package jp.juggler.subwaytooter.actmain import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import android.view.ViewConfiguration import androidx.recyclerview.widget.RecyclerView import kotlin.math.abs class TabletModeRecyclerView : RecyclerView { private var mForbidStartDragging: Boolean = false private var mScrollPointerId: Int = 0 private var mInitialTouchX: Int = 0 private var mInitialTouchY: Int = 0 private var mTouchSlop: Int = 0 constructor(context: Context) : super(context) { init(context) } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { init(context) } constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super( context, attrs, defStyle ) { init(context) } private fun init(context: Context) { val vc = ViewConfiguration.get(context) mTouchSlop = vc.scaledTouchSlop } override fun onInterceptTouchEvent(e: MotionEvent): Boolean { // final int actionIndex = e.getActionIndex( ); when (e.action) { MotionEvent.ACTION_DOWN -> { mForbidStartDragging = false mScrollPointerId = e.getPointerId(0) mInitialTouchX = (e.x + 0.5f).toInt() mInitialTouchY = (e.y + 0.5f).toInt() } MotionEvent.ACTION_MOVE -> { val index = e.findPointerIndex(mScrollPointerId) if (index >= 0) { if (mForbidStartDragging) return false val layoutManager = this.layoutManager ?: return false val x = (e.getX(index) + 0.5f).toInt() val y = (e.getY(index) + 0.5f).toInt() val canScrollHorizontally = layoutManager.canScrollHorizontally() val canScrollVertically = layoutManager.canScrollVertically() val dx = x - mInitialTouchX val dy = y - mInitialTouchY if (!canScrollVertically && abs(dy) > mTouchSlop || !canScrollHorizontally && abs( dx ) > mTouchSlop ) { mForbidStartDragging = true return false } } } } return super.onInterceptTouchEvent(e) } }
apache-2.0
b9f940b6a02a8ec3bf502160934fa32e
30.782051
102
0.549081
5.023576
false
false
false
false
gituser9/InvoiceManagement
app/src/main/java/com/user/invoicemanagement/view/fragment/ArchiveFragment.kt
1
2528
package com.user.invoicemanagement.view.fragment import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AutoCompleteTextView import com.user.invoicemanagement.R import com.user.invoicemanagement.model.dto.ClosedInvoice import com.user.invoicemanagement.presenter.ArchivePresenter import com.user.invoicemanagement.view.adapter.ArchiveAdapter import com.user.invoicemanagement.view.adapter.ArchiveClickListener class ArchiveFragment : BaseFragment() { lateinit var adapter: ArchiveAdapter lateinit var presenter: ArchivePresenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(false) presenter = ArchivePresenter(this) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater!!.inflate(R.layout.fragment_archive, container, false) val filterView = activity.findViewById<AutoCompleteTextView>(R.id.tvFilter) filterView.visibility = View.GONE adapter = ArchiveAdapter() adapter.deleteClickListener = object : ArchiveClickListener { override fun onClick(invoice: ClosedInvoice) { presenter.deleteInvoice(invoice) } } adapter.openClickListener = object : ArchiveClickListener { override fun onClick(invoice: ClosedInvoice) { showClosedIvoice(invoice.id) } } val recyclerView = view.findViewById<RecyclerView>(R.id.recycler_view_archive) recyclerView.layoutManager = LinearLayoutManager(activity.baseContext, LinearLayoutManager.HORIZONTAL, false) recyclerView.adapter = adapter presenter.getAll() return view } fun showAll(closedInvoices: List<ClosedInvoice>) { adapter.list = closedInvoices adapter.notifyDataSetChanged() } private fun showClosedIvoice(id: Long) { val fragment = ClosedInvoiceFragment() fragment.invoiceId = id val transaction = fragmentManager.beginTransaction() transaction.replace(R.id.container, fragment, "Archive") transaction.addToBackStack("Archive") transaction.commit() } override fun filter(name: String) { } override fun getAll() { } }
mit
d499d743527cfc7dd6cd941634836b9d
31
117
0.716772
5.096774
false
false
false
false
syncloud/android
syncloud/src/main/java/org/syncloud/android/ui/SettingsFragment.kt
1
3668
package org.syncloud.android.ui import android.content.Intent import android.content.SharedPreferences import android.content.SharedPreferences.OnSharedPreferenceChangeListener import android.os.Bundle import androidx.preference.Preference import androidx.preference.Preference.OnPreferenceClickListener import androidx.preference.PreferenceFragmentCompat import com.google.common.collect.Sets import org.apache.log4j.Logger import org.syncloud.android.* class SettingsFragment : PreferenceFragmentCompat(), OnSharedPreferenceChangeListener { private var removeAccountPref: Preference? = null private var feedbackPref: Preference? = null private lateinit var application: SyncloudApplication private val summaryUpdatable: Set<String> = Sets.newHashSet(PreferencesConstants.KEY_PREF_MAIN_DOMAIN) override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { application = activity?.application as SyncloudApplication addPreferencesFromResource(R.xml.preferences) removeAccountPref = findPreference(PreferencesConstants.KEY_PREF_ACCOUNT_REMOVE) removeAccountPref?.onPreferenceClickListener = OnPreferenceClickListener { val preferences = preferenceScreen.sharedPreferences val editor = preferences.edit() editor.putString(PreferencesConstants.KEY_PREF_EMAIL, null) editor.putString(PreferencesConstants.KEY_PREF_PASSWORD, null) editor.apply() updateSummary(preferences, PreferencesConstants.KEY_PREF_EMAIL) val intent = Intent([email protected], AuthActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK startActivity(intent) true } feedbackPref = findPreference(PreferencesConstants.KEY_PREF_FEEDBACK_SEND) feedbackPref?.onPreferenceClickListener = OnPreferenceClickListener { application.reportError() true } val preferences = preferenceScreen.sharedPreferences preferences.registerOnSharedPreferenceChangeListener(this) for (pref in summaryUpdatable) { updateSummary(preferences, pref) } updateSummary(preferences, PreferencesConstants.KEY_PREF_EMAIL) updateRemoveAccountPref(preferences) } private fun updateRemoveAccountPref(sharedPreferences: SharedPreferences) { val email = sharedPreferences.getString(PreferencesConstants.KEY_PREF_EMAIL, null) removeAccountPref?.isEnabled = email != null } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { if (key == PreferencesConstants.KEY_PREF_EMAIL) { updateRemoveAccountPref(sharedPreferences) } else if (summaryUpdatable.contains(key)) { updateSummary(sharedPreferences, key) } } private fun updateSummary(sharedPreferences: SharedPreferences, key: String) { logger.debug("updating: $key") val summary = getSummary(sharedPreferences, key) logger.debug("summary: $summary") val findPreference: Preference? = findPreference(key) findPreference?.summary = summary } private fun getSummary(sharedPreferences: SharedPreferences, key: String): String { val summary = sharedPreferences.getString(key, null) if (summary != null) return summary return if (key == PreferencesConstants.KEY_PREF_EMAIL) "Not specified yet" else "None" } companion object { private val logger = Logger.getLogger(SettingsFragment::class.java.name) } }
gpl-3.0
efb0d5693d46e1391eadce4f91babea8
44.296296
106
0.730371
5.410029
false
false
false
false
ssseasonnn/RxDownload
rxdownload4-manager/src/main/java/zlc/season/rxdownload4/manager/TaskManagerPool.kt
1
3151
package zlc.season.rxdownload4.manager import zlc.season.rxdownload4.download import zlc.season.rxdownload4.downloader.Dispatcher import zlc.season.rxdownload4.request.Request import zlc.season.rxdownload4.storage.Storage import zlc.season.rxdownload4.task.Task import zlc.season.rxdownload4.validator.Validator import zlc.season.rxdownload4.watcher.Watcher object TaskManagerPool { private val map = mutableMapOf<Task, TaskManager>() private fun add(task: Task, taskManager: TaskManager) { map[task] = taskManager } private fun get(task: Task): TaskManager? { return map[task] } private fun remove(task: Task) { map.remove(task) } fun obtain( task: Task, header: Map<String, String>, maxConCurrency: Int, rangeSize: Long, dispatcher: Dispatcher, validator: Validator, storage: Storage, request: Request, watcher: Watcher, notificationCreator: NotificationCreator, recorder: TaskRecorder, taskLimitation: TaskLimitation ): TaskManager { if (get(task) == null) { synchronized(this) { if (get(task) == null) { val taskManager = task.createManager( header = header, maxConCurrency = maxConCurrency, rangeSize = rangeSize, dispatcher = dispatcher, validator = validator, storage = storage, request = request, watcher = watcher, notificationCreator = notificationCreator, recorder = recorder, taskLimitation = taskLimitation ) add(task, taskManager) } } } return get(task)!! } private fun Task.createManager( header: Map<String, String>, maxConCurrency: Int, rangeSize: Long, dispatcher: Dispatcher, validator: Validator, storage: Storage, request: Request, watcher: Watcher, notificationCreator: NotificationCreator, recorder: TaskRecorder, taskLimitation: TaskLimitation ): TaskManager { val download = download( header = header, maxConCurrency = maxConCurrency, rangeSize = rangeSize, dispatcher = dispatcher, validator = validator, storage = storage, request = request, watcher = watcher ) return TaskManager( task = this, storage = storage, taskRecorder = recorder, connectFlowable = download.publish(), notificationCreator = notificationCreator, taskLimitation = taskLimitation ) } }
apache-2.0
87d9edc8560ba9e2608eceb71a2ebb80
30.838384
70
0.524278
5.687726
false
false
false
false
lisuperhong/ModularityApp
KaiyanModule/src/main/java/com/lisuperhong/openeye/ui/adapter/HorizontalBannerAdapter.kt
1
2036
package com.lisuperhong.openeye.ui.adapter import android.content.Context import android.net.Uri import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import com.lisuperhong.openeye.R import com.lisuperhong.openeye.mvp.model.bean.Banner import com.lisuperhong.openeye.ui.activity.SpecialTopicDetailActivity import com.lisuperhong.openeye.utils.ImageLoad import com.lisuperhong.openeye.utils.JumpActivityUtil import kotlinx.android.synthetic.main.item_horizontal_banner.view.* /** * Author: lisuperhong * Time: Create on 2018/8/11 22:03 * Github: https://github.com/lisuperhong * Desc: */ class HorizontalBannerAdapter(context: Context, datas: ArrayList<Banner>) : RecyclerView.Adapter<HorizontalBannerAdapter.ViewHolder>() { private var context: Context? = null private var dataList: ArrayList<Banner> = ArrayList<Banner>() init { this.context = context this.dataList = datas } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { var view = LayoutInflater.from(context).inflate(R.layout.item_horizontal_banner, parent, false) return ViewHolder(view) } override fun getItemCount(): Int { return dataList.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val banner = dataList[position] ImageLoad.loadImage(holder.horizontalBannerIv, banner.image, 5) holder.horizontalBannerIv.setOnClickListener { val uri: Uri = Uri.parse(banner.actionUrl) if (uri.host == "lightTopic") { SpecialTopicDetailActivity.start(context!!, banner.id, banner.title) } else { JumpActivityUtil.parseActionUrl(context!!, banner.actionUrl) } } } inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { var horizontalBannerIv: ImageView = view.horizontalBannerIv } }
apache-2.0
7abb9013404ed482533bb9364ce65460
32.95
103
0.720039
4.331915
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/LocSound.kt
1
2162
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Opcodes.GETFIELD import org.objectweb.asm.Type.INT_TYPE import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.OrderMapper import org.runestar.client.updater.mapper.UniqueMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Instruction2 import org.runestar.client.updater.mapper.Method2 @DependsOn(Node::class, LocType::class) class LocSound : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == type<Node>() } .and { it.instanceFields.any { it.type == type<LocType>() } } @DependsOn(LocType::class) class obj : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == type<LocType>() } } @MethodParameters() class set : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { true } } @DependsOn(set::class) class soundEffectId : OrderMapper.InMethod.Field(set::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == INT_TYPE } } class soundEffectIds : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == IntArray::class.type } } @DependsOn(set::class, RawPcmStream::class) class stream1 : UniqueMapper.InMethod.Field(set::class) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD && it.fieldType == type<RawPcmStream>() } } @DependsOn(stream1::class, RawPcmStream::class) class stream2 : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == type<RawPcmStream>() && it != field<stream1>() } } }
mit
d87a301c8f11ac176ee0416e457612db
40.596154
124
0.733117
3.966972
false
false
false
false
google/intellij-community
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/inference/common/ConstraintBuilder.kt
2
5062
// 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.j2k.post.processing.inference.common import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtTypeElement import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.utils.addToStdlib.safeAs @Suppress("unused") class ConstraintBuilder( private val inferenceContext: InferenceContext, private val boundTypeCalculator: BoundTypeCalculator, private val constraintBoundProvider: ConstraintBoundProvider ) : BoundTypeCalculator by boundTypeCalculator, ConstraintBoundProvider by constraintBoundProvider { private val constraints = mutableListOf<Constraint>() fun TypeVariable.isSubtypeOf(supertype: BoundType, priority: ConstraintPriority) { asBoundType().isSubtypeOf(supertype, priority) } fun TypeVariable.isSubtypeOf(supertype: TypeVariable, priority: ConstraintPriority) { asBoundType().isSubtypeOf(supertype.asBoundType(), priority) } fun KtExpression.isSubtypeOf(supertype: KtExpression, priority: ConstraintPriority) { boundType().isSubtypeOf(supertype.boundType(), priority) } fun KtExpression.isSubtypeOf(supertype: TypeVariable, priority: ConstraintPriority) { boundType().isSubtypeOf(supertype.asBoundType(), priority) } fun KtExpression.isSubtypeOf(supertype: BoundType, priority: ConstraintPriority) { boundType().isSubtypeOf(supertype, priority) } fun KtExpression.isTheSameTypeAs(other: State, priority: ConstraintPriority) { boundType().label.safeAs<TypeVariableLabel>()?.typeVariable?.let { typeVariable -> constraints += EqualsConstraint( typeVariable.constraintBound(), other.constraintBound() ?: return@let, priority ) } } fun TypeVariable.isTheSameTypeAs(other: BoundType, priority: ConstraintPriority) { asBoundType().isTheSameTypeAs(other, priority) } fun TypeVariable.isTheSameTypeAs( other: TypeVariable, priority: ConstraintPriority, ignoreTypeVariables: Set<TypeVariable> = emptySet() ) { asBoundType().isTheSameTypeAs(other.asBoundType(), priority, ignoreTypeVariables) } fun KtTypeElement.isTheSameTypeAs( other: KtTypeElement, priority: ConstraintPriority, ignoreTypeVariables: Set<TypeVariable> = emptySet() ) { inferenceContext.typeElementToTypeVariable[this] ?.asBoundType() ?.isTheSameTypeAs( inferenceContext.typeElementToTypeVariable[other]?.asBoundType() ?: return, priority, ignoreTypeVariables ) } fun TypeVariable.isTheSameTypeAs( other: KtTypeElement, priority: ConstraintPriority, ignoreTypeVariables: Set<TypeVariable> = emptySet() ) { asBoundType().isTheSameTypeAs( inferenceContext.typeElementToTypeVariable[other]?.asBoundType() ?: return, priority, ignoreTypeVariables ) } fun BoundType.isTheSameTypeAs( other: KtTypeElement, priority: ConstraintPriority, ignoreTypeVariables: Set<TypeVariable> = emptySet() ) { isTheSameTypeAs( inferenceContext.typeElementToTypeVariable[other]?.asBoundType() ?: return, priority, ignoreTypeVariables ) } fun BoundType.isTheSameTypeAs( other: BoundType, priority: ConstraintPriority, ignoreTypeVariables: Set<TypeVariable> = emptySet() ) { (typeParameters zip other.typeParameters).forEach { (left, right) -> left.boundType.isTheSameTypeAs(right.boundType, priority, ignoreTypeVariables) } if (typeVariable !in ignoreTypeVariables && other.typeVariable !in ignoreTypeVariables) { constraints += EqualsConstraint( constraintBound() ?: return, other.constraintBound() ?: return, priority ) } } fun BoundType.isSubtypeOf(supertype: BoundType, priority: ConstraintPriority) { (typeParameters zip supertype.typeParameters).forEach { (left, right) -> when (left.variance) { Variance.OUT_VARIANCE -> left.boundType.isSubtypeOf(right.boundType, priority) Variance.IN_VARIANCE -> right.boundType.isSubtypeOf(left.boundType, priority) Variance.INVARIANT -> right.boundType.isTheSameTypeAs(left.boundType, priority) } } constraints += SubtypeConstraint( constraintBound() ?: return, supertype.constraintBound() ?: return, priority ) } fun KtExpression.boundType() = with(boundTypeCalculator) { [email protected](inferenceContext) } val collectedConstraints: List<Constraint> get() = constraints }
apache-2.0
3432fdf2314a1e2f1b4989760a9ac148
35.688406
158
0.676412
5.643255
false
false
false
false
google/intellij-community
plugins/repository-search/src/test/kotlin/org/jetbrains/idea/reposearch/PackageSearchProviderTest.kt
2
4727
/* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.idea.reposearch import com.intellij.openapi.util.Ref import com.sun.net.httpserver.HttpExchange import com.sun.net.httpserver.HttpServer import org.jetbrains.idea.maven.onlinecompletion.model.MavenRepositoryArtifactInfo import org.jetbrains.idea.packagesearch.PackageSearchServiceConfig import org.jetbrains.idea.packagesearch.api.PackageSearchApiContentTypes import org.jetbrains.idea.packagesearch.api.PackageSearchProvider import org.junit.After import org.junit.Before import org.junit.Test import org.junit.jupiter.api.Assertions.* import java.net.HttpURLConnection import java.net.InetSocketAddress import java.net.URI class PackageSearchProviderTest { companion object { private const val LOCALHOST = "127.0.0.1" private const val fulltextEndpoint = "/package" private const val suggestEndpoint = "/package" } private lateinit var myServer: HttpServer private lateinit var myUrl: String private val response: String = this::class.java.classLoader.getResourceAsStream("pkgs-response.json")!!.bufferedReader().readText() @Before fun setUp() { myServer = HttpServer.create().apply { bind(InetSocketAddress(LOCALHOST, 0), 1) start() } myUrl = "http://" + LOCALHOST + ":" + myServer.address?.port } @After fun tearDown() { myServer.stop(0) } @Test fun `test suggested packages search`() { val params = createServer(suggestEndpoint, response) val data: MutableList<RepositoryArtifactData> = ArrayList() PackageSearchProvider(MyPackageSearchServiceConfig()).suggestPrefix( groupId = "org.apache.maven", artifactId = "maven-plugin-api", consumer = data::add ) assertNotNull(params.get()) assertEquals("org.apache.maven", params.get()["groupid"]) assertEquals("maven-plugin-api", params.get()["artifactid"]) assertEquals(1, data.size) val info = data.first() assertInstanceOf(MavenRepositoryArtifactInfo::class.java, info) info as MavenRepositoryArtifactInfo assertEquals("org.apache.maven", info.groupId) assertEquals("maven-plugin-api", info.artifactId) } @Test fun `test packages fulltext search`() { val params = createServer(fulltextEndpoint, response) val data: MutableList<RepositoryArtifactData> = ArrayList() PackageSearchProvider(MyPackageSearchServiceConfig()).fulltextSearch( searchString = "maven-plugin-api", consumer = data::add ) assertNotNull(params.get()) assertEquals("maven-plugin-api", params.get()["query"]) assertEquals(1, data.size) val info = data.first() assertInstanceOf(MavenRepositoryArtifactInfo::class.java, info) info as MavenRepositoryArtifactInfo assertEquals("org.apache.maven", info.groupId) assertEquals("maven-plugin-api", info.artifactId) } private fun createServer(endpoint: String, serverResponse: String): Ref<Map<String, String>> { val params = Ref<Map<String, String>>() myServer.createContext(endpoint) { ex: HttpExchange -> try { params.set(getQueryMap(ex.requestURI)) ex.responseHeaders.add("Content-Type", "${PackageSearchApiContentTypes.StandardV2}; charset=UTF-8") val responseBody = serverResponse.toByteArray() ex.sendResponseHeaders(HttpURLConnection.HTTP_OK, responseBody.size.toLong()) ex.responseBody.write(responseBody) } finally { ex.close() } } return params } private fun getQueryMap(uri: URI): Map<String, String>? { val params = uri.query.split("&") val map = HashMap<String, String>() for (param in params) { val split = param.split("=") map[split[0]] = split[1] } return map } private inner class MyPackageSearchServiceConfig : PackageSearchServiceConfig { override val baseUrl: String get() = myUrl override val timeoutInSeconds: Int get() = 1000 override val userAgent: String get() = "TEST" override val forceHttps: Boolean get() = false override val headers: List<Pair<String, String>> get() = emptyList() } }
apache-2.0
6b5fb174056a8c9618ee28fd8498b95a
30.731544
133
0.714195
4.35267
false
false
false
false
RuneSuite/client
api/src/main/java/org/runestar/client/api/game/ObjectDefinition.kt
1
715
package org.runestar.client.api.game import org.runestar.client.raw.access.XLocType inline class ObjectDefinition(val accessor: XLocType) { val id get() = accessor.id fun recolor(from: HslColor, to: HslColor) { if (accessor.recol_s == null) { accessor.recol_s = shortArrayOf(from.packed) accessor.recol_d = shortArrayOf(to.packed) } else { val i = accessor.recol_s.indexOf(from.packed) if (i == -1) { accessor.recol_s = accessor.recol_s.plus(from.packed) accessor.recol_d = accessor.recol_d.plus(to.packed) } else { accessor.recol_d[i] = to.packed } } } }
mit
f66a4400e4f2e18743ce5091908671c1
30.130435
69
0.572028
3.454106
false
false
false
false
CobaltVO/2048-Neural-network
src/main/java/ru/falseteam/neural2048/gnn/crossower/UniformelyDistributedNeuronsCrossover.kt
1
1856
package ru.falseteam.neural2048.gnn.crossower import ru.falseteam.neural2048.ga.MutatorCrossover import ru.falseteam.neural2048.nn.NeuralNetwork import java.util.* /** * Автор: Евгений Рудзянский * Дата : 09.10.17 */ class UniformelyDistributedNeuronsCrossover : MutatorCrossover.Crossing<NeuralNetwork> { private val random = Random() override fun crossing(chromosome1: NeuralNetwork, chromosome2: NeuralNetwork): List<NeuralNetwork> { val anotherClone = chromosome2.clone() val thisClone = chromosome1.clone() // case of switch val thisNeurons = thisClone.neurons val anotherNeurons = anotherClone.neurons //uniformelyDistributedNeuronsCrossover(thisClone.neurons, anotherClone.neurons) //uniformelyDistributedNeuronsCrossover(thisNeurons: MutableList<Neuron>, anotherNeurons: MutableList<Neuron>) val neuronsSize = thisNeurons.size var itersCount = this.random.nextInt(neuronsSize) if (itersCount == 0) { itersCount = 1 } val used = HashSet<Int>() for (iter in 0 until itersCount) { var i = this.random.nextInt(neuronsSize) if (neuronsSize > 1) { while (used.contains(i)) { i = this.random.nextInt(neuronsSize) } } val thisNeuron = thisNeurons[i] val anotherNeuron = anotherNeurons[i] anotherNeurons[i] = thisNeuron thisNeurons[i] = anotherNeuron used.add(i) } // end func // after switch val ret = ArrayList<NeuralNetwork>() ret.add(anotherClone) ret.add(thisClone) //ret.add(anotherClone.mutate_()); //ret.add(thisClone.mutate_());//TODO мазафака return ret } }
gpl-3.0
7c08cfa04e50bf24a9b38152875616dd
34.057692
118
0.631723
3.651303
false
false
false
false
square/okhttp
okhttp/src/commonMain/kotlin/okhttp3/internal/http/StatusLine.kt
2
3431
/* * Copyright (c) 2022 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package okhttp3.internal.http import kotlin.jvm.JvmField import okhttp3.Protocol import okhttp3.ProtocolException import okhttp3.Response import okio.IOException /** An HTTP response status line like "HTTP/1.1 200 OK". */ class StatusLine( @JvmField val protocol: Protocol, @JvmField val code: Int, @JvmField val message: String ) { override fun toString(): String { return buildString { if (protocol == Protocol.HTTP_1_0) { append("HTTP/1.0") } else { append("HTTP/1.1") } append(' ').append(code) append(' ').append(message) } } companion object { fun get(response: Response): StatusLine { return StatusLine(response.protocol, response.code, response.message) } @Throws(IOException::class) fun parse(statusLine: String): StatusLine { // H T T P / 1 . 1 2 0 0 T e m p o r a r y R e d i r e c t // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 // Parse protocol like "HTTP/1.1" followed by a space. val codeStart: Int val protocol: Protocol if (statusLine.startsWith("HTTP/1.")) { if (statusLine.length < 9 || statusLine[8] != ' ') { throw ProtocolException("Unexpected status line: $statusLine") } val httpMinorVersion = statusLine[7] - '0' codeStart = 9 protocol = when (httpMinorVersion) { 0 -> Protocol.HTTP_1_0 1 -> Protocol.HTTP_1_1 else -> throw ProtocolException("Unexpected status line: $statusLine") } } else if (statusLine.startsWith("ICY ")) { // Shoutcast uses ICY instead of "HTTP/1.0". protocol = Protocol.HTTP_1_0 codeStart = 4 } else if (statusLine.startsWith("SOURCETABLE ")) { // NTRIP r1 uses SOURCETABLE instead of HTTP/1.1 protocol = Protocol.HTTP_1_1 codeStart = 12 } else { throw ProtocolException("Unexpected status line: $statusLine") } // Parse response code like "200". Always 3 digits. if (statusLine.length < codeStart + 3) { throw ProtocolException("Unexpected status line: $statusLine") } val code = statusLine.substring(codeStart, codeStart + 3).toIntOrNull() ?: throw ProtocolException( "Unexpected status line: $statusLine" ) // Parse an optional response message like "OK" or "Not Modified". If it // exists, it is separated from the response code by a space. var message = "" if (statusLine.length > codeStart + 3) { if (statusLine[codeStart + 3] != ' ') { throw ProtocolException("Unexpected status line: $statusLine") } message = statusLine.substring(codeStart + 4) } return StatusLine(protocol, code, message) } } }
apache-2.0
54a1e902b8cf4a1e72ba9b6f7542f233
32.31068
80
0.626931
4.045991
false
false
false
false
HITGIF/SchoolPower
app/src/main/java/com/carbonylgroup/schoolpower/activities/SettingsActivity.kt
1
3104
/** * Copyright (C) 2019 SchoolPower Studio */ package com.carbonylgroup.schoolpower.activities import android.animation.AnimatorListenerAdapter import android.app.Activity import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.NavUtils import android.support.v7.widget.Toolbar import android.view.MenuItem import android.view.View import android.view.ViewAnimationUtils import android.widget.RelativeLayout import com.carbonylgroup.schoolpower.R import com.carbonylgroup.schoolpower.fragments.SettingsFragment import kotterknife.bindView private var recreated = false class SettingsActivity : BaseActivity(), SettingsFragment.SettingsCallBack { private val settingsToolBar: Toolbar by bindView(R.id.settings_toolbar) private val rootLayout: RelativeLayout by bindView(R.id.settings_root_layout) override fun onRecreate() { recreated = true setResult(Activity.RESULT_OK) recreate() } override fun initActivity() { super.initActivity() setContentView(R.layout.settings_toolbar) setSupportActionBar(settingsToolBar) supportFragmentManager.beginTransaction().replace(R.id.settings_content, SettingsFragment()).commit() supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.title = getString(R.string.settings) setResult(Activity.RESULT_OK) if (recreated) { rootLayout.post( { startAnimation() }) // to invoke onActivityResult to apply settings recreated = false } } private fun startAnimation() { val cx = rootLayout.width / 2 val cy = rootLayout.height / 2 val finalRadius = Math.hypot(cx.toDouble(), cy.toDouble()).toFloat() val anim = ViewAnimationUtils.createCircularReveal(rootLayout, cx, cy, 0f, finalRadius) anim.addListener(object : AnimatorListenerAdapter() {}) rootLayout.visibility = View.VISIBLE anim.start() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { NavUtils.navigateUpFromSameTask(this) return true } } return super.onOptionsItemSelected(item) } override fun onSupportNavigateUp(): Boolean { finish() return true } override fun onSaveInstanceState(outState: Bundle) { // finish setting activity to avoid java.io.NotSerializableException // com.thirtydegreesray.openhub.ui.widget.colorChooser.ColorChooserPreference // android.os.Parcel.writeSerializable(Parcel.java:1761) if (recreated) { super.onSaveInstanceState(outState) } else { finish() } } fun addFragmentOnTop(fragment: Fragment){ supportFragmentManager.beginTransaction() .add(R.id.settings_content, fragment) .addToBackStack("TAG") .commit() } }
apache-2.0
0e7e1d7eb0c85edba16ba93bdc45e762
31.333333
109
0.677835
5.022654
false
false
false
false
JetBrains/intellij-community
python/src/com/jetbrains/python/run/PythonExecution.kt
1
2265
// 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.jetbrains.python.run import com.intellij.execution.target.value.TargetEnvironmentFunction import com.intellij.execution.target.value.constant import com.intellij.openapi.vfs.encoding.EncodingManager import org.jetbrains.annotations.ApiStatus import java.io.File import java.nio.charset.Charset /** * Represents the Python script or module to be executed and its parameters. */ @ApiStatus.Experimental sealed class PythonExecution { var workingDir: TargetEnvironmentFunction<out String?>? = null val parameters: MutableList<TargetEnvironmentFunction<String>> = mutableListOf() val envs: MutableMap<String, TargetEnvironmentFunction<String>> = mutableMapOf() var charset: Charset = EncodingManager.getInstance().defaultConsoleEncoding var inputFile: File? = null fun addParameter(value: String) { addParameter(constant(value)) } fun addParameter(value: TargetEnvironmentFunction<String>) { parameters.add(value) } fun addParameters(vararg parameters: String) { parameters.forEach { parameter -> addParameter(parameter) } } fun addParameters(parameters: List<String>) { parameters.forEach { parameter -> addParameter(parameter) } } fun addEnvironmentVariable(key: String, value: String) { envs[key] = constant(value) } fun addEnvironmentVariable(key: String, value: TargetEnvironmentFunction<String>) { envs[key] = value } fun withInputFile(file: File) { inputFile = file } /** * Java alternative for [PythonExecution] sealed Kotlin class functionality. */ abstract fun accept(visitor: Visitor) interface Visitor { fun visit(pythonScriptExecution: PythonScriptExecution) fun visit(pythonModuleExecution: PythonModuleExecution) } } @ApiStatus.Experimental class PythonScriptExecution : PythonExecution() { var pythonScriptPath: TargetEnvironmentFunction<String>? = null override fun accept(visitor: Visitor) = visitor.visit(this) } @ApiStatus.Experimental class PythonModuleExecution : PythonExecution() { var moduleName: String? = null override fun accept(visitor: Visitor) = visitor.visit(this) }
apache-2.0
a635ca4832f2c194be73d807634c9d63
28.051282
140
0.763355
4.53
false
false
false
false
customerly/Customerly-Android-SDK
customerly-android-sdk/src/main/java/io/customerly/utils/DefaultInitializerDelegate.kt
1
1308
package io.customerly.utils /* * Copyright (C) 2017 Customerly * * 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 kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty /** * Created by Gianni on 30/04/18. * Project: Customerly-KAndroid-SDK */ internal class DefaultInitializerDelegate<T: Any>(private val constructor: ()->T) : ReadWriteProperty<Any?, T> { private var value: T? = null override fun getValue(thisRef: Any?, property: KProperty<*>): T { var defaultValue = this.value if(defaultValue == null) { defaultValue = constructor() this.value = defaultValue } return defaultValue } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { this.value = value } }
apache-2.0
c518e68f27d53c47bea8511d166015ea
30.926829
112
0.691896
4.302632
false
false
false
false
littleGnAl/Accounting
app/src/main/java/com/littlegnal/accounting/base/MvRxEpoxyController.kt
1
1287
package com.littlegnal.accounting.base import com.airbnb.epoxy.AsyncEpoxyController import com.airbnb.epoxy.EpoxyController import com.airbnb.mvrx.BaseMvRxViewModel import com.airbnb.mvrx.MvRxState import com.airbnb.mvrx.withState open class MvRxEpoxyController( val buildModelsCallback: EpoxyController.() -> Unit = {} ) : AsyncEpoxyController() { override fun buildModels() { buildModelsCallback() } } /** * Create a [MvRxEpoxyController] that builds models with the given callback. */ fun BaseFragment.simpleController( buildModels: EpoxyController.() -> Unit ) = MvRxEpoxyController { // Models are built asynchronously, so it is possible that this is called after the fragment // is detached under certain race conditions. if (view == null || isRemoving) return@MvRxEpoxyController buildModels() } /** * Create a [MvRxEpoxyController] that builds models with the given callback. * When models are built the current state of the viewmodel will be provided. */ fun <S : MvRxState, A : BaseMvRxViewModel<S>> BaseFragment.simpleController( viewModel: A, buildModels: EpoxyController.(state: S) -> Unit ) = MvRxEpoxyController { if (view == null || isRemoving) return@MvRxEpoxyController withState(viewModel) { state -> buildModels(state) } }
apache-2.0
66ac1c65b9f30736bc7b990dcc970072
29.642857
94
0.754468
4.377551
false
false
false
false
allotria/intellij-community
plugins/ide-features-trainer/src/training/learn/lesson/LessonStateBase.kt
2
1470
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.learn.lesson import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import training.learn.course.Lesson import training.util.trainerPluginConfigName @State(name = "LessonStateBase", storages = [Storage(value = trainerPluginConfigName)]) class LessonStateBase : PersistentStateComponent<LessonStateBase> { override fun getState(): LessonStateBase = this override fun loadState(persistedState: LessonStateBase) { map = persistedState.map.mapKeys { it.key.toLowerCase() }.toMutableMap() } var map: MutableMap<String, LessonState> = mutableMapOf() companion object { internal val instance: LessonStateBase get() = ApplicationManager.getApplication().getService(LessonStateBase::class.java) } } object LessonStateManager { fun setPassed(lesson: Lesson) { LessonStateBase.instance.map[lesson.id.toLowerCase()] = LessonState.PASSED } fun resetPassedStatus() { for (lesson in LessonStateBase.instance.map) { lesson.setValue(LessonState.NOT_PASSED) } } fun getStateFromBase(lessonId: String): LessonState = LessonStateBase.instance.map.getOrPut(lessonId.toLowerCase(), { LessonState.NOT_PASSED }) }
apache-2.0
26017fe0ccae55ccea0eea06d589aa58
34.853659
145
0.779592
4.481707
false
false
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ContentEntryBridge.kt
2
4821
package com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots import com.intellij.openapi.roots.ContentEntry import com.intellij.openapi.roots.ExcludeFolder import com.intellij.openapi.roots.SourceFolder import com.intellij.openapi.roots.impl.DirectoryIndexExcludePolicy import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.pointers.VirtualFilePointer import com.intellij.workspaceModel.storage.bridgeEntities.ContentRootEntity import com.intellij.workspaceModel.storage.bridgeEntities.SourceRootEntity import com.intellij.workspaceModel.storage.WorkspaceEntityStorageDiffBuilder import org.jetbrains.jps.model.JpsElement import org.jetbrains.jps.model.module.JpsModuleSourceRootType internal class ContentEntryBridge(internal val model: ModuleRootModelBridge, val sourceRootEntities: List<SourceRootEntity>, val entity: ContentRootEntity, val updater: (((WorkspaceEntityStorageDiffBuilder) -> Unit) -> Unit)?) : ContentEntry { private val excludeFolders by lazy { entity.excludedUrls.map { ExcludeFolderBridge(this, it) } } private val sourceFolders by lazy { sourceRootEntities.map { SourceFolderBridge(this, it) } } override fun getFile(): VirtualFile? { val virtualFilePointer = entity.url as VirtualFilePointer return virtualFilePointer.file } override fun getUrl(): String = entity.url.url override fun getSourceFolders(): Array<SourceFolder> = sourceFolders.toTypedArray() override fun getExcludeFolders(): Array<ExcludeFolder> = excludeFolders.toTypedArray() override fun getExcludePatterns(): List<String> = entity.excludedPatterns override fun getExcludeFolderFiles(): Array<VirtualFile> { val result = ArrayList<VirtualFile>(excludeFolders.size) excludeFolders.mapNotNullTo(result) { it.file } for (excludePolicy in DirectoryIndexExcludePolicy.EP_NAME.getExtensions(model.module.project)) { excludePolicy.getExcludeRootsForModule(model).mapNotNullTo(result) { it.file } } return VfsUtilCore.toVirtualFileArray(result) } override fun getExcludeFolderUrls(): MutableList<String> { val result = ArrayList<String>(excludeFolders.size) excludeFolders.mapTo(result) { it.url } for (excludePolicy in DirectoryIndexExcludePolicy.EP_NAME.getExtensions(model.module.project)) { excludePolicy.getExcludeRootsForModule(model).mapTo(result) { it.url } } return result } override fun equals(other: Any?): Boolean { return (other as? ContentEntry)?.url == url } override fun hashCode(): Int { return url.hashCode() } override fun isSynthetic() = false override fun getRootModel() = model override fun getSourceFolders(rootType: JpsModuleSourceRootType<*>): List<SourceFolder> = getSourceFolders(setOf(rootType)) override fun getSourceFolders(rootTypes: Set<JpsModuleSourceRootType<*>>): List<SourceFolder> = sourceFolders.filter { it.rootType in rootTypes } override fun getSourceFolderFiles() = sourceFolders.mapNotNull { it.file }.toTypedArray() override fun <P : JpsElement?> addSourceFolder(file: VirtualFile, type: JpsModuleSourceRootType<P>, properties: P): SourceFolder = throwReadonly() override fun <P : JpsElement?> addSourceFolder(url: String, type: JpsModuleSourceRootType<P>, properties: P): SourceFolder = throwReadonly() override fun addSourceFolder(file: VirtualFile, isTestSource: Boolean) = throwReadonly() override fun addSourceFolder(file: VirtualFile, isTestSource: Boolean, packagePrefix: String): SourceFolder = throwReadonly() override fun <P : JpsElement?> addSourceFolder(file: VirtualFile, type: JpsModuleSourceRootType<P>) = throwReadonly() override fun addSourceFolder(url: String, isTestSource: Boolean): SourceFolder = throwReadonly() override fun <P : JpsElement?> addSourceFolder(url: String, type: JpsModuleSourceRootType<P>): SourceFolder = throwReadonly() override fun removeSourceFolder(sourceFolder: SourceFolder) = throwReadonly() override fun clearSourceFolders() = throwReadonly() override fun addExcludeFolder(file: VirtualFile): ExcludeFolder = throwReadonly() override fun addExcludeFolder(url: String): ExcludeFolder = throwReadonly() override fun removeExcludeFolder(excludeFolder: ExcludeFolder) = throwReadonly() override fun removeExcludeFolder(url: String): Boolean = throwReadonly() override fun clearExcludeFolders() = throwReadonly() override fun addExcludePattern(pattern: String) = throwReadonly() override fun removeExcludePattern(pattern: String) = throwReadonly() override fun setExcludePatterns(patterns: MutableList<String>) = throwReadonly() private fun throwReadonly(): Nothing = error("This model is read-only") }
apache-2.0
700d7c6024c7a230761037952e798457
53.168539
148
0.772661
5.16167
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/ui/PathChooserDialogHelper.kt
2
1906
// 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 import com.intellij.core.CoreFileTypeRegistry import com.intellij.ide.highlighter.ArchiveFileType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.fileChooser.impl.FileChooserUtil import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.util.Getter import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.local.CoreLocalFileSystem import com.intellij.util.SmartList import java.io.File internal class PathChooserDialogHelper(private val descriptor: FileChooserDescriptor) { init { if (FileTypeRegistry.ourInstanceGetter == null) { val registry = CoreFileTypeRegistry() registry.registerFileType(ArchiveFileType.INSTANCE, "zip") registry.registerFileType(ArchiveFileType.INSTANCE, "jar") FileTypeRegistry.ourInstanceGetter = Getter { registry } } } private val localFileSystem by lazy { val app = ApplicationManager.getApplication() if (app == null) CoreLocalFileSystem() else LocalFileSystem.getInstance() } fun getChosenFiles(files: Array<File>): List<VirtualFile> { val virtualFiles = files.mapNotNullTo(SmartList()) { val virtualFile = fileToVirtualFile(it) if (virtualFile != null && virtualFile.isValid) { virtualFile } else { null } } return FileChooserUtil.getChosenFiles(descriptor, virtualFiles) } fun fileToVirtualFile(file: File): VirtualFile? { return localFileSystem.refreshAndFindFileByPath(FileUtilRt.toSystemIndependentName(file.absolutePath)) } }
apache-2.0
5e671f0daca7c08f37600955d0d1d105
36.392157
140
0.769675
4.717822
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/ui/colorpicker/GraphicalColorPipette.kt
3
10454
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ui.colorpicker import com.intellij.icons.AllIcons import com.intellij.ide.IdeEventQueue import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.WindowManager import com.intellij.util.ui.ImageUtil import com.intellij.util.ui.JBUI import java.awt.* import java.awt.event.KeyAdapter import java.awt.event.KeyEvent import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.awt.image.BufferedImage import java.awt.image.ImageObserver import javax.swing.* /** * The size of captured screen area. It is same as the number of pixels are caught.<br> * The selected pixel is the central one, so this value must be odd. */ private const val SCREEN_CAPTURE_SIZE = 11 /** * The size of zoomed rectangle which shows the captured screen. */ private const val ZOOM_RECTANGLE_SIZE = 64 private val PIPETTE_BORDER_COLOR = Color.BLACK private val INDICATOR_BOUND_COLOR = Color.RED /** * The left/top bound of selected pixel in zoomed rectangle. */ private const val INDICATOR_BOUND_START = ZOOM_RECTANGLE_SIZE * (SCREEN_CAPTURE_SIZE / 2) / SCREEN_CAPTURE_SIZE /** * The width/height of selected pixel in zoomed rectangle. */ private const val INDICATOR_BOUND_SIZE = ZOOM_RECTANGLE_SIZE * (SCREEN_CAPTURE_SIZE / 2 + 1) / SCREEN_CAPTURE_SIZE - INDICATOR_BOUND_START private val TRANSPARENT_COLOR = Color(0, true) private const val CURSOR_NAME = "GraphicalColorPicker" /** * Duration of updating the color of current hovered pixel. The unit is millisecond. */ private const val DURATION_COLOR_UPDATING = 33 /** * The [ColorPipette] which picks up the color from monitor. */ open class GraphicalColorPipette(private val parent: JComponent) : ColorPipette { override val icon: Icon = AllIcons.Ide.Pipette override val rolloverIcon: Icon = AllIcons.Ide.Pipette_rollover override val pressedIcon: Icon = AllIcons.Ide.Pipette_rollover override fun pick(callback: ColorPipette.Callback) = PickerDialog(parent, callback).pick() } class GraphicalColorPipetteProvider : ColorPipetteProvider { override fun createPipette(owner: JComponent): ColorPipette = GraphicalColorPipette(owner) } private class PickerDialog(val parent: JComponent, val callback: ColorPipette.Callback) : ImageObserver { private val timer = Timer(DURATION_COLOR_UPDATING) { updatePipette() } private val center = Point(ZOOM_RECTANGLE_SIZE / 2, ZOOM_RECTANGLE_SIZE / 2) private val zoomRect = Rectangle(0, 0, ZOOM_RECTANGLE_SIZE, ZOOM_RECTANGLE_SIZE) private val captureRect = Rectangle() private var disposable = newDisposable() private fun newDisposable() = Disposer.newDisposable("Color Pipette") private val maskImage = ImageUtil.createImage(ZOOM_RECTANGLE_SIZE, ZOOM_RECTANGLE_SIZE, BufferedImage.TYPE_INT_ARGB) private val magnifierImage = ImageUtil.createImage(ZOOM_RECTANGLE_SIZE, ZOOM_RECTANGLE_SIZE, BufferedImage.TYPE_INT_ARGB) private val image: BufferedImage = let { val image = parent.graphicsConfiguration.createCompatibleImage(ZOOM_RECTANGLE_SIZE, ZOOM_RECTANGLE_SIZE, Transparency.TRANSLUCENT) val graphics2d = image.graphics as Graphics2D graphics2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR) graphics2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF) image } private val robot = Robot() private var previousColor: Color? = null private var previousLoc: Point? = null private val picker: Dialog = let { val owner = SwingUtilities.getWindowAncestor(parent) val pickerFrame = when (owner) { is Dialog -> JDialog(owner) is Frame -> JDialog(owner) else -> JDialog(JFrame()) } pickerFrame.isUndecorated = true pickerFrame.isAlwaysOnTop = true pickerFrame.size = Dimension(ZOOM_RECTANGLE_SIZE, ZOOM_RECTANGLE_SIZE) pickerFrame.defaultCloseOperation = WindowConstants.DISPOSE_ON_CLOSE val rootPane = pickerFrame.rootPane rootPane.putClientProperty("Window.shadow", false) rootPane.border = JBUI.Borders.empty() val mouseAdapter = object : MouseAdapter() { override fun mouseReleased(e: MouseEvent) { e.consume() when { SwingUtilities.isLeftMouseButton(e) -> pickDone() SwingUtilities.isRightMouseButton(e) -> cancelPipette() else -> Unit } } override fun mouseMoved(e: MouseEvent) = updatePipette() } pickerFrame.addMouseListener(mouseAdapter) pickerFrame.addMouseMotionListener(mouseAdapter) pickerFrame.addKeyListener(object : KeyAdapter() { override fun keyPressed(e: KeyEvent) { when (e.keyCode) { KeyEvent.VK_ESCAPE -> cancelPipette() KeyEvent.VK_ENTER -> pickDone() } } }) pickerFrame } init { val maskG = maskImage.createGraphics() maskG.color = Color.BLUE maskG.fillRect(0, 0, ZOOM_RECTANGLE_SIZE, ZOOM_RECTANGLE_SIZE) maskG.color = Color.RED maskG.composite = AlphaComposite.SrcOut maskG.fillRect(0, 0, ZOOM_RECTANGLE_SIZE, ZOOM_RECTANGLE_SIZE) maskG.dispose() } fun pick() { if (Registry.`is`("ide.color.picker.new.pipette")) { timer.start() disposable = newDisposable() ApplicationManager.getApplication().invokeLater { IdeEventQueue.getInstance().addDispatcher(IdeEventQueue.EventDispatcher { if (it is MouseEvent) { if (it.clickCount > 0) { it.consume() when { SwingUtilities.isLeftMouseButton(it) -> pickDone() SwingUtilities.isRightMouseButton(it) -> cancelPipette() else -> Unit } } else if (it.id == MouseEvent.MOUSE_MOVED) { updatePipette(); } } if (it is KeyEvent && it.id == KeyEvent.KEY_PRESSED) { when (it.keyCode) { KeyEvent.VK_ESCAPE -> it.consume().also { cancelPipette() } KeyEvent.VK_ENTER -> it.consume().also { pickDone() } KeyEvent.VK_UP -> moveMouse(it, 0, -1) KeyEvent.VK_DOWN -> moveMouse(it, 0, +1) KeyEvent.VK_LEFT -> moveMouse(it, -1, 0) KeyEvent.VK_RIGHT -> moveMouse(it, +1, 0) } } false }, disposable) } } else { picker.isVisible = true timer.start() // it seems like it's the lowest value for opacity for mouse events to be processed correctly WindowManager.getInstance().setAlphaModeRatio(picker, if (SystemInfo.isMac) 0.95f else 0.99f) } } private fun moveMouse(e: KeyEvent, x: Int, y: Int) { val p = MouseInfo.getPointerInfo().location robot.mouseMove(p.x + x, p.y + y) e.consume() } override fun imageUpdate(img: Image, flags: Int, x: Int, y: Int, width: Int, height: Int) = false private fun cancelPipette() { timer.stop() picker.isVisible = false picker.dispose() Disposer.dispose(disposable) callback.cancel() } private fun pickDone() { timer.stop() val pointerInfo = MouseInfo.getPointerInfo() val location = pointerInfo.location val pickedColor = robot.getPixelColor(location.x, location.y) picker.isVisible = false Disposer.dispose(disposable) callback.picked(pickedColor) } private fun updatePipette() { if (Registry.`is`("ide.color.picker.new.pipette")) { val pointerInfo = MouseInfo.getPointerInfo() val mouseLoc = pointerInfo.location val pickedColor = robot.getPixelColor(mouseLoc.x, mouseLoc.y) if (previousLoc != mouseLoc || previousColor != pickedColor) { previousLoc = mouseLoc previousColor = pickedColor callback.update(pickedColor) } } else { if (picker.isShowing) { val pointerInfo = MouseInfo.getPointerInfo() val mouseLoc = pointerInfo.location picker.setLocation(mouseLoc.x - picker.width / 2, mouseLoc.y - picker.height / 2) val pickedColor = robot.getPixelColor(mouseLoc.x, mouseLoc.y) if (previousLoc != mouseLoc || previousColor != pickedColor) { previousLoc = mouseLoc previousColor = pickedColor val halfPixelNumber = SCREEN_CAPTURE_SIZE / 2 captureRect.setBounds(mouseLoc.x - halfPixelNumber, mouseLoc.y - halfPixelNumber, SCREEN_CAPTURE_SIZE, SCREEN_CAPTURE_SIZE) val capture = robot.createScreenCapture(captureRect) val graphics = image.graphics as Graphics2D // Clear the cursor graphics graphics.composite = AlphaComposite.Src graphics.color = TRANSPARENT_COLOR graphics.fillRect(0, 0, image.width, image.height) graphics.drawImage(capture, zoomRect.x, zoomRect.y, zoomRect.width, zoomRect.height, this) // cropping round image graphics.composite = AlphaComposite.DstOut graphics.drawImage(maskImage, zoomRect.x, zoomRect.y, zoomRect.width, zoomRect.height, this) // paint magnifier graphics.composite = AlphaComposite.SrcOver graphics.drawImage(magnifierImage, 0, 0, this) graphics.composite = AlphaComposite.SrcOver graphics.color = PIPETTE_BORDER_COLOR graphics.drawRect(0, 0, ZOOM_RECTANGLE_SIZE - 1, ZOOM_RECTANGLE_SIZE - 1) graphics.color = INDICATOR_BOUND_COLOR graphics.drawRect(INDICATOR_BOUND_START, INDICATOR_BOUND_START, INDICATOR_BOUND_SIZE, INDICATOR_BOUND_SIZE) picker.cursor = parent.toolkit.createCustomCursor(image, center, CURSOR_NAME) callback.update(pickedColor) } } } } }
apache-2.0
b40af7104b3d959e02cb35d36467b8fd
34.924399
138
0.690549
4.18998
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-test/common/src/TestScope.kt
1
13561
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.test import kotlinx.coroutines.* import kotlinx.coroutines.internal.* import kotlinx.coroutines.test.internal.* import kotlin.coroutines.* import kotlin.time.* /** * A coroutine scope that for launching test coroutines. * * The scope provides the following functionality: * * The [coroutineContext] includes a [coroutine dispatcher][TestDispatcher] that supports delay-skipping, using * a [TestCoroutineScheduler] for orchestrating the virtual time. * This scheduler is also available via the [testScheduler] property, and some helper extension * methods are defined to more conveniently interact with it: see [TestScope.currentTime], [TestScope.runCurrent], * [TestScope.advanceTimeBy], and [TestScope.advanceUntilIdle]. * * When inside [runTest], uncaught exceptions from the child coroutines of this scope will be reported at the end of * the test. * It is invalid for child coroutines to throw uncaught exceptions when outside the call to [TestScope.runTest]: * the only guarantee in this case is the best effort to deliver the exception. * * The usual way to access a [TestScope] is to call [runTest], but it can also be constructed manually, in order to * use it to initialize the components that participate in the test. * * #### Differences from the deprecated [TestCoroutineScope] * * * This doesn't provide an equivalent of [TestCoroutineScope.cleanupTestCoroutines], and so can't be used as a * standalone mechanism for writing tests: it does require that [runTest] is eventually called. * The reason for this is that a proper cleanup procedure that supports using non-test dispatchers and arbitrary * coroutine suspensions would be equivalent to [runTest], but would also be more error-prone, due to the potential * for forgetting to perform the cleanup. * * [TestCoroutineScope.advanceTimeBy] also calls [TestCoroutineScheduler.runCurrent] after advancing the virtual time. * * No support for dispatcher pausing, like [DelayController] allows. [TestCoroutineDispatcher], which supported * pausing, is deprecated; now, instead of pausing a dispatcher, one can use [withContext] to run a dispatcher that's * paused by default, like [StandardTestDispatcher]. * * No access to the list of unhandled exceptions. */ @ExperimentalCoroutinesApi public sealed interface TestScope : CoroutineScope { /** * The delay-skipping scheduler used by the test dispatchers running the code in this scope. */ @ExperimentalCoroutinesApi public val testScheduler: TestCoroutineScheduler /** * A scope for background work. * * This scope is automatically cancelled when the test finishes. * Additionally, while the coroutines in this scope are run as usual when * using [advanceTimeBy] and [runCurrent], [advanceUntilIdle] will stop advancing the virtual time * once only the coroutines in this scope are left unprocessed. * * Failures in coroutines in this scope do not terminate the test. * Instead, they are reported at the end of the test. * Likewise, failure in the [TestScope] itself will not affect its [backgroundScope], * because there's no parent-child relationship between them. * * A typical use case for this scope is to launch tasks that would outlive the tested code in * the production environment. * * In this example, the coroutine that continuously sends new elements to the channel will get * cancelled: * ``` * @Test * fun testExampleBackgroundJob() = runTest { * val channel = Channel<Int>() * backgroundScope.launch { * var i = 0 * while (true) { * channel.send(i++) * } * } * repeat(100) { * assertEquals(it, channel.receive()) * } * } * ``` */ @ExperimentalCoroutinesApi public val backgroundScope: CoroutineScope } /** * The current virtual time on [testScheduler][TestScope.testScheduler]. * @see TestCoroutineScheduler.currentTime */ @ExperimentalCoroutinesApi public val TestScope.currentTime: Long get() = testScheduler.currentTime /** * Advances the [testScheduler][TestScope.testScheduler] to the point where there are no tasks remaining. * @see TestCoroutineScheduler.advanceUntilIdle */ @ExperimentalCoroutinesApi public fun TestScope.advanceUntilIdle(): Unit = testScheduler.advanceUntilIdle() /** * Run any tasks that are pending at the current virtual time, according to * the [testScheduler][TestScope.testScheduler]. * * @see TestCoroutineScheduler.runCurrent */ @ExperimentalCoroutinesApi public fun TestScope.runCurrent(): Unit = testScheduler.runCurrent() /** * Moves the virtual clock of this dispatcher forward by [the specified amount][delayTimeMillis], running the * scheduled tasks in the meantime. * * In contrast with `TestCoroutineScope.advanceTimeBy`, this function does not run the tasks scheduled at the moment * [currentTime] + [delayTimeMillis]. * * @throws IllegalStateException if passed a negative [delay][delayTimeMillis]. * @see TestCoroutineScheduler.advanceTimeBy */ @ExperimentalCoroutinesApi public fun TestScope.advanceTimeBy(delayTimeMillis: Long): Unit = testScheduler.advanceTimeBy(delayTimeMillis) /** * The [test scheduler][TestScope.testScheduler] as a [TimeSource]. * @see TestCoroutineScheduler.timeSource */ @ExperimentalCoroutinesApi @ExperimentalTime public val TestScope.testTimeSource: TimeSource get() = testScheduler.timeSource /** * Creates a [TestScope]. * * It ensures that all the test module machinery is properly initialized. * * If [context] doesn't provide a [TestCoroutineScheduler] for orchestrating the virtual time used for delay-skipping, * a new one is created, unless either * - a [TestDispatcher] is provided, in which case [TestDispatcher.scheduler] is used; * - at the moment of the creation of the scope, [Dispatchers.Main] is delegated to a [TestDispatcher], in which case * its [TestCoroutineScheduler] is used. * * If [context] doesn't have a [TestDispatcher], a [StandardTestDispatcher] is created. * * A [CoroutineExceptionHandler] is created that makes [TestCoroutineScope.cleanupTestCoroutines] throw if there were * any uncaught exceptions, or forwards the exceptions further in a platform-specific manner if the cleanup was * already performed when an exception happened. Passing a [CoroutineExceptionHandler] is illegal, unless it's an * [UncaughtExceptionCaptor], in which case the behavior is preserved for the time being for backward compatibility. * If you need to have a specific [CoroutineExceptionHandler], please pass it to [launch] on an already-created * [TestCoroutineScope] and share your use case at * [our issue tracker](https://github.com/Kotlin/kotlinx.coroutines/issues). * * If [context] provides a [Job], that job is used as a parent for the new scope. * * @throws IllegalArgumentException if [context] has both [TestCoroutineScheduler] and a [TestDispatcher] linked to a * different scheduler. * @throws IllegalArgumentException if [context] has a [ContinuationInterceptor] that is not a [TestDispatcher]. * @throws IllegalArgumentException if [context] has an [CoroutineExceptionHandler] that is not an * [UncaughtExceptionCaptor]. */ @ExperimentalCoroutinesApi @Suppress("FunctionName") public fun TestScope(context: CoroutineContext = EmptyCoroutineContext): TestScope { val ctxWithDispatcher = context.withDelaySkipping() var scope: TestScopeImpl? = null val exceptionHandler = when (ctxWithDispatcher[CoroutineExceptionHandler]) { null -> CoroutineExceptionHandler { _, exception -> scope!!.reportException(exception) } else -> throw IllegalArgumentException( "A CoroutineExceptionHandler was passed to TestScope. " + "Please pass it as an argument to a `launch` or `async` block on an already-created scope " + "if uncaught exceptions require special treatment." ) } return TestScopeImpl(ctxWithDispatcher + exceptionHandler).also { scope = it } } /** * Adds a [TestDispatcher] and a [TestCoroutineScheduler] to the context if there aren't any already. * * @throws IllegalArgumentException if both a [TestCoroutineScheduler] and a [TestDispatcher] are passed. * @throws IllegalArgumentException if a [ContinuationInterceptor] is passed that is not a [TestDispatcher]. */ internal fun CoroutineContext.withDelaySkipping(): CoroutineContext { val dispatcher: TestDispatcher = when (val dispatcher = get(ContinuationInterceptor)) { is TestDispatcher -> { val ctxScheduler = get(TestCoroutineScheduler) if (ctxScheduler != null) { require(dispatcher.scheduler === ctxScheduler) { "Both a TestCoroutineScheduler $ctxScheduler and TestDispatcher $dispatcher linked to " + "another scheduler were passed." } } dispatcher } null -> StandardTestDispatcher(get(TestCoroutineScheduler)) else -> throw IllegalArgumentException("Dispatcher must implement TestDispatcher: $dispatcher") } return this + dispatcher + dispatcher.scheduler } internal class TestScopeImpl(context: CoroutineContext) : AbstractCoroutine<Unit>(context, initParentJob = true, active = true), TestScope { override val testScheduler get() = context[TestCoroutineScheduler]!! private var entered = false private var finished = false private val uncaughtExceptions = mutableListOf<Throwable>() private val lock = SynchronizedObject() override val backgroundScope: CoroutineScope = CoroutineScope(coroutineContext + BackgroundWork + ReportingSupervisorJob { if (it !is CancellationException) reportException(it) }) /** Called upon entry to [runTest]. Will throw if called more than once. */ fun enter() { val exceptions = synchronized(lock) { if (entered) throw IllegalStateException("Only a single call to `runTest` can be performed during one test.") entered = true check(!finished) uncaughtExceptions } if (exceptions.isNotEmpty()) { throw UncaughtExceptionsBeforeTest().apply { for (e in exceptions) addSuppressed(e) } } } /** Called at the end of the test. May only be called once. */ fun leave(): List<Throwable> { val exceptions = synchronized(lock) { check(entered && !finished) finished = true uncaughtExceptions } val activeJobs = children.filter { it.isActive }.toList() // only non-empty if used with `runBlockingTest` if (exceptions.isEmpty()) { if (activeJobs.isNotEmpty()) throw UncompletedCoroutinesError( "Active jobs found during the tear-down. " + "Ensure that all coroutines are completed or cancelled by your test. " + "The active jobs: $activeJobs" ) if (!testScheduler.isIdle()) throw UncompletedCoroutinesError( "Unfinished coroutines found during the tear-down. " + "Ensure that all coroutines are completed or cancelled by your test." ) } return exceptions } /** Stores an exception to report after [runTest], or rethrows it if not inside [runTest]. */ fun reportException(throwable: Throwable) { synchronized(lock) { if (finished) { throw throwable } else { @Suppress("INVISIBLE_MEMBER") for (existingThrowable in uncaughtExceptions) { // avoid reporting exceptions that already were reported. if (unwrap(throwable) == unwrap(existingThrowable)) return } uncaughtExceptions.add(throwable) if (!entered) throw UncaughtExceptionsBeforeTest().apply { addSuppressed(throwable) } } } } /** Throws an exception if the coroutine is not completing. */ fun tryGetCompletionCause(): Throwable? = completionCause override fun toString(): String = "TestScope[" + (if (finished) "test ended" else if (entered) "test started" else "test not started") + "]" } /** Use the knowledge that any [TestScope] that we receive is necessarily a [TestScopeImpl]. */ @Suppress("NO_ELSE_IN_WHEN") // TODO: a problem with `sealed` in MPP not allowing total pattern-matching internal fun TestScope.asSpecificImplementation(): TestScopeImpl = when (this) { is TestScopeImpl -> this } internal class UncaughtExceptionsBeforeTest : IllegalStateException( "There were uncaught exceptions in coroutines launched from TestScope before the test started. Please avoid this," + " as such exceptions are also reported in a platform-dependent manner so that they are not lost." ) /** * Thrown when a test has completed and there are tasks that are not completed or cancelled. */ @ExperimentalCoroutinesApi internal class UncompletedCoroutinesError(message: String) : AssertionError(message)
apache-2.0
50c5b28a2f005271cfae8139bf9938c9
44.506711
120
0.697367
4.963763
false
true
false
false
zdary/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/util/HtmlEditorPane.kt
1
3667
package com.jetbrains.packagesearch.intellij.plugin.ui.util import com.intellij.ide.ui.AntialiasingType import com.intellij.ui.HyperlinkAdapter import com.intellij.util.ui.GraphicsUtil import com.intellij.util.ui.JBHtmlEditorKit import com.intellij.util.ui.JBUI import org.jetbrains.annotations.Nls import javax.swing.JEditorPane import javax.swing.SizeRequirements import javax.swing.event.HyperlinkEvent import javax.swing.event.HyperlinkListener import javax.swing.text.DefaultCaret import javax.swing.text.Element import javax.swing.text.ParagraphView import javax.swing.text.View import kotlin.math.max internal abstract class HtmlEditorPane : JEditorPane() { init { @Suppress("MagicNumber") // UI code editorKit = object : JBHtmlEditorKit(false) { override fun getViewFactory() = HtmlEditorViewFactory() }.apply { //language=CSS styleSheet.addRule( """ |ul {padding-left: ${8.scaled()}px;} """.trimMargin() ) //language=CSS styleSheet.addRule( """ |a{color: ${JBUI.CurrentTheme.Link.linkColor().toCssHexColorString()};} |a:link{color: ${JBUI.CurrentTheme.Link.linkColor().toCssHexColorString()};} |a:visited{color: ${JBUI.CurrentTheme.Link.linkVisitedColor().toCssHexColorString()};} |a:active{color: ${JBUI.CurrentTheme.Link.linkPressedColor().toCssHexColorString()};} |a:hover{color: ${JBUI.CurrentTheme.Link.linkHoverColor().toCssHexColorString()};} """.trimMargin() ) } isEditable = false isOpaque = false addHyperlinkListener(ProxyingHyperlinkListener(::onLinkClicked)) margin = JBUI.emptyInsets() GraphicsUtil.setAntialiasingType(this, AntialiasingType.getAAHintForSwingComponent()) val caret = caret as DefaultCaret caret.updatePolicy = DefaultCaret.NEVER_UPDATE } protected fun setBody(@Nls body: String) { text = if (body.isEmpty()) { "" } else { "<html><body>$body</body></html>" } } protected open fun onLinkClicked(anchor: String) { // No-op by default } final override fun addHyperlinkListener(listener: HyperlinkListener?) { super.addHyperlinkListener(listener) } final override fun removeHyperlinkListener(listener: HyperlinkListener?) { super.removeHyperlinkListener(listener) } private class HtmlEditorViewFactory : JBHtmlEditorKit.JBHtmlFactory() { override fun create(elem: Element): View { val view = super.create(elem) if (view is ParagraphView) { return SizeAdjustedParagraphView(elem) } return view } } private class SizeAdjustedParagraphView(elem: Element) : ParagraphView(elem) { @Suppress("MagicNumber") // UI code override fun calculateMinorAxisRequirements(axis: Int, sizeRequirements: SizeRequirements?) = (sizeRequirements ?: SizeRequirements()).apply { minimum = layoutPool.getMinimumSpan(axis).toInt() preferred = max(minimum, layoutPool.getPreferredSpan(axis).toInt()) maximum = Integer.MAX_VALUE alignment = 0.5f } } private class ProxyingHyperlinkListener(private val callback: (anchor: String) -> Unit) : HyperlinkAdapter() { override fun hyperlinkActivated(e: HyperlinkEvent) { callback(e.description) } } }
apache-2.0
df34c025c60fafd558d1536e76ae92db
34.259615
114
0.636215
4.762338
false
false
false
false
leafclick/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/GHPRDataLoaderImpl.kt
1
1839
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.data import com.google.common.cache.CacheBuilder import com.intellij.openapi.Disposable import com.intellij.openapi.application.runInEdt import com.intellij.util.EventDispatcher import org.jetbrains.annotations.CalledInAwt import java.util.* internal class GHPRDataLoaderImpl(private val dataProviderFactory: (Long) -> GHPRDataProvider) : GHPRDataLoader { private var isDisposed = false private val cache = CacheBuilder.newBuilder() .removalListener<Long, GHPRDataProvider> { runInEdt { invalidationEventDispatcher.multicaster.providerChanged(it.key) } } .maximumSize(5) .build<Long, GHPRDataProvider>() private val invalidationEventDispatcher = EventDispatcher.create(DataInvalidatedListener::class.java) @CalledInAwt override fun invalidateAllData() { cache.invalidateAll() } @CalledInAwt override fun getDataProvider(number: Long): GHPRDataProvider { if (isDisposed) throw IllegalStateException("Already disposed") return cache.get(number) { dataProviderFactory(number) } } @CalledInAwt override fun findDataProvider(number: Long): GHPRDataProvider? = cache.getIfPresent(number) override fun addInvalidationListener(disposable: Disposable, listener: (Long) -> Unit) = invalidationEventDispatcher.addListener(object : DataInvalidatedListener { override fun providerChanged(pullRequestNumber: Long) { listener(pullRequestNumber) } }, disposable) override fun dispose() { invalidateAllData() isDisposed = true } private interface DataInvalidatedListener : EventListener { fun providerChanged(pullRequestNumber: Long) } }
apache-2.0
1a351cd380235c2ed14aaa963cf003ae
31.857143
140
0.765633
4.826772
false
false
false
false
faceofcat/Tesla-Core-Lib
src/main/kotlin/net/ndrei/teslacorelib/blocks/RegisteredBlock.kt
1
5742
package net.ndrei.teslacorelib.blocks import net.minecraft.block.Block import net.minecraft.block.ITileEntityProvider import net.minecraft.block.material.Material import net.minecraft.block.state.IBlockState import net.minecraft.client.renderer.block.model.ModelResourceLocation import net.minecraft.creativetab.CreativeTabs import net.minecraft.entity.EntityLivingBase import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.Item import net.minecraft.item.ItemBlock import net.minecraft.item.ItemStack import net.minecraft.item.crafting.IRecipe import net.minecraft.tileentity.TileEntity import net.minecraft.util.EnumFacing import net.minecraft.util.EnumHand import net.minecraft.util.ResourceLocation import net.minecraft.util.math.BlockPos import net.minecraft.world.World import net.minecraftforge.client.model.ModelLoader import net.minecraftforge.common.util.Constants import net.minecraftforge.fluids.capability.CapabilityFluidHandler import net.minecraftforge.fml.relauncher.Side import net.minecraftforge.fml.relauncher.SideOnly import net.minecraftforge.registries.IForgeRegistry import net.ndrei.teslacorelib.TeslaCoreLib import net.ndrei.teslacorelib.capabilities.TeslaCoreCapabilities import net.ndrei.teslacorelib.render.ISelfRegisteringRenderer import net.ndrei.teslacorelib.tileentities.SidedTileEntity /** * Created by CF on 2017-07-07. */ abstract class RegisteredBlock(modId: String, tab: CreativeTabs?, registryName: String, material: Material) : Block(material), ISelfRegisteringBlock, ISelfRegisteringRenderer { init { this.setRegistryName(modId, registryName) this.translationKey = "$modId.$registryName" if (tab != null) { this.creativeTab = tab } } //#region registration methods override fun registerBlock(registry: IForgeRegistry<Block>) { registry.register(this) } override fun registerItem(registry: IForgeRegistry<Item>) { val item = ItemBlock(this) item.registryName = this.registryName registry.register(item) } @Deprecated("One should really use JSON resources for recipes.", ReplaceWith("A JSON File!"), DeprecationLevel.WARNING) open fun registerRecipe(registry: (recipe: IRecipe) -> ResourceLocation) = this.recipes.forEach { registry(it) } @Deprecated("One should really use JSON resources for recipes.", ReplaceWith("A JSON File!"), DeprecationLevel.WARNING) protected open val recipe: IRecipe? get() = null @Deprecated("One should really use JSON resources for recipes.", ReplaceWith("A JSON File!"), DeprecationLevel.WARNING) protected open val recipes: List<IRecipe> get() { val recipe = this.recipe return if (recipe != null) listOf(recipe) else listOf() } @SideOnly(Side.CLIENT) override fun registerRenderer() { this.registerItemBlockRenderer() } @SideOnly(Side.CLIENT) protected open fun registerItemBlockRenderer() { ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(this), 0, ModelResourceLocation(this.registryName!!, "inventory") ) } //#endregion open fun createNewTileEntity(worldIn: World, meta: Int): TileEntity? = null override fun onBlockActivated(worldIn: World?, pos: BlockPos?, state: IBlockState?, playerIn: EntityPlayer?, hand: EnumHand?, facing: EnumFacing?, hitX: Float, hitY: Float, hitZ: Float): Boolean { if ((worldIn != null) && !worldIn.isRemote && (pos != null) && (playerIn != null) && (hand != null) && (facing != null)) { val te = worldIn.getTileEntity(pos) as? SidedTileEntity val bucket = playerIn.getHeldItem(hand) if (!bucket.isEmpty && bucket.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { if ((te != null) && te.handleBucket(playerIn, hand/*, side*/)) { return true } } } if (super.onBlockActivated(worldIn, pos, state, playerIn, hand, facing, hitX, hitY, hitZ)) { return true } if ((worldIn != null) && (pos != null) && !worldIn.isRemote) { val te = worldIn.getTileEntity(pos) if ((te != null) && te.hasCapability(TeslaCoreCapabilities.CAPABILITY_GUI_CONTAINER, null)) { playerIn!!.openGui(TeslaCoreLib, 42, worldIn, pos.x, pos.y, pos.z) } } return true } override fun onBlockPlacedBy(world: World?, pos: BlockPos?, state: IBlockState?, placer: EntityLivingBase?, stack: ItemStack?) { if ((stack != null) && !stack.isEmpty && stack.hasTagCompound() && (this is ITileEntityProvider) && (world != null)) { val nbt = stack.tagCompound if (nbt != null && nbt.hasKey("tileentity", Constants.NBT.TAG_COMPOUND)) { val teNBT = nbt.getCompoundTag("tileentity") val teMeta = if (nbt.hasKey("te_blockstate_meta", Constants.NBT.TAG_INT)) nbt.getInteger("te_blockstate_meta") else 0 try { val te = this.createNewTileEntity(world, teMeta) if (te != null) { te.deserializeNBT(teNBT) world.setTileEntity(pos, te) } } catch (t: Throwable) { TeslaCoreLib.logger.error(t) } } } super.onBlockPlacedBy(world, pos, state, placer, stack) } override fun breakBlock(worldIn: World, pos: BlockPos, state: IBlockState) { (worldIn.getTileEntity(pos) as? SidedTileEntity)?.onBlockBroken() super.breakBlock(worldIn, pos, state) } }
mit
b2ec5ee388fdd612095889809837dca3
41.533333
200
0.67224
4.549921
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/bridges/fakeCovariantOverride.kt
4
307
// KT-4145 interface A { fun foo(): Any } open class B { fun foo(): String = "A" } open class C: B(), A fun box(): String { val a: A = C() if (a.foo() != "A") return "Fail 1" if ((a as B).foo() != "A") return "Fail 2" if ((a as C).foo() != "A") return "Fail 3" return "OK" }
apache-2.0
a6d7d8cb4da9cebde1ee50ae441295c9
15.157895
46
0.47557
2.601695
false
false
false
false
blokadaorg/blokada
android5/app/src/libre/kotlin/ui/PacksViewModel.kt
1
6237
/* * This file is part of Blokada. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * Copyright © 2021 Blocka AB. All rights reserved. * * @author Karol Gusak ([email protected]) */ package ui import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.map import androidx.lifecycle.viewModelScope import engine.EngineService import kotlinx.coroutines.delay import kotlinx.coroutines.launch import model.* import org.blokada.R import service.AlertDialogService import service.BlocklistService import service.PersistenceService import ui.utils.cause import ui.utils.now import utils.FlavorSpecific import utils.Logger import kotlin.random.Random class PacksViewModel : ViewModel(), FlavorSpecific { enum class Filter { HIGHLIGHTS, ACTIVE, ALL } private val log = Logger("Pack") private val persistence = PersistenceService private val engine = EngineService private val blocklist = BlocklistService private val alert = AlertDialogService private val activeTags = listOf("official") private var filter = Filter.HIGHLIGHTS private val _packs = MutableLiveData<Packs>() val packs = _packs.map { applyFilters(it.packs) } init { viewModelScope.launch { _packs.value = persistence.load(Packs::class) } } suspend fun setup() { viewModelScope.launch { delay(3000) // Let the app start up and not block our download // Refresh every 2-3 days but only on app fresh start if (_packs.value?.lastRefreshMillis ?: 0 < (now() - (2 * 86400 + Random.nextInt(86400)))) { try { log.w("Packs are stale, re-downloading") // Also include urls of any active pack _packs.value?.let { packs -> val urls = packs.packs.filter { it.status.installed }.flatMap { it.getUrls() }.distinct() blocklist.downloadAll(urls, force = true) blocklist.mergeAll(urls) engine.reloadBlockLists() persistence.save(packs.copy(lastRefreshMillis = now())) } } catch (ex: Throwable) { log.e("Could not re-download packs".cause(ex)) } } }.join() } fun get(packId: String): Pack? { return _packs.value?.packs?.firstOrNull { it.id == packId } } fun filter(filter: Filter) { this.filter = filter updateLiveData() } fun getFilter() = filter fun changeConfig(pack: Pack, config: PackConfig) { val updated = pack.changeStatus(installed = false, config = config) updatePack(updated) install(updated) } fun install(pack: Pack) { viewModelScope.launch { updatePack(pack.changeStatus(installing = true, installed = true)) try { var urls = pack.getUrls() // Also include urls of any active pack _packs.value?.let { packs -> val moreUrls = packs.packs.filter { it.status.installed }.flatMap { it.getUrls() } urls = (urls + moreUrls).distinct() } blocklist.downloadAll(urls) blocklist.mergeAll(urls) engine.reloadBlockLists() updatePack(pack.changeStatus(installing = false, installed = true)) } catch (ex: Throwable) { log.e("Could not install pack".cause(ex)) updatePack(pack.changeStatus(installing = false, installed = false)) alert.showAlert(R.string.error_pack_install) } } } fun uninstall(pack: Pack) { viewModelScope.launch { updatePack(pack.changeStatus(installing = true, installed = false)) try { // Uninstall any downloaded sources for this pack // We get all possible sources because user might have changed config and only then decided to uninstall val urls = pack.sources.flatMap { it.urls } blocklist.removeAll(urls) // Include urls of any active pack _packs.value?.let { packs -> val urls = packs.packs.filter { it.status.installed && it.id != pack.id } .flatMap { it.getUrls() } blocklist.downloadAll(urls) blocklist.mergeAll(urls) } engine.reloadBlockLists() updatePack(pack.changeStatus(installing = false, installed = false)) } catch (ex: Throwable) { log.e("Could not uninstall pack".cause(ex)) updatePack(pack.changeStatus(installing = false, installed = false)) alert.showAlert(R.string.error_pack_install) } } } private fun updatePack(pack: Pack) { viewModelScope.launch { _packs.value?.let { current -> val new = current.replace(pack) persistence.save(new) _packs.value = new } } } private fun updateLiveData() { viewModelScope.launch { // This will cause to emit new event and to refresh the public LiveData _packs.value = _packs.value } } private fun applyFilters(allPacks: List<Pack>): List<Pack> { return when (filter) { Filter.ACTIVE -> { allPacks.filter { pack -> pack.status.installed } } Filter.ALL -> { allPacks.filter { pack -> activeTags.intersect(pack.tags).isEmpty() != true } } else -> { allPacks.filter { pack -> pack.tags.contains(Pack.recommended) /* && !pack.status.installed */ } } } } }
mpl-2.0
688d99fbc3835c3afca2800d289feb64
32.891304
120
0.561899
4.578561
false
false
false
false
smmribeiro/intellij-community
platform/diff-impl/tests/testSrc/com/intellij/diff/tools/fragmented/UnifiedFragmentBuilderAutoTest.kt
13
5494
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff.tools.fragmented import com.intellij.diff.DiffTestCase import com.intellij.diff.comparison.ComparisonPolicy import com.intellij.diff.util.DiffUtil import com.intellij.diff.util.LineRange import com.intellij.diff.util.Side import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.progress.DumbProgressIndicator import com.intellij.openapi.util.text.StringUtil class UnifiedFragmentBuilderAutoTest : DiffTestCase() { fun test() { doTest(System.currentTimeMillis(), 30, 30) } fun doTest(seed: Long, runs: Int, maxLength: Int) { doAutoTest(seed, runs) { debugData -> debugData.put("MaxLength", maxLength) val text1 = DocumentImpl(generateText(maxLength)) val text2 = DocumentImpl(generateText(maxLength)) debugData.put("Text1", textToReadableFormat(text1.charsSequence)) debugData.put("Text2", textToReadableFormat(text2.charsSequence)) for (side in Side.values()) { for (comparisonPolicy in ComparisonPolicy.values()) { debugData.put("Policy", comparisonPolicy) debugData.put("Current side", side) doTest(text1, text2, comparisonPolicy, side) } } } } fun doTest(document1: Document, document2: Document, policy: ComparisonPolicy, masterSide: Side) { val sequence1 = document1.charsSequence val sequence2 = document2.charsSequence val fragments = MANAGER.compareLinesInner(sequence1, sequence2, policy, DumbProgressIndicator.INSTANCE) val builder = UnifiedFragmentBuilder(fragments, document1, document2, masterSide) builder.exec() val ignoreWhitespaces = policy !== ComparisonPolicy.DEFAULT val text = builder.text val changes = builder.changes val convertor1 = builder.convertor1 val convertor2 = builder.convertor2 val changedLines = builder.changedLines val ranges = builder.ranges val document = DocumentImpl(text) // both documents - before and after - should be subsequence of result text. assertTrue(isSubsequence(text, sequence1, ignoreWhitespaces)) assertTrue(isSubsequence(text, sequence2, ignoreWhitespaces)) // all changes should be inside ChangedLines for (fragment in fragments) { val startLine1 = fragment.startLine1 val endLine1 = fragment.endLine1 val startLine2 = fragment.startLine2 val endLine2 = fragment.endLine2 for (i in startLine1 until endLine1) { val targetLine = convertor1.convertInv(i) assertTrue(targetLine != -1) assertTrue(isLineChanged(targetLine, changedLines)) } for (i in startLine2 until endLine2) { val targetLine = convertor2.convertInv(i) assertTrue(targetLine != -1) assertTrue(isLineChanged(targetLine, changedLines)) } } // changed fragments and changed blocks should have same content assertEquals(changes.size, fragments.size) for (i in fragments.indices) { val fragment = fragments[i] val block = changes[i] val fragment1 = sequence1.subSequence(fragment.startOffset1, fragment.endOffset1) val fragment2 = sequence2.subSequence(fragment.startOffset2, fragment.endOffset2) val block1 = DiffUtil.getLinesContent(document, block.deletedRange.start, block.deletedRange.end) val block2 = DiffUtil.getLinesContent(document, block.insertedRange.start, block.insertedRange.end) assertEqualsCharSequences(fragment1, block1, ignoreWhitespaces, true) assertEqualsCharSequences(fragment2, block2, ignoreWhitespaces, true) } // ranges should have exact same content for (range in ranges) { val sideSequence = range.side.select(sequence1, sequence2)!! val baseRange = text.subSequence(range.base.startOffset, range.base.endOffset) val sideRange = sideSequence.subSequence(range.changed.startOffset, range.changed.endOffset) assertTrue(StringUtil.equals(baseRange, sideRange)) } } private fun isSubsequence(text: CharSequence, sequence: CharSequence, ignoreWhitespaces: Boolean): Boolean { var index1 = 0 var index2 = 0 while (index2 < sequence.length) { val c2 = sequence[index2] if (c2 == '\n' || (StringUtil.isWhiteSpace(c2) && ignoreWhitespaces)) { index2++ continue } assertTrue(index1 < text.length) val c1 = text[index1] if (c1 == '\n' || (StringUtil.isWhiteSpace(c1) && ignoreWhitespaces)) { index1++ continue } if (c1 == c2) { index1++ index2++ } else { index1++ } } return true } private fun isLineChanged(line: Int, changedLines: List<LineRange>): Boolean { for (changedLine in changedLines) { if (changedLine.start <= line && changedLine.end > line) return true } return false } }
apache-2.0
a71cb14866b46d2d9f38dc65bcfb702f
34.217949
110
0.705861
4.30902
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspections/unusedSymbol/function/membersOfAnonymousInFunction.kt
13
580
fun main(args: Array<String>) { val localObject = object { fun f() { } val p = 5 } localObject.f() localObject.p fun localObject2() = object { fun f() { } @Suppress("unused") fun fNoWarn() {} val p = 5 } @Suppress("unused") fun localObject3() = object { fun fNoWarn() {} } localObject2().f() localObject2().p val a = object { val b = object { val c = object { val d = 5 } } } a.b.c.d }
apache-2.0
c9ca0adff537f6f4317c5584a4a71604
13.170732
33
0.412069
3.766234
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/scopeFunctions/letToRun/qualifyThisNoConflict.kt
9
261
// WITH_STDLIB class C { fun foo(s: String, s2: String = ""): String = "c" val bar = "C" } class D { fun baz(s: String): String = "d" val quux = "D" val x = C().<caret>let { it.foo(baz(it.foo(quux + it.bar)), baz(it.bar)) } }
apache-2.0
ca0f1284074e99d03ca5393a629b3faf
16.4
55
0.490421
2.61
false
false
false
false
smmribeiro/intellij-community
plugins/ide-features-trainer/src/training/dsl/TaskContext.kt
1
11815
// 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 training.dsl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.ui.tree.TreeVisitor import com.intellij.util.ui.tree.TreeUtil import org.intellij.lang.annotations.Language import org.jetbrains.annotations.Nls import training.learn.LearnBundle import training.ui.LearningUiHighlightingManager import training.ui.LearningUiManager import java.awt.Component import java.awt.Rectangle import java.util.concurrent.CompletableFuture import java.util.concurrent.Future import javax.swing.Icon import javax.swing.JList import javax.swing.JTree import javax.swing.tree.TreePath @LearningDsl abstract class TaskContext : LearningDslBase { abstract val project: Project open val taskId: TaskId = TaskId(0) /** * This property can be set to the true if you want that the next task restore will jump over the current task. * Default `null` value is reserved for the future automatic transparent restore calculation. */ open var transparentRestore: Boolean? = null /** * Can be set to true iff you need to rehighlight the triggered element from the previous task when it will be shown again. * Note: that the rehighlighted element can be different from `previous?.ui` (it can become `null` or `!isValid` or `!isShowing`) * */ open var rehighlightPreviousUi: Boolean? = null /** * Can be set to true iff you need to propagate found highlighting component from the previous task as found from the current task. * So it may be used as `previous.ui`. And will be rehighlighted on restore. * * The default `null` means true now, but it may be changed later. */ open var propagateHighlighting: Boolean? = null /** Put here some initialization for the task */ open fun before(preparation: TaskRuntimeContext.() -> Unit) = Unit /** * @param [restoreId] where to restore, `null` means the previous task * @param [delayMillis] the delay before restore actions can be applied. * Delay may be needed to give pass condition take place. * It is a hack solution because of possible race conditions. * @param [checkByTimer] Check by timer may be useful in UI detection tasks (in submenus for example). * @param [restoreRequired] returns true iff restore is needed */ open fun restoreState(restoreId: TaskId? = null, delayMillis: Int = 0, checkByTimer: Int? = null, restoreRequired: TaskRuntimeContext.() -> Boolean) = Unit /** Shortcut */ fun restoreByUi(restoreId: TaskId? = null, delayMillis: Int = 0, checkByTimer: Int? = null) { restoreState(restoreId, delayMillis, checkByTimer) { previous.ui?.isShowing?.not() ?: true } } /** Restore when timer is out. Is needed for chained tasks. */ open fun restoreByTimer(delayMillis: Int = 2000, restoreId: TaskId? = null) = Unit data class RestoreNotification(@Nls val message: String, @Nls val restoreLinkText: String = LearnBundle.message("learn.restore.default.link.text"), val callback: () -> Unit) open fun proposeRestore(restoreCheck: TaskRuntimeContext.() -> RestoreNotification?) = Unit open fun showWarning(@Language("HTML") @Nls text: String, restoreTaskWhenResolved: Boolean = false, warningRequired: TaskRuntimeContext.() -> Boolean) = Unit /** * Write a text to the learn panel (panel with a learning tasks). */ open fun text(@Language("HTML") @Nls text: String, useBalloon: LearningBalloonConfig? = null) = Unit /** Add an illustration */ fun illustration(icon: Icon): Unit = text("<illustration>${LearningUiManager.getIconIndex(icon)}</illustration>") /** Insert text in the current position */ open fun type(text: String) = Unit /** Write a text to the learn panel (panel with a learning tasks). */ open fun runtimeText(@Nls callback: RuntimeTextContext.() -> String?) = Unit /** Simply wait until an user perform particular action */ open fun trigger(actionId: String) = Unit /** Simply wait until an user perform actions */ open fun trigger(checkId: (String) -> Boolean) = Unit /** Trigger on actions start. Needs if you want to split long actions into several tasks. */ open fun triggerStart(actionId: String, checkState: TaskRuntimeContext.() -> Boolean = { true }) = Unit /** [actionIds] these actions required for the current task */ open fun triggers(vararg actionIds: String) = Unit /** An user need to rice an action which leads to necessary state change */ open fun <T : Any?> trigger(actionId: String, calculateState: TaskRuntimeContext.() -> T, checkState: TaskRuntimeContext.(T, T) -> Boolean) = Unit /** An user need to rice an action which leads to appropriate end state */ fun trigger(actionId: String, checkState: TaskRuntimeContext.() -> Boolean) { trigger(actionId, { }, { _, _ -> checkState() }) } /** * Check that IDE state is as expected * In some rare cases DSL could wish to complete a future by itself */ open fun stateCheck(checkState: TaskRuntimeContext.() -> Boolean): CompletableFuture<Boolean> = CompletableFuture() /** * Check that IDE state is fit * @return A feature with value associated with fit state */ open fun <T : Any> stateRequired(requiredState: TaskRuntimeContext.() -> T?): Future<T> = CompletableFuture() /** * Check that IDE state is as expected and check it by timer. * Need to consider merge this method with [stateCheck]. */ open fun timerCheck(delayMillis: Int = 200, checkState: TaskRuntimeContext.() -> Boolean): CompletableFuture<Boolean> = CompletableFuture() open fun addFutureStep(p: DoneStepContext.() -> Unit) = Unit open fun addStep(step: CompletableFuture<Boolean>) = Unit /** [action] What should be done to pass the current task */ open fun test(waitEditorToBeReady: Boolean = true, action: TaskTestContext.() -> Unit) = Unit fun triggerByFoundPathAndHighlight(highlightBorder: Boolean = true, highlightInside: Boolean = false, usePulsation: Boolean = false, clearPreviousHighlights: Boolean = true, checkPath: TaskRuntimeContext.(tree: JTree, path: TreePath) -> Boolean) { val options = LearningUiHighlightingManager.HighlightingOptions(highlightBorder, highlightInside, usePulsation, clearPreviousHighlights) triggerByFoundPathAndHighlight(options) { tree -> TreeUtil.visitVisibleRows(tree, TreeVisitor { path -> if (checkPath(tree, path)) TreeVisitor.Action.INTERRUPT else TreeVisitor.Action.CONTINUE }) } } // This method later can be converted to the public (But I'm not sure it will be ever needed in a such form) protected open fun triggerByFoundPathAndHighlight(options: LearningUiHighlightingManager.HighlightingOptions, checkTree: TaskRuntimeContext.(tree: JTree) -> TreePath?) = Unit inline fun <reified T : Component> triggerByPartOfComponent(highlightBorder: Boolean = true, highlightInside: Boolean = false, usePulsation: Boolean = false, clearPreviousHighlights: Boolean = true, noinline selector: ((candidates: Collection<T>) -> T?)? = null, crossinline rectangle: TaskRuntimeContext.(T) -> Rectangle?) { val componentClass = T::class.java @Suppress("DEPRECATION") triggerByFoundPathAndHighlightImpl(componentClass, highlightBorder, highlightInside, usePulsation, clearPreviousHighlights, selector) { rectangle(it) } } @Deprecated("Use inline version") open fun <T : Component> triggerByFoundPathAndHighlightImpl(componentClass: Class<T>, highlightBorder: Boolean, highlightInside: Boolean, usePulsation: Boolean, clearPreviousHighlights: Boolean, selector: ((candidates: Collection<T>) -> T?)?, rectangle: TaskRuntimeContext.(T) -> Rectangle?) = Unit fun triggerByListItemAndHighlight(highlightBorder: Boolean = true, highlightInside: Boolean = false, usePulsation: Boolean = false, clearPreviousHighlights: Boolean = true, checkList: TaskRuntimeContext.(item: Any) -> Boolean) { val options = LearningUiHighlightingManager.HighlightingOptions(highlightBorder, highlightInside, usePulsation, clearPreviousHighlights) triggerByFoundListItemAndHighlight(options) { ui: JList<*> -> LessonUtil.findItem(ui) { checkList(it) } } } // This method later can be converted to the public (But I'm not sure it will be ever needed in a such form protected open fun triggerByFoundListItemAndHighlight(options: LearningUiHighlightingManager.HighlightingOptions, checkList: TaskRuntimeContext.(list: JList<*>) -> Int?) = Unit inline fun <reified ComponentType : Component> triggerByUiComponentAndHighlight( highlightBorder: Boolean = true, highlightInside: Boolean = true, usePulsation: Boolean = false, clearPreviousHighlights: Boolean = true, noinline selector: ((candidates: Collection<ComponentType>) -> ComponentType?)? = null, crossinline finderFunction: TaskRuntimeContext.(ComponentType) -> Boolean ) { val componentClass = ComponentType::class.java @Suppress("DEPRECATION") triggerByUiComponentAndHighlightImpl(componentClass, highlightBorder, highlightInside, usePulsation, clearPreviousHighlights, selector) { finderFunction(it) } } @Deprecated("Use inline version") open fun <ComponentType : Component> triggerByUiComponentAndHighlightImpl(componentClass: Class<ComponentType>, highlightBorder: Boolean, highlightInside: Boolean, usePulsation: Boolean, clearPreviousHighlights: Boolean, selector: ((candidates: Collection<ComponentType>) -> ComponentType?)?, finderFunction: TaskRuntimeContext.(ComponentType) -> Boolean) = Unit open fun caret(position: LessonSamplePosition) = before { caret(position) } /** NOTE: [line] and [column] starts from 1 not from zero. So these parameters should be same as in editors. */ open fun caret(line: Int, column: Int) = before { caret(line, column) } class DoneStepContext(private val future: CompletableFuture<Boolean>, rt: TaskRuntimeContext) : TaskRuntimeContext(rt) { fun completeStep() { ApplicationManager.getApplication().assertIsDispatchThread() if (!future.isDone && !future.isCancelled) { future.complete(true) } } } data class TaskId(val idx: Int) companion object { val CaretRestoreProposal: String get() = LearnBundle.message("learn.restore.notification.caret.message") val ModificationRestoreProposal: String get() = LearnBundle.message("learn.restore.notification.modification.message") } }
apache-2.0
b74c013753e9a677cf9168f092e9a73e
48.852321
157
0.662294
5.23019
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ui/list/targetPopup.kt
1
2581
// 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. @file:JvmName("TargetPopup") package com.intellij.ui.list import com.intellij.ide.ui.UISettings import com.intellij.navigation.TargetPresentation import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.ui.popup.IPopupChooserBuilder import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.NlsContexts.PopupTitle import com.intellij.util.concurrency.annotations.RequiresEdt import java.util.function.Consumer import java.util.function.Function import javax.swing.ListCellRenderer @RequiresEdt fun <T> createTargetPopup( @PopupTitle title: String, items: List<T>, presentations: List<TargetPresentation>, processor: Consumer<in T> ): JBPopup { return createTargetPopup( title = title, items = items.zip(presentations), presentationProvider = { it.second }, processor = { processor.accept(it.first) } ) } @RequiresEdt fun <T> createTargetPopup( @PopupTitle title: String, items: List<T>, presentationProvider: Function<in T, out TargetPresentation>, processor: Consumer<in T> ): JBPopup { return buildTargetPopup(items, presentationProvider, processor) .setTitle(title) .createPopup() } @RequiresEdt fun <T> buildTargetPopup( items: List<T>, presentationProvider: Function<in T, out TargetPresentation>, processor: Consumer<in T> ): IPopupChooserBuilder<T> { require(items.size > 1) { "Attempted to build a target popup with ${items.size} elements" } return JBPopupFactory.getInstance() .createPopupChooserBuilder(items) .setRenderer(createTargetPresentationRenderer(presentationProvider)) .setFont(EditorUtil.getEditorFont()) .withHintUpdateSupply() .setNamerForFiltering { item: T -> presentationProvider.apply(item).speedSearchText() }.setItemChosenCallback(processor::accept) } fun <T> createTargetPresentationRenderer(presentationProvider: Function<in T, out TargetPresentation>): ListCellRenderer<T> { return if (UISettings.instance.showIconInQuickNavigation) { TargetPresentationRenderer(presentationProvider) } else { TargetPresentationMainRenderer(presentationProvider) } } private fun TargetPresentation.speedSearchText(): String { val presentableText = presentableText val containerText = containerText return if (containerText == null) presentableText else "$presentableText $containerText" }
apache-2.0
2414078cabbc0296fc1a735783df6580
32.519481
158
0.776443
4.266116
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/core/network/Client.kt
1
2034
package com.cout970.modeler.core.network import java.io.DataInputStream import java.io.DataOutputStream import java.net.Socket import java.util.* import kotlin.concurrent.thread /** * Created by cout970 on 2016/12/20. */ class Client() { var connection: Connection? = null fun sendPacket(packet: Packet) { if (connection == null) { throw IllegalStateException("Connection closed") } connection?.send(packet) } fun onPacket(packet: Packet) { println(packet) } fun connect(serverIp: String) { connection = Connection(this, Socket(serverIp, 6864)) connection!!.runThread() } override fun toString(): String { return "Client()" } data class Connection(val client: Client, val server: Socket) { private val packetQueue = ArrayDeque<Packet>() fun send(packet: Packet) { packetQueue.addLast(packet) } fun runThread() { thread { val outStream = DataOutputStream(server.outputStream) val inStream = DataInputStream(server.inputStream) while (!server.isClosed && server.isConnected) { while (!packetQueue.isEmpty()) { val packet = packetQueue.removeFirst() val data = packet.encode() outStream.writeInt(data.size) outStream.write(data) outStream.flush() } while (inStream.available() > 0) { val chunkSize = inStream.readInt() val packet = Packet().apply { val data = ByteArray(chunkSize) inStream.readFully(data) decode(data) } client.onPacket(packet) } Thread.yield() } } } } }
gpl-3.0
6ad2a742a7bb59934aa731ff0dd44281
27.661972
69
0.50885
5.283117
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ControlFlowWithEmptyBodyInspection.kt
1
4169
// 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.inspections import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.inspections.collections.isCalling import org.jetbrains.kotlin.idea.util.hasComments import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class ControlFlowWithEmptyBodyInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() { override fun visitIfExpression(expression: KtIfExpression) { val then = expression.then val elseKeyword = expression.elseKeyword val thenEmpty = then?.isEmptyBody() val elseEmpty = expression.`else`?.isEmptyBody() expression.ifKeyword.takeIf { thenEmpty != false && (elseEmpty != false || then?.hasComments() != true) }?.let { holder.registerProblem(expression, it) } elseKeyword?.takeIf { elseEmpty != false && (thenEmpty != false || expression.`else`?.hasComments() != true) }?.let { holder.registerProblem(expression, it) } } override fun visitWhenExpression(expression: KtWhenExpression) { if (expression.entries.isNotEmpty()) return holder.registerProblem(expression, expression.whenKeyword) } override fun visitForExpression(expression: KtForExpression) { if (expression.body.isEmptyBodyOrNull()) { holder.registerProblem(expression, expression.forKeyword) } } override fun visitWhileExpression(expression: KtWhileExpression) { val keyword = expression.allChildren.firstOrNull { it.node.elementType == KtTokens.WHILE_KEYWORD } ?: return val body = expression.body if (body?.hasComments() != true && body.isEmptyBodyOrNull()) { holder.registerProblem(expression, keyword) } } override fun visitDoWhileExpression(expression: KtDoWhileExpression) { val keyword = expression.allChildren.firstOrNull { it.node.elementType == KtTokens.DO_KEYWORD } ?: return val body = expression.body if (body?.hasComments() != true && body.isEmptyBodyOrNull()) { holder.registerProblem(expression, keyword) } } override fun visitCallExpression(expression: KtCallExpression) { val callee = expression.calleeExpression ?: return val body = when (val argument = expression.valueArguments.singleOrNull()?.getArgumentExpression()) { is KtLambdaExpression -> argument.bodyExpression is KtNamedFunction -> argument.bodyBlockExpression else -> return } if (body.isEmptyBodyOrNull() && expression.isCalling(controlFlowFunctions)) { holder.registerProblem(expression, callee) } } } private fun KtExpression?.isEmptyBodyOrNull(): Boolean = this?.isEmptyBody() ?: true private fun KtExpression.isEmptyBody(): Boolean = this is KtBlockExpression && statements.isEmpty() private fun ProblemsHolder.registerProblem(expression: KtExpression, keyword: PsiElement) { val keywordText = if (expression is KtDoWhileExpression) "do while" else keyword.text registerProblem( expression, keyword.textRange.shiftLeft(expression.startOffset), KotlinBundle.message("0.has.empty.body", keywordText) ) } companion object { private val controlFlowFunctions = listOf("kotlin.also").map { FqName(it) } } }
apache-2.0
f82ff7d4d62997970f1a44663c59a799
44.326087
158
0.675462
5.290609
false
false
false
false
leafclick/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/util/RecursionAwareSafePublicationLazy.kt
1
1858
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.util import com.intellij.openapi.util.RecursionManager import com.intellij.util.ObjectUtils import java.util.concurrent.atomic.AtomicReference /** * Same as [SafePublicationLazyImpl], but doesn't cache value in case of computation recursion occurred. */ class RecursionAwareSafePublicationLazy<T>(initializer: () -> T) : Lazy<T> { @Volatile private var initializer: (() -> T)? = initializer @Suppress("UNCHECKED_CAST") private val valueRef: AtomicReference<T> = AtomicReference(UNINITIALIZED_VALUE as T) override val value: T get() { val computedValue = valueRef.get() if (computedValue !== UNINITIALIZED_VALUE) { return computedValue } val initializerValue = initializer if (initializerValue === null) { // Some thread managed to clear the initializer => it managed to set the value. return valueRef.get() } val stamp = RecursionManager.markStack() val newValue = initializerValue() if (!stamp.mayCacheNow()) { // In case of recursion don't update [valueRef] and don't clear [initializer]. return newValue } if (!valueRef.compareAndSet(UNINITIALIZED_VALUE, newValue)) { // Some thread managed to set the value. return valueRef.get() } initializer = null return newValue } override fun isInitialized(): Boolean = valueRef.get() !== UNINITIALIZED_VALUE override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet." companion object { private val UNINITIALIZED_VALUE: Any = ObjectUtils.sentinel("RecursionAwareSafePublicationLazy initial value") } }
apache-2.0
88e2ecd07d0216c8df6c01e9558a3b86
33.407407
140
0.69591
4.727735
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/changePackage/PackageDirectoryMismatchInspection.kt
1
5907
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.move.changePackage import com.intellij.CommonBundle import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiManager import com.intellij.refactoring.PackageWrapper import com.intellij.refactoring.move.moveClassesOrPackages.AutocreatingSingleSourceRootMoveDestination import com.intellij.refactoring.move.moveClassesOrPackages.MoveClassesOrPackagesUtil import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil import com.intellij.refactoring.util.RefactoringMessageUtil import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.getFqNameByDirectory import org.jetbrains.kotlin.idea.core.getFqNameWithImplicitPrefix import org.jetbrains.kotlin.idea.core.packageMatchesDirectoryOrImplicit import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.refactoring.hasIdentifiersOnly import org.jetbrains.kotlin.idea.refactoring.isInjectedFragment import org.jetbrains.kotlin.idea.roots.getSuitableDestinationSourceRoots import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPackageDirective import org.jetbrains.kotlin.psi.packageDirectiveVisitor import org.jetbrains.kotlin.psi.psiUtil.startOffset class PackageDirectoryMismatchInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = packageDirectiveVisitor(fun(directive: KtPackageDirective) { val file = directive.containingKtFile if (file.textLength == 0 || file.isInjectedFragment || file.packageMatchesDirectoryOrImplicit()) return val fixes = mutableListOf<LocalQuickFix>() val qualifiedName = directive.qualifiedName val dirName = if (qualifiedName.isEmpty()) KotlinBundle.message("fix.move.file.to.package.dir.name.text") else "'${qualifiedName.replace('.', '/')}'" fixes += MoveFileToPackageFix(dirName) val fqNameByDirectory = file.getFqNameByDirectory() when { fqNameByDirectory.isRoot -> fixes += ChangePackageFix(KotlinBundle.message("fix.move.file.to.package.dir.name.text"), fqNameByDirectory) fqNameByDirectory.hasIdentifiersOnly() -> fixes += ChangePackageFix("'${fqNameByDirectory.asString()}'", fqNameByDirectory) } val fqNameWithImplicitPrefix = file.parent?.getFqNameWithImplicitPrefix() if (fqNameWithImplicitPrefix != null && fqNameWithImplicitPrefix != fqNameByDirectory) { fixes += ChangePackageFix("'${fqNameWithImplicitPrefix.asString()}'", fqNameWithImplicitPrefix) } val textRange = if (directive.textLength != 0) directive.textRange else file.declarations.firstOrNull()?.let { TextRange.from(it.startOffset, 1) } holder.registerProblem( file, textRange, KotlinBundle.message("text.package.directive.dont.match.file.location"), *fixes.toTypedArray() ) }) private class MoveFileToPackageFix(val dirName: String) : LocalQuickFix { override fun getFamilyName() = KotlinBundle.message("fix.move.file.to.package.family") override fun getName() = KotlinBundle.message("fix.move.file.to.package.text", dirName) override fun startInWriteAction() = false override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val file = descriptor.psiElement as? KtFile ?: return val directive = file.packageDirective ?: return val sourceRoots = getSuitableDestinationSourceRoots(project) val packageWrapper = PackageWrapper(PsiManager.getInstance(project), directive.qualifiedName) val fileToMove = directive.containingFile val chosenRoot = sourceRoots.singleOrNull() ?: MoveClassesOrPackagesUtil.chooseSourceRoot(packageWrapper, sourceRoots, fileToMove.containingDirectory) ?: return val targetDirFactory = AutocreatingSingleSourceRootMoveDestination(packageWrapper, chosenRoot) targetDirFactory.verify(fileToMove)?.let { Messages.showMessageDialog(project, it, CommonBundle.getErrorTitle(), Messages.getErrorIcon()) return } val targetDirectory = runWriteAction { targetDirFactory.getTargetDirectory(fileToMove) } ?: return RefactoringMessageUtil.checkCanCreateFile(targetDirectory, file.name)?.let { Messages.showMessageDialog(project, it, CommonBundle.getErrorTitle(), Messages.getErrorIcon()) return } runWriteAction { MoveFilesOrDirectoriesUtil.doMoveFile(file, targetDirectory) } } } private class ChangePackageFix(val packageName: String, val packageFqName: FqName) : LocalQuickFix { override fun getFamilyName() = KotlinBundle.message("fix.change.package.family") override fun getName() = KotlinBundle.message("fix.change.package.text", packageName) override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val file = descriptor.psiElement as? KtFile ?: return KotlinChangePackageRefactoring(file).run(packageFqName) } } }
apache-2.0
a979eabda582ea944ad2cb6c739a44e6
49.495726
158
0.728796
5.293011
false
false
false
false
kivensolo/UiUsingListView
module-Demo/src/main/java/com/zeke/demo/draw/paint/Paint3ComposeShaderView.kt
1
2148
package com.zeke.demo.draw.paint import android.content.Context import android.graphics.* import android.os.Build import android.util.AttributeSet import com.zeke.demo.R import com.zeke.demo.base.BasePracticeView import com.zeke.demo.model.CardItemConst /** * author: King.Z <br> * date: 2020/3/15 14:27 <br> * description: <br> * 混合着色器所谓混合,就是把两个 Shader 一起使用。 * Note: ComposeShader() 在硬件加速下是不支持两个相同类型的 Shader 的 */ class Paint3ComposeShaderView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : BasePracticeView(context, attrs, defStyleAttr) { init { setLayerType(LAYER_TYPE_HARDWARE, paint) } // 第一个 Shader:头像的 Bitmap var bitmap1: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.cat_m) private var shader1: BitmapShader = BitmapShader(bitmap1, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) private var shader2:LinearGradient = LinearGradient(380f, 45f, 600f, 550f, Color.parseColor("#5FCDDA"),Color.parseColor("#FED094"), Shader.TileMode.CLAMP) // 第二个 Shader:从上到下的线性渐变(由透明到黑色 // var bitmap2: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.arduino) // private var shader2: BitmapShader = BitmapShader(bitmap2, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) /** * shader1: dst * shader2: src */ private var composeShader: ComposeShader = ComposeShader(shader1, shader2, PorterDuff.Mode.SRC_OVER) override fun onDraw(canvas: Canvas) { super.onDraw(canvas) paint.shader = composeShader if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { canvas.saveLayer(0f,0f,1000f,600f,paint) } // 只画出circle范围内的Bitmap图像(bitmap为原尺寸大小),效果和Canvas.drawBitmap()一样 canvas.drawCircle(550f, 300f, 250f, paint) canvas.restore() } override fun getViewHeight(): Int { return CardItemConst.LARGE_HEIGHT } }
gpl-2.0
626b23ca4f603e6bdc704c05cefaddde
32.508475
110
0.697874
3.485009
false
false
false
false
siosio/intellij-community
plugins/kotlin/jvm-decompiler/src/org/jetbrains/kotlin/idea/jvmDecompiler/DecompileKotlinToJavaAction.kt
1
2434
// 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.jvmDecompiler import com.intellij.codeInsight.AttachSourcesProvider import com.intellij.ide.highlighter.JavaClassFileType import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.roots.LibraryOrderEntry import com.intellij.openapi.util.ActionCallback import com.intellij.psi.PsiFile import org.jetbrains.kotlin.idea.util.isRunningInCidrIde import org.jetbrains.kotlin.psi.KtFile class DecompileKotlinToJavaAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val binaryFile = getBinaryKotlinFile(e) ?: return KotlinJvmDecompilerFacadeImpl.showDecompiledCode(binaryFile) } override fun update(e: AnActionEvent) { if (isRunningInCidrIde) { e.presentation.isEnabledAndVisible = false } else { e.presentation.isEnabled = getBinaryKotlinFile(e) != null } } private fun getBinaryKotlinFile(e: AnActionEvent): KtFile? { val file = e.getData(CommonDataKeys.PSI_FILE) as? KtFile ?: return null if (!file.canBeDecompiledToJava()) return null return file } } fun KtFile.canBeDecompiledToJava() = isCompiled && virtualFile?.fileType == JavaClassFileType.INSTANCE // Add action to "Attach sources" notification panel class DecompileKotlinToJavaActionProvider : AttachSourcesProvider { override fun getActions( orderEntries: MutableList<LibraryOrderEntry>, psiFile: PsiFile ): Collection<AttachSourcesProvider.AttachSourcesAction> { if (psiFile !is KtFile || !psiFile.canBeDecompiledToJava()) return emptyList() return listOf(object : AttachSourcesProvider.AttachSourcesAction { override fun getName() = KotlinJvmDecompilerBundle.message("action.decompile.java.name") override fun perform(orderEntriesContainingFile: List<LibraryOrderEntry>?): ActionCallback { KotlinJvmDecompilerFacadeImpl.showDecompiledCode(psiFile) return ActionCallback.DONE } override fun getBusyText() = KotlinJvmDecompilerBundle.message("action.decompile.busy.text") }) } }
apache-2.0
628f223b9b91c07270eccd78e26184a7
38.901639
158
0.740756
4.88755
false
false
false
false
jwren/intellij-community
platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/ModuleBridgeImpl.kt
1
7476
// 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.workspaceModel.ide.impl.legacyBridge.module import com.intellij.configurationStore.RenameableStateStorageManager import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.ide.plugins.IdeaPluginDescriptorImpl import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.application.Application import com.intellij.openapi.application.WriteAction import com.intellij.openapi.components.PathMacroManager import com.intellij.openapi.components.impl.ModulePathMacroManager import com.intellij.openapi.module.Module import com.intellij.openapi.module.impl.ModuleImpl import com.intellij.openapi.project.Project import com.intellij.serviceContainer.PrecomputedExtensionModel import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener import com.intellij.workspaceModel.ide.WorkspaceModelTopics import com.intellij.workspaceModel.ide.impl.VirtualFileUrlBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleEntity import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.moduleMap import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge import com.intellij.workspaceModel.ide.toPath import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.impl.VersionedEntityStorageOnStorage import com.intellij.workspaceModel.storage.url.VirtualFileUrl internal class ModuleBridgeImpl( override var moduleEntityId: ModuleId, name: String, project: Project, virtualFileUrl: VirtualFileUrl?, override var entityStorage: VersionedEntityStorage, override var diff: WorkspaceEntityStorageDiffBuilder? ) : ModuleImpl(name, project, virtualFileUrl as? VirtualFileUrlBridge), ModuleBridge { init { // default project doesn't have modules if (!project.isDefault && !project.isDisposed) { val busConnection = project.messageBus.connect(this) WorkspaceModelTopics.getInstance(project).subscribeAfterModuleLoading(busConnection, object : WorkspaceModelChangeListener { override fun beforeChanged(event: VersionedStorageChange) { event.getChanges(ModuleEntity::class.java).filterIsInstance<EntityChange.Removed<ModuleEntity>>().forEach { if (it.entity.persistentId() != moduleEntityId) return@forEach if (event.storageBefore.moduleMap.getDataByEntity(it.entity) != this@ModuleBridgeImpl) return@forEach val currentStore = entityStorage.current val storage = if (currentStore is WorkspaceEntityStorageBuilder) currentStore.toStorage() else currentStore entityStorage = VersionedEntityStorageOnStorage(storage) assert(entityStorage.current.resolve(moduleEntityId) != null) { // If we ever get this assertion, replace use `event.storeBefore` instead of current // As it made in ArtifactBridge "Cannot resolve module $moduleEntityId. Current store: $currentStore" } } } }) } } override fun rename(newName: String, newModuleFileUrl: VirtualFileUrl?, notifyStorage: Boolean) { myImlFilePointer = newModuleFileUrl as VirtualFileUrlBridge rename(newName, notifyStorage) } override fun rename(newName: String, notifyStorage: Boolean) { moduleEntityId = moduleEntityId.copy(name = newName) super<ModuleImpl>.rename(newName, notifyStorage) } override fun onImlFileMoved(newModuleFileUrl: VirtualFileUrl) { myImlFilePointer = newModuleFileUrl as VirtualFileUrlBridge val imlPath = newModuleFileUrl.toPath() (store.storageManager as RenameableStateStorageManager).pathRenamed(imlPath, null) store.setPath(imlPath) (PathMacroManager.getInstance(this) as? ModulePathMacroManager)?.onImlFileMoved() } override fun registerComponents(modules: Sequence<IdeaPluginDescriptorImpl>, app: Application?, precomputedExtensionModel: PrecomputedExtensionModel?, listenerCallbacks: MutableList<in Runnable>?) { registerComponents(modules.find { it.pluginId == PluginManagerCore.CORE_ID }, modules, precomputedExtensionModel, app, listenerCallbacks) } override fun callCreateComponents() { createComponents(null) } override fun registerComponents(corePlugin: IdeaPluginDescriptor?, modules: Sequence<IdeaPluginDescriptorImpl>, precomputedExtensionModel: PrecomputedExtensionModel?, app: Application?, listenerCallbacks: MutableList<in Runnable>?) { super.registerComponents(modules, app, precomputedExtensionModel, listenerCallbacks) if (corePlugin == null) { return } unregisterComponent(DeprecatedModuleOptionManager::class.java) try { //todo improve val classLoader = javaClass.classLoader val apiClass = classLoader.loadClass("com.intellij.openapi.externalSystem.ExternalSystemModulePropertyManager") val implClass = classLoader.loadClass("com.intellij.openapi.externalSystem.service.project.ExternalSystemModulePropertyManagerBridge") registerService(serviceInterface = apiClass, implementation = implClass, pluginDescriptor = corePlugin, override = true) } catch (ignored: Throwable) { } } override fun getOptionValue(key: String): String? { val moduleEntity = entityStorage.current.findModuleEntity(this) if (key == Module.ELEMENT_TYPE) { return moduleEntity?.type } return moduleEntity?.customImlData?.customModuleOptions?.get(key) } override fun setOption(key: String, value: String?) { fun updateOptionInEntity(diff: WorkspaceEntityStorageDiffBuilder, entity: ModuleEntity) { if (key == Module.ELEMENT_TYPE) { diff.modifyEntity(ModifiableModuleEntity::class.java, entity) { type = value } } else { val customImlData = entity.customImlData if (customImlData == null) { if (value != null) { diff.addModuleCustomImlDataEntity(null, mapOf(key to value), entity, entity.entitySource) } } else { diff.modifyEntity(ModifiableModuleCustomImlDataEntity::class.java, customImlData) { if (value != null) { customModuleOptions[key] = value } else { customModuleOptions.remove(key) } } } } } val diff = diff if (diff != null) { val entity = entityStorage.current.findModuleEntity(this) if (entity != null) { updateOptionInEntity(diff, entity) } } else { if (getOptionValue(key) != value) { WriteAction.runAndWait<RuntimeException> { WorkspaceModel.getInstance(project).updateProjectModel { builder -> val entity = builder.findModuleEntity(this) if (entity != null) { updateOptionInEntity(builder, entity) } } } } } return } override fun getOptionsModificationCount(): Long = 0 }
apache-2.0
86fca8af9fa9cf762415bab9d7f2be68
42.725146
158
0.719502
5.49302
false
false
false
false