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
trevjonez/Kontrast
unitTestClient/src/main/kotlin/com/trevjonez/kontrast/Pixel.kt
1
1389
/* * Copyright 2017 Trevor Jones * * 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.trevjonez.kontrast import java.lang.Math.abs data class Pixel(val r: Int, val g: Int, val b: Int, val a: Int) { companion object { val EMPTY = Pixel(0, 0, 0, 0) val RED = Pixel(255, 0, 0, 255) val TRANS_BLACK = Pixel(1, 1, 1, 128) val MIX_FACTOR = .5F val INV_MIX_FACTOR = -.5F } infix fun mixWith(other: Pixel): Pixel { return Pixel( ((r * MIX_FACTOR) - (abs(r - other.r) / 2 * INV_MIX_FACTOR)).toInt(), ((g * MIX_FACTOR) - (abs(g - other.g) / 2 * INV_MIX_FACTOR)).toInt(), ((b * MIX_FACTOR) - (abs(b - other.b) / 2 * INV_MIX_FACTOR)).toInt(), ((a * MIX_FACTOR) - (abs(a - other.a) / 2 * INV_MIX_FACTOR)).toInt()) } }
apache-2.0
0f305973fd9ca303ac877f6d97eaacf7
35.578947
85
0.596832
3.455224
false
false
false
false
lttng/lttng-scope
jabberwocky-core/src/main/kotlin/com/efficios/jabberwocky/analysis/eventstats/EventStatsTotalsSeriesProvider.kt
1
2501
/* * Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]> * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.efficios.jabberwocky.analysis.eventstats import ca.polymtl.dorsal.libdelorean.exceptions.AttributeNotFoundException import ca.polymtl.dorsal.libdelorean.statevalue.IntegerStateValue import com.efficios.jabberwocky.views.common.FlatUIColors import com.efficios.jabberwocky.views.xychart.model.provider.statesystem.StateSystemXYChartSeriesProvider import com.efficios.jabberwocky.views.xychart.model.render.XYChartRender import com.efficios.jabberwocky.views.xychart.model.render.XYChartSeries import java.util.concurrent.FutureTask class EventStatsTotalsSeriesProvider(modelProvider: EventStatsXYChartProvider) : StateSystemXYChartSeriesProvider(EVENTS_TOTAL_SERIES, modelProvider) { companion object { private val EVENTS_TOTAL_SERIES = XYChartSeries("Events total", FlatUIColors.DARK_BLUE, XYChartSeries.LineStyle.INTEGRAL) } override fun fillSeriesRender(timestamps: List<Long>, task: FutureTask<*>?): List<XYChartRender.DataPoint>? { val ss = modelProvider.stateSystem if (ss == null || (task?.isCancelled == true)) { return null } val quark: Int = try { ss.getQuarkAbsolute(EventStatsAnalysis.TOTAL_ATTRIBUTE) } catch (e: AttributeNotFoundException) { return null } // TODO Support renders with less than 3 timestamps? if (timestamps.size < 3) throw IllegalArgumentException("XY Chart renders need a minimum of 3 datapoints, was $timestamps") val tsStateValues = ArrayList<Long>() for (ts in timestamps) { val queryTs = ts.coerceIn(ss.startTime, ss.currentEndTime) val sv = ss.querySingleState(queryTs, quark).stateValue tsStateValues.add(if (sv.isNull) 0L else (sv as IntegerStateValue).value.toLong()) } val dataPoints = ArrayList<XYChartRender.DataPoint>() for (i in 0 until timestamps.size - 1) { val countDiffUntilNext = tsStateValues[i + 1] - tsStateValues[i] val ts = timestamps[i] dataPoints.add(XYChartRender.DataPoint(ts, countDiffUntilNext)) } return dataPoints } }
epl-1.0
fddf6b4a2b6163c79aaf6a6df1546c3b
38.698413
151
0.718912
4.260647
false
false
false
false
yschimke/oksocial
src/main/kotlin/com/baulsupp/okurl/authenticator/AuthenticatingInterceptor.kt
1
6557
package com.baulsupp.okurl.authenticator import com.baulsupp.okurl.credentials.CredentialsStore import com.baulsupp.okurl.credentials.NoToken import com.baulsupp.okurl.credentials.Token import com.baulsupp.okurl.credentials.TokenValue import com.baulsupp.okurl.services.ServiceLibrary import kotlinx.coroutines.runBlocking import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.Interceptor import okhttp3.Response import java.util.logging.Logger // TODO log bad tags? fun Interceptor.Chain.token() = request().tag(Token::class.java) ?: NoToken suspend fun <T> credentials( tokenSet: Token, interceptor: AuthInterceptor<T>, credentialsStore: CredentialsStore ): T? { return when (tokenSet) { is TokenValue -> interceptor.serviceDefinition.castToken(tokenSet.token) is NoToken -> null else -> credentialsStore.get(interceptor.serviceDefinition, tokenSet) ?: interceptor.defaultCredentials() } } class AuthenticatingInterceptor( private val credentialsStore: CredentialsStore, override val services: List<AuthInterceptor<*>> = defaultServices() ) : Interceptor, ServiceLibrary { override fun intercept(chain: Interceptor.Chain): Response { return runBlocking { val firstInterceptor = services.find { it.supportsUrl(chain.request().url, credentialsStore) } logger.fine { "Matching interceptor: $firstInterceptor" } if (firstInterceptor != null) { intercept(firstInterceptor, chain) } else { chain.proceed(chain.request()) } } } override fun knownServices(): Set<String> { return services.map { it.name() }.toSortedSet() } suspend fun <T> intercept(interceptor: AuthInterceptor<T>, chain: Interceptor.Chain): Response { val tokenSet = chain.token() val credentials = credentials(tokenSet, interceptor, credentialsStore) return interceptor.intercept(chain, credentials, credentialsStore) } fun getByName(authName: String): AuthInterceptor<*>? = services.firstOrNull { n -> n.name() == authName } fun getByUrl(url: String): AuthInterceptor<*>? { val httpUrl = url.toHttpUrlOrNull() return httpUrl?.run { runBlocking { services.find { it.supportsUrl(httpUrl, credentialsStore) } } } } override fun findAuthInterceptor(name: String): AuthInterceptor<*>? = getByName(name) ?: getByUrl( name) fun names(): List<String> = services.map { it.name() } companion object { val logger: Logger = Logger.getLogger(AuthenticatingInterceptor::class.java.name) @Suppress("UNCHECKED_CAST") fun defaultServices(): List<AuthInterceptor<*>> = listOf( com.baulsupp.okurl.services.atlassian.AtlassianAuthInterceptor(), com.baulsupp.okurl.services.basicauth.BasicAuthInterceptor(), com.baulsupp.okurl.services.box.BoxAuthInterceptor(), com.baulsupp.okurl.services.circleci.CircleCIAuthInterceptor(), com.baulsupp.okurl.services.cirrusci.CirrusCiAuthInterceptor(), com.baulsupp.okurl.services.citymapper.CitymapperAuthInterceptor(), com.baulsupp.okurl.services.coinbase.CoinbaseAuthInterceptor(), com.baulsupp.okurl.services.coinbin.CoinBinAuthInterceptor(), com.baulsupp.okurl.services.companieshouse.CompaniesHouseAuthInterceptor(), com.baulsupp.okurl.services.cooee.CooeeAuthInterceptor(), com.baulsupp.okurl.services.cronhub.CronhubAuthInterceptor(), com.baulsupp.okurl.services.datasettes.DatasettesAuthInterceptor(), com.baulsupp.okurl.services.dropbox.DropboxAuthInterceptor(), com.baulsupp.okurl.services.facebook.FacebookAuthInterceptor(), com.baulsupp.okurl.services.fitbit.FitbitAuthInterceptor(), com.baulsupp.okurl.services.foursquare.FourSquareAuthInterceptor(), com.baulsupp.okurl.services.gdax.GdaxAuthInterceptor(), com.baulsupp.okurl.services.giphy.GiphyAuthInterceptor(), com.baulsupp.okurl.services.github.GithubAuthInterceptor(), com.baulsupp.okurl.services.google.GoogleAuthInterceptor(), com.baulsupp.okurl.services.hitbtc.HitBTCAuthInterceptor(), com.baulsupp.okurl.services.howsmyssl.HowsMySslAuthInterceptor(), com.baulsupp.okurl.services.httpbin.HttpBinAuthInterceptor(), com.baulsupp.okurl.services.imgur.ImgurAuthInterceptor(), com.baulsupp.okurl.services.instagram.InstagramAuthInterceptor(), com.baulsupp.okurl.services.linkedin.LinkedinAuthInterceptor(), com.baulsupp.okurl.services.lyft.LyftAuthInterceptor(), com.baulsupp.okurl.services.mapbox.MapboxAuthInterceptor(), com.baulsupp.okurl.services.microsoft.MicrosoftAuthInterceptor(), com.baulsupp.okurl.services.opsgenie.OpsGenieAuthInterceptor(), com.baulsupp.okurl.services.oxforddictionaries.OxfordDictionariesInterceptor(), com.baulsupp.okurl.services.paypal.PaypalAuthInterceptor(), com.baulsupp.okurl.services.paypal.PaypalSandboxAuthInterceptor(), com.baulsupp.okurl.services.postman.PostmanAuthInterceptor(), com.baulsupp.okurl.services.quip.QuipAuthInterceptor(), com.baulsupp.okurl.services.sheetsu.SheetsuAuthInterceptor(), com.baulsupp.okurl.services.slack.SlackAuthInterceptor(), com.baulsupp.okurl.services.smartystreets.SmartyStreetsAuthInterceptor(), com.baulsupp.okurl.services.spotify.SpotifyAuthInterceptor(), com.baulsupp.okurl.services.squareup.SquareUpAuthInterceptor(), com.baulsupp.okurl.services.stackexchange.StackExchangeAuthInterceptor(), com.baulsupp.okurl.services.strava.StravaAuthInterceptor(), com.baulsupp.okurl.services.streamdata.StreamdataAuthInterceptor(), com.baulsupp.okurl.services.surveymonkey.SurveyMonkeyAuthInterceptor(), com.baulsupp.okurl.services.symphony.SymphonyAuthInterceptor(), com.baulsupp.okurl.services.tfl.TflAuthInterceptor(), com.baulsupp.okurl.services.transferwise.TransferwiseAuthInterceptor(), com.baulsupp.okurl.services.transferwise.TransferwiseTestAuthInterceptor(), com.baulsupp.okurl.services.travisci.TravisCIAuthInterceptor(), com.baulsupp.okurl.services.trello.TrelloAuthInterceptor(), com.baulsupp.okurl.services.twilio.TwilioAuthInterceptor(), com.baulsupp.okurl.services.twitter.TwitterAuthInterceptor(), com.baulsupp.okurl.services.uber.UberAuthInterceptor(), com.baulsupp.okurl.services.weekdone.WeekdoneAuthInterceptor() ) } }
apache-2.0
6cdd23ba966a7384b2b722d2061be033
44.534722
100
0.744243
4.512732
false
false
false
false
thermatk/FastHub-Libre
app/src/main/java/com/fastaccess/ui/adapter/viewholder/CommitThreadViewHolder.kt
7
3340
package com.fastaccess.ui.adapter.viewholder import android.annotation.SuppressLint import android.view.View import android.view.ViewGroup import butterknife.BindView import com.fastaccess.R import com.fastaccess.data.dao.TimelineModel import com.fastaccess.data.dao.model.Comment import com.fastaccess.ui.adapter.CommitCommentsAdapter import com.fastaccess.ui.adapter.callback.OnToggleView import com.fastaccess.ui.widgets.FontTextView import com.fastaccess.ui.widgets.SpannableBuilder import com.fastaccess.ui.widgets.recyclerview.BaseRecyclerAdapter import com.fastaccess.ui.widgets.recyclerview.BaseViewHolder import com.fastaccess.ui.widgets.recyclerview.DynamicRecyclerView /** * Created by kosh on 15/08/2017. */ class CommitThreadViewHolder private constructor(view: View, adapter: BaseRecyclerAdapter<*, *, *>, val onToggleView: OnToggleView) : BaseViewHolder<TimelineModel>(view, adapter), BaseViewHolder.OnItemClickListener<Comment> { @BindView(R.id.pathText) lateinit var pathText: FontTextView @BindView(R.id.toggle) lateinit var toggle: View @BindView(R.id.toggleHolder) lateinit var toggleHolder: View @BindView(R.id.commitComments) lateinit var commitComments: DynamicRecyclerView init { toggleHolder.setOnClickListener(this) toggle.setOnClickListener(this) itemView.setOnClickListener(null) itemView.setOnLongClickListener(null) } override fun onClick(v: View) { if (v.id == R.id.toggle || v.id == R.id.toggleHolder) { val position = adapterPosition onToggleView.onToggle(position.toLong(), !onToggleView.isCollapsed(position.toLong())) onToggle(onToggleView.isCollapsed(position.toLong())) } } @SuppressLint("SetTextI18n") override fun bind(model: TimelineModel) { val t = model.commit t?.let { val builder = SpannableBuilder.builder() pathText.text = builder.append("${if (!it.login.isNullOrBlank()) it.login else ""} commented on") .append(if (!it.path.isNullOrEmpty()) { " ${it.path}#L${it.position} in " } else { " " }) .url(it.commitId.substring(0, 7)) it.comments?.let { if (!it.isEmpty()) commitComments.adapter = CommitCommentsAdapter(it, this, onToggleView) } } onToggle(onToggleView.isCollapsed(adapterPosition.toLong())) } private fun onToggle(expanded: Boolean) { toggle.rotation = if (!expanded) 0.0f else 180f commitComments.visibility = if (!expanded) View.GONE else if (commitComments.adapter != null) View.VISIBLE else View.GONE } override fun onItemClick(position: Int, v: View?, item: Comment) {} override fun onItemLongClick(position: Int, v: View?, item: Comment) {} companion object { fun newInstance(parent: ViewGroup, adapter: BaseRecyclerAdapter<*, *, *>, onToggleView: OnToggleView): CommitThreadViewHolder { return CommitThreadViewHolder(getView(parent, R.layout.grouped_commit_comment_row), adapter, onToggleView) } } }
gpl-3.0
b7f25cb7057002a0c7649e7e1f68ba36
39.253012
118
0.657485
4.606897
false
false
false
false
kharchenkovitaliypt/AndroidMvp
sample/src/main/java/com/idapgroup/android/mvpsample/SampleLceFragment.kt
1
2450
package com.idapgroup.android.mvpsample import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.idapgroup.android.mvp.impl.LcePresenterFragment class SampleLceFragment : SampleLceMvp.View, LcePresenterFragment<SampleLceMvp.View, SampleLceMvp.Presenter>() { override fun showError(error: Throwable, retry: (() -> Unit)?) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun onCreateContentView(inflater: LayoutInflater, container: ViewGroup): View { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun onCreatePresenter(): SampleLceMvp.Presenter { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } // // override var retainPresenter = true // // override fun onCreatePresenter() = SampleLcePresenter() // // override fun onCreateContentView(inflater: LayoutInflater, container: ViewGroup): View { // return inflater.inflate(R.layout.screen_sample, container, false) // } // // override fun onViewCreated(view: View, savedInstanceState: Bundle?) { // super.onViewCreated(view, savedInstanceState) // // Temp fix for overlaying screens // view.background = ColorDrawable(Color.WHITE) // // view.findViewById(R.id.ask).setOnClickListener { // val question = (view.findViewById(R.id.question) as TextView).text // presenter.onAsk(question.toString()) // } // view.findViewById(R.id.confirm).setOnClickListener { presenter.onConfirm() } // } // // override fun goToMain() { // fragmentManager.popBackStack() // } // // override fun showMessage(message: String) { // (view!!.findViewById(R.id.result) as TextView).text = message // } // // override fun showLceLoad() { // // Because was override by SampleMvp.View interface // super.showLoad() // } // // override fun showLoad() { // Toast.makeText(context, "Processing...", Toast.LENGTH_SHORT).show() // } // // override fun hideLoad() { // Toast.makeText(context, "Processing complete.", Toast.LENGTH_SHORT).show() // } // // override fun showError(error: Throwable) { // super.showError(error.message ?: error.toString(), { presenter.onRetry() }) // } }
apache-2.0
3e435e5275d6ba639918058a4a01355a
36.136364
112
0.669796
4.138514
false
false
false
false
ze-pequeno/okhttp
okhttp-tls/src/main/kotlin/okhttp3/tls/HandshakeCertificates.kt
5
8566
/* * Copyright (C) 2012 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.tls import java.security.SecureRandom import java.security.cert.X509Certificate import java.util.Collections import javax.net.ssl.HostnameVerifier import javax.net.ssl.KeyManager import javax.net.ssl.SSLContext import javax.net.ssl.SSLSocketFactory import javax.net.ssl.TrustManager import javax.net.ssl.X509KeyManager import javax.net.ssl.X509TrustManager import okhttp3.CertificatePinner import okhttp3.internal.platform.Platform import okhttp3.internal.toImmutableList import okhttp3.tls.internal.TlsUtil.newKeyManager import okhttp3.tls.internal.TlsUtil.newTrustManager import java.security.KeyStoreException /** * Certificates to identify which peers to trust and also to earn the trust of those peers in kind. * Client and server exchange these certificates during the handshake phase of a TLS connection. * * ### Server Authentication * * This is the most common form of TLS authentication: clients verify that servers are trusted and * that they own the hostnames that they represent. Server authentication is required. * * To perform server authentication: * * * The server's handshake certificates must have a [held certificate][HeldCertificate] (a * certificate and its private key). The certificate's subject alternative names must match the * server's hostname. The server must also have is a (possibly-empty) chain of intermediate * certificates to establish trust from a root certificate to the server's certificate. The root * certificate is not included in this chain. * * The client's handshake certificates must include a set of trusted root certificates. They will * be used to authenticate the server's certificate chain. Typically this is a set of well-known * root certificates that is distributed with the HTTP client or its platform. It may be * augmented by certificates private to an organization or service. * * ### Client Authentication * * This is authentication of the client by the server during the TLS handshake. Client * authentication is optional. * * To perform client authentication: * * * The client's handshake certificates must have a [held certificate][HeldCertificate] (a * certificate and its private key). The client must also have a (possibly-empty) chain of * intermediate certificates to establish trust from a root certificate to the client's * certificate. The root certificate is not included in this chain. * * The server's handshake certificates must include a set of trusted root certificates. They * will be used to authenticate the client's certificate chain. Typically this is not the same * set of root certificates used in server authentication. Instead it will be a small set of * roots private to an organization or service. */ class HandshakeCertificates private constructor( @get:JvmName("keyManager") val keyManager: X509KeyManager, @get:JvmName("trustManager") val trustManager: X509TrustManager ) { @JvmName("-deprecated_keyManager") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "keyManager"), level = DeprecationLevel.ERROR) fun keyManager(): X509KeyManager = keyManager @JvmName("-deprecated_trustManager") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "trustManager"), level = DeprecationLevel.ERROR) fun trustManager(): X509TrustManager = trustManager fun sslSocketFactory(): SSLSocketFactory = sslContext().socketFactory fun sslContext(): SSLContext { return Platform.get().newSSLContext().apply { init(arrayOf<KeyManager>(keyManager), arrayOf<TrustManager>(trustManager), SecureRandom()) } } class Builder { private var heldCertificate: HeldCertificate? = null private var intermediates: Array<X509Certificate>? = null private val trustedCertificates = mutableListOf<X509Certificate>() private val insecureHosts = mutableListOf<String>() /** * Configure the certificate chain to use when being authenticated. The first certificate is * the held certificate, further certificates are included in the handshake so the peer can * build a trusted path to a trusted root certificate. * * The chain should include all intermediate certificates but does not need the root certificate * that we expect to be known by the remote peer. The peer already has that certificate so * transmitting it is unnecessary. */ fun heldCertificate( heldCertificate: HeldCertificate, vararg intermediates: X509Certificate ) = apply { this.heldCertificate = heldCertificate this.intermediates = arrayOf(*intermediates) // Defensive copy. } /** * Add a trusted root certificate to use when authenticating a peer. Peers must provide * a chain of certificates whose root is one of these. */ fun addTrustedCertificate(certificate: X509Certificate) = apply { this.trustedCertificates += certificate } /** * Add all of the host platform's trusted root certificates. This set varies by platform * (Android vs. Java), by platform release (Android 4.4 vs. Android 9), and with user * customizations. * * Most TLS clients that connect to hosts on the public Internet should call this method. * Otherwise it is necessary to manually prepare a comprehensive set of trusted roots. * * If the host platform is compromised or misconfigured this may contain untrustworthy root * certificates. Applications that connect to a known set of servers may be able to mitigate * this problem with [certificate pinning][CertificatePinner]. */ fun addPlatformTrustedCertificates() = apply { val platformTrustManager = Platform.get().platformTrustManager() Collections.addAll(trustedCertificates, *platformTrustManager.acceptedIssuers) } /** * Configures this to not authenticate the HTTPS server on to [hostname]. This makes the user * vulnerable to man-in-the-middle attacks and should only be used only in private development * environments and only to carry test data. * * The server’s TLS certificate **does not need to be signed** by a trusted certificate * authority. Instead, it will trust any well-formed certificate, even if it is self-signed. * This is necessary for testing against localhost or in development environments where a * certificate authority is not possible. * * The server’s TLS certificate still must match the requested hostname. For example, if the * certificate is issued to `example.com` and the request is to `localhost`, the connection will * fail. Use a custom [HostnameVerifier] to ignore such problems. * * Other TLS features are still used but provide no security benefits in absence of the above * gaps. For example, an insecure TLS connection is capable of negotiating HTTP/2 with ALPN and * it also has a regular-looking handshake. * * **This feature is not supported on Android API levels less than 24.** Prior releases lacked * a mechanism to trust some hosts and not others. * * @param hostname the exact hostname from the URL for insecure connections. */ fun addInsecureHost(hostname: String) = apply { insecureHosts += hostname } fun build(): HandshakeCertificates { val immutableInsecureHosts = insecureHosts.toImmutableList() val heldCertificate = heldCertificate if (heldCertificate != null && heldCertificate.keyPair.private.format == null) { throw KeyStoreException("unable to support unencodable private key") } val keyManager = newKeyManager(null, heldCertificate, *(intermediates ?: emptyArray())) val trustManager = newTrustManager(null, trustedCertificates, immutableInsecureHosts) return HandshakeCertificates(keyManager, trustManager) } } }
apache-2.0
28b0885735b9797d138aba23eae42dfd
44.786096
100
0.740014
4.764608
false
false
false
false
shaeberling/euler
kotlin/src/com/s13g/aoc/aoc2021/Day12.kt
1
1507
package com.s13g.aoc.aoc2021 import com.s13g.aoc.Result import com.s13g.aoc.Solver /** * --- Day 12: Passage Pathing --- * https://adventofcode.com/2021/day/12 */ class Day12 : Solver { override fun solve(lines: List<String>): Result { val connections = lines.map { it.split('-') }.map { Pair(it[0], it[1]) } val system = mutableMapOf<String, Node>() for (conn in connections) { if (!system.containsKey(conn.first)) system[conn.first] = Node(conn.first) if (!system.containsKey(conn.second)) system[conn.second] = Node(conn.second) system[conn.first]!!.connections.add(system[conn.second]!!) system[conn.second]!!.connections.add(system[conn.first]!!) } val partA = countRoutes(system["start"]!!, setOf(), false) val partB = countRoutes(system["start"]!!, setOf(), true) return Result("$partA", "$partB") } private fun countRoutes(from: Node, noGos: Set<String>, smallException: Boolean): Int { if (noGos.contains(from.id) && (!smallException || from.id == "start")) return 0 if (from.id == "end") return 1 val newSmallException = if (noGos.contains(from.id)) false else smallException val newNoGos = noGos.toMutableSet() if (from.small) { newNoGos.add(from.id) } return from.connections.map { countRoutes(it, newNoGos, newSmallException) }.sum() } private data class Node(val id: String) { val small: Boolean = id[0].isLowerCase() val connections: MutableSet<Node> = mutableSetOf<Node>() } }
apache-2.0
d59e2280ec782b90a0dd9403fbd71b00
34.904762
89
0.660252
3.386517
false
false
false
false
google/horologist
media-sample/src/main/java/com/google/android/horologist/mediasample/di/DownloadModule.kt
1
6848
/* * 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.android.horologist.mediasample.di import android.annotation.SuppressLint import android.content.Context import androidx.media3.database.DatabaseProvider import androidx.media3.database.StandaloneDatabaseProvider import androidx.media3.datasource.DataSource import androidx.media3.datasource.cache.Cache import androidx.media3.datasource.okhttp.OkHttpDataSource import androidx.media3.exoplayer.offline.DownloadIndex import androidx.media3.exoplayer.offline.DownloadManager import androidx.media3.exoplayer.offline.DownloadNotificationHelper import androidx.media3.exoplayer.workmanager.WorkManagerScheduler import com.google.android.horologist.media.data.datasource.MediaDownloadLocalDataSource import com.google.android.horologist.media.data.service.download.DownloadManagerListener import com.google.android.horologist.media.data.service.download.DownloadProgressMonitor import com.google.android.horologist.media3.logging.ErrorReporter import com.google.android.horologist.media3.logging.TransferListener import com.google.android.horologist.media3.service.NetworkAwareDownloadListener import com.google.android.horologist.mediasample.data.service.download.MediaDownloadServiceImpl import com.google.android.horologist.mediasample.di.annotation.Dispatcher import com.google.android.horologist.mediasample.di.annotation.DownloadFeature import com.google.android.horologist.mediasample.di.annotation.UampDispatchers.IO import com.google.android.horologist.mediasample.ui.AppConfig import com.google.android.horologist.networks.data.RequestType.MediaRequest.Companion.DownloadRequest import com.google.android.horologist.networks.highbandwidth.HighBandwidthNetworkMediator import com.google.android.horologist.networks.okhttp.NetworkAwareCallFactory import com.google.android.horologist.networks.rules.NetworkingRulesEngine import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import okhttp3.Call import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import javax.inject.Provider import javax.inject.Singleton @SuppressLint("UnsafeOptInUsageError") @Module @InstallIn(SingletonComponent::class) object DownloadModule { private const val DOWNLOAD_WORK_MANAGER_SCHEDULER_WORK_NAME = "mediasample_download" @DownloadFeature @Singleton @Provides fun downloadDataSourceFactory( callFactory: Call.Factory, @DownloadFeature transferListener: TransferListener ): DataSource.Factory = OkHttpDataSource.Factory( NetworkAwareCallFactory( delegate = callFactory, defaultRequestType = DownloadRequest ) ).setTransferListener(transferListener) @DownloadFeature @Provides fun transferListener(errorReporter: ErrorReporter): TransferListener = TransferListener(errorReporter) @DownloadFeature @Singleton @Provides fun threadPool(): ExecutorService = Executors.newCachedThreadPool() @Singleton @Provides fun downloadNotificationHelper( @ApplicationContext applicationContext: Context ): DownloadNotificationHelper = DownloadNotificationHelper( applicationContext, MediaDownloadServiceImpl.MEDIA_DOWNLOAD_CHANNEL_ID ) @DownloadFeature @Singleton @Provides fun databaseProvider( @ApplicationContext application: Context ): DatabaseProvider = StandaloneDatabaseProvider(application) @Singleton @Provides fun downloadManager( @ApplicationContext applicationContext: Context, @DownloadFeature databaseProvider: DatabaseProvider, downloadCache: Cache, @DownloadFeature dataSourceFactory: DataSource.Factory, @DownloadFeature threadPool: ExecutorService, downloadManagerListener: DownloadManagerListener, appConfig: AppConfig, networkAwareListener: Provider<NetworkAwareDownloadListener> ) = DownloadManager( applicationContext, databaseProvider, downloadCache, dataSourceFactory, threadPool ).also { it.addListener(downloadManagerListener) if (appConfig.strictNetworking != null) { it.addListener(networkAwareListener.get()) } } @Provides fun downloadIndex(downloadManager: DownloadManager): DownloadIndex = downloadManager.downloadIndex @Singleton @Provides fun workManagerScheduler( @ApplicationContext applicationContext: Context ) = WorkManagerScheduler(applicationContext, DOWNLOAD_WORK_MANAGER_SCHEDULER_WORK_NAME) @DownloadFeature @Provides @Singleton fun coroutineScope( @Dispatcher(IO) ioDispatcher: CoroutineDispatcher ): CoroutineScope = CoroutineScope(SupervisorJob() + ioDispatcher) @Provides @Singleton fun downloadManagerListener( @DownloadFeature coroutineScope: CoroutineScope, mediaDownloadLocalDataSource: MediaDownloadLocalDataSource, downloadProgressMonitor: DownloadProgressMonitor ): DownloadManagerListener = DownloadManagerListener( coroutineScope = coroutineScope, mediaDownloadLocalDataSource = mediaDownloadLocalDataSource, downloadProgressMonitor = downloadProgressMonitor ) @Provides @Singleton fun downloadProgressMonitor( @DownloadFeature coroutineScope: CoroutineScope, mediaDownloadLocalDataSource: MediaDownloadLocalDataSource ): DownloadProgressMonitor = DownloadProgressMonitor( coroutineScope = coroutineScope, mediaDownloadLocalDataSource = mediaDownloadLocalDataSource ) @Provides @Singleton fun networkAwareListener( errorReporter: ErrorReporter, highBandwithRequester: HighBandwidthNetworkMediator, networkingRulesEngine: NetworkingRulesEngine ): NetworkAwareDownloadListener = NetworkAwareDownloadListener( errorReporter, highBandwithRequester, networkingRulesEngine ) }
apache-2.0
f984809a20761b2481c849f7e255bcd1
37.256983
102
0.780958
5.312645
false
false
false
false
google/horologist
compose-layout/src/main/java/com/google/android/horologist/compose/layout/ScrollAway.kt
1
3837
/* * 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.android.horologist.compose.layout import androidx.compose.foundation.ScrollState import androidx.compose.foundation.layout.Column import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.ui.Modifier import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.wear.compose.material.ScalingLazyListState import androidx.wear.compose.material.scrollAway as scrollAwayCompose /** * Scroll an item vertically in/out of view based on a [ScrollState]. * Typically used to scroll a [TimeText] item out of view as the user starts to scroll a * vertically scrollable [Column] of items upwards and bring additional items into view. * * @param scrollState The [ScrollState] to used as the basis for the scroll-away. * @param offset Adjustment to the starting point for scrolling away. Positive values result in * the scroll away starting later. */ @Deprecated( "Replaced by Wear Compose scrollAway", replaceWith = ReplaceWith( "this.scrollAway(scrollState, offset)", "androidx.wear.compose.material.scrollAway" ) ) public fun Modifier.scrollAway( scrollState: ScrollState, offset: Dp = 0.dp ): Modifier = scrollAwayCompose(scrollState, offset) /** * Scroll an item vertically in/out of view based on a [LazyListState]. * Typically used to scroll a [TimeText] item out of view as the user starts to scroll * a [LazyColumn] of items upwards and bring additional items into view. * * @param scrollState The [LazyListState] to used as the basis for the scroll-away. * @param itemIndex The item for which the scroll offset will trigger scrolling away. * @param offset Adjustment to the starting point for scrolling away. Positive values result in * the scroll away starting later. */ @Deprecated( "Replaced by Wear Compose scrollAway", replaceWith = ReplaceWith( "this.scrollAway(scrollState, itemIndex, offset)", "androidx.wear.compose.material.scrollAway" ) ) public fun Modifier.scrollAway( scrollState: LazyListState, itemIndex: Int = 0, offset: Dp = 0.dp ): Modifier = scrollAwayCompose(scrollState, itemIndex, offset) /** * Scroll an item vertically in/out of view based on a [ScalingLazyListState]. * Typically used to scroll a [TimeText] item out of view as the user starts to scroll * a [ScalingLazyColumn] of items upwards and bring additional items into view. * * @param scrollState The [ScalingLazyListState] to used as the basis for the scroll-away. * @param itemIndex The item for which the scroll offset will trigger scrolling away. * @param offset Adjustment to the starting point for scrolling away. Positive values result in * the scroll away starting later, negative values start scrolling away earlier. */ @Deprecated( "Replaced by Wear Compose scrollAway", replaceWith = ReplaceWith( "this.scrollAway(scrollState, itemIndex, offset)", "androidx.wear.compose.material.scrollAway" ) ) public fun Modifier.scrollAway( scrollState: ScalingLazyListState, itemIndex: Int = 1, offset: Dp = 0.dp ): Modifier = scrollAwayCompose(scrollState, itemIndex, offset)
apache-2.0
e68f708026ebb515b16dabb840cd8b4b
39.819149
95
0.754235
4.345413
false
false
false
false
jdm64/GenesisChess-Android
app/src/main/java/com/chess/genesis/activity/BoardPage.kt
1
8167
/* GenesisChess, an Android chess application * Copyright 2022, Justin Madru ([email protected]) * * 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://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.chess.genesis.activity import android.content.* import android.content.ClipboardManager import android.widget.* import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.* import androidx.compose.material.* import androidx.compose.material.icons.* import androidx.compose.material.icons.filled.* import androidx.compose.runtime.* import androidx.compose.ui.* import androidx.compose.ui.draw.* import androidx.compose.ui.graphics.* import androidx.compose.ui.platform.* import androidx.compose.ui.text.font.* import androidx.compose.ui.unit.* import androidx.compose.ui.viewinterop.* import androidx.compose.ui.window.* import androidx.navigation.* import com.chess.genesis.R import com.chess.genesis.api.* import com.chess.genesis.controller.* import com.chess.genesis.data.* import kotlinx.coroutines.* @OptIn(ExperimentalMaterialApi::class) @Composable fun GamePage(nav: NavHostController, gameId: String) { val state = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden) val ctx = LocalContext.current val gameCtlr = remember { GameController(ctx, gameId) } DisposableEffect(gameCtlr) { onDispose { gameCtlr.onDispose() } } ModalBottomSheetLayout( sheetElevation = 16.dp, sheetShape = RoundedCornerShape(32.dp), sheetState = state, sheetContent = { GameMenu(gameCtlr, state, nav) }) { GameContent(gameCtlr, state) } ShowGameDialogs(gameCtlr) ShowSubmitDialog(gameCtlr) } @OptIn(ExperimentalMaterialApi::class) @Composable fun GameMenu(gameCtlr: GameController, state: ModalBottomSheetState, nav: NavHostController) { val ctx = LocalContext.current val scope = rememberCoroutineScope() Column { ListItem( modifier = Modifier.clickable(onClick = { val clipboard = ctx.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText("simple text", gameCtlr.gameId) clipboard.setPrimaryClip(clip) Toast.makeText(ctx, "Game ID copied", Toast.LENGTH_SHORT).show() scope.launch { state.hide() } }), icon = { Icon(Icons.Filled.Share, "Copy Game ID") }, text = { Text("Copy Game ID") } ) ListItem( modifier = Modifier.clickable(onClick = { if (!nav.popBackStack("list", false)) { nav.navigate("list") } scope.launch { state.hide() } }), icon = { Icon(Icons.Filled.List, "Game List") }, text = { Text("Game List") } ) ListItem( modifier = Modifier.clickable(onClick = { scope.launch { ctx.startActivity(Intent(ctx, SettingsPage::class.java)) state.hide() } }), icon = { Icon(Icons.Filled.Settings, "Settings") }, text = { Text("Settings") } ) } } @OptIn(ExperimentalMaterialApi::class) @Composable fun GameContent(gameCtlr: IGameController, state: ModalBottomSheetState) { Column( Modifier .fillMaxHeight() .background(Color.Gray), verticalArrangement = Arrangement.SpaceBetween ) { TopBarInfo(gameCtlr) BoardAndPieces(gameCtlr) BottomBar(state) { GameNav(gameCtlr) } } } @Composable fun TopBarInfo(gameCtlr: IGameController) { val stmState = remember { gameCtlr.stmState } val colors = MaterialTheme.colors val mate = stmState.value.mate val stm = stmState.value.stm val yColor = stmState.value.yourColor val whiteColor = if (mate * stm > 0) colors.error else if (stm > 0) colors.onPrimary else Color.Gray val blackColor = if (mate * stm < 0) colors.error else if (stm < 0) colors.onPrimary else Color.Gray Row(Modifier.fillMaxWidth(1f)) { Row( Modifier .fillMaxWidth(.5f) .background(colors.primary) .border(3.dp, whiteColor) .padding(8.dp, 16.dp, 8.dp, 16.dp) ) { if (yColor > 0) { Box( Modifier .size(16.dp) .clip(CircleShape) .background(colors.secondaryVariant) .align(Alignment.CenterVertically) ) } Text( stmState.value.white, color = colors.onPrimary, modifier = Modifier.padding(6.dp, 0.dp, 0.dp, 0.dp) ) } Row( Modifier .fillMaxWidth(1f) .background(colors.primary) .border(3.dp, blackColor) .padding(8.dp, 16.dp, 8.dp, 16.dp) ) { if (yColor < 0) { Box( Modifier .size(16.dp) .clip(CircleShape) .background(colors.secondaryVariant) .align(Alignment.CenterVertically) ) } Text( stmState.value.black, color = colors.onPrimary, modifier = Modifier.padding(6.dp, 0.dp, 0.dp, 0.dp) ) } } } @Composable fun BoardAndPieces(gameCtlr: IGameController) { val ctx = LocalContext.current val showCapture = Pref.getBool(ctx, R.array.pf_showCaptured) val capturedBelow = Pref.getBool(ctx, R.array.pf_capturedBelow) val isGenChess = remember { gameCtlr.isGenChess } Column { if (capturedBelow) { if (isGenChess.value) { AndroidView({ gameCtlr.placeView }) Spacer(modifier = Modifier.height(20.dp)) } } else if (showCapture) { AndroidView({ gameCtlr.capturedView }) Spacer(modifier = Modifier.height(10.dp)) } AndroidView({ gameCtlr.boardView }) if (capturedBelow) { if (showCapture) { Spacer(modifier = Modifier.height(10.dp)) AndroidView({ gameCtlr.capturedView }) } } else if (isGenChess.value) { Spacer(modifier = Modifier.height(20.dp)) AndroidView({ gameCtlr.placeView }) } } } @OptIn(ExperimentalMaterialApi::class) @Composable fun BottomBar(state: ModalBottomSheetState, content: @Composable () -> Unit) { val scope = rememberCoroutineScope() BottomAppBar(Modifier.height(60.dp)) { IconButton(onClick = { scope.launch { state.show() } }) { Icon(Icons.Filled.Menu, "menu", Modifier.size(30.dp)) } Spacer(Modifier.aspectRatio(1.25f)) content.invoke() } } @Composable fun GameNav(gameCtlr: IGameController) { IconButton(onClick = { gameCtlr.onBackClick() }) { Icon(Icons.Filled.ArrowBack, "Back", Modifier.size(30.dp)) } IconButton(onClick = { gameCtlr.onForwardClick() }) { Icon(Icons.Filled.ArrowForward, "Forward", Modifier.size(30.dp)) } IconButton(onClick = { gameCtlr.onCurrentClick() }) { Icon(Icons.Filled.PlayArrow, "Last", Modifier.size(30.dp)) } } @Composable fun ShowGameDialogs(gameCtlr: IGameController) { val promoteState = remember { gameCtlr.promoteState } if (promoteState.value) { AlertDialog(onDismissRequest = { promoteState.value = false }, title = { Text( text = "Promote Pawn", fontWeight = FontWeight.Bold, fontSize = 20.sp ) }, text = { AndroidView({ gameCtlr.promoteView }) }, buttons = { TextButton(onClick = { promoteState.value = false }) { Text("Cancel") } } ) } } @Composable fun ShowSubmitDialog(gameCtlr: GameController) { val submitState = remember { gameCtlr.submitState } if (!submitState.value.show) { return } val ctx = LocalContext.current Popup(alignment = Alignment.BottomCenter, onDismissRequest = { gameCtlr.undoMove() submitState.value = SubmitState() } ) { Row( modifier = Modifier .height(64.dp) .background(Color.Gray) ) { OutlinedButton( onClick = { gameCtlr.undoMove() submitState.value = SubmitState() }, modifier = Modifier .fillMaxWidth(.5f) .padding(12.dp) ) { Text("Cancel", fontSize = 20.sp) } Button( onClick = { val move = submitState.value.move gameCtlr.submitMove(move) submitState.value = SubmitState() }, modifier = Modifier .fillMaxWidth(1f) .padding(12.dp) ) { Text("Submit", fontSize = 20.sp) } } } }
apache-2.0
c327c7d5553a693295bd36dd666c04d6
25.345161
94
0.694992
3.25638
false
false
false
false
Kotlin/dokka
plugins/javadoc/src/test/kotlin/org/jetbrains/dokka/javadoc/AbstractJavadocTemplateMapTest.kt
1
4685
package org.jetbrains.dokka.javadoc import org.jetbrains.dokka.* import org.jetbrains.dokka.javadoc.pages.JavadocPageNode import org.jetbrains.dokka.javadoc.renderer.JavadocContentToTemplateMapTranslator import org.jetbrains.dokka.javadoc.JavadocPlugin import org.jetbrains.dokka.javadoc.location.JavadocLocationProvider import org.jetbrains.dokka.model.withDescendants import org.jetbrains.dokka.pages.RootPageNode import org.jetbrains.dokka.plugability.* import org.jetbrains.dokka.base.testApi.testRunner.BaseAbstractTest internal abstract class AbstractJavadocTemplateMapTest : BaseAbstractTest() { protected var config: DokkaConfigurationImpl = dokkaConfiguration { format = "javadoc" suppressObviousFunctions = false sourceSets { sourceSet { sourceRoots = listOf("src") analysisPlatform = "jvm" externalDocumentationLinks = listOf( DokkaConfiguration.ExternalDocumentationLink.jdk(8), DokkaConfiguration.ExternalDocumentationLink.kotlinStdlib() ) } } } data class Result( val rootPageNode: RootPageNode, val context: DokkaContext ) { val translator: JavadocContentToTemplateMapTranslator by lazy { val locationProvider = context.plugin<JavadocPlugin>() .querySingle { locationProviderFactory } .getLocationProvider(rootPageNode) as JavadocLocationProvider JavadocContentToTemplateMapTranslator(locationProvider, context) } val JavadocPageNode.templateMap: Map<String, Any?> get() = translator.templateMapForPageNode(this) inline fun <reified T : JavadocPageNode> allPagesOfType(): List<T> { return rootPageNode.withDescendants().filterIsInstance<T>().toList() } inline fun <reified T : JavadocPageNode> firstPageOfType(): T { return rootPageNode.withDescendants().filterIsInstance<T>().first() } inline fun <reified T : JavadocPageNode> firstPageOfTypeOrNull(): T? { return rootPageNode.withDescendants().filterIsInstance<T>().firstOrNull() } inline fun <reified T : JavadocPageNode> singlePageOfType(): T { return rootPageNode.withDescendants().filterIsInstance<T>().single() } } fun testTemplateMapInline( query: String, configuration: DokkaConfigurationImpl = config, pluginsOverride: List<DokkaPlugin> = emptyList(), assertions: Result.() -> Unit ) { testInline(query, configuration, pluginOverrides = pluginsOverride) { renderingStage = { rootPageNode, dokkaContext -> val preprocessors = dokkaContext.plugin<JavadocPlugin>().query { javadocPreprocessors } val transformedRootPageNode = preprocessors.fold(rootPageNode) { acc, pageTransformer -> pageTransformer(acc) } Result(transformedRootPageNode, dokkaContext).assertions() } } } fun dualTestTemplateMapInline( kotlin: String? = null, java: String? = null, configuration: DokkaConfigurationImpl = config, pluginsOverride: List<DokkaPlugin> = emptyList(), assertions: Result.() -> Unit ) { val kotlinException = kotlin?.let { runCatching { testTemplateMapInline( query = kotlin, configuration = configuration, pluginsOverride = pluginsOverride, assertions = assertions ) }.exceptionOrNull() } val javaException = java?.let { runCatching { testTemplateMapInline( query = java, configuration = configuration, pluginsOverride = pluginsOverride, assertions = assertions ) }.exceptionOrNull() } if (kotlinException != null && javaException != null) { throw AssertionError( "Kotlin and Java Code failed assertions\n" + "Kotlin: ${kotlinException.message}\n" + "Java : ${javaException.message}", kotlinException ) } if (kotlinException != null) { throw AssertionError("Kotlin Code failed assertions", kotlinException) } if (javaException != null) { throw AssertionError("Java Code failed assertions", javaException) } } }
apache-2.0
0b8d7ac1f7c91f8663dd25037f70cea9
36.48
106
0.614301
5.776819
false
true
false
false
AIDEA775/UNCmorfi
app/src/main/java/com/uncmorfi/servings/SyncChartsGestureListener.kt
1
1863
package com.uncmorfi.servings import android.graphics.Matrix import android.view.MotionEvent import android.view.View import com.github.mikephil.charting.charts.LineChart import com.github.mikephil.charting.listener.ChartTouchListener import com.github.mikephil.charting.listener.OnChartGestureListener class SyncChartsGestureListener(private val source: LineChart, private vararg val dest: LineChart) : OnChartGestureListener { override fun onChartGestureStart(me: MotionEvent, lastPerformedGesture: ChartTouchListener.ChartGesture) {} override fun onChartGestureEnd(me: MotionEvent, lastPerformedGesture: ChartTouchListener.ChartGesture) {} override fun onChartLongPressed(me: MotionEvent) {} override fun onChartDoubleTapped(me: MotionEvent) {} override fun onChartSingleTapped(me: MotionEvent) {} override fun onChartFling(me1: MotionEvent, me2: MotionEvent, velocityX: Float, velocityY: Float) {} override fun onChartScale(me: MotionEvent, scaleX: Float, scaleY: Float) { sync() } override fun onChartTranslate(me: MotionEvent, dX: Float, dY: Float) { sync() } private fun sync() { val srcVals = FloatArray(9) var dstMatrix: Matrix val dstVals = FloatArray(9) val srcMatrix = source.viewPortHandler.matrixTouch srcMatrix.getValues(srcVals) for (chart in dest) { if (chart.visibility == View.VISIBLE) { dstMatrix = chart.viewPortHandler.matrixTouch dstMatrix.getValues(dstVals) dstVals[Matrix.MSCALE_X] = srcVals[Matrix.MSCALE_X] dstVals[Matrix.MTRANS_X] = srcVals[Matrix.MTRANS_X] dstMatrix.setValues(dstVals) chart.viewPortHandler.refresh(dstMatrix, chart, true) } } } }
gpl-3.0
c217234c4435e94097d66ca38d7fec1b
34.150943
111
0.688674
4.373239
false
false
false
false
techlung/wearfaceutils
wearfaceutils-sample/src/main/java/com/techlung/wearfaceutils/sample/animation/DrawAnimation.kt
1
813
package com.techlung.wearfaceutils.sample.animation import android.view.animation.Interpolator class DrawAnimation(val interpolator: Interpolator, val durationMillis: Int) { var startTime: Long = 0 var animationRunning: Boolean = false fun start() { startTime = System.currentTimeMillis() animationRunning = true } fun getValue(): Float { val diff: Long = System.currentTimeMillis() - startTime if (diff > durationMillis) { animationRunning = false; return interpolator.getInterpolation(1f) } else { animationRunning = true; return interpolator.getInterpolation(diff.toFloat() / durationMillis.toFloat()) } } fun isAnimationRunning(): Boolean { return animationRunning } }
apache-2.0
1c3c789fbcc2fd99af4fd5d78b8bc432
28.071429
91
0.655597
5.018519
false
false
false
false
gtomek/open-weather-kotlin
app/src/main/java/uk/co/tomek/openweatherkt/MainActivity.kt
1
4149
package uk.co.tomek.openweatherkt import android.graphics.drawable.Animatable import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.View import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.Spinner import android.widget.SpinnerAdapter import android.widget.Toast import butterknife.BindView import butterknife.ButterKnife import com.github.ajalt.timberkt.Timber import com.jakewharton.rxbinding2.widget.RxAdapterView import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import uk.co.tomek.openweatherkt.adapter.WeatherResultsAdapter import uk.co.tomek.openweatherkt.model.WeatherResponseItem import uk.co.tomek.openweatherkt.network.OpenWeatherNetworkService import uk.co.tomek.openweatherkt.presenter.MainPresenter import uk.co.tomek.openweatherkt.view.MainView import javax.inject.Inject class MainActivity : AppCompatActivity(), MainView { @Inject lateinit var networkService: OpenWeatherNetworkService @BindView(R.id.progress_image) lateinit var progressImage: ImageView @BindView(R.id.city_selector_spinner) lateinit var citySelectorSpinner: Spinner @BindView(R.id.results_recycler_view) lateinit var resultsRecyclerView: RecyclerView private val resultsAdapter = WeatherResultsAdapter() private lateinit var presenter: MainPresenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) ButterKnife.bind(this) (this.applicationContext as OpenWeatherApp).mainComponent.inject(this) presenter = MainPresenter(this, networkService, AndroidSchedulers.mainThread()) // Setup city selector spinner val adapter = ArrayAdapter .createFromResource(this, R.array.search_cities, android.R.layout.simple_spinner_item) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) citySelectorSpinner.adapter = adapter // Setup Recycler view resultsRecyclerView.layoutManager = LinearLayoutManager(this) resultsRecyclerView.adapter = resultsAdapter } override fun onDestroy() { presenter.onDestroy() super.onDestroy() } override fun onAttachedToWindow() { super.onAttachedToWindow() val drawable = progressImage.drawable if (drawable is Animatable) { drawable.start() } else { Timber.d { "got drawable $drawable which is not Animatable" } } } override fun onDetachedFromWindow() { val drawable = progressImage.drawable if (drawable is Animatable) { drawable.stop() } super.onDetachedFromWindow() } override fun showFiveDayWeather(weatherResponses: List<WeatherResponseItem>) { Timber.v { "Show 5 day weather" } resultsAdapter.setWeather(weatherResponses) } override fun showError() { Timber.w { "Show error" } Toast.makeText(this, R.string.unknown_error, Toast.LENGTH_LONG).show() } override fun showNetworkError() { Timber.w { "Show network error" } Toast.makeText(this, R.string.netwrok_error, Toast.LENGTH_LONG).show() } override fun showProgress(shouldShow: Boolean) { Timber.v { "Show progress $shouldShow" } progressImage.visibility = if (shouldShow) View.VISIBLE else View.GONE resultsRecyclerView.visibility = if (shouldShow) View.GONE else View.VISIBLE } override fun onCitySelected(): Observable<String> = RxAdapterView.itemSelections<SpinnerAdapter>(citySelectorSpinner) .filter { position -> position > -1 } .map { position -> val cities = resources.getStringArray(R.array.search_cities) cities[position] } override fun onRetryClicked(): Observable<Boolean> = Observable.just(false) }
apache-2.0
c744f855b51f4bf9187cfbb94fc390ab
34.767241
102
0.713425
4.774453
false
false
false
false
camdenorrb/KPortals
src/main/kotlin/me/camdenorrb/kportals/commands/sub/CreatePortalCmd.kt
1
2283
package me.camdenorrb.kportals.commands.sub import me.camdenorrb.kportals.KPortals import me.camdenorrb.kportals.ext.sequenceTo import me.camdenorrb.kportals.messages.Messages.* import me.camdenorrb.kportals.portal.Portal import org.bukkit.ChatColor.DARK_GREEN import org.bukkit.ChatColor.LIGHT_PURPLE import org.bukkit.Material.EMERALD_BLOCK import org.bukkit.Material.REDSTONE_BLOCK import org.bukkit.command.CommandSender import org.bukkit.entity.Player import org.bukkit.util.Vector /** * Created by camdenorrb on 3/20/17. */ class CreatePortalCmd : SubCmd("-create", "/Portal -create <Name> <Type> <ToArg>", "kportals.create") { override fun execute(sender: CommandSender, plugin: KPortals, args: List<String>): Boolean { if (sender !is Player || args.size < 3) { return false } val portalName = args[0] val portalType = Portal.Type.byName(args[1]) val portalArgs = args.drop(2).joinToString(" ") if (portalType == null) { TYPE_DOES_NOT_EXIST.send(sender) return true } if (plugin.portals.any { it.name.equals(portalName, true) }) { NAME_ALREADY_EXISTS.send(sender) return true } val selection = plugin.selectionCache[sender] if (selection == null || !selection.isSelected()) { NO_SELECTION.send(sender) return true } val sel1 = selection.sel1!! val sel2 = selection.sel2!! val min = Vector.getMinimum(sel1, sel2) val max = Vector.getMaximum(sel1, sel2) val world = sender.world val portalVectors = min.sequenceTo(max).filterTo(HashSet()) { world.getBlockAt(it.blockX, it.blockY, it.blockZ).type == REDSTONE_BLOCK } if (portalVectors.isEmpty()) { SELECTION_EMPTY.send(sender) return true } // Definitely could be just one iteration, but eh portalVectors.forEach { world.getBlockAt(it.blockX, it.blockY, it.blockZ).type = EMERALD_BLOCK } plugin.portals.add(Portal(portalName, portalArgs, world.uid, portalType, selection, portalVectors)) plugin.portalsFile.parentFile?.mkdirs() plugin.portalsFile.createNewFile() plugin.korm.push(plugin.portals, plugin.portalsFile) sender.sendMessage("${DARK_GREEN}You have successfully claimed the portal with the name: $LIGHT_PURPLE$portalName ${DARK_GREEN}and the type $LIGHT_PURPLE$portalType$DARK_GREEN!") return true } }
mit
fecf9ee2f4e0bca42db926eefd7a0e87
26.853659
180
0.734122
3.270774
false
false
false
false
sangcomz/FishBun
FishBun/src/main/java/com/sangcomz/fishbun/ui/album/model/repository/AlbumRepositoryImpl.kt
1
2083
package com.sangcomz.fishbun.ui.album.model.repository import android.os.Build import com.sangcomz.fishbun.datasource.CameraDataSource import com.sangcomz.fishbun.datasource.FishBunDataSource import com.sangcomz.fishbun.datasource.ImageDataSource import com.sangcomz.fishbun.ui.album.model.Album import com.sangcomz.fishbun.ui.album.model.AlbumMetaData import com.sangcomz.fishbun.ui.album.model.AlbumViewData import com.sangcomz.fishbun.util.future.CallableFutureTask class AlbumRepositoryImpl( private val imageDataSource: ImageDataSource, private val fishBunDataSource: FishBunDataSource, private val cameraDataSource: CameraDataSource ) : AlbumRepository { private var viewData: AlbumViewData? = null override fun getAlbumList(): CallableFutureTask<List<Album>> { return imageDataSource.getAlbumList( fishBunDataSource.getAllViewTitle(), fishBunDataSource.getExceptMimeTypeList(), fishBunDataSource.getSpecifyFolderList() ) } override fun getAlbumMetaData(albumId: Long): CallableFutureTask<AlbumMetaData> { return imageDataSource.getAlbumMetaData( albumId, fishBunDataSource.getExceptMimeTypeList(), fishBunDataSource.getSpecifyFolderList() ) } override fun getAlbumViewData(): AlbumViewData { return viewData ?: fishBunDataSource.getAlbumViewData().also { viewData = it } } override fun getImageAdapter() = fishBunDataSource.getImageAdapter() override fun getSelectedImageList() = fishBunDataSource.getSelectedImageList() override fun getAlbumMenuViewData() = fishBunDataSource.gatAlbumMenuViewData() override fun getMessageNotingSelected() = fishBunDataSource.getMessageNothingSelected() override fun getMinCount() = fishBunDataSource.getMinCount() override fun getDefaultSavePath(): String? { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { cameraDataSource.getPicturePath() } else { cameraDataSource.getCameraPath() } } }
apache-2.0
d50899305c3c72add31882a88db823b9
35.561404
91
0.744119
4.959524
false
false
false
false
RyotaMurohoshi/KotLinq
src/test/kotlin/com/muhron/kotlinq/AnyTest.kt
1
705
package com.muhron.kotlinq import org.junit.Assert import org.junit.Test class AnyTest { @Test fun test0() { val result = sequenceOf(1, 2, 3).any() Assert.assertTrue(result) } @Test fun test1() { val result = emptySequence<Int>().any() Assert.assertFalse(result) } @Test fun test2() { val result = sequenceOf(1, 2, 3).any { it < 5 } Assert.assertTrue(result) } @Test fun test3() { val result = sequenceOf(1, 2, 3).any { it > 5 } Assert.assertFalse(result) } @Test fun test4() { val result = emptySequence<Int>().any { it > 5 } Assert.assertFalse(result) } }
mit
2249179f41f39189916e5f1e5e95d6ac
18.054054
56
0.547518
3.634021
false
true
false
false
FolioReader/FolioReader-Android
folioreader/src/main/java/com/folioreader/ui/view/FolioWebView.kt
1
31278
package com.folioreader.ui.view import android.content.Context import android.graphics.Rect import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper import android.util.AttributeSet import android.util.DisplayMetrics import android.util.Log import android.view.* import android.view.ActionMode.Callback import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.webkit.ConsoleMessage import android.webkit.JavascriptInterface import android.webkit.WebView import android.widget.PopupWindow import android.widget.Toast import androidx.annotation.RequiresApi import androidx.core.content.ContextCompat import androidx.core.view.GestureDetectorCompat import com.folioreader.Config import com.folioreader.Constants import com.folioreader.R import com.folioreader.model.DisplayUnit import com.folioreader.model.HighLight import com.folioreader.model.HighlightImpl.HighlightStyle import com.folioreader.model.sqlite.HighLightTable import com.folioreader.ui.activity.FolioActivity import com.folioreader.ui.activity.FolioActivityCallback import com.folioreader.ui.fragment.DictionaryFragment import com.folioreader.ui.fragment.FolioPageFragment import com.folioreader.util.AppUtil import com.folioreader.util.HighlightUtil import com.folioreader.util.UiUtil import dalvik.system.PathClassLoader import kotlinx.android.synthetic.main.text_selection.view.* import org.json.JSONObject import org.springframework.util.ReflectionUtils import java.lang.ref.WeakReference /** * @author by mahavir on 3/31/16. */ class FolioWebView : WebView { companion object { val LOG_TAG: String = FolioWebView::class.java.simpleName private const val IS_SCROLLING_CHECK_TIMER = 100 private const val IS_SCROLLING_CHECK_MAX_DURATION = 10000 @JvmStatic fun onWebViewConsoleMessage(cm: ConsoleMessage, LOG_TAG: String, msg: String): Boolean { when (cm.messageLevel()) { ConsoleMessage.MessageLevel.LOG -> { Log.v(LOG_TAG, msg) return true } ConsoleMessage.MessageLevel.DEBUG, ConsoleMessage.MessageLevel.TIP -> { Log.d(LOG_TAG, msg) return true } ConsoleMessage.MessageLevel.WARNING -> { Log.w(LOG_TAG, msg) return true } ConsoleMessage.MessageLevel.ERROR -> { Log.e(LOG_TAG, msg) return true } else -> return false } } } private var horizontalPageCount = 0 private var displayMetrics: DisplayMetrics? = null private var density: Float = 0.toFloat() private var mScrollListener: ScrollListener? = null private var mSeekBarListener: SeekBarListener? = null private lateinit var gestureDetector: GestureDetectorCompat private var eventActionDown: MotionEvent? = null private var pageWidthCssDp: Int = 0 private var pageWidthCssPixels: Float = 0.toFloat() private lateinit var webViewPager: WebViewPager private lateinit var uiHandler: Handler private lateinit var folioActivityCallback: FolioActivityCallback private lateinit var parentFragment: FolioPageFragment private var actionMode: ActionMode? = null private var textSelectionCb: TextSelectionCb? = null private var textSelectionCb2: TextSelectionCb2? = null private var selectionRect = Rect() private val popupRect = Rect() private var popupWindow = PopupWindow() private lateinit var viewTextSelection: View private var isScrollingCheckDuration: Int = 0 private var isScrollingRunnable: Runnable? = null private var oldScrollX: Int = 0 private var oldScrollY: Int = 0 private var lastTouchAction: Int = 0 private var destroyed: Boolean = false private var handleHeight: Int = 0 private var lastScrollType: LastScrollType? = null val contentHeightVal: Int get() = Math.floor((this.contentHeight * this.scale).toDouble()).toInt() val webViewHeight: Int get() = this.measuredHeight private enum class LastScrollType { USER, PROGRAMMATIC } @JavascriptInterface fun getDirection(): String { return folioActivityCallback.direction.toString() } @JavascriptInterface fun getTopDistraction(unitString: String): Int { val unit = DisplayUnit.valueOf(unitString) return folioActivityCallback.getTopDistraction(unit) } @JavascriptInterface fun getBottomDistraction(unitString: String): Int { val unit = DisplayUnit.valueOf(unitString) return folioActivityCallback.getBottomDistraction(unit) } @JavascriptInterface fun getViewportRect(unitString: String): String { val unit = DisplayUnit.valueOf(unitString) val rect = folioActivityCallback.getViewportRect(unit) return UiUtil.rectToDOMRectJson(rect) } @JavascriptInterface fun toggleSystemUI() { uiHandler.post { folioActivityCallback.toggleSystemUI() } } @JavascriptInterface fun isPopupShowing(): Boolean { return popupWindow.isShowing } private inner class HorizontalGestureListener : GestureDetector.SimpleOnGestureListener() { override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean { //Log.d(LOG_TAG, "-> onScroll -> e1 = " + e1 + ", e2 = " + e2 + ", distanceX = " + distanceX + ", distanceY = " + distanceY); lastScrollType = LastScrollType.USER return false } override fun onFling(e1: MotionEvent?, e2: MotionEvent?, velocityX: Float, velocityY: Float): Boolean { //Log.d(LOG_TAG, "-> onFling -> e1 = " + e1 + ", e2 = " + e2 + ", velocityX = " + velocityX + ", velocityY = " + velocityY); if (!webViewPager.isScrolling) { // Need to complete the scroll as ViewPager thinks these touch events should not // scroll it's pages. //Log.d(LOG_TAG, "-> onFling -> completing scroll"); uiHandler.postDelayed({ // Delayed to avoid inconsistency of scrolling in WebView scrollTo(getScrollXPixelsForPage(webViewPager!!.currentItem), 0) }, 100) } lastScrollType = LastScrollType.USER return true } override fun onDown(event: MotionEvent?): Boolean { //Log.v(LOG_TAG, "-> onDown -> " + event.toString()); eventActionDown = MotionEvent.obtain(event) [email protected](event) return true } } @JavascriptInterface fun dismissPopupWindow(): Boolean { Log.d(LOG_TAG, "-> dismissPopupWindow -> " + parentFragment.spineItem?.href) val wasShowing = popupWindow.isShowing if (Looper.getMainLooper().thread == Thread.currentThread()) { popupWindow.dismiss() } else { uiHandler.post { popupWindow.dismiss() } } selectionRect = Rect() uiHandler.removeCallbacks(isScrollingRunnable) isScrollingCheckDuration = 0 return wasShowing } override fun destroy() { super.destroy() Log.d(LOG_TAG, "-> destroy") dismissPopupWindow() destroyed = true } private inner class VerticalGestureListener : GestureDetector.SimpleOnGestureListener() { override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean { //Log.v(LOG_TAG, "-> onScroll -> e1 = " + e1 + ", e2 = " + e2 + ", distanceX = " + distanceX + ", distanceY = " + distanceY); lastScrollType = LastScrollType.USER return false } override fun onFling(e1: MotionEvent?, e2: MotionEvent?, velocityX: Float, velocityY: Float): Boolean { //Log.v(LOG_TAG, "-> onFling -> e1 = " + e1 + ", e2 = " + e2 + ", velocityX = " + velocityX + ", velocityY = " + velocityY); lastScrollType = LastScrollType.USER return false } } constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) private fun init() { Log.v(LOG_TAG, "-> init") uiHandler = Handler() displayMetrics = resources.displayMetrics density = displayMetrics!!.density gestureDetector = if (folioActivityCallback.direction == Config.Direction.HORIZONTAL) { GestureDetectorCompat(context, HorizontalGestureListener()) } else { GestureDetectorCompat(context, VerticalGestureListener()) } initViewTextSelection() } fun initViewTextSelection() { Log.v(LOG_TAG, "-> initViewTextSelection") val textSelectionMiddleDrawable = ContextCompat.getDrawable( context, R.drawable.abc_text_select_handle_middle_mtrl_dark ) handleHeight = textSelectionMiddleDrawable?.intrinsicHeight ?: (24 * density).toInt() val config = AppUtil.getSavedConfig(context)!! val ctw = if (config.isNightMode) { ContextThemeWrapper(context, R.style.FolioNightTheme) } else { ContextThemeWrapper(context, R.style.FolioDayTheme) } viewTextSelection = LayoutInflater.from(ctw).inflate(R.layout.text_selection, null) viewTextSelection.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED) viewTextSelection.yellowHighlight.setOnClickListener { Log.v(LOG_TAG, "-> onClick -> yellowHighlight") onHighlightColorItemsClicked(HighlightStyle.Yellow, false) } viewTextSelection.greenHighlight.setOnClickListener { Log.v(LOG_TAG, "-> onClick -> greenHighlight") onHighlightColorItemsClicked(HighlightStyle.Green, false) } viewTextSelection.blueHighlight.setOnClickListener { Log.v(LOG_TAG, "-> onClick -> blueHighlight") onHighlightColorItemsClicked(HighlightStyle.Blue, false) } viewTextSelection.pinkHighlight.setOnClickListener { Log.v(LOG_TAG, "-> onClick -> pinkHighlight") onHighlightColorItemsClicked(HighlightStyle.Pink, false) } viewTextSelection.underlineHighlight.setOnClickListener { Log.v(LOG_TAG, "-> onClick -> underlineHighlight") onHighlightColorItemsClicked(HighlightStyle.Underline, false) } viewTextSelection.deleteHighlight.setOnClickListener { Log.v(LOG_TAG, "-> onClick -> deleteHighlight") dismissPopupWindow() loadUrl("javascript:clearSelection()") loadUrl("javascript:deleteThisHighlight()") } viewTextSelection.copySelection.setOnClickListener { dismissPopupWindow() loadUrl("javascript:onTextSelectionItemClicked(${it.id})") } viewTextSelection.shareSelection.setOnClickListener { dismissPopupWindow() loadUrl("javascript:onTextSelectionItemClicked(${it.id})") } viewTextSelection.defineSelection.setOnClickListener { dismissPopupWindow() loadUrl("javascript:onTextSelectionItemClicked(${it.id})") } } @JavascriptInterface fun onTextSelectionItemClicked(id: Int, selectedText: String?) { uiHandler.post { loadUrl("javascript:clearSelection()") } when (id) { R.id.copySelection -> { Log.v(LOG_TAG, "-> onTextSelectionItemClicked -> copySelection -> $selectedText") UiUtil.copyToClipboard(context, selectedText) Toast.makeText(context, context.getString(R.string.copied), Toast.LENGTH_SHORT).show() } R.id.shareSelection -> { Log.v(LOG_TAG, "-> onTextSelectionItemClicked -> shareSelection -> $selectedText") UiUtil.share(context, selectedText) } R.id.defineSelection -> { Log.v(LOG_TAG, "-> onTextSelectionItemClicked -> defineSelection -> $selectedText") uiHandler.post { showDictDialog(selectedText) } } else -> { Log.w(LOG_TAG, "-> onTextSelectionItemClicked -> unknown id = $id") } } } private fun showDictDialog(selectedText: String?) { val dictionaryFragment = DictionaryFragment() val bundle = Bundle() bundle.putString(Constants.SELECTED_WORD, selectedText?.trim()) dictionaryFragment.arguments = bundle dictionaryFragment.show(parentFragment.fragmentManager!!, DictionaryFragment::class.java.name) } private fun onHighlightColorItemsClicked(style: HighlightStyle, isAlreadyCreated: Boolean) { parentFragment.highlight(style, isAlreadyCreated) dismissPopupWindow() } @JavascriptInterface fun deleteThisHighlight(id: String?) { Log.d(LOG_TAG, "-> deleteThisHighlight") if (id.isNullOrEmpty()) return val highlightImpl = HighLightTable.getHighlightForRangy(id) if (HighLightTable.deleteHighlight(id)) { val rangy = HighlightUtil.generateRangyString(parentFragment.pageName) uiHandler.post { parentFragment.loadRangy(rangy) } if (highlightImpl != null) { HighlightUtil.sendHighlightBroadcastEvent( context, highlightImpl, HighLight.HighLightAction.DELETE ) } } } fun setParentFragment(parentFragment: FolioPageFragment) { this.parentFragment = parentFragment } fun setFolioActivityCallback(folioActivityCallback: FolioActivityCallback) { this.folioActivityCallback = folioActivityCallback init() } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { super.onLayout(changed, l, t, r, b) pageWidthCssDp = Math.ceil((measuredWidth / density).toDouble()).toInt() pageWidthCssPixels = pageWidthCssDp * density } fun setScrollListener(listener: ScrollListener) { mScrollListener = listener } fun setSeekBarListener(listener: SeekBarListener) { mSeekBarListener = listener } override fun onTouchEvent(event: MotionEvent?): Boolean { //Log.v(LOG_TAG, "-> onTouchEvent -> " + AppUtil.actionToString(event.getAction())); if (event == null) return false lastTouchAction = event.action return if (folioActivityCallback.direction == Config.Direction.HORIZONTAL) { computeHorizontalScroll(event) } else { computeVerticalScroll(event) } } private fun computeVerticalScroll(event: MotionEvent): Boolean { gestureDetector.onTouchEvent(event) return super.onTouchEvent(event) } private fun computeHorizontalScroll(event: MotionEvent): Boolean { //Log.v(LOG_TAG, "-> computeHorizontalScroll"); // Rare condition in fast scrolling if (!::webViewPager.isInitialized) return super.onTouchEvent(event) webViewPager.dispatchTouchEvent(event) val gestureReturn = gestureDetector.onTouchEvent(event) return if (gestureReturn) true else super.onTouchEvent(event) } fun getScrollXDpForPage(page: Int): Int { //Log.v(LOG_TAG, "-> getScrollXDpForPage -> page = " + page); return page * pageWidthCssDp } fun getScrollXPixelsForPage(page: Int): Int { //Log.v(LOG_TAG, "-> getScrollXPixelsForPage -> page = " + page); return Math.ceil((page * pageWidthCssPixels).toDouble()).toInt() } fun setHorizontalPageCount(horizontalPageCount: Int) { this.horizontalPageCount = horizontalPageCount uiHandler.post { webViewPager = (parent as View).findViewById(R.id.webViewPager) webViewPager.setHorizontalPageCount([email protected]) } } override fun scrollTo(x: Int, y: Int) { super.scrollTo(x, y) //Log.d(LOG_TAG, "-> scrollTo -> x = " + x); lastScrollType = LastScrollType.PROGRAMMATIC } override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) { if (mScrollListener != null) mScrollListener!!.onScrollChange(t) super.onScrollChanged(l, t, oldl, oldt) if (lastScrollType == LastScrollType.USER) { //Log.d(LOG_TAG, "-> onScrollChanged -> scroll initiated by user"); parentFragment.searchLocatorVisible = null } lastScrollType = null } interface ScrollListener { fun onScrollChange(percent: Int) } interface SeekBarListener { fun fadeInSeekBarIfInvisible() } private inner class TextSelectionCb : ActionMode.Callback { override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { Log.d(LOG_TAG, "-> onCreateActionMode") return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { Log.d(LOG_TAG, "-> onPrepareActionMode") evaluateJavascript("javascript:getSelectionRect()") { value -> val rectJson = JSONObject(value) setSelectionRect( rectJson.getInt("left"), rectJson.getInt("top"), rectJson.getInt("right"), rectJson.getInt("bottom") ) } return false } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { Log.d(LOG_TAG, "-> onActionItemClicked") return false } override fun onDestroyActionMode(mode: ActionMode) { Log.d(LOG_TAG, "-> onDestroyActionMode") dismissPopupWindow() } } @RequiresApi(api = Build.VERSION_CODES.M) private inner class TextSelectionCb2 : ActionMode.Callback2() { override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { Log.d(LOG_TAG, "-> onCreateActionMode") menu.clear() return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { Log.d(LOG_TAG, "-> onPrepareActionMode") return false } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { Log.d(LOG_TAG, "-> onActionItemClicked") return false } override fun onDestroyActionMode(mode: ActionMode) { Log.d(LOG_TAG, "-> onDestroyActionMode") dismissPopupWindow() } override fun onGetContentRect(mode: ActionMode, view: View, outRect: Rect) { Log.d(LOG_TAG, "-> onGetContentRect") evaluateJavascript("javascript:getSelectionRect()") { value -> val rectJson = JSONObject(value) setSelectionRect( rectJson.getInt("left"), rectJson.getInt("top"), rectJson.getInt("right"), rectJson.getInt("bottom") ) } } } override fun startActionMode(callback: Callback): ActionMode { Log.d(LOG_TAG, "-> startActionMode") textSelectionCb = TextSelectionCb() actionMode = super.startActionMode(textSelectionCb) actionMode?.finish() /*try { applyThemeColorToHandles() } catch (e: Exception) { Log.w(LOG_TAG, "-> startActionMode -> Failed to apply theme colors to selection " + "handles", e) }*/ return actionMode as ActionMode //Comment above code and uncomment below line for stock text selection //return super.startActionMode(callback) } @RequiresApi(api = Build.VERSION_CODES.M) override fun startActionMode(callback: Callback, type: Int): ActionMode { Log.d(LOG_TAG, "-> startActionMode") textSelectionCb2 = TextSelectionCb2() actionMode = super.startActionMode(textSelectionCb2, type) actionMode?.finish() /*try { applyThemeColorToHandles() } catch (e: Exception) { Log.w(LOG_TAG, "-> startActionMode -> Failed to apply theme colors to selection " + "handles", e) }*/ return actionMode as ActionMode //Comment above code and uncomment below line for stock text selection //return super.startActionMode(callback, type) } private fun applyThemeColorToHandles() { Log.v(LOG_TAG, "-> applyThemeColorToHandles") if (Build.VERSION.SDK_INT < 23) { val folioActivityRef: WeakReference<FolioActivity> = folioActivityCallback.activity val mWindowManagerField = ReflectionUtils.findField(FolioActivity::class.java, "mWindowManager") mWindowManagerField.isAccessible = true val mWindowManager = mWindowManagerField.get(folioActivityRef.get()) val windowManagerImplClass = Class.forName("android.view.WindowManagerImpl") val mGlobalField = ReflectionUtils.findField(windowManagerImplClass, "mGlobal") mGlobalField.isAccessible = true val mGlobal = mGlobalField.get(mWindowManager) val windowManagerGlobalClass = Class.forName("android.view.WindowManagerGlobal") val mViewsField = ReflectionUtils.findField(windowManagerGlobalClass, "mViews") mViewsField.isAccessible = true val mViews = mViewsField.get(mGlobal) as ArrayList<View> val config = AppUtil.getSavedConfig(context)!! for (view in mViews) { val handleViewClass = Class.forName("com.android.org.chromium.content.browser.input.HandleView") if (handleViewClass.isInstance(view)) { val mDrawableField = ReflectionUtils.findField(handleViewClass, "mDrawable") mDrawableField.isAccessible = true val mDrawable = mDrawableField.get(view) as BitmapDrawable UiUtil.setColorIntToDrawable(config.themeColor, mDrawable) } } } else { val folioActivityRef: WeakReference<FolioActivity> = folioActivityCallback.activity val mWindowManagerField = ReflectionUtils.findField(FolioActivity::class.java, "mWindowManager") mWindowManagerField.isAccessible = true val mWindowManager = mWindowManagerField.get(folioActivityRef.get()) val windowManagerImplClass = Class.forName("android.view.WindowManagerImpl") val mGlobalField = ReflectionUtils.findField(windowManagerImplClass, "mGlobal") mGlobalField.isAccessible = true val mGlobal = mGlobalField.get(mWindowManager) val windowManagerGlobalClass = Class.forName("android.view.WindowManagerGlobal") val mViewsField = ReflectionUtils.findField(windowManagerGlobalClass, "mViews") mViewsField.isAccessible = true val mViews = mViewsField.get(mGlobal) as ArrayList<View> val config = AppUtil.getSavedConfig(context)!! for (view in mViews) { val popupDecorViewClass = Class.forName("android.widget.PopupWindow\$PopupDecorView") if (!popupDecorViewClass.isInstance(view)) continue val mChildrenField = ReflectionUtils.findField(popupDecorViewClass, "mChildren") mChildrenField.isAccessible = true val mChildren = mChildrenField.get(view) as kotlin.Array<View> //val pathClassLoader = PathClassLoader("/system/app/Chrome/Chrome.apk", ClassLoader.getSystemClassLoader()) val pathClassLoader = PathClassLoader("/system/app/Chrome/Chrome.apk", folioActivityRef.get()?.classLoader) val popupTouchHandleDrawableClass = Class.forName( "org.chromium.android_webview.PopupTouchHandleDrawable", true, pathClassLoader ) //if (!popupTouchHandleDrawableClass.isInstance(mChildren[0])) // continue val mDrawableField = ReflectionUtils.findField(popupTouchHandleDrawableClass, "mDrawable") mDrawableField.isAccessible = true val mDrawable = mDrawableField.get(mChildren[0]) as Drawable UiUtil.setColorIntToDrawable(config.themeColor, mDrawable) } } } @JavascriptInterface fun setSelectionRect(left: Int, top: Int, right: Int, bottom: Int) { val currentSelectionRect = Rect() currentSelectionRect.left = (left * density).toInt() currentSelectionRect.top = (top * density).toInt() currentSelectionRect.right = (right * density).toInt() currentSelectionRect.bottom = (bottom * density).toInt() Log.d(LOG_TAG, "-> setSelectionRect -> $currentSelectionRect") computeTextSelectionRect(currentSelectionRect) uiHandler.post { showTextSelectionPopup() } } private fun computeTextSelectionRect(currentSelectionRect: Rect) { Log.v(LOG_TAG, "-> computeTextSelectionRect") val viewportRect = folioActivityCallback.getViewportRect(DisplayUnit.PX) Log.d(LOG_TAG, "-> viewportRect -> $viewportRect") if (!Rect.intersects(viewportRect, currentSelectionRect)) { Log.i(LOG_TAG, "-> currentSelectionRect doesn't intersects viewportRect") uiHandler.post { popupWindow.dismiss() uiHandler.removeCallbacks(isScrollingRunnable) } return } Log.i(LOG_TAG, "-> currentSelectionRect intersects viewportRect") if (selectionRect == currentSelectionRect) { Log.i( LOG_TAG, "-> setSelectionRect -> currentSelectionRect is equal to previous " + "selectionRect so no need to computeTextSelectionRect and show popupWindow again" ) return } Log.i( LOG_TAG, "-> setSelectionRect -> currentSelectionRect is not equal to previous " + "selectionRect so computeTextSelectionRect and show popupWindow" ) selectionRect = currentSelectionRect val aboveSelectionRect = Rect(viewportRect) aboveSelectionRect.bottom = selectionRect.top - (8 * density).toInt() val belowSelectionRect = Rect(viewportRect) belowSelectionRect.top = selectionRect.bottom + handleHeight //Log.d(LOG_TAG, "-> aboveSelectionRect -> " + aboveSelectionRect); //Log.d(LOG_TAG, "-> belowSelectionRect -> " + belowSelectionRect); // Priority to show popupWindow will be as following - // 1. Show popupWindow below selectionRect, if space available // 2. Show popupWindow above selectionRect, if space available // 3. Show popupWindow in the middle of selectionRect //popupRect initialisation for belowSelectionRect popupRect.left = viewportRect.left popupRect.top = belowSelectionRect.top popupRect.right = popupRect.left + viewTextSelection.measuredWidth popupRect.bottom = popupRect.top + viewTextSelection.measuredHeight //Log.d(LOG_TAG, "-> Pre decision popupRect -> " + popupRect); val popupY: Int if (belowSelectionRect.contains(popupRect)) { Log.i(LOG_TAG, "-> show below") popupY = belowSelectionRect.top } else { // popupRect initialisation for aboveSelectionRect popupRect.top = aboveSelectionRect.top popupRect.bottom = popupRect.top + viewTextSelection.measuredHeight if (aboveSelectionRect.contains(popupRect)) { Log.i(LOG_TAG, "-> show above") popupY = aboveSelectionRect.bottom - popupRect.height() } else { Log.i(LOG_TAG, "-> show in middle") val popupYDiff = (viewTextSelection.measuredHeight - selectionRect.height()) / 2 popupY = selectionRect.top - popupYDiff } } val popupXDiff = (viewTextSelection.measuredWidth - selectionRect.width()) / 2 val popupX = selectionRect.left - popupXDiff popupRect.offsetTo(popupX, popupY) //Log.d(LOG_TAG, "-> Post decision popupRect -> " + popupRect); // Check if popupRect left side is going outside of the viewportRect if (popupRect.left < viewportRect.left) { popupRect.right += 0 - popupRect.left popupRect.left = 0 } // Check if popupRect right side is going outside of the viewportRect if (popupRect.right > viewportRect.right) { val dx = popupRect.right - viewportRect.right popupRect.left -= dx popupRect.right -= dx } } private fun showTextSelectionPopup() { Log.v(LOG_TAG, "-> showTextSelectionPopup") Log.d(LOG_TAG, "-> showTextSelectionPopup -> To be laid out popupRect -> $popupRect") popupWindow.dismiss() oldScrollX = scrollX oldScrollY = scrollY isScrollingRunnable = Runnable { uiHandler.removeCallbacks(isScrollingRunnable) val currentScrollX = scrollX val currentScrollY = scrollY val inTouchMode = lastTouchAction == MotionEvent.ACTION_DOWN || lastTouchAction == MotionEvent.ACTION_MOVE if (oldScrollX == currentScrollX && oldScrollY == currentScrollY && !inTouchMode) { Log.i(LOG_TAG, "-> Stopped scrolling, show Popup") popupWindow.dismiss() popupWindow = PopupWindow(viewTextSelection, WRAP_CONTENT, WRAP_CONTENT) popupWindow.isClippingEnabled = false popupWindow.showAtLocation( this@FolioWebView, Gravity.NO_GRAVITY, popupRect.left, popupRect.top ) } else { Log.i(LOG_TAG, "-> Still scrolling, don't show Popup") oldScrollX = currentScrollX oldScrollY = currentScrollY isScrollingCheckDuration += IS_SCROLLING_CHECK_TIMER if (isScrollingCheckDuration < IS_SCROLLING_CHECK_MAX_DURATION && !destroyed) uiHandler.postDelayed(isScrollingRunnable, IS_SCROLLING_CHECK_TIMER.toLong()) } } uiHandler.removeCallbacks(isScrollingRunnable) isScrollingCheckDuration = 0 if (!destroyed) uiHandler.postDelayed(isScrollingRunnable, IS_SCROLLING_CHECK_TIMER.toLong()) } }
bsd-3-clause
4c06a0f41613fcbb5798be6f77bd34b9
37.951432
137
0.636965
5.234812
false
false
false
false
rock3r/detekt
detekt-gradle-plugin/src/main/kotlin/io/gitlab/arturbosch/detekt/DetektCreateBaselineTask.kt
1
3895
package io.gitlab.arturbosch.detekt import io.gitlab.arturbosch.detekt.internal.configurableFileCollection import io.gitlab.arturbosch.detekt.invoke.AutoCorrectArgument import io.gitlab.arturbosch.detekt.invoke.BaselineArgument import io.gitlab.arturbosch.detekt.invoke.BuildUponDefaultConfigArgument import io.gitlab.arturbosch.detekt.invoke.ConfigArgument import io.gitlab.arturbosch.detekt.invoke.CreateBaselineArgument import io.gitlab.arturbosch.detekt.invoke.DebugArgument import io.gitlab.arturbosch.detekt.invoke.DetektInvoker import io.gitlab.arturbosch.detekt.invoke.DisableDefaultRuleSetArgument import io.gitlab.arturbosch.detekt.invoke.FailFastArgument import io.gitlab.arturbosch.detekt.invoke.InputArgument import io.gitlab.arturbosch.detekt.invoke.ParallelArgument import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Classpath import org.gradle.api.tasks.Console import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Internal import org.gradle.api.tasks.Optional import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.SourceTask import org.gradle.api.tasks.TaskAction import org.gradle.language.base.plugins.LifecycleBasePlugin @CacheableTask open class DetektCreateBaselineTask : SourceTask() { init { description = "Creates a detekt baseline on the given --baseline path." group = LifecycleBasePlugin.VERIFICATION_GROUP } @get:OutputFile val baseline: RegularFileProperty = project.objects.fileProperty() @get:InputFiles @get:Optional @PathSensitive(PathSensitivity.RELATIVE) val config: ConfigurableFileCollection = project.configurableFileCollection() @get:Classpath val detektClasspath = project.configurableFileCollection() @get:Classpath val pluginClasspath = project.configurableFileCollection() @get:Console val debug: Property<Boolean> = project.objects.property(Boolean::class.javaObjectType) @get:Internal val parallel: Property<Boolean> = project.objects.property(Boolean::class.javaObjectType) @get:Input @get:Optional val disableDefaultRuleSets: Property<Boolean> = project.objects.property(Boolean::class.javaObjectType) @get:Input @get:Optional val buildUponDefaultConfig: Property<Boolean> = project.objects.property(Boolean::class.javaObjectType) @get:Input @get:Optional val failFast: Property<Boolean> = project.objects.property(Boolean::class.javaObjectType) @get:Input @get:Optional val ignoreFailures: Property<Boolean> = project.objects.property(Boolean::class.javaObjectType) @get:Input @get:Optional val autoCorrect: Property<Boolean> = project.objects.property(Boolean::class.javaObjectType) @TaskAction fun baseline() { val arguments = mutableListOf( CreateBaselineArgument, BaselineArgument(baseline.get()), InputArgument(source), ConfigArgument(config), DebugArgument(debug.getOrElse(false)), ParallelArgument(parallel.getOrElse(false)), BuildUponDefaultConfigArgument(buildUponDefaultConfig.getOrElse(false)), FailFastArgument(failFast.getOrElse(false)), AutoCorrectArgument(autoCorrect.getOrElse(false)), DisableDefaultRuleSetArgument(disableDefaultRuleSets.getOrElse(false)) ) DetektInvoker.create(project).invokeCli( arguments = arguments.toList(), ignoreFailures = ignoreFailures.getOrElse(false), classpath = detektClasspath.plus(pluginClasspath), taskName = name ) } }
apache-2.0
c0cb5c0df2d4ba42057db80e3e2ceec0
37.186275
107
0.765597
4.582353
false
true
false
false
tfcbandgeek/SmartReminders-android
smartreminderssave/src/main/java/jgappsandgames/smartreminderssave/tasks/TaskManager.kt
1
10571
package jgappsandgames.smartreminderssave.tasks // Java import java.io.File import java.io.IOException // JSONObject import org.json.JSONArray import org.json.JSONException import org.json.JSONObject // Pool Utility import jgappsandgames.me.poolutilitykotlin.Pool // Save Library import jgappsandgames.smartreminderssave.settings.SettingsManager import jgappsandgames.smartreminderssave.utility.* /** * TaskManager * Created by joshua on 12/12/2017. * Last Edited on 5/01/2019 */ class TaskManager { companion object { // Constants ------------------------------------------------------------------------------- private const val FILENAME = "taskmanager.srj" private const val VERSION = "version" private const val META = "meta" private const val HOME = "home" private const val TASKS = "tasks" private const val ARCHIVED = "archived" private const val DELETED = "deleted" private const val VERSION_12 = "version" private const val META_12 = "meta" private const val HOME_12 = "home" private const val TASKS_12 = "tasks" private const val ARCHIVED_12 = "archived" private const val DELETED_12 = "deleted" // Pools ----------------------------------------------------------------------------------- val taskPool = Pool(maxSize = 100, minSize = 20, generator = TaskCreator()) // Data ------------------------------------------------------------------------------------ private var version: Int = 0 private var meta: JSONObject = JSONObject() private var home: ArrayList<String> = ArrayList() private var tasks: ArrayList<String> = ArrayList() private var archived: ArrayList<String> = ArrayList() private var deleted: ArrayList<String> = ArrayList() // Management Methods ---------------------------------------------------------------------- @JvmStatic fun create() { if (File(FileUtility.getApplicationDataDirectory(), FILENAME).exists()) load() else forceCreate() } @JvmStatic fun forceCreate() { version = SettingsManager.getUseVersion() meta = JSONObject() home.clear() tasks.clear() archived.clear() deleted.clear() } @JvmStatic fun load() { try { loadJSON(JSONUtility.loadJSONObject(File(FileUtility.getApplicationDataDirectory(), FILENAME))) } catch (i: IOException) { i.printStackTrace() create() save() } if (deleted.size >= 50) deleted.removeAt(0) } @JvmStatic fun save() = JSONUtility.saveJSONObject(File(FileUtility.getApplicationDataDirectory(), FILENAME), saveJSON()) @JvmStatic fun clearTasks() { for (task in archived) deleteTask(Task(task)) archived = ArrayList() save() } // JSONManagement Methods ------------------------------------------------------------------ @JvmStatic fun loadJSON(data: JSONObject?) { if (data == null) { create() return } version = data.optInt(VERSION, API.RELEASE) if (version <= API.MANAGEMENT) { home.clear() tasks.clear() archived.clear() deleted.clear() val h = data.optJSONArray(HOME) val t = data.optJSONArray(TASKS) val a = data.optJSONArray(ARCHIVED) val d = data.optJSONArray(DELETED) if (h != null && h.length() != 0) for (i in 0 until h.length()) if (!home.contains(h.optString(i))) home.add(h.optString(i)) if (t != null && t.length() != 0) for (i in 0 until t.length()) if (!tasks.contains(t.optString(i))) tasks.add(t.optString(i)) if (a != null && a.length() != 0) for (i in 0 until a.length()) if (!archived.contains(a.optString(i))) archived.add(a.optString(i)) if (d != null && d.length() != 0) for (i in 0 until d.length()) if (!deleted.contains(d.optString(i))) deleted.add(d.optString(i)) // API 11 meta = if (version >= API.MANAGEMENT) data.optJSONObject(META) else JSONObject() } else { home.clear() tasks.clear() archived.clear() deleted.clear() val h = data.optJSONArray(HOME_12) val t = data.optJSONArray(TASKS_12) val a = data.optJSONArray(ARCHIVED_12) val d = data.optJSONArray(DELETED_12) if (h != null && h.length() != 0) for (i in 0 until h.length()) if (!home.contains(h.optString(i))) home.add(h.optString(i)) if (t != null && t.length() != 0) for (i in 0 until t.length()) if (!tasks.contains(t.optString(i))) tasks.add(t.optString(i)) if (a != null && a.length() != 0) for (i in 0 until a.length()) if (!archived.contains(a.optString(i))) archived.add(a.optString(i)) if (d != null && d.length() != 0) for (i in 0 until d.length()) if (!deleted.contains(d.optString(i))) deleted.add(d.optString(i)) // API 11 meta = if (version >= API.MANAGEMENT) data.optJSONObject(META_12) else JSONObject() } } @JvmStatic fun saveJSON(): JSONObject { val data = JSONObject() try { data.put(VERSION, API.MANAGEMENT) val h = JSONArray() val t = JSONArray() val a = JSONArray() val d = JSONArray() for (task in home) h.put(task) for (task in tasks) t.put(task) for (task in archived) a.put(task) for (task in deleted) d.put(task) if (SettingsManager.getUseVersion() <= 11) { data.put(META, meta) data.put(HOME, h) data.put(TASKS, t) data.put(ARCHIVED, a) data.put(DELETED, d) } else { data.put(VERSION_12, API.MANAGEMENT) data.put(META_12, meta) data.put(HOME_12, h) data.put(TASKS_12, t) data.put(ARCHIVED_12, a) data.put(DELETED_12, d) } } catch (j: JSONException) { j.printStackTrace() } return data } // Task Methods ---------------------------------------------------------------------------- @JvmStatic fun addTask(task: Task, home: Boolean): Task { if (home) { TaskManager.home.add(task.getFilename()) tasks.add(task.getFilename()) save() } else { val p = Task(task.getParent()) p.addChild(task.getFilename()) tasks.add(task.getFilename()) p.save() save() } return task } @JvmStatic fun archiveTask(task: Task) { task.markArchived() task.save() when { task.getParent() == "home" -> home.remove(task.getFilename()) tasks.contains(task.getParent()) -> { val parent = taskPool.getPoolObject().load(task.getParent()) parent.removeChild(task.getFilename()) parent.save() taskPool.returnPoolObject(parent) } else -> { try { val parent = taskPool.getPoolObject().load(task.getParent()) parent.removeChild(task.getFilename()) parent.save() taskPool.returnPoolObject(parent) } catch (e: Exception) { e.printStackTrace() } } } if (task.getType() == Task.TYPE_FOLDER) { val children: ArrayList<String> = task.getChildren().clone() as ArrayList<String> val t = taskPool.getPoolObject() for (i in 0 until children.size) archiveTask(t.load(children[i])) taskPool.returnPoolObject(t) } tasks.remove(task.getFilename()) archived.add(task.getFilename()) save() } @JvmStatic fun deleteTask(task: Task): Boolean { if (archived.contains(task.getFilename())) { task.delete() deleted.add(task.getFilename()) archived.remove(task.getFilename()) save() return true } return false } // Getters --------------------------------------------------------------------------------- fun getHome(): ArrayList<String> = home fun getHomeTasks(): ArrayList<Task> { val t = ArrayList<Task>() for (i in 0 until home.size) t.add(taskPool.getPoolObject().load(home[i])) return t } fun getAll(): ArrayList<String> = tasks fun getAllTasks(): ArrayList<Task> { val t = ArrayList<Task>() for (i in 0 until tasks.size) t.add(taskPool.getPoolObject().load(tasks[i])) return t } fun getArchived(): ArrayList<String> = archived fun getArchivedTasks(): ArrayList<Task> { val t = ArrayList<Task>() for (i in 0 until archived.size) t.add(taskPool.getPoolObject().load(archived[i])) return t } fun getDeleted(): ArrayList<String> = deleted fun getDeletedTasks(): ArrayList<Task> { val t = ArrayList<Task>() for (i in 0 until deleted.size) t.add(taskPool.getPoolObject().load(deleted[i])) return t } } }
apache-2.0
efaac3f74208a6b51434b10950f7761b
34.59596
129
0.469965
4.882679
false
false
false
false
WijayaPrinting/wp-javafx
openpss-client-javafx/src/com/hendraanggrian/openpss/ui/schedule/ScheduleController.kt
1
5009
package com.hendraanggrian.openpss.ui.schedule import com.hendraanggrian.openpss.PATTERN_DATETIMEEXT import com.hendraanggrian.openpss.R import com.hendraanggrian.openpss.R2 import com.hendraanggrian.openpss.api.OpenPSSApi import com.hendraanggrian.openpss.control.Action import com.hendraanggrian.openpss.control.UncollapsibleTreeItem import com.hendraanggrian.openpss.schema.Invoice import com.hendraanggrian.openpss.schema.no import com.hendraanggrian.openpss.ui.ActionController import com.hendraanggrian.openpss.ui.Refreshable import com.hendraanggrian.openpss.util.stringCell import java.net.URL import java.util.ResourceBundle import javafx.fxml.FXML import javafx.scene.control.Button import javafx.scene.control.SelectionMode.MULTIPLE import javafx.scene.control.ToggleButton import javafx.scene.control.TreeItem import javafx.scene.control.TreeTableColumn import javafx.scene.control.TreeTableView import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import ktfx.collections.emptyBinding import ktfx.coroutines.listener import ktfx.coroutines.onAction import ktfx.jfoenix.layouts.jfxToggleButton import ktfx.layouts.NodeManager import ktfx.layouts.borderPane import ktfx.or import ktfx.runLater import ktfx.toStringBinding class ScheduleController : ActionController(), Refreshable { @FXML lateinit var scheduleTable: TreeTableView<Schedule> @FXML lateinit var jobType: TreeTableColumn<Schedule, String> @FXML lateinit var descColumn: TreeTableColumn<Schedule, String> @FXML lateinit var qtyColumn: TreeTableColumn<Schedule, String> @FXML lateinit var typeColumn: TreeTableColumn<Schedule, String> private lateinit var refreshButton: Button private lateinit var doneButton: Button private lateinit var historyCheck: ToggleButton override fun NodeManager.onCreateActions() { refreshButton = addChild(Action(getString(R2.string.refresh), R.image.action_refresh).apply { onAction { refresh() } }) doneButton = addChild(Action(getString(R2.string.done), R.image.action_done).apply { onAction { OpenPSSApi.editInvoice( scheduleTable.selectionModel.selectedItem.value.invoice.apply { isDone = true } ) refresh() } }) borderPane { minHeight = 50.0 maxHeight = 50.0 historyCheck = jfxToggleButton { text = getString(R2.string.history) selectedProperty().listener { refresh() } doneButton.disableProperty() .bind(scheduleTable.selectionModel.selectedItems.emptyBinding or selectedProperty()) } } } override fun initialize(location: URL, resources: ResourceBundle) { super.initialize(location, resources) scheduleTable.run { root = TreeItem() selectionModel.selectionMode = MULTIPLE selectionModel.selectedItemProperty().listener { _, _, value -> if (value != null) when { value.children.isEmpty() -> selectionModel.selectAll(value.parent) else -> selectionModel.selectAll(value) } } titleProperty().bind(selectionModel.selectedItemProperty().toStringBinding { Invoice.no(this@ScheduleController, it?.value?.invoice?.no) }) } jobType.stringCell { jobType } descColumn.stringCell { title } qtyColumn.stringCell { qty } typeColumn.stringCell { type } } override fun refresh() = runLater { scheduleTable.selectionModel.clearSelection() scheduleTable.root.children.run { clear() runBlocking { when (historyCheck.isSelected) { true -> OpenPSSApi.getInvoices(isDone = true, page = 1, count = 20).items else -> OpenPSSApi.getInvoices(isDone = false, page = 1, count = 100).items } }.forEach { invoice -> addAll( UncollapsibleTreeItem( Schedule( invoice, runBlocking(Dispatchers.IO) { OpenPSSApi.getCustomer(invoice.customerId).name }, "", "", invoice.dateTime.toString(PATTERN_DATETIMEEXT) ) ).apply { Schedule.of(this@ScheduleController, invoice) .forEach { children += TreeItem<Schedule>(it) } }) } } } private fun <S> TreeTableView.TreeTableViewSelectionModel<S>.selectAll(parent: TreeItem<S>) { select(parent) parent.children.forEach { select(it) } } }
apache-2.0
2a226ba8bd4bd82d766ff1018c5fcaca
38.440945
104
0.62787
5.074975
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/PlaysSummaryActivity.kt
1
1207
package com.boardgamegeek.ui import android.view.MenuItem import androidx.activity.viewModels import androidx.fragment.app.Fragment import com.boardgamegeek.R import com.boardgamegeek.extensions.createThemedBuilder import com.boardgamegeek.ui.viewmodel.PlaysSummaryViewModel class PlaysSummaryActivity : TopLevelSinglePaneActivity() { private val viewModel by viewModels<PlaysSummaryViewModel>() override val optionsMenuId = R.menu.plays_summary override val firebaseContentType = "PlaysSummary" override fun onCreatePane(): Fragment = PlaysSummaryFragment() override val navigationItemId = R.id.plays override fun onOptionsItemSelected(item: MenuItem): Boolean { return if (item.itemId == R.id.re_sync) { createThemedBuilder() .setTitle(getString(R.string.pref_sync_re_sync_plays) + "?") .setMessage(R.string.pref_sync_re_sync_plays_info_message) .setPositiveButton(R.string.re_sync) { _, _ -> viewModel.reset() } .setNegativeButton(R.string.cancel, null) .setCancelable(true) .show() true } else super.onOptionsItemSelected(item) } }
gpl-3.0
90cd76f778c5a6a244721cde9abe847d
35.575758
82
0.695112
4.554717
false
false
false
false
fossasia/open-event-android
app/src/fdroid/java/org/fossasia/openevent/general/search/location/LocationServiceImpl.kt
1
2735
package org.fossasia.openevent.general.search.location import android.annotation.SuppressLint import android.content.Context import android.location.Geocoder import android.location.Location import android.location.LocationListener import android.location.LocationManager import android.os.Bundle import io.reactivex.Single import java.lang.IllegalArgumentException import java.util.Locale import org.fossasia.openevent.general.R import org.fossasia.openevent.general.data.Resource import org.fossasia.openevent.general.utils.nullToEmpty class LocationServiceImpl( private val context: Context, private val resource: Resource ) : LocationService { @SuppressLint("MissingPermission") override fun getAdministrativeArea(): Single<String> { val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return Single.error(IllegalStateException()) val geoCoder = Geocoder(context, Locale.getDefault()) return Single.create { emitter -> try { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0f, object : LocationListener { override fun onLocationChanged(location: Location?) { if (location == null) { emitter.onError(java.lang.IllegalStateException()) return } val addresses = geoCoder.getFromLocation(location.latitude, location.longitude, 1) try { val adminArea = if (addresses.isNotEmpty()) addresses[0].adminArea else resource.getString(R.string.no_location).nullToEmpty() emitter.onSuccess(adminArea) } catch (e: IllegalArgumentException) { emitter.onError(e) } } override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) { // To change body of created functions use File | Settings | File Templates. } override fun onProviderEnabled(provider: String?) { // To change body of created functions use File | Settings | File Templates. } override fun onProviderDisabled(provider: String?) { // To change body of created functions use File | Settings | File Templates. } }) } catch (e: SecurityException) { emitter.onError(e) } } } }
apache-2.0
ec71701af2099ccb08103917c108c735
41.734375
106
0.592687
5.856531
false
false
false
false
andersonlucasg3/SpriteKit-Android
SpriteKitLib/src/main/java/br/com/insanitech/spritekit/opengl/renderer/GLRenderer.kt
1
2101
package br.com.insanitech.spritekit.opengl.renderer import android.opengl.GLSurfaceView import java.nio.ByteBuffer import javax.microedition.khronos.egl.EGLConfig import javax.microedition.khronos.opengles.GL10 import br.com.insanitech.spritekit.opengl.model.GLCircle import br.com.insanitech.spritekit.opengl.model.GLColor import br.com.insanitech.spritekit.opengl.model.GLRectangle import br.com.insanitech.spritekit.opengl.model.GLTexture /** * Created by anderson on 6/29/15. */ internal abstract class GLRenderer : GLSurfaceView.Renderer { private var drawer: GLDrawer protected var width: Int = 0 protected var height: Int = 0 protected var circle = GLCircle() protected var rectangle = GLRectangle() protected var whiteColor = GLColor.rgba(1f, 1f, 1f, 1f) constructor(drawer: GLDrawer) { this.drawer = drawer } abstract override fun onSurfaceCreated(gl: GL10, config: EGLConfig) override fun onSurfaceChanged(gl: GL10, width: Int, height: Int) { this.width = width this.height = height } override fun onDrawFrame(gl: GL10) { this.drawer.drawFrame(this, width, height) } abstract fun logGLError() abstract val linearFilterMode: Int abstract val nearestFilterMode: Int abstract fun loadTexture(pixelData: ByteBuffer, size: Int, bytesPerRow: Int, filterMode: Int, textures: IntArray) abstract fun unloadTexture(textures: IntArray) abstract fun clear(color: GLColor) abstract fun saveState() abstract fun loadIdentity() abstract fun restoreState() abstract fun translate(tx: Float, ty: Float, tz: Float) abstract fun rotate(rx: Float, ry: Float, rz: Float) abstract fun scale(sx: Float, sy: Float) abstract fun drawTriangle(color: GLColor) abstract fun drawRectangle(color: GLColor) abstract fun drawRectangleTex(texture: GLTexture, color: GLColor, factor: Float) abstract fun drawCircle(radius: Float, color: GLColor) interface GLDrawer { fun drawFrame(renderer: GLRenderer, width: Int, height: Int) } }
bsd-3-clause
5f655b3ea673455a43c49da777ff8288
26.285714
117
0.725845
4.071705
false
false
false
false
ekager/focus-android
app/src/main/java/org/mozilla/focus/search/CustomSearchEngineStore.kt
2
5418
/* 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.search import android.content.Context import android.util.Log import mozilla.components.browser.search.SearchEngine import mozilla.components.browser.search.SearchEngineParser import org.mozilla.focus.ext.components import org.mozilla.focus.shortcut.IconGenerator import org.xmlpull.v1.XmlPullParserException import java.io.IOException object CustomSearchEngineStore { fun isSearchEngineNameUnique(context: Context, engineName: String): Boolean { val sharedPreferences = context.getSharedPreferences(PREF_FILE_SEARCH_ENGINES, Context.MODE_PRIVATE) val defaultEngines = context.components.searchEngineManager.getSearchEngines(context) return !sharedPreferences.contains(engineName) && !defaultEngines.any { it.name == engineName } } fun restoreDefaultSearchEngines(context: Context) { pref(context) .edit() .remove(PREF_KEY_HIDDEN_DEFAULT_ENGINES) .apply() } fun hasAllDefaultSearchEngines(context: Context): Boolean { return !pref(context) .contains(PREF_KEY_HIDDEN_DEFAULT_ENGINES) } fun addSearchEngine(context: Context, engineName: String, searchQuery: String): Boolean { // This is not for a homescreen shortcut so we don't want an adaptive launcher icon. val iconBitmap = IconGenerator.generateSearchEngineIcon(context) val searchEngineXml = SearchEngineWriter.buildSearchEngineXML(engineName, searchQuery, iconBitmap) ?: return false val existingEngines = pref(context).getStringSet(PREF_KEY_CUSTOM_SEARCH_ENGINES, emptySet()) val newEngines = LinkedHashSet<String>() newEngines.addAll(existingEngines!!) newEngines.add(engineName) pref(context) .edit() .putInt(PREF_KEY_CUSTOM_SEARCH_VERSION, CUSTOM_SEARCH_VERSION) .putStringSet(PREF_KEY_CUSTOM_SEARCH_ENGINES, newEngines) .putString(engineName, searchEngineXml) .apply() return true } fun removeSearchEngines(context: Context, engineIdsToRemove: MutableSet<String>) { // Check custom engines first. val customEngines = pref(context).getStringSet(PREF_KEY_CUSTOM_SEARCH_ENGINES, emptySet()) val remainingCustomEngines = LinkedHashSet<String>() val enginesEditor = pref(context).edit() for (engineId in customEngines!!) { if (engineIdsToRemove.contains(engineId)) { enginesEditor.remove(engineId) // Handled engine removal. engineIdsToRemove.remove(engineId) } else { remainingCustomEngines.add(engineId) } } enginesEditor.putStringSet(PREF_KEY_CUSTOM_SEARCH_ENGINES, remainingCustomEngines) // Everything else must be a default engine. val hiddenDefaultEngines = pref(context).getStringSet(PREF_KEY_HIDDEN_DEFAULT_ENGINES, emptySet()) engineIdsToRemove.addAll(hiddenDefaultEngines!!) enginesEditor.putStringSet(PREF_KEY_HIDDEN_DEFAULT_ENGINES, engineIdsToRemove) enginesEditor.apply() } fun getRemovedSearchEngines(context: Context): Set<String> = pref(context).getStringSet(PREF_KEY_HIDDEN_DEFAULT_ENGINES, emptySet())!! fun isCustomSearchEngine(engineId: String, context: Context): Boolean { for (e in loadCustomSearchEngines(context)) { if (e.identifier == engineId) { return true } } return false } fun loadCustomSearchEngines(context: Context): List<SearchEngine> { val customEngines = mutableListOf<SearchEngine>() val parser = SearchEngineParser() val prefs = context.getSharedPreferences(PREF_FILE_SEARCH_ENGINES, Context.MODE_PRIVATE) val engines = prefs.getStringSet(PREF_KEY_CUSTOM_SEARCH_ENGINES, emptySet()) try { for (engine in engines!!) { val engineInputStream = prefs.getString(engine, "")!!.byteInputStream().buffered() // Search engine identifier is the search engine name. customEngines.add(parser.load(engine, engineInputStream)) } } catch (e: IOException) { Log.e(LOG_TAG, "IOException while loading custom search engines", e) } catch (e: XmlPullParserException) { Log.e(LOG_TAG, "Couldn't load custom search engines", e) } return customEngines } private fun pref(context: Context) = context.getSharedPreferences(PREF_FILE_SEARCH_ENGINES, Context.MODE_PRIVATE) const val ENGINE_TYPE_CUSTOM = "custom" const val ENGINE_TYPE_BUNDLED = "bundled" private const val LOG_TAG = "CustomSearchEngineStore" private const val PREF_KEY_CUSTOM_SEARCH_ENGINES = "pref_custom_search_engines" private const val PREF_KEY_HIDDEN_DEFAULT_ENGINES = "hidden_default_engines" private const val PREF_KEY_CUSTOM_SEARCH_VERSION = "pref_custom_search_version" private const val CUSTOM_SEARCH_VERSION = 1 private const val PREF_FILE_SEARCH_ENGINES = "custom-search-engines" }
mpl-2.0
12076209d59f4114859862e9d644f362
41.328125
106
0.674603
4.549118
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/entity/vanilla/BatEntityProtocol.kt
1
1461
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.entity.vanilla import org.lanternpowered.api.key.NamespacedKey import org.lanternpowered.api.key.minecraftKey import org.lanternpowered.server.data.key.LanternKeys import org.lanternpowered.server.entity.LanternEntity import org.lanternpowered.server.network.entity.parameter.ParameterList class BatEntityProtocol<E : LanternEntity>(entity: E) : InsentientEntityProtocol<E>(entity) { companion object { private val TYPE = minecraftKey("bat") } private var lastHanging = false override val mobType: NamespacedKey get() = TYPE override fun spawn(parameterList: ParameterList) { parameterList.add(EntityParameters.Bat.FLAGS, (if (this.entity.get(LanternKeys.IS_HANGING).orElse(false)) 0x1 else 0).toByte()) } override fun update(parameterList: ParameterList) { val hanging = this.entity.get(LanternKeys.IS_HANGING).orElse(false) if (this.lastHanging != hanging) { parameterList.add(EntityParameters.Bat.FLAGS, (if (hanging) 0x1 else 0).toByte()) this.lastHanging = hanging } } }
mit
420154f0e1ea46542276e7f295ab5852
34.634146
97
0.717317
3.95935
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/api/item/inventory/equipment/ExtendedEquipmentInventory.kt
1
1573
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ @file:Suppress("NOTHING_TO_INLINE") package org.lanternpowered.api.item.inventory.equipment import org.lanternpowered.api.item.inventory.CarriedInventory import org.lanternpowered.api.item.inventory.ExtendedInventory import java.util.Optional import kotlin.contracts.contract typealias EquipmentInventory = org.spongepowered.api.item.inventory.equipment.EquipmentInventory /** * Gets the normal equipment inventory as an extended equipment inventory. */ inline fun EquipmentInventory.fix(): ExtendedEquipmentInventory<Equipable> { contract { returns() implies (this@fix is ExtendedEquipmentInventory<*>) } @Suppress("UNCHECKED_CAST") return this as ExtendedEquipmentInventory<Equipable> } /** * Gets the normal equipment inventory as an extended equipment inventory. */ @Deprecated(message = "Redundant call.", replaceWith = ReplaceWith("")) inline fun <C : Equipable> ExtendedEquipmentInventory<C>.fix(): ExtendedEquipmentInventory<C> = this /** * An extended version of [EquipmentInventory]. */ interface ExtendedEquipmentInventory<C : Equipable> : ExtendedInventory, EquipmentInventory, CarriedInventory<C> { @Deprecated(message = "Prefer to use carrierOrNull()") override fun getCarrier(): Optional<Equipable> }
mit
e4b3e5a2a97168d927cdd4cdd548dffd
34.75
114
0.767324
4.205882
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/inspections/latex/codestyle/LatexLineBreakInspection.kt
1
4895
package nl.hannahsten.texifyidea.inspections.latex.codestyle import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiFile import com.intellij.refactoring.suggested.startOffset import nl.hannahsten.texifyidea.inspections.InsightGroup import nl.hannahsten.texifyidea.inspections.TexifyInspectionBase import nl.hannahsten.texifyidea.inspections.latex.typesetting.spacing.LatexSpaceAfterAbbreviationInspection import nl.hannahsten.texifyidea.psi.LatexNormalText import nl.hannahsten.texifyidea.util.* import nl.hannahsten.texifyidea.util.files.document import nl.hannahsten.texifyidea.util.magic.PatternMagic import nl.hannahsten.texifyidea.util.magic.PatternMagic.sentenceEndPrefix import kotlin.math.min /** * @author Hannah Schellekens */ open class LatexLineBreakInspection : TexifyInspectionBase() { override val inspectionGroup = InsightGroup.LATEX override fun getDisplayName() = "Start sentences on a new line" override val inspectionId = "LineBreak" override fun inspectFile(file: PsiFile, manager: InspectionManager, isOntheFly: Boolean): List<ProblemDescriptor> { val descriptors = descriptorList() val document = file.document() ?: return descriptors // Target all regular text for this inspection. val texts = file.childrenOfType(LatexNormalText::class) for (text in texts) { // Do not trigger the inspection in math mode. if (text.inMathContext()) { continue } val matcher = PatternMagic.sentenceEnd.matcher(text.text) while (matcher.find()) { val offset = text.textOffset + matcher.end() val lineNumber = document.getLineNumber(offset) val endLine = document.getLineEndOffset(lineNumber) val startOffset = matcher.start() val endOffset = matcher.end() + (endLine - offset) val element = file.findElementAt(startOffset + text.startOffset) // Do not trigger the inspection when in a comment or when a comment starts directly after. if ((element?.isComment() == true) || (element?.nextSiblingIgnoreWhitespace()?.isComment() == true)) { continue } // It may be that this inspection is incorrectly triggered on an abbreviation. // However, that means that the correct user action is to write a normal space after the abbreviation, // which is what we suggest with this quickfix. val dotPlusSpace = "^$sentenceEndPrefix(\\.\\s)".toRegex().find(text.text.substring(startOffset, matcher.end()))?.groups?.get(0)?.range?.shiftRight(startOffset + 1) val normalSpaceFix = if (dotPlusSpace != null) LatexSpaceAfterAbbreviationInspection.NormalSpaceFix(dotPlusSpace) else null descriptors.add( manager.createProblemDescriptor( text, TextRange(startOffset, min(text.textLength, endOffset)), "Sentence does not start on a new line", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOntheFly, InspectionFix(), normalSpaceFix ) ) } } return descriptors } /** * @author Hannah Schellekens */ private class InspectionFix : LocalQuickFix { override fun getFamilyName() = "Insert line feed" override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val textElement = descriptor.psiElement val document = textElement.containingFile.document() ?: return val range = descriptor.textRangeInElement val textOffset = textElement.textOffset val textInElement = document.getText(TextRange(textOffset + range.startOffset, textOffset + range.endOffset)) // Do not apply the fix when there is no break point. val signMarker = PatternMagic.sentenceSeparator.matcher(textInElement) if (signMarker.find().not()) { return } // Fill in replacement val offset = textElement.textOffset + descriptor.textRangeInElement.startOffset + signMarker.end() + 1 val lineNumber = document.getLineNumber(offset) val replacement = "\n${document.lineIndentation(lineNumber)}" document.insertString(offset, replacement) document.deleteString(offset - 1, offset) } } }
mit
8fb3fb94f27ccbe822d25f789f48ce58
43.908257
180
0.661491
5.291892
false
false
false
false
SimonVT/cathode
cathode/src/main/java/net/simonvt/cathode/settings/NotificationSettingsActivity.kt
1
1579
/* * Copyright (C) 2016 Simon Vig Therkildsen * * 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 net.simonvt.cathode.settings import android.os.Bundle import androidx.appcompat.widget.Toolbar import net.simonvt.cathode.R import net.simonvt.cathode.ui.BaseActivity class NotificationSettingsActivity : BaseActivity() { override fun onCreate(inState: Bundle?) { super.onCreate(inState) setContentView(R.layout.activity_toolbar) if (supportFragmentManager.findFragmentByTag(FRAGMENT_SETTINGS) == null) { val settings = NotificationSettingsFragment() supportFragmentManager.beginTransaction() .add(R.id.content, settings, FRAGMENT_SETTINGS) .commit() } val toolbar = findViewById<Toolbar>(R.id.toolbar) toolbar.setTitle(R.string.title_settings) toolbar.setNavigationIcon(R.drawable.ic_arrow_back_24dp) toolbar.setNavigationOnClickListener { finish() } } companion object { private const val FRAGMENT_SETTINGS = "net.simonvt.cathode.settings.SettingsActivity.settingsFragment" } }
apache-2.0
0497794f3b044539d2a7f0e81a2ac828
33.326087
78
0.746675
4.349862
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/structure/bibtex/BibtexStructureViewModel.kt
1
1200
package nl.hannahsten.texifyidea.structure.bibtex import com.intellij.ide.structureView.StructureViewModel.ElementInfoProvider import com.intellij.ide.structureView.StructureViewModelBase import com.intellij.ide.structureView.StructureViewTreeElement import com.intellij.ide.util.treeView.smartTree.Sorter import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiFile import nl.hannahsten.texifyidea.structure.filter.EntryFilter import nl.hannahsten.texifyidea.structure.filter.PreambleFilter import nl.hannahsten.texifyidea.structure.filter.StringFilter /** * @author Hannah Schellekens */ open class BibtexStructureViewModel( val file: PsiFile, theEditor: Editor? ) : StructureViewModelBase(file, theEditor, BibtexStructureViewElement(file)), ElementInfoProvider { companion object { val sorterArray = arrayOf(Sorter.ALPHA_SORTER) val filterArray = arrayOf(EntryFilter, StringFilter, PreambleFilter) } override fun getSorters() = sorterArray override fun getFilters() = filterArray override fun isAlwaysShowsPlus(element: StructureViewTreeElement?) = false override fun isAlwaysLeaf(element: StructureViewTreeElement?) = false }
mit
8f3ab5c3167a5ca75ba19f13a28729c1
34.323529
100
0.8075
4.724409
false
false
false
false
herolynx/elepantry-android
app/src/main/java/com/herolynx/elepantry/resources/view/tags/GroupResourcesTags.kt
1
2648
package com.herolynx.elepantry.resources.view.tags import com.herolynx.elepantry.core.log.debug import com.herolynx.elepantry.core.log.error import com.herolynx.elepantry.repository.Repository import com.herolynx.elepantry.core.rx.DataEvent import com.herolynx.elepantry.core.rx.subscribeOnDefault import com.herolynx.elepantry.resources.core.model.Resource import com.herolynx.elepantry.resources.core.model.Tag import org.funktionale.option.firstOption import rx.Observable import rx.schedulers.Schedulers internal class GroupResourcesTagsRepository( private val repository: Repository<Resource>, private val resources: List<Resource> ) : Repository<GroupResourcesTags> { private val ids = resources.map(Resource::id).toSet() override fun findAll() = repository.findAll() .map { l -> l.filter { e -> ids.contains(e.id) }.plus(resources).toList() } .map { l -> listOf(GroupResourcesTags(l)) } override fun find(id: String) = findAll().map { l -> l.firstOption() } override fun asObservable() = repository.findAll() .map { l -> DataEvent(GroupResourcesTags(l)) } override fun delete(t: GroupResourcesTags): Observable<DataEvent<GroupResourcesTags>> { t.resources.forEach { r -> repository .delete(r) .subscribeOnDefault() .observeOn(Schedulers.io()) .subscribe( { r -> debug("[GroupResourcesTags] Resource deleted: $r") }, { ex -> error("[GroupResourcesTags] Couldn't delete group: $t", ex) } ) } return Observable.just(DataEvent(t)) } override fun save(t: GroupResourcesTags): Observable<DataEvent<GroupResourcesTags>> { t.resources.forEach { r -> repository .save(r) .subscribeOnDefault() .observeOn(Schedulers.io()) .subscribe( { r -> debug("[GroupResourcesTags] Resource changes saved: $r") }, { ex -> error("[GroupResourcesTags] Couldn't save changes - group: $t", ex) } ) } return Observable.just(DataEvent(t)) } } internal class GroupResourcesTags(internal val resources: List<Resource>) { fun getTags(): List<Tag> = resources.flatMap(Resource::tags).toSet().toList() fun addTags(newTags: List<Tag>): GroupResourcesTags { val tags = newTags.toSet().toList() return GroupResourcesTags(resources.map { r -> r.copy(tags = tags) }) } }
gpl-3.0
20dd36612108866657c5f5d205f96a57
37.376812
105
0.615559
4.435511
false
false
false
false
grassrootza/grassroot-android-v2
app/src/main/java/za/org/grassroot2/view/activity/DashboardActivity.kt
1
4344
package za.org.grassroot2.view.activity import android.app.Activity import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import android.support.v4.view.ViewPager import android.view.MenuItem import com.tbruyelle.rxpermissions2.RxPermissions import kotlinx.android.synthetic.main.activity_dashboard.* import za.org.grassroot2.R import za.org.grassroot2.dagger.activity.ActivityComponent import za.org.grassroot2.services.LocationManager import za.org.grassroot2.services.SyncOfflineDataService import za.org.grassroot2.util.NetworkUtil import za.org.grassroot2.view.fragment.AroundMeFragment import za.org.grassroot2.view.fragment.GroupsFragment import za.org.grassroot2.view.fragment.HomeFragment import za.org.grassroot2.view.fragment.MeFragment import javax.inject.Inject class DashboardActivity : GrassrootActivity() { override val layoutResourceId: Int get() = R.layout.activity_dashboard @Inject internal lateinit var rxPermissions: RxPermissions @Inject internal lateinit var manager: LocationManager private var menuItem: MenuItem? = null private val mOnNavigationItemSelectedListener:(MenuItem) -> Boolean = { item -> when (item.itemId) { R.id.navigation_home -> { contentPager.currentItem = TAB_HOME true } R.id.navigation_groups -> { contentPager.currentItem = TAB_GROUPS true } R.id.navigation_me -> { contentPager.currentItem = TAB_ME true } R.id.navigation_around -> { contentPager.currentItem = TAB_AROUND true } else -> false } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) contentPager.adapter = DashboardFragmentAdapter(supportFragmentManager) navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener) navigation.enableAnimation(false) navigation.enableShiftingMode(false) navigation.enableItemShiftingMode(false) contentPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { if (menuItem != null) { menuItem!!.isChecked = false } else { navigation.menu.getItem(TAB_HOME).isChecked = false } navigation.menu.getItem(position).isChecked = true menuItem = navigation.menu.getItem(position) } override fun onPageScrollStateChanged(state: Int) { } }) if (NetworkUtil.hasInternetAccess(this)) { startService(Intent(this, SyncOfflineDataService::class.java)) } val notificationText = intent.getStringExtra("notificationText") if (notificationText != null) { showMessageDialog(notificationText) } } override fun onInject(component: ActivityComponent) = component.inject(this) private inner class DashboardFragmentAdapter internal constructor(fm: FragmentManager) : FragmentPagerAdapter(fm) { override fun getItem(position: Int): Fragment? { when (position) { TAB_HOME -> return HomeFragment() TAB_GROUPS -> return GroupsFragment.newInstance() TAB_AROUND -> return AroundMeFragment.newInstance() TAB_ME -> return MeFragment.newInstance() } return null } override fun getCount(): Int { return 4 } } override fun onDestroy() { super.onDestroy() manager.disconnect() } companion object { const val TAB_HOME = 0 const val TAB_GROUPS = 1 const val TAB_AROUND = 2 const val TAB_ME = 3 fun start(activity: Activity) { activity.startActivity(Intent(activity, DashboardActivity::class.java)) } } }
bsd-3-clause
8c465f9d9fff501fb3bdfd23e9298342
32.9375
119
0.64825
5.045296
false
false
false
false
tomhenne/Jerusalem
src/main/java/de/esymetric/jerusalem/osmDataRepresentation/osm2ownMaps/PartitionedOsmNodeID2OwnIDMap.kt
1
5570
package de.esymetric.jerusalem.osmDataRepresentation.osm2ownMaps import de.esymetric.jerusalem.ownDataRepresentation.fileSystem.LatLonDir import de.esymetric.jerusalem.utils.FileBasedHashMapForLongKeys import de.esymetric.jerusalem.utils.Utils import java.io.* import java.util.* class PartitionedOsmNodeID2OwnIDMap( dataDirectoryPath: String, readOnly: Boolean ) { var cellMap: OsmNodeID2CellIDMapMemory var currentHashMap = FileBasedHashMapForLongKeys() var currentHashMapLatLonDir: LatLonDir? = null var dataDirectoryPath: String var readOnly: Boolean init { cellMap = OsmNodeID2CellIDMapMemory() this.dataDirectoryPath = dataDirectoryPath this.readOnly = readOnly } fun getAvgGetAccessNumberOfReads(): Float { return currentHashMap.avgGetAccessNumberOfReads } fun getAndClearNumberOfFileChanges(): Int { return currentHashMap.andClearNumberOfFileChanges } fun deleteLatLonTempFiles() { for (f in File(dataDirectoryPath).listFiles()) if (f.isDirectory && f.name.startsWith("lat_")) for (g in f.listFiles()) if (g.isDirectory && g.name.startsWith( "lng_" ) ) for (h in g.listFiles()) if (h.isFile && h.name == "osmMap.data") h.delete() } fun put(lat: Double, lng: Double, osmID: Long, ownID: Int) { val lld = LatLonDir(lat, lng) if (currentHashMapLatLonDir == null || !lld.equals(currentHashMapLatLonDir) ) { currentHashMapLatLonDir = lld currentHashMap.open( lld.makeDir(dataDirectoryPath, true) + File.separatorChar + "osmMap.data", readOnly ) } cellMap.put(osmID, lld) currentHashMap.put(osmID, ownID) } fun loadExistingOsm2OwnIDIntoMemory(startTime: Date) { var count = 1 val files = File(dataDirectoryPath).listFiles() Arrays.sort(files) for (f in files) if (f != null && f.isDirectory && f.name.startsWith("lat_")) { println( Utils.formatTimeStopWatch( Date() .time - startTime.time ) + " >>> " + f.name + " # " + count++ + ", cellmap uses " + cellMap.numberOfUsedArrays + "/" + cellMap.getMaxNumberOfArrays() + " arrays" ) for (g in f.listFiles()) if (g != null && g.isDirectory && g.name.startsWith("lng_") ) { val list = g.listFiles() if (list == null) { println( "Cannot list files in " + g.path ) continue } for (h in list) if (h != null && h.isFile && h.name == "osmMap.data" ) { val lat = f.name .substring(4).toInt() - LatLonDir.LAT_OFFS val lng = g.name .substring(4).toInt() - LatLonDir.LNG_OFFS val lld = LatLonDir(lat, lng) val cellID = lld.shortKey try { val l = (h.length() / 12L).toInt() val fis = FileInputStream(h) val dis = DataInputStream( BufferedInputStream(fis, 100000) ) for (i in 0 until l) { val osmNodeID = dis.readInt() dis.readLong() if (osmNodeID > 0) cellMap.put(osmNodeID.toLong(), cellID) } dis.close() fis.close() } catch (e: IOException) { e.printStackTrace() } } } } } fun getLatLonDir(osmNodeID: Int): LatLonDir { return LatLonDir(cellMap.getShort(osmNodeID.toLong())) } fun getShortCellID(osmNodeID: Long): Short { return cellMap.getShort(osmNodeID) } operator fun get(osmNodeID: Long): Int { val lld = LatLonDir(cellMap.getShort(osmNodeID)) if (currentHashMapLatLonDir == null || !lld.equals(currentHashMapLatLonDir) ) { val nextFilePath = (lld.makeDir(dataDirectoryPath, false) + File.separatorChar + "osmMap.data") if (File(nextFilePath).exists()) { currentHashMapLatLonDir = lld currentHashMap.open(nextFilePath, readOnly) } else return -1 } return currentHashMap[osmNodeID] } fun close() { currentHashMap.close() } fun setReadOnly() { currentHashMap.close() currentHashMapLatLonDir = null readOnly = true } fun getNumberOfUsedArrays(): Int { return cellMap.numberOfUsedArrays } fun getMaxNumberOfArrays(): Int { return cellMap.getMaxNumberOfArrays() } fun getEstimatedMemorySizeMB(): Float { return cellMap.getEstimatedMemorySizeMB() } }
apache-2.0
6078db391705e8365e52d951a2835774
33.044025
167
0.496409
4.946714
false
false
false
false
nemerosa/ontrack
ontrack-extension-scm/src/main/java/net/nemerosa/ontrack/extension/scm/catalog/sync/SCMOrphanDisablingJob.kt
1
1380
package net.nemerosa.ontrack.extension.scm.catalog.sync import net.nemerosa.ontrack.extension.scm.SCMJobs import net.nemerosa.ontrack.job.* import net.nemerosa.ontrack.model.settings.CachedSettingsService import net.nemerosa.ontrack.model.support.JobProvider import org.springframework.stereotype.Component import java.time.Duration /** * Job which disables the orphan projects after some inactivity. */ @Component class SCMOrphanDisablingJob( private val scmOrphanDisablingService: SCMOrphanDisablingService, private val cachedSettingsService: CachedSettingsService, ) : JobProvider { override fun getStartingJobs() = listOf( JobRegistration( createSCMOrphanDisablingJob(), Schedule.EVERY_WEEK.after(Duration.ofDays(7)) ) ) private fun createSCMOrphanDisablingJob() = object : Job { override fun getKey(): JobKey = SCMJobs.category .getType("orphan-management").withName("Orphan management") .getKey("orphan-disabling") override fun getTask() = JobRun { scmOrphanDisablingService.disableOrphanProjects() } override fun getDescription(): String = "Disabling all orphan projects" override fun isDisabled(): Boolean = !cachedSettingsService.getCachedSettings(SCMCatalogSyncSettings::class.java).orphanDisablingEnabled } }
mit
b34d2b709ee65fa449b4e17cbd4e4561
33.525
111
0.72971
4.630872
false
false
false
false
bozaro/git-as-svn
src/main/kotlin/svnserver/repository/git/GitBranch.kt
1
17663
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.repository.git import org.eclipse.jgit.diff.DiffEntry import org.eclipse.jgit.diff.RenameDetector import org.eclipse.jgit.lib.* import org.eclipse.jgit.revwalk.RevCommit import org.eclipse.jgit.revwalk.RevWalk import org.eclipse.jgit.treewalk.TreeWalk import org.eclipse.jgit.treewalk.filter.TreeFilter import org.mapdb.HTreeMap import org.slf4j.Logger import org.tmatesoft.svn.core.SVNErrorCode import org.tmatesoft.svn.core.SVNErrorMessage import org.tmatesoft.svn.core.SVNException import svnserver.Loggers import svnserver.StringHelper import svnserver.auth.User import svnserver.repository.VcsCopyFrom import svnserver.repository.git.cache.CacheChange import svnserver.repository.git.cache.CacheRevision import svnserver.repository.locks.LockStorage import java.io.IOException import java.nio.charset.StandardCharsets import java.util.* import java.util.concurrent.locks.ReentrantReadWriteLock class GitBranch constructor(val repository: GitRepository, val shortBranchName: String) { val uuid: String val gitBranch: String private val svnBranch: String /** * Lock for prevent concurrent pushes. */ private val pushLock: Any = Any() private val revisions = ArrayList<GitRevision>() private val revisionByDate = TreeMap<Long, GitRevision>() private val revisionByHash = HashMap<ObjectId, GitRevision>() private val revisionCache: HTreeMap<ObjectId, CacheRevision> private val lastUpdatesLock = ReentrantReadWriteLock() private val lastUpdates = HashMap<String, IntArray>() private val lock = ReentrantReadWriteLock() @Throws(SVNException::class) fun getRevisionInfo(revision: Int): GitRevision { return getRevisionInfoUnsafe(revision) ?: throw SVNException(SVNErrorMessage.create(SVNErrorCode.FS_NO_SUCH_REVISION, "No such revision $revision")) } private fun getRevisionInfoUnsafe(revision: Int): GitRevision? { lock.readLock().lock() try { if (revision >= revisions.size) return null return revisions[revision] } finally { lock.readLock().unlock() } } val latestRevision: GitRevision get() { lock.readLock().lock() try { return revisions[revisions.size - 1] } finally { lock.readLock().unlock() } } @Throws(IOException::class, SVNException::class) fun updateRevisions() { var gotNewRevisions = false while (true) { loadRevisions() if (!cacheRevisions()) { break } gotNewRevisions = true } if (gotNewRevisions) { val locksChanged: Boolean = repository.wrapLockWrite { lockStorage: LockStorage -> lockStorage.cleanupInvalidLocks(this) } if (locksChanged) repository.context.shared.cacheDB.commit() } } /** * Load all cached revisions. */ @Throws(IOException::class) private fun loadRevisions() { // Fast check. lock.readLock().lock() try { val lastRevision: Int = revisions.size - 1 val lastCommitId: ObjectId if (lastRevision >= 0) { lastCommitId = revisions[lastRevision].cacheCommit val head: Ref = repository.git.exactRef(svnBranch) if (head.objectId.equals(lastCommitId)) { return } } } finally { lock.readLock().unlock() } // Real loading. lock.writeLock().lock() try { val lastRevision: Int = revisions.size - 1 val lastCommitId: ObjectId? = if (lastRevision < 0) null else revisions[lastRevision].cacheCommit val head: Ref = repository.git.exactRef(svnBranch) val newRevs: MutableList<RevCommit> = ArrayList() val revWalk = RevWalk(repository.git) var objectId: ObjectId = head.objectId while (true) { if (objectId.equals(lastCommitId)) { break } val commit: RevCommit = revWalk.parseCommit(objectId) newRevs.add(commit) if (commit.parentCount == 0) break objectId = commit.getParent(0) } if (newRevs.isEmpty()) { return } val beginTime: Long = System.currentTimeMillis() var processed = 0 var reportTime: Long = beginTime log.info("[{}]: loading cached revision changes: {} revisions", this, newRevs.size) for (i in newRevs.indices.reversed()) { loadRevisionInfo(newRevs[i]) processed++ val currentTime: Long = System.currentTimeMillis() if (currentTime - reportTime > REPORT_DELAY) { log.info("[{}]: processed cached revision: {}/{} ({} rev/sec)", this, newRevs.size - i, newRevs.size, 1000.0f * processed / (currentTime - reportTime)) reportTime = currentTime processed = 0 } } val endTime: Long = System.currentTimeMillis() log.info("[{}]: {} cached revision loaded: {} ms", this, newRevs.size, endTime - beginTime) } finally { lock.writeLock().unlock() } } /** * Create cache for new revisions. */ @Throws(IOException::class) private fun cacheRevisions(): Boolean { // Fast check. lock.readLock().lock() try { val lastRevision: Int = revisions.size - 1 if (lastRevision >= 0) { val lastCommitId: ObjectId? = revisions[lastRevision].gitNewCommit val master: Ref? = repository.git.exactRef(gitBranch) if ((master == null) || (master.objectId.equals(lastCommitId))) { return false } } } finally { lock.readLock().unlock() } // Real update. lock.writeLock().lock() try { repository.git.newObjectInserter().use { inserter -> val master = repository.git.exactRef(gitBranch) val newRevs = ArrayList<RevCommit>() val revWalk = RevWalk(repository.git) var objectId = master.objectId while (true) { if (revisionByHash.containsKey(objectId)) { break } val commit: RevCommit = revWalk.parseCommit(objectId) newRevs.add(commit) if (commit.parentCount == 0) break objectId = commit.getParent(0) } if (newRevs.isNotEmpty()) { val beginTime: Long = System.currentTimeMillis() var processed = 0 var reportTime: Long = beginTime log.info("[{}]: Loading revision changes: {} revision", this, newRevs.size) var revisionId: Int = revisions.size var cacheId: ObjectId? = revisions[revisions.size - 1].cacheCommit for (i in newRevs.indices.reversed()) { val revCommit: RevCommit = newRevs[i] cacheId = LayoutHelper.createCacheCommit(inserter, (cacheId)!!, revCommit, revisionId, emptyMap()) inserter.flush() processed++ val currentTime: Long = System.currentTimeMillis() if (currentTime - reportTime > REPORT_DELAY) { log.info(" processed revision: {} ({} rev/sec)", newRevs.size - i, 1000.0f * processed / (currentTime - reportTime)) reportTime = currentTime processed = 0 val refUpdate: RefUpdate = repository.git.updateRef(svnBranch) refUpdate.setNewObjectId(cacheId) refUpdate.update() } revisionId++ } val endTime: Long = System.currentTimeMillis() log.info("Revision changes loaded: {} ms", endTime - beginTime) val refUpdate: RefUpdate = repository.git.updateRef(svnBranch) refUpdate.setNewObjectId(cacheId) refUpdate.update() } return newRevs.isNotEmpty() } } finally { lock.writeLock().unlock() } } @Throws(IOException::class) private fun loadRevisionInfo(commit: RevCommit) { val reader: ObjectReader = repository.git.newObjectReader() val cacheRevision: CacheRevision = loadCacheRevision(reader, commit, revisions.size) val revisionId: Int = revisions.size val copyFroms: MutableMap<String, VcsCopyFrom> = HashMap() for (entry: Map.Entry<String, String> in cacheRevision.getRenames().entries) { copyFroms[entry.key] = VcsCopyFrom(revisionId - 1, entry.value) } val oldCommit: RevCommit? = if (revisions.isEmpty()) null else revisions[revisions.size - 1].gitNewCommit val svnCommit: RevCommit? = if (cacheRevision.gitCommitId != null) RevWalk(reader).parseCommit(cacheRevision.gitCommitId) else null try { lastUpdatesLock.writeLock().lock() for (entry: Map.Entry<String, CacheChange> in cacheRevision.getFileChange().entries) { lastUpdates.compute(entry.key) { _, list -> val markNoFile: Boolean = entry.value.newFile == null val prevLen: Int = list?.size ?: 0 val newLen: Int = prevLen + 1 + (if (markNoFile) 1 else 0) val result: IntArray = if (list == null) IntArray(newLen) else Arrays.copyOf(list, newLen) result[prevLen] = revisionId if (markNoFile) { result[prevLen + 1] = MARK_NO_FILE } result } } } finally { lastUpdatesLock.writeLock().unlock() } val revision = GitRevision(this, commit.id, revisionId, copyFroms, oldCommit, svnCommit, commit.commitTime) if (revision.id > 0) { if (revisionByDate.isEmpty() || revisionByDate.lastKey() <= revision.date) { revisionByDate[revision.date] = revision } } if (svnCommit != null) { revisionByHash[svnCommit.id] = revision } revisions.add(revision) } @Throws(IOException::class) private fun loadCacheRevision(reader: ObjectReader, newCommit: RevCommit, revisionId: Int): CacheRevision { val cacheKey: ObjectId = newCommit.copy() var result: CacheRevision? = revisionCache[cacheKey] if (result == null) { val baseCommit: RevCommit? = LayoutHelper.loadOriginalCommit(reader, newCommit) val oldTree: GitFile = getSubversionTree(reader, if (newCommit.parentCount > 0) newCommit.getParent(0) else null, revisionId - 1) val newTree: GitFile = getSubversionTree(reader, newCommit, revisionId) val fileChange: MutableMap<String, CacheChange> = TreeMap() for (entry: Map.Entry<String, GitLogEntry> in ChangeHelper.collectChanges(oldTree, newTree, true).entries) { fileChange[entry.key] = CacheChange(entry.value) } result = CacheRevision( baseCommit, collectRename(oldTree, newTree), fileChange ) revisionCache[cacheKey] = result } return result } @Throws(IOException::class) private fun getSubversionTree(reader: ObjectReader, commit: RevCommit?, revisionId: Int): GitFile { val revCommit: RevCommit = LayoutHelper.loadOriginalCommit(reader, commit) ?: return GitFileEmptyTree(this, "", revisionId - 1) return GitFileTreeEntry.create(this, revCommit.tree, revisionId) } @Throws(IOException::class) private fun collectRename(oldTree: GitFile, newTree: GitFile): Map<String, String> { if (!repository.hasRenameDetection()) { return emptyMap() } val oldTreeId: GitObject<ObjectId>? = oldTree.objectId val newTreeId: GitObject<ObjectId>? = newTree.objectId if ((oldTreeId == null) || (newTreeId == null) || !Objects.equals(oldTreeId.repo, newTreeId.repo)) { return emptyMap() } val tw = TreeWalk(repository.git) tw.isRecursive = true tw.filter = TreeFilter.ANY_DIFF tw.addTree(oldTreeId.`object`) tw.addTree(newTreeId.`object`) val rd = RenameDetector(repository.git) rd.addAll(DiffEntry.scan(tw)) val result = HashMap<String, String>() for (diff in rd.compute(tw.objectReader, null)) { if (diff.score >= rd.renameScore) { result[StringHelper.normalize(diff.newPath)] = StringHelper.normalize(diff.oldPath) } } return result } fun getRevisionByDate(dateTime: Long): GitRevision { lock.readLock().lock() try { val entry: Map.Entry<Long, GitRevision>? = revisionByDate.floorEntry(dateTime) if (entry != null) { return entry.value } return revisions[0] } finally { lock.readLock().unlock() } } fun sureRevisionInfo(revision: Int): GitRevision { return getRevisionInfoUnsafe(revision) ?: throw IllegalStateException("No such revision $revision") } @Throws(SVNException::class) fun getRevision(revisionId: ObjectId): GitRevision { lock.readLock().lock() try { return revisionByHash[revisionId] ?: throw SVNException(SVNErrorMessage.create(SVNErrorCode.FS_NO_SUCH_REVISION, "No such revision " + revisionId.name())) } finally { lock.readLock().unlock() } } fun getLastChange(nodePath: String, beforeRevision: Int): Int? { if (nodePath.isEmpty()) return beforeRevision try { lastUpdatesLock.readLock().lock() val revs: IntArray? = lastUpdates[nodePath] if (revs != null) { var prev = 0 for (i in revs.indices.reversed()) { val rev: Int = revs[i] if ((rev >= 0) && (rev <= beforeRevision)) { if (prev == MARK_NO_FILE) { return null } return rev } prev = rev } } } finally { lastUpdatesLock.readLock().unlock() } return null } @Throws(SVNException::class) fun createWriter(user: User): GitWriter { if (user.email == null || user.email.isEmpty()) { throw SVNException(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "Users with undefined email can't create commits")) } return GitWriter(this, repository.pusher, pushLock, user) } override fun toString(): String { return repository.context.name + "@" + shortBranchName } companion object { private const val revisionCacheVersion: Int = 2 private const val REPORT_DELAY: Int = 2500 private const val MARK_NO_FILE: Int = -1 private val log: Logger = Loggers.git @Throws(IOException::class) private fun loadRepositoryId(repository: Repository, ref: Ref): String { var oid: ObjectId? = ref.objectId val revWalk = RevWalk(repository) while (true) { val revCommit: RevCommit = revWalk.parseCommit(oid) if (revCommit.parentCount == 0) { return LayoutHelper.loadRepositoryId(repository.newObjectReader(), oid) } oid = revCommit.getParent(0) } } } init { val svnBranchRef: Ref = LayoutHelper.initRepository(repository.git, shortBranchName) svnBranch = svnBranchRef.name gitBranch = Constants.R_HEADS + shortBranchName val repositoryId: String = loadRepositoryId(repository.git, svnBranchRef) uuid = UUID.nameUUIDFromBytes( String.format("%s\u0000%s\u0000%s", repositoryId, gitBranch, repository.format.revision).toByteArray(StandardCharsets.UTF_8) ).toString() val revisionCacheName: String = String.format( "cache-revision.%s.%s.%s.v%s.%s", repository.context.name, gitBranch, if (repository.hasRenameDetection()) 1 else 0, revisionCacheVersion, repository.format.revision ) revisionCache = repository.context.shared.cacheDB.hashMap<ObjectId, CacheRevision>( revisionCacheName, ObjectIdSerializer.instance, CacheRevisionSerializer.instance ).createOrOpen() } }
gpl-2.0
042d110f9787cd1d5c6c31b33605b569
40.954869
177
0.582064
4.672751
false
false
false
false
alaminopu/IST-Syllabus
app/src/main/java/org/istbd/IST_Syllabus/CreditComponent.kt
1
3327
package org.istbd.IST_Syllabus import android.os.Bundle import android.widget.TextView import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.ScrollState import androidx.compose.foundation.layout.* import androidx.compose.foundation.verticalScroll import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import org.istbd.IST_Syllabus.ui.theme.ISTTheme class Credit : ComponentActivity() { public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CreditComponent() } } } @Composable @Preview("Credit Component") fun CreditComponent() { ISTTheme { Surface(color = Color.White) { Column( modifier = Modifier .fillMaxWidth() .fillMaxHeight() .verticalScroll(state = ScrollState(0)), verticalArrangement = Arrangement.Center ) { Image( painter = painterResource(id = R.drawable.developer), contentDescription = stringResource(id = R.string.developer), modifier = Modifier .height(160.dp) .width(190.dp) .align(alignment = Alignment.CenterHorizontally) ) AndroidView( factory = { TextView(it).apply { text = it.getText(R.string.developer) setTextAppearance(it, android.R.style.TextAppearance_Medium) } }, modifier = Modifier .wrapContentWidth() .wrapContentHeight() .padding(bottom = 10.dp) .align(alignment = Alignment.CenterHorizontally) ) Image( painter = painterResource(id = R.drawable.shovon), contentDescription = stringResource(id = R.string.designer), modifier = Modifier .height(160.dp) .width(190.dp) .align(alignment = Alignment.CenterHorizontally) ) AndroidView( factory = { TextView(it).apply { text = it.getText(R.string.designer) setTextAppearance(it, android.R.style.TextAppearance_Medium) } }, modifier = Modifier .wrapContentWidth() .wrapContentHeight() .align(alignment = Alignment.CenterHorizontally), ) } } } }
gpl-2.0
3cd7aa9d6ea42d515054549990eda97d
36.393258
88
0.54734
5.619932
false
false
false
false
ivan-osipov/Clabo
src/main/kotlin/com/github/ivan_osipov/clabo/api/input/dto.kt
1
2082
package com.github.ivan_osipov.clabo.api.input import com.github.ivan_osipov.clabo.api.input.deserialization.strategies.AnnotationExclusionStrategy import com.github.ivan_osipov.clabo.api.model.* import com.github.kittinunf.fuel.core.ResponseDeserializable import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.JsonSyntaxException import com.google.gson.annotations.SerializedName open class ResponseDto<T: Any> { var ok: Boolean = false lateinit var result: T var description: String? = null var error_code: Int = -1 var parameters: ResponseParameters? = null } class ResponseParameters { @SerializedName("migrate_to_chat_id") var migrateToChatId: Long? = null @SerializedName("retry_after") var retryAfter: Int? = null } internal val gson: Gson = GsonBuilder().setExclusionStrategies(AnnotationExclusionStrategy()).create() class UserDto : ResponseDto<User>() { object deserializer : ResponseDeserializable<UserDto> { override fun deserialize(content: String) = gson.fromJson(content, UserDto::class.java)!! } } class UpdatesDto : ResponseDto<List<Update>>() { object deserializer : ResponseDeserializable<UpdatesDto> { override fun deserialize(content: String) = gson.fromJson(content, UpdatesDto::class.java)!! } } class MessageDto : ResponseDto<Message>() { object deserializer : ResponseDeserializable<MessageDto> { override fun deserialize(content: String): MessageDto? { try { return gson.fromJson(content, MessageDto::class.java)!! } catch (e: JsonSyntaxException) { return MessageDto().apply { result = EmptyMessage } } } } } class ChatDto : ResponseDto<Chat>() { object deserializer : ResponseDeserializable<ChatDto> { override fun deserialize(content: String): ChatDto? { return gson.fromJson(content, ChatDto::class.java) } } } fun <T: Any> T?.toJson(): String? = this?.let { gson.toJson(this) }
apache-2.0
e70235b172868210bea545be660d9965
32.063492
102
0.690202
4.257669
false
false
false
false
sksamuel/akka-patterns
rxhive-schemas/src/main/kotlin/com/sksamuel/rxhive/Struct.kt
1
3669
package com.sksamuel.rxhive /** * Types are inspired by Apache Spark. * https://github.com/apache/spark/blob/630e25e35506c02a0b1e202ef82b1b0f69e50966/sql/catalyst/src/main/scala/org/apache/spark/sql/types/DataType.scala */ sealed class Type data class StructType(val fields: List<StructField>) : Type() { constructor(vararg fields: StructField) : this(fields.toList()) init { require(fields.map { it.name }.toSet().size == fields.size) { "Struct type cannot contain duplicated field names" } } fun indexOf(name: String): Int = fields.indexOfFirst { it.name == name } operator fun get(index: Int): StructField = fields[index] operator fun get(name: String): StructField? = fields.find { it.name == name } fun hasField(name: String) = fields.any { it.name == name } /** * Returns a new StructType which is the same as the existing struct, but with the * given field added to the end of the existing fields. */ fun addField(field: StructField): StructType { require(!fields.any { it.name == field.name }) { "Field ${field.name} already exists" } return copy(fields = this.fields + field) } /** * Returns a new [StructType] which is the same as the existing struct, but with * the matching field removed, if it exists. * * If the field does not exist then it is a no-op. */ fun removeField(name: String): StructType { return StructType(fields.filterNot { it.name == name }) } } /** * @param nullable whether this struct field can be null or not. Defaults to true as that * is the behaviour of hive */ data class StructField(val name: String, val type: Type, val nullable: Boolean) { constructor(name: String, type: Type) : this(name, type, true) /** * Returns a new StructField with the same name as this field, but lowercased. * All other properties remain the same. */ fun toLowerCase(): StructField = copy(name = name.toLowerCase()) fun withNullable(nullable: Boolean): StructField = copy(nullable = nullable) fun nullable(): StructField = copy(nullable = true) } data class Struct(val schema: StructType, val values: List<Any?>) { constructor(type: StructType, vararg values: Any?) : this(type, values.asList()) init { require(schema.fields.size == values.size) } operator fun get(name: String): Any? { val index = schema.indexOf(name) return if (index < 0) null else values[index] } companion object { fun fromMap(schema: StructType, map: Map<String, Any?>): Struct { val values = schema.fields.map { map[it.name] } return Struct(schema, values) } } } object BooleanType : Type() object BinaryType : Type() // text types object StringType : Type() data class CharType(val size: Int) : Type() data class VarcharType(val size: Int) : Type() // floating point types object Float64Type : Type() object Float32Type : Type() // integral types object Int8Type : Type() object Int16Type : Type() object Int32Type : Type() object Int64Type : Type() object BigIntType : Type() // date time types object TimestampMillisType : Type() object TimestampMicrosType : Type() object TimeMicrosType : Type() object TimeMillisType : Type() object DateType : Type() // container types data class MapDataType(val keyType: Type, val valueType: Type) : Type() data class EnumType(val values: List<String>) : Type() { constructor(vararg values: String) : this(values.asList()) } data class ArrayType(val elementType: Type) : Type() data class Precision(val value: Int) data class Scale(val value: Int) data class DecimalType(val precision: Precision, val scale: Scale) : Type()
apache-2.0
3ca110a62b50fff27dacb1cb7b3be92b
28.352
150
0.691469
3.770812
false
false
false
false
uchuhimo/kotlin-playground
konf/src/test/kotlin/com/uchuhimo/konf/source/SourceProviderSpec.kt
1
4804
package com.uchuhimo.konf.source import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.throws import com.uchuhimo.konf.source.hocon.HoconProvider import com.uchuhimo.konf.tempFileOf import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import org.jetbrains.spek.subject.SubjectSpek import spark.Spark.get import spark.Spark.stop import java.net.URL object SourceProviderSpec : SubjectSpek<SourceProvider>({ subject { HoconProvider } given("a source provider") { on("create source from reader") { val source = subject.fromReader("type = reader".reader()) it("should have correct type") { assertThat(source.info["type"], equalTo("HOCON")) } it("should return a source which contains value from reader") { assertThat(source.get("type").toText(), equalTo("reader")) } } on("create source from input stream") { val source = subject.fromInputStream( tempFileOf("type = inputStream").inputStream()) it("should have correct type") { assertThat(source.info["type"], equalTo("HOCON")) } it("should return a source which contains value from input stream") { assertThat(source.get("type").toText(), equalTo("inputStream")) } } on("create source from file") { val file = tempFileOf("type = file") val source = subject.fromFile(file) it("should create from the specified file") { assertThat(source.context["file"], equalTo(file.toString())) } it("should return a source which contains value in file") { assertThat(source.get("type").toText(), equalTo("file")) } } on("create source from string") { val content = "type = string" val source = subject.fromString(content) it("should create from the specified string") { assertThat(source.context["content"], equalTo("\"\n$content\n\"")) } it("should return a source which contains value in string") { assertThat(source.get("type").toText(), equalTo("string")) } } on("create source from byte array") { val source = subject.fromBytes("type = bytes".toByteArray()) it("should return a source which contains value in byte array") { assertThat(source.get("type").toText(), equalTo("bytes")) } } on("create source from byte array slice") { val source = subject.fromBytes("|type = slice|".toByteArray(), 1, 12) it("should return a source which contains value in byte array slice") { assertThat(source.get("type").toText(), equalTo("slice")) } } on("create source from HTTP URL") { get("/source") { _, _ -> "type = http" } val url = "http://localhost:4567/source" val source = subject.fromUrl(URL(url)) it("should create from the specified URL") { assertThat(source.context["url"], equalTo(url)) } it("should return a source which contains value in URL") { assertThat(source.get("type").toText(), equalTo("http")) } stop() } on("create source from file URL") { val file = tempFileOf("type = fileUrl") val url = file.toURI().toURL() val source = subject.fromUrl(url) it("should create from the specified URL") { assertThat(source.context["url"], equalTo(url.toString())) } it("should return a source which contains value in URL") { assertThat(source.get("type").toText(), equalTo("fileUrl")) } } on("create source from resource") { val resource = "source/provider.conf" val source = subject.fromResource(resource) it("should create from the specified resource") { assertThat(source.context["resource"], equalTo(resource)) } it("should return a source which contains value in resource") { assertThat(source.get("type").toText(), equalTo("resource")) } } on("create source from non-existed resource") { it("should throw SourceNotFoundException") { assertThat({ subject.fromResource("source/no-provider.conf") }, throws<SourceNotFoundException>()) } } } })
apache-2.0
082c9ce584a9cce2cb89f263894f0aa8
42.279279
83
0.567236
4.857432
false
false
false
false
akinaru/bbox-api-client
sample/src/main/kotlin/fr/bmartel/bboxapi/router/sample/WirelessInfo.kt
2
1040
package fr.bmartel.bboxapi.router.sample import com.github.kittinunf.result.Result import fr.bmartel.bboxapi.router.BboxApiRouter import java.util.concurrent.CountDownLatch fun main(args: Array<String>) { val bboxapi = BboxApiRouter() bboxapi.init() bboxapi.password = "admin" //asynchronous call val latch = CountDownLatch(1) bboxapi.getWirelessInfo { _, _, result -> when (result) { is Result.Failure -> { val ex = result.getException() println(ex) } is Result.Success -> { val data = result.get() println(data) } } latch.countDown() } latch.await() //synchronous call val (_, _, result) = bboxapi.getWirelessInfoSync() when (result) { is Result.Failure -> { val ex = result.getException() println(ex) } is Result.Success -> { val data = result.get() println(data) } } }
mit
fd677ac767c1fa3275fe99bbcc633275
24.390244
54
0.543269
4.425532
false
false
false
false
damien5314/RhythmGameScoreCalculator
app/src/main/java/com/ddiehl/rgsc/data/Score.kt
1
1038
package com.ddiehl.rgsc.data abstract class Score { abstract val elements: Map<String, ScoreElement> open val earned: Int get() { var result = 0 for (element in elements.values) result += element.count * element.weight return result } open val potential: Int get() { var result = 0 for (element in elements.values) result += element.count * element.bestWeight return result } open val stepTotal: Int get() { var result = 0 for (element in elements.values) if (element.isStep) result += element.count return result } open val percent: Double get() = ((earned.toDouble() / potential.toDouble()) * 10000).toInt() / 100.00 abstract val grade: String override fun toString(): String { val result = StringBuilder() for (element in elements.values) result.append(element.count).append(" ") return result.toString() } }
apache-2.0
99fd37c7b4e80974663b2f9a1d7deb84
27.081081
89
0.579961
4.59292
false
false
false
false
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/app/photo/TakePhotoFragment.kt
1
2116
package ffc.app.photo import android.app.Activity import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import ffc.android.onClick import ffc.app.R import ffc.app.health.service.HealthCareServivceForm import ffc.app.mockRepository import ffc.entity.healthcare.HealthCareService import ffc.entity.util.URLs import kotlinx.android.synthetic.main.hs_photo_fragment.counterView import kotlinx.android.synthetic.main.hs_photo_fragment.takePhoto class TakePhotoFragment : Fragment(), HealthCareServivceForm<HealthCareService> { private val maxPhoto = 2 private var photoUrls: List<String> = listOf() set(value) { field = value counterView.text = "${field.size}/$maxPhoto" } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.hs_photo_fragment, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) counterView.text = "${photoUrls.size}/$maxPhoto" if (mockRepository) { photoUrls = listOf( "https://upload.wikimedia.org/wikipedia/commons/0/06/Hotel_Wellington_Sherbrooke.jpg", "https://c.pxhere.com/photos/b0/71/new_home_for_sale_georgia_usa_home_house_estate_sale-486530.jpg!d" ) } takePhoto.onClick { startTakePhotoActivity(PhotoType.SERVICE, photoUrls, maxPhoto) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK) photoUrls = data!!.urls!! } override fun bind(service: HealthCareService) { photoUrls = service.photosUrl } override fun dataInto(service: HealthCareService) { service.photosUrl = photoUrls.mapTo(URLs()) { it } } }
apache-2.0
327bdd361d044b8468cb284554f1bfb8
33.129032
117
0.702741
4.1409
false
false
false
false
SapuSeven/BetterUntis
weekview/src/main/java/com/sapuseven/untis/views/weekview/drawers/HolidayDrawer.kt
1
1376
package com.sapuseven.untis.views.weekview.drawers import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import com.sapuseven.untis.views.weekview.DrawingContext import com.sapuseven.untis.views.weekview.HolidayChip import com.sapuseven.untis.views.weekview.config.WeekViewConfig class HolidayDrawer(private val config: WeekViewConfig) : BaseDrawer { var holidayChips: List<HolidayChip> = emptyList() override fun draw(drawingContext: DrawingContext, canvas: Canvas) { val text = mutableListOf<String>() drawingContext.freeDays.forEach { (first, second) -> holidayChips.forEach { if (it.isOnDay(first)) text.add(it.text) } drawHoliday(text.joinToString(" / "), second, canvas) text.clear() } } private fun drawHoliday(text: String, startFromPixel: Float, canvas: Canvas) { if (text.isBlank()) return val paint = Paint(Paint.ANTI_ALIAS_FLAG) paint.strokeWidth = 5f paint.color = config.defaultEventColor val bounds = Rect() config.drawConfig.eventTextPaint.getTextBounds(text, 0, text.length, bounds) val holidayPadding = 50f canvas.save() canvas.translate(startFromPixel, config.drawConfig.headerHeight) canvas.rotate(90f) canvas.drawText(text, holidayPadding, (config.drawConfig.widthPerDay - bounds.height()) / -2f, config.drawConfig.holidayTextPaint) canvas.restore() } }
gpl-3.0
5fa36dfd04ec9c1dcc0927ee147a29c7
30.272727
132
0.762355
3.431421
false
true
false
false
codeka/wwmmo
server/src/main/kotlin/au/com/codeka/warworlds/server/admin/handlers/AjaxStarfieldHandler.kt
1
6889
package au.com.codeka.warworlds.server.admin.handlers import au.com.codeka.warworlds.common.Log import au.com.codeka.warworlds.common.proto.SectorCoord import au.com.codeka.warworlds.common.proto.Star import au.com.codeka.warworlds.common.proto.StarModification import au.com.codeka.warworlds.common.sim.MutableStar import au.com.codeka.warworlds.common.sim.Simulation import au.com.codeka.warworlds.common.sim.SuspiciousModificationException import au.com.codeka.warworlds.server.handlers.RequestException import au.com.codeka.warworlds.server.world.SectorManager import au.com.codeka.warworlds.server.world.StarManager import au.com.codeka.warworlds.server.world.SuspiciousEventManager import au.com.codeka.warworlds.server.world.WatchableObject import java.util.* /** Handler for /admin/ajax/starfield requests. */ class AjaxStarfieldHandler : AjaxHandler() { companion object { private val log = Log("AjaxStarfieldHandler") } public override fun get() { when (request.getParameter("action")) { "xy" -> { val x = request.getParameter("x").toLong() val y = request.getParameter("y").toLong() handleXyRequest(x, y) } "search" -> { val starId = request.getParameter("star_id").toLong() handleSearchRequest(starId) } else -> throw RequestException(400, "Unknown action: ${request.getParameter("action")}") } } public override fun post() { when (request.getParameter("action")) { "simulate" -> { val starId = request.getParameter("id").toLong() handleSimulateRequest(starId) } "modify" -> { val starId = request.getParameter("id").toLong() val modifyJson = request.getParameter("modify") handleModifyRequest(starId, modifyJson) } "delete" -> { val starId = request.getParameter("id").toLong() handleDeleteRequest(starId) } "clearNatives" -> { val starId = request.getParameter("id").toLong() handleClearNativesRequest(starId) } "forceMoveComplete" -> { val starId = request.getParameter("id").toLong() val fleetId = request.getParameter("fleetId").toLong() handleForceMoveComplete(starId, fleetId) } "forceBuildRequestComplete" -> { val starId = request.getParameter("id").toLong() val buildRequestId = request.getParameter("reqId").toLong() handleForceBuildRequestComplete(starId, buildRequestId) } "resetSector" -> { val x = request.getParameter("x").toLong() val y = request.getParameter("y").toLong() handleResetSector(x, y) } else -> throw RequestException(400, "Unknown action: ${request.getParameter("action")}") } } private fun handleXyRequest(x: Long, y: Long) { val sector = SectorManager.i.getSector(SectorCoord(x = x, y = y)) SectorManager.i.verifyNativeColonies(sector) setResponseJson(sector.get()) } private fun handleSearchRequest(starId: Long) { val star = StarManager.i.getStar(starId) if (star == null) { response.status = 404 return } setResponseJson(star.get()) } private fun handleSimulateRequest(starId: Long) { setResponseGson(modifyAndSimulate(starId, null)) } private fun handleModifyRequest(starId: Long, modifyJson: String) { val modification = fromJson(modifyJson, StarModification::class.java) setResponseGson(modifyAndSimulate(starId, modification)) } private fun handleDeleteRequest(starId: Long) { log.debug("delete star: %d", starId) StarManager.i.deleteStar(starId) } private fun handleClearNativesRequest(starId: Long) { log.debug("delete star: %d", starId) modifyAndSimulate(starId, StarModification( type = StarModification.Type.EMPTY_NATIVE)) } private fun handleForceMoveComplete(starId: Long, fleetId: Long) { log.debug("force move complete (star: %d, fleet: %d)", starId, fleetId) val starWo: WatchableObject<Star> = StarManager.i.getStar(starId) ?: return synchronized(starWo.lock) { var star = starWo.get() for (i in star.fleets.indices) { if (star.fleets[i].id == fleetId) { val fleets = ArrayList(star.fleets) fleets[i] = fleets[i].copy(eta = 100L) star = star.copy(fleets = fleets) } } starWo.set(star) } // Now just simulate to make sure it processes it. setResponseGson(modifyAndSimulate(starId, null)) } private fun handleForceBuildRequestComplete(starId: Long, buildRequestId: Long) { log.debug("force build request complete (star: %d, req: %d)", starId, buildRequestId) val starWo: WatchableObject<Star> = StarManager.i.getStar(starId) ?: return synchronized(starWo.lock) { val star = MutableStar.from(starWo.get()) for (planet in star.planets) { val colony = planet.colony ?: continue for (br in colony.buildRequests) { if (br.id == buildRequestId) { // Set the end time well in the past, so that the star manager think it's done. br.endTime = 100L br.progress = 1.0f } } } starWo.set(star.build()) } // Now just simulate to make sure it processes it. setResponseGson(modifyAndSimulate(starId, null)) } private fun modifyAndSimulate(starId: Long, modification: StarModification?): SimulateResponse { val resp = SimulateResponse() val startTime = System.nanoTime() val star = StarManager.i.getStarOrError(starId) resp.loadTime = (System.nanoTime() - startTime) / 1000000L val logMessages = StringBuilder() val modifications = ArrayList<StarModification>() if (modification != null) { modifications.add(modification) } try { StarManager.i.modifyStar(star, modifications, LogHandler(logMessages)) } catch (e: SuspiciousModificationException) { log.warning("Suspicious modification.", e) // We'll log it as well, even though technically it wasn't the empire who made it. SuspiciousEventManager.i.addSuspiciousEvent(e) throw RequestException(e) } val simulateTime = System.nanoTime() resp.simulateTime = (simulateTime - startTime) / 1000000L resp.logMessages = logMessages.toString() return resp } private fun handleResetSector(x: Long, y: Long) { SectorManager.i.resetSector(SectorCoord(x = x, y = y)) } private class LogHandler internal constructor(private val logMessages: StringBuilder) : Simulation.LogHandler { override fun setStarName(starName: String?) { // ignore. } override fun log(message: String) { logMessages.append(message) logMessages.append("\n") } } private class SimulateResponse { var loadTime: Long = 0 var simulateTime: Long = 0 var logMessages: String? = null } }
mit
c2b442f7b4e0efa7c139cb3a32b0181c
33.623116
98
0.673392
3.952381
false
false
false
false
codeka/wwmmo
client/src/main/kotlin/au/com/codeka/warworlds/client/opengl/TextTexture.kt
1
3380
package au.com.codeka.warworlds.client.opengl import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import android.opengl.GLES20 import android.opengl.GLUtils import au.com.codeka.warworlds.common.Log import java.util.* /** * This is a [Texture] which is used to back an image for drawing arbitrary strings. */ class TextTexture : Texture() { private val bitmap: Bitmap private val canvas: Canvas private val paint: Paint private val characters: MutableMap<Char, Rect> = HashMap() private var id: Int private var dirty = false /** The offset from the left of the texture that we'll draw the next character. */ private var currRowOffsetX = 0 /** The offset from the top of the texture that we'll draw the next character. */ private var currRowOffsetY = 0 override fun bind() { if (dirty) { if (id == -1) { val textureHandleBuffer = IntArray(1) GLES20.glGenTextures(1, textureHandleBuffer, 0) GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandleBuffer[0]) GLES20.glTexParameteri( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR) GLES20.glTexParameteri( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR) id = textureHandleBuffer[0] setTextureId(id) } super.bind() GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0) dirty = false return } super.bind() } val textHeight: Float get() = TEXT_HEIGHT.toFloat() /** Ensures that we have cached all the characters needed to draw every character in the string. */ fun ensureText(str: String) { for (i in 0 until str.length) { ensureChar(str[i]) } } /** Gets the bounds of the given char. */ fun getCharBounds(ch: Char): Rect { var bounds = characters[ch] if (bounds == null) { ensureChar(ch) bounds = characters[ch] } return bounds!! } private fun ensureChar(ch: Char) { if (characters.containsKey(ch)) { return } val str = String(charArrayOf(ch)) val charWidth = Math.ceil(paint.measureText(str).toDouble()).toInt() if (currRowOffsetX + charWidth > width) { currRowOffsetX = 0 currRowOffsetY += ROW_HEIGHT } canvas.drawText(str, currRowOffsetX.toFloat(), currRowOffsetY + TEXT_HEIGHT - paint.descent() + (ROW_HEIGHT - TEXT_HEIGHT), paint) val bounds = Rect(currRowOffsetX, currRowOffsetY, currRowOffsetX + charWidth, currRowOffsetY + ROW_HEIGHT) characters[ch] = bounds currRowOffsetX += charWidth dirty = true } companion object { private val log = Log("TextTexture") // TODO: make the bitmap automatically resize if it needs to. const val width = 512 const val height = 512 /** The height of the text. */ private const val TEXT_HEIGHT = 28 private const val ROW_HEIGHT = 32 } init { bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) canvas = Canvas(bitmap) paint = Paint() paint.textSize = TEXT_HEIGHT.toFloat() paint.isAntiAlias = true paint.setARGB(255, 255, 255, 255) id = -1 ensureText("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890" + "!@#$%^&*()`~-=_+[]\\{}|;':\",./<>? ") } }
mit
b9f9ca6bc029b91496bd314ec8663458
28.911504
101
0.658876
3.823529
false
false
false
false
AndroidX/androidx
camera/integration-tests/viewtestapp/src/main/java/androidx/camera/integration/view/MlKitFragment.kt
3
3981
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.integration.view import android.graphics.RectF import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ToggleButton import androidx.camera.core.CameraSelector.DEFAULT_BACK_CAMERA import androidx.camera.core.CameraSelector.DEFAULT_FRONT_CAMERA import androidx.camera.core.impl.utils.executor.CameraXExecutors.mainThreadExecutor import androidx.camera.mlkit.vision.MlKitAnalyzer import androidx.camera.view.CameraController.COORDINATE_SYSTEM_VIEW_REFERENCED import androidx.camera.view.LifecycleCameraController import androidx.camera.view.PreviewView import androidx.fragment.app.Fragment import com.google.mlkit.vision.barcode.BarcodeScanner import com.google.mlkit.vision.barcode.BarcodeScanning /** * Fragment for testing MLKit integration. */ class MlKitFragment : Fragment() { private lateinit var cameraController: LifecycleCameraController private lateinit var previewView: PreviewView private lateinit var overlayView: OverlayView private lateinit var toggle: ToggleButton private var barcodeScanner: BarcodeScanner? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Set up UI. val view = inflater.inflate(R.layout.mlkit_view, container, false) previewView = view.findViewById(R.id.preview_view) overlayView = view.findViewById(R.id.overlay_view) toggle = view.findViewById(R.id.toggle_camera) toggle.setOnCheckedChangeListener { _, _ -> updateCameraOrientation() } previewView.implementationMode = PreviewView.ImplementationMode.COMPATIBLE // This button resets the pipeline. This is for testing when the detector is closed, // MlKitAnalyzer handles it correctly. view.findViewById<Button>(R.id.restart).setOnClickListener { clearAndSetAnalyzer() } // Set up CameraX. cameraController = LifecycleCameraController(requireContext()) cameraController.bindToLifecycle(viewLifecycleOwner) previewView.controller = cameraController clearAndSetAnalyzer() // Update states to match UI. updateCameraOrientation() return view } override fun onDestroyView() { super.onDestroyView() barcodeScanner?.close() } private fun updateCameraOrientation() { cameraController.cameraSelector = if (toggle.isChecked) DEFAULT_BACK_CAMERA else DEFAULT_FRONT_CAMERA } private fun clearAndSetAnalyzer() { barcodeScanner?.close() barcodeScanner = BarcodeScanning.getClient() cameraController.clearImageAnalysisAnalyzer() val scanner = barcodeScanner!! cameraController.setImageAnalysisAnalyzer(mainThreadExecutor(), MlKitAnalyzer( listOf(scanner), COORDINATE_SYSTEM_VIEW_REFERENCED, mainThreadExecutor() ) { result -> val barcodes = result.getValue(scanner) if (barcodes != null && barcodes.size > 0) { overlayView.setTileRect(RectF(barcodes[0].boundingBox)) overlayView.invalidate() } }) } }
apache-2.0
fe30e436f9135595d1b6d8fcd840143a
37.288462
92
0.714142
4.92698
false
false
false
false
thanksmister/androidthings-mqtt-alarm-panel
app/src/main/java/com/thanksmister/iot/mqtt/alarmpanel/ui/fragments/MainFragment.kt
1
8894
/* * Copyright (c) 2017. ThanksMister LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thanksmister.iot.mqtt.alarmpanel.ui.fragments import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import com.thanksmister.iot.mqtt.alarmpanel.BaseActivity import com.thanksmister.iot.mqtt.alarmpanel.BaseFragment import com.thanksmister.iot.mqtt.alarmpanel.R import com.thanksmister.iot.mqtt.alarmpanel.ui.Configuration import com.thanksmister.iot.mqtt.alarmpanel.ui.activities.LogActivity import com.thanksmister.iot.mqtt.alarmpanel.ui.activities.MainActivity import com.thanksmister.iot.mqtt.alarmpanel.ui.activities.SettingsActivity import com.thanksmister.iot.mqtt.alarmpanel.ui.views.AlarmDisableView import com.thanksmister.iot.mqtt.alarmpanel.ui.views.AlarmTriggeredView import com.thanksmister.iot.mqtt.alarmpanel.ui.views.SettingsCodeView import com.thanksmister.iot.mqtt.alarmpanel.utils.AlarmUtils import com.thanksmister.iot.mqtt.alarmpanel.utils.DialogUtils import com.thanksmister.iot.mqtt.alarmpanel.viewmodel.MainViewModel import com.thanksmister.iot.mqtt.alarmpanel.viewmodel.MessageViewModel import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.fragment_main.* import timber.log.Timber import javax.inject.Inject class MainFragment : BaseFragment() { @Inject lateinit var configuration: Configuration; @Inject lateinit var dialogUtils: DialogUtils; private var listener: OnMainFragmentListener? = null /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. */ interface OnMainFragmentListener { fun manuallyLaunchScreenSaver() fun publishDisarmed() fun navigatePlatformPanel() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onAttach(context: Context?) { super.onAttach(context) if (context is OnMainFragmentListener) { listener = context } else { throw RuntimeException(context!!.toString() + " must implement OnMainFragmentListener") } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) observeViewModel(viewModel) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) buttonSettings.setOnClickListener({showSettingsCodeDialog()}) buttonSleep.setOnClickListener({listener?.manuallyLaunchScreenSaver()}) buttonLogs.setOnClickListener({ val intent = LogActivity.createStartIntent(activity!!.applicationContext) startActivity(intent) }) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_main, container, false) } override fun onResume() { super.onResume() if (viewModel.hasPlatform()) { platformButton.visibility = View.VISIBLE; platformButton.setOnClickListener(View.OnClickListener {listener?.navigatePlatformPanel() }) } else { platformButton.visibility = View.INVISIBLE; } } override fun onDetach() { super.onDetach() listener = null } private fun observeViewModel(viewModel: MessageViewModel) { disposable.add(viewModel.getAlarmState() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ state -> Timber.d("Alarm state: " + state) Timber.d("Alarm mode: " + viewModel.getAlarmMode()) activity?.runOnUiThread(java.lang.Runnable { when (state) { AlarmUtils.STATE_ARM_AWAY, AlarmUtils.STATE_ARM_HOME -> { dialogUtils.clearDialogs() } AlarmUtils.STATE_DISARM -> { dialogUtils.clearDialogs() hideTriggeredView() } AlarmUtils.STATE_PENDING -> { dialogUtils.clearDialogs() if (viewModel.isAlarmDisableMode()) { // we need a pending time greater than zero to show the dialog, or its just going to go to trigger if (viewModel.getAlarmPendingTime() > 0) { showAlarmDisableDialog(true, configuration.pendingTime) } } } AlarmUtils.STATE_TRIGGERED -> { dialogUtils.clearDialogs() showAlarmTriggered() } } }) }, { error -> Timber.e("Unable to get message: " + error) })) } private fun showSettingsCodeDialog() { if (configuration.isFirstTime) { val intent = SettingsActivity.createStartIntent(activity!!.applicationContext) startActivity(intent) } else { dialogUtils.showSettingsCodeDialog(activity as MainActivity, configuration.alarmCode, object : SettingsCodeView.ViewListener { override fun onComplete(code: Int) { if (code == configuration.alarmCode) { val intent = SettingsActivity.createStartIntent(activity!!.applicationContext) startActivity(intent) } dialogUtils.clearDialogs() } override fun onError() { Toast.makeText(activity, R.string.toast_code_invalid, Toast.LENGTH_SHORT).show() } override fun onCancel() { dialogUtils.clearDialogs() } }) } } private fun showAlarmDisableDialog(beep: Boolean, timeRemaining: Int) { if(isAdded) { dialogUtils.showAlarmDisableDialog(activity as BaseActivity, object : AlarmDisableView.ViewListener { override fun onComplete(code: Int) { listener?.publishDisarmed() dialogUtils.clearDialogs() } override fun onError() { Toast.makeText(activity, R.string.toast_code_invalid, Toast.LENGTH_SHORT).show() } override fun onCancel() { dialogUtils.clearDialogs() } }, configuration.alarmCode, beep, timeRemaining) } } private fun showAlarmTriggered() { if (isAdded) { mainView.visibility = View.GONE triggeredView.visibility = View.VISIBLE val code = configuration.alarmCode val disarmView = activity!!.findViewById<AlarmTriggeredView>(R.id.alarmTriggeredView) disarmView.setCode(code) disarmView.listener = object : AlarmTriggeredView.ViewListener { override fun onComplete() { listener!!.publishDisarmed() } override fun onError() { Toast.makeText(activity, R.string.toast_code_invalid, Toast.LENGTH_SHORT).show() } } } } private fun hideTriggeredView() { mainView.visibility = View.VISIBLE triggeredView.visibility = View.GONE } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. */ @JvmStatic fun newInstance(): MainFragment { return MainFragment() } } } // Required empty public constructor
apache-2.0
e47e0708b83889310bc4c690630131df
40.372093
138
0.615134
5.06492
false
false
false
false
AndroidX/androidx
compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/lazy/list/LazyListFocusMoveTest.kt
3
19974
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.lazy.list import androidx.compose.foundation.focusable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.focus.FocusDirection.Companion.Down import androidx.compose.ui.focus.FocusDirection.Companion.Enter import androidx.compose.ui.focus.FocusDirection.Companion.Exit import androidx.compose.ui.focus.FocusDirection.Companion.Left import androidx.compose.ui.focus.FocusDirection.Companion.Next import androidx.compose.ui.focus.FocusDirection.Companion.Previous import androidx.compose.ui.focus.FocusDirection.Companion.Right import androidx.compose.ui.focus.FocusDirection.Companion.Up import androidx.compose.ui.focus.FocusManager import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.test.junit4.ComposeContentTestRule import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.LayoutDirection.Ltr import androidx.compose.ui.unit.LayoutDirection.Rtl import androidx.compose.ui.unit.dp import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.runBlocking import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @OptIn(ExperimentalComposeUiApi::class) @MediumTest @RunWith(Parameterized::class) class LazyListFocusMoveTest(param: Param) { @get:Rule val rule = createComposeRule() // We need to wrap the inline class parameter in another class because Java can't instantiate // the inline class. class Param( val focusDirection: FocusDirection, val reverseLayout: Boolean, val layoutDirection: LayoutDirection ) { override fun toString() = "focusDirection=$focusDirection " + "reverseLayout=$reverseLayout " + "layoutDirection=$layoutDirection" } private val focusDirection = param.focusDirection private val reverseLayout = param.reverseLayout private val layoutDirection = param.layoutDirection private val initiallyFocused: FocusRequester = FocusRequester() private var isLazyListFocused by mutableStateOf(false) private val isFocused = mutableMapOf<Int, Boolean>() private lateinit var lazyListState: LazyListState private lateinit var focusManager: FocusManager companion object { @JvmStatic @Parameterized.Parameters(name = "{0}") fun initParameters() = buildList { for (direction in listOf(Previous, Next, Left, Right, Up, Down, Enter, Exit)) { for (reverseLayout in listOf(true, false)) { for (layoutDirection in listOf(Ltr, Rtl)) { add(Param(direction, reverseLayout, layoutDirection)) } } } } } @Test fun moveFocusAmongVisibleItems() { // Arrange. rule.setTestContent { lazyList(50.dp, lazyListState) { item { FocusableBox(0) } item { FocusableBox(1, initiallyFocused) } item { FocusableBox(2) } } } rule.runOnIdle { initiallyFocused.requestFocus() } // Act. val success = rule.runOnIdle { focusManager.moveFocus(focusDirection) } // Assert. rule.runOnIdle { assertThat(success).apply { if (focusDirection == Enter) isFalse() else isTrue() } when (focusDirection) { Left -> when (layoutDirection) { Ltr -> assertThat(isFocused[if (reverseLayout) 2 else 0]).isTrue() Rtl -> assertThat(isFocused[if (reverseLayout) 0 else 2]).isTrue() } Right -> when (layoutDirection) { Ltr -> assertThat(isFocused[if (reverseLayout) 0 else 2]).isTrue() Rtl -> assertThat(isFocused[if (reverseLayout) 2 else 0]).isTrue() } Up -> assertThat(isFocused[if (reverseLayout) 2 else 0]).isTrue() Down -> assertThat(isFocused[if (reverseLayout) 0 else 2]).isTrue() Previous -> assertThat(isFocused[0]).isTrue() Next -> assertThat(isFocused[2]).isTrue() Enter -> assertThat(isFocused[1]).isTrue() Exit -> assertThat(isLazyListFocused).isTrue() else -> unsupportedDirection() } } } @Test fun moveFocusToItemThatIsJustBeyondBounds() { // Arrange. rule.setTestContent { lazyList(30.dp, lazyListState) { items(5) { FocusableBox(it) } item { FocusableBox(5, initiallyFocused) } items(5) { FocusableBox(it + 6) } } } rule.runOnIdle { // Scroll so that the focused item is in the middle. runBlocking { lazyListState.scrollToItem(4) } // Move focus to the last visible item. initiallyFocused.requestFocus() when (focusDirection) { Left, Right, Up, Down, Previous, Next -> focusManager.moveFocus(focusDirection) Enter, Exit -> { /* Do nothing */ } else -> unsupportedDirection() } } // Act. val success = rule.runOnIdle { focusManager.moveFocus(focusDirection) } // Assert. rule.runOnIdle { assertThat(success).apply { if (focusDirection == Enter) isFalse() else isTrue() } when (focusDirection) { Left -> when (layoutDirection) { Ltr -> assertThat(isFocused[if (reverseLayout) 7 else 3]).isTrue() Rtl -> assertThat(isFocused[if (reverseLayout) 3 else 7]).isTrue() } Right -> when (layoutDirection) { Ltr -> assertThat(isFocused[if (reverseLayout) 3 else 7]).isTrue() Rtl -> assertThat(isFocused[if (reverseLayout) 7 else 3]).isTrue() } Up -> assertThat(isFocused[if (reverseLayout) 7 else 3]).isTrue() Down -> assertThat(isFocused[if (reverseLayout) 3 else 7]).isTrue() Previous -> assertThat(isFocused[3]).isTrue() Next -> assertThat(isFocused[7]).isTrue() Enter -> assertThat(isFocused[5]).isTrue() Exit -> assertThat(isLazyListFocused).isTrue() else -> unsupportedDirection() } } } @Test fun moveFocusToItemThatIsFarBeyondBounds() { // Arrange. rule.setTestContent { lazyList(30.dp, lazyListState) { items(5) { FocusableBox(it) } items(100) { Box(Modifier.size(10.dp)) } item { FocusableBox(105) } item { FocusableBox(106, initiallyFocused) } item { FocusableBox(107) } items(100) { Box(Modifier.size(10.dp)) } items(5) { FocusableBox(it + 208) } } } rule.runOnIdle { // Scroll so that the focused item is in the middle. runBlocking { lazyListState.scrollToItem(105) } initiallyFocused.requestFocus() // Move focus to the last visible item. when (focusDirection) { Left, Right, Up, Down, Previous, Next -> focusManager.moveFocus(focusDirection) Enter, Exit -> { /* Do nothing */ } else -> unsupportedDirection() } } // Act. val success = rule.runOnIdle { focusManager.moveFocus(focusDirection) } // Assert. rule.runOnIdle { assertThat(success).apply { if (focusDirection == Enter) isFalse() else isTrue() } when (focusDirection) { Left -> when (layoutDirection) { Ltr -> assertThat(isFocused[if (reverseLayout) 208 else 4]).isTrue() Rtl -> assertThat(isFocused[if (reverseLayout) 4 else 208]).isTrue() } Right -> when (layoutDirection) { Ltr -> assertThat(isFocused[if (reverseLayout) 4 else 208]).isTrue() Rtl -> assertThat(isFocused[if (reverseLayout) 208 else 4]).isTrue() } Up -> assertThat(isFocused[if (reverseLayout) 208 else 4]).isTrue() Down -> assertThat(isFocused[if (reverseLayout) 4 else 208]).isTrue() Previous -> assertThat(isFocused[4]).isTrue() Next -> assertThat(isFocused[208]).isTrue() Enter -> assertThat(isFocused[106]).isTrue() Exit -> assertThat(isLazyListFocused).isTrue() else -> unsupportedDirection() } } } @Test fun moveFocusToItemThatIsBeyondBoundsAndInANestedLazyList() { // Arrange. rule.setTestContent { lazyList(30.dp, lazyListState) { item { lazyListCrossAxis(30.dp) { items(3) { FocusableBox(it + 0) } } } item { FocusableBox(3) } item { FocusableBox(4, initiallyFocused) } item { FocusableBox(5) } item { lazyListCrossAxis(30.dp) { items(3) { FocusableBox(it + 6) } } } } } rule.runOnIdle { // Scroll so that the focused item is in the middle. runBlocking { lazyListState.scrollToItem(1) } initiallyFocused.requestFocus() // Move focus to the last visible item. when (focusDirection) { Left, Right, Up, Down, Previous, Next -> focusManager.moveFocus(focusDirection) Enter, Exit -> { /* Do nothing */ } else -> unsupportedDirection() } } // Act. val success = rule.runOnIdle { focusManager.moveFocus(focusDirection) } // Assert. rule.runOnIdle { assertThat(success).apply { if (focusDirection == Enter) isFalse() else isTrue() } when (focusDirection) { Left -> when (layoutDirection) { Ltr -> assertThat(isFocused[if (reverseLayout) 8 else 0]).isTrue() Rtl -> assertThat(isFocused[if (reverseLayout) 2 else 6]).isTrue() } Right -> when (layoutDirection) { Ltr -> assertThat(isFocused[if (reverseLayout) 2 else 6]).isTrue() Rtl -> assertThat(isFocused[if (reverseLayout) 8 else 0]).isTrue() } Up -> assertThat(isFocused[if (reverseLayout) 8 else 0]).isTrue() Down -> assertThat(isFocused[if (reverseLayout) 2 else 6]).isTrue() Previous -> assertThat(isFocused[2]).isTrue() Next -> assertThat(isFocused[6]).isTrue() Enter -> assertThat(isFocused[4]).isTrue() Exit -> assertThat(isLazyListFocused).isTrue() else -> unsupportedDirection() } } } @Test fun moveFocusToItemThatIsBeyondBoundsAndOutsideTheCurrentLazyList() { // Arrange. rule.setTestContent { lazyList(30.dp, lazyListState) { item { FocusableBox(0) } item { lazyListCrossAxis(30.dp) { items(3) { FocusableBox(it + 1) } } } item { FocusableBox(4, initiallyFocused) } item { lazyListCrossAxis(30.dp) { items(3) { FocusableBox(it + 5) } } } item { FocusableBox(8) } } } rule.runOnIdle { // Scroll so that the focused item is in the middle. runBlocking { lazyListState.scrollToItem(1, 10) } initiallyFocused.requestFocus() // Move focus to the last visible item. when (focusDirection) { Left, Right, Up, Down -> focusManager.moveFocus(focusDirection) Previous, Next -> repeat(3) { focusManager.moveFocus(focusDirection) } Enter, Exit -> { /* Do nothing */ } else -> unsupportedDirection() } } // Act. val success = rule.runOnIdle { focusManager.moveFocus(focusDirection) } // Assert. rule.runOnIdle { assertThat(success).apply { if (focusDirection == Enter) isFalse() else isTrue() } when (focusDirection) { Left -> when (layoutDirection) { Ltr -> assertThat(isFocused[if (reverseLayout) 8 else 0]).isTrue() Rtl -> assertThat(isFocused[if (reverseLayout) 0 else 8]).isTrue() } Right -> when (layoutDirection) { Ltr -> assertThat(isFocused[if (reverseLayout) 0 else 8]).isTrue() Rtl -> assertThat(isFocused[if (reverseLayout) 8 else 0]).isTrue() } Up -> assertThat(isFocused[if (reverseLayout) 8 else 0]).isTrue() Down -> assertThat(isFocused[if (reverseLayout) 0 else 8]).isTrue() Previous -> assertThat(isFocused[0]).isTrue() Next -> assertThat(isFocused[8]).isTrue() Enter -> assertThat(isFocused[4]).isTrue() Exit -> assertThat(isLazyListFocused).isTrue() else -> unsupportedDirection() } } } @Test fun moveFocusAmongNestedLazyLists() { // Arrange. rule.setTestContent { lazyList(30.dp, lazyListState) { item { lazyListCrossAxis(30.dp) { items(3) { FocusableBox(it + 0) } } } item { lazyListCrossAxis(30.dp) { items(3) { FocusableBox(it + 3) } } } item { FocusableBox(6, initiallyFocused) } item { lazyListCrossAxis(30.dp) { items(3) { FocusableBox(it + 7) } } } item { lazyListCrossAxis(30.dp) { items(3) { FocusableBox(it + 10) } } } } } rule.runOnIdle { // Scroll so that the focused item is in the middle. runBlocking { lazyListState.scrollToItem(2, 0) } initiallyFocused.requestFocus() // Move focus to the last visible item. when (focusDirection) { Left, Right, Up, Down -> focusManager.moveFocus(focusDirection) Previous, Next -> repeat(3) { focusManager.moveFocus(focusDirection) } Enter, Exit -> { /* Do nothing */ } else -> unsupportedDirection() } } // Act. val success = rule.runOnIdle { focusManager.moveFocus(focusDirection) } // Assert. rule.runOnIdle { assertThat(success).apply { if (focusDirection == Enter) isFalse() else isTrue() } when (focusDirection) { Left -> when (layoutDirection) { Ltr -> assertThat(isFocused[if (reverseLayout) 12 else 0]).isTrue() Rtl -> assertThat(isFocused[if (reverseLayout) 2 else 10]).isTrue() } Right -> when (layoutDirection) { Ltr -> assertThat(isFocused[if (reverseLayout) 2 else 10]).isTrue() Rtl -> assertThat(isFocused[if (reverseLayout) 12 else 0]).isTrue() } Up -> assertThat(isFocused[if (reverseLayout) 12 else 0]).isTrue() Down -> assertThat(isFocused[if (reverseLayout) 2 else 10]).isTrue() Previous -> assertThat(isFocused[2]).isTrue() Next -> assertThat(isFocused[10]).isTrue() Enter -> assertThat(isFocused[6]).isTrue() Exit -> assertThat(isLazyListFocused).isTrue() else -> unsupportedDirection() } } } @Composable private fun FocusableBox(index: Int, focusRequester: FocusRequester = FocusRequester()) { Box( Modifier .size(10.dp) .focusRequester(focusRequester) .onFocusChanged { isFocused[index] = it.isFocused } .focusable() ) } private fun ComposeContentTestRule.setTestContent(composable: @Composable () -> Unit) { setContent { CompositionLocalProvider(LocalLayoutDirection provides layoutDirection) { focusManager = LocalFocusManager.current lazyListState = rememberLazyListState() composable() } } } @Composable private fun lazyList( size: Dp, state: LazyListState = rememberLazyListState(), content: LazyListScope.() -> Unit ) { when (focusDirection) { Left, Right, Enter, Exit, Next, Previous -> LazyRow( modifier = Modifier .size(size) .onFocusChanged { isLazyListFocused = it.isFocused } .focusable(), state = state, reverseLayout = reverseLayout, content = content ) Up, Down -> LazyColumn( modifier = Modifier .size(size) .onFocusChanged { isLazyListFocused = it.isFocused } .focusable(), state = state, reverseLayout = reverseLayout, content = content ) else -> unsupportedDirection() } } @Composable private fun lazyListCrossAxis( size: Dp, state: LazyListState = rememberLazyListState(), content: LazyListScope.() -> Unit ) { when (focusDirection) { Left, Right, Enter, Exit, Next, Previous -> LazyColumn( modifier = Modifier.size(size), state = state, reverseLayout = reverseLayout, content = content ) Up, Down -> LazyRow( modifier = Modifier.size(size), state = state, reverseLayout = reverseLayout, content = content ) else -> unsupportedDirection() } } private fun unsupportedDirection(): Nothing = error("Unsupported Focus Direction.") }
apache-2.0
6345c2b03373abead39a6feb7ffe1722
40.014374
97
0.577451
5.111054
false
false
false
false
vimeo/vimeo-networking-java
models/src/main/java/com/vimeo/networking2/ReviewPage.kt
1
836
package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import com.vimeo.networking2.annotations.Internal /** * Review page information. * * @param active Whether or not the review page is active for this video. * @param link Link to the Vimeo review page. * @param notes Whether or not notes are enabled on the review page. * @param vimeoLogo Whether or not the vimeo logo should be displayed on the review page. */ @Internal @JsonClass(generateAdapter = true) data class ReviewPage( @Internal @Json(name = "active") val active: Boolean? = null, @Internal @Json(name = "link") val link: String? = null, @Internal @Json(name = "notes") val notes: String? = null, @Internal @Json(name = "vimeo_logo") val vimeoLogo: Boolean? = null )
mit
58b882a883a61e155e301b1e59b7780f
22.885714
89
0.69378
3.699115
false
false
false
false
Undin/intellij-rust
toml/src/main/kotlin/org/rust/toml/inspections/CargoTomlCyclicFeatureInspection.kt
3
1505
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.toml.inspections import com.intellij.codeInspection.ProblemsHolder import org.rust.toml.isFeatureListHeader import org.toml.lang.psi.* import org.toml.lang.psi.ext.TomlLiteralKind import org.toml.lang.psi.ext.kind /** * * Consider `Cargo.toml`: * ``` * [features] * foo = ["foo"] * #^ Shows error that "foo" feature depends on itself * ``` */ class CargoTomlCyclicFeatureInspection : CargoTomlInspectionToolBase() { override fun buildCargoTomlVisitor(holder: ProblemsHolder): TomlVisitor { return object : TomlVisitor() { override fun visitLiteral(element: TomlLiteral) { val parentArray = element.parent as? TomlArray ?: return val parentKeyValue = parentArray.parent as? TomlKeyValue ?: return val parentTable = parentKeyValue.parent as? TomlTable ?: return if (!parentTable.header.isFeatureListHeader) return val parentFeatureName = parentKeyValue.key.text ?: return val featureName = (element.kind as? TomlLiteralKind.String)?.value if (featureName == parentFeatureName) { holder.registerProblem( element, "Cyclic feature dependency: feature `$parentFeatureName` depends on itself" ) } } } } }
mit
0e8f89195135b89a3f8dd5b2d742606c
34
99
0.626578
4.630769
false
false
false
false
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Main.kt
1
574
package com.baeldung.datastructures /** * Example of how to use the {@link Node} class. * */ fun main(args: Array<String>) { val tree = Node(4) val keys = arrayOf(8, 15, 21, 3, 7, 2, 5, 10, 2, 3, 4, 6, 11) for (key in keys) { tree.insert(key) } val node = tree.find(4)!! println("Node with value ${node.key} [left = ${node.left?.key}, right = ${node.right?.key}]") println("Delete node with key = 3") node.delete(3) print("Tree content after the node elimination: ") println(tree.visit().joinToString { it.toString() }) }
gpl-3.0
0038317c6268f3f4a4570e3d5bbf367a
29.210526
97
0.597561
3.171271
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/note/NoteContextMenu.kt
1
16189
/* * Copyright (C) 2013-2017 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.note import android.content.Context import android.os.Bundle import android.text.style.URLSpan import android.view.ContextMenu import android.view.ContextMenu.ContextMenuInfo import android.view.MenuItem import android.view.View import android.view.accessibility.AccessibilityManager import org.andstatus.app.IntentExtra import org.andstatus.app.R import org.andstatus.app.account.MyAccount import org.andstatus.app.activity.ActivityViewItem import org.andstatus.app.net.social.Actor import org.andstatus.app.net.social.ApiRoutineEnum import org.andstatus.app.net.social.Note import org.andstatus.app.note.FutureNoteContextMenuData.StateForSelectedViewItem import org.andstatus.app.origin.Origin import org.andstatus.app.timeline.ContextMenuHeader import org.andstatus.app.timeline.TimelineActivity import org.andstatus.app.timeline.TimelineActivity.Companion.startForTimeline import org.andstatus.app.timeline.meta.Timeline import org.andstatus.app.timeline.meta.TimelineType import org.andstatus.app.util.MyLog import org.andstatus.app.util.MyUrlSpan import org.andstatus.app.util.StringUtil import org.andstatus.app.view.MyContextMenu /** * Context menu and corresponding actions on notes from the list * @author [email protected] */ class NoteContextMenu(val menuContainer: NoteContextMenuContainer) : MyContextMenu(menuContainer.getActivity(), MyContextMenu.MENU_GROUP_NOTE) { @Volatile private var futureData: FutureNoteContextMenuData = FutureNoteContextMenuData.EMPTY private var selectedMenuItemTitle: String = "" override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenuInfo?) { onViewSelected(v, immediateFun = { createContextMenu(menu, v, it.getViewItem()) }, asyncFun = { it.showContextMenu() } ) } fun onViewSelected(v: View, immediateFun: ((NoteContextMenu) -> Unit)? = null, asyncFun: (NoteContextMenu) -> Unit) { saveContextOfSelectedItem(v) when (futureData.getStateFor(getViewItem())) { StateForSelectedViewItem.READY -> immediateFun?.invoke(this) ?: asyncFun(this) StateForSelectedViewItem.NEW -> FutureNoteContextMenuData.loadAsync(this, v, getViewItem(), asyncFun) else -> {} } } private fun createContextMenu(menu: ContextMenu, v: View, viewItem: BaseNoteViewItem<*>) { val method = "createContextMenu" val menuData = futureData.menuData val noteForAnyAccount = futureData.menuData.noteForAnyAccount if (getSelectedActingAccount().isValid && getSelectedActingAccount() != menuData.getMyAccount()) { setSelectedActingAccount(menuData.getMyAccount()) } if (futureData === FutureNoteContextMenuData.EMPTY) return var order = 0 try { ContextMenuHeader(getActivity(), menu).setTitle(noteForAnyAccount.getBodyTrimmed()) .setSubtitle(getActingAccount().getAccountName()) if ((getMyContext().context.getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager).isTouchExplorationEnabled) { addNoteLinksSubmenu(menu, v, order++) } if (!ConversationActivity::class.java.isAssignableFrom(getActivity().javaClass)) { NoteContextMenuItem.OPEN_CONVERSATION.addTo(menu, order++, R.string.menu_item_open_conversation) } if (menuContainer.getTimeline().actor.notSameUser(noteForAnyAccount.actor) || menuContainer.getTimeline().timelineType != TimelineType.SENT) { // Notes, where an Actor of this note is an Actor ("Sent timeline" of that actor) NoteContextMenuItem.NOTES_BY_ACTOR.addTo(menu, order++, StringUtil.format( getActivity(), R.string.menu_item_user_messages, noteForAnyAccount.actor.actorNameInTimeline)) } if (viewItem.isCollapsed) { NoteContextMenuItem.SHOW_DUPLICATES.addTo(menu, order++, R.string.show_duplicates) } else if (getActivity().getListData().canBeCollapsed(getActivity().getPositionOfContextMenu())) { NoteContextMenuItem.COLLAPSE_DUPLICATES.addTo(menu, order++, R.string.collapse_duplicates) } NoteContextMenuItem.ACTORS_OF_NOTE.addTo(menu, order++, R.string.users_of_message) if (menuData.isAuthorSucceededMyAccount() && Note.mayBeEdited( noteForAnyAccount.origin.originType, noteForAnyAccount.status)) { NoteContextMenuItem.EDIT.addTo(menu, order++, R.string.menu_item_edit) } if (noteForAnyAccount.status.mayBeSent()) { NoteContextMenuItem.RESEND.addTo(menu, order++, R.string.menu_item_resend) } if (isEditorVisible()) { NoteContextMenuItem.COPY_TEXT.addTo(menu, order++, R.string.menu_item_copy_text) NoteContextMenuItem.COPY_AUTHOR.addTo(menu, order++, R.string.menu_item_copy_author) } if (menuData.getMyActor().notSameUser(noteForAnyAccount.actor)) { if (menuData.actorFollowed) { NoteContextMenuItem.UNDO_FOLLOW_ACTOR.addTo(menu, order++, StringUtil.format( getActivity(), R.string.menu_item_stop_following_user, noteForAnyAccount.actor.actorNameInTimeline)) } else { NoteContextMenuItem.FOLLOW_ACTOR.addTo(menu, order++, StringUtil.format( getActivity(), R.string.menu_item_follow_user, noteForAnyAccount.actor.actorNameInTimeline)) } } if (noteForAnyAccount.actor.notSameUser(noteForAnyAccount.author)) { if (menuContainer.getTimeline().actor.notSameUser(noteForAnyAccount.author) || menuContainer.getTimeline().timelineType != TimelineType.SENT) { // Sent timeline of that actor NoteContextMenuItem.NOTES_BY_AUTHOR.addTo(menu, order++, StringUtil.format( getActivity(), R.string.menu_item_user_messages, noteForAnyAccount.author.actorNameInTimeline)) } if (menuData.getMyActor().notSameUser(noteForAnyAccount.author)) { if (menuData.authorFollowed) { NoteContextMenuItem.UNDO_FOLLOW_AUTHOR.addTo(menu, order++, StringUtil.format( getActivity(), R.string.menu_item_stop_following_user, noteForAnyAccount.author.actorNameInTimeline)) } else { NoteContextMenuItem.FOLLOW_AUTHOR.addTo(menu, order++, StringUtil.format( getActivity(), R.string.menu_item_follow_user, noteForAnyAccount.author.actorNameInTimeline)) } } } if (noteForAnyAccount.isLoaded() && (!noteForAnyAccount.visibility.isPrivate || noteForAnyAccount.origin.originType.isPrivateNoteAllowsReply) && !isEditorVisible()) { NoteContextMenuItem.REPLY.addTo(menu, order++, R.string.menu_item_reply) NoteContextMenuItem.REPLY_TO_CONVERSATION_PARTICIPANTS.addTo(menu, order++, R.string.menu_item_reply_to_conversation_participants) NoteContextMenuItem.REPLY_TO_MENTIONED_ACTORS.addTo(menu, order++, R.string.menu_item_reply_to_mentioned_users) } NoteContextMenuItem.SHARE.addTo(menu, order++, R.string.menu_item_share) if (!getAttachedMedia().isEmpty) { NoteContextMenuItem.VIEW_MEDIA.addTo(menu, order++, if (getAttachedMedia().getFirstToShare().getContentType().isImage()) R.string.menu_item_view_image else R.string.view_media) } if (noteForAnyAccount.isLoaded() && !noteForAnyAccount.visibility.isPrivate) { if (menuData.favorited) { NoteContextMenuItem.UNDO_LIKE.addTo(menu, order++, R.string.menu_item_destroy_favorite) } else { NoteContextMenuItem.LIKE.addTo(menu, order++, R.string.menu_item_favorite) } if (menuData.reblogged) { NoteContextMenuItem.UNDO_ANNOUNCE.addTo(menu, order++, getActingAccount().alternativeTermForResourceId(R.string.menu_item_destroy_reblog)) } else { // Don't allow an Actor to reblog himself if (getActingAccount().actorId != noteForAnyAccount.actor.actorId) { NoteContextMenuItem.ANNOUNCE.addTo(menu, order++, getActingAccount().alternativeTermForResourceId(R.string.menu_item_reblog)) } } } if (noteForAnyAccount.isLoaded()) { NoteContextMenuItem.OPEN_NOTE_PERMALINK.addTo(menu, order++, R.string.menu_item_open_message_permalink) } if (noteForAnyAccount.isLoaded()) { when (getMyContext().accounts.succeededForSameOrigin(noteForAnyAccount.origin).size) { 0, 1 -> { } 2 -> NoteContextMenuItem.ACT_AS_FIRST_OTHER_ACCOUNT.addTo(menu, order++, StringUtil.format( getActivity(), R.string.menu_item_act_as_user, getMyContext().accounts .firstOtherSucceededForSameOrigin(noteForAnyAccount.origin, getActingAccount()) .getShortestUniqueAccountName())) else -> NoteContextMenuItem.ACT_AS.addTo(menu, order++, R.string.menu_item_act_as) } } if (noteForAnyAccount.isPresentAtServer()) { NoteContextMenuItem.GET_NOTE.addTo(menu, order, R.string.get_message) } if (menuData.isAuthorSucceededMyAccount()) { if (noteForAnyAccount.isPresentAtServer()) { if (!menuData.reblogged && getActingAccount().connection .hasApiEndpoint(ApiRoutineEnum.DELETE_NOTE)) { NoteContextMenuItem.DELETE_NOTE.addTo(menu, order++, R.string.menu_item_destroy_status) } } else { NoteContextMenuItem.DELETE_NOTE.addTo(menu, order++, R.string.button_discard) } } else { NoteContextMenuItem.DELETE_NOTE.addTo(menu, order++, R.string.menu_item_delete_note_from_local_cache) } } catch (e: Exception) { MyLog.w(this, method, e) } } fun getViewItem(): BaseNoteViewItem<*> { if (mViewItem.isEmpty) { return NoteViewItem.EMPTY } if (mViewItem is BaseNoteViewItem<*>) { return mViewItem as BaseNoteViewItem<*> } else if (mViewItem is ActivityViewItem) { return (mViewItem as ActivityViewItem).noteViewItem } return NoteViewItem.EMPTY } private fun addNoteLinksSubmenu(menu: ContextMenu, v: View, order: Int) { val links: Array<URLSpan> = MyUrlSpan.getUrlSpans(v.findViewById<View?>(R.id.note_body)) when (links.size) { 0 -> { } 1 -> menu.add(ContextMenu.NONE, NoteContextMenuItem.OPEN_NOTE_LINK.getId(), order, getActivity().getText(R.string.n_message_link).toString() + NoteContextMenuItem.NOTE_LINK_SEPARATOR + links[0].getURL()) else -> { val subMenu = menu.addSubMenu(ContextMenu.NONE, ContextMenu.NONE, order, StringUtil.format(getActivity(), R.string.n_message_links, links.size)) var orderSubmenu = 0 for (link in links) { subMenu.add(ContextMenu.NONE, NoteContextMenuItem.OPEN_NOTE_LINK.getId(), orderSubmenu++, link.getURL()) } } } } override fun setSelectedActingAccount(myAccount: MyAccount) { if (myAccount != futureData.menuData.getMyAccount()) { futureData = FutureNoteContextMenuData.EMPTY } super.setSelectedActingAccount(myAccount) } fun getAttachedMedia(): NoteDownloads { return futureData.menuData.noteForAnyAccount.downloads } private fun isEditorVisible(): Boolean { return menuContainer.getNoteEditor()?.isVisible() == true } fun onContextItemSelected(item: MenuItem?) { if (item != null) { selectedMenuItemTitle = StringUtil.notNull(item.title.toString()) onContextItemSelected(NoteContextMenuItem.fromId(item.itemId), getNoteId()) } } fun onContextItemSelected(contextMenuItem: NoteContextMenuItem, noteId: Long) { if (futureData.isFor(noteId)) { contextMenuItem.execute(this) } } fun switchTimelineActivityView(timeline: Timeline) { if (TimelineActivity::class.java.isAssignableFrom(getActivity().javaClass)) { (getActivity() as TimelineActivity<*>).switchView(timeline) } else { startForTimeline(getMyContext(), getActivity(), timeline) } } fun loadState(savedInstanceState: Bundle?) { if (savedInstanceState != null && savedInstanceState.containsKey(IntentExtra.ACCOUNT_NAME.key)) { setSelectedActingAccount(menuContainer.getActivity().myContext.accounts.fromAccountName( savedInstanceState.getString(IntentExtra.ACCOUNT_NAME.key, menuContainer.getActivity().myContext.accounts.currentAccount.getAccountName()))) } } fun saveState(outState: Bundle) { outState.putString(IntentExtra.ACCOUNT_NAME.key, getSelectedActingAccount().getAccountName()) } fun getNoteId(): Long { return futureData.getNoteId() } fun getOrigin(): Origin { return futureData.menuData.noteForAnyAccount.origin } override fun getActingAccount(): MyAccount { return if (getSelectedActingAccount().nonEmpty) getSelectedActingAccount() else futureData.menuData.getMyAccount() } fun getActor(): Actor { return futureData.menuData.noteForAnyAccount.actor } fun getAuthor(): Actor { return futureData.menuData.noteForAnyAccount.author } fun getSelectedMenuItemTitle(): String { return selectedMenuItemTitle } fun setFutureData(futureData: FutureNoteContextMenuData) { this.futureData = futureData } }
apache-2.0
9c841fb1bfe0b25889fafa2f1a58a3dc
47.762048
148
0.604979
4.902786
false
false
false
false
ImXico/punk
image/src/test/kotlin/cyberpunk/image/ImageHelperTests.kt
2
353
package cyberpunk.image import org.junit.Test class ImageHelperTests { @Test fun `centering on X should keep Y intact`() { val newPosition = centerX(20f, 200, 20f) assert(newPosition.y == 20f) } @Test fun `centering on Y should keep X intact`() { val newPosition = centerY(10f, 300, 40f) assert(newPosition.x == 40f) } }
mit
c916159430981c1e6dec4e05a31503ee
18.611111
47
0.66289
3.209091
false
true
false
false
java-opengl-labs/learn-OpenGL
src/main/kotlin/learnOpenGL/b_lighting/2.1 basic lighting diffuse.kt
1
5875
package learnOpenGL.b_lighting /** * Created by GBarbieri on 28.04.2017. */ import glm_.func.rad import glm_.glm import glm_.mat4x4.Mat4 import glm_.vec3.Vec3 import gln.buffer.glBindBuffer import gln.draw.glDrawArrays import gln.get import gln.glClearColor import gln.glf.glf import gln.uniform.glUniform import gln.uniform.glUniform3f import gln.vertexArray.glEnableVertexAttribArray import gln.vertexArray.glVertexAttribPointer import learnOpenGL.a_gettingStarted.end import learnOpenGL.a_gettingStarted.swapAndPoll import org.lwjgl.opengl.GL11.* import org.lwjgl.opengl.GL15.* import org.lwjgl.opengl.GL20.glGetUniformLocation import org.lwjgl.opengl.GL30.* import uno.buffer.destroyBuf import uno.buffer.intBufferBig import uno.glsl.Program import uno.glsl.glDeletePrograms import uno.glsl.glUseProgram fun main(args: Array<String>) { with(BasicLightingDiffuse()) { run() end() } } val verticesCube0 = floatArrayOf( -0.5f, -0.5f, -0.5f, 0f, 0f, -1f, +0.5f, -0.5f, -0.5f, 0f, 0f, -1f, +0.5f, +0.5f, -0.5f, 0f, 0f, -1f, +0.5f, +0.5f, -0.5f, 0f, 0f, -1f, -0.5f, +0.5f, -0.5f, 0f, 0f, -1f, -0.5f, -0.5f, -0.5f, 0f, 0f, -1f, -0.5f, -0.5f, +0.5f, 0f, 0f, 1f, +0.5f, -0.5f, +0.5f, 0f, 0f, 1f, +0.5f, +0.5f, +0.5f, 0f, 0f, 1f, +0.5f, +0.5f, +0.5f, 0f, 0f, 1f, -0.5f, +0.5f, +0.5f, 0f, 0f, 1f, -0.5f, -0.5f, +0.5f, 0f, 0f, 1f, -0.5f, +0.5f, +0.5f, -1f, 0f, 0f, -0.5f, +0.5f, -0.5f, -1f, 0f, 0f, -0.5f, -0.5f, -0.5f, -1f, 0f, 0f, -0.5f, -0.5f, -0.5f, -1f, 0f, 0f, -0.5f, -0.5f, +0.5f, -1f, 0f, 0f, -0.5f, +0.5f, +0.5f, -1f, 0f, 0f, +0.5f, +0.5f, +0.5f, 1f, 0f, 0f, +0.5f, +0.5f, -0.5f, 1f, 0f, 0f, +0.5f, -0.5f, -0.5f, 1f, 0f, 0f, +0.5f, -0.5f, -0.5f, 1f, 0f, 0f, +0.5f, -0.5f, +0.5f, 1f, 0f, 0f, +0.5f, +0.5f, +0.5f, 1f, 0f, 0f, -0.5f, -0.5f, -0.5f, 0f, -1f, 0f, +0.5f, -0.5f, -0.5f, 0f, -1f, 0f, +0.5f, -0.5f, +0.5f, 0f, -1f, 0f, +0.5f, -0.5f, +0.5f, 0f, -1f, 0f, -0.5f, -0.5f, +0.5f, 0f, -1f, 0f, -0.5f, -0.5f, -0.5f, 0f, -1f, 0f, -0.5f, +0.5f, -0.5f, 0f, 1f, 0f, +0.5f, +0.5f, -0.5f, 0f, 1f, 0f, +0.5f, +0.5f, +0.5f, 0f, 1f, 0f, +0.5f, +0.5f, +0.5f, 0f, 1f, 0f, -0.5f, +0.5f, +0.5f, 0f, 1f, 0f, -0.5f, +0.5f, -0.5f, 0f, 1f, 0f) private class BasicLightingDiffuse { val window = initWindow0("Basic Lighting Diffuse") val lighting = Lighting() val lamp = Lamp() val vbo = intBufferBig(1) enum class VA { Cube, Light } val vao = intBufferBig<VA>() // lighting val lightPos = Vec3(1.2f, 1f, 2f) init { glEnable(GL_DEPTH_TEST) glGenVertexArrays(vao) // first, configure the cube's VAO (and VBO) glGenBuffers(vbo) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, verticesCube0, GL_STATIC_DRAW) glBindVertexArray(vao[VA.Cube]) glVertexAttribPointer(glf.pos3_nor3) glEnableVertexAttribArray(glf.pos3_nor3) // second, configure the light's VAO (VBO stays the same; the vertices are the same for the light object which is also a 3D cube) glBindVertexArray(vao[VA.Light]) glBindBuffer(GL_ARRAY_BUFFER, vbo) // note that we update the lamp's position attribute's stride to reflect the updated buffer data glVertexAttribPointer(glf.pos3_nor3[0]) glEnableVertexAttribArray(glf.pos3_nor3[0]) } inner class Lighting : Lamp("shaders/b/_2_1", "basic-lighting") { val objCol = glGetUniformLocation(name, "objectColor") val lgtCol = glGetUniformLocation(name, "lightColor") val lgtPos = glGetUniformLocation(name, "lightPos") } inner open class Lamp(root: String = "shaders/b/_1", shader: String = "lamp") : Program(root, "$shader.vert", "$shader.frag") { val model = glGetUniformLocation(name, "model") val view = glGetUniformLocation(name, "view") val proj = glGetUniformLocation(name, "projection") } fun run() { while (window.open) { window.processFrame() // render glClearColor(clearColor0) glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT) // be sure to activate shader when setting uniforms/drawing objects glUseProgram(lighting) glUniform3f(lighting.objCol, 1f, 0.5f, 0.31f) glUniform3f(lighting.lgtCol, 1f) glUniform3f(lighting.lgtPos, lightPos) // view/projection transformations val projection = glm.perspective(camera.zoom.rad, window.aspect, 0.1f, 100f) val view = camera.viewMatrix glUniform(lighting.proj, projection) glUniform(lighting.view, view) // world transformation var model = Mat4() glUniform(lighting.model, model) // render the cube glBindVertexArray(vao[VA.Cube]) glDrawArrays(GL_TRIANGLES, 36) // also draw the lamp object glUseProgram(lamp) glUniform(lamp.proj, projection) glUniform(lamp.view, view) model = model .translate(lightPos) .scale(0.2f) // a smaller cube glUniform(lamp.model, model) glBindVertexArray(vao[VA.Light]) glDrawArrays(GL_TRIANGLES, 36) window.swapAndPoll() } } fun end() { // optional: de-allocate all resources once they've outlived their purpose: glDeletePrograms(lighting, lamp) glDeleteVertexArrays(vao) glDeleteBuffers(vbo) destroyBuf(vao, vbo) window.end() } }
mit
8b3b1236d8ddb0ef1e96ebb411692ba7
27.945813
137
0.573617
2.7923
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/news/model/NewsSources.kt
1
835
package de.tum.`in`.tumcampusapp.component.ui.news.model import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.RoomWarnings import com.google.gson.annotations.SerializedName /** * This class contains information about the source of a [News] item. * * Find the currently available news sources at [https://app.tum.de/api/news/sources]. * * @param id The ID of the news source * @param title The title of the news source * @param icon The image URL of the icon of the news source */ @Entity(tableName = "news_sources") @SuppressWarnings(RoomWarnings.DEFAULT_CONSTRUCTOR) data class NewsSources( @PrimaryKey @SerializedName("source") var id: Int = -1, var title: String = "", var icon: String = "" ) { val isNewspread: Boolean get() = setOf(7, 8, 9, 13).contains(id) }
gpl-3.0
07ebcdc1d35f38597de67e0587e65079
27.827586
86
0.713772
3.744395
false
false
false
false
felipebz/sonar-plsql
zpa-core/src/test/kotlin/org/sonar/plugins/plsqlopen/api/sql/HierarchicalQueryClauseTest.kt
1
1801
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plugins.plsqlopen.api.sql import com.felipebz.flr.tests.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.sonar.plugins.plsqlopen.api.DmlGrammar import org.sonar.plugins.plsqlopen.api.RuleTest class HierarchicalQueryClauseTest : RuleTest() { @BeforeEach fun init() { setRootRule(DmlGrammar.HIERARCHICAL_QUERY_CLAUSE) } @Test fun matchesSimpleHierarchical() { assertThat(p).matches("connect by foo = bar") } @Test fun matchesHierarchicalQueryConnectByFirst() { assertThat(p).matches("connect by foo = bar start with foo = bar") } @Test fun matchesHierarchicalQueryStartWithFirst() { assertThat(p).matches("start with foo = bar connect by foo = bar") } @Test fun notMatchesStartWithFirstWithoutConnectBy() { assertThat(p).notMatches("start with foo = bar") } }
lgpl-3.0
b115d497f07df9b34aaa82e19c915730
31.745455
75
0.723487
4.159353
false
true
false
false
BoD/CineToday
app/src/main/kotlin/org/jraf/android/cinetoday/app/movie/list/MovieListAdapter.kt
1
5411
/* * This source is part of the * _____ ___ ____ * __ / / _ \/ _ | / __/___ _______ _ * / // / , _/ __ |/ _/_/ _ \/ __/ _ `/ * \___/_/|_/_/ |_/_/ (_)___/_/ \_, / * /___/ * repository. * * Copyright (C) 2017-present Benoit 'BoD' Lubek ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jraf.android.cinetoday.app.movie.list import android.annotation.SuppressLint import android.content.Context import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.palette.graphics.Palette import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import org.jraf.android.cinetoday.R import org.jraf.android.cinetoday.databinding.MovieListItemBinding import org.jraf.android.cinetoday.glide.GlideApp import org.jraf.android.cinetoday.glide.GlideHelper import org.jraf.android.cinetoday.model.movie.Movie import org.jraf.android.util.log.Log class MovieListAdapter( private val context: Context, private val movieListCallbacks: MovieListCallbacks, private val paletteListener: PaletteListener ) : RecyclerView.Adapter<MovieListAdapter.ViewHolder>() { private val layoutInflater: LayoutInflater = LayoutInflater.from(context) var data: Array<Movie> = emptyArray() set(value) { field = value notifyDataSetChanged() } class ViewHolder(val itemBinding: MovieListItemBinding) : RecyclerView.ViewHolder(itemBinding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = DataBindingUtil.inflate<MovieListItemBinding>(layoutInflater, R.layout.movie_list_item, parent, false) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, @SuppressLint("RecyclerView") position: Int) { val movie = data[position] holder.itemBinding.movie = movie holder.itemBinding.callbacks = movieListCallbacks if (movie.colorDark != null && movie.colorLight != null) { paletteListener.onPaletteAvailable( id = movie.id, colorDark = movie.colorDark!!, colorLight = movie.colorLight!!, cached = true ) } holder.itemBinding.executePendingBindings() GlideHelper.load(movie.posterUri, holder.itemBinding.imgPoster, object : RequestListener<Drawable> { override fun onLoadFailed( e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean ): Boolean { return false } override fun onResourceReady( resource: Drawable, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean ): Boolean { if (movie.colorDark == null || movie.colorLight == null) { // Generate the color Palette.from((resource as BitmapDrawable).bitmap).generate { palette -> if (palette == null) { Log.w("Could not generate palette") return@generate } val defaultColor = context.getColor(R.color.movie_list_bg) val colorDark = palette.getDarkVibrantColor(defaultColor) val colorLight = palette.getLightMutedColor(defaultColor) paletteListener.onPaletteAvailable( id = movie.id, colorDark = colorDark, colorLight = colorLight, cached = false ) } } // Preload the next image if (position + 1 in data.indices) { val nextMovie = data[position + 1] GlideApp.with(context).load(nextMovie.posterUri).centerCrop() .preload(holder.itemBinding.imgPoster.width, holder.itemBinding.imgPoster.height) } return false } }) } override fun getItemCount() = data.size override fun getItemId(position: Int) = if (data.isEmpty()) RecyclerView.NO_ID else data[position].id.hashCode().toLong() }
gpl-3.0
a34ec6e33192eee29e7b4cc068444286
39.081481
114
0.609499
4.973346
false
false
false
false
RightHandedMonkey/PersonalWebNotifier
app/src/main/java/com/rhm/pwn/model/URLCheckInterval.kt
1
900
package com.rhm.pwn.model /** * Created by sambo on 9/2/17. */ enum class URLCheckInterval(val interval: Long, private val description: String) { INT_1_MIN(60, "1 Minute"), INT_15_MIN(15 * 60, "15 Minutes"), INT_1_HOUR(60 * 60, "1 Hour"), INT_6_HOURS(6 * 60 * 60, "6 Hours"), INT_1_DAY(24 * 60 * 60, "1 Day"), INT_1_WEEK(7 * 24 * 60 * 60, "1 Week"); companion object { const val DEFAULT_VAL = 3 @JvmStatic fun getIndexFromInterval(intv: Long): Int { return listOf(values().indexOfFirst { it.interval == intv }, 0).max() ?: 0 } @JvmStatic fun getIntervalFromDescription(desc: String): Long { return values().firstOrNull { it.description == desc }?.interval ?: INT_1_DAY.interval } @JvmStatic val intervalStrings: List<String> = values().map { it.description } } }
mit
d278e9bea6d818d59e7dffed52015dad
27.125
98
0.576667
3.501946
false
false
false
false
rhdunn/xquery-intellij-plugin
src/plugin-marklogic/main/uk/co/reecedunn/intellij/plugin/marklogic/lang/MarkLogic.kt
1
3492
/* * Copyright (C) 2020 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.marklogic.lang import com.intellij.navigation.ItemPresentation import uk.co.reecedunn.intellij.plugin.marklogic.resources.MarkLogicIcons import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmProductType import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmProductVersion import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSchemaFile import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmVendorType import java.io.File import javax.swing.Icon object MarkLogic : ItemPresentation, XpmVendorType, XpmProductType { // region ItemPresentation override fun getPresentableText(): String = "MarkLogic" override fun getLocationString(): String? = null override fun getIcon(unused: Boolean): Icon = MarkLogicIcons.Product // endregion // region XpmVendorType / XpmProductType override val id: String = "marklogic" override val presentation: ItemPresentation get() = this // endregion // region XpmVendorType private val markLogicExecutable = listOf( "MarkLogic.exe", // Windows "bin/MarkLogic" // Linux / Mac OS ) private val excludeSchemaNamespaces = listOf( "http://marklogic.com/xdmp", // Registered by this plugin in order to support the XSLT 2.0 vendor extensions. "http://www.w3.org/1999/xhtml", "http://www.w3.org/1999/xlink", "http://www.w3.org/1999/XSL/Transform", "http://www.w3.org/2001/XMLSchema", "http://www.w3.org/XML/1998/namespace" ) override fun isValidInstallDir(installDir: String): Boolean { return markLogicExecutable.find { File("$installDir/$it").exists() } != null } override val modulePath: String = "/Modules" private fun isMarkLogicSchemaFile(targetNamespace: String): Boolean { return !excludeSchemaNamespaces.contains(targetNamespace) } override fun schemaFiles(path: String): Sequence<XpmSchemaFile> { val files = File("$path/Config").listFiles { _, name -> name.endsWith(".xsd") }?.asSequence() ?: sequenceOf() return files.mapNotNull { val schema = XpmSchemaFile(it) schema.takeIf { isMarkLogicSchemaFile(schema.targetNamespace) } } } // endregion // region Language Versions val VERSION_6: XpmProductVersion = MarkLogicVersion(this, 6, "property::, namespace::, binary, transactions, etc.") val VERSION_7: XpmProductVersion = MarkLogicVersion(this, 7, "schema kind tests: schema-type, etc.") val VERSION_8: XpmProductVersion = MarkLogicVersion(this, 8, "json kind tests and constructors: object-node, etc.") val VERSION_9: XpmProductVersion = MarkLogicVersion(this, 9, "arrow operator '=>'") @Suppress("unused") val languageVersions: List<XpmProductVersion> = listOf( VERSION_6, VERSION_7, VERSION_8, VERSION_9 ) // endregion }
apache-2.0
1d01439d159e42557366672af76e7097
35.375
119
0.702176
4.207229
false
false
false
false
westnordost/StreetComplete
app/src/test/java/de/westnordost/streetcomplete/data/quest/UndoableOsmQuestsSourceTest.kt
1
4149
package de.westnordost.streetcomplete.data.quest import de.westnordost.osmapi.map.data.Element import de.westnordost.osmapi.map.data.OsmLatLon import de.westnordost.streetcomplete.any import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementPointGeometry import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuest import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestController import de.westnordost.streetcomplete.mock import de.westnordost.streetcomplete.on import org.junit.Before import org.junit.Assert.* import org.junit.Test import org.mockito.Mockito.* import org.mockito.invocation.InvocationOnMock import java.util.* class UndoableOsmQuestsSourceTest { private lateinit var osmQuestController: OsmQuestController private lateinit var questStatusListener: OsmQuestController.QuestStatusListener private lateinit var listener: UndoableOsmQuestsCountListener private lateinit var source: UndoableOsmQuestsSource private val baseCount = 10 @Before fun setUp() { osmQuestController = mock() on(osmQuestController.addQuestStatusListener(any())).then { invocation: InvocationOnMock -> questStatusListener = invocation.arguments[0] as OsmQuestController.QuestStatusListener Unit } on(osmQuestController.getAllUndoableCount()).thenReturn(baseCount) source = UndoableOsmQuestsSource(osmQuestController) listener = mock() source.addListener(listener) } @Test fun count() { assertEquals(baseCount, source.count) } @Test fun `remove undoable osm quest triggers listener`() { questStatusListener.onRemoved(1L, QuestStatus.ANSWERED) questStatusListener.onRemoved(2L, QuestStatus.HIDDEN) questStatusListener.onRemoved(3L, QuestStatus.CLOSED) verifyDecreasedBy(3) } @Test fun `remove non-undoable osm quest does not trigger listener`() { questStatusListener.onRemoved(2L, QuestStatus.NEW) questStatusListener.onRemoved(3L, QuestStatus.INVISIBLE) verifyNothingHappened() } @Test fun `change osm quest to undoable triggers listener`() { questStatusListener.onChanged(osmQuest(1L, QuestStatus.ANSWERED), QuestStatus.NEW) questStatusListener.onChanged(osmQuest(2L, QuestStatus.HIDDEN), QuestStatus.NEW) questStatusListener.onChanged(osmQuest(3L, QuestStatus.CLOSED), QuestStatus.NEW) verifyIncreasedBy(3) } @Test fun `change osm quest from undoable triggers listener`() { questStatusListener.onChanged(osmQuest(1L, QuestStatus.NEW), QuestStatus.ANSWERED) questStatusListener.onChanged(osmQuest(2L, QuestStatus.NEW), QuestStatus.HIDDEN) questStatusListener.onChanged(osmQuest(3L, QuestStatus.NEW), QuestStatus.CLOSED) verifyDecreasedBy(3) } @Test fun `change osm quest from non-undoable does not trigger listener`() { questStatusListener.onChanged(osmQuest(1L, QuestStatus.INVISIBLE), QuestStatus.NEW) questStatusListener.onChanged(osmQuest(2L, QuestStatus.ANSWERED), QuestStatus.CLOSED) verifyNothingHappened() } @Test fun `update of osm quests triggers listener`() { on(osmQuestController.getAllUndoableCount()).thenReturn(20) questStatusListener.onUpdated(listOf(), listOf(), listOf()) verify(listener).onUndoableOsmQuestsCountIncreased() assertEquals(20, source.count) } private fun verifyDecreasedBy(by: Int) { verify(listener, times(by)).onUndoableOsmQuestsCountDecreased() assertEquals(baseCount - by, source.count) } private fun verifyIncreasedBy(by: Int) { verify(listener, times(by)).onUndoableOsmQuestsCountIncreased() assertEquals(baseCount + by, source.count) } private fun verifyNothingHappened() { verifyZeroInteractions(listener) assertEquals(baseCount, source.count) } private fun osmQuest(id: Long, status: QuestStatus): OsmQuest { return OsmQuest(id, mock(), Element.Type.NODE, 1L, status, null, null, Date(), ElementPointGeometry(OsmLatLon(0.0,0.0))) } }
gpl-3.0
a01ae8d322c13ce85e7b097b2f5f6bcf
37.416667
128
0.736804
4.46129
false
true
false
false
InsertKoinIO/koin
core/koin-core/src/commonTest/kotlin/org/koin/dsl/ModuleDeclarationRulesTest.kt
1
2351
package org.koin.dsl import kotlin.test.assertEquals import kotlin.test.fail import kotlin.test.Test import org.koin.Simple import org.koin.core.error.DefinitionOverrideException import org.koin.core.logger.Level import org.koin.core.qualifier.named import org.koin.test.assertDefinitionsCount class ModuleDeclarationRulesTest { @Test fun `don't allow redeclaration`() { try { koinApplication { modules(module { single { Simple.ComponentA() } single { Simple.ComponentA() } }) } fail("should not redeclare") } catch (e: DefinitionOverrideException) { e.printStackTrace() } } @Test fun `allow redeclaration - different names`() { val app = koinApplication { printLogger(Level.INFO) modules(module { single(named("default")) { Simple.ComponentA() } single(named("other")) { Simple.ComponentA() } }) } app.assertDefinitionsCount(2) } @Test fun `allow qualifier redeclaration - same names`() { val koin = koinApplication { modules(module { single(named("default")) { Simple.ComponentA() } single(named("default")) { Simple.ComponentB(get(named("default"))) } }) }.koin val a = koin.get<Simple.ComponentA>(named("default")) val b = koin.get<Simple.ComponentB>(named("default")) assertEquals(a, b.a) } @Test fun `allow redeclaration - default`() { val app = koinApplication { modules(module { single { Simple.ComponentA() } single(named("other")) { Simple.ComponentA() } }) } app.assertDefinitionsCount(2) } @Test fun `don't allow redeclaration with different implementation`() { try { koinApplication { modules( module { single<Simple.ComponentInterface1> { Simple.Component1() } single<Simple.ComponentInterface1> { Simple.Component2() } }) } } catch (e: DefinitionOverrideException) { e.printStackTrace() } } }
apache-2.0
eca56abf06d558c486f108ed45eae4bd
28.4
85
0.542748
4.827515
false
true
false
false
GLodi/GitNav
app/src/main/java/giuliolodi/gitnav/ui/adapters/IssueCommentAdapter.kt
1
4114
/* * Copyright 2017 GLodi * * 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 giuliolodi.gitnav.ui.adapters import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.squareup.picasso.Picasso import giuliolodi.gitnav.R import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import kotlinx.android.synthetic.main.row_comment.view.* import org.eclipse.egit.github.core.Comment import org.ocpsoft.prettytime.PrettyTime import org.sufficientlysecure.htmltextview.HtmlHttpImageGetter /** * Created by giulio on 17/11/2017. */ class IssueCommentAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var mIssueCommentList: MutableList<Comment?> = mutableListOf() private val mPrettyTime: PrettyTime = PrettyTime() private val onImageClick: PublishSubject<String> = PublishSubject.create() fun getImageClicks(): Observable<String> { return onImageClick } class IssueCommentHolder(root: View) : RecyclerView.ViewHolder(root) { fun bind (comment: Comment, p: PrettyTime) = with(itemView) { row_comment_username.text = comment.user.login row_comment_date.text = p.format(comment.createdAt) Picasso.with(context).load(comment.user.avatarUrl).resize(75, 75).centerCrop().into(row_comment_image) row_comment_comment.setHtml(comment.bodyHtml, HtmlHttpImageGetter(row_comment_comment)) } } class LoadingHolder(root: View) : RecyclerView.ViewHolder(root) override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder { val root: RecyclerView.ViewHolder if (viewType == 1) { val view = (LayoutInflater.from(parent?.context).inflate(R.layout.row_comment, parent, false)) root = IssueCommentHolder(view) } else { val view = (LayoutInflater.from(parent?.context).inflate(R.layout.row_loading, parent, false)) root = LoadingHolder(view) } return root } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (holder is IssueCommentHolder) { val comment = mIssueCommentList[position]!! holder.bind(comment, mPrettyTime) holder.itemView.row_comment_ll.setOnClickListener { comment.user?.login?.let { onImageClick.onNext(it) } } } } override fun getItemViewType(position: Int): Int { return if (mIssueCommentList[position] != null) 1 else 0 } override fun getItemCount(): Int { return mIssueCommentList.size } override fun getItemId(position: Int): Long { return position.toLong() } fun addIssueCommentList(issueCommentList: List<Comment>) { if (mIssueCommentList.isEmpty()) { mIssueCommentList.addAll(issueCommentList) notifyDataSetChanged() } else if (!issueCommentList.isEmpty()) { val lastItemIndex = if (mIssueCommentList.size > 0) mIssueCommentList.size else 0 mIssueCommentList.addAll(issueCommentList) notifyItemRangeInserted(lastItemIndex, mIssueCommentList.size) } } fun addIssueComment(issueComment: Comment) { mIssueCommentList.add(issueComment) notifyItemInserted(mIssueCommentList.size - 1) } fun addLoading() { mIssueCommentList.add(null) notifyItemInserted(mIssueCommentList.size - 1) } fun clear() { mIssueCommentList.clear() notifyDataSetChanged() } }
apache-2.0
3549d9da24984efe172a8e22f213a42a
36.752294
118
0.702236
4.395299
false
false
false
false
Tait4198/hi_pixiv
app/src/main/java/info/hzvtc/hipixiv/util/LoadingDrawable.kt
1
2614
package info.hzvtc.hipixiv.util import android.graphics.Canvas import android.graphics.ColorFilter import android.graphics.Paint import android.graphics.RectF import android.graphics.drawable.Drawable import com.facebook.drawee.drawable.DrawableUtils class LoadingDrawable : Drawable() { private lateinit var mRingBackgroundPaint: Paint private lateinit var mRingPaint: Paint private var mRingBackgroundColor: Int = 0 private var mRingColor: Int = 0 private var mRingRadius: Float = 0F private var mStrokeWidth: Float = 0F private val mTotalProgress = 10000 private var mProgress: Int = 0 init { val mRadius = 56f mStrokeWidth = 8f mRingBackgroundColor = 0x00000000 mRingColor = 0xFF039BE5.toInt() mRingRadius = mRadius + mStrokeWidth / 2 initVariable() } private fun initVariable() { mRingBackgroundPaint = Paint() mRingBackgroundPaint.isAntiAlias = true mRingBackgroundPaint.color = mRingBackgroundColor mRingBackgroundPaint.style = Paint.Style.STROKE mRingBackgroundPaint.strokeWidth = mStrokeWidth mRingPaint = Paint() mRingPaint.isAntiAlias = true mRingPaint.color = mRingColor mRingPaint.style = Paint.Style.STROKE mRingPaint.strokeWidth = mStrokeWidth } private fun drawBar(canvas: Canvas, level: Int, paint: Paint) { if (level > 0) { val bound = bounds val mXCenter = bound.centerX() val mYCenter = bound.centerY() val oval = RectF() oval.left = mXCenter - mRingRadius oval.top = mYCenter - mRingRadius oval.right = mRingRadius * 2 + (mXCenter - mRingRadius) oval.bottom = mRingRadius * 2 + (mYCenter - mRingRadius) canvas.drawArc(oval, -90f, level.toFloat() / mTotalProgress * 360, false, paint) } } override fun onLevelChange(level: Int): Boolean { mProgress = level if (level in 1..9999) { invalidateSelf() return true } else { return false } } override fun draw(canvas: Canvas) { drawBar(canvas, mTotalProgress, mRingBackgroundPaint) drawBar(canvas, mProgress, mRingPaint) } override fun setAlpha(alpha: Int) { mRingPaint.alpha = alpha } override fun getOpacity(): Int { return DrawableUtils.getOpacityFromColor(this.mRingPaint.color) } override fun setColorFilter(colorFilter: ColorFilter?) { mRingPaint.colorFilter = colorFilter } }
mit
d1d5fa699f9c8f15abba3d94dc5febba
30.130952
92
0.649579
4.400673
false
false
false
false
kentaromiura/SakubiReader
app/src/main/java/com/blogspot/mykenta/sakubireader/MainActivity.kt
1
13449
package com.blogspot.mykenta.sakubireader import android.app.ProgressDialog import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Handler import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import android.support.v4.app.FragmentStatePagerAdapter import android.support.v4.view.PagerAdapter import android.support.v4.view.ViewPager import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.* import android.webkit.WebView import android.webkit.WebViewClient import org.jsoup.Jsoup import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.nio.charset.Charset import android.os.AsyncTask var HCBugFixed: Boolean = false; fun getCopyWithoutChildrenSections(element: Element) : Element { val copy = element.clone() copy.children().forEach { if (it.tagName() == "section") it.remove() } return copy } var colouring = true class MainActivity : AppCompatActivity() { /** * The [android.support.v4.view.PagerAdapter] that will provide * fragments for each of the sections. We use a * [FragmentPagerAdapter] derivative, which will keep every * loaded fragment in memory. If this becomes too memory intensive, it * may be best to switch to a * [android.support.v4.app.FragmentStatePagerAdapter]. */ private var mSectionsPagerAdapter: SectionsPagerAdapter? = null private var bundleOfIDS: Bundle? = null /** * The [ViewPager] that will host the section contents. */ private var mViewPager: ViewPager? = null fun getStyle(): String { var style_file = "style.css" if ( Build.VERSION.SDK_INT === 13 ) { style_file = "style.hc.css" } val input_stream = this.assets.open(style_file) val size = input_stream.available() val buffer = ByteArray(size) input_stream.read(buffer) input_stream.close() return String(buffer, Charset.forName("UTF-8")) } fun getSakubiHTML(): String { val input_stream = this.assets.open("sakubi.html") val size = input_stream.available() val buffer = ByteArray(size) input_stream.read(buffer) input_stream.close() return String(buffer, Charset.forName("UTF-8")) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val document = Jsoup.parse(getSakubiHTML()) val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) // Create the adapter that will return a fragment for each of the three // primary sections of the activity. bundleOfIDS = getIDSBundle(document) mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager, document, getStyle(), bundleOfIDS!!) // Set up the ViewPager with the sections adapter. mViewPager = findViewById(R.id.container) as ViewPager mViewPager!!.adapter = mSectionsPagerAdapter val context = this // HC has an issue with first 2 pages not showing up, this hack makes them load... if (Build.VERSION.SDK_INT === 13) { class FixHCBug() : AsyncTask<Void, Void, String>() { private var ad: ProgressDialog? = null override fun doInBackground(vararg params: Void?): String? { Thread.sleep(1000) return null } override fun onPreExecute() { super.onPreExecute() ad = ProgressDialog(context) ad!!.setCancelable(false) ad!!.setMessage("Fixing honeycomb bugs") ad!!.setProgressStyle(ProgressDialog.STYLE_SPINNER) ad!!.show() } override fun onPostExecute(result: String?) { super.onPostExecute(result) Handler().postDelayed(Runnable { Handler().postDelayed(Runnable { (mViewPager as ViewPager).setCurrentItem(4) Handler().postDelayed(Runnable { (mViewPager as ViewPager).setCurrentItem(3) Handler().postDelayed(Runnable { (mViewPager as ViewPager).setCurrentItem(2) Handler().postDelayed(Runnable { (mViewPager as ViewPager).setCurrentItem(1) Handler().postDelayed(Runnable { (mViewPager as ViewPager).setCurrentItem(0, true) ad!!.dismiss() }, 500) }, 500) }, 500) }, 500) }, 500) }, 1) } } if(!HCBugFixed) { FixHCBug().execute() HCBugFixed = true } } } fun getIDSBundle(document: Document): Bundle { val result = Bundle() val sections = document.getElementsByTag("section") sections.forEachIndexed { index, element -> val clone = getCopyWithoutChildrenSections(element) val ids = clone.getElementsByAttribute("id") ids.forEach { result.putInt(it.attr("id"), index + 1) } } return result } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. val id = item.itemId if (id == R.id.action_toc) { (mViewPager as ViewPager).currentItem = bundleOfIDS!!.getInt("toc") return true } if (id == R.id.action_toggle_coloring) { colouring = !colouring mSectionsPagerAdapter!!.notifyDataSetChanged() } if (id == R.id.action_repo) { val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/kentaromiura/SakubiReader")) startActivity(browserIntent) } return super.onOptionsItemSelected(item) } /** * A placeholder fragment containing a simple view. */ class PlaceholderFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater!!.inflate(R.layout.fragment_main, container, false) val webview = rootView.findViewById(R.id.webview) as WebView webview.getSettings().setBuiltInZoomControls(true); webview.loadUrl("about:blank") val style = arguments.getString(ARG_STYLE) webview.loadDataWithBaseURL("file:///android_asset/", "<style type=\"text/css\">$style</style>" + arguments.getString(ARG_TEXT) + "<br /><br /><br />", "text/html", "utf-8", null) webview.setWebViewClient(object: WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean { if (url != null && url.startsWith("findid://")) { val urlData = url.substring("findid://".length) val page = arguments.getBundle(ARG_IDS).getInt(urlData) (container as ViewPager).currentItem = page return true } else { if (url != null) { val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(browserIntent) return true; } } return super.shouldOverrideUrlLoading(view, url as String?) } }) return rootView } companion object { /** * The fragment argument representing the section number for this * fragment. */ private val ARG_SECTION_NUMBER = "section_number" private val ARG_TEXT = "text" private val ARG_STYLE = "style" private val ARG_IDS = "ids" fun getSection(element: Element): String { if (colouring) { val tmp = Document("") tmp.appendChild(element) tmp.outputSettings(Document.OutputSettings().prettyPrint(false)) return element.html() .replace(Regex("[^ァ-ン\u3400-\u4DB5\u4E00-\u9FCB\uF900-\uFA6A><!a-zA-Z:0-9\"',.()!\\-\\s]+"), { when(it.value) { "に" -> "<b class=ni>に</b>" "へ" -> "<b class=he>へ</b>" "から" -> "<b class=kare>から</b>" "でした" -> "<b class=copula>でした</b>" "だった" -> "<b class=copula>だった</b>" "だ" -> "<b class=copula>だ</b>" "です" -> "<b class=copula>です</b>" "の" -> "<b class=possession>の</b>" "て" -> "<b class=te>て</b>" "が" -> "<b class=ga>が</b>" "は" -> "<b class=wa>は</b>" "を" -> "<b class=o>を</b>" "か" -> "<b class=ka>か</b>" "と" -> "<b class=yo>と</b>" "も" -> "<b class=mo>も</b>" else -> it.value } }) .replace(Regex("[ァ-ン]+"), { "<b class=katakana>${it.value}</b>" }) .replace(Regex("[\u3400-\u4DB5\u4E00-\u9FCB\uF900-\uFA6A]+"), { "<b class=kanji>${it.value}</b>" }) .replace("href=\"#", "href=\"findid://") } else { return element.html() .replace("href=\"#", "href=\"findid://") } } /** * Returns a new instance of this fragment for the given section * number. */ fun newInstance(sectionNumber: Int, document: Document, style: String, bundleOfIDS: Bundle): PlaceholderFragment { val fragment = PlaceholderFragment() val args = Bundle() args.putInt(ARG_SECTION_NUMBER, sectionNumber) args.putString(ARG_STYLE, style) if (sectionNumber == 1) { val children = document.body().children() args.putString(ARG_TEXT, "<h1>${children[0].html()}</h1><p>${children[1].html()}</p><p>${children[2].html()}</p>" ) } else { val copy = getCopyWithoutChildrenSections(document.getElementsByTag("section")[sectionNumber - 2]) args.putString(ARG_TEXT, getSection(copy)) } args.putBundle(ARG_IDS, bundleOfIDS) fragment.arguments = args return fragment } } } /** * A [FragmentPagerAdapter] that returns a fragment corresponding to * one of the sections/tabs/pages. */ inner class SectionsPagerAdapter(fm: FragmentManager, val document: Document, val style: String, val bundleOfIDS: Bundle) : FragmentStatePagerAdapter(fm) { override fun getItemPosition(`object`: Any?): Int { // needed to refresh view when toggle colours is used. return PagerAdapter.POSITION_NONE } override fun getItem(position: Int): Fragment { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). return PlaceholderFragment.newInstance(position + 1, document, style, bundleOfIDS) } override fun getCount(): Int { // Show 3 total pages. val sections = document.getElementsByTag("section") return sections.size + 1 // sections + initial view } override fun getPageTitle(position: Int): CharSequence? { return "SECTION $position" } } }
mit
0c964681bf79e0835635f06f7101f7f3
38.98503
191
0.524598
4.985069
false
false
false
false
Mogikan/mobileLabs
lab2/app/src/main/java/com/astu/vk/labs/HomeActivity.kt
1
1225
package com.astu.vk.labs import android.app.Activity import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.TextView class HomeActivity : AppCompatActivity() { companion object { const val requestId = 1001 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) val textView = findViewById<EditText>(R.id.textToPass) findViewById<Button>(R.id.open2ndActivity).setOnClickListener{ val intent = Intent(this, SecondActivity::class.java) intent.putExtra("textParameter",textView.text.toString()) startActivityForResult(intent,requestId) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode== Activity.RESULT_OK) { if (requestCode == requestId) { findViewById<TextView>(R.id.resultFromeSecond).setText(data?.extras?.getString("secondExtra")) } } } }
gpl-3.0
9f96ce1f989aacfb177437e0576d4989
29.625
107
0.693878
4.570896
false
false
false
false
duncte123/SkyBot
src/main/kotlin/ml/duncte123/skybot/commands/fun/ImageCommand.kt
1
2350
/* * Skybot, a multipurpose discord bot * Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32" * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ml.duncte123.skybot.commands.`fun` import me.duncte123.botcommons.messaging.EmbedUtils import me.duncte123.botcommons.messaging.MessageUtils.sendEmbed import me.duncte123.botcommons.web.WebUtils import ml.duncte123.skybot.objects.command.Command import ml.duncte123.skybot.objects.command.CommandCategory import ml.duncte123.skybot.objects.command.CommandContext import ml.duncte123.skybot.utils.CommandUtils.isUserOrGuildPatron class ImageCommand : Command() { init { this.category = CommandCategory.PATRON this.name = "image" this.help = "Searches for an image on google" this.usage = "<search term>" } override fun execute(ctx: CommandContext) { if (isUserOrGuildPatron(ctx)) { if (ctx.args.isEmpty()) { this.sendUsageInstructions(ctx) return } val keyword = ctx.argsRaw WebUtils.ins.getJSONObject(String.format(ctx.googleBaseUrl, keyword)).async { val jsonArray = it["items"] val randomItem = jsonArray[ctx.random.nextInt(jsonArray.size())] sendEmbed( ctx, EmbedUtils.getDefaultEmbed() .setTitle( randomItem["title"].asText(), randomItem["image"]["contextLink"].asText() ) .setImage(randomItem["link"].asText()) ) } } } }
agpl-3.0
35cbb15a8f35ea6d1c544a5b9e498cfa
36.903226
104
0.639574
4.519231
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/data/Position3D.kt
1
5751
package org.hexworks.zircon.api.data import kotlin.jvm.JvmStatic /** * Represents a coordinate in 3D space. Extends [Position] with * a `z` dimension. Use [Position3D.from2DPosition] and [Position3D.to2DPosition] * to convert between the two. The `z` dimension represents the up and down axis. * * Explanation: * <pre> * ^ (z axis, positive direction) * \ * \ * \ * \ * O---------> (x axis, positive direction) * / * / * / * L (y axis, positive direction) * *</pre> */ @Suppress("DataClassPrivateConstructor") data class Position3D private constructor( val x: Int, val y: Int, val z: Int ) : Comparable<Position3D> { val isUnknown: Boolean get() = this == UNKNOWN /** * Tells whether this [Position3D] has a negative component (x, y or z) or not. */ val hasNegativeComponent: Boolean get() = x < 0 || y < 0 || z < 0 override fun compareTo(other: Position3D): Int { return when { other.z > z -> -1 other.z < z -> 1 else -> { when { other.y > y -> -1 other.y < y -> 1 else -> { when { other.x > x -> -1 other.x < x -> 1 else -> { 0 } } } } } } } /** * Returns a new [Position3D] which is the sum of `x`, `y` and `z` in both [Position3D]s. * so `Position3D(x = 1, y = 1, z = 1).plus(Position3D(x = 2, y = 2, z = 2))` will be * `Position3D(x = 3, y = 3, z = 3)`. */ operator fun plus(other: Position3D) = Position3D( x = this.x + other.x, y = this.y + other.y, z = this.z + other.z ) /** * Returns a new [Position3D] which is the difference of `x`, `y` and `z` in both [Position3D]s. * so `Position3D(x = 3, y = 3, z = 3).minus(Position3D(x = 2, y = 2, z = 2))` will be * `Position3D(x = 1, y = 1, z = 1)`. */ operator fun minus(other: Position3D) = Position3D( x = this.x - other.x, y = this.y - other.y, z = this.z - other.z ) /** * Creates a new [Position3D] object representing a 3D position with the same `y` and `y` as this but with * the supplied `x`. */ fun withX(x: Int) = if (this.x == x) this else copy(x = x) /** * Creates a new [Position3D] object representing a 3D position with the same `x` and `y` as this but with * the supplied `y`. */ fun withY(y: Int) = if (this.y == y) this else copy(y = y) /** * Creates a new [Position3D] object representing a 3D position with the same `x` and `y` as this but with * the supplied `y`. */ fun withZ(z: Int) = if (this.z == z) this else copy(z = z) /** * Creates a new [Position3D] object representing a position on the same `y` and `y`, * but with an `x` offset by the supplied `deltaX`. * Calling this method with `deltaX` 0 will returnThis `this`. * A positive `deltaX` will be added, a negative will be subtracted from the original `x`. */ fun withRelativeX(deltaX: Int) = if (deltaX == 0) this else withX(x + deltaX) /** * Creates a new [Position3D] object representing a position on the same `x` and `y`, * but with an `y` offset by the supplied `deltaY`. * Calling this method with `deltaY` 0 will returnThis `this`. * A positive `deltaY` will be added, a negative will be subtracted from the original `x`. */ fun withRelativeY(deltaY: Int) = if (deltaY == 0) this else withY(y + deltaY) /** * Creates a new [Position3D] object representing a position on the same `x` and `y`, * but with a `y` offset by the supplied `deltaZ`. * Calling this method with `deltaZ` 0 will returnThis `this`. * A positive `deltaZ` will be added, a negative will be subtracted from the original `x`. */ fun withRelativeZ(deltaZ: Int) = if (deltaZ == 0) this else withZ(z + deltaZ) /** * Creates a new [Position3D] object that is translated by an amount of x, y and z specified by another * [Position3D]. */ fun withRelative(translate: Position3D) = withRelativeY(translate.y) .withRelativeX(translate.x) .withRelativeZ(translate.z) /** * Transforms this [Position3D] to a [Size3D] so if * this position is Position(x=2, y=3, z=1) it will become * Size3D(x=2, y=3, z=1). */ fun toSize(): Size3D = Size3D.create(x, y, z) /** * Transforms this [Position3D] to a [Position]. Note that * the `y` component is lost during the conversion! */ fun to2DPosition() = Position.create(x, y) companion object { /** * Factory method for [Position3D]. */ @JvmStatic fun create(x: Int, y: Int, z: Int) = Position3D(x = x, y = y, z = z) /** * Position3d(0, 0, 0) */ @JvmStatic fun defaultPosition() = DEFAULT_POSITION @JvmStatic fun unknown() = UNKNOWN /** * Creates a new [Position3D] from a [Position]. * If `y` is not supplied it defaults to `0` (ground level). */ @JvmStatic fun from2DPosition(position: Position, z: Int = 0) = Position3D( x = position.x, y = position.y, z = z ) private val DEFAULT_POSITION = create(0, 0, 0) private val UNKNOWN = create(Int.MAX_VALUE, Int.MAX_VALUE, Int.MAX_VALUE) } }
apache-2.0
49d6017d6d957c1376b0b1fbdf0b2d20
30.95
110
0.533994
3.539077
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/viewmodel/pages/PageParentViewModel.kt
1
8152
package org.wordpress.android.viewmodel.pages import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.withContext import org.wordpress.android.R import org.wordpress.android.analytics.AnalyticsTracker.Stat.PAGES_SET_PARENT_CHANGES_SAVED import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.page.PageModel import org.wordpress.android.fluxc.model.page.PageStatus.PUBLISHED import org.wordpress.android.fluxc.store.PageStore import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.modules.UI_THREAD import org.wordpress.android.ui.pages.PageItem import org.wordpress.android.ui.pages.PageItem.Divider import org.wordpress.android.ui.pages.PageItem.Empty import org.wordpress.android.ui.pages.PageItem.ParentPage import org.wordpress.android.ui.pages.PageItem.Type.PARENT import org.wordpress.android.ui.pages.PageItem.Type.TOP_LEVEL_PARENT import org.wordpress.android.util.analytics.AnalyticsUtils import org.wordpress.android.viewmodel.ResourceProvider import org.wordpress.android.viewmodel.ScopedViewModel import org.wordpress.android.viewmodel.SingleLiveEvent import javax.inject.Inject import javax.inject.Named private const val SEARCH_DELAY = 200L private const val SEARCH_COLLAPSE_DELAY = 500L class PageParentViewModel @Inject constructor( private val pageStore: PageStore, private val resourceProvider: ResourceProvider, @Named(UI_THREAD) private val uiDispatcher: CoroutineDispatcher, @Named(BG_THREAD) private val defaultDispatcher: CoroutineDispatcher ) : ScopedViewModel(uiDispatcher) { private val _pages: MutableLiveData<List<PageItem>> = MutableLiveData() val pages: LiveData<List<PageItem>> = _pages private lateinit var _currentParent: ParentPage val currentParent: ParentPage get() = _currentParent private lateinit var _initialParent: ParentPage val initialParent: ParentPage get() = _initialParent private val _isSaveButtonVisible = MutableLiveData<Boolean>() val isSaveButtonVisible: LiveData<Boolean> = _isSaveButtonVisible private val _saveParent = SingleLiveEvent<Unit>() val saveParent: LiveData<Unit> = _saveParent private val _searchPages: MutableLiveData<List<PageItem>?> = MutableLiveData() val searchPages: LiveData<List<PageItem>?> = _searchPages private var _lastSearchQuery = "" val lastSearchQuery: String get() = _lastSearchQuery private var searchJob: Job? = null private val _isSearchExpanded = MutableLiveData<Boolean>() val isSearchExpanded: LiveData<Boolean> = _isSearchExpanded private lateinit var site: SiteModel private var isStarted: Boolean = false private var page: PageModel? = null fun start(site: SiteModel, pageId: Long) { this.site = site if (!isStarted) { _pages.postValue(listOf(Empty(R.string.empty_list_default))) isStarted = true loadPages(pageId) _isSaveButtonVisible.postValue(false) } } private fun loadPages(pageId: Long) = launch(defaultDispatcher) { page = when { pageId < 0 -> { // negative local page ID used as a temp remote post ID for local-only pages (assigned by the PageStore) pageStore.getPageByLocalId(-pageId.toInt(), site) } pageId > 0 -> pageStore.getPageByRemoteId(pageId, site) else -> { // when page ID is 0 it means the page was just created and was never even uploaded / saved locally yet null } } val parents = mutableListOf<PageItem>( ParentPage( 0, resourceProvider.getString(R.string.top_level), page?.parent == null, TOP_LEVEL_PARENT ) ) val choices = pageStore.getPagesFromDb(site) .filter { // negative local page ID used as a temp remote post ID for local-only pages and can't be assigned // as parent to other pages properly, better to filter them out it.remoteId > 0 && it.remoteId != pageId && it.status == PUBLISHED } val parentChoices = choices.filter { isNotChild(it, choices) } if (parentChoices.isNotEmpty()) { parents.add(Divider(resourceProvider.getString(R.string.pages))) parents.addAll(parentChoices.map { ParentPage(it.remoteId, it.title, page?.parent?.remoteId == it.remoteId, PARENT) }) } _currentParent = parents.firstOrNull { it is ParentPage && it.isSelected } as? ParentPage ?: parents.first() as ParentPage _initialParent = _currentParent _pages.postValue(parents) } fun onParentSelected(page: ParentPage) { _currentParent.isSelected = false _currentParent = page _currentParent.isSelected = true setSaveButton() } fun onSaveButtonTapped() { page?.let { trackSaveEvent(it) } // don't track event for null pages (just created but not yet saved / uploaded) _saveParent.asyncCall() } private fun trackSaveEvent(page: PageModel) { val properties = mutableMapOf( "page_id" to page.remoteId as Any, "new_parent_id" to currentParent.id ) AnalyticsUtils.trackWithSiteDetails(PAGES_SET_PARENT_CHANGES_SAVED, site, properties) } private fun isNotChild(choice: PageModel, choices: List<PageModel>): Boolean { return page?.let { !getChildren(it, choices).contains(choice) } ?: true } private fun getChildren(page: PageModel, pages: List<PageModel>): List<PageModel> { val children = pages.filter { it.parent?.remoteId == page.remoteId } val grandchildren = mutableListOf<PageModel>() children.forEach { grandchildren += getChildren(it, pages) } return children + grandchildren } fun onSearchExpanded(restorePreviousSearch: Boolean) { if (isSearchExpanded.value != true) { if (!restorePreviousSearch) { clearSearch() } _isSearchExpanded.value = true _isSaveButtonVisible.postValue(false) } } fun onSearchCollapsed() { _isSearchExpanded.value = false clearSearch() setSaveButton() launch { delay(SEARCH_COLLAPSE_DELAY) } } private fun clearSearch() { _lastSearchQuery = "" _searchPages.postValue(null) } fun onSearch(searchQuery: String, delay: Long = SEARCH_DELAY) { searchJob?.cancel() if (searchQuery.isNotEmpty()) { searchJob = launch { delay(delay) searchJob = null if (isActive) { _lastSearchQuery = searchQuery val result = search(searchQuery) _searchPages.postValue(result) } } } else { _isSaveButtonVisible.postValue(false) clearSearch() } } private suspend fun search( searchQuery: String ): List<PageItem> = withContext(defaultDispatcher) { _pages.value?.let { if (it.isNotEmpty()) return@withContext it .filterIsInstance(ParentPage::class.java) .filter { parentPage -> parentPage.id != 0L } .filter { parentPage -> parentPage.title.contains(searchQuery, true) } } return@withContext mutableListOf<PageItem>() } private fun setSaveButton() { if (_currentParent == _initialParent) { _isSaveButtonVisible.postValue(false) } else { _isSaveButtonVisible.postValue(true) } } }
gpl-2.0
4118c5f9b1ab6d70f839054930875c5b
34.754386
120
0.643523
4.660949
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/arrays/Norm1Array.kt
1
1482
/* Copyright 2016-present The KotlinNLP Authors. 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 com.kotlinnlp.simplednn.core.arrays import com.kotlinnlp.simplednn.simplemath.equals import com.kotlinnlp.simplednn.simplemath.ndarray.* /** * The [Norm1Array] is a wrapper of an [NDArray] in which values represent a vector with norm equals to 1. * * @property values the values as [NDArray] */ open class Norm1Array<NDArrayType : NDArray<NDArrayType>>(val values: NDArrayType) { init { require(equals(this.values.sum(), 1.0, tolerance = 1.0e-08)) { "Values sum must be equal to 1.0" } require(this.values.columns == 1) { "Values must be a column vector" } } /** * The length of this array. */ val length: Int = this.values.length /** * Assign values to the array. * * @param values values to assign to this [Norm1Array] */ open fun assignValues(values: NDArray<*>) { require(equals(values.sum(), 1.0, tolerance = 1.0e-08)) { "Values sum must be equal to 1.0" } this.values.assignValues(values) } /** * Clone this array. * * @return a clone of this [Norm1Array] */ open fun clone(): Norm1Array<NDArrayType> = Norm1Array(values = this.values.copy()) }
mpl-2.0
74d24ed1e5d8d596b02f8cba0cdc21b3
30.531915
106
0.650472
3.632353
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/ui/jetpack/backup/download/usecases/PostBackupDownloadUseCaseTest.kt
1
6091
package org.wordpress.android.ui.jetpack.backup.download.usecases import kotlinx.coroutines.InternalCoroutinesApi import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.kotlin.any import org.mockito.kotlin.whenever import org.wordpress.android.BaseUnitTest import org.wordpress.android.TEST_DISPATCHER import org.wordpress.android.fluxc.action.ActivityLogAction.BACKUP_DOWNLOAD import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.store.ActivityLogStore import org.wordpress.android.fluxc.store.ActivityLogStore.BackupDownloadError import org.wordpress.android.fluxc.store.ActivityLogStore.BackupDownloadErrorType.API_ERROR import org.wordpress.android.fluxc.store.ActivityLogStore.BackupDownloadErrorType.GENERIC_ERROR import org.wordpress.android.fluxc.store.ActivityLogStore.BackupDownloadErrorType.INVALID_RESPONSE import org.wordpress.android.fluxc.store.ActivityLogStore.BackupDownloadRequestTypes import org.wordpress.android.fluxc.store.ActivityLogStore.OnBackupDownload import org.wordpress.android.test import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadRequestState.Failure.NetworkUnavailable import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadRequestState.Failure.OtherRequestRunning import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadRequestState.Failure.RemoteRequestFailure import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadRequestState.Success import org.wordpress.android.util.NetworkUtilsWrapper @InternalCoroutinesApi class PostBackupDownloadUseCaseTest : BaseUnitTest() { private lateinit var useCase: PostBackupDownloadUseCase @Mock lateinit var networkUtilsWrapper: NetworkUtilsWrapper @Mock lateinit var activityLogStore: ActivityLogStore @Mock lateinit var siteModel: SiteModel @Before fun setup() = test { useCase = PostBackupDownloadUseCase(networkUtilsWrapper, activityLogStore, TEST_DISPATCHER) whenever(networkUtilsWrapper.isNetworkAvailable()).thenReturn(true) } @Test fun `given no network, when download is triggered, then NetworkUnavailable is returned`() = test { whenever(networkUtilsWrapper.isNetworkAvailable()).thenReturn(false) val result = useCase.postBackupDownloadRequest(rewindId, siteModel, types) assertThat(result).isEqualTo(NetworkUnavailable) } @Test fun `given invalid response, when download is triggered, then RemoteRequestFailure is returned`() = test { whenever(activityLogStore.backupDownload(any())).thenReturn( OnBackupDownload( rewindId, BackupDownloadError( INVALID_RESPONSE ), BACKUP_DOWNLOAD ) ) val result = useCase.postBackupDownloadRequest(rewindId, siteModel, types) assertThat(result).isEqualTo(RemoteRequestFailure) } @Test fun `given generic error response, when download is triggered, then RemoteRequestFailure is returned`() = test { whenever(activityLogStore.backupDownload(any())).thenReturn( OnBackupDownload( rewindId, BackupDownloadError( GENERIC_ERROR ), BACKUP_DOWNLOAD ) ) val result = useCase.postBackupDownloadRequest(rewindId, siteModel, types) assertThat(result).isEqualTo(RemoteRequestFailure) } @Test fun `given api error response, when download is triggered, then RemoteRequestFailure is returned`() = test { whenever(activityLogStore.backupDownload(any())).thenReturn( OnBackupDownload( rewindId, BackupDownloadError( API_ERROR ), BACKUP_DOWNLOAD ) ) val result = useCase.postBackupDownloadRequest(rewindId, siteModel, types) assertThat(result).isEqualTo(RemoteRequestFailure) } @Test fun `when download is triggered successfully, then Success is returned`() = test { whenever(activityLogStore.backupDownload(any())).thenReturn( OnBackupDownload( rewindId = rewindId, downloadId = downloadId, causeOfChange = BACKUP_DOWNLOAD ) ) val result = useCase.postBackupDownloadRequest(rewindId, siteModel, types) assertThat(result).isEqualTo(Success(requestRewindId = rewindId, rewindId = rewindId, downloadId = downloadId)) } @Test fun `given download success, when downloadId is null, then RemoteRequestFailure is returned`() = test { whenever(activityLogStore.backupDownload(any())).thenReturn( OnBackupDownload( rewindId = rewindId, downloadId = null, causeOfChange = BACKUP_DOWNLOAD ) ) val result = useCase.postBackupDownloadRequest(rewindId, siteModel, types) assertThat(result).isEqualTo(RemoteRequestFailure) } @Test fun `given download success, when unmatched rewindIds, then OtherRequestRunning is returned`() = test { whenever(activityLogStore.backupDownload(any())).thenReturn( OnBackupDownload( rewindId = "unmatchedRewindId", downloadId = downloadId, causeOfChange = BACKUP_DOWNLOAD ) ) val result = useCase.postBackupDownloadRequest(rewindId, siteModel, types) assertThat(result).isEqualTo(OtherRequestRunning) } private val rewindId = "rewindId" private val downloadId = 100L private val types: BackupDownloadRequestTypes = BackupDownloadRequestTypes( themes = true, plugins = true, uploads = true, sqls = true, roots = true, contents = true ) }
gpl-2.0
f9f1e0cbea74940b024b7643d63eda59
39.337748
119
0.69102
5.532243
false
true
false
false
mbrlabs/Mundus
editor/src/main/com/mbrlabs/mundus/editor/ui/modules/inspector/Inspector.kt
1
3676
/* * Copyright (c) 2016. See AUTHORS file. * * 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.mbrlabs.mundus.editor.ui.modules.inspector import com.badlogic.gdx.scenes.scene2d.Actor import com.badlogic.gdx.scenes.scene2d.InputEvent import com.badlogic.gdx.scenes.scene2d.InputListener import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane import com.badlogic.gdx.utils.Align import com.kotcrab.vis.ui.widget.VisLabel import com.kotcrab.vis.ui.widget.VisScrollPane import com.kotcrab.vis.ui.widget.VisTable import com.mbrlabs.mundus.editor.Mundus import com.mbrlabs.mundus.editor.events.AssetSelectedEvent import com.mbrlabs.mundus.editor.events.GameObjectModifiedEvent import com.mbrlabs.mundus.editor.events.GameObjectSelectedEvent import com.mbrlabs.mundus.editor.ui.UI import com.mbrlabs.mundus.editor.utils.Log /** * @author Marcus Brummer * @version 19-01-2016 */ class Inspector : VisTable(), GameObjectSelectedEvent.GameObjectSelectedListener, GameObjectModifiedEvent.GameObjectModifiedListener, AssetSelectedEvent.AssetSelectedListener { companion object { private val TAG = Inspector::class.java.simpleName } enum class InspectorMode { GAME_OBJECT, ASSET, EMPTY } private var mode = InspectorMode.EMPTY private val root = VisTable() private val scrollPane = VisScrollPane(root) private val goInspector: GameObjectInspector private val assetInspector: AssetInspector init { Mundus.registerEventListener(this) goInspector = GameObjectInspector() assetInspector = AssetInspector() init() } fun init() { setBackground("window-bg") add(VisLabel("Inspector")).expandX().fillX().pad(3f).row() addSeparator().row() root.align(Align.top) scrollPane.setScrollingDisabled(true, false) scrollPane.setFlickScroll(false) scrollPane.setFadeScrollBars(false) scrollPane.addListener(object : InputListener() { override fun enter(event: InputEvent?, x: Float, y: Float, pointer: Int, fromActor: Actor?) { UI.scrollFocus = scrollPane } override fun exit(event: InputEvent?, x: Float, y: Float, pointer: Int, toActor: Actor?) { UI.scrollFocus = null } }) add<ScrollPane>(scrollPane).expand().fill().top() } override fun onGameObjectSelected(event: GameObjectSelectedEvent) { if (mode != InspectorMode.GAME_OBJECT) { mode = InspectorMode.GAME_OBJECT root.clear() root.add(goInspector).grow().row() } goInspector.setGameObject(event.gameObject!!) } override fun onGameObjectModified(event: GameObjectModifiedEvent) { goInspector.updateGameObject() } override fun onAssetSelected(event: AssetSelectedEvent) { Log.debug(TAG, event.asset.toString()) if (mode != InspectorMode.ASSET) { mode = InspectorMode.ASSET root.clear() root.add(assetInspector).grow().row() } assetInspector.asset = event.asset } }
apache-2.0
62533fd0524c7d3e4bd992eefc5181bb
32.117117
105
0.690696
4.239908
false
false
false
false
team401/SnakeSkin
SnakeSkin-Core/src/main/kotlin/org/snakeskin/logging/LoggerManager.kt
1
3812
package org.snakeskin.logging import java.io.File import java.io.PrintWriter import java.io.StringWriter import java.util.* /** * @author Cameron Earle * @version 8/26/17 */ object LoggerManager { private const val MAX_LOG_FILES = 10 private val HOME_DIR = System.getProperty("user.home") private fun crashMessage(date: Date, t: Throwable): String { val sw = StringWriter() val pw = PrintWriter(sw) sw.append( """ ███████╗███╗ ██╗ █████╗ ██╗ ██╗███████╗███████╗██╗ ██╗██╗███╗ ██╗ ██╗ ██╔════╝████╗ ██║██╔══██╗██║ ██╔╝██╔════╝██╔════╝██║ ██╔╝██║████╗ ██║ ██╗██╔╝ ███████╗██╔██╗ ██║███████║█████╔╝ █████╗ ███████╗█████╔╝ ██║██╔██╗ ██║ ╚═╝██║ ╚════██║██║╚██╗██║██╔══██║██╔═██╗ ██╔══╝ ╚════██║██╔═██╗ ██║██║╚██╗██║ ██╗██║ ███████║██║ ╚████║██║ ██║██║ ██╗███████╗███████║██║ ██╗██║██║ ╚████║ ╚═╝╚██╗ ╚══════╝╚═╝ ╚═══╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ SnakeSkin encountered a crash it couldn't recover from. Timestamp: $date Full stack trace below: """) pw.println() t.printStackTrace(pw) return sw.toString() } private fun deleteFiles(folder: File) { if (folder.isDirectory) { var files = folder.listFiles() ?: return files.sortBy { it.lastModified() } while (files.size >= MAX_LOG_FILES) { files[0]?.delete() files = folder.listFiles() ?: return files.sortBy { it.lastModified() } } } } @JvmStatic internal fun init() { } @JvmStatic @JvmOverloads fun logThrowable(e: Throwable, t: Thread? = null) { e.printStackTrace() } @JvmStatic @JvmOverloads fun logCrash(e: Throwable, t: Thread? = null) { val date = Date(System.currentTimeMillis()) e.printStackTrace() val folder = File("$HOME_DIR/snakeskin_crashes") if (!folder.exists()) { folder.mkdir() } deleteFiles(folder) //Delete old log files val filename = date.toString().replace(' ', '_').replace(':', '-') + ".txt" val file = File("$HOME_DIR/snakeskin_crashes/$filename") file.writeText(crashMessage(date, e)) println("Crash report written to '${file.absolutePath}'") } @JvmStatic @JvmOverloads fun logMessage(message: String, level: LogLevel = LogLevel.INFO) { println(message) } private val exceptionHandler = Thread.UncaughtExceptionHandler { t, e -> logThrowable(e, t) } private val mainThreadExceptionHandler = Thread.UncaughtExceptionHandler { t, e -> logCrash(e, t) } @JvmStatic fun logCurrentThread() { Thread.currentThread().uncaughtExceptionHandler = exceptionHandler } @JvmStatic fun logMainThread() { Thread.currentThread().uncaughtExceptionHandler = mainThreadExceptionHandler } }
gpl-3.0
4760b1f898cc560c1463cbbff59c1c5b
26.675926
95
0.498996
2.138869
false
false
false
false
hermantai/samples
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-12/app-code/app/src/main/java/dev/mfazio/abl/players/SinglePlayerViewModel.kt
3
3182
package dev.mfazio.abl.players import android.app.Application import androidx.lifecycle.* import dev.mfazio.abl.data.BaseballDatabase import dev.mfazio.abl.data.BaseballRepository import dev.mfazio.abl.util.getErrorMessage import dev.mfazio.abl.util.toBattingPercentageString import dev.mfazio.abl.util.toERAString import kotlinx.coroutines.launch class SinglePlayerViewModel(application: Application) : AndroidViewModel(application) { private val repo: BaseballRepository private val playerId = MutableLiveData<String>() val playerWithStats: LiveData<PlayerWithStats> val stats: LiveData<List<PlayerStatWithLabel>> val errorMessage = MutableLiveData("") init { repo = BaseballDatabase .getDatabase(application, viewModelScope) .let { db -> BaseballRepository.getInstance(db) } playerWithStats = Transformations.switchMap(playerId) { playerId -> repo.getPlayerWithStats(playerId) } stats = Transformations.map(playerWithStats) { playerWithStats: PlayerWithStats? -> if (playerWithStats != null) { convertPlayerStatsToStatsWithLabels( playerWithStats.player.position.isPitcher(), playerWithStats.stats ) } else listOf() } } fun setPlayerId(playerId: String) { this.playerId.value = playerId viewModelScope.launch { repo.updatePlayer(playerId).getErrorMessage(getApplication()) ?.let { message -> errorMessage.value = message } } } private fun convertPlayerStatsToStatsWithLabels(isPitcher: Boolean, playerStats: PlayerStats) = if (isPitcher) { with(playerStats.pitcherStats) { listOf( PlayerStatWithLabel("G", this.games.toString()), PlayerStatWithLabel("W-L", "${this.wins}-${this.losses}"), PlayerStatWithLabel("ERA", this.era.toERAString()), PlayerStatWithLabel("WHIP", this.whip.toERAString()), PlayerStatWithLabel("IP", this.inningsPitched.toString()), PlayerStatWithLabel("K", this.strikeouts.toString()), PlayerStatWithLabel("BB", this.baseOnBalls.toString()), PlayerStatWithLabel("SV", this.saves.toString()) ) } } else { with(playerStats.batterStats) { listOf( PlayerStatWithLabel("G", this.games.toString()), PlayerStatWithLabel("AB", this.atBats.toString()), PlayerStatWithLabel("HR", this.homeRuns.toString()), PlayerStatWithLabel("SB", this.stolenBases.toString()), PlayerStatWithLabel("R", this.runs.toString()), PlayerStatWithLabel("RBI", this.rbi.toString()), PlayerStatWithLabel("BA", this.battingAverage.toBattingPercentageString()), PlayerStatWithLabel("OPS", this.ops.toBattingPercentageString()) ) } } }
apache-2.0
b5e308951466580356ca5d0a44d0e539
38.7875
99
0.60748
4.858015
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/dailychallenge/sideeffect/DailyChallengeSideEffectHandler.kt
1
2625
package io.ipoli.android.dailychallenge.sideeffect import io.ipoli.android.common.AppSideEffectHandler import io.ipoli.android.common.AppState import io.ipoli.android.common.redux.Action import io.ipoli.android.dailychallenge.DailyChallengeAction import io.ipoli.android.dailychallenge.DailyChallengeViewState import io.ipoli.android.dailychallenge.usecase.LoadDailyChallengeUseCase import io.ipoli.android.dailychallenge.usecase.SaveDailyChallengeQuestIdsUseCase import io.ipoli.android.planday.PlanDayAction import io.ipoli.android.planday.PlanDayViewState import space.traversal.kapsule.required /** * Created by Polina Zhelyazkova <[email protected]> * on 5/28/18. */ object DailyChallengeSideEffectHandler : AppSideEffectHandler() { private val loadDailyChallengeUseCase by required { loadDailyChallengeUseCase } private val saveDailyChallengeQuestIdsUseCase by required { saveDailyChallengeQuestIdsUseCase } override suspend fun doExecute(action: Action, state: AppState) { when (action) { DailyChallengeAction.Load -> { dispatch( DailyChallengeAction.Loaded( loadDailyChallengeUseCase.execute( LoadDailyChallengeUseCase.Params() ) ) ) } DailyChallengeAction.Save -> { val s = state.stateFor(DailyChallengeViewState::class.java) saveDailyChallengeQuestIdsUseCase.execute(SaveDailyChallengeQuestIdsUseCase.Params( questIds = if (s.selectedQuests == null) { emptyList() } else { s.selectedQuests.map { it.id } } )) } PlanDayAction.LoadToday -> { dispatch( PlanDayAction.DailyChallengeLoaded( loadDailyChallengeUseCase.execute( LoadDailyChallengeUseCase.Params() ) ) ) } PlanDayAction.Done -> { val s = state.stateFor(PlanDayViewState::class.java) saveDailyChallengeQuestIdsUseCase.execute( SaveDailyChallengeQuestIdsUseCase.Params( questIds = s.dailyChallengeQuestIds ?: emptyList() ) ) } } } override fun canHandle(action: Action) = action is DailyChallengeAction || action is PlanDayAction }
gpl-3.0
1dcaba889608ee4d68e00d66eca47148
35.985915
99
0.600381
5.645161
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/stories/settings/custom/name/EditStoryNameFragment.kt
1
3142
package org.thoughtcrime.securesms.stories.settings.custom.name import android.os.Bundle import android.view.View import android.view.inputmethod.EditorInfo import android.widget.EditText import androidx.appcompat.widget.Toolbar import androidx.core.content.ContextCompat import androidx.core.widget.doAfterTextChanged import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.airbnb.lottie.SimpleColorFilter import com.dd.CircularProgressButton import com.google.android.material.textfield.TextInputLayout import io.reactivex.rxjava3.kotlin.subscribeBy import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.database.model.DistributionListId import org.thoughtcrime.securesms.util.LifecycleDisposable import org.thoughtcrime.securesms.util.ViewUtil class EditStoryNameFragment : Fragment(R.layout.stories_edit_story_name_fragment) { private val viewModel: EditStoryNameViewModel by viewModels( factoryProducer = { EditStoryNameViewModel.Factory(distributionListId, EditStoryNameRepository()) } ) private val distributionListId: DistributionListId get() = EditStoryNameFragmentArgs.fromBundle(requireArguments()).distributionListId private val initialName: String get() = EditStoryNameFragmentArgs.fromBundle(requireArguments()).name private val lifecycleDisposable = LifecycleDisposable() private lateinit var saveButton: CircularProgressButton private lateinit var storyName: EditText private lateinit var storyNameWrapper: TextInputLayout override fun onViewCreated(view: View, savedInstanceState: Bundle?) { lifecycleDisposable.bindTo(viewLifecycleOwner) val toolbar: Toolbar = view.findViewById(R.id.toolbar) toolbar.navigationIcon?.colorFilter = SimpleColorFilter(ContextCompat.getColor(requireContext(), R.color.signal_icon_tint_primary)) toolbar.setNavigationOnClickListener { findNavController().popBackStack() } storyNameWrapper = view.findViewById(R.id.story_name_wrapper) storyName = view.findViewById(R.id.story_name) storyName.setText(initialName) storyName.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { onSaveClicked() true } else { false } } storyName.doAfterTextChanged { saveButton.isEnabled = !it.isNullOrEmpty() saveButton.alpha = if (it.isNullOrEmpty()) 0.5f else 1f storyNameWrapper.error = null } saveButton = view.findViewById(R.id.save) saveButton.setOnClickListener { onSaveClicked() } } override fun onPause() { super.onPause() ViewUtil.hideKeyboard(requireContext(), storyName) } private fun onSaveClicked() { saveButton.isClickable = false lifecycleDisposable += viewModel.save(storyName.text).subscribeBy( onComplete = { findNavController().popBackStack() }, onError = { saveButton.isClickable = true storyNameWrapper.error = getString(R.string.CreateStoryWithViewersFragment__there_is_already_a_story_with_this_name) } ) } }
gpl-3.0
4f3ba49c9cf893fe4ac28d440831c507
34.704545
135
0.771165
4.76783
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/util/DeleteDialog.kt
2
4353
package org.thoughtcrime.securesms.util import android.content.Context import com.google.android.material.dialog.MaterialAlertDialogBuilder import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.core.SingleEmitter import org.signal.core.util.concurrent.SignalExecutors import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.database.SignalDatabase import org.thoughtcrime.securesms.database.model.MessageRecord import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.sms.MessageSender import org.thoughtcrime.securesms.util.task.ProgressDialogAsyncTask object DeleteDialog { /** * Displays a deletion dialog for the given set of message records. * * @param context Android Context * @param messageRecords The message records to delete * @param title The dialog title * @param message The dialog message, or null * @param forceRemoteDelete Allow remote deletion, even if it would normally be disallowed * * @return a Single, who's value notes whether or not a thread deletion occurred. */ fun show( context: Context, messageRecords: Set<MessageRecord>, title: CharSequence = context.resources.getQuantityString(R.plurals.ConversationFragment_delete_selected_messages, messageRecords.size, messageRecords.size), message: CharSequence? = null, forceRemoteDelete: Boolean = false ): Single<Boolean> = Single.create { emitter -> val builder = MaterialAlertDialogBuilder(context) builder.setTitle(title) builder.setMessage(message) builder.setCancelable(true) if (forceRemoteDelete) { builder.setPositiveButton(R.string.ConversationFragment_delete_for_everyone) { _, _ -> deleteForEveryone(messageRecords, emitter) } } else { builder.setPositiveButton(R.string.ConversationFragment_delete_for_me) { _, _ -> DeleteProgressDialogAsyncTask(context, messageRecords, emitter::onSuccess).executeOnExecutor(SignalExecutors.BOUNDED) } if (RemoteDeleteUtil.isValidSend(messageRecords, System.currentTimeMillis())) { builder.setNeutralButton(R.string.ConversationFragment_delete_for_everyone) { _, _ -> handleDeleteForEveryone(context, messageRecords, emitter) } } } builder.setNegativeButton(android.R.string.cancel) { _, _ -> emitter.onSuccess(false) } builder.setOnCancelListener { emitter.onSuccess(false) } builder.show() } private fun handleDeleteForEveryone(context: Context, messageRecords: Set<MessageRecord>, emitter: SingleEmitter<Boolean>) { if (SignalStore.uiHints().hasConfirmedDeleteForEveryoneOnce()) { deleteForEveryone(messageRecords, emitter) } else { MaterialAlertDialogBuilder(context) .setMessage(R.string.ConversationFragment_this_message_will_be_deleted_for_everyone_in_the_conversation) .setPositiveButton(R.string.ConversationFragment_delete_for_everyone) { _, _ -> SignalStore.uiHints().markHasConfirmedDeleteForEveryoneOnce() deleteForEveryone(messageRecords, emitter) } .setNegativeButton(android.R.string.cancel) { _, _ -> emitter.onSuccess(false) } .setOnCancelListener { emitter.onSuccess(false) } .show() } } private fun deleteForEveryone(messageRecords: Set<MessageRecord>, emitter: SingleEmitter<Boolean>) { SignalExecutors.BOUNDED.execute { messageRecords.forEach { message -> MessageSender.sendRemoteDelete(message.id, message.isMms) } emitter.onSuccess(false) } } private class DeleteProgressDialogAsyncTask( context: Context, private val messageRecords: Set<MessageRecord>, private val onDeletionCompleted: ((Boolean) -> Unit) ) : ProgressDialogAsyncTask<Void, Void, Boolean>( context, R.string.ConversationFragment_deleting, R.string.ConversationFragment_deleting_messages ) { override fun doInBackground(vararg params: Void?): Boolean { return messageRecords.map { record -> if (record.isMms) { SignalDatabase.mms.deleteMessage(record.id) } else { SignalDatabase.sms.deleteMessage(record.id) } }.any { it } } override fun onPostExecute(result: Boolean?) { super.onPostExecute(result) onDeletionCompleted(result == true) } } }
gpl-3.0
f1837057fcc6f7464f2d5a2526105838
39.305556
161
0.729152
4.520249
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/components/settings/DSLSettingsAdapter.kt
1
9355
package org.thoughtcrime.securesms.components.settings import android.text.Spanned import android.text.method.LinkMovementMethod import android.text.style.ClickableSpan import android.view.View import android.widget.ImageView import android.widget.RadioButton import android.widget.TextView import androidx.annotation.CallSuper import androidx.core.content.ContextCompat import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.switchmaterial.SwitchMaterial import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.settings.models.AsyncSwitch import org.thoughtcrime.securesms.components.settings.models.Button import org.thoughtcrime.securesms.components.settings.models.Space import org.thoughtcrime.securesms.components.settings.models.Text import org.thoughtcrime.securesms.util.CommunicationActions import org.thoughtcrime.securesms.util.ViewUtil import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder import org.thoughtcrime.securesms.util.visible class DSLSettingsAdapter : MappingAdapter() { init { registerFactory(ClickPreference::class.java, LayoutFactory(::ClickPreferenceViewHolder, R.layout.dsl_preference_item)) registerFactory(LongClickPreference::class.java, LayoutFactory(::LongClickPreferenceViewHolder, R.layout.dsl_preference_item)) registerFactory(TextPreference::class.java, LayoutFactory(::TextPreferenceViewHolder, R.layout.dsl_preference_item)) registerFactory(RadioListPreference::class.java, LayoutFactory(::RadioListPreferenceViewHolder, R.layout.dsl_preference_item)) registerFactory(MultiSelectListPreference::class.java, LayoutFactory(::MultiSelectListPreferenceViewHolder, R.layout.dsl_preference_item)) registerFactory(ExternalLinkPreference::class.java, LayoutFactory(::ExternalLinkPreferenceViewHolder, R.layout.dsl_preference_item)) registerFactory(DividerPreference::class.java, LayoutFactory(::DividerPreferenceViewHolder, R.layout.dsl_divider_item)) registerFactory(SectionHeaderPreference::class.java, LayoutFactory(::SectionHeaderPreferenceViewHolder, R.layout.dsl_section_header)) registerFactory(SwitchPreference::class.java, LayoutFactory(::SwitchPreferenceViewHolder, R.layout.dsl_switch_preference_item)) registerFactory(RadioPreference::class.java, LayoutFactory(::RadioPreferenceViewHolder, R.layout.dsl_radio_preference_item)) Text.register(this) Space.register(this) Button.register(this) AsyncSwitch.register(this) } } abstract class PreferenceViewHolder<T : PreferenceModel<T>>(itemView: View) : MappingViewHolder<T>(itemView) { protected val iconView: ImageView = itemView.findViewById(R.id.icon) private val iconEndView: ImageView? = itemView.findViewById(R.id.icon_end) protected val titleView: TextView = itemView.findViewById(R.id.title) protected val summaryView: TextView = itemView.findViewById(R.id.summary) @CallSuper override fun bind(model: T) { listOf(itemView, titleView, summaryView).forEach { it.isEnabled = model.isEnabled } val icon = model.icon?.resolve(context) iconView.setImageDrawable(icon) iconView.visible = icon != null val iconEnd = model.iconEnd?.resolve(context) iconEndView?.setImageDrawable(iconEnd) iconEndView?.visible = iconEnd != null val title = model.title?.resolve(context) if (title != null) { titleView.text = model.title?.resolve(context) titleView.visibility = View.VISIBLE } else { titleView.visibility = View.GONE } val summary = model.summary?.resolve(context) if (summary != null) { summaryView.text = summary summaryView.visibility = View.VISIBLE val spans = (summaryView.text as? Spanned)?.getSpans(0, summaryView.text.length, ClickableSpan::class.java) if (spans?.isEmpty() == false) { summaryView.movementMethod = LinkMovementMethod.getInstance() } else { summaryView.movementMethod = null } } else { summaryView.visibility = View.GONE summaryView.movementMethod = null } } } class TextPreferenceViewHolder(itemView: View) : PreferenceViewHolder<TextPreference>(itemView) class ClickPreferenceViewHolder(itemView: View) : PreferenceViewHolder<ClickPreference>(itemView) { override fun bind(model: ClickPreference) { super.bind(model) itemView.setOnClickListener { model.onClick() } itemView.setOnLongClickListener { model.onLongClick?.invoke() ?: false } } } class LongClickPreferenceViewHolder(itemView: View) : PreferenceViewHolder<LongClickPreference>(itemView) { override fun bind(model: LongClickPreference) { super.bind(model) itemView.setOnLongClickListener() { model.onLongClick() true } } } class RadioListPreferenceViewHolder(itemView: View) : PreferenceViewHolder<RadioListPreference>(itemView) { override fun bind(model: RadioListPreference) { super.bind(model) if (model.selected >= 0) { summaryView.visibility = View.VISIBLE summaryView.text = model.listItems[model.selected] } else { summaryView.visibility = View.GONE Log.w(TAG, "Detected a radio list without a default selection: ${model.dialogTitle}") } itemView.setOnClickListener { var selection = -1 val builder = MaterialAlertDialogBuilder(context) .setTitle(model.dialogTitle.resolve(context)) .setSingleChoiceItems(model.listItems, model.selected) { dialog, which -> if (model.confirmAction) { selection = which } else { model.onSelected(which) dialog.dismiss() } } if (model.confirmAction) { builder .setPositiveButton(android.R.string.ok) { dialog, _ -> model.onSelected(selection) dialog.dismiss() } .setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.dismiss() } .show() } else { builder.show() } } } companion object { private val TAG = Log.tag(RadioListPreference::class.java) } } class MultiSelectListPreferenceViewHolder(itemView: View) : PreferenceViewHolder<MultiSelectListPreference>(itemView) { override fun bind(model: MultiSelectListPreference) { super.bind(model) summaryView.visibility = View.VISIBLE val summaryText = model.selected .mapIndexed { index, isChecked -> if (isChecked) model.listItems[index] else null } .filterNotNull() .joinToString(", ") if (summaryText.isEmpty()) { summaryView.setText(R.string.preferences__none) } else { summaryView.text = summaryText } val selected = model.selected.copyOf() itemView.setOnClickListener { MaterialAlertDialogBuilder(context) .setTitle(model.title.resolve(context)) .setMultiChoiceItems(model.listItems, selected) { _, _, _ -> // Intentionally empty } .setNegativeButton(android.R.string.cancel) { d, _ -> d.dismiss() } .setPositiveButton(android.R.string.ok) { d, _ -> model.onSelected(selected) d.dismiss() } .show() } } } class SwitchPreferenceViewHolder(itemView: View) : PreferenceViewHolder<SwitchPreference>(itemView) { private val switchWidget: SwitchMaterial = itemView.findViewById(R.id.switch_widget) override fun bind(model: SwitchPreference) { super.bind(model) switchWidget.isEnabled = model.isEnabled switchWidget.isChecked = model.isChecked itemView.setOnClickListener { model.onClick() } } } class RadioPreferenceViewHolder(itemView: View) : PreferenceViewHolder<RadioPreference>(itemView) { private val radioButton: RadioButton = itemView.findViewById(R.id.radio_widget) override fun bind(model: RadioPreference) { super.bind(model) radioButton.isChecked = model.isChecked itemView.setOnClickListener { model.onClick() } } } class ExternalLinkPreferenceViewHolder(itemView: View) : PreferenceViewHolder<ExternalLinkPreference>(itemView) { override fun bind(model: ExternalLinkPreference) { super.bind(model) val externalLinkIcon = requireNotNull(ContextCompat.getDrawable(context, R.drawable.ic_open_20)) externalLinkIcon.setBounds(0, 0, ViewUtil.dpToPx(20), ViewUtil.dpToPx(20)) if (ViewUtil.isLtr(itemView)) { titleView.setCompoundDrawables(null, null, externalLinkIcon, null) } else { titleView.setCompoundDrawables(externalLinkIcon, null, null, null) } itemView.setOnClickListener { CommunicationActions.openBrowserLink(itemView.context, itemView.context.getString(model.linkId)) } } } class DividerPreferenceViewHolder(itemView: View) : MappingViewHolder<DividerPreference>(itemView) { override fun bind(model: DividerPreference) = Unit } class SectionHeaderPreferenceViewHolder(itemView: View) : MappingViewHolder<SectionHeaderPreference>(itemView) { private val sectionHeader: TextView = itemView.findViewById(R.id.section_header) override fun bind(model: SectionHeaderPreference) { sectionHeader.text = model.title.resolve(context) } }
gpl-3.0
904aa289159a3a1ca6af9c297669351d
36.874494
142
0.738642
4.550097
false
false
false
false
qaware/majx
src/main/kotlin/de/qaware/majx/JsonMatcher.kt
1
16947
/** * MIT License * * Copyright (c) 2017 QAware GmbH * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package de.qaware.majx import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.* import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.* /** * Matcher that compares an actual JSON with a pattern JSON object. * * Can use templates on strings to check against dynamic test expectations. * Accepts wildcards. * * @property config The config that controls certain matcher aspects. * @property mustacheScope The scope from which the mustache parser reads it variables. May be a map or a POJO. * This is used in case we need dynamic test expectations. * @constructor Creates a new [JsonMatcher] with the given [mustacheScope]. */ class JsonMatcher(private val config: MatcherConfig, private val mustacheScope: Any?) { /** * Companion object provides support methods for [JsonMatcher]. */ companion object { /** * Identifier for a wildcard. * * A wildcard can be used in patterns if the content of the actual key or value is unimportant. */ private const val WILDCARD = "..." /** * Format location information string from attribute name * * @param attributeName Name of the attribute. * @return The formatted location. */ private fun formatLocation(attributeName: String): String = "Error at location $attributeName: " /** * @param node Node to check * @return True if the node contains a wildcard. */ private fun isWildcard(node: JsonNode): Boolean { return node.isTextual && WILDCARD == node.textValue() } /** * @param iterator The iterator to initialize the set with. * @return A new [MutableSet] containing the elements of the given iterator. */ private fun asSet(iterator: Iterator<String>): MutableSet<String> { val result = LinkedHashSet<String>() iterator.forEach { result.add(it) } return result } /** * Check if the node contains a wildcard. * * The wildcard is the last entry in the array or the child element with the * name "..." in an object. * @param node Node to check * @return True if the node contains a wildcard */ private fun containsWildcard(node: JsonNode): Boolean { return when (node) { is ArrayNode -> node.size() > 0 && isWildcard(node.get(node.size() - 1)) is ObjectNode -> node.get(WILDCARD) != null && isWildcard(node.get(WILDCARD)) else -> throw IllegalArgumentException("Only array and object nodes can contain wildcards.") } } /** * Validate that array or object sizes are correct. If there is a wildcard in the pattern object this means that the * actual object may contain more elements than the pattern object. * * @param pattern Pattern object. * @param actual Actual value. * @param locationInfo Location information for error output. * @param <T> Type of container to check. */ private fun <T : ContainerNode<T>> validateCorrectSize(pattern: ContainerNode<T>, actual: ContainerNode<T>, locationInfo: String) { if (containsWildcard(pattern)) { // Wildcard: Number of elements must be greater or equal to the number of actually specified elements val specifiedElems = pattern.size() - 1 val actualContainerType = if (actual.isArray()) "array" else "object" assertThat<Int>("${locationInfo}Actual $actualContainerType size too small", actual.size(), greaterThanOrEqualTo<Int>(specifiedElems)) } else { // No wildcard: number of elements must match exactly val errorMsg: String if (actual.isArray) { errorMsg = "${locationInfo}Sizes of arrays do not match." } else if (actual.isObject) { val expectedPropertiesSet = asSet(pattern.fieldNames()) val actualPropertiesSet = asSet(actual.fieldNames()) val notMatchedSet = expectedPropertiesSet.union(actualPropertiesSet).minus( expectedPropertiesSet.intersect(actualPropertiesSet) ) val notMatched = if (notMatchedSet.isNotEmpty()) notMatchedSet.joinToString() else "(empty)" val expectedProperties = if (expectedPropertiesSet.isNotEmpty()) expectedPropertiesSet.joinToString() else "(empty)" val actualProperties = if (actualPropertiesSet.isNotEmpty()) actualPropertiesSet.joinToString() else "(empty)" errorMsg = """${locationInfo}Size of object properties does not match. |Expected properties: $expectedProperties |Actual properties: $actualProperties |Not matched properties: $notMatched""".trimMargin() } else { throw UnsupportedOperationException("Not implemented handling of subtype '${actual.javaClass.name}' " + "of type '${ContainerNode<*>::javaClass.name}'") } assertThat<Int>(errorMsg, actual.size(), equalTo<Int>(pattern.size())) } } } /** * Recursively validate that the actual JSON matches the pattern JSON (potentially with wildcards). Uses default * root. * @param reason The error message to prepend to the JSON matcher error message if validation fails. * @param pattern Pattern object. * @param actual Actual value. */ fun assertMatches(reason: String?, pattern: JsonNode, actual: JsonNode) { try { validate(pattern, actual, "$") } catch (ex: AssertionError) { val actualAsText = convertToString(actual) val expectedAsText = convertToString(pattern) val mustacheScopeString = if (this.mustacheScope != null) { """ |-------------------------------------------------------------------------------------------- |Mustache Scope |-------------------------------------------------------------------------------------------- |${printMustacheScope(this.mustacheScope)} """ } else "" val reasonOutput: String = if (reason != null) "$reason: " else "" throw AssertionError("""$reasonOutput${ex.message}. |-------------------------------------------------------------------------------------------- |Actual JSON |-------------------------------------------------------------------------------------------- |$actualAsText |-------------------------------------------------------------------------------------------- |Pattern |-------------------------------------------------------------------------------------------- |$expectedAsText$mustacheScopeString""".trimMargin(), ex) } } private fun printMustacheScope(mustacheScope: Any): String { val builder = StringBuilder() if (mustacheScope is Map<*, *>) { val longestKey = mustacheScope.keys.fold(0, { acc, elem -> Math.max(acc, (elem as String).length) }) mustacheScope.forEach { key, value -> builder.appendln("${key.toString().padEnd(longestKey + 1)}= $value") } } else { builder.appendln(mustacheScope.toString()) } return builder.toString() } /** * Recursively validate that the actual value matches the pattern object (potentially with wildcards) * * @param pattern Pattern object. * @param actual Actual value. * @param attributeName Name of currently processed attribute (absolut path from root). */ private fun validate(pattern: JsonNode, actual: JsonNode, attributeName: String) { if (isWildcard(pattern)) { return } val locationInfo = formatLocation(attributeName) assertThat(locationInfo + "Incorrect type of attribute", actual.nodeType, `is`(pattern.nodeType)) when { pattern is ObjectNode && actual is ObjectNode -> validateObject(pattern, actual, attributeName) pattern is ArrayNode && actual is ArrayNode -> validateArray(pattern, actual, attributeName) pattern is TextNode && actual is TextNode -> validateString(pattern, actual, attributeName) pattern is ValueNode && actual is ValueNode -> validateScalar(pattern, actual, attributeName) else -> { val error = "Incompatible types in actual and expected. " + "Type of actual: ${actual.javaClass}, " + "type of expected: ${pattern.javaClass}" throw AssertionError("$locationInfo$error") } } } /** * Recursively validate that the actual value matches the pattern object (potentially with wildcards). * * @param pattern Pattern object. * @param actual Actual value. * @param attributeName Name of currently processed attribute (absolut path from root). */ private fun validateObject(pattern: ObjectNode, actual: ObjectNode, attributeName: String) { val locationInfo = formatLocation(attributeName) validateCorrectSize<ObjectNode>(pattern, actual, locationInfo) val expectedFieldNames = pattern.fieldNames() while (expectedFieldNames.hasNext()) { val expectedFieldName = expectedFieldNames.next() if (WILDCARD == expectedFieldName && isWildcard(pattern.get(WILDCARD))) { continue } assertThat("$locationInfo Expected field name '$expectedFieldName' not found.", actual.get(expectedFieldName), notNullValue()) validate(pattern.get(expectedFieldName), actual.get(expectedFieldName), "$attributeName.$expectedFieldName") } } /** * Recursively validate that the actual value matches the pattern array (potentially with wildcards). * * @param pattern Pattern array. * @param actual Actual array. * @param attributeName Name of currently processed attribute (absolute path from root). */ private fun validateArray(pattern: ArrayNode, actual: ArrayNode, attributeName: String) { val locationInfo: String = formatLocation(attributeName) validateCorrectSize(pattern, actual, locationInfo) if (config.randomArrayOrder) { validateArrayRandom(attributeName, pattern, actual) } else { validateArrayOrdered(attributeName, pattern, actual) } } /** * Recursively validate that the actual value matches the pattern array in any order (potentially with wildcards). * * @param pattern Pattern array. * @param actual Actual array. * @param attributeName Name of currently processed attribute (absolute path from root). */ private fun validateArrayRandom(attributeName: String, pattern: ArrayNode, actual: ArrayNode) { val locationInfo: String = formatLocation(attributeName) val wildcardMatchMode = containsWildcard(pattern) val actualNodes: List<JsonNode> = actual.toList() val expectedNodes: List<JsonNode> = if (wildcardMatchMode) pattern.filterNot(::isWildcard) else pattern.toList() // For each element in expected find at least one element in actual that does not fail validation expectedNodes.forEach { expectedNode -> if (!hasItem(actualNodes, expectedNode)) { if (wildcardMatchMode) { // Wildcard found -> actual must contain all pattern elements (and may contain additional elements) throw AssertionError("$locationInfo Actual array does not contain all pattern " + "array elements ignoring order") } else { // No wildcard -> sets must be equal throw AssertionError("$locationInfo Arrays are not equal ignoring order") } } } } /** * Returns whether the given list contains at least one item that matches the given pattern. * * @param list The list. * @param pattern The pattern. * @return Whether the list contains an item that matches the given pattern. */ private fun hasItem(list: List<JsonNode>, pattern: JsonNode): Boolean { for (actualNode in list) { // I know it is bad practice to use exeptions for control flow but currently the validation works // this way. When we restructure the code to return a list of validation errors instead of throwing, this // function will become cleaner. try { validate(pattern, actualNode, "ignored") return true } catch (ignored: AssertionError) { // Ignored } } return false } /** * Recursively validate that the actual value matches the pattern array in fixed order (potentially with wildcards). * * The fixed order is dictated by the pattern. * * @param pattern Pattern array. * @param actual Actual array. * @param attributeName Name of currently processed attribute (absolute path from root). */ private fun validateArrayOrdered(attributeName: String, pattern: ArrayNode, actual: ArrayNode) { // If pattern contains wildcard only the elements up to the wildcard must match. val maxIndex = if (containsWildcard(pattern)) pattern.size() - 2 else pattern.size() - 1 for (i in 0..maxIndex) { validate(pattern.get(i), actual.get(i), "$attributeName[$i]") } } /** * Validate string match, potentially using mustache template engine to replace variable parts of the string * * @param pattern Pattern object. * @param actual Actual value. * @param attributeName Name of currently processed attribute (absolut path from root). */ private fun validateString(pattern: TextNode, actual: TextNode, attributeName: String) { val locationInfo = formatLocation(attributeName) val patternText = pattern.textValue() MustacheMatcher.assertEqual(locationInfo + "Value does not match", patternText, actual.textValue(), mustacheScope) } /** * Recursively validate that the actual value matches the pattern object (potentially with wildcards). * * @param pattern Pattern object. * @param actual Actual value. * @param attributeName Name of curretly processed attribute (absolut path from root). */ private fun validateScalar(pattern: ValueNode, actual: ValueNode, attributeName: String) { val locationInfo = formatLocation(attributeName) assertThat(locationInfo + "Element does not match", actual.asText(), `is`<String>(pattern.asText())) } }
mit
e11298b71cfe11366731ca3a64848100
44.556452
124
0.59214
5.449196
false
false
false
false
emanuelpalm/palm-compute
core/src/main/java/se/ltu/emapal/compute/ComputeBatch.kt
1
2598
package se.ltu.emapal.compute import se.ltu.emapal.compute.util.Result import se.ltu.emapal.compute.util.media.MediaDecoder import se.ltu.emapal.compute.util.media.MediaEncodable import se.ltu.emapal.compute.util.media.MediaEncoder import se.ltu.emapal.compute.util.media.schema.MediaSchema import se.ltu.emapal.compute.util.media.schema.MediaSchemaException import java.util.* /** * Some arbitrary byte array to be processed by some identified lambda function. * * @param lambdaId Identifies lambda responsible for processing batch. * @param batchId Batch identifier unique within the application. * @param data Arbitrary byte array to process. */ class ComputeBatch( val lambdaId: Int, val batchId: Int, val data: ByteArray ) : MediaEncodable { override val encodable: (MediaEncoder) -> Unit get() = { it.encodeMap { it .add("lid", lambdaId) .add("bid", batchId) .add("dat", data) } } override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other?.javaClass != javaClass) { return false } other as ComputeBatch return lambdaId == other.lambdaId && batchId == other.batchId && Arrays.equals(data, other.data); } override fun hashCode(): Int { var result = lambdaId result += 31 * result + batchId result += 31 * result + Arrays.hashCode(data) return result } override fun toString(): String { return "ComputeBatch(lambdaId=$lambdaId, batchId=$batchId, data=${Arrays.toString(data)})" } companion object { private val decoderSchema = MediaSchema.typeMap() .schemaEntry("lid", MediaSchema.typeNumber()) .schemaEntry("bid", MediaSchema.typeNumber()) .schemaEntry("dat", MediaSchema.typeBlob()) /** Attempts to produce [ComputeBatch] using provided decoder. */ fun decode(decoder: MediaDecoder): Result<ComputeBatch, MediaSchemaException> { return decoderSchema.verify(decoder) .map { val decoderMap = decoder.toMap() ComputeBatch( decoderMap["lid"]!!.toInt(), decoderMap["bid"]!!.toInt(), decoderMap["dat"]!!.toBlob() ) } } } }
mit
5652e133e7aebe84fad8add74c0f949c
33.197368
98
0.566975
4.73224
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/extension/ExtensionManager.kt
2
13782
package eu.kanade.tachiyomi.extension import android.content.Context import android.graphics.drawable.Drawable import com.jakewharton.rxrelay.BehaviorRelay import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.extension.api.ExtensionGithubApi import eu.kanade.tachiyomi.extension.model.Extension import eu.kanade.tachiyomi.extension.model.InstallStep import eu.kanade.tachiyomi.extension.model.LoadResult import eu.kanade.tachiyomi.extension.util.ExtensionInstallReceiver import eu.kanade.tachiyomi.extension.util.ExtensionInstaller import eu.kanade.tachiyomi.extension.util.ExtensionLoader import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.util.lang.launchNow import eu.kanade.tachiyomi.util.preference.plusAssign import eu.kanade.tachiyomi.util.system.logcat import eu.kanade.tachiyomi.util.system.toast import kotlinx.coroutines.async import logcat.LogPriority import rx.Observable import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get /** * The manager of extensions installed as another apk which extend the available sources. It handles * the retrieval of remotely available extensions as well as installing, updating and removing them. * To avoid malicious distribution, every extension must be signed and it will only be loaded if its * signature is trusted, otherwise the user will be prompted with a warning to trust it before being * loaded. * * @param context The application context. * @param preferences The application preferences. */ class ExtensionManager( private val context: Context, private val preferences: PreferencesHelper = Injekt.get() ) { /** * API where all the available extensions can be found. */ private val api = ExtensionGithubApi() /** * The installer which installs, updates and uninstalls the extensions. */ private val installer by lazy { ExtensionInstaller(context) } /** * Relay used to notify the installed extensions. */ private val installedExtensionsRelay = BehaviorRelay.create<List<Extension.Installed>>() private val iconMap = mutableMapOf<String, Drawable>() /** * List of the currently installed extensions. */ var installedExtensions = emptyList<Extension.Installed>() private set(value) { field = value installedExtensionsRelay.call(value) } fun getAppIconForSource(source: Source): Drawable? { val pkgName = installedExtensions.find { ext -> ext.sources.any { it.id == source.id } }?.pkgName if (pkgName != null) { return iconMap[pkgName] ?: iconMap.getOrPut(pkgName) { context.packageManager.getApplicationIcon(pkgName) } } return null } /** * Relay used to notify the available extensions. */ private val availableExtensionsRelay = BehaviorRelay.create<List<Extension.Available>>() /** * List of the currently available extensions. */ var availableExtensions = emptyList<Extension.Available>() private set(value) { field = value availableExtensionsRelay.call(value) updatedInstalledExtensionsStatuses(value) } /** * Relay used to notify the untrusted extensions. */ private val untrustedExtensionsRelay = BehaviorRelay.create<List<Extension.Untrusted>>() /** * List of the currently untrusted extensions. */ var untrustedExtensions = emptyList<Extension.Untrusted>() private set(value) { field = value untrustedExtensionsRelay.call(value) } /** * The source manager where the sources of the extensions are added. */ private lateinit var sourceManager: SourceManager /** * Initializes this manager with the given source manager. */ fun init(sourceManager: SourceManager) { this.sourceManager = sourceManager initExtensions() ExtensionInstallReceiver(InstallationListener()).register(context) } /** * Loads and registers the installed extensions. */ private fun initExtensions() { val extensions = ExtensionLoader.loadExtensions(context) installedExtensions = extensions .filterIsInstance<LoadResult.Success>() .map { it.extension } installedExtensions .flatMap { it.sources } .forEach { sourceManager.registerSource(it) } untrustedExtensions = extensions .filterIsInstance<LoadResult.Untrusted>() .map { it.extension } } /** * Returns the relay of the installed extensions as an observable. */ fun getInstalledExtensionsObservable(): Observable<List<Extension.Installed>> { return installedExtensionsRelay.asObservable() } /** * Returns the relay of the available extensions as an observable. */ fun getAvailableExtensionsObservable(): Observable<List<Extension.Available>> { return availableExtensionsRelay.asObservable() } /** * Returns the relay of the untrusted extensions as an observable. */ fun getUntrustedExtensionsObservable(): Observable<List<Extension.Untrusted>> { return untrustedExtensionsRelay.asObservable() } /** * Finds the available extensions in the [api] and updates [availableExtensions]. */ fun findAvailableExtensions() { launchNow { val extensions: List<Extension.Available> = try { api.findExtensions() } catch (e: Exception) { logcat(LogPriority.ERROR, e) context.toast(R.string.extension_api_error) emptyList() } availableExtensions = extensions } } /** * Sets the update field of the installed extensions with the given [availableExtensions]. * * @param availableExtensions The list of extensions given by the [api]. */ private fun updatedInstalledExtensionsStatuses(availableExtensions: List<Extension.Available>) { if (availableExtensions.isEmpty()) { preferences.extensionUpdatesCount().set(0) return } val mutInstalledExtensions = installedExtensions.toMutableList() var changed = false for ((index, installedExt) in mutInstalledExtensions.withIndex()) { val pkgName = installedExt.pkgName val availableExt = availableExtensions.find { it.pkgName == pkgName } if (availableExt == null && !installedExt.isObsolete) { mutInstalledExtensions[index] = installedExt.copy(isObsolete = true) changed = true } else if (availableExt != null) { val hasUpdate = availableExt.versionCode > installedExt.versionCode if (installedExt.hasUpdate != hasUpdate) { mutInstalledExtensions[index] = installedExt.copy(hasUpdate = hasUpdate) changed = true } } } if (changed) { installedExtensions = mutInstalledExtensions } updatePendingUpdatesCount() } /** * Returns an observable of the installation process for the given extension. It will complete * once the extension is installed or throws an error. The process will be canceled if * unsubscribed before its completion. * * @param extension The extension to be installed. */ fun installExtension(extension: Extension.Available): Observable<InstallStep> { return installer.downloadAndInstall(api.getApkUrl(extension), extension) } /** * Returns an observable of the installation process for the given extension. It will complete * once the extension is updated or throws an error. The process will be canceled if * unsubscribed before its completion. * * @param extension The extension to be updated. */ fun updateExtension(extension: Extension.Installed): Observable<InstallStep> { val availableExt = availableExtensions.find { it.pkgName == extension.pkgName } ?: return Observable.empty() return installExtension(availableExt) } fun cancelInstallUpdateExtension(extension: Extension) { installer.cancelInstall(extension.pkgName) } /** * Sets to "installing" status of an extension installation. * * @param downloadId The id of the download. */ fun setInstalling(downloadId: Long) { installer.updateInstallStep(downloadId, InstallStep.Installing) } fun setInstallationResult(downloadId: Long, result: Boolean) { val step = if (result) InstallStep.Installed else InstallStep.Error installer.updateInstallStep(downloadId, step) } fun updateInstallStep(downloadId: Long, step: InstallStep) { installer.updateInstallStep(downloadId, step) } /** * Uninstalls the extension that matches the given package name. * * @param pkgName The package name of the application to uninstall. */ fun uninstallExtension(pkgName: String) { installer.uninstallApk(pkgName) } /** * Adds the given signature to the list of trusted signatures. It also loads in background the * extensions that match this signature. * * @param signature The signature to whitelist. */ fun trustSignature(signature: String) { val untrustedSignatures = untrustedExtensions.map { it.signatureHash }.toSet() if (signature !in untrustedSignatures) return ExtensionLoader.trustedSignatures += signature preferences.trustedSignatures() += signature val nowTrustedExtensions = untrustedExtensions.filter { it.signatureHash == signature } untrustedExtensions -= nowTrustedExtensions val ctx = context launchNow { nowTrustedExtensions .map { extension -> async { ExtensionLoader.loadExtensionFromPkgName(ctx, extension.pkgName) } } .map { it.await() } .forEach { result -> if (result is LoadResult.Success) { registerNewExtension(result.extension) } } } } /** * Registers the given extension in this and the source managers. * * @param extension The extension to be registered. */ private fun registerNewExtension(extension: Extension.Installed) { installedExtensions += extension extension.sources.forEach { sourceManager.registerSource(it) } } /** * Registers the given updated extension in this and the source managers previously removing * the outdated ones. * * @param extension The extension to be registered. */ private fun registerUpdatedExtension(extension: Extension.Installed) { val mutInstalledExtensions = installedExtensions.toMutableList() val oldExtension = mutInstalledExtensions.find { it.pkgName == extension.pkgName } if (oldExtension != null) { mutInstalledExtensions -= oldExtension extension.sources.forEach { sourceManager.unregisterSource(it) } } mutInstalledExtensions += extension installedExtensions = mutInstalledExtensions extension.sources.forEach { sourceManager.registerSource(it) } } /** * Unregisters the extension in this and the source managers given its package name. Note this * method is called for every uninstalled application in the system. * * @param pkgName The package name of the uninstalled application. */ private fun unregisterExtension(pkgName: String) { val installedExtension = installedExtensions.find { it.pkgName == pkgName } if (installedExtension != null) { installedExtensions -= installedExtension installedExtension.sources.forEach { sourceManager.unregisterSource(it) } } val untrustedExtension = untrustedExtensions.find { it.pkgName == pkgName } if (untrustedExtension != null) { untrustedExtensions -= untrustedExtension } } /** * Listener which receives events of the extensions being installed, updated or removed. */ private inner class InstallationListener : ExtensionInstallReceiver.Listener { override fun onExtensionInstalled(extension: Extension.Installed) { registerNewExtension(extension.withUpdateCheck()) updatePendingUpdatesCount() } override fun onExtensionUpdated(extension: Extension.Installed) { registerUpdatedExtension(extension.withUpdateCheck()) updatePendingUpdatesCount() } override fun onExtensionUntrusted(extension: Extension.Untrusted) { untrustedExtensions += extension } override fun onPackageUninstalled(pkgName: String) { unregisterExtension(pkgName) updatePendingUpdatesCount() } } /** * Extension method to set the update field of an installed extension. */ private fun Extension.Installed.withUpdateCheck(): Extension.Installed { val availableExt = availableExtensions.find { it.pkgName == pkgName } if (availableExt != null && availableExt.versionCode > versionCode) { return copy(hasUpdate = true) } return this } private fun updatePendingUpdatesCount() { preferences.extensionUpdatesCount().set(installedExtensions.count { it.hasUpdate }) } }
apache-2.0
ef90ef51f1ddd184d1ee95d6ed048762
35.173228
119
0.670004
5.163732
false
false
false
false
ClearVolume/scenery
src/test/kotlin/graphics/scenery/tests/unit/PeriodicTableTests.kt
2
1981
package graphics.scenery.tests.unit import graphics.scenery.proteins.PeriodicTable import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertNull /** * Tests for [PeriodicTable] * * @author Justin Buerger <[email protected]> */ class PeriodicTableTests { /** * Tests if findByElement finds hydrogen with elementNumber 1 */ @Test fun testHydrogen() { val table = PeriodicTable() val hydrogen = table.findElementByNumber(1) assertEquals(hydrogen.name, "Hydrogen") assertEquals(hydrogen.standardState, "Gas") assertEquals(hydrogen.atomicRadius, 120f) } /** * Tests if two periodic tables are being created equally */ @Test fun testConsistency() { val table1 = PeriodicTable() val table2 = PeriodicTable() assertEquals(table1.elementList, table2.elementList) } /** * Tests if one of the missing parameters of oganesson becomes null. */ @Test fun testOganesson() { val table = PeriodicTable() val oganesson = table.findElementByNumber(118) assertEquals(oganesson.symbol, "Og") assertNull(oganesson.boilingPoint) } /** * Tests if we fall back to hydrogen in case the given elementNumber is not in the table */ @Test fun fallBackToHydrogen() { val table = PeriodicTable() val defaultHydrogen1 = table.findElementByNumber(0) val defaultHydrogen2 = table.findElementByNumber(119) val hydrogen = table.findElementByNumber(1) assertEquals(defaultHydrogen1.atomicMass, hydrogen.atomicMass) assertEquals(defaultHydrogen2.atomicMass, hydrogen.atomicMass) } /** * Tests if Plutonium is found by its symbol */ @Test fun findPlutoniumBySymbol() { val table = PeriodicTable() val plutonium = table.findElementBySymbol("Pu") assertEquals(plutonium.atomicNumber, 94) } }
lgpl-3.0
5910ec898885bac1e747de74a742f41d
27.3
92
0.663301
4.092975
false
true
false
false
vinumeris/lighthouse
client/src/main/java/lighthouse/activities/OverviewActivity.kt
1
11356
package lighthouse.activities import de.jensd.fx.fontawesome.AwesomeDude import de.jensd.fx.fontawesome.AwesomeIcon import javafx.animation.* import javafx.application.Platform import javafx.beans.InvalidationListener import javafx.beans.property.SimpleLongProperty import javafx.beans.property.SimpleObjectProperty import javafx.beans.value.WritableValue import javafx.collections.ListChangeListener import javafx.collections.MapChangeListener import javafx.collections.ObservableList import javafx.collections.ObservableMap import javafx.event.ActionEvent import javafx.fxml.FXML import javafx.fxml.FXMLLoader import javafx.scene.control.Label import javafx.scene.input.DragEvent import javafx.scene.input.MouseEvent import javafx.scene.input.TransferMode import javafx.scene.layout.VBox import javafx.stage.FileChooser import javafx.util.Duration import lighthouse.LighthouseBackend import lighthouse.Main import lighthouse.MainWindow import lighthouse.controls.ProjectOverviewWidget import lighthouse.files.AppDirectory import lighthouse.nav.Activity import lighthouse.protocol.Project import lighthouse.subwindows.EditProjectWindow import lighthouse.threading.AffinityExecutor import lighthouse.utils.GuiUtils import lighthouse.utils.GuiUtils.getResource import lighthouse.utils.GuiUtils.platformFiddleChooser import lighthouse.utils.I18nUtil import lighthouse.utils.I18nUtil.tr import lighthouse.utils.easing.EasingMode import lighthouse.utils.easing.ElasticInterpolator import lighthouse.utils.timeIt import lighthouse.utils.ui import nl.komponents.kovenant.async import org.bitcoinj.core.Sha256Hash import org.slf4j.LoggerFactory import java.io.File import java.io.IOException import java.nio.file.Files import java.nio.file.Path /** * An activity that shows the projects that have been loaded into the app, and buttons to import/create a new one. * Also can have adverts for stuff in the Lighthouse edition. */ public class OverviewActivity : VBox(), Activity { @FXML var addProjectIcon: Label? = null private val projects: ObservableList<Project> = Main.backend.mirrorProjects(AffinityExecutor.UI_THREAD) private val projectStates: ObservableMap<Sha256Hash, LighthouseBackend.ProjectStateInfo> = Main.backend.mirrorProjectStates(AffinityExecutor.UI_THREAD) // A map indicating the status of checking each project against the network (downloading, found an error, done, etc) // This is mirrored into the UI thread from the backend. private val checkStates: ObservableMap<Project, LighthouseBackend.CheckStatus> = Main.backend.mirrorCheckStatuses(AffinityExecutor.UI_THREAD) private val numInitialBoxes: Int init { val loader = FXMLLoader(getResource("activities/overview.fxml"), I18nUtil.translations) loader.setRoot(this) loader.setController(this) loader.load<Any>() numInitialBoxes = children.size AwesomeDude.setIcon(addProjectIcon, AwesomeIcon.FILE_ALT, "50pt; -fx-text-fill: white" /* lame hack */) // 4 projects is enough to fill the window on most screens. val PRERENDER = 4 val pr = projects.reversed() val immediate = pr.take(PRERENDER) val later = pr.drop(PRERENDER) fun addWidget(w: ProjectOverviewWidget) = children.add(children.size - numInitialBoxes, w) // Attempting to parallelize this didn't work: when interpreted it takes ~500msec to load a project. // When compiled it is 10x faster. So we're already blasting away on the other CPU cores to compile // this and if we do all builds in parallel, we end up slower not faster because every load takes 500msec :( for (project in immediate) timeIt("build project widget for ${project.title}") { addWidget(buildProjectWidget(project)) } // And do the rest in the background async(ui) { later.map { buildProjectWidget(it) } } success { for (widget in it) addWidget(widget) projects.addListener(ListChangeListener<Project> { change: ListChangeListener.Change<out Project> -> while (change.next()) when { change.wasReplaced() -> updateExistingProject(change.from, change.addedSubList[0]) change.wasAdded() -> slideInNewProject(change.addedSubList[0]) change.wasRemoved() -> // Cannot animate project remove yet. children.removeAt(children.size - 1 - numInitialBoxes - change.from) } }) } } @FXML fun addProjectClicked(event: ActionEvent) = EditProjectWindow.openForCreate() @FXML fun importClicked(event: ActionEvent) { val chooser = FileChooser() chooser.title = tr("Select a bitcoin project file to import") chooser.extensionFilters.add(FileChooser.ExtensionFilter(tr("Project/contract files"), "*" + LighthouseBackend.PROJECT_FILE_EXTENSION)) platformFiddleChooser(chooser) val file = chooser.showOpenDialog(Main.instance.mainStage) ?: return log.info("Import clicked: $file") importProject(file) } @FXML fun dragOver(event: DragEvent) { var accept = false if (event.gestureSource != null) return // Coming from us. for (file in event.dragboard.files) { val s = file.toString() if (s.endsWith(LighthouseBackend.PROJECT_FILE_EXTENSION) || s.endsWith(LighthouseBackend.PLEDGE_FILE_EXTENSION)) { accept = true break } } if (accept) event.acceptTransferModes(*TransferMode.COPY_OR_MOVE) } @FXML fun dragDropped(event: DragEvent) { log.info("Drop: {}", event) for (file in event.dragboard.files) handleOpenedFile(file) } public fun handleOpenedFile(file: File) { // Can be called either due to a drop, or user double clicking a file in a file explorer. // TODO: What happens if this is called whilst the overview isn't on screen? GuiUtils.checkGuiThread() log.info("Opening {}", file) when { file.toString().endsWith(LighthouseBackend.PROJECT_FILE_EXTENSION) -> importProject(file) file.toString().endsWith(LighthouseBackend.PLEDGE_FILE_EXTENSION) -> importPledge(file) else -> log.error("Unknown file type open requested: should not happen: " + file) } } public fun importPledge(file: File) { try { val hash = Sha256Hash.of(file) Files.copy(file.toPath(), AppDirectory.dir().resolve(hash.toString() + LighthouseBackend.PLEDGE_FILE_EXTENSION)) } catch (e: IOException) { GuiUtils.informationalAlert(tr("Import failed"), // TRANS: %1$s = app name, %2$s = error message tr("Could not copy the dropped pledge into the %1\$s application directory: %2\$s"), Main.APP_NAME, e) } } public fun importProject(file: File) { importProject(file.toPath()) } public fun importProject(file: Path) { try { Main.backend.importProjectFrom(file) } catch (e: Exception) { GuiUtils.informationalAlert(tr("Failed to import project"), // TRANS: %s = error message tr("Could not read project file: %s"), e.message) } } // Triggered by the projects list being touched by the backend. private fun updateExistingProject(index: Int, newProject: Project) { log.info("Update at index $index") val uiIndex = children.size - 1 - numInitialBoxes - index check(uiIndex >= 0) children.set(uiIndex, buildProjectWidget(newProject)) } private fun buildProjectWidget(project: Project): ProjectOverviewWidget { val state = SimpleObjectProperty(getProjectState(project)) val projectWidget: ProjectOverviewWidget // TODO: Fix this offline handling. if (Main.bitcoin.isOffline()) { state.set(LighthouseBackend.ProjectState.UNKNOWN) projectWidget = ProjectOverviewWidget(project, SimpleLongProperty(0), state) } else { projectStates.addListener(InvalidationListener { state.set(getProjectState(project)) }) projectWidget = ProjectOverviewWidget(project, Main.backend.makeTotalPledgedProperty(project, AffinityExecutor.UI_THREAD), state) projectWidget.styleClass.add("project-overview-widget-clickable") projectWidget.onCheckStatusChanged(checkStates.get(project)) checkStates.addListener(MapChangeListener<Project, LighthouseBackend.CheckStatus> { change -> if (change.key == project) projectWidget.onCheckStatusChanged(if (change.wasAdded()) change.valueAdded else null) }) projectWidget.addEventHandler<MouseEvent>(MouseEvent.MOUSE_CLICKED) { log.info("Switching to project: {}", project.title) val activity = ProjectActivity(projects, project, checkStates) MainWindow.navManager.navigate(activity) } } return projectWidget } // Triggered by the project disk model being adjusted. private fun slideInNewProject(project: Project) { val sp = MainWindow.navManager.scrollPane if (sp.vvalue != sp.vmin) { // Need to scroll to the top before dropping the project widget in. scrollToTop().setOnFinished() { slideInNewProject(project) } return } val projectWidget = buildProjectWidget(project) // Hack: Add at the end for the size calculation, then we'll move it to the start after the next frame. projectWidget.isVisible = false children.add(projectWidget) // Slide in from above. Platform.runLater() { var amount = projectWidget.height amount += spacing translateY = -amount val transition = TranslateTransition(Duration.millis(1500.0), this) transition.fromY = -amount transition.toY = 0.0 transition.interpolator = ElasticInterpolator(EasingMode.EASE_OUT) transition.delay = Duration.millis(1000.0) transition.play() // Re-position at the start. children.remove(projectWidget) children.add(0, projectWidget) projectWidget.isVisible = true } } private fun scrollToTop(): Animation { val animation = Timeline( KeyFrame( GuiUtils.UI_ANIMATION_TIME, KeyValue( MainWindow.navManager.scrollPane.vvalueProperty() as WritableValue<Any>, // KT-6581 MainWindow.navManager.scrollPane.vmin, Interpolator.EASE_BOTH ) ) ) animation.play() return animation } private fun getProjectState(p: Project) = projectStates[p.idHash]?.state ?: LighthouseBackend.ProjectState.OPEN override fun onStart() {} override fun onStop() {} private val log = LoggerFactory.getLogger(OverviewActivity::class.java) }
apache-2.0
76e68d9d92d4cb9eb9d8efa91fb3f3c0
40.144928
155
0.668897
4.553328
false
false
false
false
rinp/task
src/main/kotlin/todo/Entity.kt
1
3173
package task import org.hibernate.annotations.DynamicUpdate import org.hibernate.annotations.OptimisticLocking import org.hibernate.validator.constraints.NotBlank import org.springframework.data.annotation.CreatedDate import org.springframework.data.annotation.LastModifiedDate import org.springframework.data.jpa.domain.support.AuditingEntityListener import java.time.LocalDateTime import javax.persistence.* import javax.validation.constraints.DecimalMax import javax.validation.constraints.DecimalMin import javax.validation.constraints.Size /** * @author rinp * @since 2016/06/29 */ @Entity @DynamicUpdate @OptimisticLocking @EntityListeners(AuditingEntityListener::class) data class Task( @Id @GeneratedValue(strategy = GenerationType.AUTO) val id: Long = -1, @field:NotBlank(message = "内容は必須です。") val content: String = "", @Column(columnDefinition = "CLOB") val detail: String = "", var finished: Boolean = false, @CreatedDate var createDate: LocalDateTime = LocalDateTime.now(), @LastModifiedDate var updateDate: LocalDateTime = LocalDateTime.now(), @ManyToMany(fetch = FetchType.EAGER) @JoinColumn var tags: MutableList<Tag> = mutableListOf(), @Version var version: Long = -1, @ManyToOne(fetch = FetchType.EAGER) val creator: User = User(), @ManyToOne(fetch = FetchType.EAGER) var owner: User? = null, @field:DecimalMax("100", message = "優先度の最大値は100") @field:DecimalMin("0", message = "優先度の最小値は0") var priority: Int = 50, @ManyToMany(fetch = FetchType.EAGER, cascade = arrayOf(CascadeType.ALL)) var histories: MutableList<History> = mutableListOf() ) @Entity @DynamicUpdate data class Tag( @Id @GeneratedValue(strategy = GenerationType.AUTO) val id: Long = -1, @field:NotBlank(message = "名前は必須です。") val name: String = "", /** etc...#008080 */ @field:NotBlank(message = "色は必須です。") val color: String = "", val hide: Boolean = false ) @Entity @DynamicUpdate data class User( @Id @GeneratedValue(strategy = GenerationType.AUTO) val id: Long = -1, @field:NotBlank(message = "名前は必須です。") val name: String = "", @Column(unique = true) val host: String = "", val hide: Boolean = false, val admin: Boolean = false ) @Entity @DynamicUpdate data class History( @Id @GeneratedValue(strategy = GenerationType.AUTO) val id: Long = -1, @ManyToOne(fetch = FetchType.EAGER) val creator: User = User(), @Column(columnDefinition = "CLOB") val content: String = "" ) //@Entity //@DynamicUpdate //@OptimisticLocking //data class User( // @Id // @GeneratedValue // var id: String = "", // val name: String = "", // val host: String = "", // val ip: Int = -1, // var version: Long = -1 //) : Serializable
apache-2.0
75b76f3efbf86f3e58839a79138ec7a9
23.436508
80
0.627476
3.967784
false
false
false
false
cdietze/klay
tripleklay/src/main/kotlin/tripleklay/util/Deflater.kt
1
3306
package tripleklay.util import klay.core.assert /** * Encodes typed data into a string. This is the deflating counterpart to [Inflater]. */ class Deflater : Conflater() { fun addBool(value: Boolean): Deflater { addChar(if (value) 't' else 'f') return this } fun addChar(c: Char): Deflater { _buf.append(c) return this } fun addNibble(value: Int): Deflater { check(value, 0, 0xF, "Nibble") _buf.append(Conflater.toHexString(value, 1)) return this } fun addByte(value: Int): Deflater { check(value, Byte.MIN_VALUE.toInt(), Byte.MAX_VALUE.toInt(), "Byte") _buf.append(Conflater.toHexString(value, 2)) return this } fun addShort(value: Int): Deflater { check(value, Short.MIN_VALUE.toInt(), Short.MAX_VALUE.toInt(), "Short") _buf.append(Conflater.toHexString(value, 4)) return this } fun addInt(value: Int): Deflater { _buf.append(Conflater.toHexString(value, 8)) return this } fun addVarInt(value: Int): Deflater { var value = value assert(value > Int.MIN_VALUE) { "Can't use varint for Int.MIN_VALUE" } if (value < 0) { _buf.append(Conflater.NEG_MARKER) value *= -1 } addVarInt(value, false) return this } fun addVarLong(value: Long): Deflater { var value = value assert(value > Long.MIN_VALUE) { "Can't use varlong for Long.MIN_VALUE" } if (value < 0) { _buf.append(Conflater.NEG_MARKER) value *= -1 } addVarLong(value, false) return this } fun addBitVec(value: BitVec): Deflater { // find the index of the highest non-zero word val words = value._words var wc = 0 for (ii in words.indices.reversed()) { if (words[ii] == 0) continue wc = ii + 1 break } // now write out the number of words and their contents addVarInt(wc) for (ii in 0..wc - 1) addInt(words[ii]) return this } fun addFLString(value: String): Deflater { _buf.append(value) return this } fun addString(value: String): Deflater { addShort(value.length) _buf.append(value) return this } fun <E : Enum<E>> addEnum(value: E): Deflater { return addString(value.name) } fun encoded(): String { return _buf.toString() } fun reset(): Deflater { _buf = StringBuilder() return this } protected fun addVarInt(value: Int, cont: Boolean) { if (value >= Conflater.BASE) addVarInt(value / Conflater.BASE, true) _buf.append((if (cont) Conflater.VARCONT else Conflater.VARABS)[value % Conflater.BASE]) } protected fun addVarLong(value: Long, cont: Boolean) { if (value >= Conflater.BASE) addVarLong(value / Conflater.BASE, true) _buf.append((if (cont) Conflater.VARCONT else Conflater.VARABS)[(value % Conflater.BASE).toInt()]) } protected fun check(value: Int, min: Int, max: Int, type: String) { assert(value >= min && value <= max) { "$type must be $min <= n <= $max" } } protected var _buf = StringBuilder() }
apache-2.0
809804beb0ba832bd7b66be1635c3c3d
27.016949
106
0.573503
3.752554
false
false
false
false
frc2052/FRC-Krawler
app/src/main/kotlin/com/team2052/frckrawler/metric/types/IntegerMetricTypeEntry.kt
1
2408
package com.team2052.frckrawler.metric.types import android.view.View import com.google.gson.JsonObject import com.team2052.frckrawler.database.metric.CompiledMetricValue import com.team2052.frckrawler.database.metric.MetricValue import com.team2052.frckrawler.db.Metric import com.team2052.frckrawler.db.Robot import com.team2052.frckrawler.metric.MetricTypeEntry import com.team2052.frckrawler.tba.JSON import com.team2052.frckrawler.util.MetricHelper import com.team2052.frckrawler.metrics.view.MetricWidget open class IntegerMetricType<out W : MetricWidget>(widgetType: Class<W>) : MetricTypeEntry<W>(widgetType) { override fun convertValueToString(value: JsonObject): String { return value.get("value").asDouble.toString() } override fun compileValues(robot: Robot, metric: Metric, metricData: List<MetricValue>, compileWeight: Double): JsonObject { var numerator = 0.0 var denominator = 0.0 val compiledValue = JsonObject() if (metricData.isEmpty()) { compiledValue.addProperty("value", 0.0) return compiledValue } for (metricValue in metricData) { val result = MetricHelper.getIntMetricValue(metricValue) if (result.t2.isError) continue val weight = CompiledMetricValue.getCompileWeightForMatchNumber(metricValue, metricData, compileWeight) numerator += result.t1 * weight denominator += weight } val value = CompiledMetricValue.format.format(numerator / denominator) compiledValue.addProperty("value", value) return compiledValue } override fun buildMetric(name: String, min: Int?, max: Int?, inc: Int?, commaList: List<String>?): MetricHelper.MetricFactory { val metricFactory = MetricHelper.MetricFactory(name) metricFactory.setMetricType(this.typeId) metricFactory.setDataMinMaxInc(min!!, max!!, inc) return metricFactory } override fun addInfo(metric: Metric, info: MutableMap<String, String>) { val data = JSON.getAsJsonObject(metric.data) info.put("Minimum", data.get("min").toString()) info.put("Maximum", data.get("max").toString()) } override fun commaListVisibility(): Int = View.GONE override fun maximumVisibility(): Int = View.VISIBLE override fun minimumVisibility(): Int = View.VISIBLE }
mit
3c7daa50adafb21e15abb88cb2626395
39.15
131
0.70515
4.451017
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/postfix/surrounderBasedPostfixTemplates.kt
5
2768
// 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.codeInsight.postfix import com.intellij.codeInsight.template.postfix.templates.SurroundPostfixTemplateBase import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.codeInsight.surroundWith.expression.KotlinWhenSurrounder import org.jetbrains.kotlin.idea.codeInsight.surroundWith.expression.KotlinWithIfExpressionSurrounder import org.jetbrains.kotlin.idea.codeInsight.surroundWith.statement.KotlinTryCatchSurrounder import org.jetbrains.kotlin.idea.intentions.negate import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.typeUtil.isBoolean internal object KtIfExpressionPostfixTemplate : SurroundPostfixTemplateBase( "if", "if (expr)", KtPostfixTemplatePsiInfo, createExpressionSelector { it.isBoolean() } ) { override fun getSurrounder() = KotlinWithIfExpressionSurrounder(withElse = false) } internal object KtElseExpressionPostfixTemplate : SurroundPostfixTemplateBase( "else", "if (!expr)", KtPostfixTemplatePsiInfo, createExpressionSelector { it.isBoolean() } ) { override fun getSurrounder() = KotlinWithIfExpressionSurrounder(withElse = false) override fun getWrappedExpression(expression: PsiElement?) = (expression as KtExpression).negate() } internal class KtNotNullPostfixTemplate(val name: String) : SurroundPostfixTemplateBase( name, "if (expr != null)", KtPostfixTemplatePsiInfo, createExpressionSelector(typePredicate = TypeUtils::isNullableType) ) { override fun getSurrounder() = KotlinWithIfExpressionSurrounder(withElse = false) override fun getTail() = "!= null" } internal object KtIsNullPostfixTemplate : SurroundPostfixTemplateBase( "null", "if (expr == null)", KtPostfixTemplatePsiInfo, createExpressionSelector(typePredicate = TypeUtils::isNullableType) ) { override fun getSurrounder() = KotlinWithIfExpressionSurrounder(withElse = false) override fun getTail() = "== null" } internal object KtWhenExpressionPostfixTemplate : SurroundPostfixTemplateBase( "when", "when (expr)", KtPostfixTemplatePsiInfo, createExpressionSelector() ) { override fun getSurrounder() = KotlinWhenSurrounder() } internal object KtTryPostfixTemplate : SurroundPostfixTemplateBase( "try", "try { code } catch (e: Exception) { }", KtPostfixTemplatePsiInfo, createExpressionSelector( checkCanBeUsedAsValue = false, // Do not suggest 'val x = try { init } catch (e: Exception) { }' statementsOnly = true ) ) { override fun getSurrounder() = KotlinTryCatchSurrounder() }
apache-2.0
6b35b59d354e26055f019aaec937c788
42.25
158
0.780347
4.805556
false
false
false
false
zbeboy/ISY
src/main/java/top/zbeboy/isy/web/vo/graduate/design/project/GraduationDesignProjectAddVo.kt
1
621
package top.zbeboy.isy.web.vo.graduate.design.project import javax.validation.constraints.NotNull import javax.validation.constraints.Size /** * Created by zbeboy 2018-01-22 . **/ open class GraduationDesignProjectAddVo { @NotNull @Size(max = 64) var graduationDesignReleaseId: String? = null @NotNull @Size(max = 100) var scheduling: String? = null @NotNull @Size(max = 100) var supervisionTime: String? = null @NotNull @Size(max = 150) var guideContent: String? = null @Size(max = 100) var note: String? = null @NotNull var schoolroomId: Int? = null }
mit
c7406d324a3160d54450e27dd5142c93
22.923077
53
0.671498
3.696429
false
false
false
false
MGaetan89/ShowsRage
app/src/main/kotlin/com/mgaetan89/showsrage/adapter/HistoriesAdapter.kt
1
2727
package com.mgaetan89.showsrage.adapter import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import com.mgaetan89.showsrage.R import com.mgaetan89.showsrage.extension.inflate import com.mgaetan89.showsrage.extension.toLocale import com.mgaetan89.showsrage.extension.toRelativeDate import com.mgaetan89.showsrage.helper.ImageLoader import com.mgaetan89.showsrage.model.History import com.mgaetan89.showsrage.presenter.HistoryPresenter import io.realm.RealmRecyclerViewAdapter import io.realm.RealmResults import kotlinx.android.synthetic.main.adapter_histories_list_content.view.episode_date import kotlinx.android.synthetic.main.adapter_histories_list_content.view.episode_logo import kotlinx.android.synthetic.main.adapter_histories_list_content.view.episode_name import kotlinx.android.synthetic.main.adapter_histories_list_content.view.episode_provider_quality class HistoriesAdapter(histories: RealmResults<History>) : RealmRecyclerViewAdapter<History, HistoriesAdapter.ViewHolder>(histories, true) { override fun onBindViewHolder(holder: ViewHolder, position: Int) { val history = this.getItem(position)?.takeIf { it.isValid } ?: return holder.bind(history) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = parent.inflate(R.layout.adapter_histories_list) return ViewHolder(view) } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { private val date = view.episode_date private val logo = view.episode_logo private val name = view.episode_name private val providerQuality = view.episode_provider_quality init { this.name.isSelected = true } fun bind(history: History) { val context = this.itemView.context val presenter = HistoryPresenter(history) val status = history.getStatusTranslationResource() val statusString = if (status != 0) context.getString(status) else history.status this.date.text = context.getString(R.string.spaced_texts, statusString, history.date.toRelativeDate("yyyy-MM-dd hh:mm", 0).toString().toLowerCase()) if ("subtitled".equals(history.status, true)) { val language = history.resource?.toLocale()?.displayLanguage if (!language.isNullOrEmpty()) { this.date.append(" [$language]") } } this.logo.contentDescription = presenter.getShowName() ImageLoader.load(this.logo, presenter.getPosterUrl(), true) this.name.text = context.getString(R.string.show_name_episode, presenter.getShowName(), presenter.getSeason(), presenter.getEpisode()) this.providerQuality.text = presenter.getProviderQuality() ?: context.getString(R.string.provider_quality, presenter.getProvider(), presenter.getQuality()) } } }
apache-2.0
06559724ee64c761bf4f3829fbae520d
39.701493
158
0.785845
3.824684
false
false
false
false
Zeyad-37/RxRedux
core/src/main/java/com/zeyad/rxredux/core/v2/ViewModelListener.kt
1
906
package com.zeyad.rxredux.core.v2 interface ViewModelListener<S : State, E : Effect> { var effects: (effect: E) -> Unit var states: (state: S) -> Unit var errors: (error: Error) -> Unit var progress: (progress: Progress) -> Unit } class ViewModelListenerHelper<S : State, E : Effect> : ViewModelListener<S, E> { override var effects: (effect: E) -> Unit = {} override var states: (state: S) -> Unit = {} override var progress: (progress: Progress) -> Unit = {} override var errors: (error: Error) -> Unit = {} fun errors(errors: (error: Error) -> Unit) { this.errors = errors } fun effects(effects: (effect: Effect) -> Unit) { this.effects = effects } fun states(states: (state: State) -> Unit) { this.states = states } fun progress(progress: (progress: Progress) -> Unit) { this.progress = progress } }
apache-2.0
3b45176b471dcf7f4fb888cc2fca5222
28.225806
80
0.603753
3.682927
false
false
false
false
PaulWoitaschek/MaterialAudiobookPlayer
app/src/main/java/de/ph1b/audiobook/features/audio/Equalizer.kt
1
1497
package de.ph1b.audiobook.features.audio import android.app.Activity import android.content.Context import android.content.Intent import android.media.audiofx.AudioEffect import timber.log.Timber import javax.inject.Inject import javax.inject.Singleton /** * The equalizer. Delegates to the system integrated equalizer */ @Singleton class Equalizer @Inject constructor( private val context: Context ) { private val launchIntent = Intent(AudioEffect.ACTION_DISPLAY_AUDIO_EFFECT_CONTROL_PANEL).apply { putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.packageName) putExtra(AudioEffect.EXTRA_CONTENT_TYPE, AudioEffect.CONTENT_TYPE_MUSIC) } private val updateIntent = Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION).apply { putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.packageName) putExtra(AudioEffect.EXTRA_CONTENT_TYPE, AudioEffect.CONTENT_TYPE_MUSIC) } val exists = context.packageManager.resolveActivity(launchIntent, 0) != null private fun Intent.putAudioSessionId(audioSessionId: Int) { putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId) } fun update(audioSessionId: Int) { Timber.i("update to $audioSessionId") if (audioSessionId == -1) return updateIntent.putAudioSessionId(audioSessionId) launchIntent.putAudioSessionId(audioSessionId) context.sendBroadcast(updateIntent) } fun launch(activity: Activity) { Timber.i("launch") activity.startActivityForResult(launchIntent, 12) } }
lgpl-3.0
79b690dfeb6572ee906f2e6237e3f525
30.851064
98
0.776219
4.135359
false
false
false
false
google/intellij-community
plugins/kotlin/completion/tests-k1/test/org/jetbrains/kotlin/idea/completion/test/AbstractCompletionIncrementalResolveTest31.kt
2
4676
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion.test import com.intellij.codeInsight.completion.CompletionType import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import org.jetbrains.kotlin.idea.completion.CompletionBindingContextProvider import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils import org.jetbrains.kotlin.idea.test.KotlinTestUtils import java.io.File abstract class AbstractCompletionIncrementalResolveTest31 : KotlinLightCodeInsightFixtureTestCase() { private val BEFORE_MARKER = "<before>" // position to invoke completion before private val CHANGE_MARKER = "<change>" // position to insert text specified by "TYPE" directive private val TYPE_DIRECTIVE_PREFIX = "// TYPE:" private val BACKSPACES_DIRECTIVE_PREFIX = "// BACKSPACES:" override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE protected fun doTest(testPath: String) { CompletionBindingContextProvider.ENABLED = true try { val file = File(testPath) val hasCaretMarker = FileUtil.loadFile(file, true).contains("<caret>") myFixture.configureByFile(fileName()) val document = myFixture.editor.document val beforeMarkerOffset = document.text.indexOf(BEFORE_MARKER) assertTrue("\"$BEFORE_MARKER\" is missing in file \"$testPath\"", beforeMarkerOffset >= 0) val changeMarkerOffset = document.text.indexOf(CHANGE_MARKER) assertTrue("\"$CHANGE_MARKER\" is missing in file \"$testPath\"", changeMarkerOffset >= 0) val textToType = InTextDirectivesUtils.findArrayWithPrefixes(document.text, TYPE_DIRECTIVE_PREFIX).singleOrNull() ?.let { StringUtil.unquoteString(it) } val backspaceCount = InTextDirectivesUtils.getPrefixedInt(document.text, BACKSPACES_DIRECTIVE_PREFIX) assertTrue( "At least one of \"$TYPE_DIRECTIVE_PREFIX\" and \"$BACKSPACES_DIRECTIVE_PREFIX\" should be defined", textToType != null || backspaceCount != null ) val beforeMarker = document.createRangeMarker(beforeMarkerOffset, beforeMarkerOffset + BEFORE_MARKER.length) val changeMarker = document.createRangeMarker(changeMarkerOffset, changeMarkerOffset + CHANGE_MARKER.length) changeMarker.isGreedyToRight = true project.executeWriteCommand("") { document.deleteString(beforeMarker.startOffset, beforeMarker.endOffset) document.deleteString(changeMarker.startOffset, changeMarker.endOffset) } val caretMarker = if (hasCaretMarker) document.createRangeMarker(editor.caretModel.offset, editor.caretModel.offset) else null editor.caretModel.moveToOffset(beforeMarker.startOffset) val testLog = StringBuilder() CompletionBindingContextProvider.getInstance(project).TEST_LOG = testLog myFixture.complete(CompletionType.BASIC) project.executeWriteCommand("") { if (backspaceCount != null) { document.deleteString(changeMarker.startOffset - backspaceCount, changeMarker.startOffset) } if (textToType != null) { document.insertString(changeMarker.startOffset, textToType) } } if (caretMarker != null) { editor.caretModel.moveToOffset(caretMarker.startOffset) } else { editor.caretModel.moveToOffset(changeMarker.endOffset) } testCompletion( FileUtil.loadFile(file, true), JvmPlatforms.unspecifiedJvmPlatform, { completionType, count -> myFixture.complete(completionType, count) }, additionalValidDirectives = listOf(TYPE_DIRECTIVE_PREFIX, BACKSPACES_DIRECTIVE_PREFIX) ) KotlinTestUtils.assertEqualsToFile(File(file.parent, file.nameWithoutExtension + ".log"), testLog.toString()) } finally { CompletionBindingContextProvider.ENABLED = false } } }
apache-2.0
755e63adff4a3478e08f8fedf01da81c
48.755319
158
0.687767
5.481829
false
true
false
false
google/intellij-community
platform/configuration-store-impl/src/ProjectStoreImpl.kt
3
8776
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.configurationStore import com.intellij.ide.highlighter.ProjectFileType import com.intellij.openapi.application.EDT import com.intellij.openapi.components.PathMacroManager import com.intellij.openapi.components.impl.stores.IComponentStore import com.intellij.openapi.components.impl.stores.IProjectStore import com.intellij.openapi.diagnostic.getOrLogException import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ex.ProjectNameProvider import com.intellij.openapi.project.impl.ProjectStoreFactory import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.ReadonlyStatusHandler import com.intellij.openapi.vfs.VirtualFile import com.intellij.serviceContainer.ComponentManagerImpl import com.intellij.util.io.delete import com.intellij.util.io.isDirectory import com.intellij.util.io.write import com.intellij.workspaceModel.ide.getJpsProjectConfigLocation import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsFileContentReaderWithCache import com.intellij.workspaceModel.ide.impl.jps.serialization.ProjectStoreWithJpsContentReader import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.CalledInAny import org.jetbrains.jps.util.JpsPathUtil import java.nio.file.AccessDeniedException import java.nio.file.Path @ApiStatus.Internal open class ProjectStoreImpl(project: Project) : ProjectStoreBase(project) { private var lastSavedProjectName: String? = null protected val moduleSavingCustomizer: ModuleSavingCustomizer = ProjectStoreBridge(project) init { assert(!project.isDefault) } override val serviceContainer: ComponentManagerImpl get() = project as ComponentManagerImpl final override fun getPathMacroManagerForDefaults() = PathMacroManager.getInstance(project) override val storageManager = ProjectStateStorageManager(TrackingPathMacroSubstitutorImpl(PathMacroManager.getInstance(project)), project) override fun setPath(path: Path) { setPath(path, true, null) } override fun getProjectName(): String { if (!isDirectoryBased) { return storageManager.expandMacro(PROJECT_FILE).fileName.toString().removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION) } val projectDir = directoryStorePath!! val storedName = JpsPathUtil.readProjectName(projectDir) if (storedName != null) { lastSavedProjectName = storedName return storedName } for (projectNameProvider in ProjectNameProvider.EP_NAME.iterable) { runCatching { projectNameProvider.getDefaultName(project) } .getOrLogException(LOG) ?.let { return it } } return JpsPathUtil.getDefaultProjectName(projectDir) } private suspend fun saveProjectName() { if (!isDirectoryBased) { return } val currentProjectName = project.name if (lastSavedProjectName == currentProjectName) { return } lastSavedProjectName = currentProjectName val basePath = projectBasePath fun doSave() { if (currentProjectName == basePath.fileName?.toString()) { // name equals to base path name - just remove name getNameFile().delete() } else if (basePath.isDirectory()) { getNameFile().write(currentProjectName.toByteArray()) } } try { doSave() } catch (e: AccessDeniedException) { val status = ensureFilesWritable(project, listOf(LocalFileSystem.getInstance().refreshAndFindFileByNioFile(getNameFile())!!)) if (status.hasReadonlyFiles()) { throw e } doSave() } } final override suspend fun doSave(result: SaveResult, forceSavingAllSettings: Boolean) { coroutineScope { launch { // save modules before project val saveSessionManager = createSaveSessionProducerManager() val moduleSaveSessions = saveModules(result, forceSavingAllSettings, saveSessionManager) saveSettingsSavingComponentsAndCommitComponents(result, forceSavingAllSettings, saveSessionManager) saveSessionManager .saveWithAdditionalSaveSessions(moduleSaveSessions) .appendTo(result) } launch { try { saveProjectName() } catch (e: Throwable) { LOG.error("Unable to store project name", e) } } } } protected open suspend fun saveModules(result: SaveResult, isForceSavingAllSettings: Boolean, projectSaveSessionManager: SaveSessionProducerManager): List<SaveSession> { return emptyList() } final override fun createSaveSessionProducerManager(): ProjectSaveSessionProducerManager { return moduleSavingCustomizer.createSaveSessionProducerManager() } final override fun commitObsoleteComponents(session: SaveSessionProducerManager, isProjectLevel: Boolean) { if (isDirectoryBased) { super.commitObsoleteComponents(session, true) } } } @ApiStatus.Internal interface ModuleSavingCustomizer { fun createSaveSessionProducerManager(): ProjectSaveSessionProducerManager fun saveModules(projectSaveSessionManager: SaveSessionProducerManager, store: IProjectStore) fun commitModuleComponents(projectSaveSessionManager: SaveSessionProducerManager, moduleStore: ComponentStoreImpl, moduleSaveSessionManager: SaveSessionProducerManager) } @ApiStatus.Internal open class ProjectWithModulesStoreImpl(project: Project) : ProjectStoreImpl(project), ProjectStoreWithJpsContentReader { final override suspend fun saveModules(result: SaveResult, isForceSavingAllSettings: Boolean, projectSaveSessionManager: SaveSessionProducerManager): List<SaveSession> { moduleSavingCustomizer.saveModules(projectSaveSessionManager, this) val modules = ModuleManager.getInstance(project)?.modules ?: Module.EMPTY_ARRAY if (modules.isEmpty()) { return emptyList() } return withContext(Dispatchers.EDT) { // do not create with capacity because very rarely a lot of modules will be modified val saveSessions = ArrayList<SaveSession>() // commit components for (module in modules) { val moduleStore = module.getService(IComponentStore::class.java) as? ComponentStoreImpl ?: continue // collectSaveSessions is very cheap, so, do it in EDT val saveManager = moduleStore.createSaveSessionProducerManager() commitModuleComponents(moduleStore, saveManager, projectSaveSessionManager, isForceSavingAllSettings, result) saveManager.collectSaveSessions(saveSessions) } saveSessions } } override fun createContentReader(): JpsFileContentReaderWithCache { return StorageJpsConfigurationReader(project, getJpsProjectConfigLocation(project)!!) } private fun commitModuleComponents(moduleStore: ComponentStoreImpl, moduleSaveSessionManager: SaveSessionProducerManager, projectSaveSessionManager: SaveSessionProducerManager, isForceSavingAllSettings: Boolean, saveResult: SaveResult) { moduleStore.commitComponents(isForceSavingAllSettings, moduleSaveSessionManager, saveResult) moduleSavingCustomizer.commitModuleComponents(projectSaveSessionManager, moduleStore, moduleSaveSessionManager) } } abstract class ProjectStoreFactoryImpl : ProjectStoreFactory { final override fun createDefaultProjectStore(project: Project): IComponentStore = DefaultProjectStoreImpl(project) } internal class PlatformLangProjectStoreFactory : ProjectStoreFactoryImpl() { override fun createStore(project: Project): IProjectStore { LOG.assertTrue(!project.isDefault) return ProjectWithModulesStoreImpl(project) } } internal class PlatformProjectStoreFactory : ProjectStoreFactoryImpl() { override fun createStore(project: Project): IProjectStore { LOG.assertTrue(!project.isDefault) return ProjectStoreImpl(project) } } @CalledInAny internal suspend fun ensureFilesWritable(project: Project, files: Collection<VirtualFile>): ReadonlyStatusHandler.OperationStatus { return withContext(Dispatchers.EDT) { ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(files) } }
apache-2.0
4e30d1536d20d9c683fe95ac688a1be3
37.836283
140
0.745784
5.536909
false
false
false
false
dzharkov/intellij-markdown
src/org/intellij/markdown/parser/sequentialparsers/impl/BacktickParser.kt
1
2397
package org.intellij.markdown.parser.sequentialparsers.impl import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.parser.sequentialparsers.SequentialParser import org.intellij.markdown.parser.sequentialparsers.SequentialParserUtil import org.intellij.markdown.parser.sequentialparsers.TokensCache import java.util.ArrayList public class BacktickParser : SequentialParser { override fun parse(tokens: TokensCache, rangesToGlue: Collection<Range<Int>>): SequentialParser.ParsingResult { val result = SequentialParser.ParsingResult() val indices = SequentialParserUtil.textRangesToIndices(rangesToGlue) val delegateIndices = ArrayList<Int>() var i = 0 while (i < indices.size()) { val iterator = tokens.ListIterator(indices, i) if (iterator.type == MarkdownTokenTypes.BACKTICK || iterator.type == MarkdownTokenTypes.ESCAPED_BACKTICKS) { val j = findOfSize(tokens, indices, i + 1, getLength(iterator, true)) if (j != -1) { result.withNode(SequentialParser.Node(indices.get(i)..indices.get(j) + 1, MarkdownElementTypes.CODE_SPAN)) i = j + 1 continue } } delegateIndices.add(indices.get(i)) ++i } return result.withFurtherProcessing(SequentialParserUtil.indicesToTextRanges(delegateIndices)) } private fun findOfSize(tokens: TokensCache, indices: List<Int>, from: Int, length: Int): Int { for (i in from..indices.size() - 1) { val iterator = tokens.ListIterator(indices, i) if (iterator.type != MarkdownTokenTypes.BACKTICK && iterator.type != MarkdownTokenTypes.ESCAPED_BACKTICKS) { continue } if (getLength(iterator, false) == length) { return i } } return -1 } private fun getLength(info: TokensCache.Iterator, canEscape: Boolean): Int { val tokenText = info.text var toSubtract = 0 if (info.type == MarkdownTokenTypes.ESCAPED_BACKTICKS) { if (canEscape) { toSubtract = 2 } else { toSubtract = 1 } } return tokenText.length() - toSubtract } }
apache-2.0
8a3e2ec87fbb415a5667b65c035240de
35.318182
126
0.627034
4.794
false
false
false
false
google/intellij-community
platform/analysis-impl/src/com/intellij/profile/codeInspection/ProjectInspectionProfileManager.kt
10
9835
// 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.profile.codeInspection import com.intellij.codeInspection.ex.InspectionProfileImpl import com.intellij.codeInspection.ex.InspectionToolRegistrar import com.intellij.configurationStore.* import com.intellij.diagnostic.runActivity import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.packageDependencies.DependencyValidationManager import com.intellij.profile.ProfileChangeAdapter import com.intellij.project.isDirectoryBased import com.intellij.psi.search.scope.packageSet.NamedScopeManager import com.intellij.psi.search.scope.packageSet.NamedScopesHolder import com.intellij.util.getAttributeBooleanValue import com.intellij.util.xmlb.annotations.OptionTag import org.jdom.Element import org.jetbrains.annotations.TestOnly import java.util.function.Function private const val VERSION = "1.0" private const val PROJECT_DEFAULT_PROFILE_NAME = "Project Default" private val defaultSchemeDigest = JDOMUtil.load("""<component name="InspectionProjectProfileManager"> <profile version="1.0"> <option name="myName" value="Project Default" /> </profile> </component>""").digest() const val PROFILE_DIR = "inspectionProfiles" @State(name = "InspectionProjectProfileManager", storages = [(Storage(value = "$PROFILE_DIR/profiles_settings.xml", exclusive = true))]) open class ProjectInspectionProfileManager(val project: Project) : BaseInspectionProfileManager(project.messageBus), PersistentStateComponentWithModificationTracker<Element>, Disposable { companion object { @JvmStatic fun getInstance(project: Project): ProjectInspectionProfileManager { return project.getService(InspectionProjectProfileManager::class.java) as ProjectInspectionProfileManager } } private var state = ProjectInspectionProfileManagerState() private val schemeManagerIprProvider = if (project.isDirectoryBased) null else SchemeManagerIprProvider("profile") override val schemeManager = SchemeManagerFactory.getInstance(project).create(PROFILE_DIR, object : InspectionProfileProcessor() { override fun createScheme(dataHolder: SchemeDataHolder<InspectionProfileImpl>, name: String, attributeProvider: Function<in String, String?>, isBundled: Boolean): InspectionProfileImpl { val profile = InspectionProfileImpl(name, InspectionToolRegistrar.getInstance(), this@ProjectInspectionProfileManager, dataHolder) profile.isProjectLevel = true return profile } override fun isSchemeFile(name: CharSequence) = !StringUtil.equals(name, "profiles_settings.xml") override fun isSchemeDefault(scheme: InspectionProfileImpl, digest: ByteArray): Boolean { return scheme.name == PROJECT_DEFAULT_PROFILE_NAME && digest.contentEquals(defaultSchemeDigest) } override fun onSchemeDeleted(scheme: InspectionProfileImpl) { schemeRemoved(scheme) } override fun onSchemeAdded(scheme: InspectionProfileImpl) { if (scheme.wasInitialized()) { fireProfileChanged(scheme) } } override fun onCurrentSchemeSwitched(oldScheme: InspectionProfileImpl?, newScheme: InspectionProfileImpl?, processChangeSynchronously: Boolean) { project.messageBus.syncPublisher(ProfileChangeAdapter.TOPIC).profileActivated(oldScheme, newScheme) } }, schemeNameToFileName = OLD_NAME_CONVERTER, streamProvider = schemeManagerIprProvider) override fun initializeComponent() { val app = ApplicationManager.getApplication() if (!project.isDirectoryBased || app.isUnitTestMode) { return } runActivity("project inspection profile loading") { schemeManager.loadSchemes() currentProfile.initInspectionTools(project) } StartupManager.getInstance(project).runAfterOpened { project.messageBus.syncPublisher(ProfileChangeAdapter.TOPIC).profilesInitialized() val projectScopeListener = NamedScopesHolder.ScopeListener { for (profile in schemeManager.allSchemes) { profile.scopesChanged() } } scopesManager.addScopeListener(projectScopeListener, project) NamedScopeManager.getInstance(project).addScopeListener(projectScopeListener, project) } } override fun dispose() { val cleanupInspectionProfilesRunnable = { cleanupSchemes(project) (serviceIfCreated<InspectionProfileManager>() as BaseInspectionProfileManager?)?.cleanupSchemes(project) } val app = ApplicationManager.getApplication() if (app.isUnitTestMode || app.isHeadlessEnvironment) { cleanupInspectionProfilesRunnable.invoke() } else { app.executeOnPooledThread(cleanupInspectionProfilesRunnable) } } override fun getStateModificationCount() = state.modificationCount + severityRegistrar.modificationCount + (schemeManagerIprProvider?.modificationCount ?: 0) @TestOnly fun forceLoadSchemes() { LOG.assertTrue(ApplicationManager.getApplication().isUnitTestMode) schemeManager.loadSchemes() } fun isCurrentProfileInitialized() = currentProfile.wasInitialized() override fun schemeRemoved(scheme: InspectionProfileImpl) { scheme.cleanup(project) } @Synchronized override fun getState(): Element? { val result = Element("settings") schemeManagerIprProvider?.writeState(result) serializeObjectInto(state, result) if (result.children.isNotEmpty()) { result.addContent(Element("version").setAttribute("value", VERSION)) } severityRegistrar.writeExternal(result) return wrapState(result, project) } @Synchronized override fun loadState(state: Element) { val data = unwrapState(state, project, schemeManagerIprProvider, schemeManager) val newState = ProjectInspectionProfileManagerState() data?.let { try { severityRegistrar.readExternal(it) } catch (e: Throwable) { LOG.error(e) } it.deserializeInto(newState) } this.state = newState if (data != null && data.getChild("version")?.getAttributeValue("value") != VERSION) { for (o in data.getChildren("option")) { if (o.getAttributeValue("name") == "USE_PROJECT_LEVEL_SETTINGS") { if (o.getAttributeBooleanValue("value") && newState.projectProfile != null) { currentProfile.convert(data, project) } break } } } } override fun getScopesManager() = DependencyValidationManager.getInstance(project) @Synchronized override fun getProfiles(): Collection<InspectionProfileImpl> { currentProfile return schemeManager.allSchemes } val projectProfile: String? get() = state.projectProfile @Synchronized override fun setRootProfile(name: String?) { state.useProjectProfile = name != null if (name != null) { state.projectProfile = name } schemeManager.setCurrentSchemeName(name, true) } @Synchronized fun useApplicationProfile(name: String) { state.useProjectProfile = false // yes, we reuse the same field - useProjectProfile field will be used to distinguish - is it app or project level // to avoid data format change state.projectProfile = name } @Synchronized @TestOnly fun setCurrentProfile(profile: InspectionProfileImpl?) { schemeManager.setCurrent(profile) state.useProjectProfile = profile != null if (profile != null) { state.projectProfile = profile.name } } @Synchronized override fun getCurrentProfile(): InspectionProfileImpl { if (!state.useProjectProfile) { val applicationProfileManager = InspectionProfileManager.getInstance() return (state.projectProfile?.let { applicationProfileManager.getProfile(it, false) } ?: applicationProfileManager.currentProfile) } var currentScheme = state.projectProfile?.let { schemeManager.findSchemeByName(it) } if (currentScheme == null) { currentScheme = schemeManager.allSchemes.firstOrNull() if (currentScheme == null) { currentScheme = InspectionProfileImpl(PROJECT_DEFAULT_PROFILE_NAME, InspectionToolRegistrar.getInstance(), this) currentScheme.copyFrom(InspectionProfileManager.getInstance().currentProfile) currentScheme.isProjectLevel = true currentScheme.name = PROJECT_DEFAULT_PROFILE_NAME schemeManager.addScheme(currentScheme) } schemeManager.setCurrent(currentScheme, false) } return currentScheme } @Synchronized override fun getProfile(name: String, returnRootProfileIfNamedIsAbsent: Boolean): InspectionProfileImpl? { val profile = schemeManager.findSchemeByName(name) return profile ?: InspectionProfileManager.getInstance().getProfile(name, returnRootProfileIfNamedIsAbsent) } fun fireProfileChanged() { fireProfileChanged(currentProfile) } override fun fireProfileChanged(profile: InspectionProfileImpl) { profile.profileChanged() project.messageBus.syncPublisher(ProfileChangeAdapter.TOPIC).profileChanged(profile) } } private class ProjectInspectionProfileManagerState : BaseState() { @get:OptionTag("PROJECT_PROFILE") var projectProfile by string(PROJECT_DEFAULT_PROFILE_NAME) @get:OptionTag("USE_PROJECT_PROFILE") var useProjectProfile by property(true) }
apache-2.0
7264065abfd490cfd1d0e7f41da0328a
35.561338
187
0.742044
5.36845
false
false
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.kt
1
20350
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("OVERRIDE_DEPRECATION") package com.intellij.ide.startup.impl import com.intellij.diagnostic.* import com.intellij.diagnostic.telemetry.TraceManager import com.intellij.diagnostic.telemetry.useWithScope import com.intellij.diagnostic.telemetry.useWithScope2 import com.intellij.ide.IdeEventQueue import com.intellij.ide.lightEdit.LightEdit import com.intellij.ide.lightEdit.LightEditCompatible import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.cl.PluginAwareClassLoader import com.intellij.ide.startup.StartupManagerEx import com.intellij.openapi.application.* import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionPointListener import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl import com.intellij.openapi.progress.* import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.DumbAwareRunnable import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.project.impl.isCorePlugin import com.intellij.openapi.startup.InitProjectActivity import com.intellij.openapi.startup.ProjectPostStartupActivity import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.util.registry.Registry import com.intellij.serviceContainer.AlreadyDisposedException import com.intellij.util.ModalityUiUtil import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import io.opentelemetry.context.Context import io.opentelemetry.extension.kotlin.asContextElement import kotlinx.coroutines.* import org.intellij.lang.annotations.MagicConstant import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import org.jetbrains.annotations.VisibleForTesting import java.awt.event.InvocationEvent import java.util.* import java.util.concurrent.CancellationException import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference import kotlin.coroutines.coroutineContext private val LOG = logger<StartupManagerImpl>() private val tracer by lazy { TraceManager.getTracer("startupManager") } /** * Acts as [StartupActivity.POST_STARTUP_ACTIVITY], but executed with 5 seconds delay after project opening. */ private val BACKGROUND_POST_STARTUP_ACTIVITY = ExtensionPointName<StartupActivity>("com.intellij.backgroundPostStartupActivity") private val EDT_WARN_THRESHOLD_IN_NANO = TimeUnit.MILLISECONDS.toNanos(100) private const val DUMB_AWARE_PASSED = 1 private const val ALL_PASSED = 2 @ApiStatus.Internal open class StartupManagerImpl(private val project: Project) : StartupManagerEx() { companion object { @VisibleForTesting fun addActivityEpListener(project: Project) { StartupActivity.POST_STARTUP_ACTIVITY.addExtensionPointListener(object : ExtensionPointListener<StartupActivity> { override fun extensionAdded(extension: StartupActivity, pluginDescriptor: PluginDescriptor) { if (project is LightEditCompatible && extension !is LightEditCompatible) { return } val startupManager = getInstance(project) as StartupManagerImpl val pluginId = pluginDescriptor.pluginId @Suppress("SSBasedInspection") if (extension is DumbAware) { @Suppress("DEPRECATION") project.coroutineScope.launch { if (extension is ProjectPostStartupActivity) { extension.execute(project) } else { startupManager.runActivityAndMeasureDuration(extension, pluginId) } } } else { DumbService.getInstance(project).unsafeRunWhenSmart { startupManager.runActivityAndMeasureDuration(extension, pluginId) } } } }, project) } } private val lock = Any() private val initProjectStartupActivities = ArrayDeque<Runnable>() private val postStartupActivities = ArrayDeque<Runnable>() @MagicConstant(intValues = [0, DUMB_AWARE_PASSED.toLong(), ALL_PASSED.toLong()]) @Volatile private var postStartupActivitiesPassed = 0 private val allActivitiesPassed = CompletableDeferred<Any?>() @Volatile private var isInitProjectActivitiesPassed = false private fun checkNonDefaultProject() { LOG.assertTrue(!project.isDefault, "Please don't register startup activities for the default project: they won't ever be run") } override fun registerStartupActivity(runnable: Runnable) { checkNonDefaultProject() LOG.assertTrue(!isInitProjectActivitiesPassed, "Registering startup activity that will never be run") synchronized(lock) { initProjectStartupActivities.add(runnable) } } override fun registerPostStartupActivity(runnable: Runnable) { Span.current().addEvent("register startup activity", Attributes.of(AttributeKey.stringKey("runnable"), runnable.toString())) @Suppress("SSBasedInspection") if (runnable is DumbAware) { runAfterOpened(runnable) } else { LOG.error("Activities registered via registerPostStartupActivity must be dumb-aware: $runnable") } } override fun startupActivityPassed(): Boolean = isInitProjectActivitiesPassed override fun postStartupActivityPassed(): Boolean { return when (postStartupActivitiesPassed) { ALL_PASSED -> true -1 -> throw RuntimeException("Aborted; check the log for a reason") else -> false } } override fun getAllActivitiesPassedFuture(): CompletableDeferred<Any?> = allActivitiesPassed suspend fun initProject() { // see https://github.com/JetBrains/intellij-community/blob/master/platform/service-container/overview.md#startup-activity LOG.assertTrue(!isInitProjectActivitiesPassed) runActivity("project startup") { tracer.spanBuilder("run init project activities").useWithScope2 { runInitProjectActivities() isInitProjectActivitiesPassed = true } } } suspend fun runPostStartupActivities() { // opened on startup StartUpMeasurer.compareAndSetCurrentState(LoadingState.COMPONENTS_LOADED, LoadingState.PROJECT_OPENED) // opened from the welcome screen StartUpMeasurer.compareAndSetCurrentState(LoadingState.APP_STARTED, LoadingState.PROJECT_OPENED) coroutineContext.ensureActive() val app = ApplicationManager.getApplication() if (app.isUnitTestMode && !app.isDispatchThread) { runPostStartupActivities(async = false) } else { // doesn't block project opening @Suppress("DEPRECATION") project.coroutineScope.launch { runPostStartupActivities(async = true) } if (app.isUnitTestMode) { LOG.assertTrue(app.isDispatchThread) waitAndProcessInvocationEventsInIdeEventQueue(this) } } } private suspend fun runInitProjectActivities() { runActivities(initProjectStartupActivities) val app = ApplicationManager.getApplication() val extensionPoint = (app.extensionArea as ExtensionsAreaImpl).getExtensionPoint<InitProjectActivity>("com.intellij.startupActivity") // do not create extension if not allow-listed for (adapter in extensionPoint.sortedAdapters) { coroutineContext.ensureActive() val pluginId = adapter.pluginDescriptor.pluginId if (!isCorePlugin(adapter.pluginDescriptor) && pluginId.idString != "com.jetbrains.performancePlugin" && pluginId.idString != "com.intellij.clion-makefile" && pluginId.idString != "com.jetbrains.performancePlugin.yourkit" && pluginId.idString != "com.intellij.clion-swift" && pluginId.idString != "com.intellij.appcode" && pluginId.idString != "com.intellij.clion-compdb" && pluginId.idString != "com.intellij.kmm") { LOG.error("Only bundled plugin can define ${extensionPoint.name}: ${adapter.pluginDescriptor}") continue } val activity = adapter.createInstance<InitProjectActivity>(project) ?: continue val startTime = StartUpMeasurer.getCurrentTime() tracer.spanBuilder("run activity") .setAttribute(AttributeKey.stringKey("class"), activity.javaClass.name) .setAttribute(AttributeKey.stringKey("plugin"), pluginId.idString) .useWithScope { if (project !is LightEditCompatible || activity is LightEditCompatible) { activity.run(project) } } addCompletedActivity(startTime = startTime, runnableClass = activity.javaClass, pluginId = pluginId) } } // Must be executed in a pooled thread outside of project loading modal task. The only exclusion - test mode. private suspend fun runPostStartupActivities(async: Boolean) { try { LOG.assertTrue(isInitProjectActivitiesPassed) val snapshot = PerformanceWatcher.takeSnapshot() // strictly speaking, the activity is not sequential, because sub-activities are performed in different threads // (depending on dumb-awareness), but because there is no other concurrent phase, we measure it as a sequential activity // to put it on the timeline and make clear what's going at the end (avoiding the last "unknown" phase) val dumbAwareActivity = StartUpMeasurer.startActivity(StartUpMeasurer.Activities.PROJECT_DUMB_POST_START_UP_ACTIVITIES) val edtActivity = AtomicReference<Activity?>() val uiFreezeWarned = AtomicBoolean() val counter = AtomicInteger() val dumbService = DumbService.getInstance(project) val isProjectLightEditCompatible = project is LightEditCompatible val traceContext = Context.current() StartupActivity.POST_STARTUP_ACTIVITY.processExtensions { activity, pluginDescriptor -> if (isProjectLightEditCompatible && activity !is LightEditCompatible) { return@processExtensions } if (activity is ProjectPostStartupActivity) { val pluginId = pluginDescriptor.pluginId if (async) { @Suppress("DEPRECATION") project.coroutineScope.launch { val startTime = StartUpMeasurer.getCurrentTime() val span = tracer.spanBuilder("run activity") .setAttribute(AttributeKey.stringKey("class"), activity.javaClass.name) .setAttribute(AttributeKey.stringKey("plugin"), pluginId.idString) .startSpan() withContext(traceContext.with(span).asContextElement()) { activity.execute(project) } addCompletedActivity(startTime = startTime, runnableClass = activity.javaClass, pluginId = pluginId) } } else { activity.execute(project) } return@processExtensions } @Suppress("SSBasedInspection") if (activity is DumbAware) { dumbService.runWithWaitForSmartModeDisabled().use { blockingContext { runActivityAndMeasureDuration(activity, pluginDescriptor.pluginId) } } return@processExtensions } else { if (edtActivity.get() == null) { edtActivity.set(StartUpMeasurer.startActivity("project post-startup edt activities")) } // DumbService.unsafeRunWhenSmart throws an assertion in LightEdit mode, see LightEditDumbService.unsafeRunWhenSmart if (!isProjectLightEditCompatible) { counter.incrementAndGet() blockingContext { dumbService.unsafeRunWhenSmart { traceContext.makeCurrent() val duration = runActivityAndMeasureDuration(activity, pluginDescriptor.pluginId) if (duration > EDT_WARN_THRESHOLD_IN_NANO) { reportUiFreeze(uiFreezeWarned) } dumbUnawarePostActivitiesPassed(edtActivity, counter.decrementAndGet()) } } } } } dumbUnawarePostActivitiesPassed(edtActivity, counter.get()) runPostStartupActivitiesRegisteredDynamically() dumbAwareActivity.end() snapshot.logResponsivenessSinceCreation("Post-startup activities under progress") coroutineContext.ensureActive() if (!ApplicationManager.getApplication().isUnitTestMode) { scheduleBackgroundPostStartupActivities() addActivityEpListener(project) } } catch (e: CancellationException) { throw e } catch (e: Throwable) { if (ApplicationManager.getApplication().isUnitTestMode) { postStartupActivitiesPassed = -1 } else { throw e } } } private fun runActivityAndMeasureDuration(activity: StartupActivity, pluginId: PluginId): Long { val startTime = StartUpMeasurer.getCurrentTime() try { tracer.spanBuilder("run activity") .setAttribute(AttributeKey.stringKey("class"), activity.javaClass.name) .setAttribute(AttributeKey.stringKey("plugin"), pluginId.idString) .useWithScope { if (project !is LightEditCompatible || activity is LightEditCompatible) { activity.runActivity(project) } } } catch (e: Throwable) { if (e is ControlFlowException || e is CancellationException) { throw e } LOG.error(e) } return addCompletedActivity(startTime = startTime, runnableClass = activity.javaClass, pluginId = pluginId) } private suspend fun runPostStartupActivitiesRegisteredDynamically() { tracer.spanBuilder("run post-startup dynamically registered activities").useWithScope { runActivities(postStartupActivities, activityName = "project post-startup") } postStartupActivitiesPassed = DUMB_AWARE_PASSED postStartupActivitiesPassed = ALL_PASSED allActivitiesPassed.complete(value = null) } private suspend fun runActivities(activities: Deque<Runnable>, activityName: String? = null) { synchronized(lock) { if (activities.isEmpty()) { return } } val activity = activityName?.let { StartUpMeasurer.startActivity(it) } while (true) { coroutineContext.ensureActive() val runnable = synchronized(lock, activities::pollFirst) ?: break val startTime = StartUpMeasurer.getCurrentTime() val runnableClass = runnable.javaClass val pluginId = (runnableClass.classLoader as? PluginAwareClassLoader)?.pluginId ?: PluginManagerCore.CORE_ID try { tracer.spanBuilder("run activity") .setAttribute(AttributeKey.stringKey("class"), runnableClass.name) .setAttribute(AttributeKey.stringKey("plugin"), pluginId.idString) .useWithScope { blockingContext { runnable.run() } } } catch (e: CancellationException) { throw e } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { LOG.error(e) } addCompletedActivity(startTime = startTime, runnableClass = runnableClass, pluginId = pluginId) } activity?.end() } private fun scheduleBackgroundPostStartupActivities() { @Suppress("DEPRECATION") project.coroutineScope.launch { delay(Registry.intValue("ide.background.post.startup.activity.delay", 5_000).toLong()) // read action - dynamic plugin loading executed as a write action // readActionBlocking because maybe called several times, but addExtensionPointListener must be added only once readActionBlocking { BACKGROUND_POST_STARTUP_ACTIVITY.addExtensionPointListener( object : ExtensionPointListener<StartupActivity> { override fun extensionAdded(extension: StartupActivity, pluginDescriptor: PluginDescriptor) { project.coroutineScope.runBackgroundPostStartupActivities(listOf(extension)) } }, project) BACKGROUND_POST_STARTUP_ACTIVITY.extensionList } if (!isActive) { return@launch } runBackgroundPostStartupActivities(readAction { BACKGROUND_POST_STARTUP_ACTIVITY.extensionList }) } } private fun CoroutineScope.runBackgroundPostStartupActivities(activities: List<StartupActivity>) { for (activity in activities) { try { if (project !is LightEditCompatible || activity is LightEditCompatible) { if (activity is ProjectPostStartupActivity) { launch { activity.execute(project) } } else { activity.runActivity(project) } } } catch (e: CancellationException) { throw e } catch (e: AlreadyDisposedException) { coroutineContext.ensureActive() } catch (e: Throwable) { if (e is ControlFlowException) { throw e } LOG.error(e) } } } override fun runWhenProjectIsInitialized(action: Runnable) { if (DumbService.isDumbAware(action)) { runAfterOpened { ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, project.disposed, action) } } else if (!LightEdit.owns(project)) { runAfterOpened { DumbService.getInstance(project).unsafeRunWhenSmart(action) } } } override fun runAfterOpened(runnable: Runnable) { checkNonDefaultProject() if (postStartupActivitiesPassed < DUMB_AWARE_PASSED) { synchronized(lock) { if (postStartupActivitiesPassed < DUMB_AWARE_PASSED) { postStartupActivities.add(runnable) return } } } runnable.run() } @TestOnly @Synchronized fun prepareForNextTest() { synchronized(lock) { initProjectStartupActivities.clear() postStartupActivities.clear() } } @TestOnly @Synchronized fun checkCleared() { try { synchronized(lock) { assert(initProjectStartupActivities.isEmpty()) { "Activities: $initProjectStartupActivities" } assert(postStartupActivities.isEmpty()) { "DumbAware Post Activities: $postStartupActivities" } } } finally { prepareForNextTest() } } } private fun addCompletedActivity(startTime: Long, runnableClass: Class<*>, pluginId: PluginId): Long { return StartUpMeasurer.addCompletedActivity( startTime, runnableClass, ActivityCategory.POST_STARTUP_ACTIVITY, pluginId.idString, StartUpMeasurer.MEASURE_THRESHOLD, ) } private fun dumbUnawarePostActivitiesPassed(edtActivity: AtomicReference<Activity?>, count: Int) { if (count == 0) { edtActivity.getAndSet(null)?.end() } } private fun reportUiFreeze(uiFreezeWarned: AtomicBoolean) { val app = ApplicationManager.getApplication() if (!app.isUnitTestMode && app.isDispatchThread && uiFreezeWarned.compareAndSet(false, true)) { LOG.info("Some post-startup activities freeze UI for noticeable time. " + "Please consider making them DumbAware to run them in background under modal progress," + " or just making them faster to speed up project opening.") } } // allow `invokeAndWait` inside startup activities private suspend fun waitAndProcessInvocationEventsInIdeEventQueue(startupManager: StartupManagerImpl) { ApplicationManager.getApplication().assertIsDispatchThread() val eventQueue = IdeEventQueue.getInstance() if (startupManager.postStartupActivityPassed()) { withContext(Dispatchers.EDT) { } } else { // make sure eventQueue.nextEvent will unblock startupManager.runAfterOpened(DumbAwareRunnable { ApplicationManager.getApplication().invokeLater { } }) } while (true) { val event = eventQueue.nextEvent if (event is InvocationEvent) { eventQueue.dispatchEvent(event) } if (startupManager.postStartupActivityPassed() && eventQueue.peekEvent() == null) { break } } }
apache-2.0
d2e6b8d9a6778f2ef8a04eeabffcd042
36.687037
137
0.705455
5.303623
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/migration/ObsoleteKotlinJsPackagesInspection.kt
1
5620
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.migration import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.backend.common.serialization.findPackage import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtSimpleNameExpression internal class ObsoleteKotlinJsPackagesInspection : ObsoleteCodeMigrationInspection() { override val fromVersion: LanguageVersion = LanguageVersion.KOTLIN_1_3 override val toVersion: LanguageVersion = LanguageVersion.KOTLIN_1_4 override val problemReporters: List<ObsoleteCodeProblemReporter> get() = listOf( KotlinBrowserFullyQualifiedUsageReporter, KotlinBrowserImportUsageReporter, KotlinDomImportUsageReporter ) } private object ObsoleteKotlinJsPackagesUsagesInWholeProjectFix : ObsoleteCodeInWholeProjectFix() { override val inspectionName: String = ObsoleteKotlinJsPackagesInspection().shortName override fun getFamilyName(): String = KotlinBundle.message("obsolete.kotlin.js.packages.usage.in.whole.fix.family.name") } private const val KOTLIN_BROWSER_PACKAGE = "kotlin.browser" private const val KOTLINX_BROWSER_PACKAGE = "kotlinx.browser" private const val KOTLIN_DOM_PACKAGE = "kotlin.dom" private class ObsoleteKotlinBrowserUsageFix(delegate: ObsoleteCodeFix) : ObsoleteCodeFixDelegateQuickFix(delegate) { override fun getFamilyName(): String = KotlinBundle.message("obsolete.package.usage.fix.family.name", KOTLIN_BROWSER_PACKAGE) } private class ObsoleteKotlinDomUsageFix(delegate: ObsoleteCodeFix) : ObsoleteCodeFixDelegateQuickFix(delegate) { override fun getFamilyName(): String = KotlinBundle.message("obsolete.package.usage.fix.family.name", KOTLIN_DOM_PACKAGE) } /** * We have such inspection only for 'kotlin.browser' package; it is because 'kotlin.dom' package has only extension functions. Such * functions cannot be used with fully qualified name. */ private object KotlinBrowserFullyQualifiedUsageReporter : ObsoleteCodeProblemReporter { override fun report(holder: ProblemsHolder, isOnTheFly: Boolean, simpleNameExpression: KtSimpleNameExpression): Boolean { val fullyQualifiedExpression = simpleNameExpression.parent as? KtDotQualifiedExpression ?: return false val kotlinBrowserQualifier = fullyQualifiedExpression.receiverExpression as? KtDotQualifiedExpression ?: return false if (kotlinBrowserQualifier.text != KOTLIN_BROWSER_PACKAGE) return false if (!resolvesToKotlinBrowserPackage(simpleNameExpression)) return false holder.registerProblem( kotlinBrowserQualifier, KotlinBundle.message("package.usages.are.obsolete.since.1.4", KOTLIN_DOM_PACKAGE), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, *fixesWithWholeProject( isOnTheFly, fix = ObsoleteKotlinBrowserUsageFix(KotlinBrowserFullyQualifiedUsageFix), wholeProjectFix = ObsoleteKotlinJsPackagesUsagesInWholeProjectFix ) ) return true } private fun resolvesToKotlinBrowserPackage(simpleNameExpression: KtSimpleNameExpression): Boolean { val referencedDescriptor = simpleNameExpression.resolveMainReferenceToDescriptors().singleOrNull() as? CallableDescriptor ?: return false return referencedDescriptor.findPackage().fqName.asString() == KOTLIN_BROWSER_PACKAGE } object KotlinBrowserFullyQualifiedUsageFix : ObsoleteCodeFix { override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val oldQualifier = descriptor.psiElement as? KtDotQualifiedExpression ?: return val newQualifier = KtPsiFactory(project).createExpression(KOTLINX_BROWSER_PACKAGE) oldQualifier.replace(newQualifier) } } } private object KotlinBrowserImportUsageReporter : ObsoleteImportsUsageReporter() { override val textMarker: String = "browser" override val packageBindings: Map<String, String> = mapOf(KOTLIN_BROWSER_PACKAGE to KOTLINX_BROWSER_PACKAGE) override val wholeProjectFix: LocalQuickFix = ObsoleteKotlinJsPackagesUsagesInWholeProjectFix override fun problemMessage(): String = KotlinBundle.message("package.usages.are.obsolete.since.1.4", KOTLIN_BROWSER_PACKAGE) override fun wrapFix(fix: ObsoleteCodeFix): LocalQuickFix = ObsoleteKotlinBrowserUsageFix(fix) } private object KotlinDomImportUsageReporter : ObsoleteImportsUsageReporter() { override val textMarker: String = "dom" override val packageBindings: Map<String, String> = mapOf(KOTLIN_DOM_PACKAGE to "kotlinx.dom") override val wholeProjectFix: LocalQuickFix = ObsoleteKotlinJsPackagesUsagesInWholeProjectFix override fun problemMessage(): String = KotlinBundle.message("package.usages.are.obsolete.since.1.4", KOTLIN_DOM_PACKAGE) override fun wrapFix(fix: ObsoleteCodeFix): LocalQuickFix = ObsoleteKotlinDomUsageFix(fix) }
apache-2.0
868bd72f60b6fcc1780be4c4bb1d5352
50.090909
158
0.784698
4.916885
false
false
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/blob/Blob.kt
1
1133
package com.nononsenseapps.feeder.blob import java.io.File import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.util.zip.GZIPInputStream import java.util.zip.GZIPOutputStream fun blobFile(itemId: Long, filesDir: File): File = File(filesDir, "$itemId.txt.gz") @Throws(IOException::class) fun blobInputStream(itemId: Long, filesDir: File): InputStream = GZIPInputStream(blobFile(itemId = itemId, filesDir = filesDir).inputStream()) @Throws(IOException::class) fun blobOutputStream(itemId: Long, filesDir: File): OutputStream = GZIPOutputStream(blobFile(itemId = itemId, filesDir = filesDir).outputStream()) fun blobFullFile(itemId: Long, filesDir: File): File = File(filesDir, "$itemId.full.html.gz") @Throws(IOException::class) fun blobFullInputStream(itemId: Long, filesDir: File): InputStream = GZIPInputStream(blobFullFile(itemId = itemId, filesDir = filesDir).inputStream()) @Throws(IOException::class) fun blobFullOutputStream(itemId: Long, filesDir: File): OutputStream = GZIPOutputStream(blobFullFile(itemId = itemId, filesDir = filesDir).outputStream())
gpl-3.0
1ffa04ba8ff686c0562eeef4571c5ac6
36.766667
87
0.774934
3.840678
false
false
false
false
silvertern/nox
src/main/kotlin/nox/core/Version.kt
1
2596
/** * Created by skol on 27.02.17. */ package nox.core class Version : Comparable<Version> { enum class Component { Major, Minor, Build, Suffix } val major: Long val minor: Long val build: Long val suffix: String? var shortVersion = false @JvmOverloads constructor(major: Long, minor: Long, build: Long, suffix: String? = null) { this.major = major this.minor = minor this.build = build this.suffix = suffix } @JvmOverloads constructor(versionString: String, withSuffix: Boolean = true) { val parts = versionString.trim { it <= ' ' }.split("(\\.|-|_)".toRegex()) if (parts.isEmpty()) { throw IllegalArgumentException("Major version is required") } major = java.lang.Long.valueOf(parts[0])!!.toLong() var minorno: Long = 0 if (parts.size > 1) { try { minorno = java.lang.Long.valueOf(parts[1])!!.toLong() } catch (ex: NumberFormatException) { // ignore } } minor = minorno var buildno: Long = 0 if (parts.size > 2) { try { buildno = java.lang.Long.valueOf(parts[2])!!.toLong() } catch (ex: NumberFormatException) { // ignore } } else { shortVersion = true } build = buildno if (parts.size == 4 && withSuffix) { suffix = parts[3] } else if (parts.size > 4 && withSuffix) { val suffixParts = ArrayList(parts).subList(3, parts.size) suffix = suffixParts.joinToString("-") } else { suffix = null } } fun nextMajor(): Version { return Version(major + 1, 0, 0) } fun nextMinor(): Version { return Version(major, minor + 1, 0) } override fun toString(): String { if (shortVersion) { return "%d.%d".format(major, minor) } var res = "%d.%d.%d".format(major, minor, build) if (!suffix.isNullOrBlank()) { res += "." + suffix!! } return res } fun toString(component: Component): String { when (component) { Version.Component.Major -> return "%d".format(major) Version.Component.Build -> { if (!shortVersion) { return "%d.%d.%d".format(major, minor, build) } return "%d.%d".format(major, minor) } Version.Component.Minor -> return "%d.%d".format(major, minor) else -> return toString() } } override fun compareTo(other: Version): Int { var diff = java.lang.Long.compare(major, other.major) if (diff != 0) { return diff } diff = java.lang.Long.compare(minor, other.minor) if (diff != 0) { return diff } return java.lang.Long.compare(build, other.build) } companion object { val MIN = Version(0, 0, 0) val DEFAULT = Version(0, 1, 0) val MAX = Version(java.lang.Long.MAX_VALUE, 0, 0) } }
mit
1e5dde5f6f8a74de668d289f7b304a2f
20.633333
91
0.626348
3.011601
false
false
false
false
glodanif/BluetoothChat
app/src/main/kotlin/com/glodanif/bluetoothchat/ui/widget/ActionView.kt
1
2030
package com.glodanif.bluetoothchat.ui.widget import android.annotation.SuppressLint import android.content.Context import android.text.Html import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.Button import android.widget.FrameLayout import android.widget.TextView import com.glodanif.bluetoothchat.R class ActionView : FrameLayout { @SuppressLint("InflateParams") private var container = LayoutInflater.from(context).inflate(R.layout.view_action, null) constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) fun setActions(textMessage: String, firstAction: Action?, secondAction: Action?) { removeAllViews() container.findViewById<TextView>(R.id.tv_text).text = Html.fromHtml(textMessage) container.findViewById<Button>(R.id.btn_first_action).let { button -> if (firstAction != null) { button.visibility = View.VISIBLE button.text = firstAction.text button.setOnClickListener { firstAction.action.invoke() } } else { button.visibility = View.GONE } } container.findViewById<Button>(R.id.btn_second_action).let { button -> if (secondAction != null) { button.visibility = View.VISIBLE button.text = secondAction.text button.setOnClickListener { secondAction.action.invoke() } } else { button.visibility = View.GONE } } addView(container) } fun setActionsAndShow(textMessage: String, firstAction: Action?, secondAction: Action?) { setActions(textMessage, firstAction, secondAction) visibility = View.VISIBLE } class Action(var text: String, var action: () -> Unit) }
apache-2.0
3e6cff26057b6cd703c7a00ee1693f41
32.833333
112
0.666502
4.624146
false
false
false
false
allotria/intellij-community
platform/diff-impl/src/com/intellij/diff/statistics/DiffUsagesCollector.kt
3
4099
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.diff.statistics import com.intellij.diff.impl.DiffSettingsHolder.DiffSettings import com.intellij.diff.tools.external.ExternalDiffSettings import com.intellij.diff.tools.fragmented.UnifiedDiffTool import com.intellij.diff.tools.simple.SimpleDiffTool import com.intellij.diff.tools.util.base.TextDiffSettingsHolder.TextDiffSettings import com.intellij.diff.util.DiffPlaces import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.beans.addBoolIfDiffers import com.intellij.internal.statistic.beans.addMetricsIfDiffers import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import java.util.* class DiffUsagesCollector : ApplicationUsagesCollector() { override fun getGroupId(): String = "vcs.diff" override fun getVersion(): Int = 4 override fun getMetrics(): Set<MetricEvent> { val set = HashSet<MetricEvent>() val places = listOf(DiffPlaces.DEFAULT, DiffPlaces.CHANGES_VIEW, DiffPlaces.VCS_LOG_VIEW, DiffPlaces.VCS_FILE_HISTORY_VIEW, DiffPlaces.COMMIT_DIALOG, DiffPlaces.MERGE, DiffPlaces.TESTS_FAILED_ASSERTIONS) for (place in places) { val data = FeatureUsageData().addData("diff_place", place) val diffSettings = DiffSettings.getSettings(place) val defaultDiffSettings = DiffSettings.getDefaultSettings(place) val textSettings = TextDiffSettings.getSettings(place) val defaultTextSettings = TextDiffSettings.getDefaultSettings(place) addMetricsIfDiffers(set, textSettings, defaultTextSettings, data) { addBool("sync.scroll" ) { it.isEnableSyncScroll } add("ignore.policy") { it.ignorePolicy } add("highlight.policy") { it.highlightPolicy } add("show.warnings.policy") { it.highlightingLevel } add("context.range") { it.contextRange } addBool("collapse.unchanged") { !it.isExpandByDefault } addBool("show.line.numbers") { it.isShowLineNumbers } addBool("show.white.spaces") { it.isShowWhitespaces } addBool("show.indent.lines") { it.isShowIndentLines } addBool("use.soft.wraps") { it.isUseSoftWraps } addBool("enable.read.lock") { it.isReadOnlyLock } add("show.breadcrumbs") { it.breadcrumbsPlacement } addBool("merge.apply.non.conflicted") { it.isAutoApplyNonConflictedChanges } addBool("merge.enable.lst.markers") { it.isEnableLstGutterMarkersInMerge } } addBoolIfDiffers(set, diffSettings, defaultDiffSettings, { isUnifiedToolDefault(it) }, "use.unified.diff", data) } val diffSettings = DiffSettings.getSettings(DiffPlaces.DEFAULT) val defaultDiffSettings = DiffSettings.getDefaultSettings(DiffPlaces.DEFAULT) addBoolIfDiffers(set, diffSettings, defaultDiffSettings, { it.isGoToNextFileOnNextDifference }, "iterate.next.file") val externalSettings = ExternalDiffSettings.instance val defaultExternalSettings = ExternalDiffSettings() addBoolIfDiffers(set, externalSettings, defaultExternalSettings, { it.isDiffEnabled }, "use.external.diff") addBoolIfDiffers(set, externalSettings, defaultExternalSettings, { it.isDiffEnabled && it.isDiffDefault }, "use.external.diff.by.default") addBoolIfDiffers(set, externalSettings, defaultExternalSettings, { it.isMergeEnabled }, "use.external.merge") return set } private fun isUnifiedToolDefault(settings: DiffSettings): Boolean { val toolOrder = settings.diffToolsOrder val defaultToolIndex = toolOrder.indexOf(SimpleDiffTool::class.java.canonicalName) val unifiedToolIndex = toolOrder.indexOf(UnifiedDiffTool::class.java.canonicalName) if (unifiedToolIndex == -1) return false return defaultToolIndex == -1 || unifiedToolIndex < defaultToolIndex } }
apache-2.0
f5fd6f058def1b3b001206a8e1e059dd
50.2375
142
0.737741
4.524283
false
false
false
false