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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
openMF/self-service-app | app/src/main/java/org/mifos/mobile/models/Transaction.kt | 1 | 1023 | package org.mifos.mobile.models
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
import org.mifos.mobile.models.client.Currency
import org.mifos.mobile.models.client.Type
import java.util.ArrayList
/**
* @author Vishwajeet
* @since 10/8/16.
*/
@Parcelize
data class Transaction(
@SerializedName("id")
var id: Long? = null,
@SerializedName("officeId")
var officeId: Long? = null,
@SerializedName("officeName")
var officeName: String,
@SerializedName("type")
var type: Type,
@SerializedName("date")
var date: List<Int> = ArrayList(),
@SerializedName("currency")
var currency: Currency,
@SerializedName("amount")
var amount: Double? = null,
@SerializedName("submittedOnDate")
var submittedOnDate: List<Int> = ArrayList(),
@SerializedName("reversed")
var reversed: Boolean? = null
) : Parcelable | mpl-2.0 | 5def1b22f01adeddd8039f43a1bc169d | 20.787234 | 53 | 0.650049 | 4.17551 | false | false | false | false |
bpark/companion-classification-micro | src/main/kotlin/com/github/bpark/companion/learn/Learner.kt | 1 | 3502 | /*
* Copyright 2017 bpark
*
* 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.github.bpark.companion.learn
import weka.classifiers.Classifier
import weka.classifiers.Evaluation
import weka.classifiers.bayes.NaiveBayes
import weka.classifiers.meta.FilteredClassifier
import weka.classifiers.trees.J48
import weka.core.Instances
import weka.core.converters.ArffLoader
import weka.core.stemmers.LovinsStemmer
import weka.filters.unsupervised.attribute.StringToWordVector
import java.io.BufferedReader
import java.io.FileReader
import java.util.*
abstract class AbstractLearner {
abstract fun learn(trainData: Instances): Classifier
fun loadDataset(fileName: String): Instances {
BufferedReader(FileReader(fileName)).use { reader ->
val arff = ArffLoader.ArffReader(reader)
return arff.data
}
}
fun evaluate(classifier: Classifier, trainData: Instances) {
trainData.setClassIndex(0)
val eval = Evaluation(trainData)
val folds = 3
eval.crossValidateModel(classifier, trainData, folds, Random(1))
println(eval.toSummaryString())
println(eval.toClassDetailsString())
}
}
class TextClassifierLearner: AbstractLearner() {
override fun learn(trainData: Instances): Classifier {
trainData.setClassIndex(0)
val filter = StringToWordVector()
filter.stopwordsHandler = DialogueStopWords()
filter.stemmer = LovinsStemmer()
filter.attributeIndices = "last"
val classifier = FilteredClassifier()
classifier.filter = filter
classifier.classifier = NaiveBayes()
classifier.buildClassifier(trainData)
return classifier
}
}
class SentenceTypeLearner: AbstractLearner() {
override fun learn(trainData: Instances): Classifier {
trainData.setClassIndex(0)
val classifier = J48()
classifier.options = arrayOf()
//classifier.options = arrayOf("-C 0.05", "-M 1", "-N 3")
//options.add("-U") // unpruned tree
//options.add("-C 0.05") // confidence threshold for pruning. (Default: 0.25)
//options.add("-M 1") // minimum number of instances per leaf. (Default: 2)
//options.add("-R"); // use reduced error pruning. No subtree raising is performed.
//options.add("-N 3") // number of folds for reduced error pruning. One fold is used as the pruning set. (Default: 3)
//options.add("-B"); // Use binary splits for nominal attributes.
//options.add("-S"); // not perform subtree raising.
//options.add("-L"); // not clean up after the tree has been built.
//options.add("-A"); // if set, Laplace smoothing is used for predicted probabilites.
//options.add("-Q"); // The seed for reduced-error pruning.
classifier.buildClassifier(trainData)
return classifier
}
} | apache-2.0 | 53fd5023b39d4c9c698769ee055a3846 | 33.683168 | 136 | 0.670474 | 4.115159 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | fluxc/src/main/java/org/wordpress/android/fluxc/store/stats/insights/PostingActivityStore.kt | 2 | 2171 | package org.wordpress.android.fluxc.store.stats.insights
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.stats.InsightsMapper
import org.wordpress.android.fluxc.model.stats.insights.PostingActivityModel.Day
import org.wordpress.android.fluxc.network.rest.wpcom.stats.insights.PostingActivityRestClient
import org.wordpress.android.fluxc.persistence.InsightsSqlUtils.PostingActivitySqlUtils
import org.wordpress.android.fluxc.store.StatsStore.OnStatsFetched
import org.wordpress.android.fluxc.store.StatsStore.StatsError
import org.wordpress.android.fluxc.store.StatsStore.StatsErrorType.INVALID_RESPONSE
import org.wordpress.android.fluxc.tools.CoroutineEngine
import org.wordpress.android.util.AppLog.T.STATS
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class PostingActivityStore
@Inject constructor(
private val restClient: PostingActivityRestClient,
private val sqlUtils: PostingActivitySqlUtils,
private val coroutineEngine: CoroutineEngine,
private val mapper: InsightsMapper
) {
suspend fun fetchPostingActivity(
site: SiteModel,
startDay: Day,
endDay: Day,
forced: Boolean = false
) = coroutineEngine.withDefaultContext(STATS, this, "fetchPostingActivity") {
if (!forced && sqlUtils.hasFreshRequest(site)) {
return@withDefaultContext OnStatsFetched(getPostingActivity(site, startDay, endDay), cached = true)
}
val payload = restClient.fetchPostingActivity(site, startDay, endDay, forced)
return@withDefaultContext when {
payload.isError -> OnStatsFetched(payload.error)
payload.response != null -> {
sqlUtils.insert(site, payload.response)
OnStatsFetched(mapper.map(payload.response, startDay, endDay))
}
else -> OnStatsFetched(StatsError(INVALID_RESPONSE))
}
}
fun getPostingActivity(site: SiteModel, startDay: Day, endDay: Day) =
coroutineEngine.run(STATS, this, "getPostingActivity") {
sqlUtils.select(site)?.let { mapper.map(it, startDay, endDay) }
}
}
| gpl-2.0 | a6a8736df98921ff15b69431255e0e8e | 44.229167 | 111 | 0.738369 | 4.551363 | false | false | false | false |
jonninja/node.kt | src/main/kotlin/node/express/Cookie.kt | 1 | 1949 | package node.express
import java.util.Date
import java.util.ArrayList
import node.util.encodeUriComponent
import node.util.decodeUriComponent
import node.http.asHttpFormatString
/**
* Encapsulates the data of a cookie.
*/
class Cookie(val key: String, val value: String) {
var path: String? = "/"
var expires: Date? = null
var domain: String? = null
var httpOnly: Boolean = false
/**
* Set the path for this cookie. The default is the root path
*/
fun path(str: String): Cookie {
path = str
return this
}
/**
* Set if this cookie is HTTP only, meaning it will only be available to HTTP requests
* (and not Javascripts)
*/
fun httpOnly(x: Boolean): Cookie {
httpOnly = x;
return this;
}
/**
* Set the max age of this cookie. If not set, the cookie will expire after the session is
* closed (ie. the browser window is closed)
*/
fun maxAge(age: Long): Cookie {
expires = Date(Date().getTime() + age)
return this
}
/**
* Convert the cookie to a string representation
*/
override fun toString(): String {
var pairs = ArrayList<String>()
pairs.add(key + "=" + value.encodeUriComponent())
if (domain != null) pairs.add("Domain=" + domain)
if (path != null) pairs.add("Path=" + path)
if (expires != null) pairs.add("Expires=" + expires!!.asHttpFormatString())
if (httpOnly) pairs.add("HttpOnly");
return pairs.join("; ");
}
companion object {
/**
* Parse a cookie string into a Cookie
*/
fun parse(str: String): Cookie {
var eq_idx = str.indexOf('=')
if (eq_idx == -1) {
return Cookie("", str.trim().decodeUriComponent())
}
var key = str.substring(0, eq_idx).trim()
var value = str.substring(++eq_idx).trim().decodeUriComponent()
if (value.charAt(0) == '\"') {
value = value.substring(1, value.length() - 1)
}
return Cookie(key, value)
}
}
} | mit | 6d661f472461c93c2a6a1c845e5ce1ac | 24.657895 | 92 | 0.619292 | 3.740883 | false | false | false | false |
pokk/mvp-magazine | app/src/main/kotlin/taiwan/no1/app/mvp/presenters/fragment/TvEpisodePresenter.kt | 1 | 3236 | package taiwan.no1.app.mvp.presenters.fragment
import android.view.View
import android.widget.ImageView
import com.devrapid.kotlinknifer.loge
import com.hwangjr.rxbus.RxBus
import com.touchin.constant.RxbusTag
import rx.lang.kotlin.subscriber
import taiwan.no1.app.R
import taiwan.no1.app.api.config.TMDBConfig
import taiwan.no1.app.domain.usecase.TvEpisodeDetail
import taiwan.no1.app.mvp.contracts.fragment.TvEpisodeContract
import taiwan.no1.app.mvp.models.ImageProfileModel
import taiwan.no1.app.mvp.models.tv.TvEpisodesModel
import taiwan.no1.app.ui.fragments.MovieGalleryFragment
import taiwan.no1.app.ui.fragments.ViewPagerMainCtrlFragment
/**
*
* @author Jieyi
* @since 3/6/17
*/
class TvEpisodePresenter constructor(val tvEpisode: TvEpisodeDetail):
BasePresenter<TvEpisodeContract.View>(), TvEpisodeContract.Presenter {
//region View implementation
override fun init(view: TvEpisodeContract.View) {
super.init(view)
}
private var tvEpisodesModel: TvEpisodesModel? = null
override fun requestTvEpisodeDetail(id: Int, seasonNum: Int, episodeNum: Int) {
// This is exception, because we've had the episode information.
this.view.showTvEpisodeInfo()
val request = TvEpisodeDetail.Requests(id, seasonNum, episodeNum)
request.fragmentLifecycle = this.view.getLifecycle()
this.tvEpisode.execute(request, subscriber<TvEpisodesModel>().onError {
loge(it.message)
loge(it)
this.view.showRetry()
}.onNext {
this.tvEpisodesModel = it
this.tvEpisodesModel.let {
this.view.showTvEpisodeImages(this.createViewPagerViews(it?.images?.stills.orEmpty()))
this.view.showTvEpisodeCasts(it?.credits?.cast?.filter { null != it.profile_path }.orEmpty())
this.view.showTvEpisodeCrews(it?.credits?.crew?.filter { null != it.profile_path }.orEmpty())
this.view.showTvEpisodeTrailers(it?.videos?.results.orEmpty())
}
}.onCompleted {
this.view.hideLoading()
})
}
private fun createViewPagerViews(backdrops: List<ImageProfileModel>): List<View> =
backdrops.map {
View.inflate(this.view.context(), R.layout.item_tv_backdrop, null) as ImageView
}.also {
it.forEachIndexed { i, imageView ->
this.view.showTvEpisodeBackDrop(TMDBConfig.BASE_IMAGE_URL + backdrops[i].file_path, imageView)
}
}
//endregion
override fun onResourceFinished(imageview: ImageView, argFromFragment: Int) {
imageview.setOnClickListener {
val posters: List<ImageProfileModel> = this.tvEpisodesModel?.let {
it.images?.stills?.filter { "en" == it.iso_639_1 }
} ?: emptyList()
if (posters.isNotEmpty())
RxBus.get().post(RxbusTag.FRAGMENT_CHILD_NAVIGATOR, hashMapOf(
Pair(ViewPagerMainCtrlFragment.NAVIGATOR_ARG_FRAGMENT,
MovieGalleryFragment.newInstance(posters)),
Pair(ViewPagerMainCtrlFragment.NAVIGATOR_ARG_TAG, argFromFragment)))
}
}
}
| apache-2.0 | a958f9f2decacf2381fc23112fcfbaeb | 40.487179 | 114 | 0.664091 | 4.235602 | false | false | false | false |
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/entitymapper/ShowMapper.kt | 1 | 7127 | package net.simonvt.cathode.entitymapper
import android.database.Cursor
import net.simonvt.cathode.api.enumeration.ShowStatus
import net.simonvt.cathode.common.data.MappedCursorLiveData
import net.simonvt.cathode.common.database.getBoolean
import net.simonvt.cathode.common.database.getFloat
import net.simonvt.cathode.common.database.getInt
import net.simonvt.cathode.common.database.getLong
import net.simonvt.cathode.common.database.getStringOrNull
import net.simonvt.cathode.entity.Show
import net.simonvt.cathode.provider.DatabaseContract.ShowColumns
import net.simonvt.cathode.provider.DatabaseSchematic.Tables
object ShowMapper : MappedCursorLiveData.CursorMapper<Show> {
override fun map(cursor: Cursor): Show? {
return if (cursor.moveToFirst()) mapShow(cursor) else null
}
fun mapShow(cursor: Cursor): Show {
val id = cursor.getLong(ShowColumns.ID)
val title = cursor.getStringOrNull(ShowColumns.TITLE)
val titleNoArticle = cursor.getStringOrNull(ShowColumns.TITLE_NO_ARTICLE)
val year = cursor.getInt(ShowColumns.YEAR)
val firstAired = cursor.getLong(ShowColumns.FIRST_AIRED)
val country = cursor.getStringOrNull(ShowColumns.COUNTRY)
val overview = cursor.getStringOrNull(ShowColumns.OVERVIEW)
val runtime = cursor.getInt(ShowColumns.RUNTIME)
val network = cursor.getStringOrNull(ShowColumns.NETWORK)
val airDay = cursor.getStringOrNull(ShowColumns.AIR_DAY)
val airTime = cursor.getStringOrNull(ShowColumns.AIR_TIME)
val airTimezone = cursor.getStringOrNull(ShowColumns.AIR_TIMEZONE)
val certification = cursor.getStringOrNull(ShowColumns.CERTIFICATION)
val slug = cursor.getStringOrNull(ShowColumns.SLUG)
val traktId = cursor.getLong(ShowColumns.TRAKT_ID)
val imdbId = cursor.getStringOrNull(ShowColumns.IMDB_ID)
val tvdbId = cursor.getInt(ShowColumns.TVDB_ID)
val tmdbId = cursor.getInt(ShowColumns.TMDB_ID)
val tvrageId = cursor.getLong(ShowColumns.TVRAGE_ID)
val lastUpdated = cursor.getLong(ShowColumns.LAST_UPDATED)
val trailer = cursor.getStringOrNull(ShowColumns.TRAILER)
val homepage = cursor.getStringOrNull(ShowColumns.HOMEPAGE)
val statusString = cursor.getStringOrNull(ShowColumns.STATUS)
val status: ShowStatus? = if (!statusString.isNullOrEmpty()) {
ShowStatus.fromValue(statusString)
} else {
null
}
val userRating = cursor.getInt(ShowColumns.USER_RATING)
val ratedAt = cursor.getLong(ShowColumns.RATED_AT)
val rating = cursor.getFloat(ShowColumns.RATING)
val votes = cursor.getInt(ShowColumns.VOTES)
val watchers = cursor.getInt(ShowColumns.WATCHERS)
val plays = cursor.getInt(ShowColumns.PLAYS)
val scrobbles = cursor.getInt(ShowColumns.SCROBBLES)
val checkins = cursor.getInt(ShowColumns.CHECKINS)
val inWatchlist = cursor.getBoolean(ShowColumns.IN_WATCHLIST)
val watchlistedAt = cursor.getLong(ShowColumns.LISTED_AT)
val lastWatchedAt = cursor.getLong(ShowColumns.LAST_WATCHED_AT)
val lastCollectedAt = cursor.getLong(ShowColumns.LAST_COLLECTED_AT)
val hiddenCalendar = cursor.getBoolean(ShowColumns.HIDDEN_CALENDAR)
val hiddenWatched = cursor.getBoolean(ShowColumns.HIDDEN_WATCHED)
val hiddenCollected = cursor.getBoolean(ShowColumns.HIDDEN_COLLECTED)
val hiddenRecommendations = cursor.getBoolean(ShowColumns.HIDDEN_RECOMMENDATIONS)
val watchedCount = cursor.getInt(ShowColumns.WATCHED_COUNT)
val airdateCount = cursor.getInt(ShowColumns.AIRDATE_COUNT)
val inCollectionCount = cursor.getInt(ShowColumns.IN_COLLECTION_COUNT)
val inWatchlistCount = cursor.getInt(ShowColumns.IN_WATCHLIST_COUNT)
val needsSync = cursor.getBoolean(ShowColumns.NEEDS_SYNC)
val lastSync = cursor.getLong(ShowColumns.LAST_SYNC)
val lastCommentSync = cursor.getLong(ShowColumns.LAST_COMMENT_SYNC)
val lastCreditsSync = cursor.getLong(ShowColumns.LAST_CREDITS_SYNC)
val lastRelatedSync = cursor.getLong(ShowColumns.LAST_RELATED_SYNC)
val watching = cursor.getBoolean(ShowColumns.WATCHING)
val airedCount = cursor.getInt(ShowColumns.AIRED_COUNT)
val unairedCount = cursor.getInt(ShowColumns.UNAIRED_COUNT)
val episodeCount = cursor.getInt(ShowColumns.EPISODE_COUNT)
val watchingEpisodeId = cursor.getLong(ShowColumns.WATCHING_EPISODE_ID)
return Show(
id,
title,
titleNoArticle,
year,
firstAired,
country,
overview,
runtime,
network,
airDay,
airTime,
airTimezone,
certification,
slug,
traktId,
imdbId,
tvdbId,
tmdbId,
tvrageId,
lastUpdated,
trailer,
homepage,
status,
userRating,
ratedAt,
rating,
votes,
watchers,
plays,
scrobbles,
checkins,
inWatchlist,
watchlistedAt,
lastWatchedAt,
lastCollectedAt,
hiddenCalendar,
hiddenWatched,
hiddenCollected,
hiddenRecommendations,
watchedCount,
airdateCount,
inCollectionCount,
inWatchlistCount,
needsSync,
lastSync,
lastCommentSync,
lastCreditsSync,
lastRelatedSync,
watching,
airedCount,
unairedCount,
episodeCount,
watchingEpisodeId
)
}
val projection = arrayOf(
Tables.SHOWS + "." + ShowColumns.ID,
ShowColumns.TITLE,
ShowColumns.TITLE_NO_ARTICLE,
ShowColumns.YEAR,
ShowColumns.FIRST_AIRED,
ShowColumns.COUNTRY,
Tables.SHOWS + "." + ShowColumns.OVERVIEW,
ShowColumns.RUNTIME,
ShowColumns.NETWORK,
ShowColumns.AIR_DAY,
ShowColumns.AIR_TIME,
ShowColumns.AIR_TIMEZONE,
ShowColumns.CERTIFICATION,
ShowColumns.SLUG,
Tables.SHOWS + "." + ShowColumns.TRAKT_ID,
Tables.SHOWS + "." + ShowColumns.IMDB_ID,
Tables.SHOWS + "." + ShowColumns.TVDB_ID,
Tables.SHOWS + "." + ShowColumns.TMDB_ID,
Tables.SHOWS + "." + ShowColumns.TVRAGE_ID,
Tables.SHOWS + "." + ShowColumns.LAST_UPDATED,
ShowColumns.TRAILER,
ShowColumns.HOMEPAGE,
ShowColumns.STATUS,
Tables.SHOWS + "." + ShowColumns.USER_RATING,
Tables.SHOWS + "." + ShowColumns.RATED_AT,
Tables.SHOWS + "." + ShowColumns.RATING,
Tables.SHOWS + "." + ShowColumns.VOTES,
ShowColumns.WATCHERS,
Tables.SHOWS + "." + ShowColumns.PLAYS,
ShowColumns.SCROBBLES,
ShowColumns.CHECKINS,
ShowColumns.IN_WATCHLIST,
ShowColumns.LISTED_AT,
Tables.SHOWS + "." + ShowColumns.LAST_WATCHED_AT,
ShowColumns.LAST_COLLECTED_AT,
ShowColumns.HIDDEN_CALENDAR,
ShowColumns.HIDDEN_WATCHED,
ShowColumns.HIDDEN_COLLECTED,
ShowColumns.HIDDEN_RECOMMENDATIONS,
ShowColumns.WATCHED_COUNT,
ShowColumns.AIRDATE_COUNT,
ShowColumns.IN_COLLECTION_COUNT,
ShowColumns.IN_WATCHLIST_COUNT,
ShowColumns.NEEDS_SYNC,
ShowColumns.LAST_SYNC,
Tables.SHOWS + "." + ShowColumns.LAST_COMMENT_SYNC,
ShowColumns.LAST_CREDITS_SYNC,
ShowColumns.LAST_RELATED_SYNC,
ShowColumns.WATCHING,
ShowColumns.AIRED_COUNT,
ShowColumns.UNAIRED_COUNT,
ShowColumns.EPISODE_COUNT,
ShowColumns.WATCHING_EPISODE_ID
)
}
| apache-2.0 | a746479cb1ae550a8b154f6f9dd68ab2 | 35.927461 | 85 | 0.727375 | 4.114896 | false | false | false | false |
lightem90/Sismic | app/src/main/java/com/polito/sismic/Presenters/PresenterActivity/PresenterActivity.kt | 1 | 3874 | package com.polito.sismic.Presenters.PresenterActivity
import android.app.Activity
import android.app.Fragment
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import com.polito.sismic.Interactors.DatabaseInteractor
import com.polito.sismic.R
import kotlinx.android.synthetic.main.activity_presenter.*
class PresenterActivity : AppCompatActivity(),
ReportListFragment.HistoryReload {
private val mDatabaseInteractor: DatabaseInteractor = DatabaseInteractor()
private val fragmentFactory: PresenterFragmentFactory = PresenterFragmentFactory()
companion object {
val REPORT_ACTIVITY = 50
}
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
with(fragmentFactory.GetHomeFragment())
{
pushFragment(this, this.getFragmentTag())
}
return@OnNavigationItemSelectedListener true
}
R.id.navigation_history -> {
with(fragmentFactory.GetReportListFragment())
{
pushFragment(this, this.getFragmentTag())
}
return@OnNavigationItemSelectedListener true
}
R.id.navigation_profile -> {
with(fragmentFactory.GetProfileFragment())
{
pushFragment(this, this.getFragmentTag())
}
return@OnNavigationItemSelectedListener true
}
}
false
}
private fun pushFragment(fragment: Fragment?, tag: String) {
if (fragmentManager != null) {
val ft = fragmentManager.beginTransaction()
if (ft != null) {
ft.replace(R.id.frame_canvas, fragment, tag)
ft.commit()
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
return super.onCreateOptionsMenu(menu)
}
//tutti i menù son gestiti dai fragments, non ci sono elementi ricorrenti
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return super.onOptionsItemSelected(item);
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_presenter)
val initialFrag = fragmentFactory.GetHomeFragment()
pushFragment(initialFrag, initialFrag.getFragmentTag())
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
mDatabaseInteractor.deleteNotCommittedReports(this)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REPORT_ACTIVITY) {
onHistoryReloadRequest()
}
}
//Requested from the professor
override fun onBackPressed() {
goBack()
}
private fun goBack() {
AlertDialog.Builder(this)
.setTitle(R.string.confirm_report_back)
.setMessage(R.string.confirm_presenter_back_message)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, { _, _ ->
finish()
})
.setNegativeButton(R.string.annulla, null)
.show()
}
override fun onHistoryReloadRequest() {
val history = fragmentManager.findFragmentByTag("report_list") as ReportListFragment?
history?.invalidateAndReload()
}
}
| mit | 82753c8d1f900875757f087f08d0a330 | 31.546218 | 115 | 0.640589 | 5.305479 | false | false | false | false |
Ray-Eldath/Avalon | src/main/kotlin/avalon/group/Quote.kt | 1 | 1134 | package avalon.group
import avalon.api.Flag.at
import avalon.tool.database.Table
import avalon.tool.pool.Constants.Basic.LANG
import avalon.tool.pool.Constants.Database.DB_OPERATOR
import avalon.util.GroupConfig
import avalon.util.GroupMessage
import java.util.regex.Pattern
object Quote : GroupMessageResponder() {
override fun doPost(message: GroupMessage, groupConfig: GroupConfig) {
val hashCode = message.hashCode()
if (DB_OPERATOR.exist(Table.QUOTE, "uid=$hashCode")) {
message.response("${at(message)} ${LANG.getString("group.quote.recorded")}")
return
}
val split = message.content.split(" ") // avalon quote 123 456
val speaker = split[2]
val content = split[3]
DB_OPERATOR.addQuote(hashCode, speaker, content)
message.response("${at(message)} ${LANG.getString("group.quote.success")}")
}
override fun responderInfo(): ResponderInfo =
ResponderInfo(
Pair(LANG.getString("group.quote.help.first"), LANG.getString("group.quote.help.second")),
Pattern.compile("quote \\S+ \\S+"),
permission = ResponderPermission.ADMIN
)
override fun instance(): GroupMessageResponder? = this
} | agpl-3.0 | 751299f952e4981d3ac7852a5c63198e | 33.393939 | 95 | 0.738095 | 3.646302 | false | true | false | false |
googlesamples/mlkit | android/material-showcase/app/src/main/java/com/google/mlkit/md/camera/CameraReticleAnimator.kt | 1 | 4293 | /*
* 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.google.mlkit.md.camera
import android.animation.AnimatorSet
import android.animation.ValueAnimator
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
/** Custom animator for the object or barcode reticle in live camera. */
class CameraReticleAnimator(graphicOverlay: GraphicOverlay) {
/** Returns the scale value of ripple alpha ranges in [0, 1]. */
var rippleAlphaScale = 0f
private set
/** Returns the scale value of ripple size ranges in [0, 1]. */
var rippleSizeScale = 0f
private set
/** Returns the scale value of ripple stroke width ranges in [0, 1]. */
var rippleStrokeWidthScale = 1f
private set
private val animatorSet: AnimatorSet
init {
val rippleFadeInAnimator = ValueAnimator.ofFloat(0f, 1f).setDuration(DURATION_RIPPLE_FADE_IN_MS)
rippleFadeInAnimator.addUpdateListener { animation ->
rippleAlphaScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
}
val rippleFadeOutAnimator = ValueAnimator.ofFloat(1f, 0f).setDuration(DURATION_RIPPLE_FADE_OUT_MS)
rippleFadeOutAnimator.startDelay = START_DELAY_RIPPLE_FADE_OUT_MS
rippleFadeOutAnimator.addUpdateListener { animation ->
rippleAlphaScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
}
val rippleExpandAnimator = ValueAnimator.ofFloat(0f, 1f).setDuration(DURATION_RIPPLE_EXPAND_MS)
rippleExpandAnimator.startDelay = START_DELAY_RIPPLE_EXPAND_MS
rippleExpandAnimator.interpolator = FastOutSlowInInterpolator()
rippleExpandAnimator.addUpdateListener { animation ->
rippleSizeScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
}
val rippleStrokeWidthShrinkAnimator =
ValueAnimator.ofFloat(1f, 0.5f).setDuration(DURATION_RIPPLE_STROKE_WIDTH_SHRINK_MS)
rippleStrokeWidthShrinkAnimator.startDelay = START_DELAY_RIPPLE_STROKE_WIDTH_SHRINK_MS
rippleStrokeWidthShrinkAnimator.interpolator = FastOutSlowInInterpolator()
rippleStrokeWidthShrinkAnimator.addUpdateListener { animation ->
rippleStrokeWidthScale = animation.animatedValue as Float
graphicOverlay.postInvalidate()
}
val fakeAnimatorForRestartDelay = ValueAnimator.ofInt(0, 0).setDuration(DURATION_RESTART_DORMANCY_MS)
fakeAnimatorForRestartDelay.startDelay = START_DELAY_RESTART_DORMANCY_MS
animatorSet = AnimatorSet()
animatorSet.playTogether(
rippleFadeInAnimator,
rippleFadeOutAnimator,
rippleExpandAnimator,
rippleStrokeWidthShrinkAnimator,
fakeAnimatorForRestartDelay
)
}
fun start() {
if (!animatorSet.isRunning) animatorSet.start()
}
fun cancel() {
animatorSet.cancel()
rippleAlphaScale = 0f
rippleSizeScale = 0f
rippleStrokeWidthScale = 1f
}
companion object {
private const val DURATION_RIPPLE_FADE_IN_MS: Long = 333
private const val DURATION_RIPPLE_FADE_OUT_MS: Long = 500
private const val DURATION_RIPPLE_EXPAND_MS: Long = 833
private const val DURATION_RIPPLE_STROKE_WIDTH_SHRINK_MS: Long = 833
private const val DURATION_RESTART_DORMANCY_MS: Long = 1333
private const val START_DELAY_RIPPLE_FADE_OUT_MS: Long = 667
private const val START_DELAY_RIPPLE_EXPAND_MS: Long = 333
private const val START_DELAY_RIPPLE_STROKE_WIDTH_SHRINK_MS: Long = 333
private const val START_DELAY_RESTART_DORMANCY_MS: Long = 1167
}
}
| apache-2.0 | f9d163dd89d8a1d31c95e5fc3be8724a | 39.5 | 109 | 0.703704 | 4.883959 | false | false | false | false |
FHannes/intellij-community | platform/lang-impl/src/com/intellij/execution/impl/ExecutionManagerKtImpl.kt | 5 | 7181 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution.impl
import com.intellij.execution.ExecutionManager
import com.intellij.execution.RunProfileStarter
import com.intellij.execution.configurations.RunProfileState
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.runners.ExecutionUtil
import com.intellij.execution.ui.RunContentDescriptor
import com.intellij.ide.SaveAndSyncHandler
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.TransactionGuard
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Trinity
import com.intellij.ui.AppUIUtil
import org.jetbrains.annotations.TestOnly
import java.util.concurrent.atomic.AtomicBoolean
class ExecutionManagerKtImpl(project: Project) : ExecutionManagerImpl(project) {
@set:TestOnly
@Volatile var forceCompilationInTests = false
override fun startRunProfile(starter: RunProfileStarter, state: RunProfileState, environment: ExecutionEnvironment) {
val project = environment.project
val reuseContent = contentManager.getReuseContent(environment)
if (reuseContent != null) {
reuseContent.executionId = environment.executionId
environment.contentToReuse = reuseContent
}
val executor = environment.executor
project.messageBus.syncPublisher(ExecutionManager.EXECUTION_TOPIC).processStartScheduled(executor.id, environment)
fun processNotStarted() {
project.messageBus.syncPublisher(ExecutionManager.EXECUTION_TOPIC).processNotStarted(executor.id, environment)
}
val startRunnable = Runnable {
if (project.isDisposed) {
return@Runnable
}
project.messageBus.syncPublisher(ExecutionManager.EXECUTION_TOPIC).processStarting(executor.id, environment)
fun handleError(e: Throwable) {
if (e !is ProcessCanceledException) {
ExecutionUtil.handleExecutionError(project, contentManager.getToolWindowIdByEnvironment(environment), environment.runProfile.name, e)
LOG.debug(e)
}
processNotStarted()
}
try {
starter.executeAsync(state, environment)
.done { descriptor ->
AppUIUtil.invokeLaterIfProjectAlive(project) {
if (descriptor == null) {
processNotStarted()
return@invokeLaterIfProjectAlive
}
val trinity = Trinity.create(descriptor, environment.runnerAndConfigurationSettings, executor)
myRunningConfigurations.add(trinity)
Disposer.register(descriptor, Disposable { myRunningConfigurations.remove(trinity) })
contentManager.showRunContent(executor, descriptor, environment.contentToReuse)
val processHandler = descriptor.processHandler
if (processHandler != null) {
if (!processHandler.isStartNotified) {
processHandler.startNotify()
}
project.messageBus.syncPublisher(ExecutionManager.EXECUTION_TOPIC).processStarted(executor.id, environment, processHandler)
val listener = ProcessExecutionListener(project, executor.id, environment, processHandler, descriptor)
processHandler.addProcessListener(listener)
// Since we cannot guarantee that the listener is added before process handled is start notified,
// we have to make sure the process termination events are delivered to the clients.
// Here we check the current process state and manually deliver events, while
// the ProcessExecutionListener guarantees each such event is only delivered once
// either by this code, or by the ProcessHandler.
val terminating = processHandler.isProcessTerminating
val terminated = processHandler.isProcessTerminated
if (terminating || terminated) {
listener.processWillTerminate(ProcessEvent(processHandler), false /*doesn't matter*/)
if (terminated) {
listener.processTerminated(ProcessEvent(processHandler, if (processHandler.isStartNotified) processHandler.exitCode ?: -1 else -1))
}
}
}
environment.contentToReuse = descriptor
}
}
.rejected(::handleError)
}
catch (e: Throwable) {
handleError(e)
}
}
if (!forceCompilationInTests && ApplicationManager.getApplication().isUnitTestMode) {
startRunnable.run()
}
else {
compileAndRun(Runnable { TransactionGuard.submitTransaction(project, startRunnable) }, environment, state, Runnable {
if (!project.isDisposed) {
processNotStarted()
}
})
}
}
}
private class ProcessExecutionListener(private val project: Project,
private val executorId: String,
private val environment: ExecutionEnvironment,
private val processHandler: ProcessHandler,
private val descriptor: RunContentDescriptor) : ProcessAdapter() {
private val willTerminateNotified = AtomicBoolean()
private val terminateNotified = AtomicBoolean()
override fun processTerminated(event: ProcessEvent) {
if (project.isDisposed || !terminateNotified.compareAndSet(false, true)) {
return
}
ApplicationManager.getApplication().invokeLater({
val ui = descriptor.runnerLayoutUi
if (ui != null && !ui.isDisposed) {
ui.updateActionsNow()
}
}, ModalityState.any())
project.messageBus.syncPublisher(ExecutionManager.EXECUTION_TOPIC).processTerminated(executorId, environment, processHandler, event.exitCode)
SaveAndSyncHandler.getInstance()?.scheduleRefresh()
}
override fun processWillTerminate(event: ProcessEvent, shouldNotBeUsed: Boolean) {
if (project.isDisposed || !willTerminateNotified.compareAndSet(false, true)) {
return
}
project.messageBus.syncPublisher(ExecutionManager.EXECUTION_TOPIC).processTerminating(executorId, environment, processHandler)
}
} | apache-2.0 | 4f98032e4c3eeb5d339b0b5d3fea688d | 42.005988 | 151 | 0.704359 | 5.597038 | false | false | false | false |
matiuri/Minesweeper | core/src/kotlin/mati/minesweeper/screens/GameS.kt | 1 | 5263 | package mati.minesweeper.screens
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.InputMultiplexer
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.Image
import com.badlogic.gdx.utils.Align
import com.badlogic.gdx.utils.viewport.ScreenViewport
import mati.advancedgdx.AdvancedGame
import mati.advancedgdx.screens.Screen
import mati.advancedgdx.utils.isDesktop
import mati.minesweeper.Game
import mati.minesweeper.board.Board
import mati.minesweeper.board.Cell
import mati.minesweeper.gui.*
import mati.minesweeper.gui.GUIHelper.GUIBase
import mati.minesweeper.gui.GUIHelper.guiButtons
import mati.minesweeper.gui.GUIHelper.winDialog
import mati.minesweeper.gui.GUIHelper.gameOverDialog
import mati.minesweeper.gui.Timer.TimerSerializer
import mati.minesweeper.input.CamButtonListener
import mati.minesweeper.io.BoardSerializer
import mati.minesweeper.io.CamSerializer
import mati.minesweeper.io.CamSerializer.Serializer
import mati.minesweeper.screens.NewGame.Properties
import kotlin.properties.Delegates
class GameS(game: Game) : Screen<Game>(game) {
var stage: Stage by Delegates.notNull<Stage>()
var gui: Stage by Delegates.notNull<Stage>()
var timer: Timer by Delegates.notNull<Timer>()
var cam: OrthographicCamera by Delegates.notNull<OrthographicCamera>()
var CBLL: CamButtonListener by Delegates.notNull<CamButtonListener>()
var CBLU: CamButtonListener by Delegates.notNull<CamButtonListener>()
var CBLD: CamButtonListener by Delegates.notNull<CamButtonListener>()
var CBLR: CamButtonListener by Delegates.notNull<CamButtonListener>()
var newGame: Boolean = false
private var camZ: Float = 0f
override fun load() {
cam = OrthographicCamera()
stage = Stage(ScreenViewport(cam))
camZ = cam.zoom
gui = Stage(ScreenViewport())
timer = Timer(game)
}
override fun show() {
if (isDesktop())
Gdx.graphics.setCursor(game.cursors[1])
if (newGame)
timer.reset()
else
timer = game.ioManager.load("timer", TimerSerializer::class)
val board: Board = if (newGame) Board()
else game.ioManager.load("board", BoardSerializer::class)
if (newGame)
board.init()
else if (!board.first)
timer.start()
board.timer = timer
stage.addActor(board)
val guiBottom: Image = GUIBase(gui, board)
gui.addActor(timer.label)
timer.label.setPosition(26f, 4f)
val fCounter: FlagCounter = FlagCounter(game, board, guiBottom.width - 24f)
if (!newGame) fCounter.init(board.flags)
board.fCounter = fCounter
fCounter.label.setPosition(guiBottom.width - 24f - fCounter.label.width, 4f)
fCounter.label.setAlignment(Align.right)
gui.addActor(fCounter.label)
val CBL: Array<CamButtonListener> = guiButtons(board, gui, timer, cam)
CBLL = CBL[0]
CBLU = CBL[1]
CBLD = CBL[2]
CBLR = CBL[3]
if (newGame || !game.ioManager.exists("camera")) {
cam.position.x = board.wh.toFloat() * board.size / 2f
cam.position.y = board.wh.toFloat() * board.size / 2f
cam.zoom = camZ
cam.update()
} else {
val camData: CamSerializer = game.ioManager.load("camera", Serializer::class)
cam.position.set(camData.position)
cam.zoom = camData.zoom
}
Gdx.input.inputProcessor = InputMultiplexer(gui, stage)
}
override fun render(delta: Float) {
timer.update(delta)
Cell.Static.update(delta)
if (CBLD.pressed || CBLL.pressed || CBLR.pressed || CBLU.pressed) {
val amount: Float = 2.5f * cam.zoom * delta * 100f
if (CBLD.pressed) cam.position.y -= amount
else if (CBLL.pressed) cam.position.x -= amount
else if (CBLR.pressed) cam.position.x += amount
else if (CBLU.pressed) cam.position.y += amount
cam.update()
}
stage.act(delta)
stage.draw()
gui.act(delta)
gui.draw()
}
fun gameOver() {
timer.stop()
AdvancedGame.log.d("${this.javaClass.simpleName}", "Game Over. ${timer.label.text}")
Gdx.input.inputProcessor = gui
if (isDesktop())
Gdx.graphics.setCursor(game.cursors[0])
gameOverDialog(gui)
game.ioManager.delete("board").delete("timer").delete("camera")
game.stats.addEntry(false, Properties.difficulty, Properties.size, timer.time)
}
fun win() {
timer.stop()
AdvancedGame.log.d("${this.javaClass.simpleName}", "WIN! ${timer.label.text}")
Gdx.input.inputProcessor = gui
if (isDesktop())
Gdx.graphics.setCursor(game.cursors[0])
winDialog(gui)
game.ioManager.delete("board").delete("timer").delete("camera")
game.stats.addEntry(true, Properties.difficulty, Properties.size, timer.time)
}
override fun hide() {
timer.stop()
stage.clear()
gui.clear()
}
override fun dispose() {
stage.dispose()
gui.dispose()
}
}
| gpl-2.0 | d43a8004a80cd710d4f2f3ab4a256ca8 | 34.086667 | 92 | 0.65609 | 3.981089 | false | false | false | false |
GeoffreyMetais/vlc-android | application/television/src/main/java/org/videolan/television/ui/MediaScrapingTvshowDetailsFragment.kt | 1 | 15610 | /*
* ************************************************************************
* MoviepediaTvshowDetailsFragment.kt
* *************************************************************************
* Copyright © 2019 VLC authors and VideoLAN
* Author: Nicolas POMEPUY
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* **************************************************************************
*
*
*/
/*****************************************************************************
* MoviepediaTvshowDetailsFragment.java
*
* Copyright © 2014-2019 VLC authors, VideoLAN and VideoLabs
* Author: Nicolas POMEPUY
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*/
package org.videolan.television.ui
import android.annotation.TargetApi
import android.os.Build
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.leanback.app.BackgroundManager
import androidx.leanback.app.DetailsSupportFragment
import androidx.leanback.widget.*
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.*
import org.videolan.moviepedia.database.models.*
import org.videolan.moviepedia.viewmodel.MediaMetadataFull
import org.videolan.moviepedia.viewmodel.MediaMetadataModel
import org.videolan.resources.util.getFromMl
import org.videolan.tools.HttpImageLoader
import org.videolan.vlc.R
import org.videolan.vlc.media.MediaUtils
import org.videolan.vlc.repository.BrowserFavRepository
import org.videolan.vlc.util.getScreenWidth
private const val ID_RESUME = 1
private const val ID_START_OVER = 2
@ExperimentalCoroutinesApi
@ObsoleteCoroutinesApi
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
class MediaScrapingTvshowDetailsFragment : DetailsSupportFragment(), CoroutineScope by MainScope(), OnItemViewClickedListener {
private lateinit var actionsAdapter: SparseArrayObjectAdapter
private lateinit var showId: String
private lateinit var detailsDescriptionPresenter: org.videolan.television.ui.TvShowDescriptionPresenter
private lateinit var backgroundManager: BackgroundManager
private lateinit var rowsAdapter: ArrayObjectAdapter
private lateinit var browserFavRepository: BrowserFavRepository
private lateinit var detailsOverview: DetailsOverviewRow
private lateinit var arrayObjectAdapterPosters: ArrayObjectAdapter
private lateinit var viewModel: MediaMetadataModel
private val imageDiffCallback = object : DiffCallback<MediaImage>() {
override fun areItemsTheSame(oldItem: MediaImage, newItem: MediaImage) = oldItem.url == newItem.url
override fun areContentsTheSame(oldItem: MediaImage, newItem: MediaImage) = oldItem.url == newItem.url
}
private val personsDiffCallback = object : DiffCallback<Person>() {
override fun areItemsTheSame(oldItem: Person, newItem: Person) = oldItem.moviepediaId == newItem.moviepediaId
override fun areContentsTheSame(oldItem: Person, newItem: Person) = oldItem.moviepediaId == newItem.moviepediaId && oldItem.image == newItem.image && oldItem.name == newItem.name
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
backgroundManager = BackgroundManager.getInstance(requireActivity())
backgroundManager.isAutoReleaseOnStop = false
browserFavRepository = BrowserFavRepository.getInstance(requireContext())
detailsDescriptionPresenter = org.videolan.television.ui.TvShowDescriptionPresenter()
arrayObjectAdapterPosters = ArrayObjectAdapter(org.videolan.television.ui.MediaImageCardPresenter(requireActivity(), MediaImageType.POSTER))
val extras = requireActivity().intent.extras ?: savedInstanceState ?: return
showId = extras.getString(org.videolan.television.ui.TV_SHOW_ID) ?: return
viewModel = ViewModelProviders.of(this, MediaMetadataModel.Factory(requireActivity(), showId = showId)).get(showId, MediaMetadataModel::class.java)
viewModel.updateLiveData.observe(this, Observer {
buildDetails(it)
updateMetadata(it)
})
onItemViewClickedListener = this
}
override fun onResume() {
super.onResume()
if (!backgroundManager.isAttached) backgroundManager.attachToView(view)
}
override fun onPause() {
backgroundManager.release()
super.onPause()
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putString(org.videolan.television.ui.TV_SHOW_ID, showId)
super.onSaveInstanceState(outState)
}
override fun onItemClicked(itemViewHolder: Presenter.ViewHolder?, item: Any?, rowViewHolder: RowPresenter.ViewHolder?, row: Row?) {
when (item) {
is MediaImage -> {
viewModel.updateMetadataImage(item)
}
is MediaMetadataWithImages -> {
launch {
val media = item.media
?: item.metadata.mlId?.let { requireActivity().getFromMl { getMedia(it) } }
media?.let {
org.videolan.television.ui.TvUtil.showMediaDetail(requireActivity(), it)
}
}
}
}
}
private fun loadBackdrop(url: String? = null) {
lifecycleScope.launchWhenStarted {
when {
!url.isNullOrEmpty() -> HttpImageLoader.downloadBitmap(url)
else -> null
}?.let { backgroundManager.setBitmap(it) }
}
}
private fun updateMetadata(tvshow: MediaMetadataFull?) {
var backdropLoaded = false
tvshow?.let { tvshow ->
loadBackdrop(tvshow.metadata?.metadata?.currentBackdrop)
backdropLoaded = true
lifecycleScope.launchWhenStarted {
if (!tvshow.metadata?.metadata?.currentPoster.isNullOrEmpty()) {
detailsOverview.setImageBitmap(requireActivity(), HttpImageLoader.downloadBitmap(tvshow.metadata?.metadata?.currentPoster!!))
}
}
title = tvshow.metadata?.metadata?.title
val items = ArrayList<Any>()
items.add(detailsOverview)
tvshow.seasons?.let {
it.forEach {
val arrayObjectAdapterSeason = ArrayObjectAdapter(org.videolan.television.ui.MetadataCardPresenter(requireActivity()))
arrayObjectAdapterSeason.setItems(it.episodes, org.videolan.television.ui.TvUtil.metadataDiffCallback)
val headerSeason = HeaderItem(tvshow.metadata?.metadata?.moviepediaId?.toLong(36)
?: 0, getString(R.string.season_number, it.seasonNumber.toString()))
items.add(ListRow(headerSeason, arrayObjectAdapterSeason))
}
}
if (!tvshow.writers.isNullOrEmpty()) {
val arrayObjectAdapterWriters = ArrayObjectAdapter(PersonCardPresenter(requireActivity()))
arrayObjectAdapterWriters.setItems(tvshow.writers, personsDiffCallback)
val headerWriters = HeaderItem(tvshow.metadata?.metadata?.moviepediaId?.toLong(36)
?: 0, getString(R.string.written_by))
items.add(ListRow(headerWriters, arrayObjectAdapterWriters))
}
if (!tvshow.actors.isNullOrEmpty()) {
val arrayObjectAdapterActors = ArrayObjectAdapter(PersonCardPresenter(requireActivity()))
arrayObjectAdapterActors.setItems(tvshow.actors, personsDiffCallback)
val headerActors = HeaderItem(tvshow.metadata?.metadata?.moviepediaId?.toLong(36)
?: 0, getString(R.string.casting))
items.add(ListRow(headerActors, arrayObjectAdapterActors))
}
if (!tvshow.directors.isNullOrEmpty()) {
val arrayObjectAdapterDirectors = ArrayObjectAdapter(PersonCardPresenter(requireActivity()))
arrayObjectAdapterDirectors.setItems(tvshow.directors, personsDiffCallback)
val headerDirectors = HeaderItem(tvshow.metadata?.metadata?.moviepediaId?.toLong(36)
?: 0, getString(R.string.directed_by))
items.add(ListRow(headerDirectors, arrayObjectAdapterDirectors))
}
if (!tvshow.producers.isNullOrEmpty()) {
val arrayObjectAdapterProducers = ArrayObjectAdapter(PersonCardPresenter(requireActivity()))
arrayObjectAdapterProducers.setItems(tvshow.producers, personsDiffCallback)
val headerProducers = HeaderItem(tvshow.metadata?.metadata?.moviepediaId?.toLong(36)
?: 0, getString(R.string.produced_by))
items.add(ListRow(headerProducers, arrayObjectAdapterProducers))
}
if (!tvshow.musicians.isNullOrEmpty()) {
val arrayObjectAdapterMusicians = ArrayObjectAdapter(PersonCardPresenter(requireActivity()))
arrayObjectAdapterMusicians.setItems(tvshow.musicians, personsDiffCallback)
val headerMusicians = HeaderItem(tvshow.metadata?.metadata?.moviepediaId?.toLong(36)
?: 0, getString(R.string.music_by))
items.add(ListRow(headerMusicians, arrayObjectAdapterMusicians))
}
tvshow.metadata?.let { metadata ->
if (metadata.images.any { it.imageType == MediaImageType.POSTER }) {
arrayObjectAdapterPosters.setItems(metadata.images.filter { it.imageType == MediaImageType.POSTER }, imageDiffCallback)
val headerPosters = HeaderItem(tvshow.metadata?.metadata?.moviepediaId?.toLong(36)
?: 0, getString(R.string.posters))
items.add(ListRow(headerPosters, arrayObjectAdapterPosters))
}
if (metadata.images.any { it.imageType == MediaImageType.BACKDROP }) {
val arrayObjectAdapterBackdrops = ArrayObjectAdapter(org.videolan.television.ui.MediaImageCardPresenter(requireActivity(), MediaImageType.BACKDROP))
arrayObjectAdapterBackdrops.setItems(metadata.images.filter { it.imageType == MediaImageType.BACKDROP }, imageDiffCallback)
val headerBackdrops = HeaderItem(tvshow.metadata?.metadata?.moviepediaId?.toLong(36)
?: 0, getString(R.string.backdrops))
items.add(ListRow(headerBackdrops, arrayObjectAdapterBackdrops))
}
}
rowsAdapter.setItems(items, object : DiffCallback<Row>() {
override fun areItemsTheSame(oldItem: Row, newItem: Row) = (oldItem is DetailsOverviewRow && newItem is DetailsOverviewRow && (oldItem.item == newItem.item)) || (oldItem is ListRow && newItem is ListRow && oldItem.contentDescription == newItem.contentDescription && oldItem.adapter.size() == newItem.adapter.size() && oldItem.id == newItem.id)
override fun areContentsTheSame(oldItem: Row, newItem: Row): Boolean {
if (oldItem is DetailsOverviewRow && newItem is DetailsOverviewRow) {
return oldItem.item as org.videolan.television.ui.MediaItemDetails == newItem.item as org.videolan.television.ui.MediaItemDetails
}
return true
}
})
rowsAdapter.notifyItemRangeChanged(0, 1)
}
if (!backdropLoaded) loadBackdrop()
}
private fun buildDetails(tvShow: MediaMetadataFull) {
val selector = ClassPresenterSelector()
// Attach your media item details presenter to the row presenter:
val rowPresenter = FullWidthDetailsOverviewRowPresenter(detailsDescriptionPresenter)
val videoPresenter = org.videolan.television.ui.VideoDetailsPresenter(requireActivity(), requireActivity().getScreenWidth())
val activity = requireActivity()
detailsOverview = DetailsOverviewRow(tvShow)
rowPresenter.backgroundColor = ContextCompat.getColor(activity, R.color.orange500)
rowPresenter.onActionClickedListener = OnActionClickedListener { action ->
when (action.id.toInt()) {
ID_RESUME -> {
MediaUtils.openList(activity, viewModel.provider.getResumeMedias(viewModel.updateLiveData.value?.seasons), 0)
}
ID_START_OVER -> {
org.videolan.television.ui.TvUtil.playMedia(activity, viewModel.provider.getAllMedias(viewModel.updateLiveData.value?.seasons))
}
}
}
selector.addClassPresenter(DetailsOverviewRow::class.java, rowPresenter)
selector.addClassPresenter(org.videolan.television.ui.VideoDetailsOverviewRow::class.java, videoPresenter)
selector.addClassPresenter(ListRow::class.java,
ListRowPresenter())
rowsAdapter = ArrayObjectAdapter(selector)
lifecycleScope.launchWhenStarted {
actionsAdapter = SparseArrayObjectAdapter()
val resumableEpisode = getFirstResumableEpisode()
actionsAdapter.set(ID_RESUME, Action(ID_RESUME.toLong(), if (resumableEpisode == null) resources.getString(R.string.resume) else resources.getString(R.string.resume_episode, resumableEpisode.tvEpisodeSubtitle())))
actionsAdapter.set(ID_START_OVER, Action(ID_START_OVER.toLong(), resources.getString(R.string.start_over)))
detailsOverview.actionsAdapter = actionsAdapter
}
lifecycleScope.launchWhenStarted {
if (activity.isFinishing) return@launchWhenStarted
adapter = rowsAdapter
// updateMetadata(mediaMetadataModel.updateLiveData.value)
}
}
private fun getFirstResumableEpisode(): MediaMetadataWithImages? {
val seasons = viewModel.updateLiveData.value?.seasons
seasons?.forEach {
it.episodes.forEach { episode ->
episode.media?.let { media ->
if (media.seen < 1) {
return episode
}
}
}
}
return null
}
}
| gpl-2.0 | 8f2231b558a64cd557baa3be83b70f4e | 49.025641 | 359 | 0.664339 | 5.484188 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/db/QueryUtils.kt | 1 | 732 | package org.tasks.db
import java.util.regex.Pattern
object QueryUtils {
private val HIDDEN = Pattern.compile("tasks\\.hideUntil<=?\\(strftime\\('%s','now'\\)\\*1000\\)")
private val UNCOMPLETED = Pattern.compile("tasks\\.completed<?=0")
private val ORDER = Pattern.compile("order by .*? (asc|desc)", Pattern.CASE_INSENSITIVE)
@JvmStatic
fun showHidden(query: String): String = HIDDEN.matcher(query).replaceAll("1")
@JvmStatic
fun showCompleted(query: String): String = UNCOMPLETED.matcher(query).replaceAll("1")
@JvmStatic
fun showHiddenAndCompleted(query: String): String = showCompleted(showHidden(query))
fun removeOrder(query: String): String = ORDER.matcher(query).replaceAll("")
} | gpl-3.0 | 9ddfb92ccbd14e5381d1a5a40fa768ec | 35.65 | 101 | 0.703552 | 4 | false | false | false | false |
jonalmeida/focus-android | app/src/main/java/org/mozilla/focus/popup/PopupUtils.kt | 1 | 5213 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.popup
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.URLUtil
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.graphics.drawable.toBitmap
import mozilla.components.browser.session.Session
import mozilla.components.support.utils.DrawableUtils
import org.mozilla.focus.R
import java.net.MalformedURLException
import java.net.URL
object PopupUtils {
fun createSecurityPopup(context: Context, session: Session): PopupWindow? {
val isSecure = session.securityInfo.secure
val url = session.url
val res = context.resources
val inflater = LayoutInflater.from(context)
val popUpView = inflater.inflate(R.layout.security_popup, null)
val origin = session.securityInfo.host
val verifierInfo = session.securityInfo.issuer
val hostInfo = popUpView.findViewById<TextView>(R.id.site_identity_title)
val securityInfoIcon = popUpView.findViewById<ImageView>(R.id.site_identity_icon)
val verifier = popUpView.findViewById<TextView>(R.id.verifier)
setOrigin(hostInfo, origin, url)
val identityState = popUpView.findViewById<TextView>(R.id.site_identity_state)
identityState.setText(
if (isSecure)
R.string.security_popup_secure_connection
else
R.string.security_popup_insecure_connection)
if (isSecure) {
setSecurityInfoSecure(context, identityState, verifierInfo, verifier,
securityInfoIcon)
} else {
verifier.visibility = View.GONE
setSecurityInfoInsecure(context, identityState, url, securityInfoIcon)
}
identityState.compoundDrawablePadding = res.getDimension(
R.dimen.doorhanger_drawable_padding).toInt()
return PopupWindow(popUpView, res.getDimension(R.dimen.doorhanger_width).toInt(),
ViewGroup.LayoutParams.WRAP_CONTENT, true)
}
private fun setOrigin(hostInfo: TextView, origin: String?, url: String) {
hostInfo.text = if (!TextUtils.isEmpty(origin)) {
origin
} else {
try {
URL(url).host
} catch (e: MalformedURLException) {
url
}
}
}
private fun setSecurityInfoSecure (
context: Context,
identityState: TextView,
verifierInfo: String?,
verifier: TextView,
securityInfoIcon: ImageView
) {
val photonGreen = ContextCompat.getColor(context, R.color.photonGreen60)
val checkIcon = DrawableUtils.loadAndTintDrawable(context, R.drawable.ic_check, photonGreen)
identityState.setCompoundDrawables(
getScaledDrawable(context, R.dimen.doorhanger_small_icon, checkIcon), null,
null, null)
identityState.setTextColor(photonGreen)
if (!TextUtils.isEmpty(verifierInfo)) {
verifier.text = context.getString(R.string.security_popup_security_verified,
verifierInfo)
verifier.visibility = View.VISIBLE
} else {
verifier.visibility = View.GONE
}
securityInfoIcon.setImageResource(R.drawable.ic_lock)
securityInfoIcon.setColorFilter(photonGreen)
}
private fun setSecurityInfoInsecure (
context: Context,
identityState: TextView,
url: String,
securityInfoIcon: ImageView
) {
identityState.setTextColor(Color.WHITE)
val inactiveColor = ContextCompat.getColor(context, R.color.colorTextInactive)
val photonYellow = ContextCompat.getColor(context, R.color.photonYellow60)
val securityIcon: Drawable
if (URLUtil.isHttpUrl(url)) {
securityInfoIcon.setImageResource(R.drawable.ic_internet)
securityInfoIcon.setColorFilter(inactiveColor)
} else {
securityInfoIcon.setImageResource(R.drawable.ic_warning)
securityInfoIcon.setColorFilter(photonYellow)
securityIcon = DrawableUtils.loadAndTintDrawable(context, R.drawable.ic_warning,
photonYellow)
identityState.setCompoundDrawables(
getScaledDrawable(context, R.dimen.doorhanger_small_icon,
securityIcon),
null,
null, null)
}
}
private fun getScaledDrawable(context: Context, size: Int, drawable: Drawable): Drawable {
val iconSize = context.resources.getDimension(size).toInt()
val icon = BitmapDrawable(context.resources, drawable.toBitmap())
icon.setBounds(0, 0, iconSize, iconSize)
return icon
}
}
| mpl-2.0 | 8040857b0252bdebd926f8a943ab7e54 | 37.330882 | 100 | 0.676002 | 4.61736 | false | false | false | false |
wiltonlazary/kotlin-native | samples/tetris/src/tetrisMain/kotlin/main.kt | 1 | 868 | /*
* Copyright 2010-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/LICENSE.txt file.
*/
package sample.tetris
import kotlinx.cli.*
fun main(args: Array<String>) {
val argParser = ArgParser("tetris", useDefaultHelpShortName = false)
val level by argParser.option(ArgType.Int, shortName = "l", description = "Game level").default(Config.startLevel)
val width by argParser.option(ArgType.Int, shortName = "w", description = "Width of the game field").default(Config.width)
val height by argParser.option(ArgType.Int, shortName = "h", description = "Height of the game field").default(Config.height)
argParser.parse(args)
val visualizer = SDL_Visualizer(width, height)
val game = Game(width, height, visualizer, visualizer)
game.startNewGame(level)
return
} | apache-2.0 | 83dbeb2e5e4cc065493e13acdab7cc19 | 40.380952 | 129 | 0.726959 | 3.773913 | false | true | false | false |
nemerosa/ontrack | ontrack-extension-scm/src/test/java/net/nemerosa/ontrack/extension/scm/catalog/metrics/SCMCatalogMetricsJobTest.kt | 1 | 1842 | package net.nemerosa.ontrack.extension.scm.catalog.metrics
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import net.nemerosa.ontrack.extension.scm.catalog.SCMCatalogFilterService
import net.nemerosa.ontrack.extension.scm.catalog.SCMCatalogProjectFilterLink
import org.junit.Test
import java.util.concurrent.TimeUnit
import kotlin.test.assertEquals
import kotlin.test.assertFalse
class SCMCatalogMetricsJobTest {
@Test
fun `Collection of catalog metrics`() {
val cache: SCMCatalogMetricsCache = mock()
val filterService: SCMCatalogFilterService = mock()
val provider = SCMCatalogMetricsJob(cache, filterService)
val counts = mapOf(
SCMCatalogProjectFilterLink.ALL to 10,
SCMCatalogProjectFilterLink.ENTRY to 8,
SCMCatalogProjectFilterLink.LINKED to 5,
SCMCatalogProjectFilterLink.UNLINKED to 3,
SCMCatalogProjectFilterLink.ORPHAN to 2
)
whenever(filterService.indexCatalogProjectEntries()).thenReturn(counts)
val jobs = provider.startingJobs.toList()
assertEquals(1, jobs.size)
val jobRegistration = jobs.first()
assertEquals(jobRegistration.schedule.initialPeriod, 0)
assertEquals(jobRegistration.schedule.period, 1)
assertEquals(jobRegistration.schedule.unit, TimeUnit.DAYS)
val job = jobRegistration.job
assertFalse(job.isDisabled)
assertEquals("scm", job.key.type.category.key)
assertEquals("catalog-metrics", job.key.type.key)
assertEquals("catalog-metrics", job.key.id)
assertEquals("Collection of SCM Catalog metrics", job.description)
job.task.run { println(it) }
verify(cache).counts = counts
}
} | mit | 5c839f1b4d4c95867d8748cac07a83f5 | 39.065217 | 79 | 0.718784 | 4.675127 | false | true | false | false |
rsiebert/TVHClient | data/src/main/java/org/tvheadend/data/AppRepository.kt | 1 | 1365 | package org.tvheadend.data
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import org.tvheadend.data.source.*
import javax.inject.Inject
class AppRepository @Inject
constructor(
override val channelData: ChannelDataSource,
override val programData: ProgramDataSource,
override val recordingData: RecordingDataSource,
override val seriesRecordingData: SeriesRecordingDataSource,
override val timerRecordingData: TimerRecordingDataSource,
override val connectionData: ConnectionDataSource,
override val channelTagData: ChannelTagDataSource,
override val serverStatusData: ServerStatusDataSource,
override val serverProfileData: ServerProfileDataSource,
override val tagAndChannelData: TagAndChannelDataSource,
override val miscData: MiscDataSource,
override val subscriptionData: SubscriptionDataSource,
override val inputData: InputDataSource
) : RepositoryInterface {
private var isUnlockedLiveData = MutableLiveData<Boolean>()
init {
isUnlockedLiveData.value = false
}
fun getIsUnlockedLiveData(): LiveData<Boolean> = isUnlockedLiveData
fun getIsUnlocked(): Boolean = isUnlockedLiveData.value ?: false
fun setIsUnlocked(unlocked: Boolean) {
isUnlockedLiveData.value = unlocked
}
} | gpl-3.0 | 20cd40aa9c5fc3f3fe8b4d19d486fda1 | 34.947368 | 71 | 0.758974 | 5.571429 | false | false | false | false |
nextcloud/android | app/src/main/java/com/owncloud/android/ui/fragment/ProfileBottomSheetDialog.kt | 1 | 6341 | /*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2021 Tobias Kaminsky
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.fragment
import android.content.ActivityNotFoundException
import android.content.DialogInterface
import android.content.Intent
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.FragmentActivity
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.nextcloud.android.lib.resources.profile.Action
import com.nextcloud.android.lib.resources.profile.HoverCard
import com.nextcloud.client.account.User
import com.owncloud.android.R
import com.owncloud.android.databinding.ProfileBottomSheetActionBinding
import com.owncloud.android.databinding.ProfileBottomSheetFragmentBinding
import com.owncloud.android.utils.DisplayUtils
import com.owncloud.android.utils.theme.ViewThemeUtils
/**
* Show actions of an user
*/
class ProfileBottomSheetDialog(
private val fileActivity: FragmentActivity,
private val user: User,
private val hoverCard: HoverCard,
private val viewThemeUtils: ViewThemeUtils
) : BottomSheetDialog(fileActivity), DisplayUtils.AvatarGenerationListener {
private var _binding: ProfileBottomSheetFragmentBinding? = null
// This property is only valid between onCreateView and onDestroyView.
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = ProfileBottomSheetFragmentBinding.inflate(layoutInflater)
setContentView(binding.root)
if (window != null) {
window!!.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
viewThemeUtils.platform.themeDialog(binding.root)
binding.icon.tag = hoverCard.userId
DisplayUtils.setAvatar(
user,
hoverCard.userId,
hoverCard.displayName,
this,
context.resources.getDimension(R.dimen.list_item_avatar_icon_radius),
context.resources,
binding.icon,
context
)
binding.displayName.text = hoverCard.displayName
for (action in hoverCard.actions) {
val actionBinding = ProfileBottomSheetActionBinding.inflate(
layoutInflater
)
val creatorView: View = actionBinding.root
if (action.appId == "email") {
action.hyperlink = action.title
action.title = context.resources.getString(R.string.write_email)
}
actionBinding.name.text = action.title
val icon = when (action.appId) {
"profile" -> R.drawable.ic_user
"email" -> R.drawable.ic_email
"spreed" -> R.drawable.ic_talk
else -> R.drawable.ic_edit
}
actionBinding.icon.setImageDrawable(
ResourcesCompat.getDrawable(
context.resources,
icon,
null
)
)
viewThemeUtils.platform.tintPrimaryDrawable(context, actionBinding.icon.drawable)
creatorView.setOnClickListener { v: View? ->
send(hoverCard.userId, action)
dismiss()
}
binding.creators.addView(creatorView)
}
setOnShowListener { d: DialogInterface? ->
BottomSheetBehavior.from(binding.root.parent as View)
.setPeekHeight(binding.root.measuredHeight)
}
}
private fun send(userId: String, action: Action) {
when (action.appId) {
"profile" -> openWebsite(action.hyperlink)
"core" -> sendEmail(action.hyperlink)
"spreed" -> openTalk(userId, action.hyperlink)
}
}
private fun openWebsite(url: String) {
DisplayUtils.startLinkIntent(fileActivity, url)
}
private fun sendEmail(email: String) {
val intent = Intent(Intent.ACTION_SENDTO).apply {
data = Uri.parse("mailto:")
putExtra(Intent.EXTRA_EMAIL, arrayOf(email))
}
DisplayUtils.startIntentIfAppAvailable(intent, fileActivity, R.string.no_email_app_available)
}
private fun openTalk(userId: String, hyperlink: String) {
try {
val sharingIntent = Intent(Intent.ACTION_VIEW)
sharingIntent.setClassName(
"com.nextcloud.talk2",
"com.nextcloud.talk.activities.MainActivity"
)
sharingIntent.putExtra("server", user.server.uri)
sharingIntent.putExtra("userId", userId)
fileActivity.startActivity(sharingIntent)
} catch (e: ActivityNotFoundException) {
openWebsite(hyperlink)
}
}
override fun onStop() {
super.onStop()
_binding = null
}
override fun avatarGenerated(avatarDrawable: Drawable?, callContext: Any?) {
if (callContext is ImageView) {
callContext.setImageDrawable(avatarDrawable)
}
}
override fun shouldCallGeneratedCallback(tag: String?, callContext: Any?): Boolean {
if (callContext is ImageView) {
// needs to be changed once federated users have avatars
return callContext.tag.toString() == tag!!.split("@").toTypedArray()[0]
}
return false
}
}
| gpl-2.0 | b392eb562ece6fb0e9894f7d0ef964c4 | 34.824859 | 104 | 0.661725 | 4.79652 | false | false | false | false |
adgvcxz/ViewModel | recyclerviewmodel/src/main/kotlin/com/adgvcxz/recyclerviewmodel/RecyclerAdapter.kt | 1 | 8214 | package com.adgvcxz.recyclerviewmodel
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.adgvcxz.IModel
import com.adgvcxz.IMutation
import com.adgvcxz.addTo
import com.adgvcxz.bindTo
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.functions.Consumer
import io.reactivex.rxjava3.subjects.Subject
import kotlin.reflect.KClass
/**
* zhaowei
* Created by zhaowei on 2017/6/5.
*/
open class RecyclerAdapter(
val viewModel: RecyclerViewModel,
private val configureItem: ((RecyclerItemViewModel<out IModel>) -> IView<*, *>)
) : RecyclerView.Adapter<ItemViewHolder>(), Consumer<DiffUtil.DiffResult> {
private var inflater: LayoutInflater? = null
private var viewMap: HashMap<Int, IView<*, *>?> = HashMap()
private val layoutMap: HashMap<KClass<RecyclerItemViewModel<out IModel>>, Int> = HashMap()
var items: List<RecyclerItemViewModel<out IModel>> = emptyList()
internal var itemClickListener: View.OnClickListener? = null
internal var action: Subject<Int>? = null
private var notify: Boolean = false
private var loading: Boolean = false
val disposables: CompositeDisposable = CompositeDisposable()
val holders = mutableListOf<ItemViewHolder>()
open var isAttachToBind = true
open var disposeWhenDetached = true
private val handler = Handler()
init {
// setHasStableIds(true)
initItems()
items = viewModel.currentModel().items
viewModel.changed = { model, mutation ->
if (viewModel.currentModel().isAnim) {
handler.post { updateByMutation(model.items, mutation) }
}
}
}
private fun initItems() {
viewModel.model.map { it.items }
.filter { !viewModel.currentModel().isAnim }
.subscribe {
updateData()
}.addTo(disposables)
itemClicks()
.filter { items[it] is LoadingItemViewModel }
.map { LoadMore }
.bindTo(viewModel.action)
.addTo(disposables)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
if (inflater == null) {
inflater = LayoutInflater.from(parent.context)
}
val view = inflater!!.inflate(viewType, parent, false)
ifNotNull(view, itemClickListener) { _, listener -> view.setOnClickListener(listener) }
return viewMap[viewType]!!.initView(view, parent)
}
@Suppress("UNCHECKED_CAST")
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
action?.let { holder.itemView.setOnClickListener { _ -> it.onNext(position) } }
if (!isAttachToBind) {
val iView = viewMap[getItemViewType(holder.layoutPosition)]
iView?.let {
holder.disposables.clear()
holders.add(holder)
(it as IView<in ItemViewHolder, RecyclerItemViewModel<out IModel>>)
.bind(holder, items[holder.layoutPosition], holder.layoutPosition)
}
}
checkLoadMore(position)
}
override fun getItemCount(): Int = items.size
@Suppress("UNCHECKED_CAST")
override fun getItemViewType(position: Int): Int {
val model = items[position]
var id = layoutMap[model::class]
if (id == null) {
val type = model::class as KClass<RecyclerItemViewModel<out IModel>>
val view = configureItem.invoke(model)
layoutMap.put(type, view.layoutId)
id = view.layoutId
viewMap.put(id, view)
}
return id
}
@Suppress("UNCHECKED_CAST")
override fun onViewAttachedToWindow(holder: ItemViewHolder) {
super.onViewAttachedToWindow(holder)
if (holder.layoutPosition != RecyclerView.NO_POSITION && isAttachToBind) {
val iView = viewMap[getItemViewType(holder.layoutPosition)]
iView?.let {
(it as IView<in ItemViewHolder, RecyclerItemViewModel<out IModel>>)
.bind(holder, items[holder.layoutPosition], holder.layoutPosition)
}
// viewModel.currentModel().items[holder.layoutPosition].action.onNext(WidgetLifeCircleEvent.Attach)
}
}
override fun onViewDetachedFromWindow(holder: ItemViewHolder) {
super.onViewDetachedFromWindow(holder)
if (holder.layoutPosition != RecyclerView.NO_POSITION) {
// viewModel.currentModel().items[holder.layoutPosition].action.onNext(WidgetLifeCircleEvent.Detach)
holders.remove(holder)
holder.disposables.clear()
}
}
private fun checkLoadMore(position: Int) {
val loadingModel = viewModel.currentModel().loadingViewModel
loadingModel?.let {
loading = if ((position == itemCount - 1) && !viewModel.currentModel().isLoading && !loading) {
viewModel.action.onNext(LoadMore)
true
} else {
false
}
}
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
recyclerView.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
override fun onViewDetachedFromWindow(v: View?) {
if (disposeWhenDetached) {
items.forEach { it.dispose() }
disposables.dispose()
holders.forEach { it.disposables.dispose() }
(0 until recyclerView.childCount).forEach {
val view = recyclerView.getChildAt(it)
val holder = (recyclerView.getChildViewHolder(view) as ItemViewHolder)
holder.disposables.dispose()
}
} else {
disposables.clear()
holders.forEach { it.disposables.clear() }
(0 until recyclerView.childCount).forEach {
val view = recyclerView.getChildAt(it)
val holder = (recyclerView.getChildViewHolder(view) as ItemViewHolder)
holder.disposables.clear()
}
}
}
override fun onViewAttachedToWindow(v: View?) {
if (!disposeWhenDetached && disposables.size() == 0) {
initItems()
notifyDataSetChanged()
}
}
})
}
// override fun getItemId(position: Int): Long {
// return viewModel.currentModel().items[position]._id
// }
override fun accept(result: DiffUtil.DiffResult) {
updateData()
notify = viewModel.currentModel().isRefresh
}
private fun updateData() {
items = viewModel.currentModel().items
notifyDataSetChanged()
}
open fun updateByMutation(items: List<RecyclerItemViewModel<out IModel>>, mutation: IMutation) {
this.items = items
when (mutation) {
is SetData -> notifyDataSetChanged()
is ReplaceData -> {
val min = mutation.index.minOrNull()
val max = mutation.index.minOrNull()
if (min != null && max != null) {
notifyItemRangeChanged(min, max)
}
}
is AppendData -> {
val first = mutation.data.firstOrNull()
if (first != null) {
val firstIndex = items.indexOf(first)
if (firstIndex >= 0) {
notifyItemRangeInserted(firstIndex, mutation.data.size)
}
}
}
is InsertData -> {
notifyItemRangeInserted(mutation.index, mutation.data.size)
}
is RemoveData -> {
for (index in mutation.index) {
notifyItemRemoved(index)
}
}
}
}
} | apache-2.0 | 978ed1557fbaae7ce4f92ebca5f4b263 | 36.511416 | 111 | 0.595569 | 5.182334 | false | false | false | false |
material-components/material-components-android-examples | Reply/app/src/main/java/com/materialstudies/reply/ui/search/SearchFragment.kt | 1 | 3613 | /*
* 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.materialstudies.reply.ui.search
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.google.android.material.transition.MaterialSharedAxis
import com.materialstudies.reply.R
import com.materialstudies.reply.data.SearchSuggestion
import com.materialstudies.reply.data.SearchSuggestionStore
import com.materialstudies.reply.databinding.FragmentSearchBinding
import com.materialstudies.reply.databinding.SearchSuggestionItemBinding
import com.materialstudies.reply.databinding.SearchSuggestionTitleBinding
/**
* A [Fragment] that displays search.
*/
class SearchFragment : Fragment() {
private lateinit var binding: FragmentSearchBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enterTransition = MaterialSharedAxis(MaterialSharedAxis.Z, true).apply {
duration = resources.getInteger(R.integer.reply_motion_duration_large).toLong()
}
returnTransition = MaterialSharedAxis(MaterialSharedAxis.Z, false).apply {
duration = resources.getInteger(R.integer.reply_motion_duration_large).toLong()
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentSearchBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.searchToolbar.setNavigationOnClickListener { findNavController().navigateUp() }
setUpSuggestions(binding.searchSuggestionContainer)
}
private fun setUpSuggestions(suggestionContainer: ViewGroup) {
addSuggestionTitleView(suggestionContainer, R.string.search_suggestion_title_yesterday)
addSuggestionItemViews(suggestionContainer, SearchSuggestionStore.YESTERDAY_SUGGESTIONS)
addSuggestionTitleView(suggestionContainer, R.string.search_suggestion_title_this_week)
addSuggestionItemViews(suggestionContainer, SearchSuggestionStore.THIS_WEEK_SUGGESTIONS)
}
private fun addSuggestionTitleView(parent: ViewGroup, @StringRes titleResId: Int) {
val inflater = LayoutInflater.from(parent.context)
val titleBinding = SearchSuggestionTitleBinding.inflate(inflater, parent, false)
titleBinding.title = titleResId
parent.addView(titleBinding.root)
}
private fun addSuggestionItemViews(parent: ViewGroup, suggestions: List<SearchSuggestion>) {
suggestions.forEach {
val inflater = LayoutInflater.from(parent.context)
val suggestionBinding = SearchSuggestionItemBinding.inflate(inflater, parent, false)
suggestionBinding.suggestion = it
parent.addView(suggestionBinding.root)
}
}
}
| apache-2.0 | 21336c675812c6a8a19403ce6e4d5598 | 40.056818 | 96 | 0.756158 | 4.889039 | false | false | false | false |
niranjan94/show-java | app/src/main/kotlin/com/njlabs/showjava/activities/apps/AppsHandler.kt | 1 | 2694 | /*
* Show Java - A java/apk decompiler for android
* Copyright (c) 2018 Niranjan Rajendran
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.njlabs.showjava.activities.apps
import android.content.Context
import com.njlabs.showjava.R
import com.njlabs.showjava.data.PackageInfo
import com.njlabs.showjava.utils.ktx.isSystemPackage
import com.njlabs.showjava.utils.rx.ProcessStatus
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
class AppsHandler(private var context: Context) {
/**
* Load all installed applications.
*
* @return [Observable] which can be used to track the loading progress and completion state.
*/
fun loadApps(withSystemApps: Boolean): Observable<ProcessStatus<ArrayList<PackageInfo>>> {
return Observable.create { emitter: ObservableEmitter<ProcessStatus<ArrayList<PackageInfo>>> ->
val installedApps = ArrayList<PackageInfo>()
var packages = context.packageManager.getInstalledPackages(0)
packages = packages.filter { pack ->
withSystemApps || !isSystemPackage(pack)
}
packages.forEachIndexed { index, pack ->
val packageInfo = PackageInfo.fromApkPackageInfo(context, pack)
packageInfo.icon = pack.applicationInfo.loadIcon(context.packageManager)
packageInfo.isSystemPackage = isSystemPackage(pack)
installedApps.add(packageInfo)
val currentCount = index + 1
emitter.onNext(
ProcessStatus(
(currentCount.toFloat() / packages.size.toFloat()) * 100f,
context.getString(R.string.loadingApp, packageInfo.label),
context.getString(R.string.loadingStatistic, currentCount, packages.size)
)
)
}
installedApps.sortBy {
it.label.toLowerCase()
}
emitter.onNext(ProcessStatus(installedApps))
emitter.onComplete()
}
}
} | gpl-3.0 | 98c134932cd3559725f0ed2c630b840d | 41.109375 | 103 | 0.663697 | 4.845324 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/theme/ThemeChooserDialog.kt | 1 | 16960 | package org.wikipedia.theme
import android.content.DialogInterface
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.button.MaterialButton
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.functions.Consumer
import org.wikipedia.Constants
import org.wikipedia.Constants.InvokeSource
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.activity.FragmentUtil
import org.wikipedia.analytics.AppearanceChangeFunnel
import org.wikipedia.analytics.eventplatform.AppearanceSettingInteractionEvent
import org.wikipedia.databinding.DialogThemeChooserBinding
import org.wikipedia.events.WebViewInvalidateEvent
import org.wikipedia.page.ExtendedBottomSheetDialogFragment
import org.wikipedia.settings.Prefs
import org.wikipedia.util.DeviceUtil
import org.wikipedia.util.DimenUtil
import org.wikipedia.util.FeedbackUtil
import org.wikipedia.util.ResourceUtil
class ThemeChooserDialog : ExtendedBottomSheetDialogFragment() {
private var _binding: DialogThemeChooserBinding? = null
private val binding get() = _binding!!
interface Callback {
fun onToggleDimImages()
fun onToggleReadingFocusMode()
fun onCancelThemeChooser()
fun onEditingPrefsChanged()
}
private enum class FontSizeAction {
INCREASE, DECREASE, RESET
}
private var app = WikipediaApp.instance
private lateinit var funnel: AppearanceChangeFunnel
private lateinit var appearanceSettingInteractionEvent: AppearanceSettingInteractionEvent
private lateinit var invokeSource: InvokeSource
private val disposables = CompositeDisposable()
private var updatingFont = false
private var isEditing = false
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = DialogThemeChooserBinding.inflate(inflater, container, false)
isEditing = requireArguments().getBoolean(EXTRA_IS_EDITING)
updateComponents()
binding.textSettingsCategory.text = getString(if (isEditing) R.string.theme_category_editing else R.string.theme_category_reading)
binding.buttonDecreaseTextSize.setOnClickListener(FontSizeButtonListener(FontSizeAction.DECREASE))
binding.buttonIncreaseTextSize.setOnClickListener(FontSizeButtonListener(FontSizeAction.INCREASE))
FeedbackUtil.setButtonLongPressToast(binding.buttonDecreaseTextSize, binding.buttonIncreaseTextSize)
binding.buttonThemeLight.setOnClickListener(ThemeButtonListener(Theme.LIGHT))
binding.buttonThemeDark.setOnClickListener(ThemeButtonListener(Theme.DARK))
binding.buttonThemeBlack.setOnClickListener(ThemeButtonListener(Theme.BLACK))
binding.buttonThemeSepia.setOnClickListener(ThemeButtonListener(Theme.SEPIA))
binding.buttonFontFamilySansSerif.setOnClickListener(FontFamilyListener())
binding.buttonFontFamilySerif.setOnClickListener(FontFamilyListener())
binding.themeChooserDarkModeDimImagesSwitch.setOnCheckedChangeListener { _, b -> onToggleDimImages(b) }
binding.themeChooserMatchSystemThemeSwitch.setOnCheckedChangeListener { _, b -> onToggleMatchSystemTheme(b) }
binding.themeChooserReadingFocusModeSwitch.setOnCheckedChangeListener { _, b -> onToggleReadingFocusMode(b) }
binding.textSizeSeekBar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) {
if (!fromUser) {
return
}
val currentMultiplier: Int
if (isEditing) {
currentMultiplier = Prefs.editingTextSizeMultiplier
Prefs.editingTextSizeMultiplier = binding.textSizeSeekBar.value
callback()?.onEditingPrefsChanged()
updateFontSize()
} else {
currentMultiplier = Prefs.textSizeMultiplier
val changed = app.setFontSizeMultiplier(binding.textSizeSeekBar.value)
if (changed) {
updatingFont = true
updateFontSize()
}
}
funnel.logFontSizeChange(currentMultiplier.toFloat(), Prefs.textSizeMultiplier.toFloat())
appearanceSettingInteractionEvent.logFontSizeChange(currentMultiplier.toFloat(), Prefs.textSizeMultiplier.toFloat())
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
})
binding.syntaxHighlightSwitch.setOnCheckedChangeListener { _, isChecked ->
Prefs.editSyntaxHighlightEnabled = isChecked
callback()?.onEditingPrefsChanged()
}
binding.monospaceFontSwitch.setOnCheckedChangeListener { _, isChecked ->
Prefs.editMonoSpaceFontEnabled = isChecked
callback()?.onEditingPrefsChanged()
}
binding.showLineNumbersSwitch.setOnCheckedChangeListener { _, isChecked ->
Prefs.editLineNumbersEnabled = isChecked
callback()?.onEditingPrefsChanged()
}
binding.typingSuggestionsSwitch.setOnCheckedChangeListener { _, isChecked ->
Prefs.editTypingSuggestionsEnabled = isChecked
callback()?.onEditingPrefsChanged()
}
disableBackgroundDim()
requireDialog().window?.let {
DeviceUtil.setNavigationBarColor(it, ResourceUtil.getThemedColor(requireContext(), R.attr.paper_color))
}
disposables.add(WikipediaApp.instance.bus.subscribe(EventBusConsumer()))
return binding.root
}
override fun onStart() {
super.onStart()
BottomSheetBehavior.from(requireView().parent as View).peekHeight = (DimenUtil.displayHeightPx * 0.75).toInt()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
invokeSource = requireArguments().getSerializable(Constants.INTENT_EXTRA_INVOKE_SOURCE) as InvokeSource
funnel = AppearanceChangeFunnel(app, app.wikiSite, invokeSource)
appearanceSettingInteractionEvent = AppearanceSettingInteractionEvent(invokeSource)
}
override fun onDestroyView() {
super.onDestroyView()
disposables.clear()
_binding = null
}
override fun onCancel(dialog: DialogInterface) {
super.onCancel(dialog)
callback()?.onCancelThemeChooser()
}
private fun updateForEditing() {
binding.themeChooserDarkModeDimImagesSwitch.isVisible = !isEditing
binding.readingFocusModeContainer.isVisible = !isEditing
binding.themeChooserReadingFocusModeDescription.isVisible = !isEditing
binding.fontFamilyContainer.isVisible = !isEditing
binding.syntaxHighlightSwitch.isVisible = isEditing
binding.monospaceFontSwitch.isVisible = isEditing
binding.showLineNumbersSwitch.isVisible = isEditing
binding.typingSuggestionsSwitch.isVisible = isEditing
}
private fun onToggleDimImages(enabled: Boolean) {
if (enabled == Prefs.dimDarkModeImages) {
return
}
Prefs.dimDarkModeImages = enabled
callback()?.onToggleDimImages()
}
private fun onToggleMatchSystemTheme(enabled: Boolean) {
if (enabled == Prefs.shouldMatchSystemTheme) {
return
}
Prefs.shouldMatchSystemTheme = enabled
val currentTheme = app.currentTheme
if (isMatchingSystemThemeEnabled) {
when (app.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) {
Configuration.UI_MODE_NIGHT_YES -> if (!app.currentTheme.isDark) {
app.currentTheme = if (!app.unmarshalTheme(Prefs.previousThemeId).isDark) Theme.BLACK else app.unmarshalTheme(Prefs.previousThemeId)
Prefs.previousThemeId = currentTheme.marshallingId
}
Configuration.UI_MODE_NIGHT_NO -> if (app.currentTheme.isDark) {
app.currentTheme = if (app.unmarshalTheme(Prefs.previousThemeId).isDark) Theme.LIGHT else app.unmarshalTheme(Prefs.previousThemeId)
Prefs.previousThemeId = currentTheme.marshallingId
}
}
}
conditionallyDisableThemeButtons()
}
private fun onToggleReadingFocusMode(enabled: Boolean) {
Prefs.readingFocusModeEnabled = enabled
funnel.logReadingFocusMode(enabled)
appearanceSettingInteractionEvent.logReadingFocusMode(enabled)
callback()?.onToggleReadingFocusMode()
}
private fun conditionallyDisableThemeButtons() {
updateThemeButtonAlpha(binding.buttonThemeLight, isMatchingSystemThemeEnabled && app.currentTheme.isDark)
updateThemeButtonAlpha(binding.buttonThemeSepia, isMatchingSystemThemeEnabled && app.currentTheme.isDark)
updateThemeButtonAlpha(binding.buttonThemeDark, isMatchingSystemThemeEnabled && !app.currentTheme.isDark)
updateThemeButtonAlpha(binding.buttonThemeBlack, isMatchingSystemThemeEnabled && !app.currentTheme.isDark)
binding.buttonThemeLight.isEnabled = !isMatchingSystemThemeEnabled || !app.currentTheme.isDark
binding.buttonThemeSepia.isEnabled = !isMatchingSystemThemeEnabled || !app.currentTheme.isDark
binding.buttonThemeDark.isEnabled = !isMatchingSystemThemeEnabled || app.currentTheme.isDark
binding.buttonThemeBlack.isEnabled = !isMatchingSystemThemeEnabled || app.currentTheme.isDark
}
private fun updateThemeButtonAlpha(button: View, translucent: Boolean) {
button.alpha = if (translucent) 0.2f else 1.0f
}
private val isMatchingSystemThemeEnabled: Boolean
get() = Prefs.shouldMatchSystemTheme && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
private fun updateComponents() {
updateFontSize()
updateFontFamily()
updateThemeButtons()
updateDimImagesSwitch()
updateMatchSystemThemeSwitch()
updateForEditing()
binding.themeChooserReadingFocusModeSwitch.isChecked = Prefs.readingFocusModeEnabled
binding.syntaxHighlightSwitch.isChecked = Prefs.editSyntaxHighlightEnabled
binding.monospaceFontSwitch.isChecked = Prefs.editMonoSpaceFontEnabled
binding.showLineNumbersSwitch.isChecked = Prefs.editLineNumbersEnabled
binding.typingSuggestionsSwitch.isChecked = Prefs.editTypingSuggestionsEnabled
}
private fun updateMatchSystemThemeSwitch() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
binding.themeChooserMatchSystemThemeSwitch.visibility = View.VISIBLE
binding.themeChooserMatchSystemThemeSwitch.isChecked = Prefs.shouldMatchSystemTheme
conditionallyDisableThemeButtons()
} else {
binding.themeChooserMatchSystemThemeSwitch.visibility = View.GONE
}
}
private fun updateFontSize() {
val multiplier = if (isEditing) Prefs.editingTextSizeMultiplier else Prefs.textSizeMultiplier
binding.textSizeSeekBar.value = multiplier
val percentStr = getString(R.string.text_size_percent,
(100 * (1 + multiplier * DimenUtil.getFloat(R.dimen.textSizeMultiplierFactor))).toInt())
binding.textSizePercent.text = if (multiplier == 0) getString(R.string.text_size_percent_default, percentStr) else percentStr
if (updatingFont) {
binding.fontChangeProgressBar.visibility = View.VISIBLE
} else {
binding.fontChangeProgressBar.visibility = View.GONE
}
}
private fun updateFontFamily() {
binding.buttonFontFamilySansSerif.strokeWidth = if (Prefs.fontFamily == binding.buttonFontFamilySansSerif.tag) BUTTON_STROKE_WIDTH else 0
binding.buttonFontFamilySerif.strokeWidth = if (Prefs.fontFamily == binding.buttonFontFamilySerif.tag) BUTTON_STROKE_WIDTH else 0
}
private fun updateThemeButtons() {
updateThemeButtonStroke(binding.buttonThemeLight, app.currentTheme === Theme.LIGHT)
updateThemeButtonStroke(binding.buttonThemeSepia, app.currentTheme === Theme.SEPIA)
updateThemeButtonStroke(binding.buttonThemeDark, app.currentTheme === Theme.DARK)
updateThemeButtonStroke(binding.buttonThemeBlack, app.currentTheme === Theme.BLACK)
}
private fun updateThemeButtonStroke(button: MaterialButton, selected: Boolean) {
button.strokeWidth = if (selected) BUTTON_STROKE_WIDTH else 0
button.isClickable = !selected
}
private fun updateDimImagesSwitch() {
binding.themeChooserDarkModeDimImagesSwitch.isChecked = Prefs.dimDarkModeImages
binding.themeChooserDarkModeDimImagesSwitch.isEnabled = app.currentTheme.isDark
binding.themeChooserDarkModeDimImagesSwitch.setTextColor(if (binding.themeChooserDarkModeDimImagesSwitch.isEnabled)
ResourceUtil.getThemedColor(requireContext(), R.attr.section_title_color) else ContextCompat.getColor(requireContext(), R.color.black26))
}
private inner class ThemeButtonListener(private val theme: Theme) : View.OnClickListener {
override fun onClick(v: View) {
if (app.currentTheme !== theme) {
funnel.logThemeChange(app.currentTheme, theme)
appearanceSettingInteractionEvent.logThemeChange(app.currentTheme, theme)
app.currentTheme = theme
}
}
}
private inner class FontFamilyListener : View.OnClickListener {
override fun onClick(v: View) {
if (v.tag != null) {
val newFontFamily = v.tag as String
funnel.logFontThemeChange(Prefs.fontFamily, newFontFamily)
appearanceSettingInteractionEvent.logFontThemeChange(Prefs.fontFamily, newFontFamily)
app.setFontFamily(newFontFamily)
}
}
}
private inner class FontSizeButtonListener(private val action: FontSizeAction) : View.OnClickListener {
override fun onClick(view: View) {
val currentMultiplier: Int
if (isEditing) {
currentMultiplier = Prefs.editingTextSizeMultiplier
Prefs.editingTextSizeMultiplier = app.constrainFontSizeMultiplier(
when (action) {
FontSizeAction.INCREASE -> currentMultiplier + 1
FontSizeAction.DECREASE -> currentMultiplier - 1
FontSizeAction.RESET -> 0
})
callback()?.onEditingPrefsChanged()
updateFontSize()
} else {
currentMultiplier = Prefs.textSizeMultiplier
val changed = when (action) {
FontSizeAction.INCREASE -> {
app.setFontSizeMultiplier(Prefs.textSizeMultiplier + 1)
}
FontSizeAction.DECREASE -> {
app.setFontSizeMultiplier(Prefs.textSizeMultiplier - 1)
}
FontSizeAction.RESET -> {
app.setFontSizeMultiplier(0)
}
}
if (changed) {
updatingFont = true
updateFontSize()
}
}
funnel.logFontSizeChange(currentMultiplier.toFloat(), Prefs.textSizeMultiplier.toFloat())
appearanceSettingInteractionEvent.logFontSizeChange(currentMultiplier.toFloat(), Prefs.textSizeMultiplier.toFloat())
}
}
private inner class EventBusConsumer : Consumer<Any> {
override fun accept(event: Any) {
if (event is WebViewInvalidateEvent) {
updatingFont = false
updateComponents()
}
}
}
fun callback(): Callback? {
return FragmentUtil.getCallback(this, Callback::class.java)
}
companion object {
private const val EXTRA_IS_EDITING = "isEditing"
private val BUTTON_STROKE_WIDTH = DimenUtil.roundedDpToPx(2f)
fun newInstance(source: InvokeSource, isEditing: Boolean = false): ThemeChooserDialog {
return ThemeChooserDialog().apply {
arguments = bundleOf(Constants.INTENT_EXTRA_INVOKE_SOURCE to source,
EXTRA_IS_EDITING to isEditing)
}
}
}
}
| apache-2.0 | 475db1e17357c0c93abdf5e2fa20613b | 45.465753 | 152 | 0.693455 | 5.313283 | false | false | false | false |
google-developer-training/basic-android-kotlin-compose-training-cupcake | app/src/main/java/com/example/cupcake/ui/theme/Theme.kt | 1 | 1658 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.cupcake.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
private val DarkColorPalette = darkColors(
primary = Pink400,
primaryVariant = Pink950,
onPrimary = Black,
secondary = Purple400,
secondaryVariant = Purple400,
onSecondary = Black
)
private val LightColorPalette = lightColors(
primary = Pink600,
primaryVariant = Pink950,
onPrimary = White,
secondary = Purple400,
secondaryVariant = Purple700,
onSecondary = Black
)
@Composable
fun CupcakeTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
}
| apache-2.0 | 76bcdde01b75e7733ea3e20f56bc65b2 | 28.607143 | 95 | 0.721351 | 4.605556 | false | false | false | false |
stripe/stripe-android | identity/src/main/java/com/stripe/android/identity/states/IDDetectorTransitioner.kt | 1 | 9533 | package com.stripe.android.identity.states
import android.util.Log
import com.stripe.android.camera.framework.time.Clock
import com.stripe.android.camera.framework.time.ClockMark
import com.stripe.android.camera.framework.time.milliseconds
import com.stripe.android.identity.ml.AnalyzerInput
import com.stripe.android.identity.ml.AnalyzerOutput
import com.stripe.android.identity.ml.BoundingBox
import com.stripe.android.identity.ml.Category
import com.stripe.android.identity.ml.IDDetectorOutput
import com.stripe.android.identity.states.IdentityScanState.Found
import com.stripe.android.identity.states.IdentityScanState.Initial
import com.stripe.android.identity.states.IdentityScanState.Satisfied
import com.stripe.android.identity.states.IdentityScanState.ScanType
import com.stripe.android.identity.states.IdentityScanState.Unsatisfied
import kotlin.math.max
import kotlin.math.min
/**
* [IdentityScanStateTransitioner] for IDDetector model, decides transition based on the
* Intersection Over Union(IoU) score of bounding boxes.
*
* * The transitioner first checks if the ML output [Category] matches desired [ScanType], a mismatch
* would not necessarily break the check, but will accumulate the [unmatchedFrame] streak,
* see [outputMatchesTargetType] for details.
* * Then it checks the IoU score, if the score is below threshold, then stays at Found state and
* reset the [Found.reachedStateAt] timer.
* * Finally it checks since the time elapsed since [Found] is reached, if it passed
* [timeRequired], then transitions to [Satisfied], otherwise stays in [Found].
*/
internal class IDDetectorTransitioner(
private val timeoutAt: ClockMark,
private val iouThreshold: Float = DEFAULT_IOU_THRESHOLD,
private val timeRequired: Int = DEFAULT_TIME_REQUIRED,
private val allowedUnmatchedFrames: Int = DEFAULT_ALLOWED_UNMATCHED_FRAME,
private val displaySatisfiedDuration: Int = DEFAULT_DISPLAY_SATISFIED_DURATION,
private val displayUnsatisfiedDuration: Int = DEFAULT_DISPLAY_UNSATISFIED_DURATION
) : IdentityScanStateTransitioner {
private var previousBoundingBox: BoundingBox? = null
private var unmatchedFrame = 0
override suspend fun transitionFromInitial(
initialState: Initial,
analyzerInput: AnalyzerInput,
analyzerOutput: AnalyzerOutput
): IdentityScanState {
require(analyzerOutput is IDDetectorOutput) {
"Unexpected output type: $analyzerOutput"
}
return when {
timeoutAt.hasPassed() -> {
IdentityScanState.TimeOut(initialState.type, this)
}
analyzerOutput.category.matchesScanType(initialState.type) -> {
Log.d(
TAG,
"Matching model output detected with score ${analyzerOutput.resultScore}, " +
"transition to Found."
)
Found(initialState.type, this)
}
else -> {
Log.d(
TAG,
"Model outputs ${analyzerOutput.category}, which doesn't match with " +
"scanType ${initialState.type}, stay in Initial"
)
initialState
}
}
}
override suspend fun transitionFromFound(
foundState: Found,
analyzerInput: AnalyzerInput,
analyzerOutput: AnalyzerOutput
): IdentityScanState {
require(analyzerOutput is IDDetectorOutput) {
"Unexpected output type: $analyzerOutput"
}
return when {
timeoutAt.hasPassed() -> {
IdentityScanState.TimeOut(foundState.type, foundState.transitioner)
}
!outputMatchesTargetType(analyzerOutput.category, foundState.type) -> Unsatisfied(
"Type ${analyzerOutput.category} doesn't match ${foundState.type}",
foundState.type,
foundState.transitioner
)
!iOUCheckPass(analyzerOutput.boundingBox) -> {
// reset timer of the foundState
foundState.reachedStateAt = Clock.markNow()
foundState
}
moreResultsRequired(foundState) -> foundState
else -> {
Satisfied(foundState.type, foundState.transitioner)
}
}
}
override suspend fun transitionFromSatisfied(
satisfiedState: Satisfied,
analyzerInput: AnalyzerInput,
analyzerOutput: AnalyzerOutput
): IdentityScanState {
return if (satisfiedState.reachedStateAt.elapsedSince() > displaySatisfiedDuration.milliseconds) {
Log.d(TAG, "Scan for ${satisfiedState.type} Satisfied, transition to Finished.")
IdentityScanState.Finished(satisfiedState.type, this)
} else {
satisfiedState
}
}
override suspend fun transitionFromUnsatisfied(
unsatisfiedState: Unsatisfied,
analyzerInput: AnalyzerInput,
analyzerOutput: AnalyzerOutput
): IdentityScanState {
return when {
timeoutAt.hasPassed() -> {
IdentityScanState.TimeOut(unsatisfiedState.type, this)
}
unsatisfiedState.reachedStateAt.elapsedSince() > displayUnsatisfiedDuration.milliseconds -> {
Log.d(
TAG,
"Scan for ${unsatisfiedState.type} Unsatisfied with reason ${unsatisfiedState.reason}, transition to Initial."
)
Initial(unsatisfiedState.type, this)
}
else -> {
unsatisfiedState
}
}
}
/**
* Compare the ML output [Category] and the target [ScanType].
*
* If it's a match, then return true and reset the [unmatchedFrame] streak count.
* If it's a unmatch, increase [unmatchedFrame] by one,
* * If it's still within [allowedUnmatchedFrames], return true
* * Otherwise return false
*
*/
private fun outputMatchesTargetType(
outputCategory: Category,
targetScanType: ScanType
): Boolean {
return if (outputCategory.matchesScanType(targetScanType)) {
// if it's a match, clear the unmatched frame streak count
unmatchedFrame = 0
true
} else {
// if it's an unmatch, check if it's still within allowedUnmatchedFrames
unmatchedFrame++
unmatchedFrame <= allowedUnmatchedFrames
}
}
/**
* Calculate the IoU between new box and old box.
*
* returns true if previous box is null or the result is above the threshold,
* returns false otherwise.
*/
private fun iOUCheckPass(newBoundingBox: BoundingBox): Boolean {
return previousBoundingBox?.let { previousBox ->
val iou = intersectionOverUnion(newBoundingBox, previousBox)
previousBoundingBox = newBoundingBox
return iou >= iouThreshold
} ?: run {
previousBoundingBox = newBoundingBox
true
}
}
private fun moreResultsRequired(foundState: Found): Boolean {
return foundState.reachedStateAt.elapsedSince() < timeRequired.milliseconds
}
/**
* Calculate IoU of two boxes, see https://stackoverflow.com/a/41660682/802372
*/
private fun intersectionOverUnion(boxA: BoundingBox, boxB: BoundingBox): Float {
val aLeft = boxA.left
val aRight = boxA.left + boxA.width
val aTop = boxA.top
val aBottom = boxA.top + boxA.height
val bLeft = boxB.left
val bRight = boxB.left + boxB.width
val bTop = boxB.top
val bBottom = boxB.top + boxB.height
// determine the (x, y)-coordinates of the intersection rectangle
val xA = max(aLeft, bLeft)
val yA = max(aTop, bTop)
val xB = min(aRight, bRight)
val yB = min(aBottom, bBottom)
// compute the area of intersection rectangle
val interArea = (xB - xA) * (yB - yA)
// compute the area of both the prediction and ground-truth
// rectangles
val boxAArea = (aRight - aLeft) * (aBottom - aTop)
val boxBArea = (bRight - bLeft) * (bBottom - bTop)
// compute the intersection over union by taking the intersection
// area and dividing it by the sum of prediction + ground-truth
// areas - the intersection area
return interArea / (boxAArea + boxBArea - interArea)
}
private companion object {
const val DEFAULT_TIME_REQUIRED = 500
const val DEFAULT_IOU_THRESHOLD = 0.95f
const val DEFAULT_ALLOWED_UNMATCHED_FRAME = 1
const val DEFAULT_DISPLAY_SATISFIED_DURATION = 0
const val DEFAULT_DISPLAY_UNSATISFIED_DURATION = 0
val TAG: String = IDDetectorTransitioner::class.java.simpleName
}
/**
* Checks if [Category] matches [IdentityScanState].
* Note: the ML model will output ID_FRONT or ID_BACK for both ID and Driver License.
*/
private fun Category.matchesScanType(scanType: ScanType): Boolean {
return this == Category.ID_BACK && scanType == ScanType.ID_BACK ||
this == Category.ID_FRONT && scanType == ScanType.ID_FRONT ||
this == Category.ID_BACK && scanType == ScanType.DL_BACK ||
this == Category.ID_FRONT && scanType == ScanType.DL_FRONT ||
this == Category.PASSPORT && scanType == ScanType.PASSPORT
}
}
| mit | 954b5f130af876ed871f31fcef8a68e1 | 39.394068 | 130 | 0.64261 | 4.57877 | false | false | false | false |
AlexLandau/semlang | kotlin/semlang-interpreter/src/main/kotlin/NativeFunctions.kt | 1 | 21474 | package net.semlang.interpreter
import net.semlang.api.*
import java.math.BigInteger
import java.util.*
typealias InterpreterCallback = (SemObject.FunctionBinding, List<SemObject>) -> SemObject
class NativeFunction(val id: EntityId, val apply: (List<SemObject>, InterpreterCallback) -> SemObject)
fun getNativeFunctions(): Map<EntityId, NativeFunction> {
val list = ArrayList<NativeFunction>()
addBooleanFunctions(list)
addIntegerFunctions(list)
addListFunctions(list)
addMaybeFunctions(list)
addSequenceFunctions(list)
addDataFunctions(list)
addNativeOpaqueTypeFunctions(list)
return toMap(list)
}
fun toMap(list: ArrayList<NativeFunction>): Map<EntityId, NativeFunction> {
val map = HashMap<EntityId, NativeFunction>()
list.forEach { nativeFunction ->
val previouslyThere = map.put(nativeFunction.id, nativeFunction)
if (previouslyThere != null) {
error("Defined two native functions with the ID " + nativeFunction.id)
}
}
return map
}
private fun addBooleanFunctions(list: MutableList<NativeFunction>) {
val booleanDot = fun(name: String) = EntityId.of("Boolean", name)
// Boolean.not
list.add(NativeFunction(booleanDot("not"), { args: List<SemObject>, _: InterpreterCallback ->
val bool = args[0] as? SemObject.Boolean ?: typeError()
SemObject.Boolean(!bool.value)
}))
// Boolean.and
list.add(NativeFunction(booleanDot("and"), { args: List<SemObject>, _: InterpreterCallback ->
val left = args[0] as? SemObject.Boolean ?: typeError()
val right = args[1] as? SemObject.Boolean ?: typeError()
SemObject.Boolean(left.value && right.value)
}))
// Boolean.or
list.add(NativeFunction(booleanDot("or"), { args: List<SemObject>, _: InterpreterCallback ->
val left = args[0] as? SemObject.Boolean ?: typeError()
val right = args[1] as? SemObject.Boolean ?: typeError()
SemObject.Boolean(left.value || right.value)
}))
// TODO: Use as optimizations for the standard library
// // Boolean.any
// list.add(NativeFunction(booleanDot("any"), { args: List<SemObject>, _: InterpreterCallback ->
// val list = args[0] as? SemObject.SemList ?: typeError()
// val anyTrue = list.contents.any { obj ->
// val boolean = obj as? SemObject.Boolean ?: typeError()
// boolean.value
// }
// SemObject.Boolean(anyTrue)
// }))
//
// // Boolean.all
// list.add(NativeFunction(booleanDot("all"), { args: List<SemObject>, _: InterpreterCallback ->
// val list = args[0] as? SemObject.SemList ?: typeError()
// val allTrue = list.contents.all { obj ->
// val boolean = obj as? SemObject.Boolean ?: typeError()
// boolean.value
// }
// SemObject.Boolean(allTrue)
// }))
}
private fun addIntegerFunctions(list: MutableList<NativeFunction>) {
val integerDot = fun(name: String) = EntityId.of("Integer", name)
// Integer.plus
list.add(NativeFunction(integerDot("plus"), { args: List<SemObject>, _: InterpreterCallback ->
val left = args[0] as? SemObject.Integer ?: typeError()
val right = args[1] as? SemObject.Integer ?: typeError()
SemObject.Integer(left.value + right.value)
}))
// Integer.minus
list.add(NativeFunction(integerDot("minus"), { args: List<SemObject>, _: InterpreterCallback ->
val left = args[0] as? SemObject.Integer ?: typeError()
val right = args[1] as? SemObject.Integer ?: typeError()
SemObject.Integer(left.value - right.value)
}))
// Integer.times
list.add(NativeFunction(integerDot("times"), { args: List<SemObject>, _: InterpreterCallback ->
val left = args[0] as? SemObject.Integer ?: typeError()
val right = args[1] as? SemObject.Integer ?: typeError()
SemObject.Integer(left.value * right.value)
}))
// Integer.dividedBy
list.add(NativeFunction(integerDot("dividedBy"), { args: List<SemObject>, _: InterpreterCallback ->
val left = args[0] as? SemObject.Integer ?: typeError()
val right = args[1] as? SemObject.Integer ?: typeError()
if (right.value == BigInteger.ZERO) {
SemObject.Maybe.Failure
} else {
SemObject.Maybe.Success(SemObject.Integer(left.value / right.value))
}
}))
// Integer.modulo
list.add(NativeFunction(integerDot("modulo"), { args: List<SemObject>, _: InterpreterCallback ->
val left = args[0] as? SemObject.Integer ?: typeError()
val right = args[1] as? SemObject.Integer ?: typeError()
if (right.value < BigInteger.ONE) {
SemObject.Maybe.Failure
} else {
SemObject.Maybe.Success(SemObject.Integer(left.value.mod(right.value)))
}
}))
// Integer.equals
list.add(NativeFunction(integerDot("equals"), { args: List<SemObject>, _: InterpreterCallback ->
val left = args[0] as? SemObject.Integer ?: typeError()
val right = args[1] as? SemObject.Integer ?: typeError()
SemObject.Boolean(left.value == right.value)
}))
// Integer.lessThan
list.add(NativeFunction(integerDot("lessThan"), { args: List<SemObject>, _: InterpreterCallback ->
val left = args[0] as? SemObject.Integer ?: typeError()
val right = args[1] as? SemObject.Integer ?: typeError()
SemObject.Boolean(left.value < right.value)
}))
// Integer.greaterThan
list.add(NativeFunction(integerDot("greaterThan"), { args: List<SemObject>, _: InterpreterCallback ->
val left = args[0] as? SemObject.Integer ?: typeError()
val right = args[1] as? SemObject.Integer ?: typeError()
SemObject.Boolean(left.value > right.value)
}))
// TODO: Future standard library optimization
// // Integer.sum
// list.add(NativeFunction(integerDot("sum"), { args: List<SemObject>, _: InterpreterCallback ->
// val list = args[0] as? SemObject.SemList ?: typeError()
// val sum = list.contents.foldRight(BigInteger.ZERO, { semObj, sumSoFar ->
// val int = semObj as? SemObject.Integer ?: typeError()
// sumSoFar + int.value
// })
// SemObject.Integer(sum)
// }))
}
private fun addListFunctions(list: MutableList<NativeFunction>) {
val listDot = fun(name: String) = EntityId.of("List", name)
// List.append
list.add(NativeFunction(listDot("append"), { args: List<SemObject>, _: InterpreterCallback ->
val list = args[0] as? SemObject.SemList ?: typeError()
val item = args[1]
SemObject.SemList(list.contents + item)
}))
// List.appendFront
list.add(NativeFunction(listDot("appendFront"), { args: List<SemObject>, _: InterpreterCallback ->
val list = args[0] as? SemObject.SemList ?: typeError()
val item = args[1]
SemObject.SemList(listOf(item) + list.contents)
}))
// List.concatenate
list.add(NativeFunction(listDot("concatenate"), { args: List<SemObject>, _: InterpreterCallback ->
val lists = args[0] as? SemObject.SemList ?: typeError()
val concatenated = ArrayList<SemObject>()
for (list in lists.contents) {
if (list !is SemObject.SemList) {
typeError()
}
concatenated.addAll(list.contents)
}
SemObject.SemList(concatenated)
}))
// List.subList
list.add(NativeFunction(listDot("subList"), { args: List<SemObject>, _: InterpreterCallback ->
val list = args[0] as? SemObject.SemList ?: typeError()
val startInclusive = (args[1] as? SemObject.Natural)?.value?.intValueExact() ?: typeError()
val endExclusive = (args[2] as? SemObject.Natural)?.value?.intValueExact() ?: typeError()
if (startInclusive > endExclusive || endExclusive > list.contents.size) {
SemObject.Maybe.Failure
} else {
val sublist = list.contents.subList(startInclusive, endExclusive)
SemObject.Maybe.Success(SemObject.SemList(sublist))
}
}))
// List.filter
list.add(NativeFunction(listDot("filter"), { args: List<SemObject>, apply: InterpreterCallback ->
val list = args[0] as? SemObject.SemList ?: typeError()
val filter = args[1] as? SemObject.FunctionBinding ?: typeError()
val filtered = list.contents.filter { semObject ->
val callbackResult = apply(filter, listOf(semObject))
(callbackResult as? SemObject.Boolean)?.value ?: error("")
}
SemObject.SemList(filtered)
}))
// List.map
list.add(NativeFunction(listDot("map"), { args: List<SemObject>, apply: InterpreterCallback ->
val list = args[0] as? SemObject.SemList ?: typeError()
val mapping = args[1] as? SemObject.FunctionBinding ?: typeError()
val mapped = list.contents.map { semObject ->
apply(mapping, listOf(semObject))
}
SemObject.SemList(mapped)
}))
// List.flatMap
list.add(NativeFunction(listDot("flatMap"), { args: List<SemObject>, apply: InterpreterCallback ->
val list = args[0] as? SemObject.SemList ?: typeError()
val mapping = args[1] as? SemObject.FunctionBinding ?: typeError()
val mapped = list.contents.flatMap { semObject ->
(apply(mapping, listOf(semObject)) as? SemObject.SemList ?: typeError()).contents
}
SemObject.SemList(mapped)
}))
// List.reduce
list.add(NativeFunction(listDot("reduce"), { args: List<SemObject>, apply: InterpreterCallback ->
val list = args[0] as? SemObject.SemList ?: typeError()
var result = args[1]
val reducer = args[2] as? SemObject.FunctionBinding ?: typeError()
list.contents.forEach { item ->
result = apply(reducer, listOf(result, item))
}
result
}))
// List.forEach
list.add(NativeFunction(listDot("forEach"), { args: List<SemObject>, apply: InterpreterCallback ->
val list = args[0] as? SemObject.SemList ?: typeError()
val action = args[1] as? SemObject.FunctionBinding ?: typeError()
list.contents.forEach { item ->
apply(action, listOf(item))
}
SemObject.Void
}))
// List.size
list.add(NativeFunction(listDot("size"), { args: List<SemObject>, _: InterpreterCallback ->
val list = args[0] as? SemObject.SemList ?: typeError()
SemObject.Natural(BigInteger.valueOf(list.contents.size.toLong()))
}))
// List.get
list.add(NativeFunction(listDot("get"), { args: List<SemObject>, _: InterpreterCallback ->
val list = args[0] as? SemObject.SemList ?: typeError()
val index = args[1] as? SemObject.Natural ?: typeError()
try {
SemObject.Maybe.Success(list.contents[index.value.toInt()])
} catch (e: IndexOutOfBoundsException) {
SemObject.Maybe.Failure
}
}))
// TODO: Find a way to keep in implementations for standard library functions
// // List.first
// list.add(NativeFunction(listDot("first"), { args: List<SemObject>, _: InterpreterCallback ->
// val list = args[0] as? SemObject.SemList ?: typeError()
// if (list.contents.isEmpty()) {
// SemObject.Try.Failure
// } else {
// SemObject.Try.Success(list.contents[0])
// }
// }))
// // List.last
// list.add(NativeFunction(listDot("last"), { args: List<SemObject>, _: InterpreterCallback ->
// val list = args[0] as? SemObject.SemList ?: typeError()
// if (list.contents.isEmpty()) {
// SemObject.Try.Failure
// } else {
// SemObject.Try.Success(list.contents.last())
// }
// }))
}
private fun addMaybeFunctions(list: MutableList<NativeFunction>) {
val maybeDot = fun(name: String) = EntityId.of("Maybe", name)
// Maybe.success
list.add(NativeFunction(maybeDot("success"), { args: List<SemObject>, _: InterpreterCallback ->
SemObject.Maybe.Success(args[0])
}))
// Maybe.failure
list.add(NativeFunction(maybeDot("failure"), { _: List<SemObject>, _: InterpreterCallback ->
SemObject.Maybe.Failure
}))
// Maybe.assume
list.add(NativeFunction(maybeDot("assume"), { args: List<SemObject>, _: InterpreterCallback ->
val theMaybe = args[0] as? SemObject.Maybe ?: typeError()
val success = theMaybe as? SemObject.Maybe.Success ?: throw IllegalStateException("Try.assume assumed incorrectly")
success.contents
}))
// Maybe.isSuccess
list.add(NativeFunction(maybeDot("isSuccess"), { args: List<SemObject>, apply: InterpreterCallback ->
val theMaybe = args[0] as? SemObject.Maybe ?: typeError()
SemObject.Boolean(theMaybe is SemObject.Maybe.Success)
}))
// Maybe.map
list.add(NativeFunction(maybeDot("map"), { args: List<SemObject>, apply: InterpreterCallback ->
val theMaybe = args[0] as? SemObject.Maybe ?: typeError()
val theFunction = args[1] as? SemObject.FunctionBinding ?: typeError()
when (theMaybe) {
is SemObject.Maybe.Success -> {
SemObject.Maybe.Success(apply(theFunction, listOf(theMaybe.contents)))
}
is SemObject.Maybe.Failure -> theMaybe
}
}))
// Maybe.flatMap
list.add(NativeFunction(maybeDot("flatMap"), { args: List<SemObject>, apply: InterpreterCallback ->
val theMaybe = args[0] as? SemObject.Maybe ?: typeError()
val theFunction = args[1] as? SemObject.FunctionBinding ?: typeError()
when (theMaybe) {
is SemObject.Maybe.Success -> {
apply(theFunction, listOf(theMaybe.contents))
}
is SemObject.Maybe.Failure -> theMaybe
}
}))
// Maybe.orElse
list.add(NativeFunction(maybeDot("orElse"), { args: List<SemObject>, apply: InterpreterCallback ->
val theMaybe = args[0] as? SemObject.Maybe ?: typeError()
val alternative = args[1]
when (theMaybe) {
is SemObject.Maybe.Success -> {
theMaybe.contents
}
is SemObject.Maybe.Failure -> alternative
}
}))
}
private fun addSequenceFunctions(list: MutableList<NativeFunction>) {
// Sequence.get
list.add(NativeFunction(EntityId.of("Sequence", "get"), { args: List<SemObject>, apply: InterpreterCallback ->
val sequence = args[0] as? SemObject.Struct ?: typeError()
val index = args[1] as? SemObject.Natural ?: typeError()
if (sequence.struct.id != NativeStruct.SEQUENCE.id) {
typeError()
}
val successor = sequence.objects[1] as? SemObject.FunctionBinding ?: typeError()
var value = sequence.objects[0]
// TODO: Obscure error case: Value of index is greater than Long.MAX_VALUE
for (i in 1..index.value.longValueExact()) {
value = apply(successor, listOf(value))
}
value
}))
// Sequence.first
list.add(NativeFunction(EntityId.of("Sequence", "first"), SequenceFirst@ { args: List<SemObject>, apply: InterpreterCallback ->
val sequence = args[0] as? SemObject.Struct ?: typeError()
val predicate = args[1] as? SemObject.FunctionBinding ?: typeError()
if (sequence.struct.id != NativeStruct.SEQUENCE.id) {
typeError()
}
val successor = sequence.objects[1] as? SemObject.FunctionBinding ?: typeError()
var value = sequence.objects[0]
while (true) {
val passes = apply(predicate, listOf(value)) as? SemObject.Boolean ?: typeError()
if (passes.value) {
return@SequenceFirst value
}
value = apply(successor, listOf(value))
}
error("Unreachable") // TODO: Better way to make Kotlin compile here?
}))
}
private fun dataEquals(left: SemObject, right: SemObject): Boolean {
return when (left) {
is SemObject.Integer -> {
if (right !is SemObject.Integer) typeError()
left.value == right.value
}
is SemObject.Natural -> {
if (right !is SemObject.Natural) typeError()
left.value == right.value
}
is SemObject.Boolean -> {
if (right !is SemObject.Boolean) typeError()
left.value == right.value
}
is SemObject.Struct -> {
if (right !is SemObject.Struct) typeError()
if (left.struct != right.struct) typeError()
dataListsEqual(left.objects, right.objects)
}
is SemObject.Union -> {
if (right !is SemObject.Union) typeError()
if (left.union != right.union) typeError()
left.optionIndex == right.optionIndex &&
((left.contents == null && right.contents == null)
|| (left.contents != null && right.contents != null && dataEquals(left.contents, right.contents)))
}
is SemObject.Maybe.Success -> {
if (right !is SemObject.Maybe) typeError()
right is SemObject.Maybe.Success && dataEquals(left.contents, right.contents)
}
SemObject.Maybe.Failure -> {
if (right !is SemObject.Maybe) typeError()
right is SemObject.Maybe.Failure
}
is SemObject.SemList -> {
if (right !is SemObject.SemList) typeError()
dataListsEqual(left.contents, right.contents)
}
is SemObject.SemString -> {
if (right !is SemObject.SemString) typeError()
left.contents == right.contents
}
is SemObject.FunctionBinding -> typeError()
is SemObject.TextOut -> typeError()
is SemObject.ListBuilder -> typeError()
is SemObject.Var -> typeError()
is SemObject.Int64 -> {
if (right !is SemObject.Int64) typeError()
left.value == right.value
}
is SemObject.Mock -> typeError()
}
}
private fun dataListsEqual(left: List<SemObject>, right: List<SemObject>): Boolean {
if (left.size != right.size) {
return false
}
return left.zip(right).all { (l, r) -> dataEquals(l, r) }
}
private fun addDataFunctions(list: MutableList<NativeFunction>) {
// Data.equals
list.add(NativeFunction(EntityId.of("Data", "equals"), { args: List<SemObject>, _: InterpreterCallback ->
val left = args[0]
val right = args[1]
val areEqual = dataEquals(left, right)
SemObject.Boolean(areEqual)
}))
}
private fun addNativeOpaqueTypeFunctions(list: MutableList<NativeFunction>) {
// TextOut.print
list.add(NativeFunction(EntityId.of("TextOut", "print"), { args: List<SemObject>, _: InterpreterCallback ->
val out = args[0] as? SemObject.TextOut ?: typeError()
val text = args[1] as? SemObject.SemString ?: typeError()
out.out.print(text.contents)
SemObject.Void
}))
// ListBuilder.create
list.add(NativeFunction(EntityId.of("ListBuilder"), { _: List<SemObject>, _: InterpreterCallback ->
SemObject.ListBuilder(ArrayList())
}))
// ListBuilder.append
list.add(NativeFunction(EntityId.of("ListBuilder", "append"), { args: List<SemObject>, _: InterpreterCallback ->
val builder = args[0] as? SemObject.ListBuilder ?: typeError()
val itemToAdd = args[1]
builder.listSoFar.add(itemToAdd)
SemObject.Void
}))
// ListBuilder.appendAll
list.add(NativeFunction(EntityId.of("ListBuilder", "appendAll"), { args: List<SemObject>, _: InterpreterCallback ->
val builder = args[0] as? SemObject.ListBuilder ?: typeError()
val itemsToAdd = args[1] as? SemObject.SemList ?: typeError()
builder.listSoFar.addAll(itemsToAdd.contents)
SemObject.Void
}))
// ListBuilder.build
list.add(NativeFunction(EntityId.of("ListBuilder", "build"), { args: List<SemObject>, _: InterpreterCallback ->
val builder = args[0] as? SemObject.ListBuilder ?: typeError()
SemObject.SemList(builder.listSoFar)
}))
// Var constructor
list.add(NativeFunction(EntityId.of("Var"), { args: List<SemObject>, _: InterpreterCallback ->
SemObject.Var(args[0])
}))
// Var.get
list.add(NativeFunction(EntityId.of("Var", "get"), { args: List<SemObject>, _: InterpreterCallback ->
val theVar = args[0] as? SemObject.Var ?: typeError()
synchronized(theVar) {
theVar.value
}
}))
// Var.set
list.add(NativeFunction(EntityId.of("Var", "set"), { args: List<SemObject>, _: InterpreterCallback ->
val theVar = args[0] as? SemObject.Var ?: typeError()
val newVal = args[1]
synchronized(theVar) {
theVar.value = newVal
}
SemObject.Void
}))
// Function.whileTrueDo
list.add(NativeFunction(EntityId.of("Function", "whileTrueDo"), { args: List<SemObject>, apply: InterpreterCallback ->
val condition = args[0] as? SemObject.FunctionBinding ?: typeError()
val action = args[1] as? SemObject.FunctionBinding ?: typeError()
while ((apply(condition, listOf()) as? SemObject.Boolean ?: typeError()).value) {
apply(action, listOf())
}
SemObject.Void
}))
}
private fun typeError(): Nothing {
error("Runtime type error")
}
| apache-2.0 | 7d3eb8dde3aac5c89b991399ca5a6dce | 38.401835 | 131 | 0.619261 | 3.950331 | false | false | false | false |
pdvrieze/darwin-android-auth | src/main/java/uk/ac/bournemouth/darwin/auth/AccountListActivity.kt | 1 | 4058 | package uk.ac.bournemouth.darwin.auth
import android.accounts.Account
import android.accounts.AccountManager
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import kotlinx.android.synthetic.main.account_list_content.view.*
import kotlinx.android.synthetic.main.activity_account_list.*
/**
* An activity representing a list of Pings. This activity
* has different presentations for handset and tablet-size devices. On
* handsets, the activity presents a list of items, which when touched,
* lead to a [AccountDetailActivity] representing
* item details. On tablets, the activity presents the list of items and
* item details side-by-side using two vertical panes.
*/
class AccountListActivity : AppCompatActivity() {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private var twoPane: Boolean = false
private lateinit var adapter: AccountRecyclerViewAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_account_list)
if (account_detail_container != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
twoPane = true
}
val accounts = AccountManager.get(this).getAccountsByType(DWN_ACCOUNT_TYPE).toList()
if (accounts.size==1) {
startActivity(accountDetailIntent(accounts[0]))
finish()
} else {
adapter = AccountRecyclerViewAdapter(this, accounts, twoPane)
account_list.adapter = adapter
}
}
class AccountRecyclerViewAdapter(private val parentActivity: AccountListActivity,
private val values: List<Account>,
private val twoPane: Boolean) :
RecyclerView.Adapter<AccountRecyclerViewAdapter.ViewHolder>() {
private val onClickListener: View.OnClickListener
init {
onClickListener = View.OnClickListener { v ->
val account = v.tag as Account
if (twoPane) {
val fragment = AccountDetailFragment().apply {
arguments = Bundle().apply {
putParcelable(AccountDetailFragment.ARG_ACCOUNT, account)
}
}
parentActivity.supportFragmentManager
.beginTransaction()
.replace(R.id.account_detail_container, fragment)
.commit()
} else {
val context = v.context
val intent = context.accountDetailIntent(account)
v.context.startActivity(intent)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.account_list_content, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val account = values[position]
holder.idView.text = account.name
holder.contentView.text = account.type
with(holder.itemView) {
tag = account
setOnClickListener(onClickListener)
}
}
override fun getItemCount() = values.size
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val idView: TextView = view.id_text
val contentView: TextView = view.content
}
}
}
| lgpl-2.1 | 746868043c0f59e2c7e1079f892787ad | 37.283019 | 92 | 0.613356 | 5.256477 | false | false | false | false |
Jonatino/JOGL2D | src/main/kotlin/org/anglur/joglext/jogl2d/impl/AbstractImageHelper.kt | 1 | 8368 | /*
* Copyright 2016 Jonathan Beaudoin <https://github.com/Jonatino>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.anglur.joglext.jogl2d.impl
import com.jogamp.opengl.util.texture.Texture
import com.jogamp.opengl.util.texture.awt.AWTTextureIO
import org.anglur.joglext.jogl2d.GLG2DImageHelper
import org.anglur.joglext.jogl2d.GLG2DRenderingHints
import org.anglur.joglext.jogl2d.GLGraphics2D
import java.awt.Color
import java.awt.Image
import java.awt.RenderingHints.Key
import java.awt.geom.AffineTransform
import java.awt.image.*
import java.awt.image.renderable.RenderableImage
import java.lang.ref.Reference
import java.lang.ref.ReferenceQueue
import java.lang.ref.WeakReference
import java.util.*
import java.util.logging.Level
import java.util.logging.Logger
abstract class AbstractImageHelper : GLG2DImageHelper {
/**
* See [GLG2DRenderingHints.KEY_CLEAR_TEXTURES_CACHE]
*/
private var imageCache = TextureCache()
private var clearCachePolicy: Any? = null
protected lateinit var g2d: GLGraphics2D
protected abstract fun begin(texture: Texture, xform: AffineTransform?, bgcolor: Color)
protected abstract fun applyTexture(texture: Texture, dx1: Int, dy1: Int, dx2: Int, dy2: Int,
sx1: Float, sy1: Float, sx2: Float, sy2: Float)
protected abstract fun end(texture: Texture)
override fun setG2D(g2d: GLGraphics2D) {
this.g2d = g2d
if (clearCachePolicy === GLG2DRenderingHints.VALUE_CLEAR_TEXTURES_CACHE_EACH_PAINT) {
imageCache.clear()
}
}
override fun push(newG2d: GLGraphics2D) {
// nop
}
override fun pop(parentG2d: GLGraphics2D) {
// nop
}
override fun setHint(key: Key, value: Any?) {
if (key === GLG2DRenderingHints.KEY_CLEAR_TEXTURES_CACHE) {
clearCachePolicy = value
}
}
override fun resetHints() {
clearCachePolicy = GLG2DRenderingHints.VALUE_CLEAR_TEXTURES_CACHE_DEFAULT
}
override fun dispose() {
imageCache.clear()
}
override fun drawImage(img: Image, x: Int, y: Int, bgcolor: Color, observer: ImageObserver): Boolean {
return drawImage(img, AffineTransform.getTranslateInstance(x.toDouble(), y.toDouble()), bgcolor, observer)
}
override fun drawImage(img: Image, xform: AffineTransform, observer: ImageObserver): Boolean {
return drawImage(img, xform, Color.WHITE, observer)
}
override fun drawImage(img: Image, x: Int, y: Int, width: Int, height: Int, bgcolor: Color, observer: ImageObserver): Boolean {
val imgHeight = img.getHeight(null).toDouble()
val imgWidth = img.getWidth(null).toDouble()
if (imgHeight < 0 || imgWidth < 0) {
return false
}
val transform = AffineTransform.getTranslateInstance(x.toDouble(), y.toDouble())
transform.scale(width / imgWidth, height / imgHeight)
return drawImage(img, transform, bgcolor, observer)
}
override fun drawImage(img: Image, dx1: Int, dy1: Int, dx2: Int, dy2: Int, sx1: Int, sy1: Int, sx2: Int,
sy2: Int, bgcolor: Color, observer: ImageObserver): Boolean {
val texture = getTexture(img, observer) ?: return false
val height = texture.height.toFloat()
val width = texture.width.toFloat()
begin(texture, null, bgcolor)
applyTexture(texture, dx1, dy1, dx2, dy2, sx1 / width, sy1 / height, sx2 / width, sy2 / height)
end(texture)
return true
}
private fun drawImage(img: Image, xform: AffineTransform, color: Color, observer: ImageObserver): Boolean {
val texture = getTexture(img, observer) ?: return false
begin(texture, xform, color)
applyTexture(texture)
end(texture)
return true
}
private fun applyTexture(texture: Texture) {
val width = texture.width
val height = texture.height
val coords = texture.imageTexCoords
applyTexture(texture, 0, 0, width, height, coords.left(), coords.top(), coords.right(), coords.bottom())
}
/**
* Cache the texture if possible. I have a feeling this will run into issues
* later as images change. Just not sure how to handle it if they do. I
* suspect I should be using the ImageConsumer class and dumping pixels to the
* screen as I receive them.
*
*
*
*
* If an image is a BufferedImage, turn it into a texture and cache it. If
* it's not, draw it to a BufferedImage and see if all the image data is
* available. If it is, cache it. If it's not, don't cache it. But if not all
* the image data is available, we will draw it what we have, since we draw
* anything in the image to a BufferedImage.
*
*/
private fun getTexture(image: Image, observer: ImageObserver): Texture? {
var texture: Texture? = imageCache[image]
if (texture == null) {
val bufferedImage: BufferedImage?
if (image is BufferedImage && image.type != BufferedImage.TYPE_CUSTOM) {
bufferedImage = image
} else {
bufferedImage = toBufferedImage(image)
}
if (bufferedImage != null) {
texture = create(bufferedImage)
addToCache(image, texture)
}
}
return texture
}
private fun create(image: BufferedImage): Texture {
// we'll assume the image is complete and can be rendered
return AWTTextureIO.newTexture(g2d.glContext.gl.glProfile, image, false)
}
private fun destroy(texture: Texture) {
texture.destroy(g2d.glContext.gl)
}
private fun addToCache(image: Image, texture: Texture) {
if (clearCachePolicy is Number) {
val maxSize = (clearCachePolicy as Number).toInt()
if (imageCache.size > maxSize) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Clearing texture cache with size " + imageCache.size)
}
imageCache.clear()
}
}
imageCache.put(image, texture)
}
private fun toBufferedImage(image: Image): BufferedImage? {
if (image is VolatileImage) {
return image.snapshot
}
val width = image.getWidth(null)
val height = image.getHeight(null)
if (width < 0 || height < 0) {
return null
}
val bufferedImage = BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR)
bufferedImage.createGraphics().drawImage(image, null, null)
return bufferedImage
}
override fun drawImage(img: BufferedImage, op: BufferedImageOp, x: Int, y: Int) {
TODO("drawImage(BufferedImage, BufferedImageOp, int, int)")
}
override fun drawImage(img: RenderedImage, xform: AffineTransform) {
TODO("drawImage(RenderedImage, AffineTransform)")
}
override fun drawImage(img: RenderableImage, xform: AffineTransform) {
TODO("drawImage(RenderableImage, AffineTransform)")
}
/**
* We could use a WeakHashMap here, but we want access to the ReferenceQueue
* so we can dispose the Textures when the Image is no longer referenced.
*/
@SuppressWarnings("serial")
private inner class TextureCache : HashMap<WeakKey<Image>, Texture>() {
private val queue = ReferenceQueue<Image>()
fun expungeStaleEntries() {
var ref: Reference<out Image>? = queue.poll()
while (ref != null) {
val texture = remove(ref)
if (texture != null) {
destroy(texture)
}
ref = queue.poll()
}
}
operator fun get(image: Image): Texture? {
expungeStaleEntries()
val key = WeakKey(image, null)
return get(key)
}
fun put(image: Image, texture: Texture): Texture? {
expungeStaleEntries()
val key = WeakKey(image, queue)
return put(key, texture)
}
}
private class WeakKey<T>(value: T, queue: ReferenceQueue<T>?) : WeakReference<T>(value, queue) {
private val hash: Int
init {
hash = value!!.hashCode()
}
override fun hashCode(): Int {
return hash
}
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
} else if (other is WeakKey<*>) {
return other.hash == hash && get() === other.get()
} else {
return false
}
}
}
companion object {
private val LOGGER = Logger.getLogger(AbstractImageHelper::class.java.name)
}
} | apache-2.0 | 302261c11e0f2fd12780dc37b95fa83e | 28.677305 | 128 | 0.700287 | 3.46501 | false | false | false | false |
kiruto/debug-bottle | components/src/main/kotlin/com/exyui/android/debugbottle/components/widgets/DTListItemSwitch.kt | 1 | 3533 | package com.exyui.android.debugbottle.components.widgets
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.support.v7.widget.SwitchCompat
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.exyui.android.debugbottle.components.R
import com.exyui.android.debugbottle.components.sp
/**
* Created by yuriel on 9/21/16.
*/
internal class DTListItemSwitch : LinearLayout {
var title: String = ""
set(value) {
field = value
titleView.text = field
invalidate()
requestLayout()
}
var content: String = ""
set(value) {
field = value
contentView.text = field
invalidate()
requestLayout()
}
var isChecked: Boolean
get() = switchView.isChecked
set(value) {
switchView.isChecked = value
}
var isSmart: Boolean = false
set(value) {
if (value) {
contentView.visibility = View.GONE
} else {
contentView.visibility = View.VISIBLE
}
field = value
}
/**
* Switcher enabled
*/
var enable: Boolean
get() = switchView.isEnabled
set(value) {
switchView.isEnabled = value
}
lateinit var titleView: TextView
lateinit var contentView: TextView
lateinit var switchView: SwitchCompat
constructor(context: Context): super(context) {
init(context)
}
constructor(context: Context, attr: AttributeSet): super(context, attr) {
init(context, attr)
}
constructor(context: Context, attr: AttributeSet, defStyleAttr: Int): super(context, attr, defStyleAttr) {
init(context, attr, defStyleAttr)
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@SuppressLint("NewApi")
constructor(context: Context, attr: AttributeSet, defStyleAttr: Int, defStyleRes: Int): super(context, attr, defStyleAttr, defStyleRes) {
init(context, attr, defStyleAttr, defStyleRes)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
}
fun setOnCheckedChangeListener(listener: (v: View, isChecked: Boolean) -> Unit) {
switchView.setOnCheckedChangeListener(listener)
}
private fun bindViews() {
inflate(context, R.layout.__custom_list_item_swicher, this)
titleView = findViewById(R.id.__dt_title) as TextView
contentView = findViewById(R.id.__dt_content) as TextView
switchView = findViewById(R.id.__dt_switcher) as SwitchCompat
}
private fun init(context: Context, attr: AttributeSet? = null, defStyleAttr: Int? = null, defStyleRes: Int? = null) {
bindViews()
initAttrs(context, attr, defStyleAttr?: 0, defStyleRes?: 0)
}
private fun initAttrs(context: Context, attr: AttributeSet?, defStyleAttr: Int = 0, defStyleRes: Int = 0) {
val ta = context.theme.obtainStyledAttributes(attr, R.styleable.__DTListItem, defStyleAttr, defStyleRes)
try {
title = ta.getString(R.styleable.__DTListItem___dt_title)?: ""
content = ta.getString(R.styleable.__DTListItem___dt_content)?: ""
isSmart = ta.getBoolean(R.styleable.__DTListItem___dt_smart, false)
} finally {
ta.recycle()
}
}
} | apache-2.0 | cea05a254efb0596526c82141ff453a3 | 30.837838 | 141 | 0.637702 | 4.612272 | false | false | false | false |
jorjoluiso/QuijoteLui | src/main/kotlin/com/quijotelui/electronico/xml/GeneraFactura.kt | 1 | 12053 | package com.quijotelui.electronico.xml
import com.quijotelui.electronico.comprobantes.InformacionTributaria
import com.quijotelui.electronico.comprobantes.factura.Factura
import com.quijotelui.electronico.util.Modulo11
import com.quijotelui.electronico.util.Parametros
import com.quijotelui.model.Contribuyente
import com.quijotelui.model.FacturaDetalle
import com.quijotelui.service.IFacturaService
import comprobantes.CampoAdicional
import comprobantes.InformacionAdicional
import comprobantes.factura.*
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStreamWriter
import java.io.StringWriter
import java.math.BigDecimal
import java.text.SimpleDateFormat
import javax.xml.bind.JAXBContext
import javax.xml.bind.Marshaller
class GeneraFactura(val facturaService : IFacturaService, val codigo : String, val numero : String) {
val contribuyenteFactura = facturaService.findContribuyenteByComprobante(codigo, numero)
val factura = Factura()
var claveAcceso : String? = null
get(){
val informacionTributaria = InformacionTributaria()
informacionTributaria.ambiente = Parametros.getAmbiente(facturaService.findParametroByNombre("Ambiente"))
informacionTributaria.tipoEmision = Parametros.getEmision(facturaService.findParametroByNombre("Emisión"))
return getClaveAcceso(
getContribuyente(this.contribuyenteFactura),
getFactura(this.contribuyenteFactura),
informacionTributaria.ambiente!!,
informacionTributaria.tipoEmision!!)
}
var informacionExtra = mutableListOf<CampoAdicional>()
/*
Función que genera la factura en XML
*/
fun xml() : String {
try {
factura.setId(id = "comprobante")
factura.setVersion(version = "1.1.0")
factura.setInformacionTributaria(getInformacionTributaria())
factura.setInformacionFactura(getInformacionFactura())
factura.setDetalles(getDetalle())
getInformacionAdicional()?.let { factura.setInformacionAdicional(it) }
val jaxbContext = JAXBContext.newInstance(Factura::class.java)
val marshaller = jaxbContext.createMarshaller()
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true)
marshaller.setProperty("jaxb.encoding", "UTF-8")
val stringWriter = StringWriter()
stringWriter.use {
marshaller.marshal(this.factura, stringWriter)
}
val rutaGenerado = Parametros.getRuta(facturaService.findParametroByNombre("Generado"))
val out = OutputStreamWriter(FileOutputStream("$rutaGenerado" +
"${File.separatorChar}" +
"${this.claveAcceso}.xml"), "UTF-8")
marshaller.marshal(this.factura, out)
println(stringWriter)
}
catch (e: Exception) {
println("Error en Genera Factura: ${e.message}")
return ""
}
return this.claveAcceso.toString()
}
private fun getInformacionTributaria() : InformacionTributaria{
val informacionTributaria = InformacionTributaria()
var contribuyente = getContribuyente(this.contribuyenteFactura)
var facturaDocumento = getFactura(this.contribuyenteFactura)
informacionTributaria.ambiente = Parametros.getAmbiente(facturaService.findParametroByNombre("Ambiente"))
informacionTributaria.tipoEmision = Parametros.getEmision(facturaService.findParametroByNombre("Emisión"))
informacionTributaria.razonSocial = contribuyente.razonSocial
informacionTributaria.nombreComercial = contribuyente.nombreComercial
informacionTributaria.ruc = contribuyente.ruc
this.claveAcceso = getClaveAcceso(contribuyente, facturaDocumento, informacionTributaria.ambiente!!, informacionTributaria.tipoEmision!!)
informacionTributaria.claveAcceso = this.claveAcceso
informacionTributaria.codDoc = facturaDocumento.codigoDocumento
informacionTributaria.estab = facturaDocumento.establecimiento
informacionTributaria.ptoEmi = facturaDocumento.puntoEmision
informacionTributaria.secuencial = facturaDocumento.secuencial
informacionTributaria.dirMatriz = contribuyente.direccion
return informacionTributaria
}
private fun getInformacionFactura() : InformacionFactura {
val informacionFactura = InformacionFactura()
var contribuyente = getContribuyente(this.contribuyenteFactura)
var facturaComprobante = getFactura(this.contribuyenteFactura)
informacionFactura.fechaEmision = SimpleDateFormat("dd/MM/yyyy").format(facturaComprobante.fecha)
informacionFactura.dirEstablecimiento = facturaComprobante.direccionEstablecimiento
informacionFactura.contribuyenteEspecial = contribuyente.contribuyenteEspecial
informacionFactura.obligadoContabilidad = contribuyente.obligadoContabilidad
informacionFactura.tipoIdentificacionComprador = facturaComprobante.tipoDocumento
informacionFactura.guiaRemision = facturaComprobante.guiaRemision
informacionFactura.razonSocialComprador = facturaComprobante.razonSocial
informacionFactura.identificacionComprador = facturaComprobante.documento
informacionFactura.direccionComprador = facturaComprobante.direccion
informacionFactura.totalSinImpuestos = facturaComprobante.totalSinIva!!.setScale(2, BigDecimal.ROUND_HALF_UP) +
facturaComprobante.totalConIva!!.setScale(2, BigDecimal.ROUND_HALF_UP)
informacionFactura.totalDescuento = facturaComprobante.descuentos!!.setScale(2, BigDecimal.ROUND_HALF_UP)
informacionFactura.setTotalConImpuestos(getImpuesto())
informacionFactura.setPropina(BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP))
informacionFactura.setImporteTotal(facturaComprobante.total!!.setScale(2, BigDecimal.ROUND_HALF_UP))
informacionFactura.setMoneda("DOLAR")
informacionFactura.setPagos(getPago())
return informacionFactura
}
private fun getImpuesto() : TotalConImpuestos {
val impuestos = facturaService.findImpuestoByComprobante(codigo, numero)
var totalConImpuestos = TotalConImpuestos()
for (impuesto in impuestos){
var totalImpuesto = TotalImpuesto()
totalImpuesto.codigo = impuesto.codigoImpuesto
totalImpuesto.codigoPorcentaje = impuesto.codigoPorcentaje
totalImpuesto.baseImponible = impuesto.baseImponible
totalImpuesto.tarifa = impuesto.tarifa
totalImpuesto.valor = impuesto.valor
totalConImpuestos.setTotalImpuesto(totalImpuesto)
}
return totalConImpuestos
}
private fun getPago() : Pagos {
val pagosComprobante = facturaService.findPagoByComprobante(codigo, numero)
var pagos = Pagos()
this.informacionExtra.clear()
for (pagoComprobante in pagosComprobante){
var pago = Pago()
pago.formaPago = pagoComprobante.formaPago
pago.total = pagoComprobante.total?.setScale(2, BigDecimal.ROUND_HALF_UP)
pago.plazo = pagoComprobante.plazo
pago.unidadTiempo = pagoComprobante.tiempo
// println("Pagos: ${pago.formaPago} ${pago.total}")
pagos.setPago(pago)
//Para cargar las formas de pago en la sección de información adicional
val campoFormaPago = CampoAdicional()
val campoTotal = CampoAdicional()
campoFormaPago.setNombre("Pago")
campoFormaPago.setValor(pagoComprobante.formaPagoDescripcion!!)
campoTotal.setNombre("Total")
campoTotal.setValor(pagoComprobante.total?.setScale(2, BigDecimal.ROUND_HALF_UP).toString())
informacionExtra.add(campoFormaPago)
informacionExtra.add(campoTotal)
}
return pagos
}
private fun getDetalle() : Detalles {
val facturaDetalles = facturaService.findFacturaDetalleByComprobante(codigo, numero)
var detalles = Detalles()
for (i in facturaDetalles.indices){
var detalle = Detalle()
detalle.codigoPrincipal = facturaDetalles[i].codigoPrincipal
detalle.descripcion = facturaDetalles[i].descripcion
detalle.cantidad = facturaDetalles[i].cantidad?.setScale(2, BigDecimal.ROUND_HALF_UP)
detalle.precioUnitario = facturaDetalles[i].precioUnitario?.setScale(4, BigDecimal.ROUND_HALF_UP)
detalle.descuento = facturaDetalles[i].descuento?.setScale(2, BigDecimal.ROUND_HALF_UP)
detalle.precioTotalSinImpuesto = facturaDetalles[i].precioTotalSinImpuesto?.setScale(2, BigDecimal.ROUND_HALF_UP)
detalle.setImpuestos(getDetalleImpuestos(facturaDetalles[i]))
detalles.setDetalle(detalle)
}
return detalles
}
private fun getDetalleImpuestos(detalle : FacturaDetalle) : Impuestos {
/*
Los detalles de impuestos por
producto, solo está habilitado para el IVA.
En futuras versiones se soportará ICE y más
impuestos existentes.
*/
val impuesto = Impuesto()
var impuestos = Impuestos()
impuesto.codigo = "2"
impuesto.codigoPorcentaje = detalle.codigoPorcentaje
impuesto.tarifa = detalle.porcentajeIva
impuesto.baseImponible = detalle.precioTotalSinImpuesto?.setScale(2, BigDecimal.ROUND_HALF_UP)
impuesto.valor = detalle.valorIva?.setScale(2, BigDecimal.ROUND_HALF_UP)
impuestos.setImpuesto(impuesto)
return impuestos
}
private fun getInformacionAdicional() : InformacionAdicional? {
val facturaDocumento = getFactura(this.contribuyenteFactura)
val informaciones = facturaService.findInformacionByDocumento(facturaDocumento.documento.toString())
if (informaciones.isEmpty() && informacionExtra.isEmpty()) {
return null
}
var informacionAdicional = InformacionAdicional()
for (informacion in informaciones) {
val campoAdicional = CampoAdicional()
campoAdicional.setNombre(informacion.nombre.toString())
campoAdicional.setValor(informacion.valor.toString())
informacionAdicional.setCampoAdicional(campoAdicional)
}
//Carga la forma de pago en información adicional
for (i in this.informacionExtra.indices) {
informacionAdicional.setCampoAdicional(informacionExtra[i])
}
return informacionAdicional
}
private fun getContribuyente(contribuyenteComprobante: MutableList<Any>) : Contribuyente {
var contribuyente = Contribuyente()
for (i in contribuyenteComprobante.indices) {
val row = contribuyenteComprobante[i] as Array<Any>
contribuyente = row[0] as Contribuyente
}
return contribuyente
}
private fun getFactura (contribuyenteConprobante : MutableList<Any>) : com.quijotelui.model.Factura {
var facturaModel = com.quijotelui.model.Factura()
for (i in contribuyenteConprobante.indices) {
val row = contribuyenteConprobante[i] as Array<Any>
facturaModel = row[1] as com.quijotelui.model.Factura
}
return facturaModel
}
private fun getClaveAcceso(contribuyente: Contribuyente, facturaModel: com.quijotelui.model.Factura, ambiente : String, emision : String) : String {
val m11 = Modulo11()
val claveAcceso = SimpleDateFormat("ddMMyyyy").format(facturaModel.fecha) +
facturaModel.codigoDocumento + contribuyente.ruc + ambiente +
facturaModel.establecimiento + facturaModel.puntoEmision + facturaModel.secuencial +
"12345678" + emision
return claveAcceso + m11.modulo11(claveAcceso)
}
} | gpl-3.0 | 6e49d6a77995f890d661d4de3f2ddbd6 | 39.555556 | 152 | 0.702341 | 4.079946 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/system/macosx/templates/CoreFoundation.kt | 1 | 6817 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.system.macosx.templates
import org.lwjgl.generator.*
import org.lwjgl.system.macosx.*
val ALLOCATOR = nullable..CFAllocatorRef.IN(
"allocator",
"the allocator to use to allocate memory for the new object. Pass $NULL or {@code kCFAllocatorDefault} to use the current default allocator."
)
val CoreFoundation = "CoreFoundation".nativeClass(MACOSX_PACKAGE) {
nativeImport (
"MacOSXLWJGL.h"
)
documentation = "Native bindings to <CoreFoundation.h>."
// -----------------------------------------------
// CFBase.h
ByteConstant(
"Boolean values.",
"TRUE".."1",
"FALSE".."0"
)
macro..CFAllocatorRef("kCFAllocatorDefault", "This is a synonym for $NULL, if you'd rather use a named constant.")
macro..CFAllocatorRef("kCFAllocatorSystemDefault", "Default system allocator; you rarely need to use this.")
macro..CFAllocatorRef(
"kCFAllocatorMalloc",
"""
This allocator uses {@code malloc()}, {@code realloc()}, and {@code free()}. This should not be generally used; stick to #kCFAllocatorDefault()
whenever possible. This allocator is useful as the "bytesDeallocator" in {@code CFData} or "contentsDeallocator" in {@code CFString} where the memory
was obtained as a result of {@code malloc()} type functions.
"""
)
macro..CFAllocatorRef(
"kCFAllocatorMallocZone",
"""
This allocator explicitly uses the default malloc zone, returned by {@code malloc_default_zone()}. It should only be used when an object is safe to be
allocated in non-scanned memory.
"""
)
macro..CFAllocatorRef(
"kCFAllocatorNull",
"""
Null allocator which does nothing and allocates no memory. This allocator is useful as the "bytesDeallocator" in {@code CFData} or "contentsDeallocator"
in {@code CFString} where the memory should not be freed.
"""
)
macro..CFAllocatorRef(
"kCFAllocatorUseContext",
"Special allocator argument to CFAllocatorCreate which means \"use the functions given in the context to allocate the allocator itself as well\"."
)
CFTypeRef(
"CFRetain",
"""
Retains a Core Foundation object.
You should retain a Core Foundation object when you receive it from elsewhere (that is, you did not create or copy it) and you want it to persist. If
you retain a Core Foundation object you are responsible for releasing it.
""",
CFTypeRef.IN("cf", "the CFType object to retain")
)
void(
"CFRelease",
"""
Releases a Core Foundation object.
If the retain count of {@code cf} becomes zero the memory allocated to the object is deallocated and the object is destroyed. If you create, copy, or
explicitly retain (see the #CFRetain() function) a Core Foundation object, you are responsible for releasing it when you no longer need it.
""",
CFTypeRef.IN("cf", "the CFType object to release")
)
// -----------------------------------------------
// CFBundle.h
CFBundleRef(
"CFBundleCreate",
"Creates a {@code CFBundle} object.",
ALLOCATOR,
CFURLRef.IN("bundleURL", "the location of the bundle for which to create a {@code CFBundle} object")
)
CFBundleRef(
"CFBundleGetBundleWithIdentifier",
"Locates a bundle given its program-defined identifier.",
CFStringRef.IN("bundleID", "the identifier of the bundle to locate. Note that identifier names are case-sensitive.")
)
voidptr(
"CFBundleGetFunctionPointerForName",
"Returns a pointer to a function in a bundle’s executable code using the function name as the search key.",
CFBundleRef.IN("bundle", "the bundle to examine"),
CFStringRef.IN("functionName", "the name of the function to locate")
)
// -----------------------------------------------
// CFString.h
val Encodings = IntConstant(
"Platform-independent built-in encodings; always available on all platforms.",
"kCFStringEncodingMacRoman".."0",
"kCFStringEncodingWindowsLatin1"..0x0500,
"kCFStringEncodingISOLatin1"..0x0201,
"kCFStringEncodingNextStepLatin"..0x0B01,
"kCFStringEncodingASCII"..0x0600,
"kCFStringEncodingUnicode"..0x0100,
"kCFStringEncodingUTF8"..0x08000100,
"kCFStringEncodingNonLossyASCII"..0x0BFF,
"kCFStringEncodingUTF16"..0x0100,
"kCFStringEncodingUTF16BE"..0x10000100,
"kCFStringEncodingUTF16LE"..0x14000100,
"kCFStringEncodingUTF32"..0x0c000100,
"kCFStringEncodingUTF32BE"..0x18000100,
"kCFStringEncodingUTF32LE"..0x1c000100
).javaDocLinks
CFStringRef(
"CFStringCreateWithCString",
"Creates an immutable string from a C string.",
ALLOCATOR,
const..char_p.IN("cStr", "the $NULL-terminated C string to be used to create the {@code CFString} object. The string must use an 8-bit encoding."),
CFStringEncoding.IN("encoding", "the encoding of the characters in the C string. The encoding must specify an 8-bit encoding.", Encodings)
)
CFStringRef(
"CFStringCreateWithCStringNoCopy",
"Creates a CFString object from an external C string buffer that might serve as the backing store for the object.",
ALLOCATOR,
const..char_p.IN("cStr", "the $NULL-terminated C string to be used to create the {@code CFString} object. The string must use an 8-bit encoding."),
CFStringEncoding.IN("encoding", "the encoding of the characters in the C string. The encoding must specify an 8-bit encoding.", Encodings),
nullable..CFAllocatorRef.IN(
"contentsDeallocator",
"""
the {@code CFAllocator} object to use to deallocate the external string buffer when it is no longer needed. You can pass $NULL or
{@code kCFAllocatorDefault} to request the default allocator for this purpose. If the buffer does not need to be deallocated, or if you want to
assume responsibility for deallocating the buffer (and not have the {@code CFString} object deallocate it), pass {@code kCFAllocatorNull}.
"""
)
)
// -----------------------------------------------
// CFURL.h
val PathStyles = IntConstant(
"URL path styles.",
"kCFURLPOSIXPathStyle".."0",
"kCFURLHFSPathStyle".."1",
"kCFURLWindowsPathStyle".."2"
).javaDocLinks
CFURLRef(
"CFURLCreateWithFileSystemPath",
"Creates a {@code CFURL} object using a local file system path string.",
ALLOCATOR,
CFStringRef.IN(
"filePath",
"""
the path string to convert to a {@code CFURL} object. If {@code filePath} is not absolute, the resulting URL will be considered relative to the
current working directory (evaluated when this function is being invoked).
"""
),
CFURLPathStyle.IN("pathStyle", "the operating system path style used in {@code filePath}", PathStyles),
Boolean.IN(
"isDirectory",
"""
a Boolean value that specifies whether filePath is treated as a directory path when resolving against relative path components. Pass true if the
pathname indicates a directory, false otherwise.
"""
)
)
} | bsd-3-clause | f637807bac6ed89c3fc5bca77ee4f89a | 34.5 | 154 | 0.714894 | 3.652197 | false | false | false | false |
Adonai/Man-Man | app/src/main/java/com/adonai/manman/adapters/CachedCommandsArrayAdapter.kt | 1 | 3152 | package com.adonai.manman.adapters
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.adonai.manman.MainPagerActivity
import com.adonai.manman.ManCacheFragment
import com.adonai.manman.R
import com.adonai.manman.database.DbProvider.helper
import com.adonai.manman.entities.ManPage
/**
* Array adapter for showing cached commands in ListView
* The data retrieval is done through [ManCacheFragment.doReloadCache]
*
* @see ArrayAdapter
* @see ManPage
*
* @author Kanedias
*/
class CachedCommandsArrayAdapter(context: Context, resource: Int, textViewResourceId: Int, objects: List<ManPage>) : ArrayAdapter<ManPage>(context, resource, textViewResourceId, objects) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val current = getItem(position)
val root = super.getView(position, convertView, parent)
val command = root.findViewById<View>(R.id.command_name_label) as TextView
val url = root.findViewById<View>(R.id.command_description_label) as TextView
val moreActions = root.findViewById<View>(R.id.popup_menu) as ImageView
command.text = current!!.name
url.text = current.url
moreActions.setOnClickListener { v ->
val pm = PopupMenu(context, v)
pm.inflate(R.menu.cached_item_popup)
pm.setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener { item ->
when (item.itemId) {
R.id.share_link_popup_menu_item -> {
val sendIntent = Intent(Intent.ACTION_SEND)
sendIntent.type = "text/plain"
sendIntent.putExtra(Intent.EXTRA_TITLE, current.name)
sendIntent.putExtra(Intent.EXTRA_TEXT, current.url)
context.startActivity(Intent.createChooser(sendIntent, context.getString(R.string.share_link)))
return@OnMenuItemClickListener true
}
R.id.copy_link_popup_menu_item -> {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
Toast.makeText(context.applicationContext, context.getString(R.string.copied) + " " + current.url, Toast.LENGTH_SHORT).show()
clipboard.setPrimaryClip(ClipData.newPlainText(current.name, current.url))
return@OnMenuItemClickListener true
}
R.id.delete_popup_menu_item -> {
helper.manPagesDao.delete(current)
LocalBroadcastManager.getInstance(context).sendBroadcast(Intent(MainPagerActivity.DB_CHANGE_NOTIFY))
return@OnMenuItemClickListener true
}
}
false
})
pm.show()
}
return root
}
} | gpl-3.0 | 8788db47fdc5166a3bf465ec8fa3ac1f | 44.695652 | 188 | 0.644987 | 4.849231 | false | false | false | false |
google/android-auto-companion-android | trustagent/src/com/google/android/libraries/car/trustagent/OobChannelManagerFactory.kt | 1 | 2036 | package com.google.android.libraries.car.trustagent
import com.google.android.companionprotos.CapabilitiesExchangeProto.CapabilitiesExchange.OobChannelType
import com.google.android.libraries.car.trustagent.util.loge
import com.google.android.libraries.car.trustagent.util.logi
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import kotlinx.coroutines.asCoroutineDispatcher
/** A factory of [OobChannelManager]s. */
internal fun interface OobChannelManagerFactory {
/** Creates an [OobChannelManager] based on [oobChannelTypes]. */
fun create(
oobChannelTypes: List<OobChannelType>,
oobData: OobData?,
securityVersion: Int
): OobChannelManager
}
internal class OobChannelManagerFactoryImpl() : OobChannelManagerFactory {
override fun create(
oobChannelTypes: List<OobChannelType>,
oobData: OobData?,
securityVersion: Int,
): OobChannelManager {
var executorService: ExecutorService? = null
val oobChannels: List<OobChannel> =
oobChannelTypes.mapNotNull { type ->
when (type) {
OobChannelType.BT_RFCOMM -> {
logi(TAG, "Remote supports BT_RFCOMM. Adding BluetoothRfcommChannel")
executorService = Executors.newSingleThreadExecutor()
BluetoothRfcommChannel(
securityVersion >= MIN_SECURITY_VERSION_FOR_OOB_PROTO,
executorService!!.asCoroutineDispatcher(),
)
}
OobChannelType.PRE_ASSOCIATION -> {
if (oobData != null) {
PassThroughOobChannel(oobData)
} else {
loge(TAG, "Remote supports PRE_ASSOCIATION but out-of-band data is null.")
null
}
}
OobChannelType.OOB_CHANNEL_UNKNOWN, OobChannelType.UNRECOGNIZED -> null
}
}
return OobChannelManager(oobChannels, executorService)
}
companion object {
private const val TAG = "OobChannelManagerFactory"
private const val MIN_SECURITY_VERSION_FOR_OOB_PROTO = 4
}
}
| apache-2.0 | eda2b79f56cefb5161e7a6efabe0c1ee | 34.103448 | 103 | 0.693517 | 4.378495 | false | false | false | false |
C6H2Cl2/SolidXp | src/main/java/c6h2cl2/solidxp/item/Tools/ItemXpDiamondShovel.kt | 1 | 1813 | package c6h2cl2.solidxp.item.Tools
import c6h2cl2.YukariLib.EnumToolType
import c6h2cl2.YukariLib.EnumToolType.SHOVEL
import c6h2cl2.solidxp.item.ICraftResultEnchanted
import c6h2cl2.solidxp.MOD_ID
import c6h2cl2.solidxp.SolidXpRegistry
import net.minecraft.creativetab.CreativeTabs
import net.minecraft.enchantment.EnumEnchantmentType.DIGGER
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.init.Enchantments
import net.minecraft.item.Item
import net.minecraft.item.ItemSpade
import net.minecraft.item.ItemStack
import net.minecraft.util.NonNullList
import net.minecraft.util.ResourceLocation
import net.minecraft.world.World
/**
* @author C6H2Cl2
*/
class ItemXpDiamondShovel : ItemSpade(SolidXpRegistry.materialXpDiamond), ICraftResultEnchanted {
init {
unlocalizedName = "XpDiamondShovel"
registryName = ResourceLocation(MOD_ID, "xp_diamond_shovel")
creativeTab = SolidXpRegistry.tabSolidXp
hasSubtypes = true
}
override fun getSubItems(itemIn: Item, tab: CreativeTabs?, subItems: NonNullList<ItemStack>) {
val itemStack = ItemStack(itemIn, 1, 0)
itemStack.addEnchantment(Enchantments.MENDING, 3)
itemStack.addEnchantment(SolidXpRegistry.xpBoost[DIGGER], 5)
subItems.add(itemStack)
}
override fun onCreated(stack: ItemStack, worldIn: World?, playerIn: EntityPlayer?) {
stack.addEnchantment(Enchantments.MENDING, 3)
stack.addEnchantment(SolidXpRegistry.xpBoost[DIGGER], 5)
}
override fun getEnchanted(): ItemStack {
val stack = ItemStack(this)
stack.addEnchantment(Enchantments.MENDING, 3)
stack.addEnchantment(SolidXpRegistry.xpBoost[DIGGER], 5)
return stack
}
override fun getToolType(): EnumToolType {
return SHOVEL
}
} | mpl-2.0 | ae6ed55eba9d4233f227f12aa9865dac | 33.884615 | 98 | 0.75455 | 3.722793 | false | false | false | false |
inorichi/tachiyomi-extensions | src/en/hentai2read/src/eu/kanade/tachiyomi/extension/en/hentai2read/Hentai2ReadActivity.kt | 1 | 1262 | package eu.kanade.tachiyomi.extension.en.hentai2read
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.util.Log
import kotlin.system.exitProcess
/**
* Springboard that accepts https://hentai2read.com/xxxx intents
* and redirects them to the main Tachiyomi process.
*/
class Hentai2ReadActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val pathSegments = intent?.data?.pathSegments
if (pathSegments != null) {
// TODO: filter standard paths
val id = pathSegments[0]
val mainIntent = Intent().apply {
action = "eu.kanade.tachiyomi.SEARCH"
putExtra("query", "${Hentai2Read.PREFIX_ID_SEARCH}$id")
putExtra("filter", packageName)
}
try {
startActivity(mainIntent)
} catch (e: ActivityNotFoundException) {
Log.e("Hentai2ReadActivity", e.toString())
}
} else {
Log.e("Hentai2ReadActivity", "Could not parse URI from intent $intent")
}
finish()
exitProcess(0)
}
}
| apache-2.0 | 7a4b3b389c4f4b30f5eaab1e836775af | 31.358974 | 83 | 0.62599 | 4.708955 | false | false | false | false |
pbauerochse/youtrack-worklog-viewer | application/src/main/java/de/pbauerochse/worklogviewer/favourites/fx/FavouritesStyleClasses.kt | 1 | 469 | package de.pbauerochse.worklogviewer.favourites.fx
object FavouritesStyleClasses {
const val FAVOURITE_SEARCH_CELL = "favourite-search-cell"
const val FAVOURITE_ISSUE_CELL = "favourite-issue-cell"
const val RESOLVED_ISSUE_CELL = "resolved"
const val CATEGORY_HEADER_CELL = "favourite-category-header"
val ALL = listOf(
FAVOURITE_SEARCH_CELL,
FAVOURITE_ISSUE_CELL,
RESOLVED_ISSUE_CELL,
CATEGORY_HEADER_CELL
)
} | mit | efffabf4c0067849b9acefaa4bab2dc3 | 26.647059 | 64 | 0.701493 | 3.752 | false | false | false | false |
y2k/JoyReactor | core/src/main/kotlin/y2k/joyreactor/common/http/CookieStorage.kt | 1 | 1176 | package y2k.joyreactor.common.http
import okhttp3.Request
import okhttp3.Response
import y2k.joyreactor.common.PersistentMap
import y2k.joyreactor.common.platform.Platform
import java.util.regex.Pattern
/**
* Created by y2k on 10/11/15.
*/
class CookieStorage(platform: Platform) {
private val map = PersistentMap("cookies.dat", platform)
fun attach(request: Request.Builder) {
if (map.isEmpty) return
val cookie = StringBuilder()
for (key in map.keySet())
cookie.append(key).append("=").append(map[key]).append("; ")
request.header("Cookie", cookie.toString())
}
fun grab(response: Response): Response {
val cookies = response.headers("Set-Cookie")
if (cookies == null || cookies.isEmpty()) return response
for (c in cookies) {
val m = COOKIE_PATTERN.matcher(c)
if (!m.find()) throw IllegalStateException(c)
map.put(m.group(1), m.group(2))
}
map.flush()
return response
}
fun clear() {
map.clear()
}
companion object {
private val COOKIE_PATTERN = Pattern.compile("(.+?)=([^;]+)")
}
} | gpl-2.0 | 3e69bf226e2739cd38c62c3d7865228d | 25.155556 | 72 | 0.613095 | 3.986441 | false | false | false | false |
ligee/kotlin-jupyter | jupyter-lib/api/src/main/kotlin/org/jetbrains/kotlinx/jupyter/api/VariableState.kt | 1 | 2462 | package org.jetbrains.kotlinx.jupyter.api
import kotlin.reflect.KProperty
import kotlin.reflect.KProperty1
import kotlin.reflect.jvm.isAccessible
interface VariableState {
val property: KProperty<*>
val scriptInstance: Any?
val stringValue: String?
val value: Result<Any?>
}
data class VariableStateImpl(
override val property: KProperty1<Any, *>,
override val scriptInstance: Any,
) : VariableState {
private val stringCache = VariableStateCache<String?> {
value.getOrNull()?.let { value ->
try {
value.toString()
} catch (e: Throwable) {
"${value::class.simpleName}: [exception thrown: $e]"
}
}
}
private val valCache = VariableStateCache<Result<Any?>> (
{
oldValue, newValue ->
oldValue.getOrNull() !== newValue.getOrNull()
},
{
property.asAccessible { prop ->
try {
Result.success(prop.get(scriptInstance))
} catch (ex: Throwable) {
Result.failure(ex)
}
}
}
)
fun update(): Boolean {
return (valCache.forceUpdate()).also { isChanged ->
if (isChanged) stringCache.update()
}
}
override val stringValue: String? get() = stringCache.get()
override val value: Result<Any?> get() = valCache.get()
companion object {
private fun <T : KProperty<*>, R> T.asAccessible(action: (T) -> R): R {
val wasAccessible = isAccessible
isAccessible = true
val res = action(this)
isAccessible = wasAccessible
return res
}
}
}
private class VariableStateCache<T>(
val equalityChecker: (T, T) -> Boolean = { x, y -> x == y },
val calculate: (T?) -> T
) {
private var cachedVal: T? = null
private var shouldRenew: Boolean = true
fun getOrNull(): T? {
return if (shouldRenew) {
calculate(cachedVal).also {
cachedVal = it
shouldRenew = false
}
} else {
cachedVal
}
}
fun get(): T = getOrNull()!!
fun update() {
shouldRenew = true
}
fun forceUpdate(): Boolean {
val oldVal = getOrNull()
update()
val newVal = get()
return oldVal != null && equalityChecker(oldVal, newVal)
}
}
| apache-2.0 | 6be6e1f145030cc1988c67b3c7e59689 | 24.915789 | 79 | 0.540211 | 4.567718 | false | false | false | false |
btimofeev/UniPatcher | app/src/main/java/org/emunix/unipatcher/ui/activity/HelpActivity.kt | 1 | 1843 | /*
Copyright (C) 2016, 2019-2021 Boris Timofeev
This file is part of UniPatcher.
UniPatcher 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.
UniPatcher 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 UniPatcher. If not, see <http://www.gnu.org/licenses/>.
*/
package org.emunix.unipatcher.ui.activity
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint
import org.emunix.unipatcher.databinding.ActivityHelpBinding
import org.emunix.unipatcher.ui.adapter.HelpStateAdapter
@AndroidEntryPoint
class HelpActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityHelpBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val adapter = HelpStateAdapter(this)
binding.viewpager.adapter = adapter
TabLayoutMediator(binding.tabLayout, binding.viewpager) { tab, position ->
tab.text = getString(adapter.getPageTitle(position))
}.attach()
binding.tabLayout.tabGravity = TabLayout.GRAVITY_FILL
binding.toolbar.setNavigationOnClickListener { finish() }
}
} | gpl-3.0 | 6391595bade54358e9b841913fdae3f9 | 36.632653 | 82 | 0.772653 | 4.665823 | false | false | false | false |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/quests/bikeway/AddCyclewayForm.kt | 1 | 9427 | package de.westnordost.streetcomplete.quests.bikeway
import android.os.Bundle
import androidx.annotation.AnyThread
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.ImageView
import android.widget.TextView
import java.util.Collections
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.tql.FiltersParser
import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment
import de.westnordost.streetcomplete.quests.OtherAnswer
import de.westnordost.streetcomplete.quests.StreetSideRotater
import de.westnordost.streetcomplete.view.ListAdapter
import kotlinx.android.synthetic.main.quest_street_side_puzzle.*
class AddCyclewayForm : AbstractQuestFormAnswerFragment<CyclewayAnswer>() {
override val contentLayoutResId = R.layout.quest_street_side_puzzle
override val contentPadding = false
override val otherAnswers:List<OtherAnswer> get() {
val isNoRoundabout = osmElement!!.tags["junction"] != "roundabout"
return if (!isDefiningBothSides && isNoRoundabout) {
listOf(OtherAnswer(R.string.quest_cycleway_answer_contraflow_cycleway) { showBothSides() })
} else {
listOf()
}
}
private val likelyNoBicycleContraflow = FiltersParser().parse("""
ways with oneway:bicycle != no and
(oneway ~ yes|-1 and highway ~ primary|secondary|tertiary or junction=roundabout)
""")
private var streetSideRotater: StreetSideRotater? = null
private var isDefiningBothSides: Boolean = false
private var leftSide: Cycleway? = null
private var rightSide: Cycleway? = null
/** returns whether the side that goes into the opposite direction of the driving direction of a
* one-way is on the right side of the way */
private val isReverseSideRight get() = isReversedOneway xor isLeftHandTraffic
private val isOneway get() = isForwardOneway || isReversedOneway
private val isForwardOneway get() = osmElement!!.tags["oneway"] == "yes"
private val isReversedOneway get() = osmElement!!.tags["oneway"] == "-1"
// just a shortcut
private val isLeftHandTraffic get() = countryInfo.isLeftHandTraffic
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
isDefiningBothSides = savedInstanceState?.getBoolean(DEFINE_BOTH_SIDES)
?: !likelyNoBicycleContraflow.matches(osmElement)
savedInstanceState?.getString(CYCLEWAY_RIGHT)?.let { rightSide = Cycleway.valueOf(it) }
savedInstanceState?.getString(CYCLEWAY_LEFT)?.let { leftSide = Cycleway.valueOf(it) }
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
puzzleView.listener = { isRight -> showCyclewaySelectionDialog(isRight) }
streetSideRotater = StreetSideRotater(puzzleView, compassNeedle, elementGeometry)
if (!isDefiningBothSides) {
if (isLeftHandTraffic) puzzleView.showOnlyLeftSide()
else puzzleView.showOnlyRightSide()
}
val defaultResId =
if (isLeftHandTraffic) R.drawable.ic_cycleway_unknown_l
else R.drawable.ic_cycleway_unknown
puzzleView.setLeftSideImageResource(leftSide?.getIconResId(isLeftHandTraffic) ?: defaultResId)
puzzleView.setRightSideImageResource(rightSide?.getIconResId(isLeftHandTraffic) ?: defaultResId)
checkIsFormComplete()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
rightSide?.let { outState.putString(CYCLEWAY_RIGHT, it.name) }
leftSide?.let { outState.putString(CYCLEWAY_LEFT, it.name) }
outState.putBoolean(DEFINE_BOTH_SIDES, isDefiningBothSides)
}
@AnyThread
override fun onMapOrientation(rotation: Float, tilt: Float) {
streetSideRotater?.onMapOrientation(rotation, tilt)
}
override fun onClickOk() {
val leftSide = leftSide
val rightSide = rightSide
// a cycleway that goes into opposite direction of a oneway street needs special tagging
var leftSideDir = 0
var rightSideDir = 0
var isOnewayNotForCyclists = false
if (isOneway && leftSide != null && rightSide != null) {
// if the road is oneway=-1, a cycleway that goes opposite to it would be cycleway:oneway=yes
val reverseDir = if (isReversedOneway) 1 else -1
if (isReverseSideRight) {
if (rightSide.isSingleTrackOrLane()) {
rightSideDir = reverseDir
}
} else {
if (leftSide.isSingleTrackOrLane()) {
leftSideDir = reverseDir
}
}
isOnewayNotForCyclists = leftSide.isDualTrackOrLane() || rightSide.isDualTrackOrLane()
|| (if(isReverseSideRight) rightSide else leftSide) !== Cycleway.NONE
}
applyAnswer(CyclewayAnswer(
left = leftSide?.let { CyclewaySide(it, leftSideDir) },
right = rightSide?.let { CyclewaySide(it, rightSideDir) },
isOnewayNotForCyclists = isOnewayNotForCyclists
))
}
private fun Cycleway.isSingleTrackOrLane() =
this === Cycleway.TRACK || this === Cycleway.EXCLUSIVE_LANE
private fun Cycleway.isDualTrackOrLane() =
this === Cycleway.DUAL_TRACK || this === Cycleway.DUAL_LANE
override fun isFormComplete() =
if (isDefiningBothSides) leftSide != null && rightSide != null
else leftSide != null || rightSide != null
private fun showCyclewaySelectionDialog(isRight: Boolean) {
val recyclerView = RecyclerView(activity!!)
recyclerView.layoutParams = RecyclerView.LayoutParams(MATCH_PARENT, MATCH_PARENT)
recyclerView.layoutManager = GridLayoutManager(activity, 2)
val alertDialog = AlertDialog.Builder(activity!!)
.setTitle(R.string.quest_select_hint)
.setView(recyclerView)
.create()
recyclerView.adapter = createAdapter(getCyclewayItems(isRight)) { cycleway ->
alertDialog.dismiss()
val iconResId = cycleway.getIconResId(isLeftHandTraffic)
if (isRight) {
puzzleView.replaceRightSideImageResource(iconResId)
rightSide = cycleway
} else {
puzzleView.replaceLeftSideImageResource(iconResId)
leftSide = cycleway
}
checkIsFormComplete()
}
alertDialog.show()
}
private fun getCyclewayItems(isRight: Boolean): List<Cycleway> {
val values = Cycleway.displayValues.toMutableList()
// different wording for a contraflow lane that is marked like a "shared" lane (just bicycle pictogram)
if (isOneway && isReverseSideRight == isRight) {
Collections.replaceAll(values, Cycleway.PICTOGRAMS, Cycleway.NONE_NO_ONEWAY)
}
val country = countryInfo.countryCode
if ("BE" == country) {
// Belgium does not make a difference between continuous and dashed lanes -> so don't tag that difference
// also, in Belgium there is a differentiation between the normal lanes and suggestion lanes
values.remove(Cycleway.EXCLUSIVE_LANE)
values.remove(Cycleway.ADVISORY_LANE)
values.add(0, Cycleway.LANE_UNSPECIFIED)
values.add(1, Cycleway.SUGGESTION_LANE)
} else if ("NL" == country) {
// a differentiation between dashed lanes and suggestion lanes only exist in NL and BE
values.add(values.indexOf(Cycleway.ADVISORY_LANE) + 1, Cycleway.SUGGESTION_LANE)
}
return values
}
private fun createAdapter(items: List<Cycleway>, callback: (Cycleway) -> Unit) =
object : ListAdapter<Cycleway>(items) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
object : ListAdapter.ViewHolder<Cycleway>(
LayoutInflater.from(parent.context).inflate(R.layout.labeled_icon_button_cell, parent, false)
) {
override fun onBind(with: Cycleway) {
val imageView = itemView.findViewById<ImageView>(R.id.imageView)
val textView = itemView.findViewById<TextView>(R.id.textView)
val resId = with.getIconResId(isLeftHandTraffic)
imageView.setImageDrawable(resources.getDrawable(resId))
textView.setText(with.nameResId)
itemView.setOnClickListener { callback(with) }
}
}
}
private fun showBothSides() {
isDefiningBothSides = true
puzzleView.showBothSides()
checkIsFormComplete()
}
companion object {
private const val CYCLEWAY_LEFT = "cycleway_left"
private const val CYCLEWAY_RIGHT = "cycleway_right"
private const val DEFINE_BOTH_SIDES = "define_both_sides"
}
}
| gpl-3.0 | 362c63d58498593da4e161b27d97ed10 | 40.346491 | 117 | 0.662989 | 4.956362 | false | false | false | false |
google/zsldemo | app/src/main/java/com/hadrosaur/zsldemo/CircularImageBuffer.kt | 1 | 1998 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hadrosaur.zsldemo
import android.hardware.camera2.CaptureResult
import android.hardware.camera2.TotalCaptureResult
import android.media.Image
import com.hadrosaur.zsldemo.MainActivity.Companion.Logd
import java.util.*
//TODO: there is no reason this could not be managed on the fly with a slider
val CIRCULAR_BUFFER_SIZE = 10
class CircularImageBuffer {
val buffer: ArrayDeque<Image> = ArrayDeque(CIRCULAR_BUFFER_SIZE)
fun add(image: Image) {
if (CIRCULAR_BUFFER_SIZE <= buffer.size) {
buffer.removeLast().close()
}
buffer.addFirst(image)
}
fun findMatchingImage(result: TotalCaptureResult) : Image {
val timestamp: Long? = result.get(CaptureResult.SENSOR_TIMESTAMP)
if (timestamp != null) {
//Look through the buffer for the image that matches
for (image in buffer) {
if (image.timestamp == timestamp) {
return image
}
}
}
//If we didn't find the matching image, or there is no timestamp just return one
//Note: we pick the 3rd newest if we have it to account for the finger press causing capture to be unfocused
if (buffer.size >= 3)
return buffer.elementAt(2)
else
return buffer.first
}
fun remove(image: Image) {
buffer.remove(image)
}
} | apache-2.0 | 359d95d41fd989df8b934d0e870f3fb3 | 30.730159 | 116 | 0.666667 | 4.224101 | false | false | false | false |
android/performance-samples | MacrobenchmarkSample/macrobenchmark/src/main/java/com/example/macrobenchmark/startup/FullyDrawnStartupBenchmark.kt | 1 | 1574 | /*
* 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 com.example.macrobenchmark.startup
import android.content.Intent
import androidx.benchmark.macro.StartupTimingMetric
import androidx.benchmark.macro.junit4.MacrobenchmarkRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.example.benchmark.macro.base.util.DEFAULT_ITERATIONS
import com.example.benchmark.macro.base.util.TARGET_PACKAGE
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class FullyDrawnStartupBenchmark {
@get:Rule
val benchmarkRule = MacrobenchmarkRule()
@Test
fun startup() = benchmarkRule.measureRepeated(
packageName = TARGET_PACKAGE,
metrics = listOf(StartupTimingMetric()),
iterations = DEFAULT_ITERATIONS,
) {
val intent = Intent()
intent.action = "$TARGET_PACKAGE.FULLY_DRAWN_STARTUP_ACTIVITY"
startActivityAndWait(intent)
}
}
| apache-2.0 | c83c42dd8344ba13f0a61afd047c12f0 | 33.217391 | 75 | 0.756036 | 4.277174 | false | true | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/widget/AutofitRecyclerView.kt | 1 | 1303 | package eu.kanade.tachiyomi.widget
import android.content.Context
import android.util.AttributeSet
import androidx.core.content.withStyledAttributes
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.max
class AutofitRecyclerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
RecyclerView(context, attrs) {
private val manager = GridLayoutManager(context, 1)
private var columnWidth = -1
var spanCount = 0
set(value) {
field = value
if (value > 0) {
manager.spanCount = value
}
}
val itemWidth: Int
get() = measuredWidth / manager.spanCount
init {
if (attrs != null) {
val attrsArray = intArrayOf(android.R.attr.columnWidth)
context.withStyledAttributes(attrs, attrsArray) {
columnWidth = getDimensionPixelSize(0, -1)
}
}
layoutManager = manager
}
override fun onMeasure(widthSpec: Int, heightSpec: Int) {
super.onMeasure(widthSpec, heightSpec)
if (spanCount == 0 && columnWidth > 0) {
val count = max(1, measuredWidth / columnWidth)
spanCount = count
}
}
}
| apache-2.0 | 3d2606f1d1ddcf8c1e03c238288858e5 | 27.326087 | 100 | 0.636224 | 4.86194 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/universal/ScopedFirebaseCoreService.kt | 2 | 8171 | package abi44_0_0.host.exp.exponent.modules.universal
import android.content.Context
import android.util.Base64
import com.google.firebase.FirebaseApp
import com.google.firebase.FirebaseOptions
import abi44_0_0.expo.modules.core.ModuleRegistry
import abi44_0_0.expo.modules.core.interfaces.RegistryLifecycleListener
import abi44_0_0.expo.modules.firebase.core.FirebaseCoreOptions
import abi44_0_0.expo.modules.firebase.core.FirebaseCoreService
import expo.modules.manifests.core.Manifest
import host.exp.exponent.kernel.ExperienceKey
import org.json.JSONObject
import java.io.UnsupportedEncodingException
import java.lang.Exception
class ScopedFirebaseCoreService(
context: Context,
manifest: Manifest,
experienceKey: ExperienceKey
) : FirebaseCoreService(context), RegistryLifecycleListener {
private val appName: String
private val appOptions: FirebaseOptions?
override fun getAppName(): String {
return appName
}
override fun getAppOptions(): FirebaseOptions? {
return appOptions
}
override fun isAppAccessible(name: String): Boolean {
synchronized(protectedAppNames) {
if (protectedAppNames.containsKey(name) && appName != name) {
return false
}
}
return super.isAppAccessible(name)
}
// Registry lifecycle events
override fun onCreate(moduleRegistry: ModuleRegistry) {
// noop
}
override fun onDestroy() {
// Mark this Firebase App as deleted. Don't delete it straight
// away, but mark it for deletion. When loading a new project
// a check is performed that will cleanup the deleted Firebase apps.
// This ensures that Firebase Apps don't get deleted/recreated
// every time a project reload happens, and also also ensures that
// `isAppAccessible` keeps the app unavailable for other project/packages
// after unload.
synchronized(protectedAppNames) { protectedAppNames.put(appName, true) }
}
companion object {
private val protectedAppNames = mutableMapOf<String, Boolean>() // Map<App-name, isDeleted>
private fun getEncodedExperienceScopeKey(experienceKey: ExperienceKey): String {
return try {
val encodedUrl = experienceKey.getUrlEncodedScopeKey()
val data = encodedUrl.toByteArray(charset("UTF-8"))
Base64.encodeToString(
data,
Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP
)
} catch (e: UnsupportedEncodingException) {
experienceKey.scopeKey.hashCode().toString()
}
}
// google-services.json loading
private fun getJSONStringByPath(jsonArg: JSONObject?, path: String): String? {
var json = jsonArg ?: return null
return try {
val paths = path.split(".").toTypedArray()
for (i in paths.indices) {
val name = paths[i]
if (!json.has(name)) return null
if (i == paths.size - 1) {
return json.getString(name)
} else {
json = json.getJSONObject(name)
}
}
null
} catch (err: Exception) {
null
}
}
private fun MutableMap<String, String>.putJSONString(
key: String,
json: JSONObject?,
path: String
) {
val value = getJSONStringByPath(json, path)
if (value != null) this[key] = value
}
private fun getClientFromGoogleServices(
googleServicesFile: JSONObject?,
preferredPackageNames: List<String?>
): JSONObject? {
val clients = googleServicesFile?.optJSONArray("client") ?: return null
// Find the client and prefer the ones that are in the preferredPackageNames list.
// Later in the list means higher priority.
var client: JSONObject? = null
var clientPreferredPackageNameIndex = -1
for (i in 0 until clients.length()) {
val possibleClient = clients.optJSONObject(i)
if (possibleClient != null) {
val packageName = getJSONStringByPath(possibleClient, "client_info.android_client_info.package_name")
val preferredPackageNameIndex = if (packageName != null) preferredPackageNames.indexOf(packageName) else -1
if (client == null || preferredPackageNameIndex > clientPreferredPackageNameIndex) {
client = possibleClient
clientPreferredPackageNameIndex = preferredPackageNameIndex
}
}
}
return client
}
private fun getOptionsFromManifest(manifest: Manifest): FirebaseOptions? {
return try {
val googleServicesFileString = manifest.getAndroidGoogleServicesFile()
val googleServicesFile = if (googleServicesFileString != null) JSONObject(googleServicesFileString) else null
val packageName = if (manifest.getAndroidPackageName() != null) manifest.getAndroidPackageName() else ""
// Read project-info settings
// https://developers.google.com/android/guides/google-services-plugin
val json = mutableMapOf<String, String>().apply {
putJSONString("projectId", googleServicesFile, "project_info.project_id")
putJSONString("messagingSenderId", googleServicesFile, "project_info.project_number")
putJSONString("databaseURL", googleServicesFile, "project_info.firebase_url")
putJSONString("storageBucket", googleServicesFile, "project_info.storage_bucket")
}
// Get the client that matches this app. When the Expo Go package was explicitly
// configured in google-services.json, then use that app when possible.
// Otherwise, use the client that matches the package_name specified in app.json.
// If none of those are found, use first encountered client in google-services.json.
val client = getClientFromGoogleServices(
googleServicesFile,
listOf(
packageName,
"host.exp.exponent"
)
)
// Read properties from client
json.putJSONString("appId", client, "client_info.mobilesdk_app_id")
json.putJSONString(
"trackingId",
client,
"services.analytics_service.analytics_property.tracking_id"
)
val apiKey = client?.optJSONArray("api_key")
if (apiKey != null && apiKey.length() > 0) {
json.putJSONString("apiKey", apiKey.getJSONObject(0), "current_key")
}
// The appId is the best indicator on whether all required info was available
// and parsed correctly.
if (json.containsKey("appId")) FirebaseCoreOptions.fromJSON(json) else null
} catch (err: Exception) {
null
}
}
}
init {
// Get the default firebase app name
val defaultApp = getFirebaseApp(null)
val defaultAppName = defaultApp?.name ?: DEFAULT_APP_NAME
// Get experience key & unique app name
appName = "__sandbox_" + getEncodedExperienceScopeKey(experienceKey)
appOptions = getOptionsFromManifest(manifest)
// Add the app to the list of protected app names
synchronized(protectedAppNames) {
protectedAppNames[defaultAppName] = false
protectedAppNames[appName] = false
}
// Delete any previously created apps for which the project was unloaded
// This ensures that the list of Firebase Apps doesn't keep growing
// for each uniquely loaded project.
for (app in FirebaseApp.getApps(context)) {
var isDeleted = false
synchronized(protectedAppNames) {
if (protectedAppNames.containsKey(app.name)) {
isDeleted = protectedAppNames[app.name]!!
}
}
if (isDeleted) {
app.delete()
}
}
// Cleanup any deleted apps from the protected-names map
synchronized(protectedAppNames) {
val forRemoval = mutableSetOf<String>()
for ((key, value) in protectedAppNames) {
if (value) { // isDeleted
forRemoval.add(key)
}
}
for (app in forRemoval) {
protectedAppNames.remove(app)
}
}
// Initialize the firebase app. This will delete/create/update the app
// if it has changed, and leaves the app untouched when the config
// is the same.
updateFirebaseApp(appOptions, appName)
}
}
| bsd-3-clause | ac1830b128c1a4f8e13f80468642af10 | 35.477679 | 117 | 0.674458 | 4.55971 | false | false | false | false |
Heiner1/AndroidAPS | app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt | 1 | 8294 | package info.nightscout.androidaps
import android.content.Context
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.ProfileSealed
import info.nightscout.androidaps.database.embedments.InsulinConfiguration
import info.nightscout.androidaps.database.entities.EffectiveProfileSwitch
import info.nightscout.androidaps.extensions.pureProfileFromJson
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.Config
import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.ProfileStore
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.interfaces.ResourceHelper
import org.json.JSONObject
import org.junit.Before
import org.mockito.ArgumentMatchers.anyDouble
import org.mockito.ArgumentMatchers.anyInt
import org.mockito.ArgumentMatchers.anyString
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.`when`
import org.mockito.invocation.InvocationOnMock
@Suppress("SpellCheckingInspection")
open class TestBaseWithProfile : TestBase() {
@Mock lateinit var activePluginProvider: ActivePlugin
@Mock lateinit var rh: ResourceHelper
@Mock lateinit var iobCobCalculator: IobCobCalculator
@Mock lateinit var fabricPrivacy: FabricPrivacy
@Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var config: Config
@Mock lateinit var context: Context
lateinit var dateUtil: DateUtil
val rxBus = RxBus(aapsSchedulers, aapsLogger)
val profileInjector = HasAndroidInjector { AndroidInjector { } }
private lateinit var validProfileJSON: String
lateinit var validProfile: ProfileSealed.Pure
lateinit var effectiveProfileSwitch: EffectiveProfileSwitch
@Suppress("PropertyName") val TESTPROFILENAME = "someProfile"
@Before
fun prepareMock() {
validProfileJSON = "{\"dia\":\"5\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"3\"}," +
"{\"time\":\"2:00\",\"value\":\"3.4\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4.5\"}]," +
"\"target_high\":[{\"time\":\"00:00\",\"value\":\"7\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}"
dateUtil = Mockito.spy(DateUtil(context))
`when`(dateUtil.now()).thenReturn(1656358822000)
validProfile = ProfileSealed.Pure(pureProfileFromJson(JSONObject(validProfileJSON), dateUtil)!!)
effectiveProfileSwitch = EffectiveProfileSwitch(
timestamp = dateUtil.now(),
basalBlocks = validProfile.basalBlocks,
isfBlocks = validProfile.isfBlocks,
icBlocks = validProfile.icBlocks,
targetBlocks = validProfile.targetBlocks,
glucoseUnit = EffectiveProfileSwitch.GlucoseUnit.MMOL,
originalProfileName = "",
originalCustomizedName = "",
originalTimeshift = 0,
originalPercentage = 100,
originalDuration = 0,
originalEnd = 0,
insulinConfiguration = InsulinConfiguration("", 0, 0)
)
Mockito.doAnswer { invocation: InvocationOnMock ->
val string = invocation.getArgument<Int>(0)
val arg1 = invocation.getArgument<Int?>(1)
String.format(rh.gs(string), arg1)
}.`when`(rh).gs(anyInt(), anyInt())
Mockito.doAnswer { invocation: InvocationOnMock ->
val string = invocation.getArgument<Int>(0)
val arg1 = invocation.getArgument<Double?>(1)
String.format(rh.gs(string), arg1)
}.`when`(rh).gs(anyInt(), anyDouble())
Mockito.doAnswer { invocation: InvocationOnMock ->
val string = invocation.getArgument<Int>(0)
val arg1 = invocation.getArgument<String?>(1)
String.format(rh.gs(string), arg1)
}.`when`(rh).gs(anyInt(), anyString())
Mockito.doAnswer { invocation: InvocationOnMock ->
val string = invocation.getArgument<Int>(0)
val arg1 = invocation.getArgument<String?>(1)
val arg2 = invocation.getArgument<String?>(2)
String.format(rh.gs(string), arg1, arg2)
}.`when`(rh).gs(anyInt(), anyString(), anyString())
Mockito.doAnswer { invocation: InvocationOnMock ->
val string = invocation.getArgument<Int>(0)
val arg1 = invocation.getArgument<String?>(1)
val arg2 = invocation.getArgument<Int?>(2)
String.format(rh.gs(string), arg1, arg2)
}.`when`(rh).gs(anyInt(), anyString(), anyInt())
Mockito.doAnswer { invocation: InvocationOnMock ->
val string = invocation.getArgument<Int>(0)
val arg1 = invocation.getArgument<Double?>(1)
val arg2 = invocation.getArgument<String?>(2)
String.format(rh.gs(string), arg1, arg2)
}.`when`(rh).gs(anyInt(), anyDouble(), anyString())
Mockito.doAnswer { invocation: InvocationOnMock ->
val string = invocation.getArgument<Int>(0)
val arg1 = invocation.getArgument<Double?>(1)
val arg2 = invocation.getArgument<Int?>(2)
String.format(rh.gs(string), arg1, arg2)
}.`when`(rh).gs(anyInt(), anyDouble(), anyInt())
Mockito.doAnswer { invocation: InvocationOnMock ->
val string = invocation.getArgument<Int>(0)
val arg1 = invocation.getArgument<Int?>(1)
val arg2 = invocation.getArgument<Int?>(2)
String.format(rh.gs(string), arg1, arg2)
}.`when`(rh).gs(anyInt(), anyInt(), anyInt())
Mockito.doAnswer { invocation: InvocationOnMock ->
val string = invocation.getArgument<Int>(0)
val arg1 = invocation.getArgument<Int?>(1)
val arg2 = invocation.getArgument<String?>(2)
String.format(rh.gs(string), arg1, arg2)
}.`when`(rh).gs(anyInt(), anyInt(), anyString())
Mockito.doAnswer { invocation: InvocationOnMock ->
val string = invocation.getArgument<Int>(0)
val arg1 = invocation.getArgument<Int?>(1)
val arg2 = invocation.getArgument<Int?>(2)
val arg3 = invocation.getArgument<String?>(3)
String.format(rh.gs(string), arg1, arg2, arg3)
}.`when`(rh).gs(anyInt(), anyInt(), anyInt(), anyString())
Mockito.doAnswer { invocation: InvocationOnMock ->
val string = invocation.getArgument<Int>(0)
val arg1 = invocation.getArgument<Int?>(1)
val arg2 = invocation.getArgument<String?>(2)
val arg3 = invocation.getArgument<String?>(3)
String.format(rh.gs(string), arg1, arg2, arg3)
}.`when`(rh).gs(anyInt(), anyInt(), anyString(), anyString())
Mockito.doAnswer { invocation: InvocationOnMock ->
val string = invocation.getArgument<Int>(0)
val arg1 = invocation.getArgument<Double?>(1)
val arg2 = invocation.getArgument<Int?>(2)
val arg3 = invocation.getArgument<String?>(3)
String.format(rh.gs(string), arg1, arg2, arg3)
}.`when`(rh).gs(anyInt(), anyDouble(), anyInt(), anyString())
Mockito.doAnswer { invocation: InvocationOnMock ->
val string = invocation.getArgument<Int>(0)
val arg1 = invocation.getArgument<String?>(1)
val arg2 = invocation.getArgument<Int?>(2)
val arg3 = invocation.getArgument<String?>(3)
String.format(rh.gs(string), arg1, arg2, arg3)
}.`when`(rh).gs(anyInt(), anyString(), anyInt(), anyString())
}
fun getValidProfileStore(): ProfileStore {
val json = JSONObject()
val store = JSONObject()
store.put(TESTPROFILENAME, JSONObject(validProfileJSON))
json.put("defaultProfile", TESTPROFILENAME)
json.put("store", store)
return ProfileStore(profileInjector, json, dateUtil)
}
}
| agpl-3.0 | 5ebf80867779083199d20c02731c2f7a | 45.858757 | 184 | 0.649988 | 4.564667 | false | false | false | false |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/entities/MultiwaveBolusLink.kt | 1 | 1523 | package info.nightscout.androidaps.database.entities
import androidx.room.*
import info.nightscout.androidaps.database.TABLE_MULTIWAVE_BOLUS_LINKS
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.interfaces.TraceableDBEntry
@Entity(tableName = TABLE_MULTIWAVE_BOLUS_LINKS,
foreignKeys = [ForeignKey(
entity = Bolus::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("bolusId")), ForeignKey(
entity = ExtendedBolus::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("extendedBolusId")), ForeignKey(
entity = MultiwaveBolusLink::class,
parentColumns = ["id"],
childColumns = ["referenceId"])],
indices = [Index("referenceId"), Index("bolusId"),
Index("extendedBolusId")])
data class MultiwaveBolusLink(
@PrimaryKey(autoGenerate = true)
override var id: Long = 0,
override var version: Int = 0,
override var dateCreated: Long = -1,
override var isValid: Boolean = true,
override var referenceId: Long? = null,
@Embedded
override var interfaceIDs_backing: InterfaceIDs? = null,
var bolusId: Long,
var extendedBolusId: Long
) : TraceableDBEntry {
override val foreignKeysValid: Boolean
get() = super.foreignKeysValid && bolusId != 0L && bolusId != 0L && extendedBolusId != 0L
} | agpl-3.0 | cac276afa8c476e4fc8a68a0cb707122 | 40.189189 | 97 | 0.640184 | 4.944805 | false | false | false | false |
auth0/Auth0.Android | auth0/src/main/java/com/auth0/android/management/ManagementException.kt | 1 | 2878 | package com.auth0.android.management
import com.auth0.android.Auth0Exception
import com.auth0.android.NetworkErrorException
public class ManagementException @JvmOverloads constructor(
message: String,
exception: Auth0Exception? = null
) : Auth0Exception(message, exception) {
private var code: String? = null
private var description: String? = null
/**
* Http Response status code. Can have value of 0 if not set.
*
* @return the status code.
*/
public var statusCode: Int = 0
private set
private var values: Map<String, Any>? = null
public constructor(payload: String?, statusCode: Int) : this(DEFAULT_MESSAGE) {
code = if (payload != null) NON_JSON_ERROR else EMPTY_BODY_ERROR
description = payload ?: EMPTY_RESPONSE_BODY_DESCRIPTION
this.statusCode = statusCode
}
public constructor(values: Map<String, Any>) : this(DEFAULT_MESSAGE) {
this.values = values
val codeValue =
(if (values.containsKey(ERROR_KEY)) values[ERROR_KEY] else values[CODE_KEY]) as String?
code = codeValue ?: UNKNOWN_ERROR
description =
(if (values.containsKey(DESCRIPTION_KEY)) values[DESCRIPTION_KEY] else values[ERROR_DESCRIPTION_KEY]) as String?
}
/**
* Auth0 error code if the server returned one or an internal library code (e.g.: when the server could not be reached)
*
* @return the error code.
*/
@Suppress("MemberVisibilityCanBePrivate")
public fun getCode(): String {
return if (code != null) code!! else UNKNOWN_ERROR
}
/**
* Description of the error.
* important: You should avoid displaying description to the user, it's meant for debugging only.
*
* @return the error description.
*/
@Suppress("unused")
public fun getDescription(): String {
if (description != null) {
return description!!
}
return if (UNKNOWN_ERROR == getCode()) {
String.format("Received error with code %s", getCode())
} else "Failed with unknown error"
}
/**
* Returns a value from the error map, if any.
*
* @param key key of the value to return
* @return the value if found or null
*/
public fun getValue(key: String): Any? {
return values?.get(key)
}
// When the request failed due to network issues
public val isNetworkError: Boolean
get() = cause is NetworkErrorException
private companion object {
private const val ERROR_KEY = "error"
private const val CODE_KEY = "code"
private const val DESCRIPTION_KEY = "description"
private const val ERROR_DESCRIPTION_KEY = "error_description"
private const val DEFAULT_MESSAGE =
"An error occurred when trying to authenticate with the server."
}
} | mit | 1f39682b22f6579ca685f047e2520285 | 32.870588 | 124 | 0.641418 | 4.468944 | false | false | false | false |
sjnyag/stamp | app/src/main/java/com/sjn/stamp/utils/PlayModeHelper.kt | 1 | 4181 | package com.sjn.stamp.utils
import android.app.Activity
import android.support.v4.media.MediaBrowserServiceCompat
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.PlaybackStateCompat
object PlayModeHelper {
fun restore(service: MediaBrowserServiceCompat) {
setShuffleMode(service, PreferenceHelper.loadShuffle(service, PlaybackStateCompat.SHUFFLE_MODE_NONE))
setRepeatMode(service, PreferenceHelper.loadRepeat(service, PlaybackStateCompat.REPEAT_MODE_NONE))
}
fun getShuffleMode(service: MediaBrowserServiceCompat?): Int = getShuffleMode(MediaControllerHelper.getController(service))
fun getShuffleMode(activity: Activity?): Int = getShuffleMode(MediaControllerHelper.getController(activity))
fun getRepeatMode(service: MediaBrowserServiceCompat?): Int = getRepeatMode(MediaControllerHelper.getController(service))
fun getRepeatMode(activity: Activity?): Int = getRepeatMode(MediaControllerHelper.getController(activity))
fun toggleRepeatMode(activity: Activity?) {
when (getRepeatMode(activity)) {
PlaybackStateCompat.REPEAT_MODE_NONE -> {
PlaybackStateCompat.REPEAT_MODE_ALL
}
PlaybackStateCompat.REPEAT_MODE_ALL -> {
PlaybackStateCompat.REPEAT_MODE_ONE
}
PlaybackStateCompat.REPEAT_MODE_ONE -> {
PlaybackStateCompat.REPEAT_MODE_NONE
}
else -> {
null
}
}?.let {
setRepeatMode(activity, it)
}
}
fun toggleShuffleMode(activity: Activity?) {
when (getShuffleMode(activity)) {
PlaybackStateCompat.SHUFFLE_MODE_NONE -> {
PlaybackStateCompat.SHUFFLE_MODE_ALL
}
PlaybackStateCompat.SHUFFLE_MODE_ALL -> {
PlaybackStateCompat.SHUFFLE_MODE_NONE
}
else -> {
null
}
}?.let {
setShuffleMode(activity, it)
}
}
private fun getShuffleMode(controller: MediaControllerCompat?): Int {
return controller?.shuffleMode
?: PlaybackStateCompat.SHUFFLE_MODE_INVALID.also { shuffleMode ->
if (shuffleMode == PlaybackStateCompat.SHUFFLE_MODE_INVALID || shuffleMode == PlaybackStateCompat.SHUFFLE_MODE_GROUP) {
return PlaybackStateCompat.SHUFFLE_MODE_NONE
}
}
}
private fun setShuffleMode(service: MediaBrowserServiceCompat, @PlaybackStateCompat.ShuffleMode shuffleMode: Int) {
MediaControllerHelper.getController(service)?.transportControls?.setShuffleMode(shuffleMode).also {
PreferenceHelper.saveShuffle(service, shuffleMode)
}
}
private fun setRepeatMode(service: MediaBrowserServiceCompat, @PlaybackStateCompat.RepeatMode repeatMode: Int) {
MediaControllerHelper.getController(service)?.transportControls?.setRepeatMode(repeatMode).also {
PreferenceHelper.saveRepeat(service, repeatMode)
}
}
private fun setShuffleMode(activity: Activity?, @PlaybackStateCompat.ShuffleMode shuffleMode: Int) {
MediaControllerHelper.getController(activity)?.transportControls?.setShuffleMode(shuffleMode)
activity?.let {
PreferenceHelper.saveShuffle(it, shuffleMode)
}
}
private fun getRepeatMode(controller: MediaControllerCompat?): Int {
return controller?.repeatMode
?: PlaybackStateCompat.REPEAT_MODE_INVALID.also { shuffleMode ->
if (shuffleMode == PlaybackStateCompat.REPEAT_MODE_INVALID || shuffleMode == PlaybackStateCompat.REPEAT_MODE_GROUP) {
return PlaybackStateCompat.REPEAT_MODE_NONE
}
}
}
private fun setRepeatMode(activity: Activity?, @PlaybackStateCompat.RepeatMode repeatMode: Int) {
MediaControllerHelper.getController(activity)?.transportControls?.setRepeatMode(repeatMode)
activity?.let {
PreferenceHelper.saveRepeat(it, repeatMode)
}
}
} | apache-2.0 | e78ba9e659412871cf8d73bba011a330 | 39.601942 | 139 | 0.666109 | 5.422827 | false | false | false | false |
Adventech/sabbath-school-android-2 | features/lessons/src/main/java/com/cryart/sabbathschool/lessons/ui/lessons/LessonsScreen.kt | 1 | 12310 | /*
* Copyright (c) 2022. Adventech <[email protected]>
*
* 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.
*/
@file:OptIn(ExperimentalMaterial3Api::class)
package com.cryart.sabbathschool.lessons.ui.lessons
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.calculateEndPadding
import androidx.compose.foundation.layout.calculateStartPadding
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.material.icons.rounded.Share
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import app.ss.design.compose.widget.appbar.SsTopAppBar
import app.ss.design.compose.widget.appbar.TopAppBarSpec
import app.ss.design.compose.widget.appbar.TopAppBarType
import app.ss.design.compose.widget.icon.IconBox
import app.ss.design.compose.widget.icon.IconButton
import app.ss.design.compose.widget.scaffold.SsScaffold
import com.cryart.sabbathschool.lessons.ui.lessons.components.LessonItemSpec
import com.cryart.sabbathschool.lessons.ui.lessons.components.LessonItemsSpec
import com.cryart.sabbathschool.lessons.ui.lessons.components.LessonsFooterSpec
import com.cryart.sabbathschool.lessons.ui.lessons.components.footer
import com.cryart.sabbathschool.lessons.ui.lessons.components.lessons
import com.cryart.sabbathschool.lessons.ui.lessons.components.loading
import com.cryart.sabbathschool.lessons.ui.lessons.components.quarterlyInfo
import com.cryart.sabbathschool.lessons.ui.lessons.components.spec.toSpec
import com.cryart.sabbathschool.lessons.ui.lessons.components.toSpec
import com.cryart.sabbathschool.lessons.ui.lessons.intro.LessonIntroModel
import com.google.accompanist.systemuicontroller.SystemUiController
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import app.ss.translations.R.string as RString
@Composable
fun LessonsScreen(
state: LessonsScreenState,
onNavClick: () -> Unit,
onShareClick: (String) -> Unit,
onLessonClick: (LessonItemSpec) -> Unit,
onReadMoreClick: (LessonIntroModel) -> Unit
) {
val listState: LazyListState = rememberLazyListState()
val scrollAlpha: ScrollAlpha = rememberScrollAlpha(listState = listState)
LessonsScreen(
state = state,
listState = listState,
scrollAlpha = scrollAlpha,
onNavClick = onNavClick,
onShareClick = onShareClick,
onLessonClick = onLessonClick,
onReadMoreClick = onReadMoreClick,
systemUiController = rememberSystemUiController(),
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun LessonsScreen(
state: LessonsScreenState,
listState: LazyListState,
scrollAlpha: ScrollAlpha,
onNavClick: () -> Unit = {},
onShareClick: (String) -> Unit = {},
onLessonClick: (LessonItemSpec) -> Unit = {},
onReadMoreClick: (LessonIntroModel) -> Unit = {},
systemUiController: SystemUiController? = null,
isSystemInDarkTheme: Boolean = isSystemInDarkTheme(),
) {
val quarterlyTitle = state.quarterlyTitle
val scrollCollapsed by remember { derivedStateOf { scrollAlpha.alpha > MIN_SOLID_ALPHA } }
val collapsed by remember { derivedStateOf { listState.firstVisibleItemIndex > 0 } }
val iconTint by remember { derivedStateOf { Color.White.takeUnless { collapsed } } }
SsScaffold(
modifier = Modifier,
topBar = {
Surface(
modifier = Modifier
.fillMaxWidth(),
color = MaterialTheme.colorScheme.surface.copy(
alpha = if (scrollCollapsed) 1f else scrollAlpha.alpha
),
tonalElevation = if (scrollCollapsed) 4.dp else 0.dp
) {
LessonsTopBar(
title = quarterlyTitle,
showTitle = collapsed,
iconTint = iconTint,
modifier = Modifier,
onNavClick = onNavClick,
onShareClick = {
onShareClick(quarterlyTitle)
}
)
}
},
) { innerPadding ->
LessonsLazyColumn(
quarterlyInfoState = state.quarterlyInfo,
publishingInfoState = state.publishingInfo,
innerPadding = innerPadding,
listState = listState,
onLessonClick = onLessonClick,
onReadMoreClick = onReadMoreClick,
modifier = Modifier
)
}
val useDarkIcons by remember {
derivedStateOf {
when {
isSystemInDarkTheme -> false
else -> collapsed
}
}
}
SideEffect {
systemUiController?.setStatusBarColor(
color = Color.Transparent,
darkIcons = useDarkIcons
)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun LessonsTopBar(
title: String,
showTitle: Boolean,
modifier: Modifier = Modifier,
iconTint: Color? = MaterialTheme.colorScheme.onSurface,
onNavClick: () -> Unit = {},
onShareClick: () -> Unit = {},
) {
SsTopAppBar(
spec = TopAppBarSpec(
topAppBarType = TopAppBarType.Small,
actions = listOf(
IconButton(
imageVector = Icons.Rounded.Share,
contentDescription = stringResource(id = RString.ss_share),
onClick = onShareClick,
tint = iconTint
)
).takeIf { title.isNotEmpty() } ?: emptyList()
),
title = {
val density = LocalDensity.current
AnimatedVisibility(
visible = showTitle,
enter = slideInVertically {
with(density) { -40.dp.roundToPx() }
} + expandVertically(
expandFrom = Alignment.Top
) + fadeIn(
initialAlpha = 0.3f
),
exit = fadeOut()
) {
Text(
text = title,
color = MaterialTheme.colorScheme.onSurface,
overflow = TextOverflow.Ellipsis,
maxLines = 1
)
}
},
modifier = modifier,
navigationIcon = {
IconBox(
icon = IconButton(
imageVector = Icons.Rounded.ArrowBack,
contentDescription = stringResource(id = RString.ss_action_back),
onClick = onNavClick,
tint = iconTint
)
)
},
scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(),
colors = TopAppBarDefaults.smallTopAppBarColors(
containerColor = Color.Transparent
)
)
}
@Composable
private fun LessonsLazyColumn(
quarterlyInfoState: QuarterlyInfoState,
publishingInfoState: PublishingInfoState,
innerPadding: PaddingValues,
listState: LazyListState,
onLessonClick: (LessonItemSpec) -> Unit,
onReadMoreClick: (LessonIntroModel) -> Unit,
modifier: Modifier = Modifier,
) {
val quarterlyInfo = when (quarterlyInfoState) {
QuarterlyInfoState.Error,
QuarterlyInfoState.Loading -> null
is QuarterlyInfoState.Success -> quarterlyInfoState.quarterlyInfo
}
val publishingInfo = when (publishingInfoState) {
PublishingInfoState.Error,
PublishingInfoState.Loading -> null
is PublishingInfoState.Success -> publishingInfoState.publishingInfo
}
LazyColumn(
contentPadding = PaddingValues(
innerPadding.calculateStartPadding(LayoutDirection.Ltr),
0.dp,
innerPadding.calculateEndPadding(LayoutDirection.Ltr),
innerPadding.calculateBottomPadding()
),
modifier = modifier,
state = listState
) {
quarterlyInfo?.let { ssQuarterlyInfo ->
val quarterly = ssQuarterlyInfo.quarterly
quarterlyInfo(
info = ssQuarterlyInfo.toSpec(
readMoreClick = {
onReadMoreClick(
LessonIntroModel(
quarterly.title,
quarterly.introduction ?: quarterly.description
)
)
}
),
publishingInfo = publishingInfo?.toSpec(
primaryColorHex = ssQuarterlyInfo.quarterly.color_primary
),
scrollOffset = { listState.firstVisibleItemScrollOffset.toFloat() },
onLessonClick = onLessonClick
)
lessons(
lessonsSpec = LessonItemsSpec(ssQuarterlyInfo.lessons.map { it.toSpec() }),
onClick = onLessonClick
)
footer(
spec = LessonsFooterSpec(
credits = quarterlyInfo.quarterly.credits.map { it.toSpec() },
features = quarterlyInfo.quarterly.features.map { it.toSpec() }
)
)
} ?: run {
loading()
}
}
}
private const val MIN_SOLID_ALPHA = 0.8f
@Immutable
data class ScrollAlpha(
val alpha: Float
)
@Composable
private fun rememberScrollAlpha(
listState: LazyListState
): ScrollAlpha {
val scrollAlpha by remember {
derivedStateOf {
ScrollAlpha(alpha = listState.scrollAlpha())
}
}
return scrollAlpha
}
private fun LazyListState.scrollAlpha(): Float {
return when (firstVisibleItemIndex) {
0 -> {
val size = layoutInfo.visibleItemsInfo.firstOrNull()?.size ?: run {
return 0f
}
(firstVisibleItemScrollOffset.toFloat() / size.toFloat()).coerceIn(0f, 1f)
}
else -> 1f
}
}
| mit | c7a64b7a4406caa9f6091766178eaa19 | 35.636905 | 94 | 0.652559 | 5.112126 | false | false | false | false |
AcornUI/Acorn | acornui-core/src/test/kotlin/com/acornui/signal/OnceSignalTest.kt | 1 | 1729 | /*
* Copyright 2014 Nicholas Bilyk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UNUSED_ANONYMOUS_PARAMETER")
package com.acornui.signal
import com.acornui.function.as1
import com.acornui.test.assertListEquals
import kotlin.test.*
class OnceSignalTest {
@Test fun dispatchCanOnlyHappenOnce() {
var actual = -1
val s = OnceSignal<Int>()
s.listen { actual = it }
s.dispatch(3)
assertEquals(3, actual)
assertFails {
s.dispatch(4)
}
}
@Test fun listenDefaultsToOnce() {
val arr = Array(5) { -1 }
var i = 0
val handler1 = { it: Int -> arr[i++] = 1 }
val handler2 = { it: Int -> arr[i++] = 2 }
val handler3 = { it: Int -> arr[i++] = 3 }
val handler4 = { it: Int -> arr[i++] = 4 }
val handler5 = { it: Int -> arr[i++] = 5 }
val s = OnceSignal<Int>()
s.listen(true, handler1)
val sub = s.listen(handler2)
assertTrue(sub.isOnce)
s.listen(true, handler3)
s.listen(handler4)
s.listen(true, handler5)
s.dispatch(0)
assertTrue(s.isEmpty())
assertListEquals(arrayOf(1, 2, 3, 4, 5), arr)
}
@Test fun addAfterDispatchIsIgnored() {
val s = OnceSignal<Int>()
s.listen {}
s.dispatch(0)
s.listen {}
assertTrue(s.isEmpty())
}
}
| apache-2.0 | fcb89631a92a040e942e541a5aff83b2 | 22.684932 | 75 | 0.666281 | 3.104129 | false | true | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/mysite/MySiteFragment.kt | 1 | 16392 | package org.wordpress.android.ui.mysite
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup.MarginLayoutParams
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.NonNull
import androidx.appcompat.widget.TooltipCompat
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.databinding.MySiteFragmentBinding
import org.wordpress.android.databinding.MySiteInfoHeaderCardBinding
import org.wordpress.android.ui.ActivityLauncher
import org.wordpress.android.ui.main.SitePickerActivity
import org.wordpress.android.ui.main.utils.MeGravatarLoader
import org.wordpress.android.ui.mysite.MySiteCardAndItem.SiteInfoHeaderCard
import org.wordpress.android.ui.mysite.MySiteCardAndItem.SiteInfoHeaderCard.IconState
import org.wordpress.android.ui.mysite.MySiteViewModel.SiteInfoToolbarViewParams
import org.wordpress.android.ui.mysite.MySiteViewModel.State
import org.wordpress.android.ui.mysite.MySiteViewModel.TabsUiState
import org.wordpress.android.ui.mysite.MySiteViewModel.TabsUiState.TabUiState
import org.wordpress.android.ui.mysite.tabs.MySiteTabFragment
import org.wordpress.android.ui.mysite.tabs.MySiteTabsAdapter
import org.wordpress.android.ui.posts.QuickStartPromptDialogFragment.QuickStartPromptClickInterface
import org.wordpress.android.ui.utils.UiHelpers
import org.wordpress.android.util.extensions.setVisible
import org.wordpress.android.util.image.ImageManager
import org.wordpress.android.util.image.ImageType.BLAVATAR
import org.wordpress.android.util.image.ImageType.USER
import org.wordpress.android.viewmodel.observeEvent
import org.wordpress.android.widgets.QuickStartFocusPoint
import javax.inject.Inject
class MySiteFragment : Fragment(R.layout.my_site_fragment),
QuickStartPromptClickInterface {
@Inject lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject lateinit var uiHelpers: UiHelpers
@Inject lateinit var meGravatarLoader: MeGravatarLoader
@Inject lateinit var imageManager: ImageManager
private lateinit var viewModel: MySiteViewModel
private var binding: MySiteFragmentBinding? = null
private var siteTitle: String? = null
private val viewPagerCallback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
viewModel.onTabChanged(position)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initSoftKeyboard()
initDagger()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViewModel()
binding = MySiteFragmentBinding.bind(view).apply {
setupToolbar()
setupContentViews()
setupObservers()
}
}
private fun initSoftKeyboard() {
// The following prevents the soft keyboard from leaving a white space when dismissed.
requireActivity().window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
}
private fun initDagger() {
(requireActivity().application as WordPress).component().inject(this)
}
private fun initViewModel() {
viewModel = ViewModelProvider(this, viewModelFactory).get(MySiteViewModel::class.java)
}
private fun MySiteFragmentBinding.setupToolbar() {
toolbarMain.let { toolbar ->
toolbar.inflateMenu(R.menu.my_site_menu)
toolbar.menu.findItem(R.id.me_item)?.let { meMenu ->
meMenu.actionView.let { actionView ->
actionView.contentDescription = meMenu.title
actionView.setOnClickListener { viewModel.onAvatarPressed() }
TooltipCompat.setTooltipText(actionView, meMenu.title)
}
}
}
val avatar = root.findViewById<ImageView>(R.id.avatar)
appbarMain.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
val maxOffset = appBarLayout.totalScrollRange
val currentOffset = maxOffset + verticalOffset
val percentage = if (maxOffset == 0) {
updateCollapsibleToolbar(1)
MAX_PERCENT
} else {
updateCollapsibleToolbar(currentOffset)
((currentOffset.toFloat() / maxOffset.toFloat()) * MAX_PERCENT).toInt()
}
fadeSiteInfoHeader(percentage)
avatar?.let { avatar ->
val minSize = avatar.minimumHeight
val maxSize = avatar.maxHeight
val modifierPx = (minSize.toFloat() - maxSize.toFloat()) * (percentage.toFloat() / 100) * -1
val modifierPercentage = modifierPx / minSize
val newScale = 1 + modifierPercentage
avatar.scaleX = newScale
avatar.scaleY = newScale
}
})
}
private fun MySiteFragmentBinding.updateCollapsibleToolbar(currentOffset: Int) {
if (currentOffset == 0) {
collapsingToolbar.title = siteTitle
siteInfo.siteInfoCard.visibility = View.INVISIBLE
} else {
collapsingToolbar.title = null
siteInfo.siteInfoCard.visibility = View.VISIBLE
}
}
private fun MySiteFragmentBinding.fadeSiteInfoHeader(percentage: Int) {
siteInfo.siteInfoCard.alpha = percentage.toFloat() / 100
}
private fun MySiteFragmentBinding.setupContentViews() {
setupViewPager()
setupActionableEmptyView()
}
private fun MySiteFragmentBinding.setupViewPager() {
viewPager.registerOnPageChangeCallback(viewPagerCallback)
}
private fun MySiteFragmentBinding.setupActionableEmptyView() {
actionableEmptyView.button.setOnClickListener { viewModel.onAddSitePressed() }
}
private fun MySiteFragmentBinding.setupObservers() {
viewModel.uiModel.observe(viewLifecycleOwner) { uiModel ->
loadGravatar(uiModel.accountAvatarUrl)
when (val state = uiModel.state) {
is State.SiteSelected -> loadData(state)
is State.NoSites -> loadEmptyView(state)
}
}
viewModel.onNavigation.observeEvent(viewLifecycleOwner, { handleNavigationAction(it) })
viewModel.onScrollTo.observeEvent(viewLifecycleOwner) {
var quickStartScrollPosition = it
if (quickStartScrollPosition == -1) {
appbarMain.setExpanded(true, true)
quickStartScrollPosition = 0
}
if (quickStartScrollPosition > 0) appbarMain.setExpanded(false, true)
binding?.viewPager?.getCurrentFragment()?.handleScrollTo(quickStartScrollPosition)
}
viewModel.onTrackWithTabSource.observeEvent(viewLifecycleOwner) {
binding?.viewPager?.getCurrentFragment()?.onTrackWithTabSource(it)
}
viewModel.selectTab.observeEvent(viewLifecycleOwner) { navTarget ->
viewPager.setCurrentItem(navTarget.position, navTarget.smoothAnimation)
}
}
private fun MySiteFragmentBinding.loadGravatar(avatarUrl: String) =
root.findViewById<ImageView>(R.id.avatar)?.let {
meGravatarLoader.load(
false,
meGravatarLoader.constructGravatarUrl(avatarUrl),
null,
it,
USER,
null
)
}
private fun MySiteFragmentBinding.loadData(state: State.SiteSelected) {
tabLayout.setVisible(state.tabsUiState.showTabs)
updateTabs(state.tabsUiState)
actionableEmptyView.setVisible(false)
viewModel.setActionableEmptyViewGone(actionableEmptyView.isVisible) {
actionableEmptyView.setVisible(false)
}
if (state.siteInfoHeaderState.hasUpdates || !header.isVisible) {
siteInfo.loadMySiteDetails(state.siteInfoHeaderState.siteInfoHeader)
}
updateSiteInfoToolbarView(state.siteInfoToolbarViewParams)
}
private fun MySiteInfoHeaderCardBinding.loadMySiteDetails(siteInfoHeader: SiteInfoHeaderCard) {
siteTitle = siteInfoHeader.title
if (siteInfoHeader.iconState is IconState.Visible) {
mySiteBlavatar.visibility = View.VISIBLE
imageManager.load(mySiteBlavatar, BLAVATAR, siteInfoHeader.iconState.url ?: "")
mySiteIconProgress.visibility = View.GONE
mySiteBlavatar.setOnClickListener { siteInfoHeader.onIconClick.click() }
} else if (siteInfoHeader.iconState is IconState.Progress) {
mySiteBlavatar.setOnClickListener(null)
mySiteIconProgress.visibility = View.VISIBLE
mySiteBlavatar.visibility = View.GONE
}
quickStartIconFocusPoint.setVisibleOrGone(siteInfoHeader.showIconFocusPoint)
if (siteInfoHeader.onTitleClick != null) {
siteInfoContainer.title.setOnClickListener { siteInfoHeader.onTitleClick.click() }
} else {
siteInfoContainer.title.setOnClickListener(null)
}
siteInfoContainer.title.text = siteInfoHeader.title
quickStartTitleFocusPoint.setVisibleOrGone(siteInfoHeader.showTitleFocusPoint)
quickStartSubTitleFocusPoint.setVisibleOrGone(siteInfoHeader.showSubtitleFocusPoint)
siteInfoContainer.subtitle.text = siteInfoHeader.url
siteInfoContainer.subtitle.setOnClickListener { siteInfoHeader.onUrlClick.click() }
switchSite.setOnClickListener { siteInfoHeader.onSwitchSiteClick.click() }
}
private fun MySiteFragmentBinding.updateSiteInfoToolbarView(siteInfoToolbarViewParams: SiteInfoToolbarViewParams) {
showHeader(siteInfoToolbarViewParams.headerVisible)
val appBarHeight = resources.getDimension(siteInfoToolbarViewParams.appBarHeight).toInt()
appbarMain.layoutParams.height = appBarHeight
val toolbarBottomMargin = resources.getDimension(siteInfoToolbarViewParams.toolbarBottomMargin).toInt()
updateToolbarBottomMargin(toolbarBottomMargin)
appbarMain.isLiftOnScroll = siteInfoToolbarViewParams.appBarLiftOnScroll
appbarMain.requestLayout()
}
private fun MySiteFragmentBinding.updateToolbarBottomMargin(appBarHeight: Int) {
val bottomMargin = (appBarHeight / resources.displayMetrics.density).toInt()
val layoutParams = (toolbarMain.layoutParams as? MarginLayoutParams)
layoutParams?.setMargins(0, 0, 0, bottomMargin)
toolbarMain.layoutParams = layoutParams
}
private fun MySiteFragmentBinding.loadEmptyView(state: State.NoSites) {
tabLayout.setVisible(state.tabsUiState.showTabs)
viewModel.setActionableEmptyViewVisible(actionableEmptyView.isVisible) {
actionableEmptyView.setVisible(true)
actionableEmptyView.image.setVisible(state.shouldShowImage)
}
actionableEmptyView.image.setVisible(state.shouldShowImage)
siteTitle = getString(R.string.my_site_section_screen_title)
updateSiteInfoToolbarView(state.siteInfoToolbarViewParams)
appbarMain.setExpanded(false, true)
}
private fun MySiteFragmentBinding.showHeader(visibility: Boolean) {
header.visibility = if (visibility) View.VISIBLE else View.INVISIBLE
}
private fun MySiteFragmentBinding.updateViewPagerAdapterAndMediatorIfNeeded(state: TabsUiState) {
if (viewPager.adapter == null || state.shouldUpdateViewPager) {
viewPager.adapter = MySiteTabsAdapter(this@MySiteFragment, state.tabUiStates)
TabLayoutMediator(tabLayout, viewPager, MySiteTabConfigurationStrategy(state.tabUiStates)).attach()
}
}
private fun MySiteFragmentBinding.updateTabs(state: TabsUiState) {
updateViewPagerAdapterAndMediatorIfNeeded(state)
state.tabUiStates.forEachIndexed { index, tabUiState ->
val tab = tabLayout.getTabAt(index) as TabLayout.Tab
updateTab(tab, tabUiState)
}
}
private fun MySiteFragmentBinding.updateTab(tab: TabLayout.Tab, tabUiState: TabUiState) {
val customView = tab.customView ?: createTabCustomView(tab)
with(customView) {
val title = findViewById<TextView>(R.id.tab_label)
val quickStartFocusPoint = findViewById<QuickStartFocusPoint>(R.id.tab_quick_start_focus_point)
title.text = uiHelpers.getTextOfUiString(requireContext(), tabUiState.label)
quickStartFocusPoint?.setVisible(tabUiState.showQuickStartFocusPoint)
}
}
private fun handleNavigationAction(action: SiteNavigationAction) = when (action) {
is SiteNavigationAction.OpenMeScreen -> ActivityLauncher.viewMeActivityForResult(activity)
is SiteNavigationAction.AddNewSite -> SitePickerActivity.addSite(activity, action.hasAccessToken, action.source)
else -> {
/* Pass all other navigationAction on to the child fragment, so they can be handled properly.
Added brief delay before passing action to nested (view pager) tab fragments to give them time to get
created. */
view?.postDelayed({
binding?.viewPager?.getCurrentFragment()?.handleNavigationAction(action)
}, PASS_TO_TAB_FRAGMENT_DELAY)
Unit
}
}
override fun onPositiveClicked(instanceTag: String) {
binding?.viewPager?.getCurrentFragment()?.onPositiveClicked(instanceTag)
}
override fun onNegativeClicked(instanceTag: String) {
binding?.viewPager?.getCurrentFragment()?.onNegativeClicked(instanceTag)
}
@Suppress("DEPRECATION", "OVERRIDE_DEPRECATION")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
/* Add brief delay before passing result to nested (view pager) tab fragments to give them time to get created.
This is a workaround to fix API Level 25 (GitHub #16225) issue where we noticed that nested fragments
were created after parent fragment was shown the first time and received activity result. It might not be a
real issue as we could only test it on an emulator, we added it to be safe in such cases. */
view?.postDelayed({
binding?.viewPager?.getCurrentFragment()?.onActivityResult(requestCode, resultCode, data)
}, PASS_TO_TAB_FRAGMENT_DELAY)
}
private fun ViewPager2.getCurrentFragment() =
[email protected]("f$currentItem") as? MySiteTabFragment
private fun MySiteFragmentBinding.createTabCustomView(tab: TabLayout.Tab): View {
val customView = LayoutInflater.from(context)
.inflate(R.layout.tab_custom_view, tabLayout, false)
tab.customView = customView
return customView
}
private inner class MySiteTabConfigurationStrategy(
private val tabUiStates: List<TabUiState>
) : TabLayoutMediator.TabConfigurationStrategy {
override fun onConfigureTab(@NonNull tab: TabLayout.Tab, position: Int) {
binding?.updateTab(tab, tabUiStates[position])
}
}
override fun onPause() {
super.onPause()
activity?.let {
if (!it.isChangingConfigurations) {
viewModel.clearActiveQuickStartTask()
}
}
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
companion object {
private const val PASS_TO_TAB_FRAGMENT_DELAY = 300L
private const val MAX_PERCENT = 100
fun newInstance(): MySiteFragment {
return MySiteFragment()
}
}
}
| gpl-2.0 | 797d002141a8ee346ec58657e125be07 | 43.66485 | 120 | 0.703453 | 5.045245 | false | false | false | false |
KotlinNLP/SimpleDNN | src/test/kotlin/core/layers/feedforward/norm/NormLayerStructureSpec.kt | 1 | 2227 | /* Copyright 2020-present Simone Cangialosi. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package core.layers.feedforward.norm
import com.kotlinnlp.simplednn.core.optimizer.getErrorsOf
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertTrue
/**
*
*/
class NormLayerStructureSpec : Spek({
describe("a NormLayer") {
context("forward") {
val layer = NormLayerStructureUtils.buildLayer()
layer.forward()
it("should match the expected output") {
assertTrue {
layer.outputArray.values.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(1.15786, 0.2, -0.561559, -0.44465)),
tolerance = 1.0e-06)
}
}
}
context("backward") {
val layer = NormLayerStructureUtils.buildLayer()
layer.forward()
layer.outputArray.assignErrors(NormLayerStructureUtils.getOutputErrors())
val paramsErrors = layer.backward(propagateToInput = true)
val params = layer.params
it("should match the expected errors of the input") {
assertTrue {
layer.inputArray.errors.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.496258, 0.280667, -0.408761, 0.624352)),
tolerance = 1.0e-06)
}
}
it("should match the expected errors of the weights g") {
assertTrue {
paramsErrors.getErrorsOf(params.g)!!.values.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.64465, -0.25786, -0.451255, -0.483487)),
tolerance = 1.0e-06)
}
}
it("should match the expected errors of the bias b") {
assertTrue {
paramsErrors.getErrorsOf(params.b)!!.values.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(-1.0, -0.2, 0.4, 0.6)),
tolerance = 1.0e-06)
}
}
}
}
})
| mpl-2.0 | 6412adb60aed5c6b72b5dac6d478a1b6 | 29.506849 | 97 | 0.630445 | 4.170412 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertForEachToForLoopIntention.kt | 1 | 4327 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunction
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
class ConvertForEachToForLoopIntention : SelfTargetingOffsetIndependentIntention<KtSimpleNameExpression>(
KtSimpleNameExpression::class.java, KotlinBundle.lazyMessage("replace.with.a.for.loop")
) {
companion object {
private const val FOR_EACH_NAME = "forEach"
private val FOR_EACH_FQ_NAMES: Set<String> by lazy {
sequenceOf("collections", "sequences", "text", "ranges").map { "kotlin.$it.$FOR_EACH_NAME" }.toSet()
}
}
override fun isApplicableTo(element: KtSimpleNameExpression): Boolean {
if (element.getReferencedName() != FOR_EACH_NAME) return false
val data = extractData(element) ?: return false
if (data.functionLiteral.valueParameters.size > 1) return false
if (data.functionLiteral.bodyExpression == null) return false
return true
}
override fun applyTo(element: KtSimpleNameExpression, editor: Editor?) {
val (expressionToReplace, receiver, functionLiteral, context) = extractData(element)!!
val commentSaver = CommentSaver(expressionToReplace)
val loop = generateLoop(functionLiteral, receiver, context)
val result = expressionToReplace.replace(loop) as KtForExpression
result.loopParameter?.also { editor?.caretModel?.moveToOffset(it.startOffset) }
commentSaver.restore(result)
}
private data class Data(
val expressionToReplace: KtExpression,
val receiver: KtExpression,
val functionLiteral: KtLambdaExpression,
val context: BindingContext
)
private fun extractData(nameExpr: KtSimpleNameExpression): Data? {
val parent = nameExpr.parent
val expression = (when (parent) {
is KtCallExpression -> parent.parent as? KtDotQualifiedExpression
is KtBinaryExpression -> parent
else -> null
} ?: return null) as KtExpression //TODO: submit bug
val context = expression.analyze()
val resolvedCall = expression.getResolvedCall(context) ?: return null
if (DescriptorUtils.getFqName(resolvedCall.resultingDescriptor).toString() !in FOR_EACH_FQ_NAMES) return null
val receiver = resolvedCall.call.explicitReceiver as? ExpressionReceiver ?: return null
val argument = resolvedCall.call.valueArguments.singleOrNull() ?: return null
val functionLiteral = argument.getArgumentExpression() as? KtLambdaExpression ?: return null
return Data(expression, receiver.expression, functionLiteral, context)
}
private fun generateLoop(functionLiteral: KtLambdaExpression, receiver: KtExpression, context: BindingContext): KtExpression {
val factory = KtPsiFactory(functionLiteral)
val body = functionLiteral.bodyExpression!!
val function = functionLiteral.functionLiteral
body.forEachDescendantOfType<KtReturnExpression> {
if (it.getTargetFunction(context) == function) {
it.replace(factory.createExpression("continue"))
}
}
val loopRange = KtPsiUtil.safeDeparenthesize(receiver)
val parameter = functionLiteral.valueParameters.singleOrNull()
return factory.createExpressionByPattern("for($0 in $1){ $2 }", parameter ?: "it", loopRange, body.allChildren)
}
}
| apache-2.0 | 535b59e3e75209678ab17aee20b878ff | 45.031915 | 158 | 0.73492 | 5.15733 | false | false | false | false |
ingokegel/intellij-community | platform/platform-impl/src/com/intellij/idea/ApplicationLoader.kt | 1 | 17507 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("ApplicationLoader")
@file:Internal
@file:Suppress("ReplacePutWithAssignment")
package com.intellij.idea
import com.intellij.diagnostic.*
import com.intellij.history.LocalHistory
import com.intellij.icons.AllIcons
import com.intellij.ide.*
import com.intellij.ide.plugins.*
import com.intellij.ide.plugins.marketplace.statistics.PluginManagerUsageCollector
import com.intellij.ide.plugins.marketplace.statistics.enums.DialogAcceptanceResultEnum
import com.intellij.ide.ui.LafManager
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.application.*
import com.intellij.openapi.application.ex.ApplicationEx
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.ui.DialogEarthquakeShaker
import com.intellij.openapi.updateSettings.impl.UpdateSettings
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.SystemPropertyBean
import com.intellij.openapi.util.io.OSAgnosticPathUtil
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.ManagingFS
import com.intellij.openapi.wm.WindowManager
import com.intellij.ui.AnimatedIcon
import com.intellij.ui.AppIcon
import com.intellij.util.PlatformUtils
import com.intellij.util.io.URLUtil
import com.intellij.util.io.createDirectories
import com.intellij.util.lang.ZipFilePool
import com.intellij.util.ui.AsyncProcessIcon
import kotlinx.coroutines.*
import kotlinx.coroutines.future.asCompletableFuture
import kotlinx.coroutines.future.asDeferred
import net.miginfocom.layout.PlatformDefaults
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.VisibleForTesting
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import java.util.concurrent.*
import java.util.concurrent.CancellationException
import java.util.function.BiFunction
import kotlin.system.exitProcess
@Suppress("SSBasedInspection")
private val LOG = Logger.getInstance("#com.intellij.idea.ApplicationLoader")
fun initApplication(rawArgs: List<String>, appDeferred: Deferred<Any>) {
runBlocking(rootTask()) {
doInitApplication(rawArgs, appDeferred)
}
}
suspend fun doInitApplication(rawArgs: List<String>, appDeferred: Deferred<Any>) {
val initAppActivity = StartUpMeasurer.appInitPreparationActivity!!.endAndStart("app initialization")
val pluginSet = initAppActivity.runChild("plugin descriptor init waiting") {
PluginManagerCore.getInitPluginFuture().await()
}
val (app, patchHtmlStyleJob) = initAppActivity.runChild("app waiting") {
@Suppress("UNCHECKED_CAST")
appDeferred.await() as Pair<ApplicationImpl, Job?>
}
initAppActivity.runChild("app component registration") {
app.registerComponents(modules = pluginSet.getEnabledModules(),
app = app,
precomputedExtensionModel = null,
listenerCallbacks = null)
}
withContext(Dispatchers.IO) {
initConfigurationStore(app)
}
coroutineScope {
// executed in main thread
launch {
patchHtmlStyleJob?.join()
val lafManagerDeferred = launch(CoroutineName("laf initialization") + SwingDispatcher) {
// don't wait for result - we just need to trigger initialization if not yet created
app.getServiceAsync(LafManager::class.java)
}
if (!app.isHeadlessEnvironment) {
// preload only when LafManager is ready
lafManagerDeferred.join()
app.getServiceAsync(EditorColorsManager::class.java)
}
}
withContext(Dispatchers.Default) {
val args = processProgramArguments(rawArgs)
val deferredStarter = runActivity("app starter creation") {
createAppStarterAsync(args)
}
initApplicationImpl(args = args,
initAppActivity = initAppActivity,
pluginSet = pluginSet,
app = app,
deferredStarter = deferredStarter)
}
}
}
private suspend fun initApplicationImpl(args: List<String>,
initAppActivity: Activity,
pluginSet: PluginSet,
app: ApplicationImpl,
deferredStarter: Deferred<ApplicationStarter>) {
val appInitializedListeners = coroutineScope {
preloadCriticalServices(app)
app.preloadServices(modules = pluginSet.getEnabledModules(), activityPrefix = "", syncScope = this)
launch {
initAppActivity.runChild("old component init task creating", app::createInitOldComponentsTask)?.let { loadComponentInEdtTask ->
val placeOnEventQueueActivity = initAppActivity.startChild("place on event queue")
withContext(SwingDispatcher) {
placeOnEventQueueActivity.end()
loadComponentInEdtTask()
}
}
StartUpMeasurer.setCurrentState(LoadingState.COMPONENTS_LOADED)
}
runActivity("app init listener preload") {
getAppInitializedListeners(app)
}
}
val asyncScope = app.coroutineScope
coroutineScope {
initAppActivity.runChild("app initialized callback") {
callAppInitialized(appInitializedListeners, asyncScope)
}
// doesn't block app start-up
asyncScope.runPostAppInitTasks(app)
}
initAppActivity.end()
asyncScope.launch {
addActivateAndWindowsCliListeners()
}
val starter = deferredStarter.await()
if (starter.requiredModality == ApplicationStarter.NOT_IN_EDT) {
if (starter is ModernApplicationStarter) {
starter.start(args)
}
else {
// todo https://youtrack.jetbrains.com/issue/IDEA-298594
CompletableFuture.runAsync {
starter.main(args)
}
}
}
else {
withContext(Dispatchers.EDT) {
(TransactionGuard.getInstance() as TransactionGuardImpl).performUserActivity {
starter.main(args)
}
}
}
// no need to use pool once started
ZipFilePool.POOL = null
}
fun CoroutineScope.preloadCriticalServices(app: ApplicationImpl) {
launch {
// LocalHistory wants ManagingFS, it should be fixed somehow, but for now, to avoid thread contention, preload it in a controlled manner
app.getServiceAsync(ManagingFS::class.java).join()
// PlatformVirtualFileManager also wants ManagingFS
launch { app.getServiceAsync(VirtualFileManager::class.java) }
launch { app.getServiceAsyncIfDefined(LocalHistory::class.java) }
}
launch {
// required for indexing tasks (see JavaSourceModuleNameIndex for example)
// FileTypeManager by mistake uses PropertiesComponent instead of own state - it should be fixed someday
app.getServiceAsync(PropertiesComponent::class.java).join()
app.getServiceAsync(FileTypeManager::class.java).join()
// ProjectJdkTable wants FileTypeManager
launch { app.getServiceAsync(ProjectJdkTable::class.java) }
// wants PropertiesComponent
launch { app.getServiceAsync(DebugLogManager::class.java) }
}
}
fun getAppInitializedListeners(app: Application): List<ApplicationInitializedListener> {
val extensionArea = app.extensionArea as ExtensionsAreaImpl
val point = extensionArea.getExtensionPoint<ApplicationInitializedListener>("com.intellij.applicationInitializedListener")
val result = point.extensionList
point.reset()
return result
}
private fun CoroutineScope.runPostAppInitTasks(app: ApplicationImpl) {
launch(CoroutineName("create locator file") + Dispatchers.IO) {
createAppLocatorFile()
}
if (!AppMode.isLightEdit()) {
// this functionality should be used only by plugin functionality that is used after start-up
launch(CoroutineName("system properties setting")) {
SystemPropertyBean.initSystemProperties()
}
}
launch {
val noteAccepted = PluginManagerCore.isThirdPartyPluginsNoteAccepted()
if (noteAccepted == true) {
UpdateSettings.getInstance().isThirdPartyPluginsAllowed = true
PluginManagerUsageCollector.thirdPartyAcceptanceCheck(DialogAcceptanceResultEnum.ACCEPTED)
}
else if (noteAccepted == false) {
PluginManagerUsageCollector.thirdPartyAcceptanceCheck(DialogAcceptanceResultEnum.DECLINED)
}
}
if (app.isHeadlessEnvironment) {
return
}
launch(CoroutineName("icons preloading") + Dispatchers.IO) {
if (app.isInternal) {
IconLoader.setStrictGlobally(true)
}
AsyncProcessIcon("")
AnimatedIcon.Blinking(AllIcons.Ide.FatalError)
AnimatedIcon.FS()
}
launch {
// IDEA-170295
PlatformDefaults.setLogicalPixelBase(PlatformDefaults.BASE_FONT_SIZE)
}
if (!app.isUnitTestMode && System.getProperty("enable.activity.preloading", "true").toBoolean()) {
val extensionPoint = app.extensionArea.getExtensionPoint<PreloadingActivity>("com.intellij.preloadingActivity")
val isDebugEnabled = LOG.isDebugEnabled
ExtensionPointName<PreloadingActivity>("com.intellij.preloadingActivity").processExtensions { preloadingActivity, pluginDescriptor ->
launch {
executePreloadActivity(preloadingActivity, pluginDescriptor, isDebugEnabled)
}
}
extensionPoint.reset()
}
}
// `ApplicationStarter` is an extension, so to find a starter, extensions must be registered first
private fun CoroutineScope.createAppStarterAsync(args: List<String>): Deferred<ApplicationStarter> {
val first = args.firstOrNull()
// first argument maybe a project path
if (first == null) {
return async { IdeStarter() }
}
else if (args.size == 1 && OSAgnosticPathUtil.isAbsolute(first)) {
return async { createDefaultAppStarter() }
}
val starter = findStarter(first) ?: createDefaultAppStarter()
if (AppMode.isHeadless() && !starter.isHeadless) {
@Suppress("DEPRECATION") val commandName = starter.commandName
val message = IdeBundle.message(
"application.cannot.start.in.a.headless.mode",
when {
starter is IdeStarter -> 0
commandName != null -> 1
else -> 2
},
commandName,
starter.javaClass.name,
if (args.isEmpty()) 0 else 1,
args.joinToString(" ")
)
StartupErrorReporter.showMessage(IdeBundle.message("main.startup.error"), message, true)
exitProcess(AppExitCodes.NO_GRAPHICS)
}
// must be executed before container creation
starter.premain(args)
return CompletableDeferred(value = starter)
}
private fun createDefaultAppStarter(): ApplicationStarter {
return if (PlatformUtils.getPlatformPrefix() == "LightEdit") IdeStarter.StandaloneLightEditStarter() else IdeStarter()
}
@VisibleForTesting
internal fun createAppLocatorFile() {
val locatorFile = Path.of(PathManager.getSystemPath(), ApplicationEx.LOCATOR_FILE_NAME)
try {
locatorFile.parent?.createDirectories()
Files.writeString(locatorFile, PathManager.getHomePath(), StandardCharsets.UTF_8)
}
catch (e: IOException) {
LOG.warn("Can't store a location in '$locatorFile'", e)
}
}
private fun addActivateAndWindowsCliListeners() {
addExternalInstanceListener { rawArgs ->
LOG.info("External instance command received")
val (args, currentDirectory) = if (rawArgs.isEmpty()) emptyList<String>() to null else rawArgs.subList(1, rawArgs.size) to rawArgs[0]
ApplicationManager.getApplication().coroutineScope.async {
handleExternalCommand(args, currentDirectory).future.asDeferred().await()
}.asCompletableFuture()
}
EXTERNAL_LISTENER = BiFunction { currentDirectory, args ->
LOG.info("External Windows command received")
if (args.isEmpty()) {
return@BiFunction 0
}
val result = runBlocking { handleExternalCommand(args.asList(), currentDirectory) }
CliResult.unmap(result.future, AppExitCodes.ACTIVATE_ERROR).exitCode
}
ApplicationManager.getApplication().messageBus.simpleConnect().subscribe(AppLifecycleListener.TOPIC, object : AppLifecycleListener {
override fun appWillBeClosed(isRestart: Boolean) {
addExternalInstanceListener { CliResult.error(AppExitCodes.ACTIVATE_DISPOSING, IdeBundle.message("activation.shutting.down")) }
EXTERNAL_LISTENER = BiFunction { _, _ -> AppExitCodes.ACTIVATE_DISPOSING }
}
})
}
private suspend fun handleExternalCommand(args: List<String>, currentDirectory: String?): CommandLineProcessorResult {
val result = if (args.isNotEmpty() && args[0].contains(URLUtil.SCHEME_SEPARATOR)) {
CommandLineProcessorResult(project = null, result = CommandLineProcessor.processProtocolCommand(args[0]))
}
else {
CommandLineProcessor.processExternalCommandLine(args, currentDirectory)
}
// not a part of handleExternalCommand invocation - invokeLater
ApplicationManager.getApplication().coroutineScope.launch(Dispatchers.EDT) {
if (result.showErrorIfFailed()) {
return@launch
}
val windowManager = WindowManager.getInstance()
if (result.project == null) {
windowManager.findVisibleFrame()?.let { frame ->
frame.toFront()
DialogEarthquakeShaker.shake(frame)
}
}
else {
windowManager.getIdeFrame(result.project)?.let {
AppIcon.getInstance().requestFocus(it)
}
}
}
return result
}
fun findStarter(key: String): ApplicationStarter? {
val point = ApplicationStarter.EP_NAME.point as ExtensionPointImpl<ApplicationStarter>
var result: ApplicationStarter? = point.sortedAdapters.firstOrNull { it.orderId == key } ?.createInstance(point.componentManager)
if (result == null) {
result = point.firstOrNull {
@Suppress("DEPRECATION")
it?.commandName == key
}
}
return result
}
fun initConfigurationStore(app: ApplicationImpl) {
var activity = StartUpMeasurer.startActivity("beforeApplicationLoaded")
val configPath = PathManager.getConfigDir()
for (listener in ApplicationLoadListener.EP_NAME.iterable) {
try {
(listener ?: break).beforeApplicationLoaded(app, configPath)
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
}
}
activity = activity.endAndStart("init app store")
// we set it after beforeApplicationLoaded call, because the app store can depend on stream provider state
app.stateStore.setPath(configPath)
StartUpMeasurer.setCurrentState(LoadingState.CONFIGURATION_STORE_INITIALIZED)
activity.end()
}
/**
* The method looks for `-Dkey=value` program arguments and stores some of them in system properties.
* We should use it for a limited number of safe keys; one of them is a list of required plugins.
*/
@Suppress("SpellCheckingInspection")
private fun processProgramArguments(args: List<String>): List<String> {
if (args.isEmpty()) {
return emptyList()
}
// no need to have it as a file-level constant - processProgramArguments called at most once.
val safeJavaEnvParameters = arrayOf(JetBrainsProtocolHandler.REQUIRED_PLUGINS_KEY)
val arguments = mutableListOf<String>()
for (arg in args) {
if (arg.startsWith("-D")) {
val keyValue = arg.substring(2).split('=')
if (keyValue.size == 2 && safeJavaEnvParameters.contains(keyValue[0])) {
System.setProperty(keyValue[0], keyValue[1])
continue
}
}
if (!CommandLineArgs.isKnownArgument(arg)) {
arguments.add(arg)
}
}
return arguments
}
fun CoroutineScope.callAppInitialized(listeners: List<ApplicationInitializedListener>, asyncScope: CoroutineScope) {
for (listener in listeners) {
launch {
listener.execute(asyncScope)
}
}
}
@Internal
internal inline fun <T> ExtensionPointName<T>.processExtensions(consumer: (extension: T, pluginDescriptor: PluginDescriptor) -> Unit) {
val app = ApplicationManager.getApplication()
val extensionArea = app.extensionArea as ExtensionsAreaImpl
for (adapter in extensionArea.getExtensionPoint<T>(name).getSortedAdapters()) {
val extension: T = try {
adapter.createInstance(app) ?: continue
}
catch (e: CancellationException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
continue
}
consumer(extension, adapter.pluginDescriptor)
}
}
private suspend fun executePreloadActivity(activity: PreloadingActivity, descriptor: PluginDescriptor?, isDebugEnabled: Boolean) {
val measureActivity = if (descriptor == null) {
null
}
else {
StartUpMeasurer.startActivity(activity.javaClass.name, ActivityCategory.PRELOAD_ACTIVITY, descriptor.pluginId.idString)
}
try {
activity.execute()
if (isDebugEnabled) {
LOG.debug("${activity.javaClass.name} finished")
}
}
catch (e: CancellationException) {
throw e
}
catch (e: Throwable) {
LOG.error("cannot execute preloading activity ${activity.javaClass.name}", e)
}
finally {
measureActivity?.end()
}
}
| apache-2.0 | 256674f93c690b67fc04ae12c49221fc | 34.583333 | 140 | 0.731479 | 4.61196 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/opus/OpusTransitData.kt | 1 | 4997 | /*
* OpusTransitData.kt
*
* Copyright 2018 Google
*
* 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 au.id.micolous.metrodroid.transit.opus
import au.id.micolous.metrodroid.card.CardType
import au.id.micolous.metrodroid.card.calypso.CalypsoApplication
import au.id.micolous.metrodroid.card.calypso.CalypsoCardTransitFactory
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.transit.CardInfo
import au.id.micolous.metrodroid.transit.TransitIdentity
import au.id.micolous.metrodroid.transit.TransitRegion
import au.id.micolous.metrodroid.transit.en1545.*
import au.id.micolous.metrodroid.transit.intercode.IntercodeTransitData
import au.id.micolous.metrodroid.util.ImmutableByteArray
@Parcelize
class OpusTransitData (val capsule: Calypso1545TransitDataCapsule): Calypso1545TransitData(capsule) {
override val cardName: String
get() = NAME
private constructor(card: CalypsoApplication) : this(Calypso1545TransitData.parse(
card, ticketEnvFields, contractListFields, getSerial(card),
{ data, counter, _, _ -> if (counter == null) null else OpusSubscription(data, counter) },
{ data -> OpusTransaction(data) }, null,
// Contracts 2 is a copy of contract list on opus
card.getFile(CalypsoApplication.File.TICKETING_CONTRACTS_1)?.recordList.orEmpty()))
override val lookup get() = OpusLookup
companion object {
// 124 = Canada
private const val OPUS_NETWORK_ID = 0x124001
private const val NAME = "Opus"
private val contractListFields = En1545Repeat(4,
En1545Bitmap(
En1545FixedInteger(En1545TransitData.CONTRACTS_PROVIDER, 8),
En1545FixedInteger(En1545TransitData.CONTRACTS_TARIFF, 16),
En1545FixedInteger(En1545TransitData.CONTRACTS_UNKNOWN_A, 4),
En1545FixedInteger(En1545TransitData.CONTRACTS_POINTER, 5)
)
)
private val CARD_INFO = CardInfo(
imageId = R.drawable.opus_card,
name = OpusTransitData.NAME,
locationId = R.string.location_quebec,
cardType = CardType.ISO7816,
region = TransitRegion.CANADA,
preview = true)
private val ticketEnvFields = En1545Container(
IntercodeTransitData.TICKET_ENV_FIELDS,
En1545Bitmap(
En1545Container(
En1545FixedInteger(En1545TransitData.HOLDER_UNKNOWN_A, 3),
En1545FixedInteger.dateBCD(En1545TransitData.HOLDER_BIRTH_DATE),
En1545FixedInteger(En1545TransitData.HOLDER_UNKNOWN_B, 13),
En1545FixedInteger.date(En1545TransitData.HOLDER_PROFILE),
En1545FixedInteger(En1545TransitData.HOLDER_UNKNOWN_C, 8)
),
// Possibly part of HolderUnknownB or HolderUnknownC
En1545FixedInteger(En1545TransitData.HOLDER_UNKNOWN_D, 8)
)
)
val FACTORY: CalypsoCardTransitFactory = object : CalypsoCardTransitFactory {
override val allCards: List<CardInfo>
get() = listOf(CARD_INFO)
override fun parseTransitIdentity(card: CalypsoApplication) = TransitIdentity(NAME, getSerial(card))
override fun check(tenv: ImmutableByteArray) = try {
OPUS_NETWORK_ID == tenv.getBitsFromBuffer(13, 24)
} catch (e: Exception) {
false
}
override fun parseTransitData(card: CalypsoApplication) = OpusTransitData(card)
override fun getCardInfo(tenv: ImmutableByteArray) = CARD_INFO
}
private fun getSerial(card: CalypsoApplication): String? {
val iccData = card.getFile(CalypsoApplication.File.ICC)?.getRecord(1) ?: return null
if (iccData.byteArrayToLong(16, 4) != 0L) {
return iccData.byteArrayToLong(16, 4).toString()
}
if (iccData.byteArrayToLong(0, 4) != 0L) {
return iccData.byteArrayToLong(0, 4).toString()
}
return null
}
}
}
| gpl-3.0 | 40290b810531e48b1a6cf5b72a820ce3 | 41.709402 | 112 | 0.641785 | 4.546861 | false | false | false | false |
InsideZhou/Instep | dao/src/main/kotlin/instep/dao/sql/dialect/PostgreSQLDialect.kt | 1 | 2090 | package instep.dao.sql.dialect
import instep.Instep
import instep.dao.sql.*
import instep.typeconversion.TypeConversion
import org.postgresql.util.PGobject
import java.sql.Blob
import java.sql.PreparedStatement
import javax.sql.rowset.serial.SerialBlob
open class PostgreSQLDialect : SeparateCommentDialect() {
val typeconvert = Instep.make(TypeConversion::class.java)
class ResultSet(private val rs: java.sql.ResultSet) : AbstractDialect.ResultSet(rs) {
override fun getBlob(columnIndex: Int): Blob? {
val stream = rs.getBinaryStream(columnIndex) ?: return null
return SerialBlob(stream.readBytes())
}
}
override val returningClauseForInsert = "RETURNING *"
override val offsetDateTimeSupported: Boolean = false
override fun definitionForAutoIncrementColumn(column: IntegerColumn): String = when (column.type) {
IntegerColumnType.Long -> "BIGSERIAL"
else -> "SERIAL"
}
override val defaultValueForInsert = "DEFAULT"
override fun definitionForUUIDColumn(column: StringColumn): String = "UUID"
override fun definitionForJSONColumn(column: StringColumn): String = "JSONB"
override fun definitionForBinaryColumn(column: BinaryColumn): String = "BYTEA"
override fun setParameterForPreparedStatement(stmt: PreparedStatement, index: Int, value: Any?) {
value?.let {
typeconvert.getConverter(value.javaClass, PGobject::class.java)?.let { converter ->
stmt.setObject(index, converter.convert(value))
return
}
}
super.setParameterForPreparedStatement(stmt, index, value)
}
override fun placeholderForParameter(column: Column<*>): String {
when (column) {
is StringColumn -> {
when (column.type) {
StringColumnType.JSON -> return "?::JSONB"
StringColumnType.UUID -> return "?::UUID"
else -> Unit
}
}
}
return super.placeholderForParameter(column)
}
} | bsd-2-clause | 4278b52c8d993082c92c566b2b5de2c9 | 32.725806 | 103 | 0.661722 | 4.717833 | false | false | false | false |
Major-/Vicis | legacy/src/main/kotlin/rs/emulate/legacy/archive/Archive.kt | 1 | 1170 | package rs.emulate.legacy.archive
import java.io.FileNotFoundException
/**
* An archive in the RuneScape cache. An archive is a set of files that can be completely compressed, or each
* individual file can be compressed.
*/
class Archive(val entries: List<ArchiveEntry>) {
val size: Int
get() = entries.sumBy(ArchiveEntry::size)
operator fun get(name: String): ArchiveEntry {
return getOrNull(name) ?: throw FileNotFoundException("Missing entry $name")
}
fun getOrNull(name: String): ArchiveEntry? {
val hash = name.entryHash()
return entries.firstOrNull { it.identifier == hash }
}
override fun equals(other: Any?): Boolean {
return entries == (other as? Archive)?.entries
}
override fun hashCode(): Int {
return entries.hashCode()
}
companion object {
/**
* Hashes an [ArchiveEntry] name into an integer to be used as an identifier.
*/
fun String.entryHash(): Int {
return toUpperCase().fold(0) { hash, character -> hash * 61 + character.toInt() - 32 }
}
val EMPTY_ARCHIVE = Archive(emptyList())
}
}
| isc | 8136551932aa1dbd5f900a55f3e0c9d1 | 26.209302 | 109 | 0.630769 | 4.398496 | false | false | false | false |
hermantai/samples | kotlin/Mastering-Kotlin-master/Chapter11/src/pizza/Order.kt | 1 | 985 | package pizza
import java.util.*
fun order(init: Order.() -> Unit): Order {
val order = Order(UUID.randomUUID().toString())
order.init()
return order
}
class Order(val id: String) : Item("") {
val items: MutableMap<Item, Int> = mutableMapOf()
fun pizza(init: Pizza.() -> Unit) {
val pizza = BuildYourOwn()
pizza.init()
items[pizza] = 1
}
fun soda(soda: Soda) = items.put(soda, items.getOrDefault(soda, 0) + 1)
infix fun Soda.quantity(quantity: Int) {
[email protected](this, [email protected](this, 0) + quantity)
}
operator fun Soda.unaryPlus() = [email protected](this)
operator fun Pizza.unaryPlus() {
[email protected](this, [email protected](this, 0) + 1)
}
override fun log(indent: String) {
println("Order: $id")
println("Items")
items.forEach {
print("${it.value} x ")
it.key.log()
}
}
} | apache-2.0 | 95e07a237f26462ca2d49d7f91c140e2 | 23.65 | 85 | 0.583756 | 3.45614 | false | false | false | false |
android/nowinandroid | core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/icon/NiaIcons.kt | 1 | 3627 | /*
* 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
*
* 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.google.samples.apps.nowinandroid.core.designsystem.icon
import androidx.annotation.DrawableRes
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.outlined.AccountCircle
import androidx.compose.material.icons.rounded.Add
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.material.icons.rounded.ArrowDropDown
import androidx.compose.material.icons.rounded.ArrowDropUp
import androidx.compose.material.icons.rounded.Check
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.ExpandLess
import androidx.compose.material.icons.rounded.Fullscreen
import androidx.compose.material.icons.rounded.Grid3x3
import androidx.compose.material.icons.rounded.Person
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material.icons.rounded.Settings
import androidx.compose.material.icons.rounded.ShortText
import androidx.compose.material.icons.rounded.Tag
import androidx.compose.material.icons.rounded.ViewDay
import androidx.compose.material.icons.rounded.VolumeOff
import androidx.compose.material.icons.rounded.VolumeUp
import androidx.compose.ui.graphics.vector.ImageVector
import com.google.samples.apps.nowinandroid.core.designsystem.R
/**
* Now in Android icons. Material icons are [ImageVector]s, custom icons are drawable resource IDs.
*/
object NiaIcons {
val AccountCircle = Icons.Outlined.AccountCircle
val Add = Icons.Rounded.Add
val ArrowBack = Icons.Rounded.ArrowBack
val ArrowDropDown = Icons.Rounded.ArrowDropDown
val ArrowDropUp = Icons.Rounded.ArrowDropUp
val Bookmark = R.drawable.ic_bookmark
val BookmarkBorder = R.drawable.ic_bookmark_border
val Bookmarks = R.drawable.ic_bookmarks
val BookmarksBorder = R.drawable.ic_bookmarks_border
val Check = Icons.Rounded.Check
val Close = Icons.Rounded.Close
val ExpandLess = Icons.Rounded.ExpandLess
val Fullscreen = Icons.Rounded.Fullscreen
val Grid3x3 = Icons.Rounded.Grid3x3
val MenuBook = R.drawable.ic_menu_book
val MenuBookBorder = R.drawable.ic_menu_book_border
val MoreVert = Icons.Default.MoreVert
val Person = Icons.Rounded.Person
val PlayArrow = Icons.Rounded.PlayArrow
val Search = Icons.Rounded.Search
val Settings = Icons.Rounded.Settings
val ShortText = Icons.Rounded.ShortText
val Tag = Icons.Rounded.Tag
val Upcoming = R.drawable.ic_upcoming
val UpcomingBorder = R.drawable.ic_upcoming_border
val ViewDay = Icons.Rounded.ViewDay
val VolumeOff = Icons.Rounded.VolumeOff
val VolumeUp = Icons.Rounded.VolumeUp
}
/**
* A sealed class to make dealing with [ImageVector] and [DrawableRes] icons easier.
*/
sealed class Icon {
data class ImageVectorIcon(val imageVector: ImageVector) : Icon()
data class DrawableResourceIcon(@DrawableRes val id: Int) : Icon()
}
| apache-2.0 | fa6f491528ae8b785cd91f179bdbd6b1 | 42.178571 | 99 | 0.78853 | 4.066143 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/common/job/FixedDailyJob.kt | 1 | 2365 | package io.ipoli.android.common.job
import com.crashlytics.android.Crashlytics
import com.evernote.android.job.Job
import com.evernote.android.job.JobRequest
import com.evernote.android.job.util.support.PersistableBundleCompat
import io.ipoli.android.BuildConfig
import io.ipoli.android.common.datetime.Time
import io.ipoli.android.common.datetime.toMillis
import org.threeten.bp.LocalDate
import org.threeten.bp.LocalDateTime
import org.threeten.bp.LocalTime
import timber.log.Timber
abstract class FixedDailyJob(private val tag: String) : Job() {
override fun onRunJob(params: Params): Result {
try {
doRunJob(params)
} catch (e: Throwable) {
if (BuildConfig.DEBUG) {
Timber.e(e)
} else {
Crashlytics.logException(e)
}
}
val scheduleAt = Time.of(params.extras.getInt("minuteOfDay", -1))
val nextSchedule = LocalDateTime.of(
LocalDate.now().plusDays(1),
LocalTime.of(scheduleAt.hours, scheduleAt.getMinutes())
).toMillis()
JobRequest.Builder(tag)
.setUpdateCurrent(true)
.setExtras(PersistableBundleCompat().apply {
putInt("minuteOfDay", scheduleAt.toMinuteOfDay())
})
.setExact(nextSchedule - System.currentTimeMillis())
.build()
.schedule()
return Result.SUCCESS
}
abstract fun doRunJob(params: Params): Result
}
object FixedDailyJobScheduler {
fun schedule(tag: String, scheduleAt: Time) {
val nextScheduled = if (scheduleAt <= Time.now()) {
LocalDateTime.of(
LocalDate.now().plusDays(1),
LocalTime.of(scheduleAt.hours, scheduleAt.getMinutes())
).toMillis()
} else {
LocalDateTime.of(
LocalDate.now(),
LocalTime.of(scheduleAt.hours, scheduleAt.getMinutes())
).toMillis()
}
val scheduleMillis = nextScheduled - System.currentTimeMillis()
JobRequest.Builder(tag)
.setUpdateCurrent(true)
.setExtras(PersistableBundleCompat().apply {
putInt("minuteOfDay", scheduleAt.toMinuteOfDay())
})
.setExact(scheduleMillis)
.build()
.schedule()
}
} | gpl-3.0 | 3c202bd58a6c1a69b3a36227581e2b94 | 30.131579 | 73 | 0.611839 | 4.610136 | false | false | false | false |
JetBrains/teamcity-nuget-support | nuget-feed/src/jetbrains/buildServer/nuget/feed/server/json/JsonServiceIndexHandler.kt | 1 | 1175 | package jetbrains.buildServer.nuget.feed.server.json
import jetbrains.buildServer.nuget.feed.server.controllers.NuGetFeedHandler
import jetbrains.buildServer.nuget.feed.server.index.NuGetFeedData
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
class JsonServiceIndexHandler : NuGetFeedHandler {
override fun handleRequest(feedData: NuGetFeedData, request: HttpServletRequest, response: HttpServletResponse) {
if (request.pathInfo != "/index.json") {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Requested resource not found")
return
}
val feedPathV3 = request.servletPath
val feedPathV2 = feedPathV3.replaceAfterLast("/", "v2")
val rootUrl = request.getRootUrl()
val responseText = JsonServiceIndexHandler::class.java.getResourceAsStream("/feed-metadata/NuGet-V3.json").use {
it.bufferedReader().readText()
}
response.status = HttpServletResponse.SC_OK
response.contentType = "application/json;charset=UTF-8"
response.writer.printf(responseText, rootUrl + feedPathV3, rootUrl + feedPathV2)
}
}
| apache-2.0 | 75d50e544742df445aabd857f28b1f4c | 42.518519 | 120 | 0.732766 | 4.351852 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/player/attribute/AttributeRank.kt | 1 | 747 | package io.ipoli.android.player.attribute
import io.ipoli.android.player.data.Player
object AttributeRank {
fun of(attributeLevel: Int, playerRank: Player.Rank) =
Player.Rank.values().reversed().firstOrNull { status ->
val index = Player.Rank.values().indexOf(status)
if (index == 0)
false
else if (attributeLevel == 100 && playerRank == Player.Rank.DIVINITY) {
true
} else {
val prevStatus = Player.Rank.values()[index - 1]
val curStatus = Player.Rank.values()[index]
attributeLevel >= index * 10 && (playerRank == curStatus || playerRank == prevStatus)
}
} ?: Player.Rank.NOVICE
} | gpl-3.0 | 8cda82a3e915514379403f344837ff52 | 33 | 101 | 0.57162 | 4.368421 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/framework/KotlinLibraryUtil.kt | 4 | 1194 | // 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.framework
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.libraries.Library
import org.jetbrains.kotlin.idea.configuration.GRADLE_SYSTEM_ID
val MAVEN_SYSTEM_ID = ProjectSystemId("Maven")
@Deprecated(
"Moved to the org.jetbrains.kotlin.idea.configuration package.",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith("org.jetbrains.kotlin.idea.configuration.GRADLE_SYSTEM_ID")
)
val GRADLE_SYSTEM_ID: ProjectSystemId
get() = org.jetbrains.kotlin.idea.configuration.GRADLE_SYSTEM_ID
@Deprecated(
"Moved to the 'org.jetbrains.kotlin.idea.base.util' package.",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith("org.jetbrains.kotlin.idea.base.util.isGradleModule()")
)
fun Module.isGradleModule(): Boolean {
return ExternalSystemApiUtil.isExternalSystemAwareModule(GRADLE_SYSTEM_ID, this)
} | apache-2.0 | faa35cad17fca717f45e4f8b989fb3dc | 41.678571 | 158 | 0.79397 | 4.117241 | false | true | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/OoParentWithPidEntityImpl.kt | 2 | 11087 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.SymbolicEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class OoParentWithPidEntityImpl(val dataSource: OoParentWithPidEntityData) : OoParentWithPidEntity, WorkspaceEntityBase() {
companion object {
internal val CHILDONE_CONNECTION_ID: ConnectionId = ConnectionId.create(OoParentWithPidEntity::class.java,
OoChildForParentWithPidEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
internal val CHILDTHREE_CONNECTION_ID: ConnectionId = ConnectionId.create(OoParentWithPidEntity::class.java,
OoChildAlsoWithPidEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
CHILDONE_CONNECTION_ID,
CHILDTHREE_CONNECTION_ID,
)
}
override val parentProperty: String
get() = dataSource.parentProperty
override val childOne: OoChildForParentWithPidEntity?
get() = snapshot.extractOneToOneChild(CHILDONE_CONNECTION_ID, this)
override val childThree: OoChildAlsoWithPidEntity?
get() = snapshot.extractOneToOneChild(CHILDTHREE_CONNECTION_ID, this)
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: OoParentWithPidEntityData?) : ModifiableWorkspaceEntityBase<OoParentWithPidEntity, OoParentWithPidEntityData>(
result), OoParentWithPidEntity.Builder {
constructor() : this(OoParentWithPidEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity OoParentWithPidEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isParentPropertyInitialized()) {
error("Field OoParentWithPidEntity#parentProperty should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as OoParentWithPidEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.parentProperty != dataSource.parentProperty) this.parentProperty = dataSource.parentProperty
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var parentProperty: String
get() = getEntityData().parentProperty
set(value) {
checkModificationAllowed()
getEntityData(true).parentProperty = value
changedProperty.add("parentProperty")
}
override var childOne: OoChildForParentWithPidEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(CHILDONE_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
CHILDONE_CONNECTION_ID)] as? OoChildForParentWithPidEntity
}
else {
this.entityLinks[EntityLink(true, CHILDONE_CONNECTION_ID)] as? OoChildForParentWithPidEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, CHILDONE_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(CHILDONE_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, CHILDONE_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, CHILDONE_CONNECTION_ID)] = value
}
changedProperty.add("childOne")
}
override var childThree: OoChildAlsoWithPidEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(CHILDTHREE_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
CHILDTHREE_CONNECTION_ID)] as? OoChildAlsoWithPidEntity
}
else {
this.entityLinks[EntityLink(true, CHILDTHREE_CONNECTION_ID)] as? OoChildAlsoWithPidEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, CHILDTHREE_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(CHILDTHREE_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, CHILDTHREE_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, CHILDTHREE_CONNECTION_ID)] = value
}
changedProperty.add("childThree")
}
override fun getEntityClass(): Class<OoParentWithPidEntity> = OoParentWithPidEntity::class.java
}
}
class OoParentWithPidEntityData : WorkspaceEntityData.WithCalculableSymbolicId<OoParentWithPidEntity>() {
lateinit var parentProperty: String
fun isParentPropertyInitialized(): Boolean = ::parentProperty.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<OoParentWithPidEntity> {
val modifiable = OoParentWithPidEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): OoParentWithPidEntity {
return getCached(snapshot) {
val entity = OoParentWithPidEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun symbolicId(): SymbolicEntityId<*> {
return OoParentEntityId(parentProperty)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return OoParentWithPidEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return OoParentWithPidEntity(parentProperty, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as OoParentWithPidEntityData
if (this.entitySource != other.entitySource) return false
if (this.parentProperty != other.parentProperty) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as OoParentWithPidEntityData
if (this.parentProperty != other.parentProperty) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + parentProperty.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + parentProperty.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 92cc2766423ad0ae8df1532a14fe3e43 | 38.038732 | 156 | 0.683593 | 5.510437 | false | false | false | false |
ftomassetti/kolasu | emf/src/main/kotlin/com/strumenta/kolasu/emf/cli/EMFCLICommands.kt | 1 | 3912 | package com.strumenta.kolasu.emf.cli
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.options.default
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.help
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.types.file
import com.strumenta.kolasu.cli.ASTProcessingCommand
import com.strumenta.kolasu.cli.ParserInstantiator
import com.strumenta.kolasu.cli.changeExtension
import com.strumenta.kolasu.emf.*
import com.strumenta.kolasu.model.Node
import com.strumenta.kolasu.parsing.ParsingResult
import org.eclipse.emf.common.util.URI
import org.eclipse.emf.ecore.resource.Resource
import java.io.File
class EMFModelCommand<R : Node, P>(parserInstantiator: ParserInstantiator<P>) :
ASTProcessingCommand<R, P>(
parserInstantiator,
help = "Parses a file and exports the AST to an EMF (XMI) file.",
name = "model"
) where P : EMFEnabledParser<R, *, *> {
val metamodel by option("--metamodel")
val outputDirectory by option("--output", "-o")
.file()
.help("Directory where to store the output. By default the current directory is used.")
.default(File("."))
val includeMetamodel by option("--include-metamodel", "-imm")
.help("Include metamodel in each saved model.")
.flag(default = false)
override fun finalizeRun() {
// Nothing to do
}
override fun processException(input: File, relativePath: String, e: Exception) {
// Nothing to do
}
override fun processResult(input: File, relativePath: String, result: ParsingResult<R>, parser: P) {
val targetFile = File(this.outputDirectory.absolutePath + File.separator + relativePath)
.changeExtension("json")
val targetFileParent = targetFile.parentFile
targetFileParent.absoluteFile.mkdirs()
val mmFile = File("metamodel.json")
val resource = saveMetamodel(parser, mmFile)
val start = System.currentTimeMillis()
if (verbose) {
echo("Saving AST for $input to $targetFile... ")
}
result.saveModel(resource, URI.createFileURI(targetFile.path), includeMetamodel = includeMetamodel)
if (verbose) {
echo("Done (${System.currentTimeMillis() - start}ms).")
}
}
private fun saveMetamodel(parser: EMFMetamodelSupport, target: File): Resource {
val start = System.currentTimeMillis()
val metamodel = if (this.metamodel != null) {
File(this.metamodel!!)
} else {
File(target.parentFile, "metamodel." + (target.path.substring(target.path.lastIndexOf(".") + 1)))
}.absolutePath
if (verbose) {
echo("Saving metamodel to $metamodel... ")
}
val mmResource = parser.saveMetamodel(URI.createFileURI(target.path))
if (verbose) {
echo("Done (${System.currentTimeMillis() - start}ms).")
}
return mmResource
}
}
class EMFMetaModelCommand(val metamodelSupport: EMFMetamodelSupport) :
CliktCommand(
help = "Generate the metamodel for a language.",
name = "metamodel"
) {
val verbose by option("--verbose", "-v")
.help("Print additional messages")
.flag(default = false)
val output by option("--output", "-o")
.file()
.help("File where to store the metamodel")
.default(File("metamodel.json"))
val includeKolasu by option("--include-kolasu", "-ik").flag(default = false)
override fun run() {
val mmResource = createResource(URI.createFileURI(output.path))!!
metamodelSupport.generateMetamodel(mmResource, includeKolasu)
mmResource.save(emptyMap<Any, Any>())
if (verbose) {
echo("Metamodel saved to ${output.absolutePath}")
}
}
}
| apache-2.0 | 4b20f6de204d3f5973e9e67ae6588b7d | 37.732673 | 109 | 0.662577 | 4.188437 | false | false | false | false |
adwabh/DragCart | app/src/main/java/com/adwait/widget/dragcart/activities/MainActivity.kt | 1 | 1245 | package com.adwait.widget.dragcart.activities
import android.opengl.Visibility
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.TextView
import com.adwait.widget.dragcart.R
import com.adwait.widget.dragcart.fragments.SampleListFragment
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private var count: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView_cart_count.text = "1"
setUpFragment(floatingActionButton,textView_cart_count)
}
private fun setUpFragment(anchor: View, textView_cart_count: TextView) {
var transaction = supportFragmentManager?.beginTransaction()
with(transaction){
var fragment = SampleListFragment.newInstance().apply {
callback = { [email protected] += 1; textView_cart_count.text = [email protected]()} }
fragment.count = count_layout
fragment.anchor = anchor
this?.replace(R.id.fragment_container,fragment)
this?.commit()
}
}
}
| apache-2.0 | 1bc8b7ea7bc10fd04e29f35ae99d77a4 | 31.763158 | 123 | 0.711647 | 4.446429 | false | false | false | false |
ktorio/ktor | ktor-network/jvm/src/io/ktor/network/util/Utils.kt | 1 | 2341 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.network.util
import io.ktor.util.date.*
import io.ktor.utils.io.concurrent.*
import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import kotlin.contracts.*
/**
* Infinite timeout in milliseconds.
*/
internal const val INFINITE_TIMEOUT_MS = Long.MAX_VALUE
internal class Timeout(
private val name: String,
private val timeoutMs: Long,
private val clock: () -> Long,
private val scope: CoroutineScope,
private val onTimeout: suspend () -> Unit
) {
private val lastActivityTime = atomic(0L)
private val isStarted = atomic(false)
private var workerJob = initTimeoutJob()
fun start() {
lastActivityTime.value = clock()
isStarted.value = true
}
fun stop() {
isStarted.value = false
}
fun finish() {
workerJob?.cancel()
}
private fun initTimeoutJob(): Job? {
if (timeoutMs == INFINITE_TIMEOUT_MS) return null
return scope.launch(scope.coroutineContext + CoroutineName("Timeout $name")) {
try {
while (true) {
if (!isStarted.value) {
lastActivityTime.value = clock()
}
val remaining = lastActivityTime.value + timeoutMs - clock()
if (remaining <= 0 && isStarted.value) {
break
}
delay(remaining)
}
yield()
onTimeout()
} catch (cause: Throwable) {
// no op
}
}
}
}
/**
* Starts timeout coroutine that will invoke [onTimeout] after [timeoutMs] of inactivity.
* Use [Timeout] object to wrap code that can timeout or cancel this coroutine
*/
internal fun CoroutineScope.createTimeout(
name: String = "",
timeoutMs: Long,
clock: () -> Long = { getTimeMillis() },
onTimeout: suspend () -> Unit
): Timeout {
return Timeout(name, timeoutMs, clock, this, onTimeout)
}
internal inline fun <T> Timeout?.withTimeout(block: () -> T): T {
if (this == null) {
return block()
}
start()
return try {
block()
} finally {
stop()
}
}
| apache-2.0 | 8ce0d3d5c3f6bf9013d1191ccb82eb13 | 24.445652 | 119 | 0.570269 | 4.467557 | false | false | false | false |
marius-m/wt4 | app/src/main/java/lt/markmerkk/ui_2/views/ContextMenuTicketSelect.kt | 1 | 3917 | package lt.markmerkk.ui_2.views
import com.google.common.eventbus.EventBus
import com.jfoenix.svg.SVGGlyph
import com.vdurmont.emoji.EmojiParser
import javafx.scene.control.ContextMenu
import javafx.scene.control.MenuItem
import javafx.scene.paint.Color
import lt.markmerkk.*
import lt.markmerkk.entities.TicketCode
import lt.markmerkk.events.EventSnackBarMessage
import lt.markmerkk.mvp.HostServicesInteractor
import lt.markmerkk.utils.AccountAvailablility
import lt.markmerkk.utils.JiraLinkGenerator
import lt.markmerkk.utils.JiraLinkGeneratorBasic
import lt.markmerkk.utils.JiraLinkGeneratorOAuth
import lt.markmerkk.widgets.tickets.TicketViewModel
import org.slf4j.LoggerFactory
import rx.Observable
import rx.Subscription
class ContextMenuTicketSelect(
private val graphics: Graphics<SVGGlyph>,
private val eventBus: WTEventBus,
private val hostServicesInteractor: HostServicesInteractor,
private val accountAvailablility: AccountAvailablility
) {
private val jiraLinkGenerator = if (BuildConfig.oauth) {
JiraLinkGeneratorOAuth(view = null, accountAvailability = accountAvailablility)
} else {
JiraLinkGeneratorBasic(view = null, accountAvailablility = accountAvailablility)
}
private var subsTicketSelect: Subscription? = null
fun onAttach() {}
fun onDetach() {
subsTicketSelect?.unsubscribe()
}
fun attachTicketSelection(ticketCodeSelectAsStream: Observable<String?>) {
ticketCodeSelectAsStream
.filter { it != null }
.subscribe({
if (it != null) {
bindCodes(listOf(it))
} else {
bindCodes(emptyList())
}
}, { error ->
logger.warn("Error subscribing to ticket code selection stream", error)
})
}
val root: ContextMenu = ContextMenu()
.apply {
items.addAll(
MenuItem(
"Copy web-link",
graphics.from(Glyph.LINK, Color.BLACK, 14.0, 16.0)
).apply { id = SelectType.WEB_LINK.name },
MenuItem(
"Open in browser",
graphics.from(Glyph.NEW, Color.BLACK, 16.0, 16.0)
).apply { id = SelectType.BROWSER.name }
)
setOnAction { event ->
val selectType = SelectType.valueOf((event.target as MenuItem).id)
val ticketCode = TicketCode.new(selectedCodes.firstOrNull() ?: "")
if (!ticketCode.isEmpty()) {
when (selectType) {
SelectType.WEB_LINK -> {
val webLinkToTicket = jiraLinkGenerator.webLinkFromInput(ticketCode.code)
val message = EmojiParser.parseToUnicode("Copied $webLinkToTicket :rocket:")
eventBus.post(EventSnackBarMessage(message))
hostServicesInteractor.ticketWebLinkToClipboard(webLinkToTicket)
}
SelectType.BROWSER -> {
val webLinkToTicket = jiraLinkGenerator.webLinkFromInput(ticketCode.code)
hostServicesInteractor.openLink(webLinkToTicket)
}
}
}
}
}
private var selectedCodes = emptyList<String>()
fun bindCodes(codes: List<String>) {
selectedCodes = codes
}
private enum class SelectType {
WEB_LINK,
BROWSER,
;
}
companion object {
val logger = LoggerFactory.getLogger(Tags.INTERNAL)!!
}
} | apache-2.0 | cdb78f3a9d425711f9aff771802900f1 | 37.038835 | 108 | 0.572887 | 5.174373 | false | false | false | false |
ktorio/ktor | ktor-utils/common/src/io/ktor/util/Text.kt | 1 | 3172 | /*
* 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.util
/**
* Escapes the characters in a String using HTML entities
*/
public fun String.escapeHTML(): String {
val text = this@escapeHTML
if (text.isEmpty()) return text
return buildString(length) {
for (idx in 0 until text.length) {
val ch = text[idx]
when (ch) {
'\'' -> append("'")
'\"' -> append(""")
'&' -> append("&")
'<' -> append("<")
'>' -> append(">")
else -> append(ch)
}
}
}
}
/**
* Splits the given string into two parts before and after separator.
*
* Useful together with destructuring declarations
*/
public inline fun String.chomp(
separator: String,
onMissingDelimiter: () -> Pair<String, String>
): Pair<String, String> {
val idx = indexOf(separator)
return when (idx) {
-1 -> onMissingDelimiter()
else -> substring(0, idx) to substring(idx + 1)
}
}
/**
* Does the same as the regular [toLowerCase] except that locale-specific rules are not applied to ASCII characters
* so latin characters are converted by the original english rules.
*/
public fun String.toLowerCasePreservingASCIIRules(): String {
val firstIndex = indexOfFirst {
toLowerCasePreservingASCII(it) != it
}
if (firstIndex == -1) {
return this
}
val original = this
return buildString(length) {
append(original, 0, firstIndex)
for (index in firstIndex..original.lastIndex) {
append(toLowerCasePreservingASCII(original[index]))
}
}
}
/**
* Does the same as the regular [toUpperCase] except that locale-specific rules are not applied to ASCII characters
* so latin characters are converted by the original english rules.
*/
public fun String.toUpperCasePreservingASCIIRules(): String {
val firstIndex = indexOfFirst {
toUpperCasePreservingASCII(it) != it
}
if (firstIndex == -1) {
return this
}
val original = this
return buildString(length) {
append(original, 0, firstIndex)
for (index in firstIndex..original.lastIndex) {
append(toUpperCasePreservingASCII(original[index]))
}
}
}
private fun toLowerCasePreservingASCII(ch: Char): Char = when (ch) {
in 'A'..'Z' -> ch + 32
in '\u0000'..'\u007f' -> ch
else -> ch.lowercaseChar()
}
private fun toUpperCasePreservingASCII(ch: Char): Char = when (ch) {
in 'a'..'z' -> ch - 32
in '\u0000'..'\u007f' -> ch
else -> ch.lowercaseChar()
}
internal fun String.caseInsensitive(): CaseInsensitiveString = CaseInsensitiveString(this)
internal class CaseInsensitiveString(val content: String) {
private val hash = content.lowercase().hashCode()
override fun equals(other: Any?): Boolean =
(other as? CaseInsensitiveString)?.content?.equals(content, ignoreCase = true) == true
override fun hashCode(): Int = hash
override fun toString(): String = content
}
| apache-2.0 | 5a171ecb21389c945fa4a8b308a0fdf4 | 26.824561 | 118 | 0.623897 | 4.263441 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/library/ChangeMangaCategoriesDialog.kt | 2 | 3507 | package eu.kanade.tachiyomi.ui.library
import android.app.Dialog
import android.os.Bundle
import com.bluelinelabs.conductor.Controller
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Category
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.ui.base.controller.DialogController
import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction
import eu.kanade.tachiyomi.ui.category.CategoryController
import eu.kanade.tachiyomi.widget.materialdialogs.QuadStateTextView
import eu.kanade.tachiyomi.widget.materialdialogs.setQuadStateMultiChoiceItems
class ChangeMangaCategoriesDialog<T>(bundle: Bundle? = null) :
DialogController(bundle) where T : Controller, T : ChangeMangaCategoriesDialog.Listener {
private var mangas = emptyList<Manga>()
private var categories = emptyList<Category>()
private var preselected = emptyArray<Int>()
private var selected = emptyArray<Int>().toIntArray()
constructor(
target: T,
mangas: List<Manga>,
categories: List<Category>,
preselected: Array<Int>
) : this() {
this.mangas = mangas
this.categories = categories
this.preselected = preselected
this.selected = preselected.toIntArray()
targetController = target
}
override fun onCreateDialog(savedViewState: Bundle?): Dialog {
return MaterialAlertDialogBuilder(activity!!)
.setTitle(R.string.action_move_category)
.setNegativeButton(android.R.string.cancel, null)
.apply {
if (categories.isNotEmpty()) {
setQuadStateMultiChoiceItems(
items = categories.map { it.name },
isActionList = false,
initialSelected = preselected.toIntArray()
) { selections ->
selected = selections
}
setPositiveButton(android.R.string.ok) { _, _ ->
val add = selected
.mapIndexed { index, value -> if (value == QuadStateTextView.State.CHECKED.ordinal) categories[index] else null }
.filterNotNull()
val remove = selected
.mapIndexed { index, value -> if (value == QuadStateTextView.State.UNCHECKED.ordinal) categories[index] else null }
.filterNotNull()
(targetController as? Listener)?.updateCategoriesForMangas(mangas, add, remove)
}
} else {
setMessage(R.string.information_empty_category_dialog)
setPositiveButton(R.string.action_edit_categories) { _, _ ->
if (targetController is LibraryController) {
val libController = targetController as LibraryController
libController.clearSelection()
}
router.popCurrentController()
router.pushController(CategoryController().withFadeTransaction())
}
}
}
.create()
}
interface Listener {
fun updateCategoriesForMangas(mangas: List<Manga>, addCategories: List<Category>, removeCategories: List<Category> = emptyList<Category>())
}
}
| apache-2.0 | 29dc099a7ba941bf85a2639b48ff3360 | 44.545455 | 147 | 0.610778 | 5.378834 | false | false | false | false |
emanuelpalm/palm-compute | android/src/main/java/se/ltu/emapal/compute/client/android/ActivityMain.kt | 1 | 6301 | package se.ltu.emapal.compute.client.android
import android.os.AsyncTask
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import rx.android.schedulers.AndroidSchedulers
import se.ltu.emapal.compute.Computer
import se.ltu.emapal.compute.client.android.view.ViewConnector
import se.ltu.emapal.compute.io.ComputeClientStatus
import se.ltu.emapal.compute.util.Result
import java.net.ConnectException
import java.net.SocketException
import java.net.SocketTimeoutException
import java.util.concurrent.atomic.AtomicReference
class ActivityMain : AppCompatActivity() {
val computer = AtomicReference<Computer?>(null)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
view_connector.listener?.let {
it.whenConnect.subscribe { addressPair ->
val address = addressPair.first
val port = addressPair.second
view_connector.setState(ViewConnector.State.SHOW_CONNECTING)
startComputer(address, port)
}
it.whenDisconnect.subscribe { addressPair ->
showSnackbar(R.string.text_disconnected_from_ss, addressPair.first, addressPair.second)
view_connector.setState(ViewConnector.State.SHOW_CONNECT)
view_status.visibility = View.GONE
stopComputer()
}
}
}
private fun showSnackbar(resourceId: Int, vararg parameters: Any) {
Snackbar.make(view_connector, getString(resourceId, *parameters), Snackbar.LENGTH_LONG)
.show()
}
private fun startComputer(address: String, port: String) {
AsyncTaskCreateComputer({ result ->
when (result) {
is Result.Success -> {
showSnackbar(R.string.text_connected_to_ss, address, port)
computer.set(result.value)
val computer = result.value
computer.whenLambdaCount
.observeOn(AndroidSchedulers.mainThread())
.subscribe { view_status.lambdaCount = it }
computer.whenBatchPendingCount
.observeOn(AndroidSchedulers.mainThread())
.subscribe { view_status.pendingBatchCount = it }
computer.whenBatchProcessedCount
.observeOn(AndroidSchedulers.mainThread())
.subscribe { view_status.processedBatchCount = it }
computer.whenException
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
Log.e(javaClass.simpleName, "Compute context ${it.first} error.", it.second)
stopComputer()
}
computer.client.whenException
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
Log.e(javaClass.simpleName, "Compute client error.", it)
stopComputer()
}
computer.client.whenStatus
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
when (it) {
ComputeClientStatus.DISRUPTED -> {
showSnackbar(R.string.text_connection_lost_to_ss, address, port)
Log.w(javaClass.simpleName, "Compute client disrupted.")
view_status.visibility = View.GONE
view_connector.setState(ViewConnector.State.SHOW_CONNECT)
}
ComputeClientStatus.TERMINATED -> {
showSnackbar(R.string.text_connection_closed_by_ss, address, port)
view_status.visibility = View.GONE
view_connector.setState(ViewConnector.State.SHOW_CONNECT)
}
else -> Unit
}
}
view_connector.setState(ViewConnector.State.SHOW_DISCONNECT)
view_status.alpha = 0.0f
view_status.visibility = View.VISIBLE
view_status.animate()
.alpha(1.0f)
.setStartDelay(800)
.setDuration(156)
.start()
}
is Result.Failure -> {
val resource = when (result.error) {
is IllegalArgumentException -> R.string.text_error_address
is ConnectException -> R.string.text_error_failed_to_connect_to_ss
is SocketTimeoutException -> R.string.text_error_timed_out_connecting_to_ss
is SocketException -> {
Log.w(javaClass.simpleName, "Failed to connect to service.", result.error)
R.string.text_error_failed_to_connect_to_ss
}
else -> {
Log.e(javaClass.simpleName, "Failed to connect to service.", result.error)
R.string.text_error_failed_to_connect_to_ss
}
}
showSnackbar(resource, address, port)
view_connector.setState(ViewConnector.State.SHOW_CONNECT)
}
}
}).execute(address, port)
}
fun stopComputer() {
AsyncTask.execute {
computer.get()?.let {
it.close()
it.client.close()
}
}
}
}
| mit | 2336d8358e48d4df3f68fabd1fae0999 | 42.157534 | 108 | 0.512141 | 5.641003 | false | false | false | false |
cfieber/orca | orca-core/src/main/java/com/netflix/spinnaker/orca/pipeline/model/JenkinsTrigger.kt | 1 | 2738 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.pipeline.model
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonProperty
import com.netflix.spinnaker.kork.artifacts.model.Artifact
import com.netflix.spinnaker.kork.artifacts.model.ExpectedArtifact
data class JenkinsTrigger
@JvmOverloads constructor(
override val type: String = "jenkins",
override val correlationId: String? = null,
override val user: String? = "[anonymous]",
override val parameters: Map<String, Any> = mutableMapOf(),
override val artifacts: List<Artifact> = mutableListOf(),
override val notifications: List<Map<String, Any>> = mutableListOf(),
override var isRebake: Boolean = false,
override var isDryRun: Boolean = false,
override var isStrategy: Boolean = false,
val master: String,
val job: String,
val buildNumber: Int,
val propertyFile: String?
) : Trigger {
override var other: Map<String, Any> = mutableMapOf()
override var resolvedExpectedArtifacts: List<ExpectedArtifact> = mutableListOf()
var buildInfo: BuildInfo? = null
var properties: Map<String, Any> = mutableMapOf()
data class BuildInfo
@JsonCreator constructor(
@param:JsonProperty("name") val name: String,
@param:JsonProperty("number") val number: Int,
@param:JsonProperty("url") val url: String,
@JsonProperty("artifacts") val artifacts: List<JenkinsArtifact>? = emptyList(),
@JsonProperty("scm") val scm: List<SourceControl>? = emptyList(),
@param:JsonProperty("building") val isBuilding: Boolean,
@param:JsonProperty("result") val result: String?
) {
@get:JsonIgnore
val fullDisplayName: String
get() = name + " #" + number
}
data class SourceControl
@JsonCreator constructor(
@param:JsonProperty("name") val name: String,
@param:JsonProperty("branch") val branch: String,
@param:JsonProperty("sha1") val sha1: String
)
data class JenkinsArtifact
@JsonCreator constructor(
@param:JsonProperty("fileName") val fileName: String,
@param:JsonProperty("relativePath") val relativePath: String
)
}
| apache-2.0 | 73554073ecb522a55cfa317c4908242e | 36 | 83 | 0.7374 | 4.258165 | false | false | false | false |
mdanielwork/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/GithubApiRequests.kt | 1 | 14942 | // 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.api
import com.intellij.util.ThrowableConvertor
import org.jetbrains.plugins.github.api.GithubApiRequest.*
import org.jetbrains.plugins.github.api.data.*
import org.jetbrains.plugins.github.api.requests.*
import org.jetbrains.plugins.github.api.util.GithubApiPagesLoader
import org.jetbrains.plugins.github.api.util.GithubApiSearchQueryBuilder
import org.jetbrains.plugins.github.api.util.GithubApiUrlQueryBuilder
import java.awt.Image
/**
* Collection of factory methods for API requests used in plugin
* TODO: improve url building (DSL?)
*/
object GithubApiRequests {
object CurrentUser : Entity("/user") {
@JvmStatic
fun get(server: GithubServerPath) = get(getUrl(server, urlSuffix))
@JvmStatic
fun get(url: String) = Get.json<GithubAuthenticatedUser>(url).withOperationName("get profile information")
@JvmStatic
fun getAvatar(url: String) = object : Get<Image>(url) {
override fun extractResult(response: GithubApiResponse): Image {
return response.handleBody(ThrowableConvertor {
GithubApiContentHelper.loadImage(it)
})
}
}.withOperationName("get profile avatar")
object Repos : Entity("/repos") {
@JvmOverloads
@JvmStatic
fun pages(server: GithubServerPath, allAssociated: Boolean = true, pagination: GithubRequestPagination? = null) =
GithubApiPagesLoader.Request(get(server, allAssociated, pagination), ::get)
@JvmOverloads
@JvmStatic
fun get(server: GithubServerPath, allAssociated: Boolean = true, pagination: GithubRequestPagination? = null) =
get(getUrl(server, CurrentUser.urlSuffix, urlSuffix,
getQuery(if (allAssociated) "" else "type=owner", pagination?.toString().orEmpty())))
@JvmStatic
fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get user repositories")
@JvmStatic
fun create(server: GithubServerPath, name: String, description: String, private: Boolean, autoInit: Boolean? = null) =
Post.json<GithubRepo>(getUrl(server, CurrentUser.urlSuffix, urlSuffix),
GithubRepoRequest(name, description, private, autoInit))
.withOperationName("create user repository")
}
object RepoSubs : Entity("/subscriptions") {
@JvmStatic
fun pages(server: GithubServerPath) = GithubApiPagesLoader.Request(get(server), ::get)
@JvmOverloads
@JvmStatic
fun get(server: GithubServerPath, pagination: GithubRequestPagination? = null) =
get(getUrl(server, CurrentUser.urlSuffix, urlSuffix, getQuery(pagination?.toString().orEmpty())))
@JvmStatic
fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get repository subscriptions")
}
}
object Organisations : Entity("/orgs") {
object Repos : Entity("/repos") {
@JvmStatic
fun pages(server: GithubServerPath, organisation: String) = GithubApiPagesLoader.Request(get(server, organisation), ::get)
@JvmOverloads
@JvmStatic
fun get(server: GithubServerPath, organisation: String, pagination: GithubRequestPagination? = null) =
get(getUrl(server, Organisations.urlSuffix, "/", organisation, urlSuffix, pagination?.toString().orEmpty()))
@JvmStatic
fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get organisation repositories")
@JvmStatic
fun create(server: GithubServerPath, organisation: String, name: String, description: String, private: Boolean) =
Post.json<GithubRepo>(getUrl(server, Organisations.urlSuffix, "/", organisation, urlSuffix),
GithubRepoRequest(name, description, private, null))
.withOperationName("create organisation repository")
}
}
object Repos : Entity("/repos") {
@JvmStatic
fun get(server: GithubServerPath, username: String, repoName: String) =
Get.Optional.json<GithubRepoDetailed>(getUrl(server, urlSuffix, "/$username/$repoName"))
.withOperationName("get information for repository $username/$repoName")
@JvmStatic
fun delete(server: GithubServerPath, username: String, repoName: String) =
delete(getUrl(server, urlSuffix, "/$username/$repoName")).withOperationName("delete repository $username/$repoName")
@JvmStatic
fun delete(url: String) = Delete(url).withOperationName("delete repository at $url")
object Branches : Entity("/branches") {
@JvmStatic
fun pages(server: GithubServerPath, username: String, repoName: String) =
GithubApiPagesLoader.Request(get(server, username, repoName), ::get)
@JvmOverloads
@JvmStatic
fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) =
get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty())))
@JvmStatic
fun get(url: String) = Get.jsonPage<GithubBranch>(url).withOperationName("get branches")
}
object Forks : Entity("/forks") {
@JvmStatic
fun create(server: GithubServerPath, username: String, repoName: String) =
Post.json<GithubRepo>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix), Any())
.withOperationName("fork repository $username/$repoName for cuurent user")
@JvmStatic
fun pages(server: GithubServerPath, username: String, repoName: String) =
GithubApiPagesLoader.Request(get(server, username, repoName), ::get)
@JvmOverloads
@JvmStatic
fun get(server: GithubServerPath, username: String, repoName: String, pagination: GithubRequestPagination? = null) =
get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, getQuery(pagination?.toString().orEmpty())))
@JvmStatic
fun get(url: String) = Get.jsonPage<GithubRepo>(url).withOperationName("get forks")
}
object Collaborators : Entity("/collaborators") {
@JvmStatic
fun add(server: GithubServerPath, username: String, repoName: String, collaborator: String) =
Put.json<Any>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", collaborator))
}
object Issues : Entity("/issues") {
@JvmStatic
fun create(server: GithubServerPath,
username: String,
repoName: String,
title: String,
body: String? = null,
milestone: Long? = null,
labels: List<String>? = null,
assignees: List<String>? = null) =
Post.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix),
GithubCreateIssueRequest(title, body, milestone, labels, assignees))
@JvmStatic
fun pages(server: GithubServerPath, username: String, repoName: String,
state: String? = null, assignee: String? = null) = GithubApiPagesLoader.Request(get(server, username, repoName,
state, assignee), ::get)
@JvmStatic
fun get(server: GithubServerPath, username: String, repoName: String,
state: String? = null, assignee: String? = null, pagination: GithubRequestPagination? = null) =
get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix,
GithubApiUrlQueryBuilder.urlQuery { param("state", state); param("assignee", assignee); param(pagination) }))
@JvmStatic
fun get(url: String) = Get.jsonPage<GithubIssue>(url).withOperationName("get issues in repository")
@JvmStatic
fun get(server: GithubServerPath, username: String, repoName: String, id: String) =
Get.Optional.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", id))
@JvmStatic
fun updateState(server: GithubServerPath, username: String, repoName: String, id: String, open: Boolean) =
Patch.json<GithubIssue>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix, "/", id),
GithubChangeIssueStateRequest(if (open) "open" else "closed"))
object Comments : Entity("/comments") {
@JvmStatic
fun create(server: GithubServerPath, username: String, repoName: String, issueId: String, body: String) =
Post.json<GithubIssueComment>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", Issues.urlSuffix, "/", issueId, urlSuffix),
GithubCreateIssueCommentRequest(body))
@JvmStatic
fun pages(server: GithubServerPath, username: String, repoName: String, issueId: String) =
GithubApiPagesLoader.Request(get(server, username, repoName, issueId), ::get)
@JvmStatic
fun pages(url: String) = GithubApiPagesLoader.Request(get(url), ::get)
@JvmStatic
fun get(server: GithubServerPath, username: String, repoName: String, issueId: String,
pagination: GithubRequestPagination? = null) =
get(getUrl(server, Repos.urlSuffix, "/$username/$repoName", Issues.urlSuffix, "/", issueId, urlSuffix,
GithubApiUrlQueryBuilder.urlQuery { param(pagination) }))
@JvmStatic
fun get(url: String) = Get.jsonPage<GithubIssueCommentWithHtml>(url, GithubApiContentHelper.V3_HTML_JSON_MIME_TYPE)
.withOperationName("get comments for issue")
}
}
object PullRequests : Entity("/pulls") {
@JvmStatic
fun get(url: String) = Get.json<GithubPullRequestDetailed>(url).withOperationName("get pull request")
@JvmStatic
fun getHtml(url: String) = Get.json<GithubPullRequestDetailedWithHtml>(url, GithubApiContentHelper.V3_HTML_JSON_MIME_TYPE)
.withOperationName("get pull request")
@JvmStatic
fun create(server: GithubServerPath,
username: String, repoName: String,
title: String, description: String, head: String, base: String) =
Post.json<GithubPullRequestDetailed>(getUrl(server, Repos.urlSuffix, "/$username/$repoName", urlSuffix),
GithubPullRequestRequest(title, description, head, base))
.withOperationName("create pull request in $username/$repoName")
@JvmStatic
fun merge(pullRequest: GithubPullRequest, commitSubject: String, commitBody: String, headSha: String) =
Put.json<Unit>(getMergeUrl(pullRequest),
GithubPullRequestMergeRequest(commitSubject, commitBody, headSha, GithubPullRequestMergeMethod.merge))
.withOperationName("merge pull request ${pullRequest.number}")
@JvmStatic
fun squashMerge(pullRequest: GithubPullRequest, commitSubject: String, commitBody: String, headSha: String) =
Put.json<Unit>(getMergeUrl(pullRequest),
GithubPullRequestMergeRequest(commitSubject, commitBody, headSha, GithubPullRequestMergeMethod.squash))
.withOperationName("squash and merge pull request ${pullRequest.number}")
@JvmStatic
fun rebaseMerge(pullRequest: GithubPullRequest, headSha: String) =
Put.json<Unit>(getMergeUrl(pullRequest),
GithubPullRequestMergeRebaseRequest(headSha))
.withOperationName("rebase and merge pull request ${pullRequest.number}")
private fun getMergeUrl(pullRequest: GithubPullRequest) = pullRequest.url + "/merge"
}
}
object Gists : Entity("/gists") {
@JvmStatic
fun create(server: GithubServerPath,
contents: List<GithubGistRequest.FileContent>, description: String, public: Boolean) =
Post.json<GithubGist>(getUrl(server, urlSuffix), GithubGistRequest(contents, description, public))
.withOperationName("create gist")
@JvmStatic
fun get(server: GithubServerPath, id: String) = Get.Optional.json<GithubGist>(getUrl(server, urlSuffix, "/$id"))
.withOperationName("get gist $id")
@JvmStatic
fun delete(server: GithubServerPath, id: String) = Delete(getUrl(server, urlSuffix, "/$id"))
.withOperationName("delete gist $id")
}
object Search : Entity("/search") {
object Issues : Entity("/issues") {
@JvmStatic
fun pages(server: GithubServerPath, repoPath: GithubFullPath?, state: String?, assignee: String?, query: String?) =
GithubApiPagesLoader.Request(get(server, repoPath, state, assignee, query), ::get)
@JvmStatic
fun get(server: GithubServerPath, repoPath: GithubFullPath?, state: String?, assignee: String?, query: String?,
pagination: GithubRequestPagination? = null) =
get(getUrl(server, Search.urlSuffix, urlSuffix,
GithubApiUrlQueryBuilder.urlQuery {
param("q", GithubApiSearchQueryBuilder.searchQuery {
qualifier("repo", repoPath?.fullName.orEmpty())
qualifier("state", state)
qualifier("assignee", assignee)
query(query)
})
param(pagination)
}))
@JvmStatic
fun get(server: GithubServerPath, query: String, pagination: GithubRequestPagination? = null) =
get(getUrl(server, Search.urlSuffix, urlSuffix,
GithubApiUrlQueryBuilder.urlQuery {
param("q", query)
param(pagination)
}))
@JvmStatic
fun get(url: String) = Get.jsonSearchPage<GithubSearchedIssue>(url).withOperationName("search issues in repository")
}
}
object Auth : Entity("/authorizations") {
@JvmStatic
fun create(server: GithubServerPath, scopes: List<String>, note: String) =
Post.json<GithubAuthorization>(getUrl(server, urlSuffix), GithubAuthorizationCreateRequest(scopes, note, null))
.withOperationName("create authorization $note")
@JvmStatic
fun get(server: GithubServerPath) = Get.jsonList<GithubAuthorization>(getUrl(server, urlSuffix))
.withOperationName("get authorizations")
}
abstract class Entity(val urlSuffix: String)
private fun getUrl(server: GithubServerPath, suffix: String) = server.toApiUrl() + suffix
fun getUrl(server: GithubServerPath, vararg suffixes: String) = StringBuilder(server.toApiUrl()).append(*suffixes).toString()
private fun getQuery(vararg queryParts: String): String {
val builder = StringBuilder()
for (part in queryParts) {
if (part.isEmpty()) continue
if (builder.isEmpty()) builder.append("?")
else builder.append("&")
builder.append(part)
}
return builder.toString()
}
} | apache-2.0 | 5a596ed85a922ac75aab2ea12e629430 | 45.263158 | 140 | 0.667715 | 5.054804 | false | false | false | false |
dahlstrom-g/intellij-community | platform/lang-impl/src/com/intellij/refactoring/rename/inplace/inplaceRename.kt | 10 | 13754 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.rename.inplace
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.codeInsight.template.Expression
import com.intellij.codeInsight.template.Template
import com.intellij.codeInsight.template.TemplateManager
import com.intellij.codeInsight.template.TemplateResultListener.TemplateResult
import com.intellij.codeInsight.template.impl.TemplateState
import com.intellij.codeInsight.template.impl.Variable
import com.intellij.injected.editor.DocumentWindow
import com.intellij.injected.editor.EditorWindow
import com.intellij.model.Pointer
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.command.impl.FinishMarkAction
import com.intellij.openapi.command.impl.StartMarkAction
import com.intellij.openapi.command.impl.StartMarkAction.AlreadyStartedException
import com.intellij.openapi.editor.CaretModel
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Segment
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.search.LocalSearchScope
import com.intellij.refactoring.InplaceRefactoringContinuation
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.rename.api.*
import com.intellij.refactoring.rename.api.ReplaceTextTargetContext.IN_COMMENTS_AND_STRINGS
import com.intellij.refactoring.rename.api.ReplaceTextTargetContext.IN_PLAIN_TEXT
import com.intellij.refactoring.rename.impl.*
import com.intellij.refactoring.rename.inplace.InplaceRefactoring.PRIMARY_VARIABLE_NAME
import com.intellij.refactoring.rename.inplace.TemplateInlayUtil.createRenameSettingsInlay
import com.intellij.util.Query
/**
* @return `false` if the template cannot be started,
* e.g., when usage under caret isn't supported
*/
internal fun inplaceRename(project: Project, editor: Editor, target: RenameTarget): Boolean {
val targetPointer: Pointer<out RenameTarget> = target.createPointer()
fun performRename(newName: String) {
ApplicationManager.getApplication().assertReadAccessAllowed()
val restoredTarget = targetPointer.dereference() ?: return
val options = renameOptions(project, restoredTarget)
rename(project, targetPointer, newName, options)
}
val document: Document = editor.document
val file: PsiFile = PsiDocumentManager.getInstance(project).getPsiFile(document)
?: return false
val hostEditor: Editor = (editor as? EditorWindow)?.delegate ?: editor
val hostDocument: Document = (document as? DocumentWindow)?.delegate ?: document
val hostFile: PsiFile = PsiDocumentManager.getInstance(project).getPsiFile(hostDocument)
?: return false
val usageQuery: Query<out RenameUsage> = buildUsageQuery(
project, target,
RenameOptions(TextOptions(commentStringOccurrences = true, textOccurrences = true), LocalSearchScope(hostFile))
)
val usages: Collection<RenameUsage> = usageQuery.findAll()
val psiUsages: List<PsiRenameUsage> = usages.filterIsInstance<PsiRenameUsage>()
val segmentsLimit = Registry.intValue("inplace.rename.segments.limit", -1)
if (segmentsLimit != -1 && psiUsages.size > segmentsLimit) {
return false
}
val offset: Int = editor.caretModel.offset
val originUsage: PsiRenameUsage? = psiUsages.find { usage: PsiRenameUsage ->
usage.file == file &&
usage.range.containsOffset(offset)
}
if (originUsage == null) {
// e.g. when started from Java "var" keyword, the keyword itself is not a usage
// => there are no usages containing the current offset
// => fall back to rename with a dialog
return false
}
if (originUsage !is ModifiableRenameUsage || originUsage.fileUpdater !== idFileRangeUpdater) {
// TODO support starting inplace rename from a usage with a custom updater,
// e.g., starting rename from `foo` reference to `getFoo` method.
// This will require an ability to obtain the new name by a usage text,
// and we don't need this ability when we are 100% sure they are the same (idFileRangeUpdater).
return false
}
var textOptions: TextOptions = getTextOptions(target)
val data = prepareTemplate(hostDocument, hostFile, originUsage, psiUsages, textOptionsRef = { textOptions })
?: return false
val commandName: String = RefactoringBundle.message("rename.command.name.0.in.place.template", target.presentation.presentableText)
val startMarkAction: StartMarkAction = try {
InplaceRefactoring.startMarkAction(project, hostEditor, commandName)
}
catch (e: AlreadyStartedException) {
InplaceRefactoring.unableToStartWarning(project, hostEditor)
// This happens when there is an InplaceRefactoring started, including "old" VariableInplaceRenamer.
// At this point there is no RenameTarget inplace rename in progress, otherwise it would've been handled by InplaceRenameContinuation.
// Returning `false` would've allowed to perform rename with a dialog, which is undesirable.
return true
}
val finishMarkAction = Runnable {
FinishMarkAction.finish(project, hostEditor, startMarkAction)
}
WriteCommandAction.writeCommandAction(project).withName(commandName).run<Throwable> {
try {
val templateState = runLiveTemplate(project, hostEditor, data, ::performRename)
val templateHighlighting = highlightTemplateVariables(project, hostEditor, data.template, templateState, textOptions)
templateHighlighting.updateHighlighters(textOptions)
createRenameSettingsInlay(templateState, templateState.getOriginSegmentEndOffset(), textOptions) { newOptions ->
textOptions = newOptions
templateState.update()
templateHighlighting.updateHighlighters(textOptions)
setTextOptions(targetPointer, textOptions)
}
Disposer.register(templateState, templateHighlighting)
Disposer.register(templateState, storeInplaceContinuation(hostEditor, InplaceRenameContinuation(targetPointer)))
Disposer.register(templateState, finishMarkAction::run)
}
catch (e: Throwable) {
finishMarkAction.run()
throw e
}
}
return true
}
private class TemplateData(
val template: Template,
val templateSegmentRanges: List<TextRange>
)
private data class SegmentData(
val range: TextRange,
val variableName: String,
val expression: Expression,
)
private const val usageVariablePrefix = "inplace_usage_"
internal const val commentStringUsageVariablePrefix = "comment_string_usage_"
internal const val plainTextUsageVariablePrefix = "plain_text_usage_"
private fun prepareTemplate(
hostDocument: Document,
hostFile: PsiFile,
originUsage: PsiRenameUsage,
usages: Collection<PsiRenameUsage>,
textOptionsRef: () -> TextOptions,
): TemplateData? {
val originUsageRange: TextRange = usageRangeInHost(hostFile, originUsage)
?: return null // can't start inplace rename from a usage broken into pieces
val hostDocumentContent = hostDocument.text
val originUsageText = originUsageRange.substring(hostDocumentContent)
val originSegment = SegmentData(
originUsageRange, PRIMARY_VARIABLE_NAME,
MyLookupExpression(originUsageText, null, null, null, false, null)
)
val isCommentStringActive = { textOptionsRef().commentStringOccurrences == true }
val isPlainTextActive = { textOptionsRef().textOccurrences == true }
val segments = ArrayList<SegmentData>(usages.size)
segments += originSegment
var variableCounter = 0
for (usage in usages) {
if (usage === originUsage) {
continue // already handled
}
if (usage !is ModifiableRenameUsage) {
continue // don't know how to update the usage
}
val fileUpdater = usage.fileUpdater
if (fileUpdater !is PsiRenameUsageRangeUpdater) {
continue
}
val usageRangeInHost: TextRange = usageRangeInHost(hostFile, usage)
?: continue // the usage is inside injection, and it's split into several chunks in host
val usageTextByName = fileUpdater.usageTextByName
val segment = if (usage is TextRenameUsage) {
val originalText = usageRangeInHost.substring(hostDocumentContent)
when (usage.context) {
IN_COMMENTS_AND_STRINGS -> SegmentData(
range = usageRangeInHost,
variableName = commentStringUsageVariablePrefix + variableCounter,
expression = InplaceRenameTextUsageExpression(usageTextByName, originalText, isCommentStringActive)
)
IN_PLAIN_TEXT -> SegmentData(
range = usageRangeInHost,
variableName = plainTextUsageVariablePrefix + variableCounter,
expression = InplaceRenameTextUsageExpression(usageTextByName, originalText, isPlainTextActive)
)
}
}
else {
SegmentData(
range = usageRangeInHost,
variableName = usageVariablePrefix + variableCounter,
expression = InplaceRenameUsageExpression(usageTextByName),
)
}
segments += segment
variableCounter++
}
segments.sortWith(Comparator.comparing(SegmentData::range, Segment.BY_START_OFFSET_THEN_END_OFFSET))
val template: Template = buildTemplate(hostFile.project, hostDocumentContent, segments)
assignTemplateExpressionsToVariables(template, originSegment, segments)
return TemplateData(template, segments.map(SegmentData::range))
}
private fun buildTemplate(
project: Project,
hostDocumentContent: String,
segments: List<SegmentData>,
): Template {
val template = TemplateManager.getInstance(project).createTemplate("", "")
var lastOffset = 0
for ((range, variableName, _) in segments) {
template.addTextSegment(hostDocumentContent.substring(lastOffset, range.startOffset))
template.addVariableSegment(variableName)
lastOffset = range.endOffset
}
template.addTextSegment(hostDocumentContent.substring(lastOffset))
return template
}
private fun assignTemplateExpressionsToVariables(
template: Template,
originSegment: SegmentData,
segments: List<SegmentData>,
) {
// add primary variable first, because variables added before it won't be recomputed
template.addVariable(Variable(originSegment.variableName, originSegment.expression, originSegment.expression, true, false))
for ((_, variableName, expression) in segments) {
if (variableName == originSegment.variableName) {
continue
}
template.addVariable(Variable(variableName, expression, null, false, false))
}
}
private fun runLiveTemplate(
project: Project,
hostEditor: Editor,
data: TemplateData,
newNameConsumer: (String) -> Unit,
): TemplateState {
val template = data.template
template.setInline(true)
template.setToIndent(false)
template.isToShortenLongNames = false
template.isToReformat = false
val restoreCaretAndSelection: Runnable = moveCaretForTemplate(hostEditor) // required by `TemplateManager#runTemplate`
val restoreDocument = deleteInplaceTemplateSegments(project, hostEditor.document, data.templateSegmentRanges)
val state: TemplateState = TemplateManager.getInstance(project).runTemplate(hostEditor, template)
DaemonCodeAnalyzer.getInstance(project).disableUpdateByTimer(state)
state.addTemplateResultListener { result: TemplateResult ->
when (result) {
TemplateResult.Canceled -> Unit // don't restore document inside undo
TemplateResult.BrokenOff -> {
restoreDocument.run()
}
TemplateResult.Finished -> {
val newName: String = state.getNewName()
restoreDocument.run()
newNameConsumer(newName)
}
}
}
restoreCaretAndSelection.run()
return state
}
/**
* @return a handle to restore caret position and selection after template initialization
*/
private fun moveCaretForTemplate(editor: Editor): Runnable {
val caretModel: CaretModel = editor.caretModel
val offset: Int = caretModel.offset
val selectedRange: TextRange? = editor.selectionModel.let { selectionModel ->
if (selectionModel.hasSelection()) {
TextRange(selectionModel.selectionStart, selectionModel.selectionEnd)
}
else {
null
}
}
caretModel.moveToOffset(0)
return Runnable {
InplaceRefactoring.restoreOldCaretPositionAndSelection(editor, offset) {
if (selectedRange != null) {
VariableInplaceRenamer.restoreSelection(editor, selectedRange)
}
}
}
}
private fun setTextOptions(targetPointer: Pointer<out RenameTarget>, newOptions: TextOptions) {
targetPointer.dereference()?.let { restoredTarget ->
setTextOptions(restoredTarget, newOptions)
}
}
fun TemplateState.getNewName(): String {
return requireNotNull(getVariableValue(PRIMARY_VARIABLE_NAME)).text
}
private fun TemplateState.getOriginSegmentEndOffset(): Int {
return requireNotNull(getVariableRange(PRIMARY_VARIABLE_NAME)).endOffset
}
private fun storeInplaceContinuation(editor: Editor, continuation: InplaceRefactoringContinuation): Disposable {
editor.putUserData(InplaceRefactoringContinuation.INPLACE_REFACTORING_CONTINUATION, continuation)
editor.putUserData(InplaceRefactoring.INPLACE_RENAMER, ImaginaryInplaceRefactoring)
return Disposable {
editor.putUserData(InplaceRefactoringContinuation.INPLACE_REFACTORING_CONTINUATION, null)
editor.putUserData(InplaceRefactoring.INPLACE_RENAMER, null)
}
}
| apache-2.0 | 012dcb9b05d2be6261f6c7973d6970d1 | 40.678788 | 140 | 0.762833 | 4.690996 | false | false | false | false |
mctoyama/PixelServer | src/main/kotlin/org/pixelndice/table/pixelserver/connection/ping/ContextPing.kt | 1 | 2090 | package org.pixelndice.table.pixelserver.connection.ping
import com.google.common.base.Throwables
import com.google.common.eventbus.Subscribe
import org.apache.logging.log4j.LogManager
import org.hibernate.Session
import org.hibernate.Transaction
import org.pixelndice.table.pixelprotocol.Channel
import org.pixelndice.table.pixelprotocol.ChannelCanceledException
import org.pixelndice.table.pixelprotocol.Protobuf
import org.pixelndice.table.pixelserver.Bus
import org.pixelndice.table.pixelserver.sessionFactory
import org.pixelndice.table.pixelserverhibernate.Account
import org.pixelndice.table.pixelserverhibernate.Ping
import java.net.InetAddress
private val logger = LogManager.getLogger(ContextPing::class.java)
class ContextPing(address: InetAddress) {
private val h = BusHandler()
var state: StatePing = State00Start()
var channel: Channel = Channel(address)
var account: Account = Account()
var ping: Ping = Ping()
init {
Bus.register(h)
}
fun process() {
try {
// state processing
state.process(this)
} catch (e: ChannelCanceledException) {
logger.trace("Channel in invalid state. Waiting to be disposed.")
}
}
inner class BusHandler{
@Subscribe
fun handleLobbyUnreachable(ev: Bus.LobbyUnreachable){
if( [email protected] == ev.ping ){
var session: Session? = null
var tx: Transaction? = null
try {
session = sessionFactory.openSession()
tx = session.beginTransaction()
session.delete([email protected])
tx.commit()
}catch (e: Exception){
logger.fatal("Hibernate fatal error!")
logger.fatal(Throwables.getStackTraceAsString(e))
tx?.rollback()
}finally {
session?.close()
}
[email protected] = StateStop()
}
}
}
} | bsd-2-clause | 8414368be3ce772c0e6830cd94d2efb1 | 26.513158 | 77 | 0.62823 | 4.860465 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/iam/src/main/kotlin/com/kotlin/iam/DeleteAccessKey.kt | 1 | 1864 | // snippet-sourcedescription:[DeleteAccessKey.kt demonstrates how to delete an access key from an AWS Identity and Access Management (IAM) user.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Identity and Access Management (IAM)]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.iam
// snippet-start:[iam.kotlin.delete_access_key.import]
import aws.sdk.kotlin.services.iam.IamClient
import aws.sdk.kotlin.services.iam.model.DeleteAccessKeyRequest
import kotlin.system.exitProcess
// snippet-end:[iam.kotlin.delete_access_key.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<username> <accessKey>
Where:
username - The name of the user.
accessKey - The access key ID for the secret access key you want to delete.
"""
if (args.size != 2) {
println(usage)
exitProcess(0)
}
val userName = args[0]
val accessKey = args[1]
deleteKey(userName, accessKey)
}
// snippet-start:[iam.kotlin.delete_access_key.main]
suspend fun deleteKey(userNameVal: String, accessKey: String) {
val request = DeleteAccessKeyRequest {
accessKeyId = accessKey
userName = userNameVal
}
IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
iamClient.deleteAccessKey(request)
println("Successfully deleted access key $accessKey from $userNameVal")
}
}
// snippet-end:[iam.kotlin.delete_access_key.main]
| apache-2.0 | 842d9d5fc80911c37c7f7dd5efb29e50 | 29.59322 | 145 | 0.679185 | 3.991435 | false | false | false | false |
paplorinc/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/WrapLayout.kt | 1 | 5304 | // 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.pullrequest.ui
import java.awt.Container
import java.awt.Dimension
import java.awt.FlowLayout
import javax.swing.JScrollPane
import javax.swing.SwingUtilities
/**
* FlowLayout subclass that fully supports wrapping of components.
*/
class WrapLayout : FlowLayout {
/**
* Constructs a new `WrapLayout` with a left
* alignment and a default 5-unit horizontal and vertical gap.
*/
constructor() : super()
/**
* Constructs a new `FlowLayout` with the specified
* alignment and a default 5-unit horizontal and vertical gap.
* The value of the alignment argument must be one of
* `WrapLayout`, `WrapLayout`,
* or `WrapLayout`.
* @param align the alignment value
*/
constructor(align: Int) : super(align)
/**
* Creates a new flow layout manager with the indicated alignment
* and the indicated horizontal and vertical gaps.
*
*
* The value of the alignment argument must be one of
* `WrapLayout`, `WrapLayout`,
* or `WrapLayout`.
* @param align the alignment value
* @param hgap the horizontal gap between components
* @param vgap the vertical gap between components
*/
constructor(align: Int, hgap: Int, vgap: Int) : super(align, hgap, vgap)
/**
* Returns the preferred dimensions for this layout given the
* *visible* components in the specified target container.
* @param target the component which needs to be laid out
* @return the preferred dimensions to lay out the
* subcomponents of the specified container
*/
override fun preferredLayoutSize(target: Container): Dimension {
return layoutSize(target, true)
}
/**
* Returns the minimum dimensions needed to layout the *visible*
* components contained in the specified target container.
* @param target the component which needs to be laid out
* @return the minimum dimensions to lay out the
* subcomponents of the specified container
*/
override fun minimumLayoutSize(target: Container): Dimension {
val minimum = layoutSize(target, false)
minimum.width -= hgap + 1
return minimum
}
/**
* Returns the minimum or preferred dimension needed to layout the target
* container.
*
* @param target target to get layout size for
* @param preferred should preferred size be calculated
* @return the dimension to layout the target container
*/
private fun layoutSize(target: Container, preferred: Boolean): Dimension {
synchronized(target.treeLock) {
// Each row must fit with the width allocated to the containter.
// When the container width = 0, the preferred width of the container
// has not yet been calculated so lets ask for the maximum.
var container = target
while (container.size.width == 0 && container.parent != null) {
container = container.parent
}
var targetWidth = container.size.width
if (targetWidth == 0) {
targetWidth = Integer.MAX_VALUE
}
val hgap = hgap
val vgap = vgap
val insets = target.insets
val horizontalInsetsAndGap = insets.left + insets.right + hgap * 2
val maxWidth = targetWidth - horizontalInsetsAndGap
// Fit components into the allowed width
val dim = Dimension(0, 0)
var rowWidth = 0
var rowHeight = 0
val nmembers = target.componentCount
for (i in 0 until nmembers) {
val m = target.getComponent(i)
if (m.isVisible) {
val d = if (preferred) m.preferredSize else m.minimumSize
// Can't add the component to current row. Start a new row.
if (rowWidth + hgap + d.width > maxWidth) {
addRow(dim, rowWidth, rowHeight)
rowWidth = 0
rowHeight = 0
}
// Add a horizontal gap for all components after the first
if (rowWidth != 0) {
rowWidth += hgap
}
rowWidth += d.width
rowHeight = Math.max(rowHeight, d.height)
}
}
addRow(dim, rowWidth, rowHeight)
dim.width += horizontalInsetsAndGap
dim.height += insets.top + insets.bottom + vgap * 2
// When using a scroll pane or the DecoratedLookAndFeel we need to
// make sure the preferred size is less than the size of the
// target containter so shrinking the container size works
// correctly. Removing the horizontal gap is an easy way to do this.
val scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane::class.java, target)
if (scrollPane != null && target.isValid) {
dim.width -= hgap + 1
}
return dim
}
}
/**
* A new row has been completed. Use the dimensions of this row
* to update the preferred size for the container.
*
* @param dim update the width and height when appropriate
* @param rowWidth the width of the row to add
* @param rowHeight the height of the row to add
*/
private fun addRow(dim: Dimension, rowWidth: Int, rowHeight: Int) {
dim.width = Math.max(dim.width, rowWidth)
if (dim.height > 0) {
dim.height += vgap
}
dim.height += rowHeight
}
} | apache-2.0 | 03b1f40c027a61f7ce28cf19174d71a4 | 31.546012 | 140 | 0.663839 | 4.376238 | false | false | false | false |
google/intellij-community | plugins/devkit/intellij.devkit.workspaceModel/tests/testData/simpleCase/after/gen/SimpleEntityImpl.kt | 1 | 6867 | package com.intellij.workspaceModel.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SimpleEntityImpl(val dataSource: SimpleEntityData) : SimpleEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val version: Int get() = dataSource.version
override val name: String
get() = dataSource.name
override val isSimple: Boolean get() = dataSource.isSimple
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: SimpleEntityData?) : ModifiableWorkspaceEntityBase<SimpleEntity>(), SimpleEntity.Builder {
constructor() : this(SimpleEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SimpleEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isNameInitialized()) {
error("Field SimpleEntity#name should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as SimpleEntity
this.entitySource = dataSource.entitySource
this.version = dataSource.version
this.name = dataSource.name
this.isSimple = dataSource.isSimple
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var version: Int
get() = getEntityData().version
set(value) {
checkModificationAllowed()
getEntityData().version = value
changedProperty.add("version")
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData().name = value
changedProperty.add("name")
}
override var isSimple: Boolean
get() = getEntityData().isSimple
set(value) {
checkModificationAllowed()
getEntityData().isSimple = value
changedProperty.add("isSimple")
}
override fun getEntityData(): SimpleEntityData = result ?: super.getEntityData() as SimpleEntityData
override fun getEntityClass(): Class<SimpleEntity> = SimpleEntity::class.java
}
}
class SimpleEntityData : WorkspaceEntityData<SimpleEntity>() {
var version: Int = 0
lateinit var name: String
var isSimple: Boolean = false
fun isNameInitialized(): Boolean = ::name.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<SimpleEntity> {
val modifiable = SimpleEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): SimpleEntity {
return getCached(snapshot) {
val entity = SimpleEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SimpleEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return SimpleEntity(version, name, isSimple, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SimpleEntityData
if (this.entitySource != other.entitySource) return false
if (this.version != other.version) return false
if (this.name != other.name) return false
if (this.isSimple != other.isSimple) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SimpleEntityData
if (this.version != other.version) return false
if (this.name != other.name) return false
if (this.isSimple != other.isSimple) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + version.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + isSimple.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + version.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + isSimple.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 6c11e9126a425ab897c4eb4be11ba12a | 29.932432 | 118 | 0.710208 | 5.25 | false | false | false | false |
google/intellij-community | plugins/settings-sync/src/com/intellij/settingsSync/SettingsSnapshotZipSerializer.kt | 4 | 3308 | package com.intellij.settingsSync
import com.fasterxml.jackson.databind.ObjectMapper
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.io.*
import java.nio.file.Files
import java.nio.file.Path
import java.time.Instant
import java.time.format.DateTimeFormatter
import java.util.*
import java.util.stream.Collectors
import kotlin.io.path.div
internal object SettingsSnapshotZipSerializer {
private const val METAINFO = ".metainfo"
private const val INFO = "info.json"
private val LOG = logger<SettingsSnapshotZipSerializer>()
fun serializeToZip(snapshot: SettingsSnapshot): Path {
val file = FileUtil.createTempFile(SETTINGS_SYNC_SNAPSHOT_ZIP, null)
Compressor.Zip(file)
.use { zip ->
zip.addFile("$METAINFO/$INFO", serializeMetaInfo(snapshot.metaInfo))
for (fileState in snapshot.fileStates) {
val content = if (fileState is FileState.Modified) fileState.content else DELETED_FILE_MARKER.toByteArray()
zip.addFile(fileState.file, content)
}
}
return file.toPath()
}
fun extractFromZip(zipFile: Path): SettingsSnapshot {
val tempDir = FileUtil.createTempDirectory("settings.sync.updates", null).toPath()
Decompressor.Zip(zipFile).extract(tempDir)
val metaInfoFolder = tempDir / METAINFO
val metaInfo = parseMetaInfo(metaInfoFolder)
val fileStates = Files.walk(tempDir)
.filter { it.isFile() && !metaInfoFolder.isAncestor(it) }
.map { getFileStateFromFileWithDeletedMarker(it, tempDir) }
.collect(Collectors.toSet())
return SettingsSnapshot(metaInfo, fileStates)
}
private fun serializeMetaInfo(snapshotMetaInfo: SettingsSnapshot.MetaInfo): ByteArray {
val formattedDate = DateTimeFormatter.ISO_INSTANT.format(snapshotMetaInfo.dateCreated)
val metaInfo = MetaInfo().apply {
date = formattedDate
applicationId = snapshotMetaInfo.appInfo?.applicationId.toString()
userName = snapshotMetaInfo.appInfo?.userName.toString()
hostName = snapshotMetaInfo.appInfo?.hostName.toString()
configFolder = snapshotMetaInfo.appInfo?.configFolder.toString()
}
return ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsBytes(metaInfo)
}
private fun parseMetaInfo(path: Path): SettingsSnapshot.MetaInfo {
try {
val infoFile = path / INFO
if (infoFile.exists()) {
val metaInfo = ObjectMapper().readValue(infoFile.readText(), MetaInfo::class.java)
val date = DateTimeFormatter.ISO_INSTANT.parse(metaInfo.date, Instant::from)
val appInfo = SettingsSnapshot.AppInfo(UUID.fromString(metaInfo.applicationId),
metaInfo.userName, metaInfo.hostName, metaInfo.configFolder)
return SettingsSnapshot.MetaInfo(date, appInfo)
}
else {
LOG.warn("Timestamp file doesn't exist")
}
}
catch (e: Throwable) {
LOG.error("Couldn't read .metainfo from $SETTINGS_SYNC_SNAPSHOT_ZIP", e)
}
return SettingsSnapshot.MetaInfo(Instant.now(), appInfo = null)
}
private class MetaInfo {
lateinit var date: String
lateinit var applicationId: String
var userName: String = ""
var hostName: String = ""
var configFolder: String = ""
}
} | apache-2.0 | 1abddb5b406b95f2570d73ceccd93292 | 37.476744 | 117 | 0.715538 | 4.569061 | false | false | false | false |
dyoung81/PokemonGoBot | src/main/kotlin/ink/abb/pogo/scraper/util/Log.kt | 1 | 1468 | /**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper.util
import java.text.SimpleDateFormat
import java.util.*
class Log {
companion object {
private val green_ = "\u001B[32m"
private val black_ = "\u001B[30m"
private val yellow_ = "\u001B[33m"
private val red_ = "\u001B[31m"
private val white_ = "\u001B[37m"
private val reset = "\u001B[0m"
var format = SimpleDateFormat("dd MMM HH:mm:ss")
fun green(text: String) {
println("${green_}${format.format(Date())}: $text ${reset}")
}
fun normal(text: String) {
println("${format.format(Date())}: $text")
}
fun red(text: String) {
println("${red_}${format.format(Date())}: $text ${reset}")
}
fun yellow(text: String) {
println("${yellow_}${format.format(Date())}: $text ${reset}")
}
fun white(text: String) {
println("${white_}${format.format(Date())}: $text ${reset}")
}
fun black(text: String) {
println("${black_}${format.format(Date())}: $text ${reset}")
}
}
} | gpl-3.0 | 789a93184a001562646bab2f478f0550 | 27.803922 | 97 | 0.574251 | 3.883598 | false | false | false | false |
JetBrains/intellij-community | plugins/git4idea/src/git4idea/checkin/GitPostCommitChangeConverter.kt | 1 | 3590 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.checkin
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.CommitContext
import com.intellij.openapi.vcs.checkin.PostCommitChangeConverter
import com.intellij.util.CollectConsumer
import com.intellij.vcs.commit.commitExecutorProperty
import com.intellij.vcs.log.Hash
import git4idea.GitCommit
import git4idea.GitUtil
import git4idea.commands.Git
import git4idea.history.GitCommitRequirements
import git4idea.history.GitLogUtil
import git4idea.repo.GitRepository
class GitPostCommitChangeConverter(private val project: Project) : PostCommitChangeConverter {
override fun collectChangesAfterCommit(commitContext: CommitContext): List<Change> {
val hashes = commitContext.postCommitHashes ?: return emptyList()
val result = mutableListOf<Change>()
for ((repo, hash) in hashes) {
result += loadChangesFromCommit(repo, hash)
}
return result
}
private fun loadChangesFromCommit(repo: GitRepository, hash: Hash): List<Change> {
val consumer = CollectConsumer<GitCommit>()
val commitRequirements = GitCommitRequirements(diffInMergeCommits = GitCommitRequirements.DiffInMergeCommits.FIRST_PARENT)
GitLogUtil.readFullDetailsForHashes(project, repo.root, listOf(hash.asString()), commitRequirements, consumer)
val commit = consumer.result.first()
return commit.getChanges(0).toList()
}
override fun areConsequentCommits(commitContexts: List<CommitContext>): Boolean {
val commitHashes = commitContexts.map { it.postCommitHashes }
if (commitHashes.all { it == null }) return true // no git commits, not our problem
if (commitHashes.any { it == null }) return false // has non-git commits, give up
val repoMap = mutableMapOf<GitRepository, Hash>()
for (hashes in commitHashes.reversed()) {
for ((repo, hash) in hashes!!) {
val oldHash = repoMap.put(repo, hash)
if (oldHash != null) {
val parentHash = Git.getInstance().resolveReference(repo, "${oldHash}^1")
if (parentHash != hash) {
logger<GitPostCommitChangeConverter>().debug("Non-consequent commits: $oldHash - $hash")
return false
}
}
}
}
return true
}
override fun isFailureUpToDate(commitContexts: List<CommitContext>): Boolean {
val lastCommit = commitContexts.lastOrNull()?.postCommitHashes ?: return true // non-git commits, not our problem
return lastCommit.entries.any { (repo, hash) -> repo.currentRevision == hash.asString() }
}
companion object {
private val GIT_POST_COMMIT_HASHES_KEY = Key.create<MutableMap<GitRepository, Hash>>("Git.Post.Commit.Hash")
private var CommitContext.postCommitHashes: MutableMap<GitRepository, Hash>? by commitExecutorProperty(GIT_POST_COMMIT_HASHES_KEY, null)
@JvmStatic
fun markRepositoryCommit(commitContext: CommitContext, repository: GitRepository) {
var hashes = commitContext.postCommitHashes
if (hashes == null) {
hashes = mutableMapOf()
commitContext.postCommitHashes = hashes
}
val head = GitUtil.getHead(repository) ?: return
val oldHead = hashes.put(repository, head)
if (oldHead != null) {
logger<GitPostCommitChangeConverter>().warn("Multiple commits found for $repository: $head - $oldHead")
}
}
}
} | apache-2.0 | b0691949fdb18e31f00f9b725fe099c9 | 40.275862 | 140 | 0.731476 | 4.309724 | false | false | false | false |
apollographql/apollo-android | apollo-adapters/src/jsTest/kotlin/com/apollographql/apollo3/adapter/test/BigDecimalTests.kt | 1 | 1965 | package com.apollographql.apollo3.adapter.test
import com.apollographql.apollo3.adapter.BigDecimal
import kotlin.test.*
class BigDecimalTests {
@Test
fun equality() {
assertEquals(BigDecimal("12345.12345678901234567890123"), BigDecimal("12345.12345678901234567890123"))
assertEquals(BigDecimal("987654321098765432109876543210"), BigDecimal("987654321098765432109876543210"))
assertEquals(BigDecimal("1024768"), BigDecimal("1024768"))
assertEquals(BigDecimal(-Double.MAX_VALUE), BigDecimal(-Double.MAX_VALUE))
assertEquals(BigDecimal(Double.MAX_VALUE), BigDecimal(Double.MAX_VALUE))
assertEquals(BigDecimal(-Long.MAX_VALUE - 1), BigDecimal(-Long.MAX_VALUE - 1))
assertEquals(BigDecimal(Long.MAX_VALUE), BigDecimal(Long.MAX_VALUE))
}
@Test
fun overflow() {
assertFails {
BigDecimal("987654321098765432109876543210").toLong()
}
}
@Test
fun truncating() {
assertEquals(
BigDecimal("12345.12345678901234567890123").toDouble(),
12345.123456789011
)
}
@Test
fun roundTrip_Int() {
val bridged = BigDecimal(Int.MAX_VALUE)
assertEquals(bridged.toInt(), Int.MAX_VALUE)
val bridgedNeg = BigDecimal( -Int.MAX_VALUE - 1)
assertEquals(bridgedNeg.toInt(), -Int.MAX_VALUE - 1)
}
@Test
fun roundTrip_Long() {
val bridged = BigDecimal(Long.MAX_VALUE)
assertEquals(bridged.toLong(), Long.MAX_VALUE)
val bridgedNeg = BigDecimal(-Long.MAX_VALUE - 1)
assertEquals(bridgedNeg.toLong(), -Long.MAX_VALUE - 1)
}
@Test
fun roundTrip_Double() {
val bridged = BigDecimal(Double.MAX_VALUE)
assertEquals(bridged.toDouble(), Double.MAX_VALUE)
val bridgedNeg = BigDecimal(-Double.MAX_VALUE)
assertEquals(bridgedNeg.toDouble(), -Double.MAX_VALUE)
assertFails {
BigDecimal(Double.POSITIVE_INFINITY)
}
assertFails {
BigDecimal(Double.NEGATIVE_INFINITY)
}
assertFails {
BigDecimal(Double.NaN)
}
}
}
| mit | 58c58c2c0829e2cf0f01d037679db917 | 26.291667 | 108 | 0.702799 | 3.993902 | false | true | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/util/ScreenColorShader.kt | 2 | 1197 | package io.github.chrislo27.rhre3.util
import com.badlogic.gdx.graphics.glutils.ShaderProgram
object ScreenColorShader {
const val vertexShader: String = """
attribute vec4 ${ShaderProgram.POSITION_ATTRIBUTE};
attribute vec4 ${ShaderProgram.COLOR_ATTRIBUTE};
attribute vec2 ${ShaderProgram.TEXCOORD_ATTRIBUTE}0;
uniform mat4 u_projTrans;
varying vec4 v_color;
varying vec2 v_texCoords;
void main()
{
v_color = ${ShaderProgram.COLOR_ATTRIBUTE};
// v_color.a = v_color.a * (255.0/254.0);
v_texCoords = ${ShaderProgram.TEXCOORD_ATTRIBUTE}0;
gl_Position = u_projTrans * ${ShaderProgram.POSITION_ATTRIBUTE};
}
"""
const val fragmentShader: String = """
#ifdef GL_ES
#define LOWP lowp
precision mediump float;
#else
#define LOWP
#endif
varying LOWP vec4 v_color;
varying vec2 v_texCoords;
uniform sampler2D u_texture;
uniform vec4 screenColor;
void main()
{
vec3 s = 1.0 - (1.0 - screenColor.rgb) * (1.0 - screenColor.rgb);
vec4 texel = texture2D(u_texture, v_texCoords);
gl_FragColor = vec4(s * (1.0 - texel.rgb) + v_color.rgb * texel.rgb, v_color.a * texel.a);
}
"""
fun createShader(): ShaderProgram = ShaderProgram(vertexShader, fragmentShader)
} | gpl-3.0 | d2280a0a33c3964be829c86b15acf3cb | 24.489362 | 92 | 0.714286 | 3.166667 | false | false | false | false |
dmcg/konsent | src/main/java/com/oneeyedmen/konsent/webdriver/web-selectors.kt | 1 | 981 | package com.oneeyedmen.konsent.webdriver
import com.oneeyedmen.konsent.Actor
import com.oneeyedmen.konsent.selector
import org.openqa.selenium.remote.RemoteWebDriver
import org.openqa.selenium.remote.RemoteWebElement
import java.net.URI
fun <ResultT> webSelector(description: String, block: Actor<RemoteWebDriver>.() -> ResultT) = selector(description, block)
val thePageLocation = webSelector("the page location") {
URI.create(driver.currentUrl)
}
val thePageContent = webSelector("the page content") {
driver.findElementByTagName("body") as RemoteWebElement?
}
val thePageTitle = webSelector("the page title") {
driver.title
}
@Deprecated("too cutesy", replaceWith = ReplaceWith("thePageLocation")) val `the page location` = thePageLocation
@Deprecated("too cutesy", replaceWith = ReplaceWith("thePageContent")) val `the page content` = thePageContent
@Deprecated("too cutesy", replaceWith = ReplaceWith("thePageTitle")) val `the page title` = thePageTitle
| apache-2.0 | fc82fd4030c8864f5959925bfba435ac | 32.827586 | 122 | 0.777778 | 3.773077 | false | false | false | false |
allotria/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/GrazieConfig.kt | 2 | 4841 | // 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.grazie
import com.intellij.grazie.config.CheckingContext
import com.intellij.grazie.config.DetectionContext
import com.intellij.grazie.config.SuppressingContext
import com.intellij.grazie.config.migration.VersionedState
import com.intellij.grazie.ide.msg.GrazieInitializerManager
import com.intellij.grazie.jlanguage.Lang
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.service
import com.intellij.util.containers.CollectionFactory
import com.intellij.util.xmlb.annotations.Property
import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet
@State(name = "GraziConfig", presentableName = GrazieConfig.PresentableNameGetter::class, storages = [
Storage("grazie_global.xml"),
Storage(value = "grazi_global.xml", deprecated = true)
])
class GrazieConfig : PersistentStateComponent<GrazieConfig.State> {
@Suppress("unused")
enum class Version : VersionedState.Version<State> {
INITIAL,
//Since commit abc7e5f5
OLD_UI {
override fun migrate(state: State) = state.copy(
checkingContext = CheckingContext(
isCheckInCommitMessagesEnabled = state.enabledCommitIntegration
)
)
},
//Since commit cc47dd17
NEW_UI;
override fun next() = values().getOrNull(ordinal + 1)
override fun toString() = ordinal.toString()
companion object {
val CURRENT = NEW_UI
}
}
/**
* State of Grazie plugin
*
* Note, that all serialized values should be MUTABLE.
* Immutable values (like emptySet()) as default may lead to deserialization failure
*/
data class State(
@Property val enabledLanguages: Set<Lang> = hashSetOf(Lang.AMERICAN_ENGLISH),
@Property val enabledGrammarStrategies: Set<String> = defaultEnabledStrategies,
@Property val disabledGrammarStrategies: Set<String> = HashSet(),
@Deprecated("Moved to checkingContext in version 2") @Property val enabledCommitIntegration: Boolean = false,
@Property val userDisabledRules: Set<String> = HashSet(),
@Property val userEnabledRules: Set<String> = HashSet(),
//Formerly suppressionContext -- name changed due to compatibility issues
@Property val suppressingContext: SuppressingContext = SuppressingContext(),
@Property val detectionContext: DetectionContext.State = DetectionContext.State(),
@Property val checkingContext: CheckingContext = CheckingContext(),
@Property override val version: Version = Version.CURRENT
) : VersionedState<Version, State> {
/**
* Available languages set depends on current loaded LanguageTool modules.
*
* Note, that after loading of new module this field will not change. It will
* remain equal to the moment field was accessed first time.
*
* Lazy is used, because deserialized properties are updated during initial deserialization
*
* *NOTE: By default availableLanguages are not included into equals. Check for it manually.*
*/
val availableLanguages: Set<Lang> by lazy {
enabledLanguages.asSequence().filter { lang -> lang.jLanguage != null }.toCollection(CollectionFactory.createSmallMemoryFootprintLinkedSet())
}
val missedLanguages: Set<Lang>
get() = enabledLanguages.asSequence().filter { it.jLanguage == null }.toCollection(CollectionFactory.createSmallMemoryFootprintLinkedSet())
override fun increment() = copy(version = version.next() ?: error("Attempt to increment latest version $version"))
fun hasMissedLanguages(): Boolean {
return enabledLanguages.any { it.jLanguage == null }
}
}
companion object {
private val defaultEnabledStrategies = hashSetOf("nl.rubensten.texifyidea:Latex", "org.asciidoctor.intellij.asciidoc:AsciiDoc")
private val instance by lazy { service<GrazieConfig>() }
/**
* Get copy of Grazie config state
*
* Should never be called in GrazieStateLifecycle actions
*/
fun get() = instance.state
/** Update Grazie config state */
@Synchronized
fun update(change: (State) -> State) = instance.loadState(change(get()))
}
class PresentableNameGetter : com.intellij.openapi.components.State.NameGetter() {
override fun get() = "Grazie Config"
}
private var myState = State()
override fun getState() = myState
override fun loadState(state: State) {
val prevState = myState
myState = VersionedState.migrate(state)
if (prevState != myState || prevState.availableLanguages != myState.availableLanguages) {
service<GrazieInitializerManager>().publisher.update(prevState, myState)
}
}
}
| apache-2.0 | ab51553d1887867b445e037f0d9d3635 | 38.357724 | 147 | 0.735385 | 4.690891 | false | true | false | false |
muntasirsyed/intellij-community | platform/script-debugger/backend/src/org/jetbrains/debugger/BreakpointManagerBase.kt | 1 | 4113 | /*
* 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 org.jetbrains.debugger
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.EventDispatcher
import com.intellij.util.SmartList
import com.intellij.util.containers.ContainerUtil
import gnu.trove.TObjectHashingStrategy
import org.jetbrains.util.concurrency.Promise
import org.jetbrains.util.concurrency.RejectedPromise
import org.jetbrains.util.concurrency.ResolvedPromise
import java.util.concurrent.ConcurrentMap
public abstract class BreakpointManagerBase<T : BreakpointBase<*>> : BreakpointManager {
override val breakpoints: MutableSet<T> = ContainerUtil.newConcurrentSet<T>()
protected val breakpointDuplicationByTarget: ConcurrentMap<T, T> = ContainerUtil.newConcurrentMap<T, T>(object : TObjectHashingStrategy<T> {
override fun computeHashCode(b: T): Int {
var result = b.line
result *= 31 + b.column
if (b.condition != null) {
result *= 31 + b.condition!!.hashCode()
}
result *= 31 + b.target.hashCode()
return result
}
override fun equals(b1: T, b2: T) = b1.target.javaClass == b2.target.javaClass && b1.target == b2.target && b1.line == b2.line && b1.column == b2.column && StringUtil.equals(b1.condition, b2.condition)
})
protected val dispatcher: EventDispatcher<BreakpointManager.BreakpointListener> = EventDispatcher.create(BreakpointManager.BreakpointListener::class.java)
protected abstract fun createBreakpoint(target: BreakpointTarget, line: Int, column: Int, condition: String?, ignoreCount: Int, enabled: Boolean): T
protected abstract fun doSetBreakpoint(target: BreakpointTarget, breakpoint: T): Promise<Breakpoint>
override fun setBreakpoint(target: BreakpointTarget, line: Int, column: Int, condition: String?, ignoreCount: Int, enabled: Boolean): Breakpoint {
val breakpoint = createBreakpoint(target, line, column, condition, ignoreCount, enabled)
val existingBreakpoint = breakpointDuplicationByTarget.putIfAbsent(breakpoint, breakpoint)
if (existingBreakpoint != null) {
return existingBreakpoint
}
breakpoints.add(breakpoint)
if (enabled) {
doSetBreakpoint(target, breakpoint).rejected { dispatcher.multicaster.errorOccurred(breakpoint, it.getMessage() ?: it.toString()) }
}
return breakpoint
}
override fun remove(breakpoint: Breakpoint): Promise<*> {
@Suppress("UNCHECKED_CAST")
val b = breakpoint as T
val existed = breakpoints.remove(b)
if (existed) {
breakpointDuplicationByTarget.remove(b)
}
return if (!existed || !b.isVmRegistered()) ResolvedPromise() else doClearBreakpoint(b)
}
override fun removeAll(): Promise<*> {
val list = breakpoints.toList()
breakpoints.clear()
breakpointDuplicationByTarget.clear()
val promises = SmartList<Promise<*>>()
for (b in list) {
if (b.isVmRegistered()) {
promises.add(doClearBreakpoint(b))
}
}
return Promise.all(promises)
}
protected abstract fun doClearBreakpoint(breakpoint: T): Promise<*>
override fun addBreakpointListener(listener: BreakpointManager.BreakpointListener) {
dispatcher.addListener(listener)
}
protected fun notifyBreakpointResolvedListener(breakpoint: T) {
if (breakpoint.isResolved) {
dispatcher.multicaster.resolved(breakpoint)
}
}
@Suppress("UNCHECKED_CAST")
override fun flush(breakpoint: Breakpoint) = (breakpoint as T).flush(this)
override fun enableBreakpoints(enabled: Boolean): Promise<*> = RejectedPromise<Any?>("Unsupported")
} | apache-2.0 | 087466e038922f66a06357e1f3bd5917 | 38.557692 | 205 | 0.737175 | 4.329474 | false | false | false | false |
dagi12/eryk-android-common | src/main/java/pl/edu/amu/wmi/erykandroidcommon/verify/TextValidator.kt | 1 | 911 | package pl.edu.amu.wmi.erykandroidcommon.verify
import android.support.design.widget.TextInputLayout
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
/**
* @author Eryk Mariankowski <[email protected]> on 20.11.17.
*/
abstract class TextValidator(private val inputLayout: TextInputLayout, private val errMsg: String) : TextWatcher {
abstract fun isCorrect(text: String): Boolean
override fun afterTextChanged(editable: Editable?) {
val correct = isCorrect(editable.toString())
if (correct && !TextUtils.isEmpty(inputLayout.error)) {
inputLayout.error = ""
} else if (!correct) {
inputLayout.error = errMsg
}
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) = Unit
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) = Unit
} | apache-2.0 | 0481f556530d718714b18e006de5a9da | 32.777778 | 114 | 0.703622 | 4.048889 | false | false | false | false |
JetBrains/teamcity-dnx-plugin | plugin-dotnet-agent/src/test/kotlin/jetbrains/buildServer/dotnet/test/dotnet/VersionTest.kt | 1 | 5120 | package jetbrains.buildServer.dotnet.test.dotnet
import jetbrains.buildServer.dotnet.Version
import org.testng.Assert
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
class VersionTest {
@DataProvider
fun testDataComparable(): Array<Array<out Any?>> {
return arrayOf(
arrayOf(Version(2), Version(1), 1),
arrayOf(Version(2, 0), Version(1, 0), 1),
arrayOf(Version(2), Version(2), 0),
arrayOf(Version(0, 2), Version(0, 2), 0),
arrayOf(Version(2), Version(2, 0), 0),
arrayOf(Version(2, 0, 1), Version(2, 0, 1), 0),
arrayOf(Version(2, 1), Version(2, 1, 0), 0),
arrayOf(Version(2, 1), Version(2, 1, 0), 0),
arrayOf(Version(2, 0, 1), Version(2, 0, 1), 0),
arrayOf(Version(1), Version(2), -1),
arrayOf(Version(1, 2), Version(1, 1), 1),
arrayOf(Version(0), Version(1), -1),
arrayOf(Version(3, 3), Version(0), 1),
arrayOf(Version(0, 3), Version(5), -1),
arrayOf(Version.parse("1.0.0"), Version.parse("1.0.0-beta"), 1),
arrayOf(Version.parse("1.0.0-beta1"), Version.parse("1.0.0-beta2"), -1),
arrayOf(Version.parse("1.0.0-beta+meta1"), Version.parse("1.0.0-beta+meta2"), 0))
}
@Test(dataProvider = "testDataComparable")
fun shouldBeComparable(version1: Version, version2: Version, expectedCompareResult: Int) {
// Given
// When
val actualCompareResult = version1.compareTo(version2)
// Then
Assert.assertEquals(actualCompareResult, expectedCompareResult)
}
@DataProvider
fun testDataToString(): Array<Array<out Any?>> {
return arrayOf(
arrayOf(Version(2), "2.0.0"),
arrayOf(Version(99, 3, 10), "99.3.10"),
arrayOf(Version(0, 2), "0.2.0"),
arrayOf(Version(2, 0, 0), "2.0.0"),
arrayOf(Version(0, 0, 2), "0.0.2"),
arrayOf(Version.parse("0.1.2-beta+meta"), "0.1.2-beta+meta"))
}
@Test(dataProvider = "testDataToString")
fun shouldSupportToString(version: Version, expectedString: String) {
// Given
// When
val actualString = version.toString()
// Then
Assert.assertEquals(actualString, expectedString)
}
@DataProvider
fun testDataEquitable(): Array<Array<out Any?>> {
return arrayOf(
arrayOf(Version(1), Version(1), true),
arrayOf(Version(0, 1), Version(0, 1), true),
arrayOf(Version(1), Version(1, 0), true),
arrayOf(Version(1), Version(1, 0, 0), true),
arrayOf(Version(1), Version(2), false),
arrayOf(Version(1, 0), Version(2, 0), false),
arrayOf(Version(0, 1, 0), Version(0, 2, 0), false),
arrayOf(Version(0), Version(2), false),
arrayOf(Version(1, 2), Version(1, 2), true),
arrayOf(Version(1, 2), Version(1), false),
arrayOf(Version(1, 2), Version(1, 3), false),
arrayOf(Version(1, 2), Version(2, 2), false),
arrayOf(Version.parse("1.0.0-beta+meta1"), Version.parse("1.0.0-beta+meta2"), true),
arrayOf(Version.parse("1.0.0-beta1"), Version.parse("1.0.0-beta2"), false))
}
@Test(dataProvider = "testDataEquitable")
fun shouldBeEquitable(version1: Version, version2: Version, expectedEqualsResult: Boolean) {
// Given
// When
val actualEqualsResult1 = version1 == version2
val actualEqualsResult2 = version1 == version2
val actualEqualsResult3 = version2 == version1
val hashCode1 = version1.hashCode()
val hashCode2 = version1.hashCode()
// Then
Assert.assertEquals(actualEqualsResult1, expectedEqualsResult)
Assert.assertEquals(actualEqualsResult2, expectedEqualsResult)
Assert.assertEquals(actualEqualsResult3, expectedEqualsResult)
if (expectedEqualsResult) {
Assert.assertTrue(hashCode1 == hashCode2)
}
}
@DataProvider
fun testDataParse(): Array<Array<out Any?>> {
return arrayOf(
arrayOf("", Version.Empty),
arrayOf("1", Version(1)),
arrayOf("1.23.99", Version(1, 23, 99)),
arrayOf("abc", Version.Empty),
arrayOf("abc.xyz", Version.Empty),
arrayOf("abc.", Version.Empty),
arrayOf("1.", Version.Empty),
arrayOf(".xyz", Version.Empty),
arrayOf(".1", Version.Empty),
arrayOf("abc.1", Version.Empty),
arrayOf("1.abc", Version.Empty))
}
@Test(dataProvider = "testDataParse")
fun shouldParse(text: String, expectedVersion: Version) {
// Given
// When
val actualVersion = Version.parse(text)
// Then
Assert.assertEquals(actualVersion, expectedVersion)
}
} | apache-2.0 | cdb3742568164a1d9d17934316aeb703 | 38.697674 | 100 | 0.558594 | 3.981337 | false | true | false | false |
leafclick/intellij-community | plugins/groovy/test/org/jetbrains/plugins/groovy/codeInsight/hint/GroovyParameterTypeHintsInlayProviderTest.kt | 1 | 3086 | // 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.groovy.codeInsight.hint
import com.intellij.openapi.util.registry.Registry
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.utils.inlays.InlayHintsProviderTestCase
import org.jetbrains.plugins.groovy.GroovyProjectDescriptors
import org.jetbrains.plugins.groovy.intentions.style.inference.MethodParameterAugmenter
class GroovyParameterTypeHintsInlayProviderTest : InlayHintsProviderTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor {
return GroovyProjectDescriptors.GROOVY_LATEST
}
private fun testTypeHints(text: String, settings:
GroovyParameterTypeHintsInlayProvider.Settings = GroovyParameterTypeHintsInlayProvider.Settings(showInferredParameterTypes = true,
showTypeParameterList = true)) {
testProvider("test.groovy", text, GroovyParameterTypeHintsInlayProvider(), settings)
}
override fun setUp() {
Registry.get(MethodParameterAugmenter.GROOVY_COLLECT_METHOD_CALLS_FOR_INFERENCE).setValue(true)
super.setUp()
}
override fun tearDown() {
Registry.get(MethodParameterAugmenter.GROOVY_COLLECT_METHOD_CALLS_FOR_INFERENCE).resetToDefault()
super.tearDown()
}
fun testSingleType() {
val text = """
def foo(<# [Integer ] #>a) {}
foo(1)
""".trimIndent()
testTypeHints(text)
}
fun testWildcard() {
val text = """
def foo(<# [[List < [? [ super Number]] >] ] #>a) {
a.add(1)
}
foo(null as List<Object>)
foo(null as List<Number>)
""".trimIndent()
testTypeHints(text)
}
fun testTypeParameters() {
val text = """
def<# [< T >] #> foo(<# [[List < T >] ] #>a, <# [[List < [? [ extends T]] >] ] #>b) {
a.add(b[0])
}
foo([1], [1])
foo(['q'], ['q'])
""".trimIndent()
testTypeHints(text)
}
fun testClosure() {
val text = """
def<# [< [T extends A] >] #> foo(<# [T ] #>a, <# [[Closure < [? ] >] ] #>c) {
c(a)
}
interface A{def foo()}
foo(null as A) {
it.foo()
}
""".trimIndent()
testTypeHints(text)
}
fun testInsideClosure() {
val text = """
def foo(<# [Integer ] #>arg, <# [[Closure < [? ] >] ] #>closure) {
closure(arg)
}
foo(1) { <# [Integer ] #>a -> a.byteValue() }
""".trimIndent()
testTypeHints(text)
}
fun testNoTypeHintsWithoutTypeInformation() {
val text = """
def foo(x) {}
""".trimIndent()
testTypeHints(text)
}
fun testNestedClosureBlockWithUnresolvableVariables() {
val text = """
import groovy.transform.stc.ClosureParams
import groovy.transform.stc.SimpleType
def foo(@ClosureParams(value=SimpleType, options=['java.lang.Integer'])Closure a) {}
def bar(@ClosureParams(value=SimpleType, options=['java.lang.Integer'])Closure b) {}
foo { <# [Integer ] #>a ->
bar { <# [Integer ] #>b ->
for (x in y){}
}
}
""".trimIndent()
testTypeHints(text)
}
} | apache-2.0 | d1d2ce9d8d2cbee95efa7cacb93612f9 | 26.318584 | 140 | 0.647116 | 3.70024 | false | true | false | false |
bitsydarel/DBWeather | dbweatherdata/src/main/java/com/dbeginc/dbweatherdata/implementations/datasources/remote/news/HttpApiNewsDataSource.kt | 1 | 5224 | /*
* Copyright (C) 2017 Darel Bitsy
* 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.dbeginc.dbweatherdata.implementations.datasources.remote.news
import android.content.Context
import android.support.annotation.RestrictTo
import com.androidnetworking.AndroidNetworking
import com.androidnetworking.interceptors.HttpLoggingInterceptor
import com.dbeginc.dbweatherdata.BuildConfig
import com.dbeginc.dbweatherdata.DEFAULT_NETWORK_CACHE_SIZE
import com.dbeginc.dbweatherdata.NETWORK_CACHE_NAME
import com.dbeginc.dbweatherdata.implementations.datasources.remote.RemoteNewsDataSource
import com.dbeginc.dbweatherdata.implementations.datasources.remote.news.translator.Translator
import com.dbeginc.dbweatherdata.implementations.datasources.remote.news.translator.YandexTranslator
import com.dbeginc.dbweatherdata.proxies.mappers.toDomain
import com.dbeginc.dbweatherdata.proxies.remote.news.RemoteArticle
import com.dbeginc.dbweatherdata.proxies.remote.news.RemoteNewsResponse
import com.dbeginc.dbweatherdata.proxies.remote.news.RemoteSourceResponse
import com.dbeginc.dbweatherdomain.entities.news.Article
import com.dbeginc.dbweatherdomain.entities.news.NewsPaper
import com.dbeginc.dbweatherdomain.entities.requests.news.ArticlesRequest
import com.rx2androidnetworking.Rx2AndroidNetworking
import io.reactivex.Single
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
import java.util.*
import java.util.concurrent.TimeUnit
/**
* Created by darel on 04.10.17.
*
* Remote News Data NewsPaper Implementation
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
class HttpApiNewsDataSource private constructor(private val translator: Translator) : RemoteNewsDataSource {
private val deviceLanguage by lazy { Locale.getDefault().language }
companion object {
fun create(context: Context): RemoteNewsDataSource {
val client = OkHttpClient.Builder()
.connectTimeout(35, TimeUnit.SECONDS)
.writeTimeout(35, TimeUnit.SECONDS)
.readTimeout(55, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.cache(Cache(File(context.cacheDir, NETWORK_CACHE_NAME), DEFAULT_NETWORK_CACHE_SIZE))
AndroidNetworking.enableLogging(HttpLoggingInterceptor.Level.BASIC)
AndroidNetworking.initialize(context, client.build())
return HttpApiNewsDataSource(translator = YandexTranslator())
}
}
override fun getNewsPapers(): Single<List<NewsPaper>> {
return Rx2AndroidNetworking
.get("https://newsapi.org/v2/sources")
.addQueryParameter("apiKey", BuildConfig.NEWS_API_KEY)
.build()
.getObjectSingle(RemoteSourceResponse::class.java)
.map { response -> response.sources }
.map { sources -> sources.map { source -> source.toDomain() } }
}
override fun getTranslatedArticles(request: ArticlesRequest<String>): Single<List<Article>> {
return getArticlesFromApi(newsPaperId = request.newsPaperId)
.flattenAsObservable { it }
.flatMapSingle { originalArticle ->
translator.translate(text = originalArticle.title, language = deviceLanguage)
.map { translation -> originalArticle.apply { title = translation } }
.flatMap { mapperArticle ->
mapperArticle.description
?.let {
translator.translate(text = it, language = deviceLanguage)
.map { translation -> originalArticle.apply { description = translation } }
} ?: Single.just(mapperArticle)
}
}
.toList()
.map { articles -> articles.map { article -> article.toDomain() } }
}
override fun getArticles(request: ArticlesRequest<String>): Single<List<Article>> {
return getArticlesFromApi(newsPaperId = request.newsPaperId)
.map { articles -> articles.map { article -> article.toDomain() } }
}
private fun getArticlesFromApi(newsPaperId: String): Single<List<RemoteArticle>> {
return Rx2AndroidNetworking.get("https://newsapi.org/v2/top-headlines")
.addQueryParameter("sources", newsPaperId)
.addQueryParameter("apiKey", BuildConfig.NEWS_API_KEY)
.build()
.getObjectSingle(RemoteNewsResponse::class.java)
.map { response -> response.articles }
}
} | gpl-3.0 | 38cf3302ad9bb032044a8958e039abe0 | 46.072072 | 127 | 0.67745 | 4.846011 | false | false | false | false |
romannurik/muzei | wearable/src/main/java/com/google/android/apps/muzei/datalayer/OpenOnPhoneReceiver.kt | 1 | 3315 | /*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.datalayer
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.support.wearable.activity.ConfirmationActivity
import android.util.Log
import androidx.core.net.toUri
import com.google.android.apps.muzei.util.goAsync
import com.google.android.apps.muzei.util.toast
import com.google.android.gms.wearable.CapabilityClient
import com.google.android.gms.wearable.Node
import com.google.android.gms.wearable.Wearable
import com.google.android.wearable.intent.RemoteIntent
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.ktx.Firebase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.withContext
import net.nurik.roman.muzei.R
import java.util.TreeSet
class OpenOnPhoneReceiver : BroadcastReceiver() {
companion object {
private const val TAG = "OpenOnPhoneReceiver"
}
override fun onReceive(context: Context, intent: Intent) {
goAsync {
val capabilityClient = Wearable.getCapabilityClient(context)
val nodes: Set<Node> = try {
// We use activate_muzei for compatibility with
// older versions of Muzei's phone app
capabilityClient.getCapability("activate_muzei",
CapabilityClient.FILTER_REACHABLE).await().nodes
} catch (e: Exception) {
Log.e(TAG, "Error getting reachable capability info", e)
TreeSet()
}
if (nodes.isEmpty()) {
withContext(Dispatchers.Main.immediate) {
context.toast(R.string.datalayer_open_failed)
}
} else {
Firebase.analytics.logEvent("data_layer_open_on_phone", null)
// Show the open on phone animation
val openOnPhoneIntent = Intent(context, ConfirmationActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK
putExtra(ConfirmationActivity.EXTRA_ANIMATION_TYPE,
ConfirmationActivity.OPEN_ON_PHONE_ANIMATION)
}
context.startActivity(openOnPhoneIntent)
// Use RemoteIntent.startRemoteActivity to open Muzei on the phone
for (node in nodes) {
RemoteIntent.startRemoteActivity(context, Intent(Intent.ACTION_VIEW).apply {
data = "android-app://${context.packageName}".toUri()
addCategory(Intent.CATEGORY_BROWSABLE)
}, null, node.id)
}
}
}
}
} | apache-2.0 | f9034e6fd9cd86bcc860cc12c247cfd5 | 40.45 | 97 | 0.659729 | 4.669014 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/debugger-tests/src/test/kotlin/org/jetbrains/kotlin/compiletest/LldbTests.kt | 1 | 2773 | import org.jetbrains.kotlin.compiletest.lldbTest
import org.junit.Test
class LldbTests {
@Test
fun `can step through code`() = lldbTest("""
fun main(args: Array<String>) {
var x = 1
var y = 2
var z = x + y
println(z)
}
""", """
> b main.kt:2
Breakpoint 1: [..]
> r
Process [..] stopped
[..] at main.kt:2, [..] stop reason = breakpoint 1.1
> n
Process [..] stopped
[..] at main.kt:3, [..] stop reason = step over
> n
Process [..] stopped
[..] at main.kt:4, [..] stop reason = step over
> n
Process [..] stopped
[..] at main.kt:5, [..] stop reason = step over
""")
//FIXME: Boolean and Int are wrong
@Test
fun `can inspect values of primitive types`() = lldbTest("""
fun main(args: Array<String>) {
var a: Byte = 1
var b: Int = 2
var c: Long = -3
var d: Char = 'c'
var e: Boolean = true
return
}
""", """
> b main.kt:7
> r
> fr var
(char) a = '\x01'
(int) b = 2
(long) c = -3
(unsigned char) d = 'c'
(void) e = <Unable to determine byte size.>
""")
@Test
fun `can inspect classes`() = lldbTest("""
fun main(args: Array<String>) {
val point = Point(1, 2)
val person = Person()
return
}
data class Point(val x: Int, val y: Int)
class Person {
override fun toString() = "John Doe"
}
""", """
> b main.kt:4
> r
> fr var
(ObjHeader *) point = Point(x=1, y=2)
(ObjHeader *) person = John Doe
""")
@Test
fun `can inspect arrays`() = lldbTest("""
fun main(args: Array<String>) {
val xs = IntArray(3)
xs[0] = 1
xs[1] = 2
xs[2] = 3
val ys: Array<Any?> = arrayOfNulls(2)
ys[0] = Point(1, 2)
return
}
data class Point(val x: Int, val y: Int)
""", """
> b main.kt:8
> r
> fr var
(ObjHeader *) xs = [1, 2, 3]
(ObjHeader *) ys = [Point(x=1, y=2), null]
""")
@Test
fun `can inspect array children`() = lldbTest("""
fun main(args: Array<String>) {
val xs = intArrayOf(3, 5, 8)
return
}
data class Point(val x: Int, val y: Int)
""", """
> type summary add "ObjHeader *" --inline-children
> b main.kt:3
> r
> fr var xs
(ObjHeader *) xs = [..] (0 = 3, 1 = 5, 2 = 8)
""")
} | apache-2.0 | e84d00eea04249736bade1dd02ba5dba | 23.767857 | 64 | 0.421926 | 3.867503 | false | true | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/mesh/HalfEdgeMesh.kt | 1 | 19355 | package de.fabmax.kool.modules.mesh
import de.fabmax.kool.math.*
import de.fabmax.kool.math.spatial.OcTree
import de.fabmax.kool.pipeline.Attribute
import de.fabmax.kool.scene.BetterLineMesh
import de.fabmax.kool.scene.LineMesh
import de.fabmax.kool.scene.Mesh
import de.fabmax.kool.scene.geometry.IndexedVertexList
import de.fabmax.kool.scene.geometry.VertexView
import de.fabmax.kool.util.*
/**
* An editable mesh.
*
* @author fabmax
*/
class HalfEdgeMesh(geometry: IndexedVertexList, val edgeHandler: EdgeHandler = ListEdgeHandler()): Mesh(geometry) {
private val verts: MutableList<HalfEdgeVertex>
val vertices: List<HalfEdgeVertex>
get() = verts
private val positionOffset = geometry.attributeByteOffsets[Attribute.POSITIONS]!!
private val tmpVec1 = MutableVec3f()
private val tmpVec2 = MutableVec3f()
private val tmpVec3 = MutableVec3f()
private val vertexIt1 = geometry[0]
private val vertexIt2 = geometry[0]
val vertCount: Int
get() = verts.size
val faceCount: Int
get() = edgeHandler.numEdges / 3
interface EdgeHandler : Iterable<HalfEdge> {
val numEdges: Int
operator fun plusAssign(edge: HalfEdge)
operator fun minusAssign(edge: HalfEdge)
fun checkedUpdateEdgeTo(edge: HalfEdge, newTo: HalfEdgeVertex)
fun checkedUpdateEdgeFrom(edge: HalfEdge, newFrom: HalfEdgeVertex)
fun checkedUpdateVertexPosition(vertex: HalfEdgeVertex, x: Float, y: Float, z: Float)
fun distinctTriangleEdges(): List<HalfEdge> = filter { it.id < it.next.id && it.id < it.next.next.id }
fun rebuild()
}
init {
// if (meshData.primitiveType != GL_TRIANGLES) {
// throw KoolException("Supplied meshData must be of primitive type GL_TRIANGLES")
// }
verts = MutableList(geometry.numVertices) { HalfEdgeVertex(it) }
for (i in 0 until geometry.numIndices step 3) {
// create triangle vertices
val v0 = verts[geometry.indices[i]]
val v1 = verts[geometry.indices[i+1]]
val v2 = verts[geometry.indices[i+2]]
// create inner half-edges and connect them
val e0 = HalfEdge(v0, v1)
val e1 = HalfEdge(v1, v2).apply { e0.next = this }
val e2 = HalfEdge(v2, v0).apply { e1.next = this; next = e0 }
// link opposite edges if existing
e0.opp = v1.getEdgeTo(v0)?.apply { opp = e0 }
e1.opp = v2.getEdgeTo(v1)?.apply { opp = e1 }
e2.opp = v0.getEdgeTo(v2)?.apply { opp = e2 }
// insert newly created edges
edgeHandler += e0
edgeHandler += e1
edgeHandler += e2
}
}
fun generateWireframe(lineMesh: LineMesh, lineColor: Color = MdColor.PINK) {
val v0 = MutableVec3f()
val v1 = MutableVec3f()
edgeHandler.filter { it.opp == null || it.from.index < it.to.index }.forEach { edge ->
v0.set(edge.from)
v1.set(edge.to)
lineMesh.addLine(v0, lineColor, v1, lineColor)
}
}
fun generateWireframe(lineMesh: BetterLineMesh, lineColor: Color = MdColor.PINK, lineWidth: Float = 2f) {
val v0 = MutableVec3f()
val v1 = MutableVec3f()
edgeHandler.filter { it.opp == null || it.from.index < it.to.index }.forEach { edge ->
v0.set(edge.from)
v1.set(edge.to)
lineMesh.line(v0, v1, lineColor, lineWidth)
}
}
fun sanitize() {
// assign new vertex indices
val vIt = verts.iterator()
var vi = 0
for (v in vIt) {
if (v.isDeleted) {
vIt.remove()
} else {
v.index = vi++
}
}
val vertCnt = verts.size
edgeHandler.rebuild()
if (edgeHandler.numEdges % 3 != 0) {
logW { "Uneven edge count: ${edgeHandler.numEdges % 3}" }
}
// check for invalid edges
// fixme: check why deleted edges sometimes remain linked to their from vertex
// test with cow model: 7 such edges on 1% simplification
val removeEdges = mutableListOf<HalfEdge>()
for (v in verts) {
v.edges.removeAll {
if (it.isDeleted) {
logW { "Deleted edge in v, edge.from == v: ${it.from === v}" }
}
it.isDeleted
}
for (he in v.edges) {
val i0 = he.from.index
val i1 = he.next.from.index
val i2 = he.next.next.from.index
if (i0 >= vertCnt || i1 >= vertCnt || i2 >= vertCnt) {
logW { "Inconsistent triangle indices: i0=$i0, i1=$i1, i2=$i2, mesh has only $vertCnt vertices" }
removeEdges += he
}
}
}
edgeHandler.forEach { he ->
if (he.from.isDeleted || he.from.index >= vertCnt || he.to.isDeleted || he.to.index >= vertCnt) {
logW { "Inconsistent edge: ${he.from.index} (del=${he.from.isDeleted}) -> ${he.to.index} (del=${he.to.isDeleted}), mesh has only $vertCnt vertices" }
removeEdges += he
}
if (he === he.next || he === he.next.next) {
logW { "Invalid edge linkage: he == he.next || he == he.next.next" }
removeEdges += he
}
}
removeEdges.forEach { it.deleteTriangle() }
}
/**
* Removes all vertices / triangles marked as deleted
*/
fun rebuild(generateNormals: Boolean = true, generateTangents: Boolean = true) {
sanitize()
geometry.batchUpdate(true) {
// apply new indices to mesh vertex list
val strideF = geometry.vertexSizeF
val strideI = geometry.vertexSizeI
val vertCnt = verts.size
val newDataF = createFloat32Buffer(vertCnt * strideF)
val newDataI = if (strideI > 0) createUint32Buffer(vertCnt * strideI) else geometry.dataI
for (i in verts.indices) {
// copy data from previous location
val oldIdx = verts[i].meshDataIndex
verts[i].meshDataIndex = verts[i].index
for (j in 0 until strideF) {
newDataF.put(geometry.dataF[oldIdx * strideF + j])
}
if (strideI > 0) {
for (j in 0 until strideI) {
newDataI.put(geometry.dataI[oldIdx * strideI + j])
}
}
}
// rebuild triangle index list
geometry.clearIndices()
for (e in edgeHandler.distinctTriangleEdges()) {
geometry.addIndex(e.from.index)
geometry.addIndex(e.next.from.index)
geometry.addIndex(e.next.next.from.index)
}
if (geometry.numIndices != faceCount * 3) {
logW { "Inconsistent triangle count! MeshData: ${geometry.numIndices / 3}, HalfEdgeMesh: $faceCount" }
}
geometry.dataF = newDataF
geometry.dataI = newDataI
geometry.numVertices = vertCnt
if (generateNormals) {
geometry.generateNormals()
}
if (generateTangents) {
geometry.generateTangents()
}
}
}
fun selectBorders(): MutableList<MutableList<HalfEdge>> {
val borders = mutableListOf<MutableList<HalfEdge>>()
val collected = mutableSetOf<HalfEdge>()
var border = mutableListOf<HalfEdge>()
for (edge in edgeHandler) {
if (edge.opp == null) {
var borderEdge = edge
while (borderEdge !in collected) {
border.add(borderEdge)
collected.add(borderEdge)
borderEdge = borderEdge.to.edges.find { it.opp == null && it !in collected } ?: break
}
if (border.isNotEmpty()) {
borders.add(border)
border = mutableListOf()
}
}
}
return borders
}
fun subSelect(start: HalfEdge, maxTris: Int = 0): Pair<List<HalfEdge>, List<HalfEdge>> {
val selection = mutableListOf<HalfEdge>()
val borderEdges = mutableSetOf<Long>()
val innerEdges = mutableSetOf<Long>()
val borderQueue = mutableListOf(start)
while (borderQueue.isNotEmpty() && (maxTris == 0 || selection.size / 3 < maxTris)) {
val he = borderQueue.removeAt(0)
if (he.id in innerEdges) {
continue
}
selection += he.also { innerEdges += it.id }
selection += he.next.also { innerEdges += it.id }
selection += he.next.next.also { innerEdges += it.id }
if (he.opp != null && he.opp!!.id !in innerEdges && he.opp!!.id !in borderEdges) {
borderQueue += he.opp!!
}
if (he.next.opp != null && he.next.opp!!.id !in innerEdges && he.next.opp!!.id !in borderEdges) {
borderQueue += he.next.opp!!
}
if (he.next.next.opp != null && he.next.next.opp!!.id !in innerEdges && he.next.next.opp!!.id !in borderEdges) {
borderQueue += he.next.next.opp!!
}
}
return Pair(borderQueue, selection)
}
fun splitEdge(edge: HalfEdge, fraction: Float): HalfEdgeVertex {
// spawn new vertex
val idx = geometry.addVertex {
position.set(edge.to).subtract(edge.from).scale(fraction).add(edge.from)
// interpolate texture coordinates and normals
edge.from.getMeshVertex(vertexIt1)
edge.to.getMeshVertex(vertexIt2)
texCoord.set(vertexIt2.texCoord).subtract(vertexIt1.texCoord).scale(fraction).add(vertexIt1.texCoord)
normal.set(vertexIt2.normal).subtract(vertexIt1.normal).scale(fraction).add(vertexIt1.normal)
}
val insertV = HalfEdgeVertex(idx)
verts += insertV
// insert new half edges for right triangle and adjust linkage
val prevToR = edge.to
edge.updateTo(insertV)
edge.next.from.edges -= edge.next
edge.next.updateFrom(insertV)
insertV.edges += edge.next
val insertEdR0 = HalfEdge(insertV, prevToR)
val insertEdR1 = HalfEdge(prevToR, edge.next.to).apply {
insertEdR0.next = this
opp = edge.next.opp
opp?.opp = this
}
val insertEdR2 = HalfEdge(edge.next.to, insertV).apply {
insertEdR1.next = this
next = insertEdR0
opp = edge.next
edge.next.opp = this
}
edgeHandler += insertEdR0
edgeHandler += insertEdR1
edgeHandler += insertEdR2
// insert new half edges for left (opposing) triangle and adjust linkage
val edgeOpp = edge.opp
if (edgeOpp != null) {
val prevToL = edgeOpp.to
edgeOpp.updateTo(insertV)
edgeOpp.next.from.edges -= edgeOpp.next
edgeOpp.next.updateFrom(insertV)
insertV.edges += edgeOpp.next
val insertEdL0 = HalfEdge(insertV, prevToL)
val insertEdL1 = HalfEdge(prevToL, edgeOpp.next.to).apply {
insertEdL0.next = this
opp = edgeOpp.next.opp
opp?.opp = this
}
val insertEdL2 = HalfEdge(edgeOpp.next.to, insertV).apply {
insertEdL1.next = this
next = insertEdL0
opp = edgeOpp.next
edgeOpp.next.opp = this
}
insertEdL0.opp = edge
edge.opp = insertEdL0
insertEdR0.opp = edgeOpp
edgeOpp.opp = insertEdR0
edgeHandler += insertEdL0
edgeHandler += insertEdL1
edgeHandler += insertEdL2
}
return insertV
}
fun collapseEdge(edge: HalfEdge, fraction: Float) {
val srcVert = edge.from
val delVert = edge.to
val oppR1 = edge.next.opp
if (oppR1 != null) {
// colOppR1 points to delVert
edge.next.opp = null
oppR1.opp = null
oppR1.updateTo(srcVert)
}
val oppR2 = edge.next.next.opp
if (oppR2 != null) {
// colOppR2 points from srcVert to colOppR1.from
edge.next.next.opp = null
oppR2.opp = oppR1
if (oppR1 != null) {
oppR1.opp = oppR2
}
}
val edgeOpp = edge.opp
if (edgeOpp != null) {
val oppL1 = edgeOpp.next.opp
if (oppL1 != null) {
// colOppL1 points to srcVert
edgeOpp.next.opp = null
oppL1.opp = null
}
val oppL2 = edgeOpp.next.next.opp
if (oppL2 != null) {
// colOppL2 points from delVert to colOppL1.from
delVert.edges.remove(oppL2)
srcVert.edges.add(oppL2)
oppL2.updateFrom(srcVert)
oppL2.next.next.updateTo(srcVert)
edgeOpp.next.next.opp = null
oppL2.opp = oppL1
if (oppL1 != null) {
oppL1.opp = oppL2
}
}
}
// delete triangle defined by edge
edge.deleteTriangle()
// delete opposite triangle of edge (if it exists)
edgeOpp?.deleteTriangle()
for (i in delVert.edges.indices) {
val e = delVert.edges[i]
e.updateFrom(srcVert)
e.next.next.updateTo(srcVert)
val eOpp = e.opp
if (eOpp != null) {
eOpp.updateTo(srcVert)
eOpp.next.updateFrom(srcVert)
}
srcVert.edges += e
}
delVert.edges.clear()
delVert.delete()
if (fraction != 0f) {
val newX = srcVert.x + (delVert.x - srcVert.x) * fraction
val newY = srcVert.y + (delVert.y - srcVert.y) * fraction
val newZ = srcVert.z + (delVert.z - srcVert.z) * fraction
srcVert.updatePosition(newX, newY, newZ)
}
}
fun subMeshOf(edges: List<HalfEdge>): IndexedVertexList {
val subData = IndexedVertexList(geometry.vertexAttributes)
val indexMap = mutableMapOf<Int, Int>()
val v = geometry.vertexIt
edges.forEach { he ->
if (he.from.index !in indexMap.keys) {
indexMap[he.from.index] = subData.addVertex {
set(v.apply { index = he.from.index })
}
}
if (he.to.index !in indexMap.keys) {
indexMap[he.to.index] = subData.addVertex {
set(v.apply { index = he.to.index })
}
}
}
val addedHes = mutableSetOf<Long>()
edges.forEach { he ->
if (he.id !in addedHes) {
subData.addTriIndices(indexMap[he.from.index]!!, indexMap[he.next.from.index]!!, indexMap[he.next.next.from.index]!!)
addedHes += he.id
addedHes += he.next.id
addedHes += he.next.next.id
}
}
return subData
}
inner class HalfEdgeVertex(var index: Int): Vec3f(0f) {
/**
* List of edges that start with this vertex.
*/
val edges = mutableListOf<HalfEdge>()
var isDeleted = false
private set
internal var meshDataIndex = index
override val x: Float
get() = geometry.dataF[index * geometry.vertexSizeF + positionOffset]
override val y: Float
get() = geometry.dataF[index * geometry.vertexSizeF + positionOffset + 1]
override val z: Float
get() = geometry.dataF[index * geometry.vertexSizeF + positionOffset + 2]
internal fun setPosition(x: Float, y: Float, z: Float) {
geometry.dataF[index * geometry.vertexSizeF + positionOffset] = x
geometry.dataF[index * geometry.vertexSizeF + positionOffset + 1] = y
geometry.dataF[index * geometry.vertexSizeF + positionOffset + 2] = z
}
fun getMeshVertex(result: VertexView): VertexView {
result.index = this.index
return result
}
fun getEdgeTo(v: HalfEdgeVertex): HalfEdge? {
for (i in edges.indices) {
if (edges[i].to === v) {
return edges[i]
}
}
return null
}
fun delete() {
while (edges.isNotEmpty()) {
edges.last().deleteTriangle()
}
// mark vertex as deleted, cleanup is done sometime later
isDeleted = true
}
fun updatePosition(newPos: Vec3f) = updatePosition(newPos.x, newPos.y, newPos.z)
fun updatePosition(x: Float, y: Float, z: Float) = edgeHandler.checkedUpdateVertexPosition(this, x, y, z)
}
inner class HalfEdge(from: HalfEdgeVertex, to: HalfEdgeVertex) {
var from = from
internal set
var to = to
internal set
var isDeleted = false
internal set
var treeNode: OcTree<HalfEdge>.OcNode? = null
internal set
val id: Long
get() = (from.index.toLong() shl 32) or to.index.toLong()
val triId: Long
get() = minOf(id, next.id, next.next.id)
lateinit var next: HalfEdge
internal set
var opp: HalfEdge? = null
internal set
init {
from.edges += this
}
fun computeLength(): Float = from.distance(to)
fun computeTriArea(): Float = triArea(from, to, next.to)
fun computeTriAspectRatio() = triAspectRatio(from, to, next.to)
fun computeTriNormal(result: MutableVec3f): MutableVec3f {
to.subtract(from, tmpVec1)
next.to.subtract(from, tmpVec2)
tmpVec1.cross(tmpVec2, result)
return result.norm()
}
fun computeTriPlane(result: MutableVec4f): MutableVec4f {
computeTriNormal(tmpVec3)
result.set(tmpVec3, -tmpVec3.dot(from))
return result
}
fun collapse(fraction: Float) {
collapseEdge(this, fraction)
}
fun split(fraction: Float): HalfEdgeVertex {
return splitEdge(this, fraction)
}
private fun deleteEdge() {
edgeHandler -= this
isDeleted = true
from.edges -= this
opp?.apply { opp = null }
treeNode = null
opp = null
}
fun deleteTriangle() {
deleteEdge()
next.deleteEdge()
next.next.deleteEdge()
}
fun updateFrom(newFrom: HalfEdgeVertex) = edgeHandler.checkedUpdateEdgeFrom(this, newFrom)
fun updateTo(newTo: HalfEdgeVertex) = edgeHandler.checkedUpdateEdgeTo(this, newTo)
override fun toString(): String {
return "${from.index} -> ${to.index}"
}
}
}
| apache-2.0 | cd354906603824c66fd06eccd80a5061 | 33.5625 | 165 | 0.541979 | 3.962129 | false | false | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/navigation/PsiElementNavigationTarget.kt | 1 | 1310 | // 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.codeInsight.navigation
import com.intellij.ide.util.EditSourceUtil
import com.intellij.navigation.NavigationTarget
import com.intellij.navigation.TargetPopupPresentation
import com.intellij.pom.Navigatable
import com.intellij.psi.PsiElement
import org.jetbrains.annotations.ApiStatus.Experimental
@Experimental
class PsiElementNavigationTarget(private val myElement: PsiElement) : NavigationTarget {
private val myNavigatable by lazy {
if (myElement is Navigatable) myElement else EditSourceUtil.getDescriptor(myElement)
}
private val myPresentation by lazy {
PsiElementTargetPopupPresentation(myElement)
}
override fun isValid(): Boolean = myElement.isValid
override fun getNavigatable(): Navigatable? = myNavigatable
override fun getTargetPresentation(): TargetPopupPresentation = myPresentation
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as PsiElementNavigationTarget
if (myElement != other.myElement) return false
return true
}
override fun hashCode(): Int {
return myElement.hashCode()
}
}
| apache-2.0 | 6d3e571793cd901be260c3e25616be85 | 30.190476 | 140 | 0.780916 | 4.88806 | false | false | false | false |
leafclick/intellij-community | plugins/stats-collector/src/com/intellij/stats/personalization/UserFactorDescriptions.kt | 1 | 3147 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.stats.personalization
import com.intellij.stats.personalization.impl.*
/**
* @author Vitaliy.Bibaev
*/
object UserFactorDescriptions {
private val IDS: MutableSet<String> = mutableSetOf()
val COMPLETION_TYPE: UserFactorDescription<CompletionTypeUpdater, CompletionTypeReader> =
Descriptor.register("completionType", ::CompletionTypeUpdater, ::CompletionTypeReader)
val COMPLETION_FINISH_TYPE: UserFactorDescription<CompletionFinishTypeUpdater, CompletionFinishTypeReader> =
Descriptor.register("completionFinishedType", ::CompletionFinishTypeUpdater, ::CompletionFinishTypeReader)
val COMPLETION_USAGE: UserFactorDescription<CompletionUsageUpdater, CompletionUsageReader> =
Descriptor.register("completionUsage", ::CompletionUsageUpdater, ::CompletionUsageReader)
val PREFIX_LENGTH_ON_COMPLETION: UserFactorDescription<PrefixLengthUpdater, PrefixLengthReader> =
Descriptor.register("prefixLength", ::PrefixLengthUpdater, ::PrefixLengthReader)
val SELECTED_ITEM_POSITION: UserFactorDescription<ItemPositionUpdater, ItemPositionReader> =
Descriptor.register("itemPosition", ::ItemPositionUpdater, ::ItemPositionReader)
val TIME_BETWEEN_TYPING: UserFactorDescription<TimeBetweenTypingUpdater, TimeBetweenTypingReader> =
Descriptor.register("timeBetweenTyping", ::TimeBetweenTypingUpdater, ::TimeBetweenTypingReader)
val MNEMONICS_USAGE: UserFactorDescription<MnemonicsUsageUpdater, MnemonicsUsageReader> =
Descriptor.register("mnemonicsUsage", ::MnemonicsUsageUpdater, ::MnemonicsUsageReader)
fun isKnownFactor(id: String): Boolean = id in IDS
private class Descriptor<out U : FactorUpdater, out R : FactorReader> private constructor(
override val factorId: String,
override val updaterFactory: (MutableDoubleFactor) -> U,
override val readerFactory: (DailyAggregatedDoubleFactor) -> R) : UserFactorDescription<U, R> {
companion object {
fun <U : FactorUpdater, R : FactorReader> register(factorId: String,
updaterFactory: (MutableDoubleFactor) -> U,
readerFactory: (DailyAggregatedDoubleFactor) -> R): UserFactorDescription<U, R> {
assert(!isKnownFactor(factorId)) { "Descriptor with id '$factorId' already exists" }
IDS.add(factorId)
return Descriptor(factorId, updaterFactory, readerFactory)
}
}
}
} | apache-2.0 | fd746372a5c7943f0985d815028bd647 | 53.275862 | 144 | 0.725771 | 4.871517 | false | false | false | false |
idea4bsd/idea4bsd | python/src/com/jetbrains/python/console/PydevConsoleExecuteActionHandler.kt | 1 | 8187 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.console
import com.intellij.codeInsight.hint.HintManager
import com.intellij.execution.console.LanguageConsoleView
import com.intellij.execution.console.ProcessBackedConsoleExecuteActionHandler
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.openapi.application.Result
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.util.TextRange
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.jetbrains.python.PythonFileType
import com.jetbrains.python.console.pydev.ConsoleCommunication
import com.jetbrains.python.console.pydev.ConsoleCommunicationListener
import java.awt.Font
/**
* @author traff
*/
open class PydevConsoleExecuteActionHandler(private val myConsoleView: LanguageConsoleView,
processHandler: ProcessHandler,
val consoleCommunication: ConsoleCommunication) : ProcessBackedConsoleExecuteActionHandler(processHandler, false), ConsoleCommunicationListener {
private val project = myConsoleView.project
private val myEnterHandler = PyConsoleEnterHandler()
private var myIpythonInputPromptCount = 1
var isEnabled = false
set(value) {
field = value
updateConsoleState()
}
init {
this.consoleCommunication.addCommunicationListener(this)
}
override fun processLine(text: String) {
executeMultiLine(text)
}
private fun executeMultiLine(text: String) {
val commandText = if (!text.endsWith("\n")) {
text + "\n"
}
else {
text
}
val singleLine = text.count { it == '\n' } < 2
sendLineToConsole(ConsoleCommunication.ConsoleCodeFragment(commandText, singleLine))
}
private fun sendLineToConsole(code: ConsoleCommunication.ConsoleCodeFragment) {
val consoleComm = consoleCommunication
if (!consoleComm.isWaitingForInput) {
executingPrompt()
}
if (ipythonEnabled && !consoleComm.isWaitingForInput && !code.getText().isBlank()) {
++myIpythonInputPromptCount;
}
consoleComm.execInterpreter(code) {}
}
private fun updateConsoleState() {
if (!isEnabled) {
executingPrompt()
}
else if (consoleCommunication.isWaitingForInput) {
waitingForInputPrompt()
}
else if (canExecuteNow()) {
if (consoleCommunication.needsMore()) {
more()
}
else {
inPrompt()
}
}
else {
executingPrompt()
}
}
fun inputReceived() {
if (consoleCommunication is PythonDebugConsoleCommunication) {
if (consoleCommunication.waitingForInput) {
consoleCommunication.waitingForInput = false
val console = myConsoleView
if (PyConsoleUtil.INPUT_PROMPT.equals(console.prompt) || PyConsoleUtil.HELP_PROMPT.equals(console.prompt)) {
console.prompt = PyConsoleUtil.ORDINARY_PROMPT
}
}
}
}
private fun inPrompt() {
if (ipythonEnabled) {
ipythonInPrompt()
}
else {
ordinaryPrompt()
}
}
private fun ordinaryPrompt() {
if (PyConsoleUtil.ORDINARY_PROMPT != myConsoleView.prompt) {
myConsoleView.prompt = PyConsoleUtil.ORDINARY_PROMPT
PyConsoleUtil.scrollDown(myConsoleView.currentEditor)
}
}
private val ipythonEnabled: Boolean
get() = PyConsoleUtil.getOrCreateIPythonData(myConsoleView.virtualFile).isIPythonEnabled
private fun ipythonInPrompt() {
myConsoleView.setPromptAttributes(object : ConsoleViewContentType("", ConsoleViewContentType.USER_INPUT_KEY) {
override fun getAttributes(): TextAttributes {
val attrs = super.getAttributes()
attrs.fontType = Font.PLAIN
return attrs
}
})
myConsoleView.prompt = "In[$myIpythonInputPromptCount]:"
PyConsoleUtil.scrollDown(myConsoleView.currentEditor)
}
private fun executingPrompt() {
myConsoleView.prompt = PyConsoleUtil.EXECUTING_PROMPT
}
private fun waitingForInputPrompt() {
if (PyConsoleUtil.INPUT_PROMPT != myConsoleView.prompt && PyConsoleUtil.HELP_PROMPT != myConsoleView.prompt) {
myConsoleView.prompt = PyConsoleUtil.INPUT_PROMPT
PyConsoleUtil.scrollDown(myConsoleView.currentEditor)
}
}
private fun more() {
val prompt = if (ipythonEnabled) {
PyConsoleUtil.IPYTHON_INDENT_PROMPT
}
else {
PyConsoleUtil.INDENT_PROMPT
}
if (prompt != myConsoleView.prompt) {
myConsoleView.prompt = prompt
PyConsoleUtil.scrollDown(myConsoleView.currentEditor)
}
}
override fun commandExecuted(more: Boolean) = updateConsoleState()
override fun inputRequested() = updateConsoleState()
val pythonIndent: Int
get() = CodeStyleSettingsManager.getSettings(project).getIndentSize(PythonFileType.INSTANCE)
val cantExecuteMessage: String
get() {
if (!isEnabled) {
return consoleIsNotEnabledMessage
}
else if (!canExecuteNow()) {
return prevCommandRunningMessage
}
else {
return "Can't execute the command"
}
}
override fun runExecuteAction(console: LanguageConsoleView) {
if (isEnabled) {
if (!canExecuteNow()) {
HintManager.getInstance().showErrorHint(console.consoleEditor, prevCommandRunningMessage)
}
else {
doRunExecuteAction(console)
}
}
else {
HintManager.getInstance().showErrorHint(console.consoleEditor, consoleIsNotEnabledMessage)
}
}
private fun stripEmptyLines(editor: Editor) {
object : WriteCommandAction<Nothing>(project) {
@Throws(Throwable::class)
override fun run(result: Result<Nothing>) {
val document = editor.document
val lineCount = document.lineCount
if (lineCount < 2)
return
for (count in lineCount - 1 downTo 1) {
val lineEndOffset = document.getLineEndOffset(count)
val lineStartOffset = document.getLineStartOffset(count)
val textRange = TextRange(lineStartOffset, lineEndOffset)
val text = document.getText(textRange)
if (text.isEmpty()) {
document.deleteString(lineStartOffset - 1, lineStartOffset)
}
else {
break
}
}
}
}.execute()
}
private fun doRunExecuteAction(console: LanguageConsoleView) {
val isComplete = myEnterHandler.handleEnterPressed(console.consoleEditor)
if (isComplete || consoleCommunication.isWaitingForInput) {
stripEmptyLines(myConsoleView.consoleEditor)
if (shouldCopyToHistory(console)) {
copyToHistoryAndExecute(console)
}
else {
processLine(myConsoleView.consoleEditor.document.text)
}
}
}
private fun copyToHistoryAndExecute(console: LanguageConsoleView) = super.runExecuteAction(console)
fun canExecuteNow(): Boolean = !consoleCommunication.isExecuting || consoleCommunication.isWaitingForInput
protected open val consoleIsNotEnabledMessage: String
get() = notEnabledMessage
companion object {
val prevCommandRunningMessage: String
get() = "Previous command is still running. Please wait or press Ctrl+C in console to interrupt."
val notEnabledMessage: String
get() = "Console is not enabled."
private fun shouldCopyToHistory(console: LanguageConsoleView): Boolean {
return !PyConsoleUtil.isPagingPrompt(console.prompt)
}
}
}
| apache-2.0 | 882097fed26ee3fe7d5da555021008dd | 28.44964 | 189 | 0.702089 | 4.917117 | false | false | false | false |
siosio/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/AppearanceConfigurable.kt | 1 | 20441 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.ui
import com.intellij.application.options.editor.CheckboxDescriptor
import com.intellij.application.options.editor.checkBox
import com.intellij.ide.GeneralSettings
import com.intellij.ide.IdeBundle.message
import com.intellij.ide.actions.QuickChangeLookAndFeel
import com.intellij.ide.ui.search.OptionDescription
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.PlatformEditorBundle
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager
import com.intellij.openapi.editor.colors.impl.EditorColorsManagerImpl
import com.intellij.openapi.help.HelpManager
import com.intellij.openapi.keymap.KeyMapBundle
import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty
import com.intellij.openapi.observable.properties.PropertyGraph
import com.intellij.openapi.options.BoundSearchableConfigurable
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.openapi.wm.impl.IdeFrameDecorator
import com.intellij.ui.ContextHelpLabel
import com.intellij.ui.FontComboBox
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.UIBundle
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.Label
import com.intellij.ui.layout.*
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.Font
import java.awt.RenderingHints
import java.awt.Window
import javax.swing.DefaultComboBoxModel
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JList
// @formatter:off
private val settings get() = UISettings.instance
private val generalSettings get() = GeneralSettings.getInstance()
private val lafManager get() = LafManager.getInstance()
private val cdShowToolWindowBars get() = CheckboxDescriptor(message("checkbox.show.tool.window.bars"), PropertyBinding({ !settings.hideToolStripes }, { settings.hideToolStripes = !it }), groupName = windowOptionGroupName)
private val cdShowToolWindowNumbers get() = CheckboxDescriptor(message("checkbox.show.tool.window.numbers"), settings::showToolWindowsNumbers, groupName = windowOptionGroupName)
private val cdEnableMenuMnemonics get() = CheckboxDescriptor(KeyMapBundle.message("enable.mnemonic.in.menu.check.box"), PropertyBinding({ !settings.disableMnemonics }, { settings.disableMnemonics = !it }), groupName = windowOptionGroupName)
private val cdEnableControlsMnemonics get() = CheckboxDescriptor(KeyMapBundle.message("enable.mnemonic.in.controls.check.box"), PropertyBinding({ !settings.disableMnemonicsInControls }, { settings.disableMnemonicsInControls = !it }), groupName = windowOptionGroupName)
private val cdSmoothScrolling get() = CheckboxDescriptor(message("checkbox.smooth.scrolling"), settings::smoothScrolling, groupName = uiOptionGroupName)
private val cdWidescreenToolWindowLayout get() = CheckboxDescriptor(message("checkbox.widescreen.tool.window.layout"), settings::wideScreenSupport, groupName = windowOptionGroupName)
private val cdLeftToolWindowLayout get() = CheckboxDescriptor(message("checkbox.left.toolwindow.layout"), settings::leftHorizontalSplit, groupName = windowOptionGroupName)
private val cdRightToolWindowLayout get() = CheckboxDescriptor(message("checkbox.right.toolwindow.layout"), settings::rightHorizontalSplit, groupName = windowOptionGroupName)
private val cdUseCompactTreeIndents get() = CheckboxDescriptor(message("checkbox.compact.tree.indents"), settings::compactTreeIndents, groupName = uiOptionGroupName)
private val cdShowTreeIndents get() = CheckboxDescriptor(message("checkbox.show.tree.indent.guides"), settings::showTreeIndentGuides, groupName = uiOptionGroupName)
private val cdDnDWithAlt get() = CheckboxDescriptor(message("dnd.with.alt.pressed.only"), settings::dndWithPressedAltOnly, groupName = uiOptionGroupName)
private val cdUseTransparentMode get() = CheckboxDescriptor(message("checkbox.use.transparent.mode.for.floating.windows"), PropertyBinding({ settings.state.enableAlphaMode }, { settings.state.enableAlphaMode = it }))
private val cdOverrideLaFFont get() = CheckboxDescriptor(message("checkbox.override.default.laf.fonts"), settings::overrideLafFonts)
private val cdUseContrastToolbars get() = CheckboxDescriptor(message("checkbox.acessibility.contrast.scrollbars"), settings::useContrastScrollbars)
private val cdMergeMainMenuWithWindowTitle get() = CheckboxDescriptor(message("checkbox.merge.main.menu.with.window.title"), settings::mergeMainMenuWithWindowTitle, groupName = windowOptionGroupName)
private val cdFullPathsInTitleBar get() = CheckboxDescriptor(message("checkbox.full.paths.in.window.header"), settings::fullPathsInWindowHeader)
private val cdShowMenuIcons get() = CheckboxDescriptor(message("checkbox.show.icons.in.menu.items"), settings::showIconsInMenus, groupName = windowOptionGroupName)
// @formatter:on
internal val appearanceOptionDescriptors: List<OptionDescription>
get() = listOf(
cdShowToolWindowBars,
cdShowToolWindowNumbers,
cdEnableMenuMnemonics,
cdEnableControlsMnemonics,
cdSmoothScrolling,
cdWidescreenToolWindowLayout,
cdLeftToolWindowLayout,
cdRightToolWindowLayout,
cdUseCompactTreeIndents,
cdShowTreeIndents,
cdDnDWithAlt,
cdFullPathsInTitleBar
).map(CheckboxDescriptor::asUiOptionDescriptor)
internal class AppearanceConfigurable : BoundSearchableConfigurable(message("title.appearance"), "preferences.lookFeel") {
private var shouldUpdateLaF = false
private val propertyGraph = PropertyGraph()
private val lafProperty = propertyGraph.graphProperty { lafManager.lookAndFeelReference }
private val syncThemeProperty = propertyGraph.graphProperty { lafManager.autodetect }
override fun createPanel(): DialogPanel {
lafProperty.afterChange({ QuickChangeLookAndFeel.switchLafAndUpdateUI(lafManager, lafManager.findLaf(it), true) }, disposable!!)
syncThemeProperty.afterChange ({ lafManager.autodetect = it }, disposable!!)
return panel {
blockRow {
fullRow {
label(message("combobox.look.and.feel"))
val theme = comboBox(lafManager.lafComboBoxModel, lafProperty, lafManager.lookAndFeelCellRenderer).
accessibleName(message("combobox.look.and.feel"))
val syncCheckBox = checkBox(message("preferred.theme.autodetect.selector"),
syncThemeProperty).withLargeLeftGap().
apply { component.isVisible = lafManager.autodetectSupported }
theme.enableIf(syncCheckBox.selected.not())
component(lafManager.settingsToolbar).visibleIf(syncCheckBox.selected).withLeftGap()
}.largeGapAfter()
fullRow {
val overrideLaF = checkBox(cdOverrideLaFFont)
.shouldUpdateLaF()
component(FontComboBox())
.withBinding(
{ it.fontName },
{ it, value -> it.fontName = value },
PropertyBinding({ if (settings.overrideLafFonts) settings.fontFace else JBFont.label().family },
{ settings.fontFace = it })
)
.shouldUpdateLaF()
.enableIf(overrideLaF.selected)
.accessibleName(cdOverrideLaFFont.name)
component(Label(message("label.font.size")))
.withLargeLeftGap()
.enableIf(overrideLaF.selected)
fontSizeComboBox({ if (settings.overrideLafFonts) settings.fontSize else JBFont.label().size },
{ settings.fontSize = it },
settings.fontSize)
.shouldUpdateLaF()
.enableIf(overrideLaF.selected)
.accessibleName(message("label.font.size"))
}
}
titledRow(message("title.accessibility")) {
fullRow {
val isOverridden = GeneralSettings.isSupportScreenReadersOverridden()
checkBox(message("checkbox.support.screen.readers"),
generalSettings::isSupportScreenReaders, generalSettings::setSupportScreenReaders,
comment = if (isOverridden) message("option.is.overridden.by.jvm.property", GeneralSettings.SUPPORT_SCREEN_READERS)
else null)
.enabled(!isOverridden)
commentNoWrap(message("support.screen.readers.comment"))
.withLargeLeftGap()
}
fullRow { checkBox(cdUseContrastToolbars) }
val supportedValues = ColorBlindness.values().filter { ColorBlindnessSupport.get(it) != null }
if (supportedValues.isNotEmpty()) {
val modelBinding = PropertyBinding({ settings.colorBlindness }, { settings.colorBlindness = it })
val onApply = {
// callback executed not when all changes are applied, but one component by one, so, reload later when everything were applied
ApplicationManager.getApplication().invokeLater(Runnable {
DefaultColorSchemesManager.getInstance().reload()
(EditorColorsManager.getInstance() as EditorColorsManagerImpl).schemeChangedOrSwitched(null)
})
}
fullRow {
if (supportedValues.size == 1) {
component(JBCheckBox(UIBundle.message("color.blindness.checkbox.text")))
.comment(UIBundle.message("color.blindness.checkbox.comment"))
.withBinding({ if (it.isSelected) supportedValues.first() else null },
{ it, value -> it.isSelected = value != null },
modelBinding)
.onApply(onApply)
}
else {
val enableColorBlindness = component(JBCheckBox(UIBundle.message("color.blindness.combobox.text")))
.applyToComponent { isSelected = modelBinding.get() != null }
component(ComboBox(supportedValues.toTypedArray()))
.enableIf(enableColorBlindness.selected)
.applyToComponent { renderer = SimpleListCellRenderer.create<ColorBlindness>("") { PlatformEditorBundle.message(it.key) } }
.comment(UIBundle.message("color.blindness.combobox.comment"))
.withBinding({ if (enableColorBlindness.component.isSelected) it.selectedItem as? ColorBlindness else null },
{ it, value -> it.selectedItem = value ?: supportedValues.first() },
modelBinding)
.onApply(onApply)
.accessibleName(UIBundle.message("color.blindness.checkbox.text"))
}
component(ActionLink(UIBundle.message("color.blindness.link.to.help"))
{ HelpManager.getInstance().invokeHelp("Colorblind_Settings") })
.withLargeLeftGap()
}
}
}
@Suppress("MoveLambdaOutsideParentheses") // this suggestion is wrong, see KT-40969
titledRow(message("group.ui.options")) {
val leftColumnControls = sequence<InnerCell.() -> Unit> {
yield({ checkBox(cdShowTreeIndents) })
yield({ checkBox(cdUseCompactTreeIndents) })
yield({ checkBox(cdEnableMenuMnemonics) })
yield({ checkBox(cdEnableControlsMnemonics) })
}
val rightColumnControls = sequence<InnerCell.() -> Unit> {
yield({
checkBox(cdSmoothScrolling)
ContextHelpLabel.create(message("checkbox.smooth.scrolling.description"))()
})
yield({ checkBox(cdDnDWithAlt) })
if (IdeFrameDecorator.isCustomDecorationAvailable()) {
yield({
val overridden = UISettings.isMergeMainMenuWithWindowTitleOverridden
checkBox(cdMergeMainMenuWithWindowTitle).enabled(!overridden)
if (overridden) {
ContextHelpLabel.create(
message("option.is.overridden.by.jvm.property", UISettings.MERGE_MAIN_MENU_WITH_WINDOW_TITLE_PROPERTY))()
}
commentNoWrap(message("checkbox.merge.main.menu.with.window.title.comment")).withLargeLeftGap()
})
}
yield({ checkBox(cdFullPathsInTitleBar) })
yield({ checkBox(cdShowMenuIcons) })
}
// Since some of the columns have variable number of items, enumerate them in a loop, while moving orphaned items from the right
// column to the left one:
val leftIt = leftColumnControls.iterator()
val rightIt = rightColumnControls.iterator()
while (leftIt.hasNext() || rightIt.hasNext()) {
when {
leftIt.hasNext() && rightIt.hasNext() -> twoColumnRow(leftIt.next(), rightIt.next())
leftIt.hasNext() -> twoColumnRow(leftIt.next()) { placeholder() }
rightIt.hasNext() -> twoColumnRow(rightIt.next()) { placeholder() } // move from right to left
}
}
val backgroundImageAction = ActionManager.getInstance().getAction("Images.SetBackgroundImage")
if (backgroundImageAction != null) {
fullRow {
buttonFromAction(message("background.image.button"), ActionPlaces.UNKNOWN, backgroundImageAction)
.applyToComponent { isEnabled = ProjectManager.getInstance().openProjects.isNotEmpty() }
}
}
}
if (Registry.`is`("ide.transparency.mode.for.windows") &&
WindowManagerEx.getInstanceEx().isAlphaModeSupported) {
val settingsState = settings.state
titledRow(message("group.transparency")) {
lateinit var checkbox: CellBuilder<JBCheckBox>
fullRow { checkbox = checkBox(cdUseTransparentMode) }
fullRow {
label(message("label.transparency.delay.ms"))
intTextField(settingsState::alphaModeDelay, columns = 4)
}.enableIf(checkbox.selected)
fullRow {
label(message("label.transparency.ratio"))
slider(0, 100, 10, 50)
.labelTable {
put(0, JLabel("0%"))
put(50, JLabel("50%"))
put(100, JLabel("100%"))
}
.withValueBinding(
PropertyBinding(
{ (settingsState.alphaModeRatio * 100f).toInt() },
{ settingsState.alphaModeRatio = it / 100f }
)
)
.applyToComponent {
addChangeListener { toolTipText = "${value}%" }
}
}.enableIf(checkbox.selected)
}
}
titledRow(message("group.antialiasing.mode")) {
twoColumnRow(
{
label(message("label.text.antialiasing.scope.ide"))
val ideAAOptions =
if (!AntialiasingType.canUseSubpixelAAForIDE())
arrayOf(AntialiasingType.GREYSCALE, AntialiasingType.OFF)
else
AntialiasingType.values()
comboBox(DefaultComboBoxModel(ideAAOptions), settings::ideAAType, renderer = AAListCellRenderer(false))
.shouldUpdateLaF()
.accessibleName(message("label.text.antialiasing.scope.ide"))
.onApply {
for (w in Window.getWindows()) {
for (c in UIUtil.uiTraverser(w).filter(JComponent::class.java)) {
GraphicsUtil.setAntialiasingType(c, AntialiasingType.getAAHintForSwingComponent())
}
}
}
},
{
label(message("label.text.antialiasing.scope.editor"))
val editorAAOptions =
if (!AntialiasingType.canUseSubpixelAAForEditor())
arrayOf(AntialiasingType.GREYSCALE, AntialiasingType.OFF)
else
AntialiasingType.values()
comboBox(DefaultComboBoxModel(editorAAOptions), settings::editorAAType, renderer = AAListCellRenderer(true))
.shouldUpdateLaF()
.accessibleName(message("label.text.antialiasing.scope.editor"))
}
)
}
titledRow(message("group.window.options")) {
twoColumnRow(
{ checkBox(cdShowToolWindowBars) },
{ checkBox(cdShowToolWindowNumbers) }
)
twoColumnRow(
{ checkBox(cdLeftToolWindowLayout) },
{ checkBox(cdRightToolWindowLayout) }
)
row {
checkBox(cdWidescreenToolWindowLayout)
ContextHelpLabel.create(message("checkbox.widescreen.tool.window.layout.description"))()
}
}
titledRow(message("group.presentation.mode")) {
fullRow {
label(message("presentation.mode.fon.size"))
fontSizeComboBox({ settings.presentationModeFontSize },
{ settings.presentationModeFontSize = it },
settings.presentationModeFontSize)
.shouldUpdateLaF()
}
}
}
}
override fun apply() {
val uiSettingsChanged = isModified
shouldUpdateLaF = false
super.apply()
if (shouldUpdateLaF) {
LafManager.getInstance().updateUI()
}
if (uiSettingsChanged) {
UISettings.instance.fireUISettingsChanged()
EditorFactory.getInstance().refreshAllEditors()
}
}
private fun <T : JComponent> CellBuilder<T>.shouldUpdateLaF(): CellBuilder<T> = onApply { shouldUpdateLaF = true }
}
fun Cell.fontSizeComboBox(getter: () -> Int, setter: (Int) -> Unit, defaultValue: Int): CellBuilder<ComboBox<String>> {
val model = DefaultComboBoxModel(UIUtil.getStandardFontSizes())
val modelBinding: PropertyBinding<String?> = PropertyBinding({ getter().toString() }, { setter(getIntValue(it, defaultValue)) })
return component(ComboBox(model))
.accessibleName(message("presentation.mode.fon.size"))
.applyToComponent {
isEditable = true
renderer = SimpleListCellRenderer.create("") { it.toString() }
selectedItem = modelBinding.get()
}
.withBinding(
{ component -> component.editor.item as String? },
{ component, value -> component.setSelectedItem(value) },
modelBinding
)
}
private fun RowBuilder.twoColumnRow(column1: InnerCell.() -> Unit, column2: InnerCell.() -> Unit): Row = row {
cell {
column1()
}
placeholder().withLeftGap(JBUI.scale(60))
cell {
column2()
}
placeholder().constraints(growX, pushX)
}
private fun getIntValue(text: String?, defaultValue: Int): Int {
if (text != null && text.isNotBlank()) {
val value = text.toIntOrNull()
if (value != null && value > 0) return value
}
return defaultValue
}
private class AAListCellRenderer(private val myUseEditorFont: Boolean) : SimpleListCellRenderer<AntialiasingType>() {
private val SUBPIXEL_HINT = GraphicsUtil.createAATextInfo(RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB)
private val GREYSCALE_HINT = GraphicsUtil.createAATextInfo(RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
override fun customize(list: JList<out AntialiasingType>, value: AntialiasingType, index: Int, selected: Boolean, hasFocus: Boolean) {
val aaType = when (value) {
AntialiasingType.SUBPIXEL -> SUBPIXEL_HINT
AntialiasingType.GREYSCALE -> GREYSCALE_HINT
AntialiasingType.OFF -> null
}
GraphicsUtil.setAntialiasingType(this, aaType)
if (myUseEditorFont) {
val scheme = EditorColorsManager.getInstance().globalScheme
font = Font(scheme.editorFontName, Font.PLAIN, scheme.editorFontSize)
}
text = value.presentableName
}
}
| apache-2.0 | 621ee8970e0b0fc36b0378ea8d73062f | 49.596535 | 284 | 0.671542 | 5.007594 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/references/KtDestructuringDeclarationReferenceDescriptorsImpl.kt | 1 | 1715 | // 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.references
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.psi.KtDestructuringDeclarationEntry
import org.jetbrains.kotlin.resolve.BindingContext
class KtDestructuringDeclarationReferenceDescriptorsImpl(
element: KtDestructuringDeclarationEntry
) : KtDestructuringDeclarationReference(element), KtDescriptorsBasedReference {
override fun isReferenceTo(element: PsiElement): Boolean =
super<KtDescriptorsBasedReference>.isReferenceTo(element)
override fun getTargetDescriptors(context: BindingContext): Collection<DeclarationDescriptor> {
return listOfNotNull(
context[BindingContext.VARIABLE, element],
context[BindingContext.COMPONENT_RESOLVED_CALL, element]?.candidateDescriptor
)
}
override fun resolve() = multiResolve(false).asSequence()
.map { it.element }
.first { it is KtDestructuringDeclarationEntry }
override fun getRangeInElement() = TextRange(0, element.textLength)
override fun canRename(): Boolean {
val bindingContext = expression.analyze() //TODO: should it use full body resolve?
return resolveToDescriptors(bindingContext).all {
it is CallableMemberDescriptor && it.kind == CallableMemberDescriptor.Kind.SYNTHESIZED
}
}
}
| apache-2.0 | 0dbd40d7f0f195d9be1e39e0cd1ce737 | 44.131579 | 158 | 0.770845 | 5.410095 | false | false | false | false |
siosio/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunConfigurationSettings.kt | 1 | 6454 | // 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.idea.maven.execution
import com.intellij.execution.util.ProgramParametersUtil.expandPathAndMacros
import com.intellij.openapi.project.Project
import com.intellij.util.xmlb.XmlSerializer
import com.intellij.util.xmlb.annotations.Transient
import org.jdom.Element
import org.jetbrains.idea.maven.execution.MavenExecutionOptions.*
import org.jetbrains.idea.maven.project.MavenGeneralSettings
import org.jetbrains.idea.maven.project.MavenProjectsManager
@Suppress("DuplicatedCode")
class MavenRunConfigurationSettings : Cloneable {
/** @see MavenRunnerParameters */
var commandLine: String = ""
var workingDirectory: String = ""
var profilesMap: Map<String, Boolean> = HashMap()
var isResolveToWorkspace: Boolean = false
/** @see org.jetbrains.idea.maven.project.MavenGeneralSettings */
var mavenHome: String? = null
var userSettings: String? = null
var localRepository: String? = null
var threads: String? = null
var isWorkOffline: Boolean = false
var checksumPolicy: ChecksumPolicy? = null
var outputLevel: LoggingLevel? = null
var isUsePluginRegistry: Boolean = false
var isPrintErrorStackTraces: Boolean = false
var isAlwaysUpdateSnapshots: Boolean = false
var failureBehavior: FailureMode? = null
var isExecuteGoalsRecursive: Boolean = false
/** @see MavenRunnerSettings */
var jreName: String? = null
var vmOptions: String? = null
var environment: Map<String, String> = HashMap()
var isPassParentEnvs: Boolean = true
var isSkipTests: Boolean = false
public override fun clone(): MavenRunConfigurationSettings {
val clone = super.clone() as MavenRunConfigurationSettings
clone.setSettings(this)
return clone
}
private fun setSettings(settings: MavenRunConfigurationSettings) {
commandLine = settings.commandLine
workingDirectory = settings.workingDirectory
profilesMap = settings.profilesMap
isResolveToWorkspace = settings.isResolveToWorkspace
mavenHome = settings.mavenHome
userSettings = settings.userSettings
localRepository = settings.localRepository
threads = settings.threads
isWorkOffline = settings.isWorkOffline
checksumPolicy = settings.checksumPolicy
outputLevel = settings.outputLevel
isUsePluginRegistry = settings.isUsePluginRegistry
isPrintErrorStackTraces = settings.isPrintErrorStackTraces
isAlwaysUpdateSnapshots = settings.isAlwaysUpdateSnapshots
failureBehavior = settings.failureBehavior
isExecuteGoalsRecursive = settings.isExecuteGoalsRecursive
jreName = settings.jreName
vmOptions = settings.vmOptions
environment = settings.environment
isPassParentEnvs = settings.isPassParentEnvs
isSkipTests = settings.isSkipTests
}
@Transient
fun getGeneralSettings(project: Project): MavenGeneralSettings? {
val projectsManager = MavenProjectsManager.getInstance(project)
val originalSettings = projectsManager.generalSettings
val settings = originalSettings.clone()
mavenHome?.let { settings.mavenHome = it }
userSettings?.let { settings.setUserSettingsFile(expandPathAndMacros(it, null, project)) }
localRepository?.let { settings.setLocalRepository(expandPathAndMacros(it, null, project)) }
threads?.let { settings.threads = it }
isWorkOffline.let { settings.isWorkOffline = it }
checksumPolicy?.let { settings.checksumPolicy = it }
outputLevel?.let { settings.outputLevel = it }
isUsePluginRegistry.let { settings.isUsePluginRegistry = it }
isPrintErrorStackTraces.let { settings.isPrintErrorStackTraces = it }
isAlwaysUpdateSnapshots.let { settings.isAlwaysUpdateSnapshots = it }
failureBehavior?.let { settings.failureBehavior = it }
isExecuteGoalsRecursive.let { settings.isNonRecursive = !it }
return if (settings == originalSettings) null else settings
}
@Transient
fun setGeneralSettings(settings: MavenGeneralSettings) {
mavenHome = settings.mavenHome
userSettings = settings.userSettingsFile
localRepository = settings.localRepository
threads = settings.threads
isWorkOffline = settings.isWorkOffline
checksumPolicy = settings.checksumPolicy
outputLevel = settings.outputLevel
isUsePluginRegistry = settings.isUsePluginRegistry
isPrintErrorStackTraces = settings.isPrintErrorStackTraces
isAlwaysUpdateSnapshots = settings.isAlwaysUpdateSnapshots
failureBehavior = settings.failureBehavior
isExecuteGoalsRecursive = !settings.isNonRecursive
}
@Transient
fun getRunnerSettings(project: Project): MavenRunnerSettings? {
val mavenRunner = MavenRunner.getInstance(project)
val originalSettings = mavenRunner.settings
val settings = originalSettings.clone()
jreName?.let { settings.setJreName(it) }
vmOptions?.let { settings.setVmOptions(expandPathAndMacros(it, null, project)) }
environment.let { settings.environmentProperties = it }
isPassParentEnvs.let { settings.isPassParentEnv = it }
isSkipTests.let { settings.isSkipTests = it }
return if (settings == originalSettings) null else settings
}
@Transient
fun setRunnerSettings(settings: MavenRunnerSettings) {
jreName = settings.jreName
vmOptions = settings.vmOptions
environment = settings.environmentProperties
isPassParentEnvs = settings.isPassParentEnv
isSkipTests = settings.isSkipTests
}
@Transient
fun getRunnerParameters(): MavenRunnerParameters {
val parameters = MavenRunnerParameters()
parameters.commandLine = commandLine
parameters.workingDirPath = workingDirectory
parameters.profilesMap = profilesMap
parameters.isResolveToWorkspace = isResolveToWorkspace
return parameters
}
@Transient
fun setRunnerParameters(parameters: MavenRunnerParameters) {
commandLine = parameters.commandLine
workingDirectory = parameters.workingDirPath
profilesMap = parameters.profilesMap
isResolveToWorkspace = parameters.isResolveToWorkspace
}
fun readExternal(element: Element) {
val settingsElement = element.getChild(MavenRunConfigurationSettings::class.simpleName) ?: return
setSettings(XmlSerializer.deserialize(settingsElement, MavenRunConfigurationSettings::class.java))
}
fun writeExternal(element: Element) {
element.addContent(XmlSerializer.serialize(this))
}
} | apache-2.0 | 4a1f4634d7b9153e33aacab1637f93c2 | 39.85443 | 158 | 0.777347 | 4.834457 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/maven/src/org/jetbrains/kotlin/idea/maven/KotlinMavenArchetypesProvider.kt | 1 | 4593 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.maven
import com.google.gson.JsonElement
import com.google.gson.JsonParser
import com.intellij.openapi.application.ApplicationManager
import com.intellij.util.net.HttpConfigurable
import org.jetbrains.idea.maven.dom.MavenVersionComparable
import org.jetbrains.idea.maven.indices.MavenArchetypesProvider
import org.jetbrains.idea.maven.model.MavenArchetype
import org.jetbrains.kotlin.idea.KotlinPluginUtil
import org.jetbrains.kotlin.utils.ifEmpty
import java.net.HttpURLConnection
import java.net.URLEncoder
import java.util.concurrent.TimeUnit
class KotlinMavenArchetypesProvider(private val kotlinPluginVersion: String, private val predefinedInternalMode: Boolean?) :
MavenArchetypesProvider {
@Suppress("unused")
constructor() : this(KotlinPluginUtil.getPluginVersion(), null)
companion object {
private val VERSIONS_LIST_URL = mavenSearchUrl("org.jetbrains.kotlin", packaging = "maven-archetype", rowsLimit = 1000)
private fun mavenSearchUrl(
group: String,
artifactId: String? = null,
version: String? = null,
packaging: String? = null,
rowsLimit: Int = 20
): String {
val q = listOf(
"g" to group,
"a" to artifactId,
"v" to version,
"p" to packaging
)
.filter { it.second != null }.joinToString(separator = " AND ") { "${it.first}:\"${it.second}\"" }
return "https://search.maven.org/solrsearch/select?q=${q.encodeURL()}&core=gav&rows=$rowsLimit&wt=json"
}
private fun String.encodeURL() = URLEncoder.encode(this, "UTF-8")
}
private val versionPrefix by lazy { versionPrefix(kotlinPluginVersion) }
private val fallbackVersion = "1.0.3"
private val internalMode: Boolean
get() = predefinedInternalMode ?: ApplicationManager.getApplication().isInternal
private val archetypesBlocking by lazy {
try {
loadVersions().ifEmpty { fallbackArchetypes() }
} catch (t: Throwable) {
fallbackArchetypes()
}
}
override fun getArchetypes() = archetypesBlocking.toMutableList()
private fun fallbackArchetypes() =
listOf("kotlin-archetype-jvm", "kotlin-archetype-js")
.map { MavenArchetype("org.jetbrains.kotlin", it, fallbackVersion, null, null) }
private fun loadVersions(): List<MavenArchetype> {
return connectAndApply(VERSIONS_LIST_URL) { urlConnection ->
urlConnection.inputStream.bufferedReader().use { reader ->
extractVersions(JsonParser().parse(reader))
}
}
}
fun extractVersions(root: JsonElement) =
root.asJsonObject.get("response")
.asJsonObject.get("docs")
.asJsonArray
.map { it.asJsonObject }
.map { MavenArchetype(it.get("g").asString, it.get("a").asString, it.get("v").asString, null, null) }
.let { versions ->
val prefix = versionPrefix
when {
internalMode || prefix == null -> versions
else -> versions.filter { it.version?.startsWith(prefix) ?: false }.ifEmpty { versions }
}
.groupBy { it.groupId + ":" + it.artifactId + ":" + versionPrefix(it.version) }
.mapValues { chooseVersion(it.value) }
.mapNotNull { it.value }
}
private fun chooseVersion(versions: List<MavenArchetype>): MavenArchetype? {
return versions.maxByOrNull { MavenVersionComparable(it.version) }
}
private fun <R> connectAndApply(url: String, timeoutSeconds: Int = 15, block: (HttpURLConnection) -> R): R {
return HttpConfigurable.getInstance().openHttpConnection(url).use { urlConnection ->
val timeout = TimeUnit.SECONDS.toMillis(timeoutSeconds.toLong()).toInt()
urlConnection.connectTimeout = timeout
urlConnection.readTimeout = timeout
urlConnection.connect()
block(urlConnection)
}
}
private fun <R> HttpURLConnection.use(block: (HttpURLConnection) -> R): R =
try {
block(this)
} finally {
disconnect()
}
private fun versionPrefix(version: String) = """^\d+\.\d+\.""".toRegex().find(version)?.value
}
| apache-2.0 | 0d07a3457282212edb6299498b5cca61 | 38.594828 | 158 | 0.631831 | 4.60682 | false | false | false | false |
vyo/twig | src/main/kotlin/io/github/vyo/twig/logger/Logger.kt | 1 | 10867 | package io.github.vyo.twig.logger
import io.github.vyo.twig.appender.Appender
import io.github.vyo.twig.appender.ConsoleAppender
import nl.komponents.kovenant.Kovenant
import nl.komponents.kovenant.Promise
import nl.komponents.kovenant.task
import nl.komponents.kovenant.disruptor.queue.disruptorWorkQueue
import java.io.PrintWriter
import java.io.StringWriter
import java.lang.management.ManagementFactory
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
/**
* Default logger implementation for Twig
*
* Created by Manuel Weidmann on 24.11.2015.
*/
open class Logger @JvmOverloads constructor(val caller: Any,
var appender: Appender = Logger.global.appender,
var level: Level = Logger.global.level,
var serialiser: (any: Any) -> String = Logger.global.simpleSerialiser) {
companion object global {
private val TWIG_LEVEL = "TWIG_LEVEL"
private val TWIG_WORKERS = "TWIG_WORKERS"
private val TWIG_QUEUE = "TWIG_QUEUE"
private val TWIG_EXPANSION_LEVEL = "TWIG_EXPANSION_LEVEL"
private val TWIG_EXPANSION_DEPTH = "TWIG_EXPANSION_DEPTH"
val simpleSerialiser = { any: Any ->
when (any) {
is Boolean,
is Double,
is Float,
is Long,
is Int,
is Short,
is Byte,
is Char -> simplePrimitiveSerialiser(any)
is Array<*> -> simpleArraySerialiser(any)
is Collection<*> -> simpleCollectionSerialiser(any)
else -> "\"${escapeSpecialChars(any.toString())}\""
}
}
private fun simplePrimitiveSerialiser(any: Any): String {
return "${any.toString()}"
}
private fun simpleArraySerialiser(array: Array<*>): String {
var string = "["
for (element: Any? in array) {
if (element is Any) {
string += simpleSerialiser(element)
string += ","
}
}
string += "]"
return string.replace(",]", "]")
}
private fun simpleCollectionSerialiser(collection: Collection<*>): String {
var string = "["
for (element: Any? in collection) {
if (element is Any) {
string += simpleSerialiser(element)
string += ","
}
}
string += "]"
return string.replace(",]", "]")
}
var appender: Appender = ConsoleAppender()
set(value) {
field = value
logger.appender = value
logger.info("global appender $appender")
}
var level: Level = Level.INFO
set(value) {
field = value
logger.info("global log level $level")
}
var serialiser: (any: Any) -> String = simpleSerialiser
var expansionLevel = Level.DEBUG
set(value) {
field = value
logger.info("global throwable expansion level $expansionLevel")
}
var expansionDepth = 50
set(value) {
field = value
logger.info("global throwable expansion depth $expansionDepth")
}
private val processInfo: String = ManagementFactory.getRuntimeMXBean().name
private val pid: Int = Integer.parseInt(processInfo.split('@')[0])
private val hostName: String = processInfo.split('@')[1]
private val timeZone: TimeZone = TimeZone.getTimeZone("UTC")
private val isoFormat: DateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
private val logger: Logger = Logger("twig")
private fun escapeSpecialChars(string: String): String {
var escapedString: String = string
escapedString = escapedString.replace("\\", "\\\\")
escapedString = escapedString.replace("\n", "\\n")
escapedString = escapedString.replace("\r", "\\r")
escapedString = escapedString.replace("\b", "\\b")
escapedString = escapedString.replace("\t", "\\t")
escapedString = escapedString.replace("\"", "\\\"")
return escapedString
}
init {
isoFormat.timeZone = timeZone
val queue: Int
val workers: Int
val levelEnv: String? = System.getenv(TWIG_LEVEL)
try {
if (levelEnv is String) {
level = Level.valueOf(levelEnv)
}
} catch (exception: IllegalArgumentException) {
level = Level.INFO
}
val queueEnv: String? = System.getenv(TWIG_QUEUE)
if (queueEnv is String && Integer.parseInt(queueEnv) is Int) {
queue = Integer.parseInt(queueEnv)
} else {
queue = 1024
}
val workerEnv: String? = System.getenv(TWIG_WORKERS)
if (workerEnv is String && Integer.parseInt(workerEnv) is Int) {
workers = Integer.parseInt(workerEnv)
} else {
workers = Runtime.getRuntime().availableProcessors()
}
Kovenant.context {
callbackContext {
dispatcher {
concurrentTasks = workers
workQueue = disruptorWorkQueue(capacity = queue)
}
}
}
val expansionLevelEnv: String? = System.getenv(TWIG_EXPANSION_LEVEL)
try {
if (expansionLevelEnv is String) {
expansionLevel = Level.valueOf(expansionLevelEnv)
}
} catch (exception: IllegalArgumentException) {
level = Level.DEBUG
}
val expansionDepthEnv: String? = System.getenv(TWIG_EXPANSION_DEPTH)
if (expansionDepthEnv is String && Integer.parseInt(expansionDepthEnv) is Int) {
expansionDepth = Integer.parseInt(expansionDepthEnv)
} else {
expansionDepth = 50
}
logger.info("logging worker count: $workers")
logger.info("logging work queue size: $queue")
logger.info("global log level: $level")
logger.info("throwable expansion level: $expansionLevel")
logger.info("throwable expansion depth: $expansionDepth")
}
}
fun log(level: Level, message: Any, vararg customMessages: Pair<String, Any>): Promise<Unit, Exception> {
if (level < this.level) return task { }
val thread: Thread = java.lang.Thread.currentThread()
val time: String = isoFormat.format(Date(System.currentTimeMillis()))
if (expansionLevel >= level && message is Throwable) {
val stacktraceSize = Math.min(message.stackTrace.size, expansionDepth)
val stacktrace = Arrays.copyOf(message.stackTrace, stacktraceSize)
val adjustedCustomMessages = Arrays.copyOf(customMessages, customMessages.size + 1)
adjustedCustomMessages[customMessages.size] = Pair("stacktrace", stacktrace)
return log(level, "$message", *adjustedCustomMessages)
}
return task {
var entry: String = "{${serialiser("hostname")}:${serialiser(hostName)}," +
"${serialiser("pid")}:${serialiser(pid)}," +
"${serialiser("thread")}:${serialiser(thread)}," +
"${serialiser("time")}:${serialiser(time)}," +
"${serialiser("level")}:${serialiser(level.toInt())}," +
"${serialiser("name")}:${serialiser(caller)}," +
"${serialiser("msg")}:${serialiser(message)}"
for (customMessage in customMessages) {
entry += ",${serialiser(customMessage.first)}:${serialiser(customMessage.second)}"
}
entry += ",${serialiser("v")}:${serialiser(0)}}"
appender.write(entry)
} fail {
//get the stacktrace
val writer: StringWriter = StringWriter()
it.printStackTrace(PrintWriter(writer))
val stacktrace = serialiser(writer.toString())
var entry: String = "{${serialiser("hostname")}:${serialiser(hostName)}," +
"${serialiser("pid")}:${serialiser(pid)}," +
"${serialiser("thread")}:${serialiser(thread)}," +
"${serialiser("time")}:${serialiser(isoFormat.format(Date(System.currentTimeMillis())))}," +
"${serialiser("level")}:${serialiser(Level.FATAL.toInt())}" +
"${serialiser("name")}:${serialiser(this)}," +
"${serialiser("msg")}:${serialiser("logging exception: ${it.javaClass}")}," +
"${serialiser("exception message")}:${serialiser("${it.message}")}," +
"${serialiser("exception stacktrace")}:${serialiser(stacktrace)}," +
"${serialiser("original time")}:${serialiser(time)}," +
"${serialiser("original level")}:${serialiser(level.toInt())}," +
"${serialiser("original name")}:${serialiser(caller)}," +
"${serialiser("original msg")}:${serialiser(message)}"
for (customMessage in customMessages) {
entry += ",${serialiser("original " + customMessage.first)}:${serialiser(customMessage.second)}"
}
entry += ",${serialiser("v")}:${serialiser(0)}}"
System.err.println(entry)
}
}
fun trace(message: Any, vararg customMessages: Pair<String, Any>): Promise<Unit, Exception> {
return log(Level.TRACE, message, *customMessages)
}
fun debug(message: Any, vararg customMessages: Pair<String, Any>): Promise<Unit, Exception> {
return log(Level.DEBUG, message, *customMessages)
}
fun info(message: Any, vararg customMessages: Pair<String, Any>): Promise<Unit, Exception> {
return log(Level.INFO, message, *customMessages)
}
fun warn(message: Any, vararg customMessages: Pair<String, Any>): Promise<Unit, Exception> {
return log(Level.WARN, message, *customMessages)
}
fun error(message: Any, vararg customMessages: Pair<String, Any>): Promise<Unit, Exception> {
return log(Level.ERROR, message, *customMessages)
}
fun fatal(message: Any, vararg customMessages: Pair<String, Any>): Promise<Unit, Exception> {
return log(Level.FATAL, message, *customMessages)
}
}
| isc | f5d6a38886df30d9fea324354164bedf | 37.810714 | 116 | 0.551578 | 4.838379 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.