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
auth0/Lock.Android
app/src/main/java/com/auth0/android/lock/app/DemoActivity.kt
1
11714
/* * DemoActivity.java * * Copyright (c) 2016 Auth0 (http://auth0.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.auth0.android.lock.app import android.os.Bundle import android.view.View import android.widget.Button import android.widget.CheckBox import android.widget.LinearLayout import android.widget.RadioGroup import androidx.appcompat.app.AppCompatActivity import com.auth0.android.Auth0 import com.auth0.android.authentication.AuthenticationException import com.auth0.android.callback.Callback import com.auth0.android.lock.* import com.auth0.android.provider.WebAuthProvider.login import com.auth0.android.provider.WebAuthProvider.logout import com.auth0.android.result.Credentials import com.google.android.material.snackbar.Snackbar class DemoActivity : AppCompatActivity() { // Configured instances private var lock: Lock? = null private var passwordlessLock: PasswordlessLock? = null // Views private lateinit var rootLayout: View private lateinit var groupSubmitMode: RadioGroup private lateinit var checkboxClosable: CheckBox private lateinit var groupPasswordlessChannel: RadioGroup private lateinit var groupPasswordlessMode: RadioGroup private lateinit var checkboxConnectionsDB: CheckBox private lateinit var checkboxConnectionsEnterprise: CheckBox private lateinit var checkboxConnectionsSocial: CheckBox private lateinit var checkboxConnectionsPasswordless: CheckBox private lateinit var checkboxHideMainScreenTitle: CheckBox private lateinit var groupDefaultDB: RadioGroup private lateinit var groupUsernameStyle: RadioGroup private lateinit var checkboxLoginAfterSignUp: CheckBox private lateinit var checkboxScreenLogIn: CheckBox private lateinit var checkboxScreenSignUp: CheckBox private lateinit var checkboxScreenReset: CheckBox private lateinit var groupInitialScreen: RadioGroup override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.demo_activity) rootLayout = findViewById(R.id.scrollView) //Basic groupSubmitMode = findViewById(R.id.group_submitmode) checkboxClosable = findViewById(R.id.checkbox_closable) checkboxHideMainScreenTitle = findViewById(R.id.checkbox_hide_title) checkboxConnectionsDB = findViewById(R.id.checkbox_connections_db) checkboxConnectionsEnterprise = findViewById(R.id.checkbox_connections_enterprise) checkboxConnectionsSocial = findViewById(R.id.checkbox_connections_social) checkboxConnectionsPasswordless = findViewById(R.id.checkbox_connections_Passwordless) groupPasswordlessChannel = findViewById(R.id.group_passwordless_channel) groupPasswordlessMode = findViewById(R.id.group_passwordless_mode) //Advanced groupDefaultDB = findViewById(R.id.group_default_db) groupUsernameStyle = findViewById(R.id.group_username_style) checkboxLoginAfterSignUp = findViewById(R.id.checkbox_login_after_signup) checkboxScreenLogIn = findViewById(R.id.checkbox_enable_login) checkboxScreenSignUp = findViewById(R.id.checkbox_enable_signup) checkboxScreenReset = findViewById(R.id.checkbox_enable_reset) groupInitialScreen = findViewById(R.id.group_initial_screen) //Buttons val advancedContainer = findViewById<LinearLayout>(R.id.advanced_container) val checkboxShowAdvanced = findViewById<CheckBox>(R.id.checkbox_show_advanced) checkboxShowAdvanced.setOnCheckedChangeListener { _, b -> advancedContainer.visibility = if (b) View.VISIBLE else View.GONE } val btnShowLockClassic = findViewById<Button>(R.id.btn_show_lock_classic) btnShowLockClassic.setOnClickListener { showClassicLock() } val btnShowLockPasswordless = findViewById<Button>(R.id.btn_show_lock_passwordless) btnShowLockPasswordless.setOnClickListener { showPasswordlessLock() } val btnShowUniversalLogin = findViewById<Button>(R.id.btn_show_universal_login) btnShowUniversalLogin.setOnClickListener { showWebAuth() } val btnClearSession = findViewById<Button>(R.id.btn_clear_session) btnClearSession.setOnClickListener { clearSession() } } private fun showWebAuth() { login(account) .withScheme("demo") .withAudience(String.format("https://%s/userinfo", getString(R.string.com_auth0_domain))) .start(this, loginCallback) } private fun clearSession() { logout(account) .withScheme("demo") .start(this, logoutCallback) } private fun showClassicLock() { val builder = Lock.newBuilder(account, callback) .withScheme("demo") .closable(checkboxClosable.isChecked) .useLabeledSubmitButton(groupSubmitMode.checkedRadioButtonId == R.id.radio_use_label) .loginAfterSignUp(checkboxLoginAfterSignUp.isChecked) .allowLogIn(checkboxScreenLogIn.isChecked) .allowSignUp(checkboxScreenSignUp.isChecked) .allowForgotPassword(checkboxScreenReset.isChecked) .allowedConnections(generateConnections()) .hideMainScreenTitle(checkboxHideMainScreenTitle.isChecked) when (groupUsernameStyle.checkedRadioButtonId) { R.id.radio_username_style_email -> { builder.withUsernameStyle(UsernameStyle.EMAIL) } R.id.radio_username_style_username -> { builder.withUsernameStyle(UsernameStyle.USERNAME) } } when (groupInitialScreen.checkedRadioButtonId) { R.id.radio_initial_reset -> { builder.initialScreen(InitialScreen.FORGOT_PASSWORD) } R.id.radio_initial_signup -> { builder.initialScreen(InitialScreen.SIGN_UP) } else -> { builder.initialScreen(InitialScreen.LOG_IN) } } if (checkboxConnectionsDB.isChecked) { when (groupDefaultDB.checkedRadioButtonId) { R.id.radio_default_db_policy -> { builder.setDefaultDatabaseConnection("with-strength") } R.id.radio_default_db_mfa -> { builder.setDefaultDatabaseConnection("mfa-connection") } else -> { builder.setDefaultDatabaseConnection("Username-Password-Authentication") } } } // For demo purposes because options change dynamically, we release the resources of Lock here. // In a real app, you will have a single instance and release its resources in Activity#OnDestroy. lock?.onDestroy(this) // Create a new instance with the updated configuration lock = builder.build(this) startActivity(lock!!.newIntent(this)) } private fun showPasswordlessLock() { val builder = PasswordlessLock.newBuilder(account, callback) .withScheme("demo") .closable(checkboxClosable.isChecked) .allowedConnections(generateConnections()) .hideMainScreenTitle(checkboxHideMainScreenTitle.isChecked) if (groupPasswordlessMode.checkedRadioButtonId == R.id.radio_use_link) { builder.useLink() } else { builder.useCode() } // For demo purposes because options change dynamically, we release the resources of Lock here. // In a real app, you will have a single instance and release its resources in Activity#OnDestroy. passwordlessLock?.onDestroy(this) // Create a new instance with the updated configuration passwordlessLock = builder.build(this) startActivity(passwordlessLock!!.newIntent(this)) } private val account: Auth0 by lazy { Auth0(getString(R.string.com_auth0_client_id), getString(R.string.com_auth0_domain)) } private fun generateConnections(): List<String> { val connections: MutableList<String> = ArrayList() if (checkboxConnectionsDB.isChecked) { connections.add("Username-Password-Authentication") connections.add("mfa-connection") connections.add("with-strength") } if (checkboxConnectionsEnterprise.isChecked) { connections.add("ad") connections.add("another") connections.add("fake-saml") connections.add("contoso-ad") } if (checkboxConnectionsSocial.isChecked) { connections.add("google-oauth2") connections.add("twitter") connections.add("facebook") connections.add("paypal-sandbox") } if (checkboxConnectionsPasswordless.isChecked) { connections.add(if (groupPasswordlessChannel.checkedRadioButtonId == R.id.radio_use_sms) "sms" else "email") } if (connections.isEmpty()) { connections.add("no-connection") } return connections } public override fun onDestroy() { super.onDestroy() lock?.onDestroy(this) passwordlessLock?.onDestroy(this) } internal fun showResult(message: String) { Snackbar.make(rootLayout, message, Snackbar.LENGTH_LONG).show() } private val callback: LockCallback = object : AuthenticationCallback() { override fun onAuthentication(credentials: Credentials) { showResult("OK > " + credentials.accessToken) } override fun onError(error: AuthenticationException) { if (error.isCanceled) { showResult("User pressed back.") } else { showResult(error.getDescription()) } } } private val loginCallback: Callback<Credentials, AuthenticationException> = object : Callback<Credentials, AuthenticationException> { override fun onFailure(error: AuthenticationException) { showResult("Failed > " + error.getDescription()) } override fun onSuccess(result: Credentials) { showResult("OK > " + result.accessToken) } } private val logoutCallback: Callback<Void?, AuthenticationException> = object : Callback<Void?, AuthenticationException> { override fun onFailure(error: AuthenticationException) { showResult("Log out cancelled") } override fun onSuccess(result: Void?) { showResult("Logged out!") } } }
mit
3991561bacdff1e9b2640ca7c61d4e3b
43.041353
137
0.68209
4.84851
false
false
false
false
CruGlobal/android-gto-support
gto-support-picasso/src/test/kotlin/org/ccci/gto/android/common/picasso/view/SimplePicassoImageViewTest.kt
1
1746
package org.ccci.gto.android.common.picasso.view import android.content.Context import android.util.AttributeSet import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import org.ccci.gto.android.common.picasso.R import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric @RunWith(AndroidJUnit4::class) class SimplePicassoImageViewTest { private val context get() = ApplicationProvider.getApplicationContext<Context>() @Test fun `testConstructor - attribute - placeholder resource`() { val attrs = Robolectric.buildAttributeSet() .addAttribute(R.attr.placeholder, "@android:drawable/btn_default") .build() val view = TestSimplePicassoImageView(context, attrs) assertEquals(android.R.drawable.btn_default, view.helper.placeholderResId) assertNull(view.helper.placeholder) } @Test fun `testConstructor - scaleType Attribute`() { val attrs = Robolectric.buildAttributeSet().addAttribute(android.R.attr.scaleType, "center").build() SimplePicassoImageView(context, attrs) } @Test fun `testConstructor - scaleType Attribute - Subclass`() { val attrs = Robolectric.buildAttributeSet().addAttribute(android.R.attr.scaleType, "center").build() object : SimplePicassoImageView(context, attrs) { override val helper by lazy { PicassoImageView.Helper(this, attrs) } } } class TestSimplePicassoImageView(context: Context, attrs: AttributeSet?) : SimplePicassoImageView(context, attrs) { public override val helper get() = super.helper } }
mit
a7a567e505800b38d1b70767bae3c718
37.8
119
0.731959
4.454082
false
true
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/callableReference/property/privateSetterOutsideClass.kt
4
675
// See KT-12337 Reference to property with invisible setter should not be a KMutableProperty import kotlin.reflect.KProperty1 import kotlin.reflect.KMutableProperty open class Bar(name: String) { var foo: String = name private set } class Baz : Bar("") { fun ref() = Bar::foo } fun box(): String { val p1: KProperty1<Bar, String> = Bar::foo if (p1 is KMutableProperty<*>) return "Fail: p1 is a KMutableProperty" val p2 = Baz().ref() if (p2 is KMutableProperty<*>) return "Fail: p2 is a KMutableProperty" val p3 = Bar("")::foo if (p3 is KMutableProperty<*>) return "Fail: p3 is a KMutableProperty" return p1.get(Bar("OK")) }
apache-2.0
1b441ea4a46b7b8318dfdacd8839fd87
24.961538
92
0.666667
3.688525
false
false
false
false
jiaminglu/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/StaticData.kt
1
6451
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.backend.konan.llvm import llvm.* import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.ir.expressions.IrConst import org.jetbrains.kotlin.types.KotlinType /** * Provides utilities to create static data. */ internal class StaticData(override val context: Context): ContextUtils { /** * Represents the LLVM global variable. */ class Global private constructor(val staticData: StaticData, val llvmGlobal: LLVMValueRef) { companion object { private fun createLlvmGlobal(module: LLVMModuleRef, type: LLVMTypeRef, name: String, isExported: Boolean ): LLVMValueRef { if (isExported && LLVMGetNamedGlobal(module, name) != null) { throw IllegalArgumentException("Global '$name' already exists") } // Globals created with this API are *not* thread local. val llvmGlobal = LLVMAddGlobal(module, type, name)!! if (!isExported) { LLVMSetLinkage(llvmGlobal, LLVMLinkage.LLVMInternalLinkage) } return llvmGlobal } fun create(staticData: StaticData, type: LLVMTypeRef, name: String, isExported: Boolean): Global { val module = staticData.context.llvmModule val isUnnamed = (name == "") // LLVM will select the unique index and represent the global as `@idx`. if (isUnnamed && isExported) { throw IllegalArgumentException("unnamed global can't be exported") } val llvmGlobal = createLlvmGlobal(module!!, type, name, isExported) return Global(staticData, llvmGlobal) } } fun setInitializer(value: ConstValue) { LLVMSetInitializer(llvmGlobal, value.llvm) } fun setConstant(value: Boolean) { LLVMSetGlobalConstant(llvmGlobal, if (value) 1 else 0) } val pointer = Pointer.to(this) } /** * Represents the pointer to static data. * It can be a pointer to either a global or any its element. * * TODO: this class is probably should be implemented more optimally */ class Pointer private constructor(val global: Global, private val delegate: ConstPointer, val offsetInGlobal: Long) : ConstPointer by delegate { companion object { fun to(global: Global) = Pointer(global, constPointer(global.llvmGlobal), 0L) } private fun getElementOffset(index: Int): Long { val llvmTargetData = global.staticData.llvmTargetData val type = LLVMGetElementType(delegate.llvmType) return when (LLVMGetTypeKind(type)) { LLVMTypeKind.LLVMStructTypeKind -> LLVMOffsetOfElement(llvmTargetData, type, index) LLVMTypeKind.LLVMArrayTypeKind -> LLVMABISizeOfType(llvmTargetData, LLVMGetElementType(type)) * index else -> TODO() } } override fun getElementPtr(index: Int): Pointer { return Pointer(global, delegate.getElementPtr(index), offsetInGlobal + this.getElementOffset(index)) } /** * @return the distance from other pointer to this. * * @throws UnsupportedOperationException if it is not possible to represent the distance as [Int] value */ fun sub(other: Pointer): Int { if (this.global != other.global) { throw UnsupportedOperationException("pointers must belong to the same global") } val res = this.offsetInGlobal - other.offsetInGlobal if (res.toInt().toLong() != res) { throw UnsupportedOperationException("result doesn't fit into Int") } return res.toInt() } } /** * Creates [Global] with given type and name. * * It is external until explicitly initialized with [Global.setInitializer]. */ fun createGlobal(type: LLVMTypeRef, name: String, isExported: Boolean = false): Global { return Global.create(this, type, name, isExported) } /** * Creates [Global] with given name and value. */ fun placeGlobal(name: String, initializer: ConstValue, isExported: Boolean = false): Global { val global = createGlobal(initializer.llvmType, name, isExported) global.setInitializer(initializer) return global } /** * Creates array-typed global with given name and value. */ fun placeGlobalArray(name: String, elemType: LLVMTypeRef?, elements: List<ConstValue>): Global { val initializer = ConstArray(elemType, elements) val global = placeGlobal(name, initializer) return global } private val stringLiterals = mutableMapOf<String, ConstPointer>() private val cStringLiterals = mutableMapOf<String, ConstPointer>() fun cStringLiteral(value: String) = cStringLiterals.getOrPut(value) { placeCStringLiteral(value) } fun kotlinStringLiteral(type: KotlinType, value: IrConst<String>) = stringLiterals.getOrPut(value.value) { createKotlinStringLiteral(type, value) } } /** * Creates static instance of `konan.ImmutableByteArray` with given values of elements. * * @param args data for constant creation. */ internal fun StaticData.createImmutableBinaryBlob(value: IrConst<String>): LLVMValueRef { val args = value.value.map { Int8(it.toByte()).llvm } return createKotlinArray(context.ir.symbols.immutableBinaryBlob.descriptor.defaultType, args) }
apache-2.0
32a3a19f1b0a67c6354f036e91aa2d4f
36.511628
117
0.629825
4.931957
false
false
false
false
WhosNickDoglio/Aww-Gallery
app/src/main/java/com/nicholasdoglio/eyebleach/data/util/DataExtensions.kt
1
1879
/* * MIT License * * Copyright (c) 2019. Nicholas Doglio * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.nicholasdoglio.eyebleach.data.util import com.nicholasdoglio.eyebleach.data.ChildData import com.nicholasdoglio.eyebleach.data.ListingResponse import com.nicholasdoglio.eyebleach.data.RedditPost fun ListingResponse.toRedditPosts(): List<RedditPost> = this.data.children.asSequence() .filter { !it.data.over18 } .filter { it.data.url.contains(".jpg") || it.data.url.contains(".png") } .map { it.data.toRedditPost() } .toList() fun ChildData.toRedditPost(): RedditPost = RedditPost( url = url, name = name, thumbnail = thumbnail, permalink = permalink ) inline val RedditPost.redditUrl: String get() = "https://reddit.com$permalink"
mit
bfb31e2a72afadf3c441eb7a0bb3c681
39.847826
87
0.725386
3.989384
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/ProgressItem.kt
1
1647
package eu.kanade.tachiyomi.ui.catalogue.browse import android.support.v7.widget.RecyclerView import android.view.View import android.widget.ProgressBar import android.widget.TextView import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.AbstractFlexibleItem import eu.davidea.flexibleadapter.items.IFlexible import eu.davidea.viewholders.FlexibleViewHolder import eu.kanade.tachiyomi.R class ProgressItem : AbstractFlexibleItem<ProgressItem.Holder>() { private var loadMore = true override fun getLayoutRes(): Int { return R.layout.catalogue_progress_item } override fun createViewHolder(view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>): Holder { return Holder(view, adapter) } override fun bindViewHolder(adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>, holder: Holder, position: Int, payloads: List<Any?>) { holder.progressBar.visibility = View.GONE holder.progressMessage.visibility = View.GONE if (!adapter.isEndlessScrollEnabled) { loadMore = false } if (loadMore) { holder.progressBar.visibility = View.VISIBLE } else { holder.progressMessage.visibility = View.VISIBLE } } override fun equals(other: Any?): Boolean { return this === other } class Holder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter) { val progressBar: ProgressBar = view.findViewById(R.id.progress_bar) val progressMessage: TextView = view.findViewById(R.id.progress_message) } }
apache-2.0
2bd4d5f2fdf7cfdfec4be20ad92d78d7
31.313725
148
0.71949
4.732759
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/more/NewUpdateDialogController.kt
1
2517
package eu.kanade.tachiyomi.ui.more import android.app.Dialog import android.os.Bundle import android.text.method.LinkMovementMethod import android.view.View import android.widget.TextView import androidx.core.os.bundleOf import com.google.android.material.dialog.MaterialAlertDialogBuilder import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.updater.AppUpdateResult import eu.kanade.tachiyomi.data.updater.AppUpdateService import eu.kanade.tachiyomi.ui.base.controller.DialogController import eu.kanade.tachiyomi.ui.base.controller.openInBrowser import io.noties.markwon.Markwon class NewUpdateDialogController(bundle: Bundle? = null) : DialogController(bundle) { constructor(update: AppUpdateResult.NewUpdate) : this( bundleOf( BODY_KEY to update.release.info, VERSION_KEY to update.release.version, RELEASE_URL_KEY to update.release.releaseLink, DOWNLOAD_URL_KEY to update.release.getDownloadLink(), ), ) override fun onCreateDialog(savedViewState: Bundle?): Dialog { val releaseBody = args.getString(BODY_KEY)!! .replace("""---(\R|.)*Checksums(\R|.)*""".toRegex(), "") val info = Markwon.create(activity!!).toMarkdown(releaseBody) return MaterialAlertDialogBuilder(activity!!) .setTitle(R.string.update_check_notification_update_available) .setMessage(info) .setPositiveButton(R.string.update_check_confirm) { _, _ -> applicationContext?.let { context -> // Start download val url = args.getString(DOWNLOAD_URL_KEY)!! val version = args.getString(VERSION_KEY) AppUpdateService.start(context, url, version) } } .setNeutralButton(R.string.update_check_open) { _, _ -> openInBrowser(args.getString(RELEASE_URL_KEY)!!) } .create() } override fun onAttach(view: View) { super.onAttach(view) // Make links in Markdown text clickable (dialog?.findViewById(android.R.id.message) as? TextView)?.movementMethod = LinkMovementMethod.getInstance() } } private const val BODY_KEY = "NewUpdateDialogController.body" private const val VERSION_KEY = "NewUpdateDialogController.version" private const val RELEASE_URL_KEY = "NewUpdateDialogController.release_url" private const val DOWNLOAD_URL_KEY = "NewUpdateDialogController.download_url"
apache-2.0
d329bf0b5c0deedbddbfebd373f92ad1
39.596774
84
0.678586
4.502683
false
false
false
false
russhwolf/Code-Computer
src/test/kotlin/codecomputer/AccumulatorTest.kt
1
2283
package codecomputer import org.junit.Test class AccumulatorTest { private val A = 27 private val B = 16 private val C = 62 @Test fun accumulatorTest() { val input = 0.toSignals(8) val add = Relay() val clear = Relay() val accumulator = Accumulator(input, add, clear) accumulator.readAndAssert(0, "accumulator 1") input.write(A) accumulator.readAndAssert(0, "accumulator 2") add.write(true) add.write(false) accumulator.readAndAssert(A, "accumulator 3") input.write(B) accumulator.readAndAssert(A, "accumulator 4") add.write(true) add.write(false) accumulator.readAndAssert(A + B, "accumulator 5") input.write(C) add.write(true) add.write(false) accumulator.readAndAssert(A + B + C, "accumulator 6") add.write(true) add.write(false) accumulator.readAndAssert(A + B + C + C, "accumulator 7") clear.write(true) clear.write(false) accumulator.readAndAssert(0, "accumulator 8") } @Test fun ramAccumulatorTest() { val oscillator = Oscillator() val address = 0.toSignals(4) val data = 0.toSignals(8) val write = Relay() val clear = Relay() val takeover = Relay() val accumulator = RamAccumulator(oscillator, address, data, write, clear, takeover) accumulator.readAndAssert(0, "ram accumulator 1") takeover.write(true) address.write(0) data.write(A) write.write(true) write.write(false) address.write(1) data.write(B) write.write(true) write.write(false) address.write(2) data.write(C) write.write(true) write.write(false) takeover.write(false) accumulator.readAndAssert(0, "ram accumulator 2") oscillator.run(2) accumulator.readAndAssert(A, "ram accumulator 3") oscillator.run(2) accumulator.readAndAssert(A + B, "ram accumulator 4") oscillator.run(2) accumulator.readAndAssert(A + B + C, "ram accumulator 5") clear.write(true) clear.write(false) accumulator.readAndAssert(0, "ram accumulator 6") } }
mit
440d280580b5a0a855df3995ea5b96f2
30.708333
91
0.597459
4.005263
false
true
false
false
Heiner1/AndroidAPS
diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageInquireResponsePacket.kt
1
1372
package info.nightscout.androidaps.diaconn.packet import dagger.android.HasAndroidInjector import info.nightscout.androidaps.diaconn.DiaconnG8Pump import info.nightscout.shared.logging.LTag import javax.inject.Inject /** * LanguageInquireResponsePacket */ class LanguageInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) { @Inject lateinit var diaconnG8Pump: DiaconnG8Pump init { msgType = 0xA0.toByte() aapsLogger.debug(LTag.PUMPCOMM, "LanguageInquireResponsePacket init") } override fun handleMessage(data: ByteArray?) { val result = defect(data) if (result != 0) { aapsLogger.debug(LTag.PUMPCOMM, "LanguageInquireResponsePacket Got some Error") failed = true return } else failed = false val bufferData = prefixDecode(data) val result2 = getByteToInt(bufferData) if(!isSuccInquireResponseResult(result2)) { failed = true return } diaconnG8Pump.selectedLanguage = getByteToInt(bufferData) aapsLogger.debug(LTag.PUMPCOMM, "Result --> ${diaconnG8Pump.result}") aapsLogger.debug(LTag.PUMPCOMM, "selectedLanguage --> ${diaconnG8Pump.selectedLanguage}") } override fun getFriendlyName(): String { return "PUMP_LANGUAGE_INQUIRE_RESPONSE" } }
agpl-3.0
069e9110cc7270d7dc8618b0d5767df0
30.906977
97
0.688047
4.604027
false
false
false
false
onoderis/failchat
src/main/kotlin/failchat/chat/OriginStatusManager.kt
2
1531
package failchat.chat import failchat.Origin import failchat.chat.OriginStatus.DISCONNECTED import failchat.chatOrigins import failchat.util.enumMap import java.util.EnumMap import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.read import kotlin.concurrent.write class OriginStatusManager( private val messageSender: ChatMessageSender ) { private companion object { val allDisconnected: Map<Origin, OriginStatus> = enumMap<Origin, OriginStatus>().also { map -> chatOrigins.forEach { origin -> map[origin] = DISCONNECTED } } } private val statuses: EnumMap<Origin, OriginStatus> = enumMap() private val lock = ReentrantReadWriteLock() init { chatOrigins.forEach { statuses[it] = DISCONNECTED } } fun getStatuses(): Map<Origin, OriginStatus> { return lock.read { cloneStatuses() } } fun setStatus(origin: Origin, status: OriginStatus) { val afterMap = lock.write { statuses[origin] = status cloneStatuses() } messageSender.sendConnectedOriginsMessage(afterMap) } fun reset() { lock.write { statuses.entries.forEach { it.setValue(DISCONNECTED) } } messageSender.sendConnectedOriginsMessage(allDisconnected) } private fun cloneStatuses(): EnumMap<Origin, OriginStatus> { return EnumMap(statuses) } }
gpl-3.0
fc4d4b65c623f20ed7775e40d0001b67
24.516667
102
0.638798
4.754658
false
false
false
false
Maccimo/intellij-community
platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewState.kt
3
3814
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.projectView.impl import com.intellij.ide.projectView.ProjectViewSettings import com.intellij.ide.ui.UISettings import com.intellij.openapi.application.ApplicationManager.getApplication import com.intellij.openapi.components.* import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.registry.Registry import com.intellij.ui.ExperimentalUI import com.intellij.util.xmlb.XmlSerializerUtil @State(name = "ProjectViewState", storages = [(Storage(value = StoragePathMacros.WORKSPACE_FILE))]) class ProjectViewState : PersistentStateComponent<ProjectViewState> { companion object { @JvmStatic fun getInstance(project: Project): ProjectViewState = project.service() @JvmStatic fun getDefaultInstance(): ProjectViewState = ProjectManager.getInstance().defaultProject.service() } var abbreviatePackageNames = ProjectViewSettings.Immutable.DEFAULT.isAbbreviatePackageNames var autoscrollFromSource = ExperimentalUI.isNewUI() var autoscrollToSource = UISettings.getInstance().state.defaultAutoScrollToSource var compactDirectories = ProjectViewSettings.Immutable.DEFAULT.isCompactDirectories var flattenModules = ProjectViewSettings.Immutable.DEFAULT.isFlattenModules var flattenPackages = ProjectViewSettings.Immutable.DEFAULT.isFlattenPackages var foldersAlwaysOnTop = ProjectViewSettings.Immutable.DEFAULT.isFoldersAlwaysOnTop var hideEmptyMiddlePackages = ProjectViewSettings.Immutable.DEFAULT.isHideEmptyMiddlePackages var manualOrder = false var showExcludedFiles = ProjectViewSettings.Immutable.DEFAULT.isShowExcludedFiles var showLibraryContents = ProjectViewSettings.Immutable.DEFAULT.isShowLibraryContents var showMembers = ProjectViewSettings.Immutable.DEFAULT.isShowMembers var showModules = ProjectViewSettings.Immutable.DEFAULT.isShowModules var showURL = ProjectViewSettings.Immutable.DEFAULT.isShowURL var showVisibilityIcons = ProjectViewSettings.Immutable.DEFAULT.isShowVisibilityIcons var sortByType = false var useFileNestingRules = ProjectViewSettings.Immutable.DEFAULT.isUseFileNestingRules override fun noStateLoaded() { val application = getApplication() if (application == null || application.isUnitTestMode) return // for backward compatibility abbreviatePackageNames = ProjectViewSharedSettings.instance.abbreviatePackages autoscrollFromSource = ProjectViewSharedSettings.instance.autoscrollFromSource autoscrollToSource = ProjectViewSharedSettings.instance.autoscrollToSource compactDirectories = ProjectViewSharedSettings.instance.compactDirectories flattenModules = ProjectViewSharedSettings.instance.flattenModules flattenPackages = ProjectViewSharedSettings.instance.flattenPackages foldersAlwaysOnTop = ProjectViewSharedSettings.instance.foldersAlwaysOnTop hideEmptyMiddlePackages = ProjectViewSharedSettings.instance.hideEmptyPackages manualOrder = ProjectViewSharedSettings.instance.manualOrder showExcludedFiles = ProjectViewSharedSettings.instance.showExcludedFiles showLibraryContents = ProjectViewSharedSettings.instance.showLibraryContents showMembers = ProjectViewSharedSettings.instance.showMembers showModules = ProjectViewSharedSettings.instance.showModules showURL = Registry.`is`("project.tree.structure.show.url") showVisibilityIcons = ProjectViewSharedSettings.instance.showVisibilityIcons sortByType = ProjectViewSharedSettings.instance.sortByType } override fun loadState(state: ProjectViewState) { XmlSerializerUtil.copyBean(state, this) } override fun getState(): ProjectViewState { return this } }
apache-2.0
2eda68a5c3e589146a928644f0d8f6ad
52.71831
120
0.835868
5.239011
false
false
false
false
PolymerLabs/arcs
src/tools/tests/goldens/generated-schemas.jvm.kt
1
22543
/* ktlint-disable */ @file:Suppress("PackageName", "TopLevelName") package arcs.golden // // GENERATED CODE -- DO NOT EDIT // import arcs.core.data.Annotation import arcs.core.data.expression.* import arcs.core.data.expression.Expression.* import arcs.core.data.expression.Expression.BinaryOp.* import arcs.core.data.util.toReferencable import arcs.sdk.ArcsDuration import arcs.sdk.ArcsInstant import arcs.sdk.BigInt import arcs.sdk.Entity import arcs.sdk.toBigInt import javax.annotation.Generated typealias Gold_Data_Ref = AbstractGold.GoldInternal1 typealias Gold_Data_Ref_Slice = AbstractGold.GoldInternal1Slice typealias Gold_Alias = AbstractGold.GoldInternal1 typealias Gold_Alias_Slice = AbstractGold.GoldInternal1Slice typealias Gold_AllPeople = AbstractGold.Gold_AllPeople typealias Gold_AllPeople_Slice = AbstractGold.Gold_AllPeople_Slice typealias Gold_Collection = AbstractGold.Foo typealias Gold_Collection_Slice = AbstractGold.FooSlice typealias Gold_Data = AbstractGold.Gold_Data typealias Gold_Data_Slice = AbstractGold.Gold_Data_Slice typealias Gold_QCollection = AbstractGold.Gold_QCollection typealias Gold_QCollection_Slice = AbstractGold.Gold_QCollection_Slice @Generated("src/tools/schema2kotlin.ts") abstract class AbstractGold : arcs.sdk.BaseParticle() { override val handles: Handles = Handles() interface GoldInternal1Slice : arcs.sdk.Entity { val val_: String } @Suppress("UNCHECKED_CAST") class GoldInternal1( val_: String = "", entityId: String? = null, creationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP, expirationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP ) : arcs.sdk.EntityBase( "GoldInternal1", SCHEMA, entityId, creationTimestamp, expirationTimestamp, false ), GoldInternal1Slice { override var val_: String get() = super.getSingletonValue("val") as String? ?: "" private set(_value) = super.setSingletonValue("val", _value) init { this.val_ = val_ } /** * Use this method to create a new, distinctly identified copy of the entity. * Storing the copy will result in a new copy of the data being stored. */ fun copy(val_: String = this.val_) = GoldInternal1(val_ = val_) /** * Use this method to create a new version of an existing entity. * Storing the mutation will overwrite the existing entity in the set, if it exists. */ fun mutate(val_: String = this.val_) = GoldInternal1( val_ = val_, entityId = entityId, creationTimestamp = creationTimestamp, expirationTimestamp = expirationTimestamp ) companion object : arcs.sdk.EntitySpec<GoldInternal1> { override val SCHEMA = arcs.core.data.Schema( setOf(), arcs.core.data.SchemaFields( singletons = mapOf("val" to arcs.core.data.FieldType.Text), collections = emptyMap() ), "a90c278182b80e5275b076240966fde836108a5b", refinementExpression = true.asExpr(), queryExpression = true.asExpr() ) private val nestedEntitySpecs: Map<String, arcs.sdk.EntitySpec<out arcs.sdk.Entity>> = emptyMap() init { arcs.core.data.SchemaRegistry.register(SCHEMA) } override fun deserialize(data: arcs.core.data.RawEntity) = GoldInternal1().apply { deserialize(data, nestedEntitySpecs) } } } interface Gold_AllPeople_Slice : arcs.sdk.Entity { val name: String val age: Double val lastCall: Double val address: String val favoriteColor: String val birthDayMonth: Double val birthDayDOM: Double } @Suppress("UNCHECKED_CAST") class Gold_AllPeople( name: String = "", age: Double = 0.0, lastCall: Double = 0.0, address: String = "", favoriteColor: String = "", birthDayMonth: Double = 0.0, birthDayDOM: Double = 0.0, entityId: String? = null, creationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP, expirationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP ) : arcs.sdk.EntityBase( "Gold_AllPeople", SCHEMA, entityId, creationTimestamp, expirationTimestamp, false ), Gold_AllPeople_Slice { override var name: String get() = super.getSingletonValue("name") as String? ?: "" private set(_value) = super.setSingletonValue("name", _value) override var age: Double get() = super.getSingletonValue("age") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("age", _value) override var lastCall: Double get() = super.getSingletonValue("lastCall") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("lastCall", _value) override var address: String get() = super.getSingletonValue("address") as String? ?: "" private set(_value) = super.setSingletonValue("address", _value) override var favoriteColor: String get() = super.getSingletonValue("favoriteColor") as String? ?: "" private set(_value) = super.setSingletonValue("favoriteColor", _value) override var birthDayMonth: Double get() = super.getSingletonValue("birthDayMonth") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("birthDayMonth", _value) override var birthDayDOM: Double get() = super.getSingletonValue("birthDayDOM") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("birthDayDOM", _value) init { this.name = name this.age = age this.lastCall = lastCall this.address = address this.favoriteColor = favoriteColor this.birthDayMonth = birthDayMonth this.birthDayDOM = birthDayDOM } /** * Use this method to create a new, distinctly identified copy of the entity. * Storing the copy will result in a new copy of the data being stored. */ fun copy( name: String = this.name, age: Double = this.age, lastCall: Double = this.lastCall, address: String = this.address, favoriteColor: String = this.favoriteColor, birthDayMonth: Double = this.birthDayMonth, birthDayDOM: Double = this.birthDayDOM ) = Gold_AllPeople( name = name, age = age, lastCall = lastCall, address = address, favoriteColor = favoriteColor, birthDayMonth = birthDayMonth, birthDayDOM = birthDayDOM ) /** * Use this method to create a new version of an existing entity. * Storing the mutation will overwrite the existing entity in the set, if it exists. */ fun mutate( name: String = this.name, age: Double = this.age, lastCall: Double = this.lastCall, address: String = this.address, favoriteColor: String = this.favoriteColor, birthDayMonth: Double = this.birthDayMonth, birthDayDOM: Double = this.birthDayDOM ) = Gold_AllPeople( name = name, age = age, lastCall = lastCall, address = address, favoriteColor = favoriteColor, birthDayMonth = birthDayMonth, birthDayDOM = birthDayDOM, entityId = entityId, creationTimestamp = creationTimestamp, expirationTimestamp = expirationTimestamp ) companion object : arcs.sdk.EntitySpec<Gold_AllPeople> { override val SCHEMA = arcs.core.data.Schema( setOf(arcs.core.data.SchemaName("People")), arcs.core.data.SchemaFields( singletons = mapOf( "name" to arcs.core.data.FieldType.Text, "age" to arcs.core.data.FieldType.Number, "lastCall" to arcs.core.data.FieldType.Number, "address" to arcs.core.data.FieldType.Text, "favoriteColor" to arcs.core.data.FieldType.Text, "birthDayMonth" to arcs.core.data.FieldType.Number, "birthDayDOM" to arcs.core.data.FieldType.Number ), collections = emptyMap() ), "430781483d522f87f27b5cc3d40fd28aa02ca8fd", refinementExpression = true.asExpr(), queryExpression = true.asExpr() ) private val nestedEntitySpecs: Map<String, arcs.sdk.EntitySpec<out arcs.sdk.Entity>> = emptyMap() init { arcs.core.data.SchemaRegistry.register(SCHEMA) } override fun deserialize(data: arcs.core.data.RawEntity) = Gold_AllPeople().apply { deserialize(data, nestedEntitySpecs) } } } interface FooSlice : arcs.sdk.Entity { val num: Double } @Suppress("UNCHECKED_CAST") class Foo( num: Double = 0.0, entityId: String? = null, creationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP, expirationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP ) : arcs.sdk.EntityBase("Foo", SCHEMA, entityId, creationTimestamp, expirationTimestamp, false), FooSlice { override var num: Double get() = super.getSingletonValue("num") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("num", _value) init { this.num = num } /** * Use this method to create a new, distinctly identified copy of the entity. * Storing the copy will result in a new copy of the data being stored. */ fun copy(num: Double = this.num) = Foo(num = num) /** * Use this method to create a new version of an existing entity. * Storing the mutation will overwrite the existing entity in the set, if it exists. */ fun mutate(num: Double = this.num) = Foo( num = num, entityId = entityId, creationTimestamp = creationTimestamp, expirationTimestamp = expirationTimestamp ) companion object : arcs.sdk.EntitySpec<Foo> { override val SCHEMA = arcs.core.data.Schema( setOf(arcs.core.data.SchemaName("Foo")), arcs.core.data.SchemaFields( singletons = mapOf("num" to arcs.core.data.FieldType.Number), collections = emptyMap() ), "b73fa6f39c1a582996bec8776857fc24341b533c", refinementExpression = true.asExpr(), queryExpression = true.asExpr() ) private val nestedEntitySpecs: Map<String, arcs.sdk.EntitySpec<out arcs.sdk.Entity>> = emptyMap() init { arcs.core.data.SchemaRegistry.register(SCHEMA) } override fun deserialize(data: arcs.core.data.RawEntity) = Foo().apply { deserialize(data, nestedEntitySpecs) } } } interface Gold_Data_Slice : arcs.sdk.Entity { val num: Double val txt: String val lnk: String val flg: Boolean val ref: arcs.sdk.Reference<GoldInternal1>? } @Suppress("UNCHECKED_CAST") class Gold_Data( num: Double = 0.0, txt: String = "", lnk: String = "", flg: Boolean = false, ref: arcs.sdk.Reference<GoldInternal1>? = null, entityId: String? = null, creationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP, expirationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP ) : arcs.sdk.EntityBase("Gold_Data", SCHEMA, entityId, creationTimestamp, expirationTimestamp, false), Gold_Data_Slice { override var num: Double get() = super.getSingletonValue("num") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("num", _value) override var txt: String get() = super.getSingletonValue("txt") as String? ?: "" private set(_value) = super.setSingletonValue("txt", _value) override var lnk: String get() = super.getSingletonValue("lnk") as String? ?: "" private set(_value) = super.setSingletonValue("lnk", _value) override var flg: Boolean get() = super.getSingletonValue("flg") as Boolean? ?: false private set(_value) = super.setSingletonValue("flg", _value) override var ref: arcs.sdk.Reference<GoldInternal1>? get() = super.getSingletonValue("ref") as arcs.sdk.Reference<GoldInternal1>? private set(_value) = super.setSingletonValue("ref", _value) init { this.num = num this.txt = txt this.lnk = lnk this.flg = flg this.ref = ref } /** * Use this method to create a new, distinctly identified copy of the entity. * Storing the copy will result in a new copy of the data being stored. */ fun copy( num: Double = this.num, txt: String = this.txt, lnk: String = this.lnk, flg: Boolean = this.flg, ref: arcs.sdk.Reference<GoldInternal1>? = this.ref ) = Gold_Data(num = num, txt = txt, lnk = lnk, flg = flg, ref = ref) /** * Use this method to create a new version of an existing entity. * Storing the mutation will overwrite the existing entity in the set, if it exists. */ fun mutate( num: Double = this.num, txt: String = this.txt, lnk: String = this.lnk, flg: Boolean = this.flg, ref: arcs.sdk.Reference<GoldInternal1>? = this.ref ) = Gold_Data( num = num, txt = txt, lnk = lnk, flg = flg, ref = ref, entityId = entityId, creationTimestamp = creationTimestamp, expirationTimestamp = expirationTimestamp ) companion object : arcs.sdk.EntitySpec<Gold_Data> { override val SCHEMA = arcs.core.data.Schema( setOf(), arcs.core.data.SchemaFields( singletons = mapOf( "num" to arcs.core.data.FieldType.Number, "txt" to arcs.core.data.FieldType.Text, "lnk" to arcs.core.data.FieldType.Text, "flg" to arcs.core.data.FieldType.Boolean, "ref" to arcs.core.data.FieldType.EntityRef("a90c278182b80e5275b076240966fde836108a5b") ), collections = emptyMap() ), "ac9a319922d90e47a2f2a271fd9da3eda9aebd92", refinementExpression = true.asExpr(), queryExpression = true.asExpr() ) private val nestedEntitySpecs: Map<String, arcs.sdk.EntitySpec<out arcs.sdk.Entity>> = mapOf("a90c278182b80e5275b076240966fde836108a5b" to GoldInternal1) init { arcs.core.data.SchemaRegistry.register(SCHEMA) } override fun deserialize(data: arcs.core.data.RawEntity) = Gold_Data().apply { deserialize(data, nestedEntitySpecs) } } } interface Gold_QCollection_Slice : Gold_AllPeople_Slice { } @Suppress("UNCHECKED_CAST") class Gold_QCollection( name: String = "", age: Double = 0.0, lastCall: Double = 0.0, address: String = "", favoriteColor: String = "", birthDayMonth: Double = 0.0, birthDayDOM: Double = 0.0, entityId: String? = null, creationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP, expirationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP ) : arcs.sdk.EntityBase( "Gold_QCollection", SCHEMA, entityId, creationTimestamp, expirationTimestamp, false ), Gold_QCollection_Slice { override var name: String get() = super.getSingletonValue("name") as String? ?: "" private set(_value) = super.setSingletonValue("name", _value) override var age: Double get() = super.getSingletonValue("age") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("age", _value) override var lastCall: Double get() = super.getSingletonValue("lastCall") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("lastCall", _value) override var address: String get() = super.getSingletonValue("address") as String? ?: "" private set(_value) = super.setSingletonValue("address", _value) override var favoriteColor: String get() = super.getSingletonValue("favoriteColor") as String? ?: "" private set(_value) = super.setSingletonValue("favoriteColor", _value) override var birthDayMonth: Double get() = super.getSingletonValue("birthDayMonth") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("birthDayMonth", _value) override var birthDayDOM: Double get() = super.getSingletonValue("birthDayDOM") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("birthDayDOM", _value) init { this.name = name this.age = age this.lastCall = lastCall this.address = address this.favoriteColor = favoriteColor this.birthDayMonth = birthDayMonth this.birthDayDOM = birthDayDOM } /** * Use this method to create a new, distinctly identified copy of the entity. * Storing the copy will result in a new copy of the data being stored. */ fun copy( name: String = this.name, age: Double = this.age, lastCall: Double = this.lastCall, address: String = this.address, favoriteColor: String = this.favoriteColor, birthDayMonth: Double = this.birthDayMonth, birthDayDOM: Double = this.birthDayDOM ) = Gold_QCollection( name = name, age = age, lastCall = lastCall, address = address, favoriteColor = favoriteColor, birthDayMonth = birthDayMonth, birthDayDOM = birthDayDOM ) /** * Use this method to create a new version of an existing entity. * Storing the mutation will overwrite the existing entity in the set, if it exists. */ fun mutate( name: String = this.name, age: Double = this.age, lastCall: Double = this.lastCall, address: String = this.address, favoriteColor: String = this.favoriteColor, birthDayMonth: Double = this.birthDayMonth, birthDayDOM: Double = this.birthDayDOM ) = Gold_QCollection( name = name, age = age, lastCall = lastCall, address = address, favoriteColor = favoriteColor, birthDayMonth = birthDayMonth, birthDayDOM = birthDayDOM, entityId = entityId, creationTimestamp = creationTimestamp, expirationTimestamp = expirationTimestamp ) companion object : arcs.sdk.EntitySpec<Gold_QCollection> { override val SCHEMA = arcs.core.data.Schema( setOf(arcs.core.data.SchemaName("People")), arcs.core.data.SchemaFields( singletons = mapOf( "name" to arcs.core.data.FieldType.Text, "age" to arcs.core.data.FieldType.Number, "lastCall" to arcs.core.data.FieldType.Number, "address" to arcs.core.data.FieldType.Text, "favoriteColor" to arcs.core.data.FieldType.Text, "birthDayMonth" to arcs.core.data.FieldType.Number, "birthDayDOM" to arcs.core.data.FieldType.Number ), collections = emptyMap() ), "430781483d522f87f27b5cc3d40fd28aa02ca8fd", refinementExpression = true.asExpr(), queryExpression = ((lookup<String>("name") eq query<String>("queryArgument")) and (lookup<Number>("lastCall") lt 259200.asExpr())) ) private val nestedEntitySpecs: Map<String, arcs.sdk.EntitySpec<out arcs.sdk.Entity>> = emptyMap() init { arcs.core.data.SchemaRegistry.register(SCHEMA) } override fun deserialize(data: arcs.core.data.RawEntity) = Gold_QCollection().apply { deserialize(data, nestedEntitySpecs) } } } class Handles : arcs.sdk.HandleHolderBase( "Gold", mapOf( "data" to setOf(Gold_Data), "allPeople" to setOf(Gold_AllPeople), "qCollection" to setOf(Gold_QCollection), "alias" to setOf(Gold_Alias), "collection" to setOf(Foo) ) ) { val data: arcs.sdk.ReadSingletonHandle<Gold_Data> by handles val allPeople: arcs.sdk.ReadCollectionHandle<Gold_AllPeople> by handles val qCollection: arcs.sdk.ReadQueryCollectionHandle<Gold_QCollection, String> by handles val alias: arcs.sdk.WriteSingletonHandle<Gold_Alias_Slice> by handles val collection: arcs.sdk.ReadCollectionHandle<Foo> by handles } }
bsd-3-clause
df1611ddce4179acd0c951904dfeaeea
37.867241
154
0.580801
4.528526
false
false
false
false
firebase/FirebaseUI-Android
lint/src/main/java/com/firebaseui/lint/FirestoreRecyclerAdapterLifecycleDetector.kt
2
4497
package com.firebaseui.lint import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category.Companion.CORRECTNESS import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity.WARNING import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.UClass import org.jetbrains.uast.UField import org.jetbrains.uast.visitor.AbstractUastVisitor import java.util.EnumSet class FirestoreRecyclerAdapterLifecycleDetector : Detector(), Detector.UastScanner { override fun getApplicableUastTypes() = listOf(UClass::class.java) override fun createUastHandler(context: JavaContext) = MissingLifecycleMethodsVisitor(context) class MissingLifecycleMethodsVisitor( private val context: JavaContext ) : UElementHandler() { private val FIRESTORE_RECYCLER_ADAPTER_TYPE = "FirestoreRecyclerAdapter" override fun visitClass(node: UClass) { val adapterReferences = node .fields .filter { FIRESTORE_RECYCLER_ADAPTER_TYPE == it.type.canonicalText } .map { AdapterReference(it) } node.accept(AdapterStartListeningMethodVisitor(adapterReferences)) node.accept(AdapterStopListeningMethodVisitor(adapterReferences)) adapterReferences.forEach { if (it.hasCalledStart && !it.hasCalledStop) { context.report( ISSUE_MISSING_LISTENING_STOP_METHOD, it.uField, context.getLocation(it.uField), "Have called .startListening() without .stopListening()." ) } else if (!it.hasCalledStart) { context.report( ISSUE_MISSING_LISTENING_START_METHOD, it.uField, context.getLocation(it.uField), "Have not called .startListening()." ) } } } } class AdapterStartListeningMethodVisitor( private val adapterReferences: List<AdapterReference> ) : AbstractUastVisitor() { private val START_LISTENING_METHOD_NAME = "startListening" override fun visitCallExpression(node: UCallExpression): Boolean = if (START_LISTENING_METHOD_NAME == node.methodName) { adapterReferences .find { it.uField.name == node.receiver?.asRenderString() } ?.let { it.hasCalledStart = true } true } else { super.visitCallExpression(node) } } class AdapterStopListeningMethodVisitor( private val adapterReferences: List<AdapterReference> ) : AbstractUastVisitor() { private val STOP_LISTENING_METHOD_NAME = "stopListening" override fun visitCallExpression(node: UCallExpression): Boolean = if (STOP_LISTENING_METHOD_NAME == node.methodName) { adapterReferences .find { it.uField.name == node.receiver?.asRenderString() } ?.let { it.hasCalledStop = true } true } else { super.visitCallExpression(node) } } companion object { val ISSUE_MISSING_LISTENING_START_METHOD = Issue.create( "FirestoreAdapterMissingStartListeningMethod", "Checks if FirestoreAdapter has called .startListening() method.", "If a class is using a FirestoreAdapter and does not call startListening it won't be " + "notified on changes.", CORRECTNESS, 10, WARNING, Implementation( FirestoreRecyclerAdapterLifecycleDetector::class.java, EnumSet.of(Scope.JAVA_FILE) ) ) val ISSUE_MISSING_LISTENING_STOP_METHOD = Issue.create( "FirestoreAdapterMissingStopListeningMethod", "Checks if FirestoreAdapter has called .stopListening() method.", "If a class is using a FirestoreAdapter and has called .startListening() but missing " + " .stopListening() might cause issues with RecyclerView data changes.", CORRECTNESS, 10, WARNING, Implementation( FirestoreRecyclerAdapterLifecycleDetector::class.java, EnumSet.of(Scope.JAVA_FILE) ) ) } } data class AdapterReference( val uField: UField, var hasCalledStart: Boolean = false, var hasCalledStop: Boolean = false )
apache-2.0
5acd8e8c5b8130cb54f76929579b169f
34.976
96
0.67356
4.718783
false
false
false
false
fcostaa/kotlin-rxjava-android
library/cache/src/main/kotlin/com/github/felipehjcosta/marvelapp/cache/data/ThumbnailEntity.kt
1
646
package com.github.felipehjcosta.marvelapp.cache.data import androidx.room.* @Entity( tableName = "thumbnail", indices = [Index(value = ["thumbnail_character_id"], name = "thumbnail_character_index")], foreignKeys = [ForeignKey( entity = CharacterEntity::class, parentColumns = ["id"], childColumns = ["thumbnail_character_id"] )] ) data class ThumbnailEntity( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "thumbnail_id") var id: Long = 0L, var path: String = "", var extension: String = "", @ColumnInfo(name = "thumbnail_character_id") var characterId: Long = 0L )
mit
79a6086d95feb8c3fe5c41995f4a70e8
24.84
94
0.647059
4.062893
false
false
false
false
DiUS/pact-jvm
core/model/src/main/kotlin/au/com/dius/pact/core/model/BaseRequest.kt
1
2450
package au.com.dius.pact.core.model import au.com.dius.pact.core.support.Json import au.com.dius.pact.core.support.json.JsonValue import java.io.ByteArrayOutputStream import javax.mail.internet.InternetHeaders import javax.mail.internet.MimeBodyPart import javax.mail.internet.MimeMultipart abstract class BaseRequest : HttpPart() { /** * Sets up the request as a multipart file upload * @param partName The attribute name in the multipart upload that the file is included in * @param contentType The content type of the file data * @param contents File contents */ fun withMultipartFileUpload(partName: String, filename: String, contentType: ContentType, contents: String) = withMultipartFileUpload(partName, filename, contentType.toString(), contents) /** * Sets up the request as a multipart file upload * @param partName The attribute name in the multipart upload that the file is included in * @param contentType The content type of the file data * @param contents File contents */ fun withMultipartFileUpload(partName: String, filename: String, contentType: String, contents: String): BaseRequest { val multipart = MimeMultipart("form-data") val internetHeaders = InternetHeaders() internetHeaders.setHeader("Content-Disposition", "form-data; name=\"$partName\"; filename=\"$filename\"") internetHeaders.setHeader("Content-Type", contentType) multipart.addBodyPart(MimeBodyPart(internetHeaders, contents.toByteArray())) val stream = ByteArrayOutputStream() multipart.writeTo(stream) body = OptionalBody.body(stream.toByteArray(), ContentType(contentType)) headers["Content-Type"] = listOf(multipart.contentType) return this } /** * If this request represents a multipart file upload */ fun isMultipartFileUpload() = contentType().equals("multipart/form-data", ignoreCase = true) companion object { fun parseQueryParametersToMap(query: JsonValue?): Map<String, List<String>> { return when (query) { null -> emptyMap() is JsonValue.Object -> query.entries.entries.associate { entry -> val list = when (entry.value) { is JsonValue.Array -> entry.value.asArray().values.map { Json.toString(it) } else -> emptyList() } entry.key to list } is JsonValue.StringValue -> queryStringToMap(query.asString()) else -> emptyMap() } } } }
apache-2.0
b48a6acdc568f9a7d8122b22d780a636
37.888889
119
0.711837
4.545455
false
false
false
false
ingokegel/intellij-community
platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/writer/apiCode.kt
1
5235
// 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.workspaceModel.codegen import com.intellij.workspaceModel.codegen.classes.* import com.intellij.workspaceModel.codegen.deft.meta.ObjClass import com.intellij.workspaceModel.codegen.deft.meta.ObjProperty import com.intellij.workspaceModel.codegen.deft.meta.OwnProperty import com.intellij.workspaceModel.codegen.deft.meta.ValueType import com.intellij.workspaceModel.codegen.fields.javaMutableType import com.intellij.workspaceModel.codegen.fields.javaType import com.intellij.workspaceModel.codegen.fields.wsCode import com.intellij.workspaceModel.codegen.utils.fqn import com.intellij.workspaceModel.codegen.utils.fqn7 import com.intellij.workspaceModel.codegen.utils.lines import com.intellij.workspaceModel.codegen.writer.allFields import com.intellij.workspaceModel.codegen.writer.isStandardInterface import com.intellij.workspaceModel.codegen.writer.javaName import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type val SKIPPED_TYPES: Set<String> = setOfNotNull(WorkspaceEntity::class.simpleName, ReferableWorkspaceEntity::class.simpleName, ModifiableWorkspaceEntity::class.simpleName, ModifiableReferableWorkspaceEntity::class.simpleName, WorkspaceEntityWithPersistentId::class.simpleName) fun ObjClass<*>.generateBuilderCode(): String = lines { line("@${GeneratedCodeApiVersion::class.fqn}(${CodeGeneratorVersions.API_VERSION})") val (typeParameter, typeDeclaration) = if (openness.extendable) "T" to "<T: $javaFullName>" else javaFullName to "" val superBuilders = superTypes.filterIsInstance<ObjClass<*>>().filter { !it.isStandardInterface }.joinToString { ", ${it.name}.Builder<$typeParameter>" } val header = "interface Builder$typeDeclaration: $javaFullName$superBuilders, ${ModifiableWorkspaceEntity::class.fqn}<$typeParameter>, ${ObjBuilder::class.fqn}<$typeParameter>" section(header) { list(allFields.noPersistentId()) { wsBuilderApi } } } fun ObjClass<*>.generateCompanionObject(): String = lines { val builderGeneric = if (openness.extendable) "<$javaFullName>" else "" val companionObjectHeader = buildString { append("companion object: ${Type::class.fqn}<$javaFullName, Builder$builderGeneric>(") val base = superTypes.filterIsInstance<ObjClass<*>>().firstOrNull() if (base != null && base.name !in SKIPPED_TYPES) append(base.javaFullName) append(")") } val mandatoryFields = allFields.mandatoryFields() if (mandatoryFields.isNotEmpty()) { val fields = mandatoryFields.joinToString { "${it.name}: ${it.valueType.javaType}" } section(companionObjectHeader) { section("operator fun invoke($fields, init: (Builder$builderGeneric.() -> Unit)? = null): $javaFullName") { line("val builder = builder()") list(mandatoryFields) { if (this.valueType is ValueType.Set<*> && !this.valueType.isRefType()) { "builder.$name = $name.${fqn7(Collection<*>::toMutableWorkspaceSet)}()" } else if (this.valueType is ValueType.List<*> && !this.valueType.isRefType()) { "builder.$name = $name.${fqn7(Collection<*>::toMutableWorkspaceList)}()" } else { "builder.$name = $name" } } line("init?.invoke(builder)") line("return builder") } } } else { section(companionObjectHeader) { section("operator fun invoke(init: (Builder$builderGeneric.() -> Unit)? = null): $javaFullName") { line("val builder = builder()") line("init?.invoke(builder)") line("return builder") } } } } fun List<OwnProperty<*, *>>.mandatoryFields(): List<ObjProperty<*, *>> { var fields = this.noRefs().noOptional().noPersistentId().noDefaultValue() if (fields.isNotEmpty()) { fields = fields.noEntitySource() + fields.single { it.name == "entitySource" } } return fields } fun ObjClass<*>.generateExtensionCode(): String? { val fields = module.extensions.filter { it.receiver == this || it.receiver.module != module && it.valueType.isRefType() && it.valueType.getRefType().target == this } if (openness.extendable && fields.isEmpty()) return null return lines { if (!openness.extendable) { line("fun ${MutableEntityStorage::class.fqn}.modifyEntity(entity: $name, modification: $name.Builder.() -> Unit) = modifyEntity($name.Builder::class.java, entity, modification)") } fields.sortedWith(compareBy({ it.receiver.name }, { it.name })).forEach { line(it.wsCode) } } } val ObjProperty<*, *>.wsBuilderApi: String get() { val returnType = if (valueType is ValueType.Collection<*, *> && !valueType.isRefType()) valueType.javaMutableType else valueType.javaType return "override var $javaName: $returnType" }
apache-2.0
bc8d8fe852f800d6ba15e0aea848126a
46.162162
184
0.69914
4.520725
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/store/avatar/usecase/BuyAvatarUseCase.kt
1
1167
package io.ipoli.android.store.avatar.usecase import io.ipoli.android.common.UseCase import io.ipoli.android.player.data.Avatar import io.ipoli.android.player.data.Player import io.ipoli.android.player.persistence.PlayerRepository /** * Created by Venelin Valkov <[email protected]> * on 03/25/2018. */ class BuyAvatarUseCase(private val playerRepository: PlayerRepository) : UseCase<BuyAvatarUseCase.Params, BuyAvatarUseCase.Result> { override fun execute(parameters: Params): Result { val player = playerRepository.find() requireNotNull(player) val avatar = parameters.avatar require(!player!!.inventory.hasAvatar(avatar)) if (player.gems < avatar.gemPrice) { return Result.TooExpensive } val newPlayer = player.copy( gems = player.gems - avatar.gemPrice, inventory = player.inventory.addAvatar(avatar) ) return Result.Bought(playerRepository.save(newPlayer)) } data class Params(val avatar: Avatar) sealed class Result { data class Bought(val player: Player) : Result() object TooExpensive : Result() } }
gpl-3.0
e7cd86720d9efc36469b520e427bcf34
28.948718
72
0.688089
4.228261
false
false
false
false
GunoH/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/dataframe/ColumnUtils.kt
9
1379
/* * Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.plugins.notebooks.visualization.r.inlays.dataframe import org.jetbrains.plugins.notebooks.visualization.r.inlays.dataframe.columns.Column class ColumnUtils { companion object { /** * Checks that the Number is ordered (does not matters ascendant or descendant). Applicable only for numerical columns. * Column contains only null values will be ordered. */ fun isColumnOrdered(column: Column<out Number>): Boolean { if(column.size < 2) { return true } var prev = -1 var order: Boolean? = null for (i in 0 until column.size) { if(column.isNull(i)) continue if(prev==-1) { prev = i continue } if(order == null) { order = column[prev].toDouble() <= column[i].toDouble() } else { if (order != column[prev].toDouble() <= column[i].toDouble()) { return false } } prev = i } return true } } }
apache-2.0
bb740d511f1d402ba01cd7a345bb2b9a
27.75
140
0.504714
4.925
false
false
false
false
GunoH/intellij-community
plugins/kotlin/compiler-plugins/compiler-plugin-support/common/src/org/jetbrains/kotlin/idea/compilerPlugin/idePluginUtils.kt
4
2803
// 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.compilerPlugin import com.intellij.openapi.module.Module import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCommonCompilerArgumentsHolder import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.facet.KotlinFacet import org.jetbrains.kotlin.idea.facet.getInstance import org.jetbrains.kotlin.idea.macros.KOTLIN_BUNDLED import java.io.File fun Module.getSpecialAnnotations(prefix: String): List<String> = KotlinCommonCompilerArgumentsHolder.getInstance(this).pluginOptions ?.filter { it.startsWith(prefix) } ?.map { it.substring(prefix.length) } ?: emptyList() class CompilerPluginSetup(val options: List<PluginOption>, val classpath: List<String>) { class PluginOption(val key: String, val value: String) } fun File.toJpsVersionAgnosticKotlinBundledPath(): String { val kotlincDirectory = KotlinPluginLayout.kotlinc require(this.startsWith(kotlincDirectory)) { "$this should start with ${kotlincDirectory}" } return "\$$KOTLIN_BUNDLED\$/${this.relativeTo(kotlincDirectory)}" } fun modifyCompilerArgumentsForPlugin( facet: KotlinFacet, setup: CompilerPluginSetup?, compilerPluginId: String, pluginName: String ) { val facetSettings = facet.configuration.settings // investigate why copyBean() sometimes throws exceptions val commonArguments = facetSettings.compilerArguments ?: CommonCompilerArguments.DummyImpl() /** See [CommonCompilerArguments.PLUGIN_OPTION_FORMAT] **/ val newOptionsForPlugin = setup?.options?.map { "plugin:$compilerPluginId:${it.key}=${it.value}" } ?: emptyList() val oldAllPluginOptions = (commonArguments.pluginOptions ?: emptyArray()).filterTo(mutableListOf()) { !it.startsWith("plugin:$compilerPluginId:") } val newAllPluginOptions = oldAllPluginOptions + newOptionsForPlugin val oldPluginClasspaths = (commonArguments.pluginClasspaths ?: emptyArray()).filterTo(mutableListOf()) { val lastIndexOfFile = it.lastIndexOfAny(charArrayOf('/', File.separatorChar)) if (lastIndexOfFile < 0) { return@filterTo true } !it.drop(lastIndexOfFile + 1).matches("(kotlin-)?(maven-)?$pluginName-.*\\.jar".toRegex()) } val newPluginClasspaths = oldPluginClasspaths + (setup?.classpath ?: emptyList()) commonArguments.pluginOptions = newAllPluginOptions.toTypedArray() commonArguments.pluginClasspaths = newPluginClasspaths.toTypedArray() facetSettings.compilerArguments = commonArguments }
apache-2.0
a7c25147a3125ddb0e2bda76605f12ea
44.225806
158
0.758473
4.799658
false
false
false
false
marius-m/wt4
models/src/main/java/lt/markmerkk/entities/Ticket.kt
1
2727
package lt.markmerkk.entities import lt.markmerkk.Const data class Ticket( val id: Long = Const.NO_ID, val code: TicketCode = TicketCode.asEmpty(), val description: String = "", val parentId: Long = Const.NO_ID, // todo up of removal val status: String, val assigneeName: String, val reporterName: String, val isWatching: Boolean, val parentCode: TicketCode, val remoteData: RemoteData? = null ) { fun clearStatus(): Ticket { return Ticket( id = id, code = code, description = description, parentId = parentId, status = "", assigneeName = assigneeName, reporterName = reporterName, isWatching = isWatching, parentCode = parentCode, remoteData = remoteData ) } companion object { fun new( code: String, description: String, remoteData: RemoteData? ): Ticket { return Ticket( code = TicketCode.new(code), description = description, status = "", parentCode = TicketCode.asEmpty(), assigneeName = "", reporterName = "", isWatching = false, remoteData = remoteData ) } fun fromRemoteData( code: String, description: String, status: String, assigneeName: String, reporterName: String, isWatching: Boolean, parentCode: String, remoteData: RemoteData? ): Ticket { return Ticket( code = TicketCode.new(code), description = description, status = status, assigneeName = assigneeName, reporterName = reporterName, isWatching = isWatching, parentCode = TicketCode.new(parentCode), remoteData = remoteData ) } } } fun Ticket.markAsError( errorMessage: String ): Ticket { return Ticket( id = id, code = code, description = description, parentId = parentId, status = status, assigneeName = assigneeName, reporterName = reporterName, isWatching = isWatching, parentCode = parentCode, remoteData = remoteData.markAsError(errorMessage) ) }
apache-2.0
fbc13f3d40d34891a9e5b3f49334b66e
29.3
63
0.478915
5.8394
false
false
false
false
evanchooly/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/MavenId.kt
1
3004
package com.beust.kobalt.maven import com.beust.kobalt.api.Kobalt import org.eclipse.aether.artifact.DefaultArtifact /** * Encapsulate a Maven id captured in one string, as used by Gradle or Ivy, e.g. "org.testng:testng:6.9.9". * These id's are somewhat painful to manipulate because on top of containing groupId, artifactId * and version, they also accept an optional packaging (e.g. "aar") and qualifier (e.g. "no_aop"). * Determining which is which in an untyped string separated by colons is not clearly defined so * this class does a best attempt at deconstructing an id but there's surely room for improvement. * * This class accepts a versionless id, which needs to end with a :, e.g. "com.beust:jcommander:" (which * usually means "latest version") but it doesn't handle version ranges yet. */ class MavenId private constructor(val groupId: String, val artifactId: String, val packaging: String?, val classifier: String?, val version: String?) { companion object { fun isMavenId(id: String) = with(id.split(":")) { size >= 3 && size <= 5 } fun isRangedVersion(s: String): Boolean { return s.first() in listOf('[', '(') && s.last() in listOf(']', ')') } /** * Similar to create(MavenId) but don't run IMavenIdInterceptors. */ fun createNoInterceptors(id: String) : MavenId = DefaultArtifact(id).run { MavenId(groupId, artifactId, extension, classifier, version) } fun toKobaltId(id: String) = if (id.endsWith(":")) id + "(0,]" else id /** * The main entry point to create Maven Id's. Id's created by this function * will run through IMavenIdInterceptors. */ fun create(originalId: String) : MavenId { val id = toKobaltId(originalId) var originalMavenId = createNoInterceptors(id) var interceptedMavenId = originalMavenId val interceptors = Kobalt.context?.pluginInfo?.mavenIdInterceptors if (interceptors != null) { interceptedMavenId = interceptors.fold(originalMavenId, { id, interceptor -> interceptor.intercept(id) }) } return interceptedMavenId } fun create(groupId: String, artifactId: String, packaging: String?, classifier: String?, version: String?) = create(toId(groupId, artifactId, packaging, classifier, version)) fun toId(groupId: String, artifactId: String, packaging: String? = null, classifier: String? = null, version: String?) = "$groupId:$artifactId" + (if (packaging != null && packaging != "") ":$packaging" else "") + (if (classifier != null && classifier != "") ":$classifier" else "") + ":$version" } val hasVersion = version != null val toId = MavenId.toId(groupId, artifactId, packaging, classifier, version) }
apache-2.0
593056fc44a7ccfba94cd1565c67090e
42.536232
128
0.62217
4.510511
false
false
false
false
eyyoung/idea-plugin-custom-ui-panel
src/main/kotlin/com/nd/sdp/common/model/Widget.kt
1
712
package com.nd.sdp.common.model /** * 控件Bean * Created by Young on 2017/7/3. */ class Widget { var name: String? = null var repository: String? = null var readme: String? = null var more: String? = null var image: String? = null var imageWiki: String? = null var category: String? = null var xml: String? = null var java: String? = null var defaultType: String? = null var dependency: Dependency? = null var wiki: String? = null var dependencies: Dependencies? = null override fun toString(): String { return if (name == null) "" else name!! } fun getSearchInfo(): String { return name + readme + more + category } }
mit
4514716ec021dcc9eedf20443ef0fa9f
22.6
47
0.611582
3.806452
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_gpu_shader_fp64.kt
4
9038
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* val ARB_gpu_shader_fp64 = "ARBGPUShaderFP64".nativeClassGL("ARB_gpu_shader_fp64") { documentation = """ Native bindings to the $registryLink extension. This extension allows GLSL shaders to use double-precision floating-point data types, including vectors and matrices of doubles. Doubles may be used as inputs, outputs, and uniforms. The shading language supports various arithmetic and comparison operators on double-precision scalar, vector, and matrix types, and provides a set of built-in functions including: ${ul( "square roots and inverse square roots;", "fused floating-point multiply-add operations;", """ splitting a floating-point number into a significand and exponent (frexp), or building a floating-point number from a significand and exponent (ldexp); """, """ absolute value, sign tests, various functions to round to an integer value, modulus, minimum, maximum, clamping, blending two values, step functions, and testing for infinity and NaN values; """, "packing and unpacking doubles into a pair of 32-bit unsigned integers;", "matrix component-wise multiplication, and computation of outer products, transposes, determinants, and inverses; and", "vector relational functions." )} Double-precision versions of angle, trigonometry, and exponential functions are not supported. Implicit conversions are supported from integer and single-precision floating-point values to doubles, and this extension uses the relaxed function overloading rules specified by the ARB_gpu_shader5 extension to resolve ambiguities. This extension provides API functions for specifying double-precision uniforms in the default uniform block, including functions similar to the uniform functions added by ${EXT_direct_state_access.link} (if supported). This extension provides an "LF" suffix for specifying double-precision constants. Floating-point constants without a suffix in GLSL are treated as single-precision values for backward compatibility with versions not supporting doubles; similar constants are treated as double-precision values in the "C" programming language. This extension does not support interpolation of double-precision values; doubles used as fragment shader inputs must be qualified as "flat". Additionally, this extension does not allow vertex attributes with 64-bit components. That support is added separately by ${registryLinkTo("EXT", "vertex_attrib_64bit")}. Requires ${GL32.link} and GLSL 1.50. ${GL40.promoted} """ IntConstant( "Returned in the {@code type} parameter of GetActiveUniform, and GetTransformFeedbackVarying.", "DOUBLE_VEC2"..0x8FFC, "DOUBLE_VEC3"..0x8FFD, "DOUBLE_VEC4"..0x8FFE, "DOUBLE_MAT2"..0x8F46, "DOUBLE_MAT3"..0x8F47, "DOUBLE_MAT4"..0x8F48, "DOUBLE_MAT2x3"..0x8F49, "DOUBLE_MAT2x4"..0x8F4A, "DOUBLE_MAT3x2"..0x8F4B, "DOUBLE_MAT3x4"..0x8F4C, "DOUBLE_MAT4x2"..0x8F4D, "DOUBLE_MAT4x3"..0x8F4E ) reuse(GL40C, "Uniform1d") reuse(GL40C, "Uniform2d") reuse(GL40C, "Uniform3d") reuse(GL40C, "Uniform4d") reuse(GL40C, "Uniform1dv") reuse(GL40C, "Uniform2dv") reuse(GL40C, "Uniform3dv") reuse(GL40C, "Uniform4dv") reuse(GL40C, "UniformMatrix2dv") reuse(GL40C, "UniformMatrix3dv") reuse(GL40C, "UniformMatrix4dv") reuse(GL40C, "UniformMatrix2x3dv") reuse(GL40C, "UniformMatrix2x4dv") reuse(GL40C, "UniformMatrix3x2dv") reuse(GL40C, "UniformMatrix3x4dv") reuse(GL40C, "UniformMatrix4x2dv") reuse(GL40C, "UniformMatrix4x3dv") reuse(GL40C, "GetUniformdv") val program = GLuint("program", "the program object to update") var src = GL40C["Uniform1d"] IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void( "ProgramUniform1dEXT", "DSA version of #Uniform1d().", program, src["location"], src["x"] ) src = GL40C["Uniform2d"] IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void( "ProgramUniform2dEXT", "DSA version of #Uniform2d().", program, src["location"], src["x"], src["y"] ) src = GL40C["Uniform3d"] IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void( "ProgramUniform3dEXT", "DSA version of #Uniform3d().", program, src["location"], src["x"], src["y"], src["z"] ) src = GL40C["Uniform4d"] IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void( "ProgramUniform4dEXT", "DSA version of #Uniform4d().", program, src["location"], src["x"], src["y"], src["z"], src["w"] ) src = GL40C["Uniform1dv"] IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void( "ProgramUniform1dvEXT", "DSA version of #Uniform1dv().", program, src["location"], src["count"], src["value"] ) src = GL40C["Uniform2dv"] IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void( "ProgramUniform2dvEXT", "DSA version of #Uniform2dv().", program, src["location"], src["count"], src["value"] ) src = GL40C["Uniform3dv"] IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void( "ProgramUniform3dvEXT", "DSA version of #Uniform3dv().", program, src["location"], src["count"], src["value"] ) src = GL40C["Uniform4dv"] IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void( "ProgramUniform4dvEXT", "DSA version of #Uniform4dv().", program, src["location"], src["count"], src["value"] ) src = GL40C["UniformMatrix2dv"] IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void( "ProgramUniformMatrix2dvEXT", "DSA version of #UniformMatrix2dv().", program, src["location"], src["count"], src["transpose"], src["value"] ) src = GL40C["UniformMatrix3dv"] IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void( "ProgramUniformMatrix3dvEXT", "DSA version of #UniformMatrix3dv().", program, src["location"], src["count"], src["transpose"], src["value"] ) src = GL40C["UniformMatrix4dv"] IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void( "ProgramUniformMatrix4dvEXT", "DSA version of #UniformMatrix4dv().", program, src["location"], src["count"], src["transpose"], src["value"] ) src = GL40C["UniformMatrix2x3dv"] IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void( "ProgramUniformMatrix2x3dvEXT", "DSA version of #UniformMatrix2x3dv().", program, src["location"], src["count"], src["transpose"], src["value"] ) src = GL40C["UniformMatrix2x4dv"] IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void( "ProgramUniformMatrix2x4dvEXT", "DSA version of #UniformMatrix2x4dv().", program, src["location"], src["count"], src["transpose"], src["value"] ) src = GL40C["UniformMatrix3x2dv"] IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void( "ProgramUniformMatrix3x2dvEXT", "DSA version of #UniformMatrix3x2dv().", program, src["location"], src["count"], src["transpose"], src["value"] ) src = GL40C["UniformMatrix3x4dv"] IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void( "ProgramUniformMatrix3x4dvEXT", "DSA version of #UniformMatrix3x4dv().", program, src["location"], src["count"], src["transpose"], src["value"] ) src = GL40C["UniformMatrix4x2dv"] IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void( "ProgramUniformMatrix4x2dvEXT", "DSA version of #UniformMatrix4x2dv().", program, src["location"], src["count"], src["transpose"], src["value"] ) src = GL40C["UniformMatrix4x3dv"] IgnoreMissing..DependsOn("GL_EXT_direct_state_access")..void( "ProgramUniformMatrix4x3dvEXT", "DSA version of #UniformMatrix4x3dv().", program, src["location"], src["count"], src["transpose"], src["value"] ) }
bsd-3-clause
44d526e48f15d78f49cf04ef214009c9
29.955479
160
0.61341
4.089593
false
false
false
false
aerisweather/AerisAndroidSDK
Kotlin/AerisSdkDemo/app/src/main/java/com/example/demoaerisproject/view/locations/LocationSearchActivity.kt
1
10026
package com.example.demoaerisproject.view.locations import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CornerSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.window.DialogProperties import androidx.lifecycle.Observer import com.aerisweather.aeris.response.PlacesResponse import com.example.demoaerisproject.R import com.example.demoaerisproject.data.room.MyPlace import com.example.demoaerisproject.view.BaseActivity import com.example.demoaerisproject.view.ComposeSnackbar import com.example.demoaerisproject.view.ComposeSpinner import dagger.hilt.android.AndroidEntryPoint import java.util.* @AndroidEntryPoint class LocationSearchActivity : BaseActivity() { private val viewModel: LocationSearchViewModel by viewModels() private val DEBOUNCE_LIMIT = 1500L // seconds private var outlineTextValue: String = "" override fun onCreate(savedInstanceState: Bundle?) { setContent { Box( Modifier .fillMaxSize() .background(Color.Black) .testTag("init_black_box") ) } actionBarTitle = resources.getString(R.string.activity_search) super.onCreate(savedInstanceState) } override fun onResume() { super.onResume() viewModel.event.observe(this, Observer(::onViewModelEvent)) } private fun onViewModelEvent(event: SearchEvent) { setContent { when (event) { is SearchEvent.Success -> { Render(event) } is SearchEvent.InProgress -> { Render() ComposeSpinner() } is SearchEvent.Error -> { Render() ComposeSnackbar(event.msg) } } } } @Composable private fun Render(event: SearchEvent.Success? = null) { Column( modifier = Modifier .fillMaxSize() .background(Color.Black) ) { Row( modifier = Modifier .fillMaxWidth() .padding(10.dp, 10.dp, 10.dp, 10.dp) ) { val focusRequester = remember { FocusRequester() } val editTextString = remember { mutableStateOf( TextFieldValue( text = outlineTextValue, selection = TextRange(outlineTextValue.length) ) ) } var timer: Timer? = null val debounce: (str: String) -> Unit = { timer = Timer() timer?.apply { schedule( object : TimerTask() { override fun run() { viewModel.search(it) cancel() } }, DEBOUNCE_LIMIT, 5000 ) } } OutlinedTextField( value = editTextString.value, label = { Text( text = stringResource(id = R.string.text_input), style = TextStyle(color = Color.Gray) ) }, onValueChange = { editTextString.value = it if (outlineTextValue != it.text) { timer?.cancel() debounce(it.text) outlineTextValue = it.text } }, colors = TextFieldDefaults.outlinedTextFieldColors( textColor = Color.White, focusedBorderColor = Color.Gray, unfocusedBorderColor = Color.Gray ), modifier = Modifier .testTag("search_text") .focusRequester(focusRequester) ) LaunchedEffect(Unit) { focusRequester.requestFocus() } Box( modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd ) { IconButton(onClick = { viewModel.search(outlineTextValue) }) { Icon( painterResource(id = R.drawable.ic_search), contentDescription = resources.getString(R.string.activity_search), tint = Color.White, modifier = Modifier.padding(0.dp, 10.dp, 10.dp, 0.dp), ) } } } if (event?.response?.isNotEmpty() == true) { LazyColumn( contentPadding = PaddingValues( horizontal = 16.dp, vertical = 8.dp ) ) { items( items = event.response, itemContent = { ComposeListPlace(place = it) }) } } } } @Composable private fun ComposeListPlace(place: PlacesResponse) { val openDialog = remember { mutableStateOf(false) } Card( Modifier .padding(horizontal = 5.dp, vertical = 5.dp) .fillMaxWidth() .background(Color.Black) .clickable { openDialog.value = true }, shape = RoundedCornerShape(corner = CornerSize(8.dp)) ) { Column( modifier = Modifier .fillMaxWidth() .background(Color.Black) ) { place.place.apply { Text( text = resources.getString( R.string.city_state_country, name ?: city, state, country ), color = Color.White, fontSize = 18.sp, modifier = Modifier.padding(10.dp) ) } Divider(color = Color(0xFF808080), thickness = 1.dp) } } if (openDialog.value) { AlertDialog(onDismissRequest = { openDialog.value = false }, properties = DialogProperties( dismissOnClickOutside = true, dismissOnBackPress = true ), title = { Text(resources.getString(R.string.alert_dlg_confirm_title)) }, text = { Text(resources.getString(R.string.alert_dlg_confirm_desc)) }, confirmButton = { Button(onClick = { onDlgConfirm(place) openDialog.value = false }) { Text(text = resources.getString(R.string.alert_dlg_yes)) } }, dismissButton = { Button(onClick = { openDialog.value = false }) { Text(text = resources.getString(R.string.alert_dlg_cancel)) } } ) } } var onDlgConfirm: (myPlace: PlacesResponse?) -> Unit = { it?.apply { viewModel.addLocation( myPlace = MyPlace( place.name ?: place.city, place.state, place.country, true, location.lat, location.lon ) ) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { val inflater = menuInflater inflater.inflate(R.menu.menu_search, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menuLocateMe -> { viewModel.locateMe() return true } R.id.menuMyLocs -> { startActivity(Intent(this, MyLocsActivity::class.java)) return true } } return super.onOptionsItemSelected(item) } }
mit
84dbb0b69f2a11497bf6a637d09fbf02
34.431095
95
0.489727
5.725871
false
false
false
false
senyuyuan/Gluttony
gluttony-realm/src/main/java/sen/yuan/dao/gluttony_realm/realm_save.kt
1
1263
package sen.yuan.dao.gluttony_realm import io.realm.RealmObject /** * Created by Administrator on 2016/11/23. */ /** * @return 托管状态 的 model * */ fun <T : RealmObject> T.save(): T { val mClassAnnotations = this.javaClass.kotlin.annotations var managedData: T = this Gluttony.realm.executeTransaction { // var person = DynamicRealm.getInstance(RealmConfiguration.Builder().build()).createObject("person") if (mClassAnnotations.firstOrNull { it is Singleton } != null) { it.delete(this.javaClass) } managedData = it.copyToRealm(this@save) } return managedData } // ///** // * 对单例模式数据的支持:寻找 // * // * 注意:必须有@Singleton注解的Int字段 // * */ //inline fun <reified T : RealmObject> T.saveSingleton(): T? { // var managedData: T = this // Gluttony.realm.executeTransaction { // managedData = it.copyToRealm(this@saveSingleton) // } // return managedData //} /** * @return 托管状态 的 model * */ inline fun <reified T : RealmObject> T.updateOrSave(): T { var managedData: T = this Gluttony.realm.executeTransaction { managedData = it.copyToRealmOrUpdate(this@updateOrSave) } return managedData }
apache-2.0
7d02dafc78361008f5dcbce66bb7cf52
20.818182
108
0.648874
3.622356
false
false
false
false
mctoyama/PixelServer
src/main/kotlin/org/pixelndice/table/pixelserver/connection/main/state04joingame/State05WaitingQueryGame.kt
1
3209
package org.pixelndice.table.pixelserver.connection.main.state04joingame import com.google.common.base.Throwables import org.apache.logging.log4j.LogManager import org.hibernate.Session import org.pixelndice.table.pixelprotocol.Protobuf import org.pixelndice.table.pixelserver.connection.main.Context import org.pixelndice.table.pixelserver.connection.main.State import org.pixelndice.table.pixelserver.connection.main.State03JoinOrHostGame import org.pixelndice.table.pixelserver.sessionFactory import org.pixelndice.table.pixelserverhibernate.Game import org.pixelndice.table.pixelserverhibernate.RPGGameSystem private val logger = LogManager.getLogger(State05WaitingQueryGame::class.java) class State05WaitingQueryGame: State { override fun process(ctx: Context) { // one get operation val p = ctx.channel.packet val resp = Protobuf.Packet.newBuilder() if (p != null) { if (p.payloadCase == Protobuf.Packet.PayloadCase.QUERYGAME) { var session: Session? = null try { session = sessionFactory.openSession() val query = session.createNamedQuery("gameByUUID", Game::class.java) query.setParameter("uuid", p.queryGame.uuid) val list = query.list() if (list.isEmpty()) { val notFound = Protobuf.GameNotFound.newBuilder() resp.gameNotFound = notFound.build() ctx.channel.packet = resp.build() } else { val gameFound = list.get(0) val gameByUUID = Protobuf.GameByUUID.newBuilder() val game = Protobuf.Game.newBuilder() game.uuid = p.queryGame.uuid val gm = Protobuf.Account.newBuilder() gm.id = gameFound.gm!!.id!! gm.email = gameFound.gm!!.email gm.name = gameFound.gm!!.name game.gm = gm.build() game.campaign = gameFound.campaign game.rpgGameSystem = RPGGameSystem.toProtobuf(gameFound.rpgGameSystem) game.hostname = gameFound.hostname game.port = gameFound.port gameByUUID.game = game.build() resp.gameByUuid = gameByUUID.build() ctx.channel.packet = resp.build() } ctx.state = State03JoinOrHostGame() }catch (e: Exception){ logger.fatal("Hibernate fatal error!") logger.fatal(Throwables.getStackTraceAsString(e)) }finally { session?.close() } }else{ logger.error("Expecting QueryGame. Instead Received: $p") val rend = Protobuf.EndWithError.newBuilder() rend.reason = "key.expectingquerygame" resp.setEndWithError(rend) ctx.channel.packet = resp.build() } } } }
bsd-2-clause
c0af2df700294dc8ebae164d839fd52c
34.274725
94
0.560299
4.936923
false
false
false
false
airbnb/epoxy
epoxy-composesample/src/main/java/com/airbnb/epoxy/compose/sample/ComposableInteropActivity.kt
1
2451
package com.airbnb.epoxy.compose.sample import android.os.Bundle import androidx.activity.ComponentActivity import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.Divider import androidx.compose.material.Text 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.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.airbnb.epoxy.EpoxyRecyclerView import com.airbnb.epoxy.composableInterop import com.airbnb.epoxy.compose.sample.epoxyviews.headerView class ComposableInteropActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_composable_interop) val recyclerView: EpoxyRecyclerView = findViewById(R.id.epoxy_recycler_view) recyclerView.withModels { headerView { id("header") title("Testing Composable in Epoxy") } for (i in 0..100) { composableInterop(id = "compose_text_$i") { ShowCaption("Caption coming from composable") } composableInterop(id = "news_$i") { NewsStory() } } } } } @Composable @Preview fun NewsStory() { Column( modifier = Modifier.padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { Image( painter = painterResource(id = R.drawable.header), contentDescription = null ) ShowCaption("Above Image and below text are coming from Compose in Epoxy") ShowCaption("Davenport, California") ShowCaption("December 2021") Divider( color = Color(0x859797CF), thickness = 2.dp, modifier = Modifier.padding(top = 16.dp) ) } } @Composable fun ShowCaption(text: String) { Text( text, textAlign = TextAlign.Center, modifier = Modifier .padding(4.dp) .fillMaxWidth() ) }
apache-2.0
5db3a1902571c048dfc7a581433b7a0c
28.890244
84
0.663403
4.607143
false
false
false
false
BreakOutEvent/breakout-backend
src/main/java/backend/model/posting/PostingRepository.kt
1
1577
package backend.model.posting import org.springframework.data.domain.Pageable import org.springframework.data.jpa.repository.Query import org.springframework.data.repository.CrudRepository import org.springframework.data.repository.query.Param interface PostingRepository : CrudRepository<Posting, Long> { fun findById(id: Long): Posting @Query("select p from Posting p inner join p.hashtags h where h.value = :hashtag order by p.id desc") fun findByHashtag(@Param("hashtag") hashtag: String, pageable: Pageable): List<Posting> fun findAllByOrderByIdDesc(pageable: Pageable): List<Posting> fun findByTeamEventIdInOrderByIdDesc(eventIdList: List<Long>, pageable: Pageable): List<Posting> @Query("select p from Posting p where p.reported = true") fun findReported(): List<Posting> fun findAllByUserId(userId: Long): List<Posting> @Query("select distinct p from Posting p inner join p.comments c where c.user.id = :userId") fun findAllCommentedByUser(@Param("userId") userId: Long): List<Posting> @Query("select p from Posting p inner join p.likes l where l.user.id = :userId") fun findAllLikedByUser(@Param("userId") userId: Long): List<Posting> @Query("select p from Posting p where p.challenge = :challengeId") fun findAllByChallengeId(@Param("challengeId") challengeId: Long): List<Posting> @Query(""" select * from posting where team_id = :id order by id desc limit 1 """, nativeQuery = true) fun findLastPostingByTeamId(@Param("id") id: Long): Posting? }
agpl-3.0
a01a230eafbd137bcf12ef93733b9588
38.425
105
0.722257
4.117493
false
false
false
false
paplorinc/intellij-community
python/src/com/jetbrains/python/testing/PyUnitTest.kt
6
4246
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.testing import com.intellij.execution.Executor import com.intellij.execution.configurations.RunProfileState import com.intellij.execution.configurations.RuntimeConfigurationWarning import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.options.SettingsEditor import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.LocalFileSystem import com.jetbrains.python.PyNames import com.jetbrains.python.PythonHelper import com.jetbrains.python.run.targetBasedConfiguration.PyRunTargetVariant /** * unittest */ class PyUnitTestSettingsEditor(configuration: PyAbstractTestConfiguration) : PyAbstractTestSettingsEditor( PyTestSharedForm.create(configuration, PyTestSharedForm.CustomOption(PyUnitTestConfiguration::pattern.name, PyRunTargetVariant.PATH) )) class PyUnitTestExecutionEnvironment(configuration: PyUnitTestConfiguration, environment: ExecutionEnvironment) : PyTestExecutionEnvironment<PyUnitTestConfiguration>(configuration, environment) { override fun getRunner(): PythonHelper = // different runner is used for setup.py if (configuration.isSetupPyBased()) { PythonHelper.SETUPPY } else { PythonHelper.UNITTEST } } class PyUnitTestConfiguration(project: Project, factory: PyUnitTestFactory) : PyAbstractTestConfiguration(project, factory, PythonTestConfigurationsModel.PYTHONS_UNITTEST_NAME) { // Bare functions not supported in unittest: classes only @ConfigField var pattern: String? = null override fun getState(executor: Executor, environment: ExecutionEnvironment): RunProfileState? = PyUnitTestExecutionEnvironment(this, environment) override fun createConfigurationEditor(): SettingsEditor<PyAbstractTestConfiguration> = PyUnitTestSettingsEditor(this) override fun getCustomRawArgumentsString(forRerun: Boolean): String { // Pattern can only be used with folders ("all in folder" in legacy terms) if ((!pattern.isNullOrEmpty()) && target.targetType != PyRunTargetVariant.CUSTOM) { val path = LocalFileSystem.getInstance().findFileByPath(target.target) ?: return "" // "Pattern" works only for "discovery" mode and for "rerun" we are using "python" targets ("concrete" tests) return if (path.isDirectory && !forRerun) "-p $pattern" else "" } else { return "" } } /** * @return configuration should use runner for setup.py */ internal fun isSetupPyBased(): Boolean { val setupPy = target.targetType == PyRunTargetVariant.PATH && target.target.endsWith(PyNames.SETUP_DOT_PY) return setupPy } // setup.py runner is not id-based override fun isIdTestBased(): Boolean = !isSetupPyBased() override fun checkConfiguration() { super.checkConfiguration() if (target.targetType == PyRunTargetVariant.PATH && target.target.endsWith(".py") && !pattern.isNullOrEmpty()) { throw RuntimeConfigurationWarning("Pattern can only be used to match files in folder. Can't use pattern for file.") } } override fun isFrameworkInstalled(): Boolean = true //Unittest is always available // Unittest does not support filesystem path. It needs qname resolvable against root or working directory override fun shouldSeparateTargetPath() = false } object PyUnitTestFactory : PyAbstractTestFactory<PyUnitTestConfiguration>() { override fun createTemplateConfiguration(project: Project): PyUnitTestConfiguration = PyUnitTestConfiguration(project, this) override fun getName(): String = PythonTestConfigurationsModel.PYTHONS_UNITTEST_NAME }
apache-2.0
e619162f4d5db1c637a81220ace19c52
37.963303
142
0.760716
4.977726
false
true
false
false
paplorinc/intellij-community
java/java-tests/testSrc/com/intellij/copyright/JavaCopyrightTest.kt
6
1704
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.copyright import com.intellij.ide.highlighter.JavaFileType import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase import com.maddyhome.idea.copyright.CopyrightProfile import com.maddyhome.idea.copyright.psi.UpdateCopyrightFactory class JavaCopyrightTest : LightPlatformCodeInsightFixtureTestCase() { fun testMultipleCopyrightsInOneFile() { myFixture.configureByText(JavaFileType.INSTANCE, """ /** * Copyright JetBrains */ /** * Copyright empty */ class A {} """) updateCopyright() myFixture.checkResult(""" /* * Copyright text * copyright text */ /** * Copyright empty */ class A {} """) } fun testMultipleCopyrightsInOneFileOneRemoved() { myFixture.configureByText(JavaFileType.INSTANCE, """ /* * Copyright JetBrains * second line */ /* * Copyright JetBrains */ public class A {} """) updateCopyright() myFixture.checkResult(""" /* * Copyright text * copyright text */ public class A {} """) } @Throws(Exception::class) private fun updateCopyright() { val options = CopyrightProfile() options.notice = "Copyright text\ncopyright text" options.keyword = "Copyright" options.allowReplaceRegexp = "JetBrains" val updateCopyright = UpdateCopyrightFactory.createUpdateCopyright(myFixture.project, myFixture.module, myFixture.file, options) updateCopyright!!.prepare() updateCopyright.complete() } }
apache-2.0
7c6926136e78a45852ad8b3faa4aae3d
21.733333
140
0.680751
4.746518
false
true
false
false
nibarius/opera-park-android
app/src/main/java/se/barsk/park/analytics/Analytics.kt
1
654
package se.barsk.park.analytics import android.content.Context import com.google.firebase.analytics.FirebaseAnalytics import se.barsk.park.ParkApp /** * Object for handling all analytics reporting. */ class Analytics(context: Context) { private val fa: FirebaseAnalytics = FirebaseAnalytics.getInstance(context) fun optOutToggled() = updateOptOutState() fun logEvent(event: AnalyticsEvent) = fa.logEvent(event.name, event.parameters) fun setProperty(property: String, value: String) = fa.setUserProperty(property, value) private fun updateOptOutState() = fa.setAnalyticsCollectionEnabled(ParkApp.storageManager.statsEnabled()) }
mit
d1c84f4b5a2c51adf51bd2f3c3d58c07
35.388889
109
0.785933
4.36
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureHandler.kt
2
11452
// 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.refactoring.changeSignature import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiMethod import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.parentOfType import com.intellij.refactoring.HelpID import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.changeSignature.ChangeSignatureHandler import com.intellij.refactoring.changeSignature.ChangeSignatureUtil import com.intellij.refactoring.util.CommonRefactoringUtil import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZED import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.surroundWith.KotlinSurrounderUtils import org.jetbrains.kotlin.idea.intentions.isInvokeOperator import org.jetbrains.kotlin.idea.util.expectedDescriptor import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.tasks.isDynamic import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments class KotlinChangeSignatureHandler : ChangeSignatureHandler { override fun findTargetMember(element: PsiElement) = findTargetForRefactoring(element) override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext) { editor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE) val element = findTargetMember(file, editor) ?: CommonDataKeys.PSI_ELEMENT.getData(dataContext) ?: return val elementAtCaret = file.findElementAt(editor.caretModel.offset) ?: return if (element !is KtElement) throw KotlinExceptionWithAttachments("This handler must be invoked for Kotlin elements only: ${element::class.java}") .withAttachment("element", element) invokeChangeSignature(element, elementAtCaret, project, editor) } override fun invoke(project: Project, elements: Array<PsiElement>, dataContext: DataContext?) { val element = elements.singleOrNull()?.unwrapped ?: return if (element !is KtElement) { throw KotlinExceptionWithAttachments("This handler must be invoked for Kotlin elements only: ${element::class.java}") .withAttachment("element", element) } val editor = dataContext?.let { CommonDataKeys.EDITOR.getData(it) } invokeChangeSignature(element, element, project, editor) } override fun getTargetNotFoundMessage() = KotlinBundle.message("error.wrong.caret.position.function.or.constructor.name") companion object { fun findTargetForRefactoring(element: PsiElement): PsiElement? { val elementParent = element.parent if ((elementParent is KtNamedFunction || elementParent is KtClass || elementParent is KtProperty) && (elementParent as KtNamedDeclaration).nameIdentifier === element ) return elementParent if (elementParent is KtParameter && elementParent.hasValOrVar() && elementParent.parentOfType<KtPrimaryConstructor>()?.valueParameterList === elementParent.parent ) return elementParent if (elementParent is KtProperty && elementParent.valOrVarKeyword === element) return elementParent if (elementParent is KtConstructor<*> && elementParent.getConstructorKeyword() === element) return elementParent element.parentOfType<KtParameterList>()?.let { parameterList -> return PsiTreeUtil.getParentOfType(parameterList, KtFunction::class.java, KtProperty::class.java, KtClass::class.java) } element.parentOfType<KtTypeParameterList>()?.let { typeParameterList -> return PsiTreeUtil.getParentOfType(typeParameterList, KtFunction::class.java, KtProperty::class.java, KtClass::class.java) } val call: KtCallElement? = PsiTreeUtil.getParentOfType( element, KtCallExpression::class.java, KtSuperTypeCallEntry::class.java, KtConstructorDelegationCall::class.java ) val calleeExpr = call?.let { val callee = it.calleeExpression (callee as? KtConstructorCalleeExpression)?.constructorReferenceExpression ?: callee } ?: element.parentOfType<KtSimpleNameExpression>() if (calleeExpr is KtSimpleNameExpression || calleeExpr is KtConstructorDelegationReferenceExpression) { val bindingContext = element.parentOfType<KtElement>()?.analyze(BodyResolveMode.FULL) ?: return null if (call?.getResolvedCall(bindingContext)?.resultingDescriptor?.isInvokeOperator == true) return call val descriptor = bindingContext[BindingContext.REFERENCE_TARGET, calleeExpr as KtReferenceExpression] if (descriptor is ClassDescriptor || descriptor is CallableDescriptor) return calleeExpr } return null } fun invokeChangeSignature(element: KtElement, context: PsiElement, project: Project, editor: Editor?) { val bindingContext = element.analyze(BodyResolveMode.FULL) val callableDescriptor = findDescriptor(element, project, editor, bindingContext) ?: return if (callableDescriptor is DeserializedDescriptor) { return CommonRefactoringUtil.showErrorHint( project, editor, KotlinBundle.message("error.hint.the.read.only.declaration.cannot.be.changed"), RefactoringBundle.message("changeSignature.refactoring.name"), "refactoring.changeSignature", ) } if (callableDescriptor is JavaCallableMemberDescriptor) { val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, callableDescriptor) if (declaration is PsiClass) { val message = RefactoringBundle.getCannotRefactorMessage( RefactoringBundle.message("error.wrong.caret.position.method.or.class.name") ) CommonRefactoringUtil.showErrorHint( project, editor, message, RefactoringBundle.message("changeSignature.refactoring.name"), "refactoring.changeSignature", ) return } assert(declaration is PsiMethod) { "PsiMethod expected: $callableDescriptor" } ChangeSignatureUtil.invokeChangeSignatureOn(declaration as PsiMethod, project) return } if (callableDescriptor.isDynamic()) { if (editor != null) { KotlinSurrounderUtils.showErrorHint( project, editor, KotlinBundle.message("message.change.signature.is.not.applicable.to.dynamically.invoked.functions"), RefactoringBundle.message("changeSignature.refactoring.name"), null ) } return } runChangeSignature(project, editor, callableDescriptor, KotlinChangeSignatureConfiguration.Empty, context, null) } private fun getDescriptor(bindingContext: BindingContext, element: PsiElement): DeclarationDescriptor? { val descriptor = when { element is KtParameter && element.hasValOrVar() -> bindingContext[BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, element] element is KtReferenceExpression -> bindingContext[BindingContext.REFERENCE_TARGET, element] element is KtCallExpression -> element.getResolvedCall(bindingContext)?.resultingDescriptor else -> bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, element] } return if (descriptor is ClassDescriptor) descriptor.unsubstitutedPrimaryConstructor else descriptor } fun findDescriptor(element: PsiElement, project: Project, editor: Editor?, bindingContext: BindingContext): CallableDescriptor? { if (!CommonRefactoringUtil.checkReadOnlyStatus(project, element)) return null var descriptor = getDescriptor(bindingContext, element) if (descriptor is MemberDescriptor && descriptor.isActual) { descriptor = descriptor.expectedDescriptor() ?: descriptor } return when (descriptor) { is PropertyDescriptor -> descriptor is FunctionDescriptor -> { if (descriptor.valueParameters.any { it.varargElementType != null }) { val message = KotlinBundle.message("error.cant.refactor.vararg.functions") CommonRefactoringUtil.showErrorHint( project, editor, message, RefactoringBundle.message("changeSignature.refactoring.name"), HelpID.CHANGE_SIGNATURE ) return null } if (descriptor.kind === SYNTHESIZED) { val message = KotlinBundle.message("cannot.refactor.synthesized.function", descriptor.name) CommonRefactoringUtil.showErrorHint( project, editor, message, RefactoringBundle.message("changeSignature.refactoring.name"), HelpID.CHANGE_SIGNATURE ) return null } descriptor } else -> { val message = RefactoringBundle.getCannotRefactorMessage( KotlinBundle.message("error.wrong.caret.position.function.or.constructor.name") ) CommonRefactoringUtil.showErrorHint( project, editor, message, RefactoringBundle.message("changeSignature.refactoring.name"), HelpID.CHANGE_SIGNATURE ) null } } } } }
apache-2.0
f39349abc38b11b9fa435f4fe869bdf2
49.008734
158
0.64277
6.227297
false
false
false
false
indianpoptart/RadioControl
OldCode/rootChecker-jun2021.kt
1
1989
//Check for root first if (!rootCheck()) { Log.d("RadioControl-Main","NotRooted") //toggle.isEnabled = false toggle.isChecked = false //Uncheck toggle statusText.setText(R.string.noRoot) //Sets the status text to no root statusText.setTextColor(ContextCompat.getColor(applicationContext, R.color.status_no_root)) //Sets text to deactivated (RED) color //Drawer icon carrierIcon = IconicsDrawable(this, GoogleMaterial.Icon.gmd_error_outline).apply { colorInt = Color.RED } carrierName = "Not Rooted" } else{ Log.d("RadioControl-Main","RootedIGuess") toggle.isChecked = true //Preference handling editor.putInt(getString(R.string.preference_app_active), 1) //UI Handling statusText.setText(R.string.showEnabled) //Sets the status text to enabled statusText.setTextColor(ContextCompat.getColor(applicationContext, R.color.status_activated)) carrierIcon = IconicsDrawable(this, GoogleMaterial.Icon.gmd_check_circle).apply { colorInt = Color.GREEN } carrierName = "Rooted" //Service initialization applicationContext.startService(bgj) //Alarm scheduling alarmUtil.scheduleAlarm(applicationContext) //Checks if workmode is enabled and starts the Persistence Service, otherwise it registers the broadcast receivers if (getPrefs.getBoolean(getString(R.string.preference_work_mode), true)) { val i = Intent(applicationContext, PersistenceService::class.java) if (Build.VERSION.SDK_INT >= 26) { applicationContext.startForegroundService(i) } else { applicationContext.startService(i) } Log.d("RadioControl-Main", "persist Service launched") } else { registerForBroadcasts(applicationContext) } //Checks if background optimization is enabled and schedules a job if (getPrefs.getBoolean(getString(R.string.key_preference_settings_battery_opimization), false)) { scheduleJob() } }
gpl-3.0
734678f7285425f785792b426792faff
37.269231
134
0.708899
4.400442
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/internal/ui/AnimationPanelTestAction.kt
3
20032
package com.intellij.internal.ui import com.intellij.icons.AllIcons import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CustomShortcutSet import com.intellij.openapi.application.ex.ClipboardUtil import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.Disposer import com.intellij.ui.* import com.intellij.ui.components.ActionLink import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.JBTextArea import com.intellij.ui.components.fields.ExpandableTextField import com.intellij.ui.components.fields.ExtendableTextComponent import com.intellij.ui.components.panels.HorizontalLayout import com.intellij.ui.components.panels.OpaquePanel import com.intellij.ui.components.panels.VerticalLayout import com.intellij.ui.components.panels.Wrapper import com.intellij.ui.layout.* import com.intellij.util.animation.* import com.intellij.util.animation.components.BezierPainter import com.intellij.util.ui.EmptyIcon import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.awt.event.WindowAdapter import java.awt.event.WindowEvent import java.awt.geom.Point2D import java.lang.Math.PI import java.text.NumberFormat import java.util.function.Consumer import javax.swing.Action import javax.swing.JButton import javax.swing.JComponent import javax.swing.SwingConstants import javax.swing.border.CompoundBorder import kotlin.math.absoluteValue import kotlin.math.pow import kotlin.math.roundToInt @Suppress("HardCodedStringLiteral") class AnimationPanelTestAction : DumbAwareAction("Show Animation Panel") { private class DemoPanel(val disposable: Disposable, val bezier: () -> Easing) : BorderLayoutPanel() { val textArea: JBTextArea init { preferredSize = Dimension(600, 300) border = JBUI.Borders.emptyLeft(12) textArea = JBTextArea() createScrollPaneWithAnimatedActions(textArea) } fun load() { loadStage1() } private fun loadStage1() { val baseColor = UIUtil.getTextFieldForeground() val showDemoBtn = JButton("Click to start a demo", AllIcons.Process.Step_1).also { it.border = JBUI.Borders.customLine(baseColor, 1) it.isContentAreaFilled = false it.isOpaque = true } val showTestPageLnk = ActionLink("or load the testing page") addToCenter(OpaquePanel(VerticalLayout(15, SwingConstants.CENTER)).also { it.add(showDemoBtn, VerticalLayout.CENTER) it.add(showTestPageLnk, VerticalLayout.CENTER) }) val icons = arrayOf(AllIcons.Process.Step_1, AllIcons.Process.Step_2, AllIcons.Process.Step_3, AllIcons.Process.Step_4, AllIcons.Process.Step_5, AllIcons.Process.Step_6, AllIcons.Process.Step_7, AllIcons.Process.Step_8) val iconAnimator = JBAnimator(disposable).apply { period = 60 isCyclic = true type = JBAnimator.Type.EACH_FRAME ignorePowerSaveMode() } iconAnimator.animate(animation(icons, showDemoBtn::setIcon).apply { duration = iconAnimator.period * icons.size }) val fadeOutElements = listOf( transparent(baseColor) { showDemoBtn.foreground = it showDemoBtn.border = JBUI.Borders.customLine(it, 1) }, animation { val array = showDemoBtn.text.toCharArray() array.shuffle() showDemoBtn.text = String(array) }, transparent(showTestPageLnk.foreground, showTestPageLnk::setForeground).apply { runWhenScheduled { showDemoBtn.icon = EmptyIcon.ICON_16 showDemoBtn.isOpaque = false showDemoBtn.repaint() Disposer.dispose(iconAnimator) } runWhenExpired { removeAll() revalidate() repaint() } } ) showDemoBtn.addActionListener { animate { fadeOutElements + animation().runWhenExpired { loadStage2() } } } showTestPageLnk.addActionListener { animate { fadeOutElements + animation().runWhenExpired { loadTestPage() } } } showDemoBtn.addMouseListener(object : MouseAdapter() { private val consumers = arrayOf( consumer(DoubleColorFunction(showDemoBtn.background, showDemoBtn.foreground), showDemoBtn::setBackground), consumer(DoubleColorFunction(showDemoBtn.foreground, showDemoBtn.background), showDemoBtn::setForeground), ) val animator = JBAnimator() val statefulEasing = CubicBezierEasing(0.215, 0.61, 0.355, 1.0).stateful() override fun mouseEntered(e: MouseEvent) { animator.animate(Animation(*consumers).apply { duration = 500 easing = statefulEasing.coerceIn(statefulEasing.value, 1.0) duration = (duration * (1.0 - statefulEasing.value)).roundToInt() }) } override fun mouseExited(e: MouseEvent) { animator.animate(Animation(*consumers).apply { delay = 50 duration = 450 easing = statefulEasing.coerceIn(0.0, statefulEasing.value).reverse() duration = (duration * statefulEasing.value).roundToInt() }) } }) } private fun loadStage2() { val clicks = 2 val buttonDemo = SpringButtonPanel("Here!", Rectangle(width / 2 - 50, 10, 100, 40), clicks) { [email protected](it) loadStage3() } addToCenter(buttonDemo) val scroller = ComponentUtil.getScrollPane(textArea) ?: error("text area has no scroll pane") if (scroller.parent == null) { textArea.text = """ Hello! Click the button ${clicks + 1} times. """.trimIndent() scroller.preferredSize = Dimension([email protected], 0) addToTop(scroller) } JBAnimator().animate(let { val to = Dimension([email protected], 100) animation(scroller.preferredSize, to, scroller::setPreferredSize) .setEasing(bezier()) .runWhenUpdated { revalidate() repaint() } }) } private fun loadStage3() { val scroller = ComponentUtil.getScrollPane(textArea) ?: error("text area has no scroll pane") if (scroller.parent == null) { textArea.text = "Good start!" scroller.preferredSize = Dimension([email protected], 0) addToTop(scroller) } val oopsText = "Oops... Everything is gone" val sorryText = """ $oopsText To check page scroll options insert a text and press UP or DOWN key. These values are funny: 0.34, 1.56, 0.64, 1 """.trimIndent() animate { type = JBAnimator.Type.EACH_FRAME makeSequent( animation(scroller.preferredSize, size, scroller::setPreferredSize).apply { duration = 500 delay = 500 easing = bezier() runWhenUpdated { revalidate() repaint() } }, animation(textArea.text, oopsText, textArea::setText).apply { duration = ((textArea.text.length + oopsText.length) * 20).coerceAtMost(5_000) delay = 200 }, animation(oopsText, sorryText, textArea::setText).apply { duration = ((oopsText.length + sorryText.length) * 20).coerceAtMost(7_500) delay = 1000 }, animation(size, Dimension(width, height - 30), scroller::setPreferredSize).apply { delay = 2_500 easing = bezier() runWhenUpdated { revalidate() repaint() } runWhenExpired { val link = ActionLink("Got it! Now, open the test panel") { loadTestPage() } val foreground = link.foreground val transparent = ColorUtil.withAlpha(link.foreground, 0.0) link.foreground = transparent addToBottom(Wrapper(FlowLayout(), link)) animate(transparent(foreground, link::setForeground).apply { easing = easing.reverse() }) } } ) } } private fun loadTestPage() = hideAllComponentsAndRun { val linear = FillPanel("Linear") val custom = FillPanel("Custom") val content = Wrapper(HorizontalLayout(40)).apply { border = JBUI.Borders.empty(0, 40) add(custom, HorizontalLayout.CENTER) add(linear, HorizontalLayout.CENTER) } addToCenter(content) val animations = listOf( animation(custom::value::set), animation(linear::value::set), animation().runWhenUpdated { content.repaint() } ) val fillers = JBAnimator(disposable) addToLeft(AnimationSettings { options -> fillers.period = options.period fillers.isCyclic = options.cyclic fillers.type = options.type animations[0].easing = bezier() animations[1].easing = Easing.LINEAR animations.forEach { animation -> animation.duration = options.duration animation.delay = options.delay animation.easing = animation.easing.coerceIn( options.coerceMin / 100.0, options.coerceMax / 100.0 ) if (options.inverse) { animation.easing = animation.easing.invert() } if (options.reverse) { animation.easing = animation.easing.reverse() } if (options.mirror) { animation.easing = animation.easing.mirror() } } fillers.animate(animations) }) revalidate() } private fun hideAllComponentsAndRun(afterFinish: () -> Unit) { val remover = mutableListOf<Animation>() val scroller = ComponentUtil.getScrollPane(textArea) components.forEach { comp -> if (scroller === comp) { remover += animation(comp.preferredSize, Dimension(comp.width, 0), comp::setPreferredSize) .setEasing(bezier()) .runWhenUpdated { revalidate() repaint() } remover += animation(textArea.text, "", textArea::setText).setEasing { x -> 1 - (1 - x).pow(4.0) } remover += transparent(textArea.foreground, textArea::setForeground) } else if (comp is Wrapper && comp.targetComponent is ActionLink) { val link = comp.targetComponent as ActionLink remover += transparent(link.foreground, link::setForeground) } } remover += animation().runWhenExpired { removeAll() afterFinish() } remover.forEach { it.duration = 800 } animate { remover } } private fun createScrollPaneWithAnimatedActions(textArea: JBTextArea): JBScrollPane { val pane = JBScrollPane(textArea) val commonAnimator = JBAnimator(disposable) create("Scroll Down") { val from: Int = pane.verticalScrollBar.value val to: Int = from + pane.visibleRect.height commonAnimator.animate( animation(from, to, pane.verticalScrollBar::setValue) .setDuration(350) .setEasing(bezier()) ) }.registerCustomShortcutSet(CustomShortcutSet.fromString("DOWN"), pane) create("Scroll Up") { val from: Int = pane.verticalScrollBar.value val to: Int = from - pane.visibleRect.height commonAnimator.animate( animation(from, to, pane.verticalScrollBar::setValue) .setDuration(350) .setEasing(bezier()) ) }.registerCustomShortcutSet(CustomShortcutSet.fromString("UP"), pane) return pane } } class Options { var period: Int = 10 var duration: Int = 1000 var delay: Int = 0 var cyclic: Boolean = false var reverse: Boolean = false var inverse: Boolean = false var mirror: Boolean = false var coerceMin: Int = 0 var coerceMax: Int = 100 var type: JBAnimator.Type = JBAnimator.Type.IN_TIME } private class AnimationSettings(val onStart: (Options) -> Unit) : BorderLayoutPanel() { private val options = Options() init { val panel = panel { row("Duration:") { spinner(options::duration, 0, 5000, 50) } row("Period:") { spinner(options::period, 5, 1000, 5) } row("Delay:") { spinner(options::delay, 0, 5000, 100) } row { checkBox("Cyclic", options::cyclic) } row { checkBox("Reverse", options::reverse) } row { checkBox("Inverse", options::inverse) } row { checkBox("Mirror", options::mirror) } row("Coerce (%)") { spinner(options::coerceMin, 0, 100, 5) spinner(options::coerceMax, 0, 100, 5) } row { comboBox(EnumComboBoxModel(JBAnimator.Type::class.java), options::type, listCellRenderer { value, _, _ -> text = value.toString().split("_").joinToString(" ") { it.toLowerCase().capitalize() } }) } } addToCenter(panel) addToBottom(JButton("Start Animation").apply { addActionListener { panel.apply() onStart(options) } }) } } private class FillPanel(val description: String) : JComponent() { var value: Double = 1.0 init { background = JBColor(0xC2D6F6, 0x455563) preferredSize = Dimension(40, 0) border = JBUI.Borders.empty(40, 5, 40, 0) } override fun paintComponent(g: Graphics) { val g2d = g as Graphics2D val insets = insets val bounds = g2d.clipBounds.apply { height -= insets.top + insets.bottom y += insets.top } val fillHeight = (bounds.height * value).roundToInt() val fillY = bounds.y + bounds.height - fillHeight.coerceAtLeast(0) g2d.color = background g2d.fillRect(bounds.x, fillY, bounds.width, fillHeight.absoluteValue) g2d.color = UIUtil.getPanelBackground() g2d.stroke = BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0f, floatArrayOf(3f), 0f) g2d.drawLine(bounds.x, bounds.y, bounds.x + bounds.width, bounds.y) g2d.drawLine(bounds.x, bounds.y + bounds.height, bounds.x + bounds.width, bounds.y + bounds.height) val textX = bounds.width val textY = bounds.y + bounds.height g2d.color = UIUtil.getPanelBackground() g2d.font = g2d.font.deriveFont(30f).deriveFont(Font.BOLD) g2d.rotate(-PI / 2, textX.toDouble(), textY.toDouble()) g2d.drawString(description, textX, textY) } } private class BezierEasingPanel : BorderLayoutPanel() { private val painter = BezierPainter(0.215, 0.61, 0.355, 1.0).also(this::addToCenter).apply { border = JBUI.Borders.empty(25) } private val display = ExpandableTextField().also(this::addToTop).apply { isEditable = false text = getControlPoints(painter).joinToString(transform = format::format) border = JBUI.Borders.empty(1) } init { border = JBUI.Borders.customLine(UIUtil.getBoundsColor(), 1) painter.addPropertyChangeListener { e -> if (e.propertyName.endsWith("ControlPoint")) { display.text = getControlPoints(painter).joinToString(transform = format::format) } } display.setExtensions( ExtendableTextComponent.Extension.create(AllIcons.General.Reset, "Reset") { setControlPoints(painter, listOf(0.215, 0.61, 0.355, 1.0)) }, ExtendableTextComponent.Extension.create(AllIcons.Actions.MenuPaste, "Paste from Clipboard") { try { ClipboardUtil.getTextInClipboard()?.let { setControlPoints(painter, parseControlPoints(it)) } } catch (ignore: NumberFormatException) { animate { listOf(animation(UIUtil.getErrorForeground(), UIUtil.getTextFieldForeground(), display::setForeground).apply { duration = 800 easing = Easing { x -> x * x * x } }) } } }) } fun getEasing() = painter.getEasing() private fun getControlPoints(bezierPainter: BezierPainter): List<Double> = listOf( bezierPainter.firstControlPoint.x, bezierPainter.firstControlPoint.y, bezierPainter.secondControlPoint.x, bezierPainter.secondControlPoint.y, ) private fun setControlPoints(bezierPainter: BezierPainter, values: List<Double>) { bezierPainter.firstControlPoint = Point2D.Double(values[0], values[1]) bezierPainter.secondControlPoint = Point2D.Double(values[2], values[3]) } @Throws(java.lang.NumberFormatException::class) private fun parseControlPoints(value: String): List<Double> = value.split(",").also { if (it.size != 4) throw NumberFormatException("Cannot parse $value;") }.map { it.trim().toDouble() } companion object { private val format = NumberFormat.getNumberInstance() } } private class SpringButtonPanel(text: String, start: Rectangle, val until: Int, val onFinish: Consumer<SpringButtonPanel>) : Wrapper() { val button = JButton(text) val animator = JBAnimator().apply { period = 5 type = JBAnimator.Type.IN_TIME } val easing = Easing { x -> 1 + 2.7 * (x - 1).pow(3.0) + 1.7 * (x - 1).pow(2.0) } var turns = 0 init { button.bounds = start button.addActionListener { if (turns >= until) { flyAway() } else { jump() turns++ } } layout = null add(button) } private fun flyAway() { animator.animate( animation(button.bounds, Rectangle(width / 2, 0, 0, 0), button::setBounds).apply { duration = 350 easing = [email protected] runWhenExpired { onFinish.accept(this@SpringButtonPanel) } } ) } private fun jump() { animator.animate( animation(button.bounds, generateBounds(), button::setBounds).apply { duration = 350 easing = [email protected] } ) } private fun generateBounds(): Rectangle { val size = bounds val x = (Math.random() * size.width / 2).toInt() val y = (Math.random() * size.height / 2).toInt() val width = (Math.random() * (size.width - x)).coerceAtLeast(100.0).toInt() val height = (Math.random() * (size.height - y)).coerceAtLeast(24.0).toInt() return Rectangle(x, y, width, height) } } override fun actionPerformed(e: AnActionEvent) { object : DialogWrapper(e.project) { val bezier = BezierEasingPanel() val demo = DemoPanel(disposable, bezier::getEasing) init { title = "Animation Panel Test Action" bezier.border = CompoundBorder(JBUI.Borders.emptyRight(12), bezier.border) setResizable(true) init() window.addWindowListener(object : WindowAdapter() { override fun windowOpened(e: WindowEvent?) { demo.load() window.removeWindowListener(this) } }) } override fun createCenterPanel() = OnePixelSplitter(false, .3f).also { ops -> ops.firstComponent = bezier ops.secondComponent = demo } override fun createActions() = emptyArray<Action>() }.show() } }
apache-2.0
c0a49143851755c275dbac670bf20eac
31.468395
138
0.614467
4.562059
false
false
false
false
genonbeta/TrebleShot
app/src/main/java/org/monora/uprotocol/client/android/database/model/UClient.kt
1
4152
/* * Copyright (C) 2021 Veli Tasalı * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.monora.uprotocol.client.android.database.model import android.os.Parcelable import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.parcelize.Parcelize import org.monora.uprotocol.core.protocol.Client import org.monora.uprotocol.core.protocol.ClientType import java.io.FileInputStream import java.security.cert.X509Certificate @Parcelize @Entity(tableName = "client") data class UClient( @PrimaryKey var uid: String, var nickname: String, var manufacturer: String, var product: String, var type: ClientType, var versionName: String, var versionCode: Int, var protocolVersion: Int, var protocolVersionMin: Int, var revisionOfPicture: Long, var lastUsageTime: Long = System.currentTimeMillis(), var blocked: Boolean = false, var local: Boolean = false, var trusted: Boolean = false, var certificate: X509Certificate? = null, ) : Client, Parcelable { override fun getClientCertificate(): X509Certificate? = certificate override fun getClientLastUsageTime(): Long = lastUsageTime override fun getClientManufacturer(): String = manufacturer override fun getClientNickname(): String = nickname override fun getClientProduct(): String = product override fun getClientProtocolVersion(): Int = protocolVersion override fun getClientProtocolVersionMin(): Int = protocolVersionMin override fun getClientType(): ClientType = type override fun getClientUid(): String = uid override fun getClientVersionCode(): Int = versionCode override fun getClientVersionName(): String = versionName override fun getClientRevisionOfPicture(): Long = revisionOfPicture override fun isClientBlocked(): Boolean = blocked override fun isClientLocal(): Boolean = local override fun isClientTrusted(): Boolean = trusted override fun setClientBlocked(blocked: Boolean) { this.blocked = blocked } override fun setClientCertificate(certificate: X509Certificate?) { this.certificate = certificate } override fun setClientLastUsageTime(lastUsageTime: Long) { this.lastUsageTime = lastUsageTime } override fun setClientLocal(local: Boolean) { this.local = local } override fun setClientManufacturer(manufacturer: String) { this.manufacturer = manufacturer } override fun setClientNickname(nickname: String) { this.nickname = nickname } override fun setClientProduct(product: String) { this.product = product } override fun setClientProtocolVersion(protocolVersion: Int) { this.protocolVersion = protocolVersion } override fun setClientProtocolVersionMin(protocolVersionMin: Int) { this.protocolVersionMin = protocolVersionMin } override fun setClientRevisionOfPicture(revision: Long) { this.revisionOfPicture = revision } override fun setClientTrusted(trusted: Boolean) { this.trusted = trusted } override fun setClientType(type: ClientType) { this.type = type } override fun setClientUid(uid: String) { this.uid = uid } override fun setClientVersionCode(versionCode: Int) { this.versionCode = versionCode } override fun setClientVersionName(versionName: String) { this.versionName = versionName } }
gpl-2.0
2762e7bbc546ac91751e920bd1f976f5
28.863309
82
0.722236
4.690395
false
false
false
false
notsyncing/cowherd
cowherd-flex/src/main/kotlin/io/github/notsyncing/cowherd/flex/CowherdScriptManager.kt
1
8815
package io.github.notsyncing.cowherd.flex import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner import io.github.notsyncing.cowherd.models.ActionMethodInfo import io.github.notsyncing.cowherd.models.RouteInfo import io.github.notsyncing.cowherd.routing.RouteManager import io.vertx.core.http.HttpMethod import java.io.IOException import java.io.InputStream import java.io.InputStreamReader import java.io.Reader import java.nio.file.* import java.util.concurrent.Executors import java.util.logging.Logger import kotlin.concurrent.thread import kotlin.reflect.jvm.javaMethod import kotlin.reflect.jvm.reflect object CowherdScriptManager { private const val SCRIPT_EXT = ".cf.kts" const val TAG_SCRIPT_PATH = "cowherd.flex.route_tag.script_path" const val TAG_FUNCTION = "cowherd.flex.route_tag.function" const val TAG_FUNCTION_CLASS = "cowherd.flex.route_tag.function_class" const val TAG_REAL_FUNCTION = "cowherd.flex.route_tag.real_function" const val TAG_HTTP_METHOD = "cowherd.flex.route_tag.http_method" private lateinit var engine: CowherdScriptEngine private val searchPaths = mutableListOf("$") var ignoreClasspathScripts = false private lateinit var watcher: WatchService private lateinit var watchingThread: Thread private val watchingPaths = mutableMapOf<WatchKey, Path>() private var watching = true private var currentScriptPath: String = "" private var isInit = true private val reloadThread = Executors.newSingleThreadExecutor { Thread(it).apply { this.name = "cowherd.flex.reloader" this.isDaemon = true } } private val logger = Logger.getLogger(javaClass.simpleName) fun addSearchPath(p: Path) { addSearchPath(p.toAbsolutePath().normalize().toString()) } fun addSearchPath(p: String) { if (searchPaths.contains(p)) { logger.warning("Script search paths already contain $p, will skip adding it.") return } searchPaths.add(p) if (!isInit) { loadAndWatchScriptsFromDirectory(p) } } fun init() { isInit = true engine = KotlinScriptEngine() watcher = FileSystems.getDefault().newWatchService() watching = true watchingThread = thread(name = "cowherd.flex.watcher", isDaemon = true, block = this::watcherThread) loadAllScripts() isInit = false } private fun evalScript(reader: Reader, path: String) { reader.use { currentScriptPath = path engine.eval(it) currentScriptPath = "" } } private fun evalScript(inputStream: InputStream, path: String) { evalScript(InputStreamReader(inputStream), path) } private fun evalScript(file: Path) { val path = file.toAbsolutePath().normalize().toString() currentScriptPath = path engine.loadScript(file) currentScriptPath = "" } private fun loadAndWatchScriptsFromDirectory(path: String) { val p = Paths.get(path) var counter = 0 Files.list(p) .filter { it.fileName.toString().endsWith(SCRIPT_EXT) } .forEach { f -> logger.info("Loading script $f") evalScript(f) counter++ } val watchKey = p.register(watcher, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY) watchingPaths[watchKey] = p logger.info("Loaded $counter scripts from $path and added them to the watching list.") } private fun loadAllScripts() { watchingPaths.keys.forEach { it.cancel() } watchingPaths.clear() for (path in searchPaths) { if (path == "$") { if (ignoreClasspathScripts) { continue } val regex = "^(.*?)${SCRIPT_EXT.replace(".", "\\.")}$" FastClasspathScanner() .matchFilenamePattern(regex) { relativePath: String, inputStream, _ -> InputStreamReader(inputStream).use { logger.info("Loading script $relativePath from classpath") evalScript(it, relativePath) } } .scan() } else { loadAndWatchScriptsFromDirectory(path) } } } fun registerAction(method: HttpMethod, route: String, code: Function<*>) { if (RouteManager.containsRoute(RouteInfo(route))) { logger.warning("Route map already contains an action with route $route, the previous one " + "will be overwritten!") } val routeInfo = RouteInfo(route) routeInfo.isFastRoute = true routeInfo.setTag(TAG_SCRIPT_PATH, currentScriptPath) routeInfo.setTag(TAG_FUNCTION, code.reflect()) routeInfo.setTag(TAG_FUNCTION_CLASS, code) routeInfo.setTag(TAG_REAL_FUNCTION, code.javaClass.methods.firstOrNull { it.name == "invoke" } ?.apply { this.isAccessible = true }) routeInfo.setTag(TAG_HTTP_METHOD, method) RouteManager.addRoute(routeInfo, ActionMethodInfo(ScriptActionInvoker::invokeAction.javaMethod)) } fun destroy() { watching = false watcher.close() watchingThread.interrupt() RouteManager.removeRouteIf { routeInfo, _ -> routeInfo.hasTag(TAG_SCRIPT_PATH) } } fun reset() { searchPaths.clear() searchPaths.add("$") watchingPaths.keys.forEach { it.cancel() } watchingPaths.clear() ignoreClasspathScripts = false } private fun updateActions(scriptFile: Path, type: WatchEvent.Kind<*>) { val iter = RouteManager.getRoutes().entries.iterator() val scriptFilePathStr = scriptFile.toString() if ((type == StandardWatchEventKinds.ENTRY_MODIFY) || (type == StandardWatchEventKinds.ENTRY_DELETE)) { while (iter.hasNext()) { val (info, _) = iter.next() val path = info.getTag(TAG_SCRIPT_PATH) as String? if (path == null) { continue } if (Files.isDirectory(scriptFile)) { if (Paths.get(path).startsWith(scriptFile)) { iter.remove() } } else { if (path == scriptFilePathStr) { iter.remove() } } } } if (type != StandardWatchEventKinds.ENTRY_DELETE) { evalScript(scriptFile) } logger.info("Script file $scriptFile updated, type $type.") } private fun watcherThread() { while (watching) { val key: WatchKey try { key = watcher.take() } catch (x: InterruptedException) { continue } catch (x: ClosedWatchServiceException) { if (!watching) { continue } throw x } for (event in key.pollEvents()) { val kind = event.kind() if (kind == StandardWatchEventKinds.OVERFLOW) { logger.warning("Script watcher overflow, at ${watchingPaths[key]}") continue } val ev = event as WatchEvent<Path> val filename = ev.context() if (!filename.toString().endsWith(SCRIPT_EXT)) { continue } val dir = watchingPaths[key] if (dir == null) { logger.warning("We are notified by a path not in the watching list, filename: $filename") continue } try { val fullPath = dir.resolve(filename) reloadThread.submit { try { updateActions(fullPath, kind) } catch (e: Exception) { logger.warning("An exception occured when reloading script $fullPath: ${e.message}") e.printStackTrace() } } } catch (x: IOException) { x.printStackTrace() continue } } val valid = key.reset() if (!valid) { continue } } } }
gpl-3.0
29d379e2435ba70ebae6b96783b12ca5
30.151943
118
0.555984
4.977414
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/src/internal/ConcurrentLinkedList.kt
1
9055
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.internal import kotlinx.atomicfu.* import kotlinx.coroutines.* import kotlin.jvm.* import kotlin.native.concurrent.SharedImmutable /** * Returns the first segment `s` with `s.id >= id` or `CLOSED` * if all the segments in this linked list have lower `id`, and the list is closed for further segment additions. */ private inline fun <S : Segment<S>> S.findSegmentInternal( id: Long, createNewSegment: (id: Long, prev: S?) -> S ): SegmentOrClosed<S> { /* Go through `next` references and add new segments if needed, similarly to the `push` in the Michael-Scott queue algorithm. The only difference is that "CAS failure" means that the required segment has already been added, so the algorithm just uses it. This way, only one segment with each id can be added. */ var cur: S = this while (cur.id < id || cur.removed) { val next = cur.nextOrIfClosed { return SegmentOrClosed(CLOSED) } if (next != null) { // there is a next node -- move there cur = next continue } val newTail = createNewSegment(cur.id + 1, cur) if (cur.trySetNext(newTail)) { // successfully added new node -- move there if (cur.removed) cur.remove() cur = newTail } } return SegmentOrClosed(cur) } /** * Returns `false` if the segment `to` is logically removed, `true` on a successful update. */ @Suppress("NOTHING_TO_INLINE") // Must be inline because it is an AtomicRef extension private inline fun <S : Segment<S>> AtomicRef<S>.moveForward(to: S): Boolean = loop { cur -> if (cur.id >= to.id) return true if (!to.tryIncPointers()) return false if (compareAndSet(cur, to)) { // the segment is moved if (cur.decPointers()) cur.remove() return true } if (to.decPointers()) to.remove() // undo tryIncPointers } /** * Tries to find a segment with the specified [id] following by next references from the * [startFrom] segment and creating new ones if needed. The typical use-case is reading this `AtomicRef` values, * doing some synchronization, and invoking this function to find the required segment and update the pointer. * At the same time, [Segment.cleanPrev] should also be invoked if the previous segments are no longer needed * (e.g., queues should use it in dequeue operations). * * Since segments can be removed from the list, or it can be closed for further segment additions. * Returns the segment `s` with `s.id >= id` or `CLOSED` if all the segments in this linked list have lower `id`, * and the list is closed. */ internal inline fun <S : Segment<S>> AtomicRef<S>.findSegmentAndMoveForward( id: Long, startFrom: S, createNewSegment: (id: Long, prev: S?) -> S ): SegmentOrClosed<S> { while (true) { val s = startFrom.findSegmentInternal(id, createNewSegment) if (s.isClosed || moveForward(s.segment)) return s } } /** * Closes this linked list of nodes by forbidding adding new ones, * returns the last node in the list. */ internal fun <N : ConcurrentLinkedListNode<N>> N.close(): N { var cur: N = this while (true) { val next = cur.nextOrIfClosed { return cur } if (next === null) { if (cur.markAsClosed()) return cur } else { cur = next } } } internal abstract class ConcurrentLinkedListNode<N : ConcurrentLinkedListNode<N>>(prev: N?) { // Pointer to the next node, updates similarly to the Michael-Scott queue algorithm. private val _next = atomic<Any?>(null) // Pointer to the previous node, updates in [remove] function. private val _prev = atomic(prev) private val nextOrClosed get() = _next.value /** * Returns the next segment or `null` of the one does not exist, * and invokes [onClosedAction] if this segment is marked as closed. */ @Suppress("UNCHECKED_CAST") inline fun nextOrIfClosed(onClosedAction: () -> Nothing): N? = nextOrClosed.let { if (it === CLOSED) { onClosedAction() } else { it as N? } } val next: N? get() = nextOrIfClosed { return null } /** * Tries to set the next segment if it is not specified and this segment is not marked as closed. */ fun trySetNext(value: N): Boolean = _next.compareAndSet(null, value) /** * Checks whether this node is the physical tail of the current linked list. */ val isTail: Boolean get() = next == null val prev: N? get() = _prev.value /** * Cleans the pointer to the previous node. */ fun cleanPrev() { _prev.lazySet(null) } /** * Tries to mark the linked list as closed by forbidding adding new nodes after this one. */ fun markAsClosed() = _next.compareAndSet(null, CLOSED) /** * This property indicates whether the current node is logically removed. * The expected use-case is removing the node logically (so that [removed] becomes true), * and invoking [remove] after that. Note that this implementation relies on the contract * that the physical tail cannot be logically removed. Please, do not break this contract; * otherwise, memory leaks and unexpected behavior can occur. */ abstract val removed: Boolean /** * Removes this node physically from this linked list. The node should be * logically removed (so [removed] returns `true`) at the point of invocation. */ fun remove() { assert { removed } // The node should be logically removed at first. assert { !isTail } // The physical tail cannot be removed. while (true) { // Read `next` and `prev` pointers ignoring logically removed nodes. val prev = leftmostAliveNode val next = rightmostAliveNode // Link `next` and `prev`. next._prev.value = prev if (prev !== null) prev._next.value = next // Checks that prev and next are still alive. if (next.removed) continue if (prev !== null && prev.removed) continue // This node is removed. return } } private val leftmostAliveNode: N? get() { var cur = prev while (cur !== null && cur.removed) cur = cur._prev.value return cur } private val rightmostAliveNode: N get() { assert { !isTail } // Should not be invoked on the tail node var cur = next!! while (cur.removed) cur = cur.next!! return cur } } /** * Each segment in the list has a unique id and is created by the provided to [findSegmentAndMoveForward] method. * Essentially, this is a node in the Michael-Scott queue algorithm, * but with maintaining [prev] pointer for efficient [remove] implementation. */ internal abstract class Segment<S : Segment<S>>(val id: Long, prev: S?, pointers: Int): ConcurrentLinkedListNode<S>(prev) { /** * This property should return the maximal number of slots in this segment, * it is used to define whether the segment is logically removed. */ abstract val maxSlots: Int /** * Numbers of cleaned slots (the lowest bits) and AtomicRef pointers to this segment (the highest bits) */ private val cleanedAndPointers = atomic(pointers shl POINTERS_SHIFT) /** * The segment is considered as removed if all the slots are cleaned. * There are no pointers to this segment from outside, and * it is not a physical tail in the linked list of segments. */ override val removed get() = cleanedAndPointers.value == maxSlots && !isTail // increments the number of pointers if this segment is not logically removed. internal fun tryIncPointers() = cleanedAndPointers.addConditionally(1 shl POINTERS_SHIFT) { it != maxSlots || isTail } // returns `true` if this segment is logically removed after the decrement. internal fun decPointers() = cleanedAndPointers.addAndGet(-(1 shl POINTERS_SHIFT)) == maxSlots && !isTail /** * Invoked on each slot clean-up; should not be invoked twice for the same slot. */ fun onSlotCleaned() { if (cleanedAndPointers.incrementAndGet() == maxSlots && !isTail) remove() } } private inline fun AtomicInt.addConditionally(delta: Int, condition: (cur: Int) -> Boolean): Boolean { while (true) { val cur = this.value if (!condition(cur)) return false if (this.compareAndSet(cur, cur + delta)) return true } } @JvmInline internal value class SegmentOrClosed<S : Segment<S>>(private val value: Any?) { val isClosed: Boolean get() = value === CLOSED @Suppress("UNCHECKED_CAST") val segment: S get() = if (value === CLOSED) error("Does not contain segment") else value as S } private const val POINTERS_SHIFT = 16 @SharedImmutable private val CLOSED = Symbol("CLOSED")
apache-2.0
b0419ddeb53036cb894df41df7e81e87
36.572614
123
0.65069
4.127165
false
false
false
false
flamurey/koltin-func
src/main/kotlin/com/flamurey/kfunc/core/Either.kt
1
2264
package com.flamurey.kfunc.core sealed class Either<out A, out B> : Monad<B> { class Left<out A>(val value: A) : Either<A, Nothing>() { override fun get(): Nothing { throw UnsupportedOperationException() } override fun isPresent(): Boolean = false override fun <B> map(f: (Nothing) -> B): Either<A, B> = this override fun <B> flatMap(f: (Nothing) -> Monad<B>): Either<A, B> = this } class Right<out B>(val value: B) : Either<Nothing, B>() { override fun get(): B = value override fun isPresent(): Boolean = true override fun <C> map(f: (B) -> C): Either<Nothing, C> = Right(f(value)) override fun <C> flatMap(f: (B) -> Monad<C>): Either<Monad<C>, C> { val m = f(value) return when (m) { is Right<C> -> m else -> if (m.isPresent()) Right(m.get()) else Left(m) } } } fun apply(success: (B) -> Unit, fail: (A) -> Unit) : Unit = when (this) { is Either.Left<A> -> fail(value) is Either.Right<B> -> success(value) } companion object { fun <A, B> fail(error: A): Either<A, B> = Left(error) fun <A, B> success(result: B): Either<A, B> = Right(result) } } fun <A, B, C> Either<A, B>.flatMap(f: (B) -> Either<A, C>): Either<A, C> = when (this) { is Either.Left<A> -> this is Either.Right<B> -> f(value) } fun <E, A, B, C> Either<E, A>.map2(other: Either<E, B>, f: (A, B) -> C): Either<E, C> = when (this) { is Either.Left<E> -> this is Either.Right<A> -> when (other) { is Either.Left<E> -> other is Either.Right<B> -> Either.Right(f(this.value, other.value)) } } fun <A, B> Either<A, B>.getOrElse(other: B): B = when (this) { is Either.Right<B> -> value else -> other } fun <A, B> Either<A, B>.orElse(other: B): Either<A, B> = when (this) { is Either.Right<B> -> this else -> Either.Right(other) } fun <A> tryDo(f: () -> A): Either<Exception, A> = try { Either.Right(f()) } catch (e: Exception) { Either.Left(e) } fun <A, B> Either<Monad<A>, Monad<B>>.codistribute(): Monad<Either<A, B>> = when (this) { is Either.Left<Monad<A>> -> value.map { Either.Left(it) } is Either.Right<Monad<B>> -> value.map { Either.Right(it) } }
mit
355b9ddf7918e5443309aae2d99bcecf
25.952381
87
0.55477
2.8622
false
false
false
false
zdary/intellij-community
platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/library/ProjectLibraryTableBridgeImpl.kt
2
10405
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.ide.impl.legacyBridge.library import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.project.Project import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryTable import com.intellij.openapi.roots.libraries.LibraryTablePresentation import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.util.Disposer import com.intellij.projectModel.ProjectModelBundle import com.intellij.util.EventDispatcher import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener import com.intellij.workspaceModel.ide.WorkspaceModelTopics import com.intellij.workspaceModel.ide.impl.executeOrQueueOnDispatchThread import com.intellij.workspaceModel.ide.impl.jps.serialization.getLegacyLibraryName import com.intellij.workspaceModel.ide.legacyBridge.ProjectLibraryTableBridge import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.bridgeEntities.LibraryEntity import com.intellij.workspaceModel.storage.bridgeEntities.LibraryId import com.intellij.workspaceModel.storage.bridgeEntities.LibraryTableId internal class ProjectLibraryTableBridgeImpl( private val parentProject: Project ) : ProjectLibraryTableBridge, Disposable { private val LOG = Logger.getInstance(javaClass) private val entityStorage: VersionedEntityStorage = WorkspaceModel.getInstance(parentProject).entityStorage private val dispatcher = EventDispatcher.create(LibraryTable.Listener::class.java) private val libraryArrayValue = CachedValue<Array<Library>> { storage -> storage.entities(LibraryEntity::class.java).filter { it.tableId == LibraryTableId.ProjectLibraryTableId } .mapNotNull { storage.libraryMap.getDataByEntity(it) } .toList().toTypedArray() } init { val messageBusConnection = project.messageBus.connect(this) WorkspaceModelTopics.getInstance(project).subscribeAfterModuleLoading(messageBusConnection, object : WorkspaceModelChangeListener { override fun beforeChanged(event: VersionedStorageChange) { val changes = event.getChanges(LibraryEntity::class.java).filterProjectLibraryChanges() .filterIsInstance<EntityChange.Removed<LibraryEntity>>() if (changes.isEmpty()) return executeOrQueueOnDispatchThread { for (change in changes) { val library = event.storageBefore.libraryMap.getDataByEntity(change.entity) LOG.debug { "Fire 'beforeLibraryRemoved' event for ${change.entity.name}, library = $library" } if (library != null) { dispatcher.multicaster.beforeLibraryRemoved(library) } } } } override fun changed(event: VersionedStorageChange) { val changes = event.getChanges(LibraryEntity::class.java).filterProjectLibraryChanges() if (changes.isEmpty()) return executeOrQueueOnDispatchThread { for (change in changes) { LOG.debug { "Process library change $change" } when (change) { is EntityChange.Added -> { val alreadyCreatedLibrary = event.storageAfter.libraryMap.getDataByEntity(change.entity) as LibraryBridgeImpl? val library = if (alreadyCreatedLibrary != null) { alreadyCreatedLibrary.entityStorage = entityStorage alreadyCreatedLibrary } else { var newLibrary: LibraryBridge? = null WorkspaceModel.getInstance(project).updateProjectModelSilent { newLibrary = it.mutableLibraryMap.getOrPutDataByEntity(change.entity) { LibraryBridgeImpl( libraryTable = this@ProjectLibraryTableBridgeImpl, project = project, initialId = change.entity.persistentId(), initialEntityStorage = entityStorage, targetBuilder = null ) } } newLibrary!! } dispatcher.multicaster.afterLibraryAdded(library) } is EntityChange.Removed -> { val library = event.storageBefore.libraryMap.getDataByEntity(change.entity) if (library != null) { // TODO There won't be any content in libraryImpl as EntityStore's current was already changed dispatcher.multicaster.afterLibraryRemoved(library) Disposer.dispose(library) } } is EntityChange.Replaced -> { val idBefore = change.oldEntity.persistentId() val idAfter = change.newEntity.persistentId() if (idBefore != idAfter) { val library = event.storageBefore.libraryMap.getDataByEntity(change.oldEntity) as? LibraryBridgeImpl if (library != null) { library.entityId = idAfter dispatcher.multicaster.afterLibraryRenamed(library, getLegacyLibraryName(idBefore)) } } } } } } } }) } internal fun loadLibraries() { val storage = entityStorage.current val libraries = storage .entities(LibraryEntity::class.java) .filter { it.tableId is LibraryTableId.ProjectLibraryTableId } .filter { storage.libraryMap.getDataByEntity(it) == null } .map { libraryEntity -> Pair(libraryEntity, LibraryBridgeImpl( libraryTable = this@ProjectLibraryTableBridgeImpl, project = project, initialId = libraryEntity.persistentId(), initialEntityStorage = entityStorage, targetBuilder = null )) } .toList() LOG.debug("Initial load of project-level libraries") if (libraries.isNotEmpty()) { WorkspaceModel.getInstance(project).updateProjectModelSilent { libraries.forEach { (entity, library) -> it.mutableLibraryMap.addIfAbsent(entity, library) } } libraries.forEach { (_, library) -> dispatcher.multicaster.afterLibraryAdded(library) } } } override fun getProject(): Project = parentProject override fun getLibraries(): Array<Library> = entityStorage.cachedValue(libraryArrayValue) override fun createLibrary(): Library = createLibrary(null) override fun createLibrary(name: String?): Library { if (name == null) error("Creating unnamed project libraries is unsupported") if (getLibraryByName(name) != null) { error("Project library named $name already exists") } val modifiableModel = modifiableModel modifiableModel.createLibrary(name) modifiableModel.commit() val newLibrary = getLibraryByName(name) if (newLibrary == null) { error("Library $name was not created") } return newLibrary } override fun removeLibrary(library: Library) { val modifiableModel = modifiableModel modifiableModel.removeLibrary(library) modifiableModel.commit() } override fun getLibraryIterator(): Iterator<Library> = libraries.iterator() override fun getLibraryByName(name: String): Library? { val entity = entityStorage.current.resolve(LibraryId(name, LibraryTableId.ProjectLibraryTableId)) ?: return null return entityStorage.current.libraryMap.getDataByEntity(entity) } override fun getTableLevel(): String = LibraryTablesRegistrar.PROJECT_LEVEL override fun getPresentation(): LibraryTablePresentation = PROJECT_LIBRARY_TABLE_PRESENTATION override fun getModifiableModel(): LibraryTable.ModifiableModel = ProjectModifiableLibraryTableBridgeImpl( libraryTable = this, project = project, originalStorage = entityStorage.current ) override fun getModifiableModel(diff: WorkspaceEntityStorageBuilder): LibraryTable.ModifiableModel = ProjectModifiableLibraryTableBridgeImpl( libraryTable = this, project = project, originalStorage = entityStorage.current, diff = diff, cacheStorageResult = false ) override fun addListener(listener: LibraryTable.Listener) = dispatcher.addListener(listener) override fun addListener(listener: LibraryTable.Listener, parentDisposable: Disposable) = dispatcher.addListener(listener, parentDisposable) override fun removeListener(listener: LibraryTable.Listener) = dispatcher.removeListener(listener) override fun dispose() { for (library in libraries) { Disposer.dispose(library) } } companion object { private fun List<EntityChange<LibraryEntity>>.filterProjectLibraryChanges() = filter { when (it) { is EntityChange.Added -> it.entity.tableId is LibraryTableId.ProjectLibraryTableId is EntityChange.Removed -> it.entity.tableId is LibraryTableId.ProjectLibraryTableId is EntityChange.Replaced -> it.oldEntity.tableId is LibraryTableId.ProjectLibraryTableId } } internal val PROJECT_LIBRARY_TABLE_PRESENTATION = object : LibraryTablePresentation() { override fun getDisplayName(plural: Boolean) = ProjectModelBundle.message("project.library.display.name", if (plural) 2 else 1) override fun getDescription() = ProjectModelBundle.message("libraries.node.text.project") override fun getLibraryTableEditorTitle() = ProjectModelBundle.message("library.configure.project.title") } private const val LIBRARY_BRIDGE_MAPPING_ID = "intellij.libraries.bridge" internal val WorkspaceEntityStorage.libraryMap: ExternalEntityMapping<LibraryBridge> get() = getExternalMapping(LIBRARY_BRIDGE_MAPPING_ID) internal val WorkspaceEntityStorageDiffBuilder.mutableLibraryMap: MutableExternalEntityMapping<LibraryBridge> get() = getMutableExternalMapping(LIBRARY_BRIDGE_MAPPING_ID) internal fun WorkspaceEntityStorage.findLibraryEntity(library: LibraryBridge) = libraryMap.getEntities(library).firstOrNull() as LibraryEntity? } }
apache-2.0
ae4f9b819519e0dd22bea693c9475d74
40.955645
140
0.701586
5.456214
false
false
false
false
code-helix/slatekit
src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_Args.kt
1
5174
/** <slate_header> author: Kishore Reddy url: www.github.com/code-helix/slatekit copyright: 2015 Kishore Reddy license: www.github.com/code-helix/slatekit/blob/master/LICENSE.md desc: A tool-kit, utility library and server-backend usage: Please refer to license on github for more info. </slate_header> */ package slatekit.examples //<doc:import_required> import slatekit.common.args.Args import slatekit.common.args.ArgsSchema //</doc:import_required> //<doc:import_examples> import slatekit.results.Success import slatekit.results.Try import slatekit.results.getOrElse //</doc:import_examples> class Example_Args : Command("args") { override fun execute(request: CommandRequest) : Try<Any> { //<doc:examples> // Example: // Given on the the command line: // -log.level=info -env=dev -text='hello world' showResults( Args.parse( "-log.level=info -env=dev -text='hello world'") ) // CASE 1: Parse using an action prefixed to the arguments showResults( Args.parse( "service.action -log.level=info -env=dev -text='hello world'", hasAction = true) ) // CASE 2: Custom prefix and sep e.g. "!" and separator ":" showResults( Args.parse( "!env=dev !text='hello word' !batch:10 ", prefix = "!", sep = ":") ) // CASE 3a: Check for action/method call in the beginning val args = Args.parse( "manage.movies.createSample -title='Dark Knight' -date='2013-07-18'", hasAction = true ) showResults( args ) args.onSuccess { args -> args.getString("title") args.getLocalDate("date") } // CASE 3c: Check for only action name in the beginning. showResults( Args.parse( "method", prefix = "-", sep = "=", hasAction = true ) ) // CASE 4: No args showResults( Args.parse( "service.method", prefix = "-", sep = "=", hasAction = true ) ) // CASE 5a: Help request ( "?", "help") showResults( Args.parse( "?" ) ) // CASE 5b: Help request with method call ( "method.action" ? ) showResults( Args.parse( "service.method help" , hasAction = true ) ) // CASE 6: Version request ( "ver", "version" ) showResults( Args.parse( "version" ) ) // CASE 7: Exit request showResults( Args.parse( "exit" ) ) // CASE 8: Build up the schema val schema = ArgsSchema().text("env", "env").flag("log", "log").number("level", "level") print(schema) //</doc:examples> return Success("") } //<doc:examples_support> fun showResults(result:Try<Args>) { println("RESULTS:") if(!result.success) { println("Error parsing args : " + result.desc) return } val args = result.getOrElse { Args.empty() } println("action : " + args.action) if(!args.parts.isEmpty()) { print("parts : ") var parts = "" args.parts.forEach{ item -> parts += (item + " ") } println( parts ) } println("prefix : '" + args.prefix + "'") println("separator: '" + args.separator + "'") println("named : " + args.named.size ) if(!args.named.isEmpty()) { args.named.forEach { pair -> println("\t" + pair.key + " " + args.separator + " " + pair.value) } } println("index : " + args.positional.size) if(!args.positional.isEmpty()) { args.positional.forEach{ item -> println( "\t" + item) } } if(args.isHelp) println("help") if(args.isEmpty) println("empty") if(args.isVersion)println("version") println() println() } //</doc:examples_support> /* //<doc:output> {{< highlight bat >}} RESULTS: action : prefix : '-' separator: ':' named : 3 text : hello world batch : 10 env : dev index : 0 RESULTS: action : prefix : '!' separator: '=' named : 3 text = hello word batch = 10 env = dev index : 0 RESULTS: action : area.service.method parts : area service method prefix : '-' separator: '=' named : 3 text = hello word batch = 10 env = dev index : 0 RESULTS: action : service.method parts : service method prefix : '-' separator: '=' named : 3 text = hello word batch = 10 env = dev index : 0 RESULTS: action : method parts : method prefix : '-' separator: '=' named : 0 index : 0 empty RESULTS: action : service.method parts : service method prefix : '-' separator: '=' named : 0 index : 0 empty RESULTS: action : prefix : '-' separator: ':' named : 0 index : 1 ? help RESULTS: action : service.method.help parts : service method help prefix : '-' separator: ':' named : 0 index : 0 empty RESULTS: action : prefix : '-' separator: ':' named : 0 index : 1 version version RESULTS: action : prefix : '-' separator: ':' named : 0 index : 1 {{< /highlight >}} //</doc:output> */ /** * Sample class to show storing of the command line options. * * @param env * @param text * @param batch */ class SampleOptions(val env:String, val text:String, val batch:Int) }
apache-2.0
0d25bbe3efc4f2434f14ea6c968bea2c
20.380165
115
0.586394
3.570738
false
false
false
false
leafclick/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/update/RefreshVFsSynchronously.kt
1
4755
// 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.openapi.vcs.update import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.ChangesUtil.CASE_SENSITIVE_FILE_PATH_HASHING_STRATEGY import com.intellij.openapi.vcs.changes.ContentRevision import com.intellij.openapi.vcs.update.UpdateFilesHelper.iterateFileGroupFilesDeletedOnServerFirst import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil.markDirtyAndRefresh import com.intellij.openapi.vfs.VirtualFile import java.io.File interface FilePathChange { val beforePath: FilePath? val afterPath: FilePath? } object RefreshVFsSynchronously { @JvmStatic fun updateAllChanged(updatedFiles: UpdatedFiles) { val collector = FilesCollector() iterateFileGroupFilesDeletedOnServerFirst(updatedFiles, collector) refreshDeletedFiles(collector.deletedFiles) refreshFiles(collector.files) } @JvmStatic fun refreshFiles(files: Collection<File>) { val toRefresh = files.mapNotNullTo(mutableSetOf()) { findValidParent(it) } markDirtyAndRefresh(false, false, false, *toRefresh.toTypedArray()) } private fun refreshDeletedFiles(files: Collection<File>) { val toRefresh = files.mapNotNullTo(mutableSetOf()) { findValidParent(it.parentFile) } markDirtyAndRefresh(false, true, false, *toRefresh.toTypedArray()) } private fun findValidParent(file: File?): VirtualFile? = generateSequence(file) { it.parentFile } .mapNotNull { LocalFileSystem.getInstance().findFileByIoFile(it) } .firstOrNull { it.isValid } @JvmStatic fun updateChangesForRollback(changes: List<Change>) = refresh(changes, REVERSED_CHANGE_WRAPPER) @JvmStatic fun updateChanges(changes: Collection<Change>) = refresh(changes, CHANGE_WRAPPER) fun refresh(changes: Collection<FilePathChange>, isRollback: Boolean = false) = refresh(changes, if (isRollback) REVERSED_FILE_PATH_CHANGE_WRAPPER else FILE_PATH_CHANGE_WRAPPER) private fun <T> refresh(changes: Collection<T>, wrapper: Wrapper<T>) { val files = mutableSetOf<File>() val deletedFiles = mutableSetOf<File>() changes.forEach { change -> val beforePath = wrapper.getBeforePath(change) val afterPath = wrapper.getAfterPath(change) beforePath?.let { (if (wrapper.isBeforePathDeleted(change)) deletedFiles else files) += it.ioFile } afterPath?.let { if (it != beforePath) files += it.ioFile } } refreshFiles(files) refreshDeletedFiles(deletedFiles) } } private val CHANGE_WRAPPER = ChangeWrapper(false) private val REVERSED_CHANGE_WRAPPER = ChangeWrapper(true) private val FILE_PATH_CHANGE_WRAPPER = FilePathChangeWrapper(false) private val REVERSED_FILE_PATH_CHANGE_WRAPPER = FilePathChangeWrapper(true) private class ChangeWrapper(private val isReversed: Boolean) : Wrapper<Change> { private fun getBeforeRevision(change: Change): ContentRevision? = change.run { if (isReversed) afterRevision else beforeRevision } private fun getAfterRevision(change: Change): ContentRevision? = change.run { if (isReversed) beforeRevision else afterRevision } override fun getBeforePath(change: Change): FilePath? = getBeforeRevision(change)?.file override fun getAfterPath(change: Change): FilePath? = getAfterRevision(change)?.file override fun isBeforePathDeleted(change: Change): Boolean = change.run { getAfterRevision(this) == null || isMoved || isRenamed || isIsReplaced } } private class FilePathChangeWrapper(private val isReversed: Boolean) : Wrapper<FilePathChange> { override fun getBeforePath(change: FilePathChange): FilePath? = change.run { if (isReversed) afterPath else beforePath } override fun getAfterPath(change: FilePathChange): FilePath? = change.run { if (isReversed) beforePath else afterPath } override fun isBeforePathDeleted(change: FilePathChange): Boolean = change.let { getAfterPath(it) == null || !CASE_SENSITIVE_FILE_PATH_HASHING_STRATEGY.equals(getBeforePath(it), getAfterPath(it)) } } private interface Wrapper<T> { fun getBeforePath(change: T): FilePath? fun getAfterPath(change: T): FilePath? fun isBeforePathDeleted(change: T): Boolean } private class FilesCollector : UpdateFilesHelper.Callback { val files = mutableSetOf<File>() val deletedFiles = mutableSetOf<File>() override fun onFile(filePath: String, groupId: String) { val file = File(filePath) if (FileGroup.REMOVED_FROM_REPOSITORY_ID == groupId || FileGroup.MERGED_WITH_TREE_CONFLICT.endsWith(groupId)) { deletedFiles.add(file) } else { files.add(file) } } }
apache-2.0
f02d945391951ef55176a3b7f5b24b63
40.356522
140
0.75878
4.116883
false
false
false
false
smmribeiro/intellij-community
platform/lang-api/src/com/intellij/ide/bookmark/BookmarkType.kt
1
5348
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.bookmark import com.intellij.ide.ui.UISettings import com.intellij.lang.LangBundle import com.intellij.openapi.editor.colors.EditorColorsUtil import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.util.registry.Registry import com.intellij.util.ui.RegionPainter import com.intellij.ui.IconWrapperWithToolTip import com.intellij.ui.JBColor import com.intellij.ui.paint.RectanglePainter import com.intellij.util.ui.RegionPaintIcon import java.awt.Component import java.awt.Graphics2D import java.awt.RenderingHints import java.awt.geom.Path2D import javax.swing.Icon enum class BookmarkType(val mnemonic: Char, private val painter: RegionPainter<Component?>) { DIGIT_1('1'), DIGIT_2('2'), DIGIT_3('3'), DIGIT_4('4'), DIGIT_5('5'), DIGIT_6('6'), DIGIT_7('7'), DIGIT_8('8'), DIGIT_9('9'), DIGIT_0('0'), LETTER_A('A'), LETTER_B('B'), LETTER_C('C'), LETTER_D('D'), LETTER_E('E'), LETTER_F('F'), LETTER_G('G'), LETTER_H('H'), LETTER_I('I'), LETTER_J('J'), LETTER_K('K'), LETTER_L('L'), LETTER_M('M'), LETTER_N('N'), LETTER_O('O'), LETTER_P('P'), LETTER_Q('Q'), LETTER_R('R'), LETTER_S('S'), LETTER_T('T'), LETTER_U('U'), LETTER_V('V'), LETTER_W('W'), LETTER_X('X'), LETTER_Y('Y'), LETTER_Z('Z'), DEFAULT(0.toChar(), BookmarkPainter()); constructor(mnemonic: Char) : this(mnemonic, MnemonicPainter(mnemonic.toString())) val icon by lazy { createIcon(16, 1) } val gutterIcon by lazy { createIcon(12, 0) } private fun createIcon(size: Int, insets: Int): Icon = IconWrapperWithToolTip( RegionPaintIcon(size, size, insets, painter).withIconPreScaled(false), LangBundle.messagePointer("tooltip.bookmarked")) companion object { @JvmStatic fun get(mnemonic: Char) = values().firstOrNull { it.mnemonic == mnemonic } ?: DEFAULT } } private val BOOKMARK_ICON_BACKGROUND = EditorColorsUtil.createColorKey("Bookmark.iconBackground", JBColor(0xF7C777, 0xAA8542)) private class BookmarkPainter : RegionPainter<Component?> { override fun toString() = "BookmarkIcon" override fun hashCode() = toString().hashCode() override fun equals(other: Any?) = other === this || other is BookmarkPainter override fun paint(g: Graphics2D, x: Int, y: Int, width: Int, height: Int, c: Component?) { val background = EditorColorsUtil.getColor(c, BOOKMARK_ICON_BACKGROUND) if (background != null) { val xL = width / 6f val xR = width - xL val xC = width / 2f val yT = height / 24f val yB = height - yT val yC = yB + xL - xC val path = Path2D.Float() path.moveTo(x + xL, y + yT) path.lineTo(x + xL, y + yB) path.lineTo(x + xC, y + yC) path.lineTo(x + xR, y + yB) path.lineTo(x + xR, y + yT) path.closePath() g.paint = background g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.fill(path) } } } private val MNEMONIC_ICON_FOREGROUND = EditorColorsUtil.createColorKey("Bookmark.Mnemonic.iconForeground", JBColor(0x000000, 0xBBBBBB)) private val MNEMONIC_ICON_BACKGROUND = EditorColorsUtil.createColorKey("Bookmark.Mnemonic.iconBackground", JBColor(0xFEF7EC, 0x5B5341)) private val MNEMONIC_ICON_BORDER_COLOR = EditorColorsUtil.createColorKey("Bookmark.Mnemonic.iconBorderColor", JBColor(0xF4AF3D, 0xD9A343)) private class MnemonicPainter(val mnemonic: String) : RegionPainter<Component?> { override fun toString() = "BookmarkMnemonicIcon:$mnemonic" override fun hashCode() = mnemonic.hashCode() override fun equals(other: Any?): Boolean { if (other === this) return true val painter = other as? MnemonicPainter ?: return false return painter.mnemonic == mnemonic } override fun paint(g: Graphics2D, x: Int, y: Int, width: Int, height: Int, c: Component?) { val foreground = EditorColorsUtil.getColor(c, MNEMONIC_ICON_FOREGROUND) val background = EditorColorsUtil.getColor(c, MNEMONIC_ICON_BACKGROUND) val borderColor = EditorColorsUtil.getColor(c, MNEMONIC_ICON_BORDER_COLOR) val divisor = Registry.intValue("ide.mnemonic.icon.round", 0) val round = if (divisor > 0) width.coerceAtLeast(height) / divisor else null if (background != null) { g.paint = background RectanglePainter.FILL.paint(g, x, y, width, height, round) } if (foreground != null) { g.paint = foreground UISettings.setupAntialiasing(g) val frc = g.fontRenderContext val font = EditorFontType.PLAIN.globalFont val size1 = .8f * height val vector1 = font.deriveFont(size1).createGlyphVector(frc, mnemonic) val bounds1 = vector1.visualBounds val size2 = .8f * size1 * size1 / bounds1.height.toFloat() val vector2 = font.deriveFont(size2).createGlyphVector(frc, mnemonic) val bounds2 = vector2.visualBounds val dx = x - bounds2.x + .5 * (width - bounds2.width) val dy = y - bounds2.y + .5 * (height - bounds2.height) g.drawGlyphVector(vector2, dx.toFloat(), dy.toFloat()) } if (borderColor != null && borderColor != background) { g.paint = borderColor RectanglePainter.DRAW.paint(g, x, y, width, height, round) } } }
apache-2.0
62a2c9af1a7d1ebeb7101f50824dfbb7
40.138462
158
0.693343
3.441441
false
false
false
false
smmribeiro/intellij-community
jvm/jvm-analysis-kotlin-tests/testData/codeInspection/nonNls/LiteralsInNonNlsClass.kt
19
323
import org.jetbrains.annotations.NonNls @NonNls class LiteralsInNonNlsClass { var field = "field" fun method(param: String = "paramDefaultValue"): String { field = "field" val variable = "var" variable.plus("plus") variable == "equalityOperator" variable.equals("equals") return "return" } }
apache-2.0
25f78d4097bcc28f68e69be7eb921853
20.6
59
0.678019
3.891566
false
false
false
false
smmribeiro/intellij-community
platform/core-impl/src/com/intellij/ide/plugins/dataLoader.kt
9
1084
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.plugins import com.intellij.util.lang.ZipFilePool import org.jetbrains.annotations.ApiStatus import java.io.InputStream import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.Path @ApiStatus.Internal interface DataLoader { val pool: ZipFilePool? val emptyDescriptorIfCannotResolve: Boolean get() = false fun isExcludedFromSubSearch(jarFile: Path): Boolean = false fun load(path: String): InputStream? override fun toString(): String } @ApiStatus.Internal class LocalFsDataLoader(val basePath: Path) : DataLoader { override val pool: ZipFilePool? get() = ZipFilePool.POOL override val emptyDescriptorIfCannotResolve: Boolean get() = true override fun load(path: String): InputStream? { return try { Files.newInputStream(basePath.resolve(path)) } catch (e: NoSuchFileException) { null } } override fun toString() = basePath.toString() }
apache-2.0
073f9690c7770d912b085a12bb74518b
24.232558
120
0.748155
4.185328
false
false
false
false
smmribeiro/intellij-community
plugins/gradle/native/tooling/testSources/org/jetbrains/plugins/gradle/nativeplatform/tooling/model/DeterminedEntityGenerator.kt
13
965
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.nativeplatform.tooling.model import java.util.* import kotlin.collections.LinkedHashSet class DeterminedEntityGenerator { private val alphaNum = ('a'..'z') + ('A'..'Z') + ('0'..'9') private val strings = LinkedHashSet<String>() private val random = Random(0) fun nextInt(lower: Int, upper: Int) = random.nextInt(upper - lower) + lower fun nextBoolean() = random.nextBoolean() fun nextString(length: Int) = (1..length) .map { random.nextInt(alphaNum.size) } .map(alphaNum::get) .joinToString("") tailrec fun nextUString(minLength: Int): String { repeat(100) { val string = nextString(minLength) if (!strings.contains(string)) { strings.add(string) return string } } return nextUString(minLength + 1) } }
apache-2.0
0a86daeb4517a225a98680058fc04ac9
28.272727
140
0.674611
3.814229
false
false
false
false
fabmax/kool
kool-core/src/jvmMain/kotlin/de/fabmax/kool/platform/gl/ShaderGeneratorImplGL.kt
1
9414
package de.fabmax.kool.platform.gl import de.fabmax.kool.KoolContext import de.fabmax.kool.pipeline.* import de.fabmax.kool.pipeline.shadermodel.CodeGenerator import de.fabmax.kool.pipeline.shadermodel.ShaderGenerator import de.fabmax.kool.pipeline.shadermodel.ShaderGraph import de.fabmax.kool.pipeline.shadermodel.ShaderModel class ShaderGeneratorImplGL : ShaderGenerator() { override fun generateShader(model: ShaderModel, pipelineLayout: Pipeline.Layout, ctx: KoolContext): ShaderCode { val (vs, fs) = generateCode(model, pipelineLayout) return ShaderCode(ShaderCode.GlCode(vs, fs)) } private fun generateCode(model: ShaderModel, pipelineLayout: Pipeline.Layout): Pair<String, String> { val vertShader = generateVertexShaderCode(model, pipelineLayout) val fragShader = generateFragmentShaderCode(model, pipelineLayout) if (model.dumpCode) { println("Vertex shader:\n$vertShader") println("Fragment shader:\n$fragShader") } return vertShader to fragShader } private fun generateVertexShaderCode(model: ShaderModel, pipelineLayout: Pipeline.Layout): String { val codeGen = CodeGen() model.vertexStageGraph.generateCode(codeGen) return """ #version 300 es ${model.infoStr()} // descriptor layout / uniforms ${generateDescriptorBindings(pipelineLayout, ShaderStage.VERTEX_SHADER)} // vertex attributes ${generateAttributeBindings(pipelineLayout)} // outputs ${model.vertexStageGraph.generateStageOutputs()} // functions ${codeGen.generateFunctions()} void main() { ${codeGen.generateMain()} gl_Position = ${model.vertexStageGraph.positionOutput.variable.ref4f()}; } """.trimIndent() } private fun generateFragmentShaderCode(model: ShaderModel, pipelineLayout: Pipeline.Layout): String { val codeGen = CodeGen() model.fragmentStageGraph.generateCode(codeGen) return """ #version 300 es precision highp float; precision highp sampler2DShadow; ${model.infoStr()} // descriptor layout / uniforms ${generateDescriptorBindings(pipelineLayout, ShaderStage.FRAGMENT_SHADER)} // inputs ${model.fragmentStageGraph.generateStageInputs()} // functions ${codeGen.generateFunctions()} void main() { ${codeGen.generateMain()} } """.trimIndent() } private fun ShaderModel.infoStr(): String { return modelName.lines().joinToString { "// $it\n"} } private fun generateDescriptorBindings(pipelineLayout: Pipeline.Layout, stage: ShaderStage): String { val srcBuilder = StringBuilder("\n") pipelineLayout.descriptorSets.forEach { set -> set.descriptors.forEach { desc -> if (desc.stages.contains(stage)) { when (desc) { is UniformBuffer -> srcBuilder.append(generateUniformBuffer(desc)) is TextureSampler1d -> srcBuilder.append(generateTextureSampler1d(desc)) is TextureSampler2d -> srcBuilder.append(generateTextureSampler2d(desc)) is TextureSampler3d -> srcBuilder.append(generateTextureSampler3d(desc)) is TextureSamplerCube -> srcBuilder.append(generateTextureSamplerCube(desc)) } } } } // WebGL doesn't have an equivalent for push constants, generate standard uniforms instead val pushConstants = pipelineLayout.pushConstantRanges.filter { it.stages.contains(stage) } if (pushConstants.isNotEmpty()) { pipelineLayout.pushConstantRanges.forEach { pcr -> pcr.pushConstants.forEach { u -> srcBuilder.appendln("uniform ${u.declare()};") } } } return srcBuilder.toString() } private fun generateUniformBuffer(desc: UniformBuffer): String { // fixme: implement support for UBOs (supported by WebGL2), for now individual uniforms are used val srcBuilder = StringBuilder() desc.uniforms.forEach { u -> srcBuilder.appendln("uniform ${u.declare()};") } return srcBuilder.toString() } private fun generateTextureSampler1d(desc: TextureSampler1d): String { val arraySuffix = if (desc.arraySize > 1) { "[${desc.arraySize}]" } else { "" } return "uniform sampler2D ${desc.name}$arraySuffix;\n" } private fun generateTextureSampler2d(desc: TextureSampler2d): String { val samplerType = if (desc.isDepthSampler) "sampler2DShadow" else "sampler2D" val arraySuffix = if (desc.arraySize > 1) { "[${desc.arraySize}]" } else { "" } return "uniform $samplerType ${desc.name}$arraySuffix;\n" } private fun generateTextureSampler3d(desc: TextureSampler3d): String { val arraySuffix = if (desc.arraySize > 1) { "[${desc.arraySize}]" } else { "" } return "uniform sampler3D ${desc.name}$arraySuffix;\n" } private fun generateTextureSamplerCube(desc: TextureSamplerCube): String { val samplerType = if (desc.isDepthSampler) "samplerCubeShadow" else "samplerCube" val arraySuffix = if (desc.arraySize > 1) { "[${desc.arraySize}]" } else { "" } return "uniform $samplerType ${desc.name}$arraySuffix;\n" } private fun generateAttributeBindings(pipelineLayout: Pipeline.Layout): String { val srcBuilder = StringBuilder("\n") pipelineLayout.vertices.bindings.forEach { binding -> binding.vertexAttributes.forEach { attr -> srcBuilder.appendln("layout(location=${attr.location}) in ${attr.type.glslType} ${attr.name};") } } return srcBuilder.toString() } private fun ShaderGraph.generateStageInputs(): String { val srcBuilder = StringBuilder("\n") inputs.forEach { val flat = if (it.isFlat) "flat" else "" srcBuilder.appendln("$flat in ${it.variable.glslType()} ${it.variable.name};") } return srcBuilder.toString() } private fun ShaderGraph.generateStageOutputs(): String { val srcBuilder = StringBuilder("\n") outputs.forEach { val flat = if (it.isFlat) "flat" else "" srcBuilder.appendln("$flat out ${it.variable.glslType()} ${it.variable.name};") } return srcBuilder.toString() } private fun StringBuilder.appendln(line: String) = append("$line\n") private fun Uniform<*>.declare(): String { return when (this) { is Uniform1f -> "float $name" is Uniform2f -> "vec2 $name" is Uniform3f -> "vec3 $name" is Uniform4f -> "vec4 $name" is UniformColor -> "vec4 $name" is Uniform1fv -> "float $name[$length]" is Uniform2fv -> "vec2 $name[$length]" is Uniform3fv -> "vec3 $name[$length]" is Uniform4fv -> "vec4 $name[$length]" is UniformMat3f -> "mat3 $name" is UniformMat3fv -> "mat3 $name[$length" is UniformMat4f -> "mat4 $name" is UniformMat4fv -> "mat4 $name[$length]" is Uniform1i -> "int $name" is Uniform2i -> "ivec2 $name" is Uniform3i -> "ivec3 $name" is Uniform4i -> "ivec4 $name" is Uniform1iv -> "int $name[$length]" is Uniform2iv -> "ivec2 $name[$length]" is Uniform3iv -> "ivec3 $name[$length]" is Uniform4iv -> "ivec4 $name[$length]" } } private class CodeGen : CodeGenerator { val functions = mutableMapOf<String, String>() val mainCode = mutableListOf<String>() override fun appendFunction(name: String, glslCode: String) { functions[name] = glslCode } override fun appendMain(glslCode: String) { mainCode += glslCode } override fun sampleTexture1d(texName: String, texCoords: String, lod: String?) = sampleTexture(texName, "vec2($texCoords, 0.0)", lod) override fun sampleTexture2d(texName: String, texCoords: String, lod: String?) = sampleTexture(texName, texCoords, lod) override fun sampleTexture2dDepth(texName: String, texCoords: String): String { return "textureProj($texName, $texCoords)" } override fun sampleTexture3d(texName: String, texCoords: String, lod: String?) = sampleTexture(texName, texCoords, lod) override fun sampleTextureCube(texName: String, texCoords: String, lod: String?) = sampleTexture(texName, texCoords, lod) fun generateFunctions(): String = functions.values.joinToString("\n") fun generateMain(): String = mainCode.joinToString("\n") private fun sampleTexture(texName: String, texCoords: String, lod: String?): String { return if (lod == null) { "texture($texName, $texCoords)" } else { "textureLod($texName, $texCoords, $lod)" } } } }
apache-2.0
3bb2aa8b532cda5f8808455dd38a61bd
40.29386
118
0.609199
4.470085
false
false
false
false
stepstone-tech/android-material-app-rating
app-rating/src/main/java/com/stepstone/apprating/AppRatingDialogFragment.kt
1
6940
/* Copyright 2017 StepStone Services 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.stepstone.apprating import android.app.Dialog import android.content.Context import android.os.Bundle import androidx.fragment.app.DialogFragment import androidx.appcompat.app.AlertDialog import android.text.TextUtils import com.stepstone.apprating.extensions.applyIfNotZero import com.stepstone.apprating.listener.RatingDialogListener /** * This class represents rating dialog created by [com.stepstone.apprating.AppRatingDialog.Builder]. * @see AppRatingDialog */ class AppRatingDialogFragment : DialogFragment() { private var listener: RatingDialogListener? = null get() { if (host is RatingDialogListener) { return host as RatingDialogListener } return targetFragment as RatingDialogListener? } private lateinit var data: AppRatingDialog.Builder.Data private lateinit var alertDialog: AlertDialog private lateinit var dialogView: AppRatingDialogView private val title by lazy { data.title.resolveText(resources) } private val description by lazy { data.description.resolveText(resources) } private val defaultComment by lazy { data.defaultComment.resolveText(resources) } private val hint by lazy { data.hint.resolveText(resources) } private val positiveButtonText by lazy { data.positiveButtonText.resolveText(resources) } private val neutralButtonText by lazy { data.neutralButtonText.resolveText(resources) } private val negativeButtonText by lazy { data.negativeButtonText.resolveText(resources) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return setupAlertDialog(activity!!) } override fun onSaveInstanceState(outState: Bundle) { outState.putFloat(CURRENT_RATE_NUMBER, dialogView.rateNumber) super.onSaveInstanceState(outState) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val rateNumber: Float? = savedInstanceState?.getFloat(CURRENT_RATE_NUMBER) if (rateNumber != null) { dialogView.setDefaultRating(rateNumber.toInt()) } } private fun setupAlertDialog(context: Context): AlertDialog { dialogView = AppRatingDialogView(context) val builder = AlertDialog.Builder(activity!!) data = arguments?.getSerializable(DIALOG_DATA) as AppRatingDialog.Builder.Data setupPositiveButton(dialogView, builder) setupNegativeButton(builder) setupNeutralButton(builder) setupTitleAndContentMessages(dialogView) setupHint(dialogView) setupColors(dialogView) setupInputBox() setupRatingBar() builder.setView(dialogView) alertDialog = builder.create() setupAnimation() setupCancelable() return alertDialog } private fun setupRatingBar() { dialogView.setNumberOfStars(data.numberOfStars) val isEmpty = data.noteDescriptions?.isEmpty() ?: true if (!isEmpty) { dialogView.setNoteDescriptions(data.noteDescriptions!!) } dialogView.setDefaultRating(data.defaultRating) } private fun setupInputBox() { dialogView.setCommentInputEnabled(data.commentInputEnabled) } private fun setupCancelable() { data.cancelable?.let { isCancelable = it } data.canceledOnTouchOutside?.let { alertDialog.setCanceledOnTouchOutside(it) } } private fun setupAnimation() { if (data.windowAnimationResId != 0) { alertDialog.window.attributes.windowAnimations = data.windowAnimationResId } } private fun setupColors(dialogView: AppRatingDialogView) { data.titleTextColorResId.applyIfNotZero { dialogView.setTitleTextColor(this) } data.descriptionTextColorResId.applyIfNotZero { dialogView.setDescriptionTextColor(this) } data.commentTextColorResId.applyIfNotZero { dialogView.setEditTextColor(this) } data.commentBackgroundColorResId.applyIfNotZero { dialogView.setEditBackgroundColor(this) } data.hintTextColorResId.applyIfNotZero { dialogView.setHintColor(this) } data.starColorResId.applyIfNotZero { dialogView.setStarColor(this) } data.noteDescriptionTextColor.applyIfNotZero { dialogView.setNoteDescriptionTextColor(this) } } private fun setupTitleAndContentMessages(dialogView: AppRatingDialogView) { if (!title.isNullOrEmpty()) { dialogView.setTitleText(title!!) } if (!description.isNullOrEmpty()) { dialogView.setDescriptionText(description!!) } if (!defaultComment.isNullOrEmpty()) { dialogView.setDefaultComment(defaultComment!!) } } private fun setupHint(dialogView: AppRatingDialogView) { if (!TextUtils.isEmpty(hint)) { dialogView.setHint(hint!!) } } private fun setupNegativeButton(builder: AlertDialog.Builder) { if (!TextUtils.isEmpty(negativeButtonText)) { builder.setNegativeButton(negativeButtonText) { _, _ -> listener?.onNegativeButtonClicked() } } } private fun setupPositiveButton(dialogView: AppRatingDialogView, builder: AlertDialog.Builder) { if (!TextUtils.isEmpty(positiveButtonText)) { builder.setPositiveButton(positiveButtonText) { _, _ -> val rateNumber = dialogView.rateNumber.toInt() val comment = dialogView.comment listener?.onPositiveButtonClicked(rateNumber, comment) } } } private fun setupNeutralButton(builder: AlertDialog.Builder) { if (!TextUtils.isEmpty(neutralButtonText)) { builder.setNeutralButton(neutralButtonText) { _, _ -> listener?.onNeutralButtonClicked() } } } companion object { fun newInstance(data: AppRatingDialog.Builder.Data): AppRatingDialogFragment { val fragment = AppRatingDialogFragment() val bundle = Bundle() bundle.putSerializable(DIALOG_DATA, data) fragment.arguments = bundle return fragment } } }
apache-2.0
62bca0f10ca93f68f0a5e60fc5bf78e3
34.228426
100
0.684006
5.140741
false
false
false
false
jotomo/AndroidAPS
danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgInitConnStatusTime_k.kt
1
2415
package info.nightscout.androidaps.danaRKorean.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danar.R import info.nightscout.androidaps.danar.comm.MessageBase import info.nightscout.androidaps.events.EventRebuildTabs import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification class MsgInitConnStatusTime_k( injector: HasAndroidInjector ) : MessageBase(injector) { init { SetCommand(0x0301) aapsLogger.debug(LTag.PUMPCOMM, "New message") } override fun handleMessage(bytes: ByteArray) { if (bytes.size - 10 < 10) { val notification = Notification(Notification.WRONG_DRIVER, resourceHelper.gs(R.string.pumpdrivercorrected), Notification.NORMAL) rxBus.send(EventNewNotification(notification)) danaRKoreanPlugin.disconnect("Wrong Model") aapsLogger.debug(LTag.PUMPCOMM, "Wrong model selected. Switching to export DanaR") danaRKoreanPlugin.setPluginEnabled(PluginType.PUMP, false) danaRKoreanPlugin.setFragmentVisible(PluginType.PUMP, false) danaRPlugin.setPluginEnabled(PluginType.PUMP, true) danaRPlugin.setFragmentVisible(PluginType.PUMP, true) danaPump.reset() // mark not initialized //If profile coming from pump, switch it as well configBuilder.storeSettings("ChangingKoreanDanaDriver") rxBus.send(EventRebuildTabs()) commandQueue.readStatus("PumpDriverChange", null) // force new connection return } val time = dateTimeSecFromBuff(bytes, 0) val versionCode1 = intFromBuff(bytes, 6, 1) val versionCode2 = intFromBuff(bytes, 7, 1) val versionCode3 = intFromBuff(bytes, 8, 1) val versionCode4 = intFromBuff(bytes, 9, 1) aapsLogger.debug(LTag.PUMPCOMM, "Pump time: " + dateUtil.dateAndTimeString(time)) aapsLogger.debug(LTag.PUMPCOMM, "Version code1: $versionCode1") aapsLogger.debug(LTag.PUMPCOMM, "Version code2: $versionCode2") aapsLogger.debug(LTag.PUMPCOMM, "Version code3: $versionCode3") aapsLogger.debug(LTag.PUMPCOMM, "Version code4: $versionCode4") } }
agpl-3.0
d7283b76db2c761f4fd90c8f87bc572a
48.306122
140
0.721739
4.548023
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/duplicateUtil.kt
1
4553
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine import com.intellij.codeInsight.folding.CodeFoldingManager import com.intellij.codeInsight.highlighting.HighlightManager import com.intellij.find.FindManager import com.intellij.java.refactoring.JavaRefactoringBundle import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.markup.RangeHighlighter import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.refactoring.util.duplicates.MethodDuplicatesHandler import com.intellij.ui.ReplacePromptDialog import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiRange import org.jetbrains.kotlin.idea.refactoring.introduce.getPhysicalTextRange import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.isUnitTestMode fun KotlinPsiRange.highlight(project: Project, editor: Editor): RangeHighlighter? { val textRange = getPhysicalTextRange() val highlighters = ArrayList<RangeHighlighter>() HighlightManager.getInstance(project).addRangeHighlight( editor, textRange.startOffset, textRange.endOffset, EditorColors.SEARCH_RESULT_ATTRIBUTES, true, highlighters ) return highlighters.firstOrNull() } fun KotlinPsiRange.preview(project: Project, editor: Editor): RangeHighlighter? { val highlight = highlight(project, editor) ?: return null val startOffset = getPhysicalTextRange().startOffset val foldedRegions = CodeFoldingManager.getInstance(project) .getFoldRegionsAtOffset(editor, startOffset) .filter { !it.isExpanded } if (!foldedRegions.isEmpty()) { editor.foldingModel.runBatchFoldingOperation { foldedRegions.forEach { it.isExpanded = true } } } editor.scrollingModel.scrollTo(editor.offsetToLogicalPosition(startOffset), ScrollType.MAKE_VISIBLE) return highlight } fun processDuplicates( duplicateReplacers: Map<KotlinPsiRange, () -> Unit>, project: Project, editor: Editor, scopeDescription: String = "this file", usageDescription: String = "a usage of extracted declaration" ) { val size = duplicateReplacers.size if (size == 0) return if (size == 1) { duplicateReplacers.keys.first().preview(project, editor) } val answer = if (isUnitTestMode()) { Messages.YES } else { Messages.showYesNoDialog( project, KotlinBundle.message("0.has.detected.1.code.fragments.in.2.that.can.be.replaced.with.3", ApplicationNamesInfo.getInstance().productName, duplicateReplacers.size, scopeDescription, usageDescription ), KotlinBundle.message("text.process.duplicates"), Messages.getQuestionIcon() ) } if (answer != Messages.YES) { return } var showAll = false duplicateReplacersLoop@ for ((i, entry) in duplicateReplacers.entries.withIndex()) { val (pattern, replacer) = entry if (!pattern.isValid) continue val highlighter = pattern.preview(project, editor) if (!isUnitTestMode()) { if (size > 1 && !showAll) { val promptDialog = ReplacePromptDialog(false, JavaRefactoringBundle.message("process.duplicates.title", i + 1, size), project) promptDialog.show() when (promptDialog.exitCode) { FindManager.PromptResult.ALL -> showAll = true FindManager.PromptResult.SKIP -> continue@duplicateReplacersLoop FindManager.PromptResult.CANCEL -> return } } } highlighter?.let { HighlightManager.getInstance(project).removeSegmentHighlighter(editor, it) } project.executeWriteCommand(MethodDuplicatesHandler.getRefactoringName(), replacer) } } fun processDuplicatesSilently(duplicateReplacers: Map<KotlinPsiRange, () -> Unit>, project: Project) { project.executeWriteCommand(MethodDuplicatesHandler.getRefactoringName()) { duplicateReplacers.values.forEach { it() } } }
apache-2.0
5f29c6e557a000192403c3835619501c
38.947368
158
0.715572
4.807814
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/search/SearchFragment.kt
1
2440
package io.github.feelfreelinux.wykopmobilny.ui.modules.search import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.SearchView import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.base.BaseActivity import io.github.feelfreelinux.wykopmobilny.base.BaseFragment import io.github.feelfreelinux.wykopmobilny.utils.hideKeyboard import io.reactivex.subjects.PublishSubject import kotlinx.android.synthetic.main.activity_search.* class SearchFragment : BaseFragment() { companion object { fun newInstance() = SearchFragment() } val querySubject by lazy { PublishSubject.create<String>() } private lateinit var viewPagerAdapter: SearchPagerAdapter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { setHasOptionsMenu(true) return inflater.inflate(R.layout.activity_search, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewPagerAdapter = SearchPagerAdapter(resources, childFragmentManager) pager.adapter = viewPagerAdapter pager.offscreenPageLimit = 3 tabLayout.setupWithViewPager(pager) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) (activity as BaseActivity).supportActionBar?.setTitle(R.string.search) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) menu.clear() inflater.inflate(R.menu.search_menu, menu) val item = menu.findItem(R.id.action_search) item.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM or MenuItem.SHOW_AS_ACTION_WITH_TEXT) val searchView = item.actionView as SearchView val historyDb = HistorySuggestionListener(context!!, { querySubject.onNext(it) activity?.hideKeyboard() }, searchView) with(searchView) { setOnQueryTextListener(historyDb) setOnSuggestionListener(historyDb) setIconifiedByDefault(false) isIconified = false } } }
mit
5f1edf0de49ceabb4f7c71f874ec6cd2
36.553846
116
0.736885
5.010267
false
false
false
false
idea4bsd/idea4bsd
platform/script-debugger/debugger-ui/src/ScopeVariablesGroup.kt
5
4386
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.xdebugger.XDebuggerBundle import com.intellij.xdebugger.frame.XCompositeNode import com.intellij.xdebugger.frame.XValueChildrenList import com.intellij.xdebugger.frame.XValueGroup import org.jetbrains.concurrency.done import org.jetbrains.concurrency.rejected import org.jetbrains.concurrency.thenAsyncAccept class ScopeVariablesGroup(val scope: Scope, parentContext: VariableContext, callFrame: CallFrame?) : XValueGroup(scope.createScopeNodeName()) { private val context = createVariableContext(scope, parentContext, callFrame) private val callFrame = if (scope.type == Scope.Type.LOCAL) callFrame else null override fun isAutoExpand() = scope.type == Scope.Type.LOCAL || scope.type == Scope.Type.CATCH override fun getComment(): String? { val className = scope.description return if ("Object" == className) null else className } override fun computeChildren(node: XCompositeNode) { val promise = processScopeVariables(scope, node, context, callFrame == null) if (callFrame == null) { return } promise .done(node) { context.memberFilter .thenAsyncAccept(node) { if (it.hasNameMappings()) { it.sourceNameToRaw(RECEIVER_NAME)?.let { return@thenAsyncAccept callFrame.evaluateContext.evaluate(it) .done(node) { VariableImpl(RECEIVER_NAME, it.value, null) node.addChildren(XValueChildrenList.singleton(VariableView(VariableImpl(RECEIVER_NAME, it.value, null), context)), true) } } } context.viewSupport.computeReceiverVariable(context, callFrame, node) } .rejected(node) { context.viewSupport.computeReceiverVariable(context, callFrame, node) } } } } fun createAndAddScopeList(node: XCompositeNode, scopes: List<Scope>, context: VariableContext, callFrame: CallFrame?) { val list = XValueChildrenList(scopes.size) for (scope in scopes) { list.addTopGroup(ScopeVariablesGroup(scope, context, callFrame)) } node.addChildren(list, true) } fun createVariableContext(scope: Scope, parentContext: VariableContext, callFrame: CallFrame?): VariableContext { if (callFrame == null || scope.type == Scope.Type.LIBRARY) { // functions scopes - we can watch variables only from global scope return ParentlessVariableContext(parentContext, scope, scope.type == Scope.Type.GLOBAL) } else { return VariableContextWrapper(parentContext, scope) } } private class ParentlessVariableContext(parentContext: VariableContext, scope: Scope, private val watchableAsEvaluationExpression: Boolean) : VariableContextWrapper(parentContext, scope) { override fun watchableAsEvaluationExpression() = watchableAsEvaluationExpression } private fun Scope.createScopeNodeName(): String { when (type) { Scope.Type.GLOBAL -> return XDebuggerBundle.message("scope.global") Scope.Type.LOCAL -> return XDebuggerBundle.message("scope.local") Scope.Type.WITH -> return XDebuggerBundle.message("scope.with") Scope.Type.CLOSURE -> return XDebuggerBundle.message("scope.closure") Scope.Type.CATCH -> return XDebuggerBundle.message("scope.catch") Scope.Type.LIBRARY -> return XDebuggerBundle.message("scope.library") Scope.Type.INSTANCE -> return XDebuggerBundle.message("scope.instance") Scope.Type.CLASS -> return XDebuggerBundle.message("scope.class") Scope.Type.BLOCK -> return XDebuggerBundle.message("scope.block") Scope.Type.SCRIPT -> return XDebuggerBundle.message("scope.script") Scope.Type.UNKNOWN -> return XDebuggerBundle.message("scope.unknown") else -> throw IllegalArgumentException(type.name) } }
apache-2.0
08b4c3a28dfaa2e3ffe030175e4b580e
41.182692
188
0.726402
4.700965
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/utils/preferences/SettingsPreferences.kt
1
3339
package io.github.feelfreelinux.wykopmobilny.utils.preferences import android.content.Context interface SettingsPreferencesApi { var notificationsSchedulerDelay: String? var hotEntriesScreen: String? var defaultScreen: String? var linkImagePosition: String? var linkShowImage: Boolean var linkSimpleList: Boolean var linkShowAuthor: Boolean var showAdultContent: Boolean var hideNsfw: Boolean var useDarkTheme: Boolean var useAmoledTheme: Boolean var showNotifications: Boolean var piggyBackPushNotifications: Boolean var showMinifiedImages: Boolean var cutLongEntries: Boolean var cutImages: Boolean var openSpoilersDialog: Boolean var hideLowRangeAuthors: Boolean var hideContentWithoutTags: Boolean var cutImageProportion: Int var fontSize: String? var hideLinkCommentsByDefault: Boolean var hideBlacklistedViews: Boolean var enableYoutubePlayer: Boolean var enableEmbedPlayer: Boolean var useBuiltInBrowser: Boolean var groupNotifications: Boolean var disableExitConfirmation: Boolean var dialogShown: Boolean } class SettingsPreferences(context: Context) : Preferences(context, true), SettingsPreferencesApi { override var notificationsSchedulerDelay by stringPref(defaultValue = "15") override var showAdultContent by booleanPref(defaultValue = false) override var hideNsfw: Boolean by booleanPref(defaultValue = true) override var hideLowRangeAuthors: Boolean by booleanPref(defaultValue = false) override var hideContentWithoutTags: Boolean by booleanPref(defaultValue = false) override var hotEntriesScreen by stringPref(defaultValue = "newest") override var defaultScreen by stringPref(defaultValue = "mainpage") override var fontSize by stringPref(defaultValue = "normal") override var linkImagePosition by stringPref(defaultValue = "left") override var linkShowImage by booleanPref(defaultValue = true) override var linkSimpleList by booleanPref(defaultValue = false) override var linkShowAuthor by booleanPref(defaultValue = false) override var useDarkTheme by booleanPref(defaultValue = false) override var useAmoledTheme by booleanPref(defaultValue = false) override var showMinifiedImages by booleanPref(defaultValue = false) override var piggyBackPushNotifications by booleanPref(defaultValue = false) override var cutLongEntries by booleanPref(defaultValue = true) override var cutImages by booleanPref(defaultValue = true) override var cutImageProportion by intPref(defaultValue = 60) override var openSpoilersDialog by booleanPref(defaultValue = true) override var showNotifications by booleanPref(defaultValue = true) override var hideLinkCommentsByDefault by booleanPref(defaultValue = false) override var hideBlacklistedViews: Boolean by booleanPref(defaultValue = false) override var enableEmbedPlayer by booleanPref(defaultValue = true) override var enableYoutubePlayer by booleanPref(defaultValue = true) override var useBuiltInBrowser by booleanPref(defaultValue = true) override var groupNotifications by booleanPref(defaultValue = true) override var disableExitConfirmation by booleanPref(defaultValue = false) override var dialogShown by booleanPref(defaultValue = false) }
mit
e6dd91ca77f461ce1d503735523b3b33
48.117647
98
0.790356
5.200935
false
false
false
false
siosio/intellij-community
plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/asJava/fields/FirLightFieldEnumEntry.kt
2
3433
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.asJava import com.intellij.psi.* import org.jetbrains.kotlin.asJava.builder.LightMemberOrigin import org.jetbrains.kotlin.asJava.classes.* import org.jetbrains.kotlin.asJava.elements.FirLightIdentifier import org.jetbrains.kotlin.fir.declarations.FirResolvePhase import org.jetbrains.kotlin.idea.asJava.* import org.jetbrains.kotlin.idea.frontend.api.isValid import org.jetbrains.kotlin.idea.frontend.api.symbols.KtEnumEntrySymbol import org.jetbrains.kotlin.idea.util.ifTrue import org.jetbrains.kotlin.psi.KtEnumEntry internal class FirLightFieldForEnumEntry( private val enumEntrySymbol: KtEnumEntrySymbol, containingClass: FirLightClassForSymbol, override val lightMemberOrigin: LightMemberOrigin? ) : FirLightField(containingClass, lightMemberOrigin), PsiEnumConstant { private val _modifierList by lazyPub { FirLightClassModifierList( containingDeclaration = this@FirLightFieldForEnumEntry, modifiers = setOf(PsiModifier.STATIC, PsiModifier.FINAL, PsiModifier.PUBLIC), annotations = emptyList() ) } override fun getModifierList(): PsiModifierList = _modifierList override val kotlinOrigin: KtEnumEntry? = enumEntrySymbol.psi as? KtEnumEntry override fun isDeprecated(): Boolean = false //TODO Make with KtSymbols private val hasBody: Boolean get() = kotlinOrigin?.let { it.body != null } ?: true private val _initializingClass: PsiEnumConstantInitializer? by lazyPub { hasBody.ifTrue { FirLightClassForEnumEntry( enumEntrySymbol = enumEntrySymbol, enumConstant = this@FirLightFieldForEnumEntry, enumClass = containingClass, manager = manager ) } } override fun getInitializingClass(): PsiEnumConstantInitializer? = _initializingClass override fun getOrCreateInitializingClass(): PsiEnumConstantInitializer = _initializingClass ?: cannotModify() override fun getArgumentList(): PsiExpressionList? = null override fun resolveMethod(): PsiMethod? = null override fun resolveConstructor(): PsiMethod? = null override fun resolveMethodGenerics(): JavaResolveResult = JavaResolveResult.EMPTY override fun hasInitializer() = true override fun computeConstantValue(visitedVars: MutableSet<PsiVariable>?) = this override fun getName(): String = enumEntrySymbol.name.asString() private val _type: PsiType by lazyPub { enumEntrySymbol.annotatedType.asPsiType(enumEntrySymbol, this@FirLightFieldForEnumEntry, FirResolvePhase.TYPES) } override fun getType(): PsiType = _type override fun getInitializer(): PsiExpression? = null override fun hashCode(): Int = enumEntrySymbol.hashCode() private val _identifier: PsiIdentifier by lazyPub { FirLightIdentifier(this, enumEntrySymbol) } override fun getNameIdentifier(): PsiIdentifier = _identifier override fun isValid(): Boolean = super.isValid() && enumEntrySymbol.isValid() override fun equals(other: Any?): Boolean = other is FirLightFieldForEnumEntry && enumEntrySymbol == other.enumEntrySymbol }
apache-2.0
c5aba3f34df575a59f28887a1d76ac0c
37.58427
119
0.737256
5.233232
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameOnSecondaryConstructorHandler.kt
5
2129
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.rename import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.rename.RenameHandler import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils import org.jetbrains.kotlin.psi.* class RenameOnSecondaryConstructorHandler : RenameHandler { override fun isAvailableOnDataContext(dataContext: DataContext): Boolean { val editor = CommonDataKeys.EDITOR.getData(dataContext) ?: return false val file = CommonDataKeys.PSI_FILE.getData(dataContext) ?: return false val element = PsiTreeUtil.findElementOfClassAtOffsetWithStopSet( file, editor.caretModel.offset, KtSecondaryConstructor::class.java, false, KtBlockExpression::class.java, KtValueArgumentList::class.java, KtParameterList::class.java, KtConstructorDelegationCall::class.java ) return element != null } override fun isRenaming(dataContext: DataContext): Boolean = isAvailableOnDataContext(dataContext) override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext?) { CodeInsightUtils.showErrorHint( project, editor, KotlinBundle.message("text.rename.is.not.applicable.to.secondary.constructors"), RefactoringBundle.message("rename.title"), null ) } override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext?) { // Do nothing: this method is called not from editor } }
apache-2.0
8cdb416ca90d6a96bd05778ad2091d80
39.942308
158
0.72992
4.939675
false
false
false
false
apollographql/apollo-android
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/kotlin/adapter/ResponseAdapterBuilder.kt
1
983
package com.apollographql.apollo3.compiler.codegen.kotlin.adapter import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinContext import com.apollographql.apollo3.compiler.ir.IrModelGroup import com.squareup.kotlinpoet.TypeSpec interface ResponseAdapterBuilder { fun prepare() fun build(): List<TypeSpec> companion object { fun create( context: KotlinContext, modelGroup: IrModelGroup, path: List<String>, public: Boolean ): ResponseAdapterBuilder = when(modelGroup.models.size) { 0 -> error("Don't know how to create an adapter for a scalar type") 1 -> MonomorphicFieldResponseAdapterBuilder( context = context, model = modelGroup.models.first(), path = path, public = public ) else -> PolymorphicFieldResponseAdapterBuilder( context = context, modelGroup = modelGroup, path = path, public = public ) } } }
mit
0dd4707a8eb0878af1d4d24796809bc4
26.305556
73
0.661241
4.572093
false
false
false
false
stoyicker/dinger
data/src/main/kotlin/data/tinder/recommendation/RecommendationSourceModule.kt
1
2326
package data.tinder.recommendation import android.content.Context import com.nytimes.android.external.fs3.FileSystemRecordPersister import com.nytimes.android.external.fs3.filesystem.FileSystemFactory import com.nytimes.android.external.store3.base.Fetcher import com.nytimes.android.external.store3.base.impl.FluentMemoryPolicyBuilder import com.nytimes.android.external.store3.base.impl.FluentStoreBuilder.Companion.parsedWithKey import com.nytimes.android.external.store3.base.impl.StalePolicy import com.nytimes.android.external.store3.base.impl.Store import com.nytimes.android.external.store3.middleware.moshi.MoshiParserFactory import com.squareup.moshi.Moshi import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter import dagger.Module import dagger.Provides import data.crash.CrashReporterModule import data.network.ParserModule import data.tinder.TinderApi import data.tinder.TinderApiModule import okio.BufferedSource import reporter.CrashReporter import java.util.Date import java.util.concurrent.TimeUnit import javax.inject.Singleton import dagger.Lazy as DaggerLazy @Module(includes = [ ParserModule::class, TinderApiModule::class, CrashReporterModule::class]) internal class RecommendationSourceModule { @Provides @Singleton fun store(context: Context, moshiBuilder: Moshi.Builder, api: TinderApi) = parsedWithKey<Unit, BufferedSource, RecommendationResponse>( Fetcher { fetch(api) }) { parsers = listOf(MoshiParserFactory.createSourceParser(moshiBuilder .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe()) .build(), RecommendationResponse::class.java)) persister = FileSystemRecordPersister.create( FileSystemFactory.create(context.externalCacheDir!!), { it.toString() }, 7, TimeUnit.DAYS) memoryPolicy = FluentMemoryPolicyBuilder.build { expireAfterWrite = 30 expireAfterTimeUnit = TimeUnit.MINUTES } stalePolicy = StalePolicy.NETWORK_BEFORE_STALE } @Provides @Singleton fun source(store: DaggerLazy<Store<RecommendationResponse, Unit>>, crashReporter: CrashReporter) = GetRecommendationSource(store, crashReporter) private fun fetch(api: TinderApi) = api.getRecommendations().map { it.source() } }
mit
d587fa7f7f17f6fc53a61b1b68fc387b
39.807018
95
0.769132
4.481696
false
false
false
false
SimpleMobileTools/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/extensions/List.kt
1
633
package com.simplemobiletools.commons.extensions import java.util.* fun List<String>.getMimeType(): String { val mimeGroups = HashSet<String>(size) val subtypes = HashSet<String>(size) forEach { val parts = it.getMimeType().split("/") if (parts.size == 2) { mimeGroups.add(parts.getOrElse(0) { "" }) subtypes.add(parts.getOrElse(1) { "" }) } else { return "*/*" } } return when { subtypes.size == 1 -> "${mimeGroups.first()}/${subtypes.first()}" mimeGroups.size == 1 -> "${mimeGroups.first()}/*" else -> "*/*" } }
gpl-3.0
0756b98971d36bcffd3c02d2e1bae8fe
26.521739
73
0.537125
4.083871
false
false
false
false
GunoH/intellij-community
plugins/kotlin/fir/testData/quickDoc/EscapeHtmlInsideCodeBlocks.kt
4
628
/** * Code block: * ``` kotlin * A<T> * ``` * Code span: * `<T>` is type parameter */ class <caret>A<T> //INFO: <div class='definition'><pre>class A&lt;T&gt;</pre></div><div class='content'><p style='margin-top:0;padding-top:0;'>Code block:</p> //INFO: <pre><code style='font-size:96%;'> //INFO: <span style=""><span style="">A&lt;T&gt;</span></span> //INFO: </code></pre><p>Code span: <code style='font-size:96%;'><span style=""><span style="">&lt;T&gt;</span></span></code> is type parameter</p></div><table class='sections'></table><div class='bottom'><icon src="file"/>&nbsp;EscapeHtmlInsideCodeBlocks.kt<br/></div>
apache-2.0
75593eab96320044adb752401b7965bd
43.857143
268
0.616242
2.880734
false
false
false
false
GunoH/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/ProjectDataProvider.kt
2
6094
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models import com.jetbrains.packagesearch.intellij.plugin.util.CoroutineLRUCache import com.jetbrains.packagesearch.intellij.plugin.util.TraceInfo import com.jetbrains.packagesearch.intellij.plugin.util.logDebug import com.jetbrains.packagesearch.intellij.plugin.util.logInfo import com.jetbrains.packagesearch.intellij.plugin.util.logTrace import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.buffer import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.toList import org.jetbrains.idea.packagesearch.api.PackageSearchApiClient import org.jetbrains.packagesearch.api.v2.ApiPackagesResponse import org.jetbrains.packagesearch.api.v2.ApiRepository import org.jetbrains.packagesearch.api.v2.ApiStandardPackage internal class ProjectDataProvider( private val apiClient: PackageSearchApiClient, private val packageCache: CoroutineLRUCache<InstalledDependency, ApiStandardPackage> ) { suspend fun fetchKnownRepositories(): List<ApiRepository> = apiClient.repositories().repositories suspend fun doSearch( searchQuery: String, filterOptions: FilterOptions ): ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion> { val repositoryIds = filterOptions.onlyRepositoryIds return apiClient.packagesByQuery( searchQuery = searchQuery, onlyStable = filterOptions.onlyStable, onlyMpp = filterOptions.onlyKotlinMultiplatform, repositoryIds = repositoryIds.toList() ) } suspend fun fetchInfoFor(installedDependencies: List<InstalledDependency>, traceInfo: TraceInfo): Map<InstalledDependency, ApiStandardPackage> { if (installedDependencies.isEmpty()) { return emptyMap() } val apiInfoByDependency = fetchInfoFromCacheOrApiFor(installedDependencies, traceInfo) val (emptyApiInfoByDependency, successfulApiInfoByDependency) = apiInfoByDependency.partition { (_, v) -> v == null } if (emptyApiInfoByDependency.isNotEmpty() && emptyApiInfoByDependency.size != installedDependencies.size) { val failedDependencies = emptyApiInfoByDependency.keys logInfo(traceInfo, "ProjectDataProvider#fetchInfoFor()") { "Failed obtaining data for ${failedDependencies.size} dependencies" } } return successfulApiInfoByDependency.filterNotNullValues() } private suspend fun fetchInfoFromCacheOrApiFor( dependencies: List<InstalledDependency>, traceInfo: TraceInfo ): Map<InstalledDependency, ApiStandardPackage?> { logDebug(traceInfo, "ProjectDataProvider#fetchInfoFromCacheOrApiFor()") { "Fetching data for ${dependencies.count()} dependencies..." } val remoteInfoByDependencyMap = mutableMapOf<InstalledDependency, ApiStandardPackage?>() val packagesToFetch = mutableListOf<InstalledDependency>() for (dependency in dependencies) { val standardV2Package = packageCache.get(dependency) remoteInfoByDependencyMap[dependency] = standardV2Package if (standardV2Package == null) { packagesToFetch += dependency } } if (packagesToFetch.isEmpty()) { logTrace(traceInfo, "ProjectDataProvider#fetchInfoFromCacheOrApiFor()") { "Found all ${dependencies.count() - packagesToFetch.count()} packages in cache" } return remoteInfoByDependencyMap } packagesToFetch.asSequence() .map { dependency -> dependency.coordinatesString } .distinct() .sorted() .also { logTrace(traceInfo, "ProjectDataProvider#fetchInfoFromCacheOrApiFor()") { "Found ${dependencies.count() - packagesToFetch.count()} packages in cache, still need to fetch ${it.count()} from API" } } .chunked(size = 25) .asFlow() .buffer(25) .map { dependenciesToFetch -> apiClient.packagesByRange(dependenciesToFetch).packages } .catch { logDebug( "${this::class.run { qualifiedName ?: simpleName ?: this }}#fetchedPackages", it, ) { "Error while retrieving packages" } emit(emptyList()) } .toList() .flatten() .forEach { v2Package -> val dependency = InstalledDependency.from(v2Package) packageCache.put(dependency, v2Package) remoteInfoByDependencyMap[dependency] = v2Package } return remoteInfoByDependencyMap } } private fun <K, V> Map<K, V>.partition(transform: (Map.Entry<K, V>) -> Boolean): Pair<Map<K, V>, Map<K, V>> { val trueMap = mutableMapOf<K, V>() val falseMap = mutableMapOf<K, V>() forEach { if (transform(it)) trueMap[it.key] = it.value else falseMap[it.key] = it.value } return trueMap to falseMap } private fun <K, V> Map<K, V?>.filterNotNullValues() = buildMap<K, V> { [email protected] { (k, v) -> if (v != null) put(k, v) } }
apache-2.0
f6830759a946fe118d4d6348e4a30dd9
41.915493
148
0.661963
5.181973
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/ide/wizard/NewEmptyProjectBuilder.kt
1
1633
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.wizard import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.ide.wizard.util.CommentNewProjectWizardStep import com.intellij.openapi.module.GeneralModuleType import com.intellij.openapi.module.ModuleTypeManager import com.intellij.openapi.project.Project import com.intellij.ui.UIBundle import com.intellij.util.ui.EmptyIcon import javax.swing.Icon class NewEmptyProjectBuilder : AbstractNewProjectWizardBuilder() { override fun getPresentableName() = UIBundle.message("label.project.wizard.empty.project.generator.name") override fun getDescription() = UIBundle.message("label.project.wizard.empty.project.generator.description") override fun getNodeIcon(): Icon = EmptyIcon.ICON_0 override fun createStep(context: WizardContext) = RootNewProjectWizardStep(context).chain( ::CommentStep, ::newProjectWizardBaseStepWithoutGap, ::GitNewProjectWizardStep, ::Step ) private class CommentStep(parent: NewProjectWizardStep) : CommentNewProjectWizardStep(parent) { override val comment: String = UIBundle.message("label.project.wizard.empty.project.generator.full.description") } private class Step(parent: NewProjectWizardStep) : AbstractNewProjectWizardStep(parent) { override fun setupProject(project: Project) { val moduleType = ModuleTypeManager.getInstance().findByID(GeneralModuleType.TYPE_ID) moduleType.createModuleBuilder().commit(project) } } }
apache-2.0
457a801937eb02f1da80b80a56edcb02
44.388889
158
0.792407
4.561453
false
false
false
false
jwren/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/EditSourceFromChangesBrowserAction.kt
4
1915
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.committed import com.intellij.icons.AllIcons import com.intellij.ide.actions.EditSourceAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys.PROJECT import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsDataKeys.SELECTED_CHANGES import com.intellij.openapi.vcs.changes.ChangesUtil.getFiles import com.intellij.openapi.vcs.changes.ChangesUtil.getNavigatableArray import com.intellij.openapi.vcs.changes.committed.CommittedChangesBrowserUseCase.IN_AIR import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase import com.intellij.pom.Navigatable import com.intellij.util.containers.stream internal class EditSourceFromChangesBrowserAction : EditSourceAction() { override fun update(e: AnActionEvent) { super.update(e) e.presentation.apply { icon = AllIcons.Actions.EditSource text = VcsBundle.message("edit.source.action.text") val isModalContext = e.getData(PlatformCoreDataKeys.IS_MODAL_CONTEXT) == true val changesBrowser = e.getData(ChangesBrowserBase.DATA_KEY) isVisible = isVisible && changesBrowser != null isEnabled = isEnabled && changesBrowser != null && !isModalContext && e.getData(CommittedChangesBrowserUseCase.DATA_KEY) != IN_AIR } } override fun getNavigatables(dataContext: DataContext): Array<Navigatable>? { val project = PROJECT.getData(dataContext) ?: return null val changes = SELECTED_CHANGES.getData(dataContext) ?: return null return getNavigatableArray(project, getFiles(changes.stream())) } }
apache-2.0
e643ea1e61eea85d0b10b00f29167b6f
44.619048
140
0.781723
4.484778
false
false
false
false
yuzumone/SDNMonitor
app/src/main/kotlin/net/yuzumone/sdnmonitor/fragment/StatusFragment.kt
1
3323
/* * Copyright (C) 2016 yuzumone * * 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.yuzumone.sdnmonitor.fragment 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 net.yuzumone.sdnmonitor.R import net.yuzumone.sdnmonitor.api.MonitorClient import net.yuzumone.sdnmonitor.databinding.FragmentStatusBinding import net.yuzumone.sdnmonitor.util.OnToggleElevationListener import net.yuzumone.sdnmonitor.widget.StatusArrayAdapter import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import rx.subscriptions.CompositeSubscription import javax.inject.Inject class StatusFragment : BaseFragment() { private lateinit var binding: FragmentStatusBinding private lateinit var adapter: StatusArrayAdapter private lateinit var listener: OnToggleElevationListener @Inject lateinit var monitorClient: MonitorClient @Inject lateinit var compositeSubscription: CompositeSubscription override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentStatusBinding.inflate(inflater, container, false) initView() compositeSubscription.add(fetchSwitches()) return binding.root } override fun onAttach(context: Context?) { super.onAttach(context) getComponent().inject(this) if (context is OnToggleElevationListener) { listener = context } } fun initView() { listener.onToggleElevation(true) adapter = StatusArrayAdapter(activity) binding.listStatus.adapter = adapter binding.swipeRefresh.setColorSchemeResources(R.color.colorPrimary) binding.swipeRefresh.setOnRefreshListener { compositeSubscription.clear() compositeSubscription.add(fetchSwitches()) } } fun fetchSwitches(): Subscription { return monitorClient.getStatuses() .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .doOnCompleted { binding.swipeRefresh.isRefreshing = false } .subscribe ( { response -> adapter.clear() adapter.addAll(response) adapter.notifyDataSetChanged() }, { error -> Toast.makeText(activity, error.message, Toast.LENGTH_SHORT).show() } ) } override fun onDestroy() { compositeSubscription.unsubscribe() super.onDestroy() } }
apache-2.0
c256a959b1931a6e62300324570a72cc
34.361702
117
0.681613
5.167963
false
false
false
false
smmribeiro/intellij-community
platform/ide-core/src/com/intellij/ui/SpinningProgressIcon.kt
7
3680
// 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.ui import com.intellij.ui.scale.DerivedScaleType import com.intellij.ui.scale.ScaleContext import com.intellij.util.IconUtil import com.intellij.util.SVGLoader import com.intellij.util.ui.JBUI import org.jetbrains.annotations.ApiStatus.Internal import java.awt.Color import java.awt.Component import java.awt.Graphics import java.awt.image.BufferedImage import javax.swing.Icon /** * Internal utility class for generating loading icons on the fly. * Generated icons are UI theme aware and can change base color using * <code>ProgressIcon.color</code> UI key. * * @see com.intellij.util.ui.AsyncProcessIcon * @see AnimatedIcon * @author Konstantin Bulenkov */ @Internal open class SpinningProgressIcon: AnimatedIcon() { open val opacities get() = arrayOf(1.0, 0.875, 0.75, 0.625, 0.5, 0.375, 0.25, 0.125) open val paths get() = arrayOf("M8 2V4.5", "M3.75739 3.75739L5.52515 5.52515", "M2.0011 7.99738H4.5011", "M3.75848 12.2401L5.52625 10.4723", "M8.00214 13.998V11.498", "M12.2414 12.2404L10.4736 10.4727", "M13.9981 7.99921H11.4981", "M12.2426 3.75739L10.4748 5.52515") open val size get() = 16 private var iconColor: Color = JBColor.namedColor("ProgressIcon.color", JBColor(0x767A8A, 0xCED0D6)) fun getCacheKey() = ColorUtil.toHex(iconColor) val iconCache = arrayOfNulls<Icon>(paths.size) var iconCacheKey = "" override fun createFrames() = Array(paths.size) { createFrame(it) } fun setIconColor(color: Color) { iconColor = color } fun getIconColor() = iconColor fun createFrame(i: Int): Frame { return object : Frame { override fun getIcon() = CashedDelegateIcon(i) override fun getDelay() = JBUI.getInt("ProgressIcon.delay", 125) } } inner class CashedDelegateIcon(val index: Int): Icon { private fun getDelegate() = getIconFromCache(index) override fun paintIcon(c: Component?, g: Graphics?, x: Int, y: Int) = getDelegate().paintIcon(c, g, x, y) override fun getIconWidth() = getDelegate().iconWidth override fun getIconHeight() = getDelegate().iconHeight } private fun getIconFromCache(i: Int): Icon { val icon = iconCache[i] if (icon != null && iconCacheKey == getCacheKey()) { return icon } iconCache.forEachIndexed { index, _ -> run { val svg = generateSvgIcon(index) val scaleContext = ScaleContext.create() val image = SVGLoader.load(svg.byteInputStream(), scaleContext.getScale(DerivedScaleType.PIX_SCALE).toFloat()) iconCache[index] = IconUtil.toRetinaAwareIcon(image as BufferedImage) } } iconCacheKey = getCacheKey() return iconCache[i]!! } private fun generateSvgIcon(index: Int): String { val stroke = getCacheKey() var s = """<svg width="$size" height="$size" viewBox="0 0 $size $size" fill="none" xmlns="http://www.w3.org/2000/svg">""".plus("\n") for (n in paths.indices) { val opacity = opacities[(n + index) % opacities.size] s += """ <path opacity="$opacity" d="${paths[n]}" stroke="#$stroke" stroke-width="1.6" stroke-linecap="round"/>""".plus("\n") } s += "</svg>" return s } } //fun main() { // val svgIcon = generateSvgIcon(0) // println(svgIcon) // @Suppress("SSBasedInspection") // val tmpFile = File.createTempFile("krutilka", ".svg").also { // it.writeText(svgIcon) // it.deleteOnExit() // } // Desktop.getDesktop().open(tmpFile) //}
apache-2.0
1fb6702c061ed8738ed00d9772448cb2
34.057143
136
0.660598
3.498099
false
false
false
false
GlobalTechnology/android-gto-support
gto-support-androidx-lifecycle/src/main/kotlin/org/ccci/gto/android/common/androidx/lifecycle/SavedStateHandle+Delegates.kt
1
1336
package org.ccci.gto.android.common.androidx.lifecycle import androidx.lifecycle.MutableLiveData import androidx.lifecycle.SavedStateHandle import kotlin.properties.ReadOnlyProperty import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow fun <T> SavedStateHandle.delegate(key: String? = null) = object : ReadWriteProperty<Any, T?> { override fun getValue(thisRef: Any, property: KProperty<*>): T? = get(key ?: property.name) override fun setValue(thisRef: Any, property: KProperty<*>, value: T?) = set(key ?: property.name, value) } fun <T : Any> SavedStateHandle.delegate(key: String? = null, ifNull: T) = object : ReadWriteProperty<Any, T> { override fun getValue(thisRef: Any, property: KProperty<*>): T = get(key ?: property.name) ?: ifNull override fun setValue(thisRef: Any, property: KProperty<*>, value: T) = set(key ?: property.name, value) } fun <T> SavedStateHandle.livedata(key: String? = null) = ReadOnlyProperty<Any, MutableLiveData<T>> { _, property -> getLiveData(key ?: property.name) } fun <T> SavedStateHandle.livedata(key: String? = null, initialValue: T) = ReadOnlyProperty<Any, MutableLiveData<T>> { _, property -> getLiveData(key ?: property.name, initialValue) }
mit
3214ad46d168f42789b2df442a243112
46.714286
115
0.738024
4.085627
false
false
false
false
MartinStyk/AndroidApkAnalyzer
app/src/main/java/sk/styk/martin/apkanalyzer/ui/permission/list/PermissionListAdapter.kt
1
2742
package sk.styk.martin.apkanalyzer.ui.permission.list import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.LiveData import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import sk.styk.martin.apkanalyzer.databinding.ListItemPermissionLocalDataBinding import sk.styk.martin.apkanalyzer.model.permissions.LocalPermissionData import sk.styk.martin.apkanalyzer.util.live.SingleLiveEvent import java.lang.ref.WeakReference import javax.inject.Inject class PermissionListAdapter @Inject constructor() : RecyclerView.Adapter<PermissionListAdapter.ViewHolder>() { private val openPermissionEvent = SingleLiveEvent<PermissionClickData>() val openPermission: LiveData<PermissionClickData> = openPermissionEvent var permissions = emptyList<LocalPermissionData>() set(value) { val diffResult = DiffUtil.calculateDiff(PermissionDiffCallback(value, field)) field = value diffResult.dispatchUpdatesTo(this) } override fun getItemCount(): Int = permissions.size override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = ListItemPermissionLocalDataBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.update(PermissionItemViewModel(permissions[position])) } inner class PermissionItemViewModel(val permissionData: LocalPermissionData) { fun onClick(view: View) { openPermissionEvent.value = PermissionClickData(WeakReference(view), permissionData) } } inner class ViewHolder(private val binding: ListItemPermissionLocalDataBinding) : RecyclerView.ViewHolder(binding.root) { fun update(viewModel: PermissionItemViewModel) { binding.viewModel = viewModel } } private inner class PermissionDiffCallback(private val newList: List<LocalPermissionData>, private val oldList: List<LocalPermissionData>) : DiffUtil.Callback() { override fun getOldListSize() = oldList.size override fun getNewListSize() = newList.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) = oldList[oldItemPosition].permissionData.name == newList[newItemPosition].permissionData.name override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) = oldList[oldItemPosition] == newList[newItemPosition] } data class PermissionClickData(val view: WeakReference<View>, val localPermissionData: LocalPermissionData) }
gpl-3.0
ae9f9736c566890f5e6a1c2a4b056cd0
45.491525
175
0.754923
5.273077
false
false
false
false
AMARJITVS/NoteDirector
app/src/main/kotlin/com/amar/notesapp/adapters/DirectoryAdapter.kt
1
15754
package com.amar.NoteDirector.adapters import android.graphics.PorterDuff import android.os.Build import android.support.v7.view.ActionMode import android.support.v7.widget.RecyclerView import android.util.SparseArray import android.view.* import com.bignerdranch.android.multiselector.ModalMultiSelectorCallback import com.bignerdranch.android.multiselector.MultiSelector import com.bignerdranch.android.multiselector.SwappingHolder import com.bumptech.glide.Glide import com.google.gson.Gson import com.simplemobiletools.commons.dialogs.ConfirmationDialog import com.simplemobiletools.commons.dialogs.PropertiesDialog import com.simplemobiletools.commons.dialogs.RenameItemDialog import com.simplemobiletools.commons.extensions.* import com.amar.NoteDirector.activities.SimpleActivity import com.amar.NoteDirector.dialogs.ExcludeFolderDialog import com.amar.NoteDirector.dialogs.PickMediumDialog import com.amar.NoteDirector.extensions.* import com.amar.NoteDirector.models.AlbumCover import com.amar.NoteDirector.models.Directory import kotlinx.android.synthetic.main.directory_item.view.* import java.io.File import java.util.* class DirectoryAdapter(val activity: SimpleActivity, var dirs: MutableList<Directory>, val listener: DirOperationsListener?, val isPickIntent: Boolean, val itemClick: (Directory) -> Unit) : RecyclerView.Adapter<DirectoryAdapter.ViewHolder>() { val multiSelector = MultiSelector() val config = activity.config var actMode: ActionMode? = null var itemViews = SparseArray<View>() val selectedPositions = HashSet<Int>() var primaryColor = config.primaryColor var pinnedFolders = config.pinnedFolders var scrollVertically = !config.scrollHorizontally fun toggleItemSelection(select: Boolean, pos: Int) { if (select) { itemViews[pos]?.dir_check?.background?.setColorFilter(primaryColor, PorterDuff.Mode.SRC_IN) selectedPositions.add(pos) } else selectedPositions.remove(pos) itemViews[pos]?.dir_check?.beVisibleIf(select) if (selectedPositions.isEmpty()) { actMode?.finish() return } updateTitle(selectedPositions.size) } fun updateTitle(cnt: Int) { actMode?.title = "$cnt / ${dirs.size}" actMode?.invalidate() } val adapterListener = object : MyAdapterListener { override fun toggleItemSelectionAdapter(select: Boolean, position: Int) { toggleItemSelection(select, position) } override fun getSelectedPositions(): HashSet<Int> = selectedPositions } val multiSelectorMode = object : ModalMultiSelectorCallback(multiSelector) { override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { when (item.itemId) { com.amar.NoteDirector.R.id.cab_properties -> showProperties() com.amar.NoteDirector.R.id.cab_rename -> renameDir() com.amar.NoteDirector.R.id.cab_pin -> pinFolders(true) com.amar.NoteDirector.R.id.cab_unpin -> pinFolders(false) com.amar.NoteDirector.R.id.cab_copy_to -> copyMoveTo(true) com.amar.NoteDirector.R.id.cab_move_to -> copyMoveTo(false) com.amar.NoteDirector.R.id.cab_select_all -> selectAll() com.amar.NoteDirector.R.id.cab_delete -> askConfirmDelete() com.amar.NoteDirector.R.id.cab_select_photo -> changeAlbumCover(false) com.amar.NoteDirector.R.id.cab_use_default -> changeAlbumCover(true) else -> return false } return true } override fun onCreateActionMode(actionMode: ActionMode?, menu: Menu?): Boolean { super.onCreateActionMode(actionMode, menu) actMode = actionMode activity.menuInflater.inflate(com.amar.NoteDirector.R.menu.cab_directories, menu) return true } override fun onPrepareActionMode(actionMode: ActionMode?, menu: Menu): Boolean { menu.findItem(com.amar.NoteDirector.R.id.cab_rename).isVisible = selectedPositions.size <= 1 menu.findItem(com.amar.NoteDirector.R.id.cab_change_cover_image).isVisible = selectedPositions.size <= 1 checkHideBtnVisibility() checkPinBtnVisibility(menu) return true } override fun onDestroyActionMode(actionMode: ActionMode?) { super.onDestroyActionMode(actionMode) selectedPositions.forEach { itemViews[it]?.dir_check?.beGone() } selectedPositions.clear() actMode = null } fun checkHideBtnVisibility() { var hiddenCnt = 0 var unhiddenCnt = 0 selectedPositions.map { dirs.getOrNull(it)?.path }.filterNotNull().forEach { if (File(it).containsNoMedia()) hiddenCnt++ else unhiddenCnt++ } } fun checkPinBtnVisibility(menu: Menu) { val pinnedFolders = config.pinnedFolders var pinnedCnt = 0 var unpinnedCnt = 0 selectedPositions.map { dirs.getOrNull(it)?.path }.filterNotNull().forEach { if (pinnedFolders.contains(it)) pinnedCnt++ else unpinnedCnt++ } menu.findItem(com.amar.NoteDirector.R.id.cab_pin).isVisible = unpinnedCnt > 0 menu.findItem(com.amar.NoteDirector.R.id.cab_unpin).isVisible = pinnedCnt > 0 } } private fun showProperties() { if (selectedPositions.size <= 1) { PropertiesDialog(activity, dirs[selectedPositions.first()].path, config.shouldShowHidden) } else { val paths = ArrayList<String>() selectedPositions.forEach { paths.add(dirs[it].path) } PropertiesDialog(activity, paths, config.shouldShowHidden) } } private fun renameDir() { val path = dirs[selectedPositions.first()].path val dir = File(path) if (activity.isAStorageRootFolder(dir.absolutePath)) { activity.toast(com.amar.NoteDirector.R.string.rename_folder_root) return } RenameItemDialog(activity, dir.absolutePath) { activity.runOnUiThread { listener?.refreshItems() actMode?.finish() } } } private fun toggleFoldersVisibility(hide: Boolean) { getSelectedPaths().forEach { if (hide) { if (config.wasHideFolderTooltipShown) { hideFolder(it) } else { config.wasHideFolderTooltipShown = true ConfirmationDialog(activity, activity.getString(com.amar.NoteDirector.R.string.hide_folder_description)) { hideFolder(it) } } } else { activity.removeNoMedia(it) { noMediaHandled() } } } } private fun hideFolder(path: String) { activity.addNoMedia(path) { noMediaHandled() } } private fun tryExcludeFolder() { ExcludeFolderDialog(activity, getSelectedPaths().toList()) { listener?.refreshItems() actMode?.finish() } } private fun noMediaHandled() { activity.runOnUiThread { listener?.refreshItems() actMode?.finish() } } private fun pinFolders(pin: Boolean) { if (pin) config.addPinnedFolders(getSelectedPaths()) else config.removePinnedFolders(getSelectedPaths()) pinnedFolders = config.pinnedFolders listener?.refreshItems() notifyDataSetChanged() actMode?.finish() } private fun copyMoveTo(isCopyOperation: Boolean) { if (selectedPositions.isEmpty()) return val files = ArrayList<File>() selectedPositions.forEach { val dir = File(dirs[it].path) files.addAll(dir.listFiles().filter { it.isFile && it.isImageVideoGif() }) } activity.tryCopyMoveFilesTo(files, isCopyOperation) { config.tempFolderPath = "" listener?.refreshItems() actMode?.finish() } } fun selectAll() { val cnt = dirs.size for (i in 0..cnt - 1) { selectedPositions.add(i) notifyItemChanged(i) } updateTitle(cnt) } private fun askConfirmDelete() { ConfirmationDialog(activity) { deleteFiles() actMode?.finish() } } private fun deleteFiles() { val folders = ArrayList<File>(selectedPositions.size) val removeFolders = ArrayList<Directory>(selectedPositions.size) var needPermissionForPath = "" selectedPositions.forEach { if (dirs.size > it) { val path = dirs[it].path if (activity.needsStupidWritePermissions(path) && config.treeUri.isEmpty()) { needPermissionForPath = path } } } activity.handleSAFDialog(File(needPermissionForPath)) { selectedPositions.sortedDescending().forEach { if (dirs.size > it) { val directory = dirs[it] folders.add(File(directory.path)) removeFolders.add(directory) notifyItemRemoved(it) itemViews.put(it, null) } } dirs.removeAll(removeFolders) selectedPositions.clear() listener?.tryDeleteFolders(folders) val newItems = SparseArray<View>() var curIndex = 0 for (i in 0..itemViews.size() - 1) { if (itemViews[i] != null) { newItems.put(curIndex, itemViews[i]) curIndex++ } } itemViews = newItems } } private fun changeAlbumCover(useDefault: Boolean) { if (selectedPositions.size != 1) return val path = dirs[selectedPositions.first()].path var albumCovers = config.parseAlbumCovers() if (useDefault) { albumCovers = albumCovers.filterNot { it.path == path } as ArrayList storeCovers(albumCovers) } else { PickMediumDialog(activity, path) { albumCovers = albumCovers.filterNot { it.path == path } as ArrayList albumCovers.add(AlbumCover(path, it)) storeCovers(albumCovers) } } } private fun storeCovers(albumCovers: ArrayList<AlbumCover>) { activity.config.albumCovers = Gson().toJson(albumCovers) actMode?.finish() listener?.refreshItems() } private fun getSelectedPaths(): HashSet<String> { val paths = HashSet<String>(selectedPositions.size) selectedPositions.forEach { paths.add(dirs[it].path) } return paths } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent?.context).inflate(com.amar.NoteDirector.R.layout.directory_item, parent, false) return ViewHolder(view, adapterListener, activity, multiSelectorMode, multiSelector, listener, isPickIntent, itemClick) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val dir = dirs[position] itemViews.put(position, holder.bindView(dir, pinnedFolders.contains(dir.path), scrollVertically)) toggleItemSelection(selectedPositions.contains(position), position) holder.itemView.tag = holder } override fun onViewRecycled(holder: ViewHolder?) { super.onViewRecycled(holder) holder?.stopLoad() } override fun getItemCount() = dirs.size fun updateDirs(newDirs: ArrayList<Directory>) { dirs = newDirs notifyDataSetChanged() } fun selectItem(pos: Int) { toggleItemSelection(true, pos) } fun selectRange(from: Int, to: Int, min: Int, max: Int) { if (from == to) { (min..max).filter { it != from } .forEach { toggleItemSelection(false, it) } return } if (to < from) { for (i in to..from) toggleItemSelection(true, i) if (min > -1 && min < to) { (min until to).filter { it != from } .forEach { toggleItemSelection(false, it) } } if (max > -1) { for (i in from + 1..max) toggleItemSelection(false, i) } } else { for (i in from..to) toggleItemSelection(true, i) if (max > -1 && max > to) { (to + 1..max).filter { it != from } .forEach { toggleItemSelection(false, it) } } if (min > -1) { for (i in min until from) toggleItemSelection(false, i) } } } class ViewHolder(val view: View, val adapterListener: MyAdapterListener, val activity: SimpleActivity, val multiSelectorCallback: ModalMultiSelectorCallback, val multiSelector: MultiSelector, val listener: DirOperationsListener?, val isPickIntent: Boolean, val itemClick: (Directory) -> (Unit)) : SwappingHolder(view, MultiSelector()) { fun bindView(directory: Directory, isPinned: Boolean, scrollVertically: Boolean): View { itemView.apply { dir_name.text = directory.name photo_cnt.text = directory.mediaCnt.toString() activity.loadImage(directory.tmb, dir_thumbnail, scrollVertically) dir_pin.beVisibleIf(isPinned) dir_sd_card.beVisibleIf(activity.isPathOnSD(directory.path)) setOnClickListener { viewClicked(directory) } setOnLongClickListener { if (isPickIntent) viewClicked(directory) else viewLongClicked(); true } } return itemView } private fun viewClicked(directory: Directory) { if (multiSelector.isSelectable) { val isSelected = adapterListener.getSelectedPositions().contains(layoutPosition) adapterListener.toggleItemSelectionAdapter(!isSelected, layoutPosition) } else { itemClick(directory) } } private fun viewLongClicked() { if (listener != null) { if (!multiSelector.isSelectable) { activity.startSupportActionMode(multiSelectorCallback) adapterListener.toggleItemSelectionAdapter(true, layoutPosition) } listener.itemLongClicked(layoutPosition) } } fun stopLoad() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed) return Glide.with(activity).clear(view.dir_thumbnail) } } interface MyAdapterListener { fun toggleItemSelectionAdapter(select: Boolean, position: Int) fun getSelectedPositions(): HashSet<Int> } interface DirOperationsListener { fun refreshItems() fun tryDeleteFolders(folders: ArrayList<File>) fun itemLongClicked(position: Int) } }
apache-2.0
5962d58f939f652a5382db487bb6e040
34.165179
161
0.59623
4.977567
false
false
false
false
drmashu/koshop
src/main/kotlin/io/github/drmashu/koshop/action/manage/ManageAccountListAction.kt
1
1381
package io.github.drmashu.koshop.action.manage import com.warrenstrange.googleauth.GoogleAuthenticator import com.warrenstrange.googleauth.GoogleAuthenticatorQRGenerator import io.github.drmashu.buri.HtmlAction import io.github.drmashu.dikon.inject import io.github.drmashu.koshop.dao.AccountDao import io.github.drmashu.koshop.dao.getNextId import io.github.drmashu.koshop.model.Account import io.github.drmashu.koshop.model.Totp import org.seasar.doma.jdbc.Config import javax.servlet.ServletContext import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse /** * Created by drmashu on 2015/10/24. */ class ManageAccountListAction(context: ServletContext, request: HttpServletRequest, response: HttpServletResponse, @inject("doma_config") val domaConfig: Config, val accountDao: AccountDao): HtmlAction(context, request, response) { val defaultAccount = Account() init { defaultAccount.id = 0 defaultAccount.name = "" defaultAccount.mail = "" defaultAccount.gauth = true } override fun get() { logger.entry() domaConfig.transactionManager.required { val accountList = accountDao.selectAll() responseFromTemplate("/manage/account_list", arrayOf(object { val accountList = accountList })) } logger.exit() } }
apache-2.0
83eaec6d9574e31a9474aedb3abc7624
36.351351
231
0.735699
4.28882
false
true
false
false
breadwallet/breadwallet-android
ui/ui-gift/src/main/java/CreateGiftHandler.kt
1
10052
/** * BreadWallet * * Created by Drew Carlson <[email protected]> on 12/1/20. * Copyright (c) 2020 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.ui.uigift import android.security.keystore.UserNotAuthenticatedException import android.text.format.DateUtils import android.util.Base64 import com.breadwallet.breadbox.BreadBox import com.breadwallet.breadbox.addressFor import com.breadwallet.breadbox.createExportablePaperWallet import com.breadwallet.breadbox.hashString import com.breadwallet.breadbox.defaultUnit import com.breadwallet.breadbox.estimateFee import com.breadwallet.breadbox.estimateMaximum import com.breadwallet.breadbox.feeForSpeed import com.breadwallet.breadbox.getSize import com.breadwallet.breadbox.toBigDecimal import com.breadwallet.crypto.Amount import com.breadwallet.crypto.TransferState import com.breadwallet.crypto.errors.ExportablePaperWalletError import com.breadwallet.crypto.errors.FeeEstimationError import com.breadwallet.crypto.errors.FeeEstimationInsufficientFundsError import com.breadwallet.crypto.errors.LimitEstimationError import com.breadwallet.crypto.errors.LimitEstimationInsufficientFundsError import com.breadwallet.crypto.errors.TransferSubmitError import com.breadwallet.logger.logDebug import com.breadwallet.logger.logError import com.breadwallet.platform.entities.GiftMetaData import com.breadwallet.platform.entities.TxMetaDataValue import com.breadwallet.platform.interfaces.AccountMetaDataProvider import com.breadwallet.repository.RatesRepository import com.breadwallet.tools.manager.BRSharedPrefs import com.breadwallet.tools.security.BrdUserManager import com.breadwallet.tools.util.EventUtils import com.breadwallet.ui.uigift.CreateGift.E import com.breadwallet.ui.uigift.CreateGift.F import com.breadwallet.ui.uigift.CreateGift.PaperWalletError import com.breadwallet.ui.uigift.CreateGift.MaxEstimateError import com.breadwallet.ui.uigift.CreateGift.FeeEstimateError import drewcarlson.mobius.flow.subtypeEffectHandler import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.withContext private const val GIFT_BASE_URL = "https://brd.com/x/gift" fun createCreateGiftingHandler( currencyId: String, breadBox: BreadBox, userManager: BrdUserManager, rates: RatesRepository, giftBackup: GiftBackup, metaDataManager: AccountMetaDataProvider ) = subtypeEffectHandler<F, E> { addFunction<F.CreatePaperWallet> { val wallet = breadBox.wallet(currencyId).first() try { val exportableWallet = wallet.walletManager.createExportablePaperWallet() val privateKey = checkNotNull(exportableWallet.key.orNull()).encodeAsPrivate() val address = checkNotNull(exportableWallet.address.orNull()).toString() val encodedPrivateKey = Base64.encode(privateKey, Base64.NO_PADDING).toString(Charsets.UTF_8) val url = "$GIFT_BASE_URL/$encodedPrivateKey" E.OnPaperWalletCreated(privateKey.toString(Charsets.UTF_8), address, url) } catch (e: ExportablePaperWalletError) { logError("Failed to create exportable paper wallet", e) E.OnPaperWalletFailed(PaperWalletError.UNKNOWN) } } addConsumer<F.BackupGift> { (address, privateKey) -> giftBackup.putGift(GiftCopy(address, privateKey)) } addFunction<F.DeleteGiftBackup> { (address) -> giftBackup.removeUnusedGift(address) E.OnGiftBackupDeleted } addFunction<F.EstimateFee> { (address, amount, transferSpeed) -> val wallet = breadBox.wallet(currencyId).first() val coreAddress = wallet.addressFor(address) val networkFee = wallet.feeForSpeed(transferSpeed) val coreAmount = Amount.create(amount.toDouble(), wallet.unit) if (coreAddress == null) { logError("Invalid address provided") E.OnFeeFailed(FeeEstimateError.INVALID_TARGET) } else { try { E.OnFeeUpdated(wallet.estimateFee(coreAddress, coreAmount, networkFee)) } catch (e: FeeEstimationError) { logError("Failed to estimate fee", e) when (e) { is FeeEstimationInsufficientFundsError -> E.OnFeeFailed(FeeEstimateError.INSUFFICIENT_BALANCE) else -> E.OnFeeFailed(FeeEstimateError.SERVER_ERROR) } } } } addFunction<F.EstimateMax> { (address, transferSpeed, fiatCurrencyCode) -> val wallet = breadBox.wallet(currencyId).first() val coreAddress = wallet.addressFor(address) val networkFee = wallet.feeForSpeed(transferSpeed) if (coreAddress == null) { E.OnMaxEstimateFailed(MaxEstimateError.INVALID_TARGET) } else { try { var max = wallet.estimateMaximum(coreAddress, networkFee) if (max.unit != wallet.defaultUnit) { max = checkNotNull(max.convert(wallet.defaultUnit).orNull()) } val fiatPerCryptoUnit = rates.getFiatPerCryptoUnit( max.currency.code, fiatCurrencyCode ) E.OnMaxEstimated(max.toBigDecimal() * fiatPerCryptoUnit, fiatPerCryptoUnit) } catch (e: LimitEstimationError) { logError("Failed to estimate max", e) when (e) { is LimitEstimationInsufficientFundsError -> E.OnMaxEstimateFailed(MaxEstimateError.INSUFFICIENT_BALANCE) else -> E.OnMaxEstimateFailed(MaxEstimateError.SERVER_ERROR) } } } } addFunction<F.SendTransaction> { (address, amount, feeBasis) -> val wallet = breadBox.wallet(currencyId).first() val coreAddress = wallet.addressFor(address) val coreAmount = Amount.create(amount.toDouble(), wallet.unit) val phrase = try { userManager.getPhrase() } catch (e: UserNotAuthenticatedException) { logDebug("Authentication cancelled") return@addFunction E.OnTransferFailed } if (coreAddress == null) { logError("Invalid address provided") E.OnTransferFailed } else { val transfer = wallet.createTransfer(coreAddress, coreAmount, feeBasis, null).orNull() if (transfer == null) { logError("Failed to create transfer") E.OnTransferFailed } else { try { wallet.walletManager.submit(transfer, phrase) val transferHash = transfer.hashString() breadBox.walletTransfer(wallet.currency.code, transferHash) .mapNotNull { tx -> when (checkNotNull(tx.state.type)) { TransferState.Type.CREATED, TransferState.Type.SIGNED -> null TransferState.Type.INCLUDED, TransferState.Type.PENDING, TransferState.Type.SUBMITTED -> { EventUtils.pushEvent(EventUtils.EVENT_GIFT_SEND) E.OnTransactionSent(transferHash) } TransferState.Type.DELETED, TransferState.Type.FAILED -> { logError("Failed to submit transfer ${tx.state.failedError.orNull()}") E.OnTransferFailed } } }.first() } catch (e: TransferSubmitError) { logError("Failed to submit transfer", e) E.OnTransferFailed } } } } addFunction<F.SaveGift> { effect -> withContext(NonCancellable) { giftBackup.markGiftIsUsed(effect.address) val wallet = breadBox.wallet(currencyId).first() val transfer = breadBox.walletTransfer(wallet.currency.code, effect.txHash).first() metaDataManager.putTxMetaData( transfer, TxMetaDataValue( BRSharedPrefs.getDeviceId(), "", effect.fiatCurrencyCode, effect.fiatPerCryptoUnit.toDouble(), wallet.walletManager.network.height.toLong(), transfer.fee.toBigDecimal().toDouble(), transfer.getSize()?.toInt() ?: 0, (System.currentTimeMillis() / DateUtils.SECOND_IN_MILLIS).toInt(), gift = GiftMetaData( keyData = effect.privateKey, recipientName = effect.recipientName ) ) ) E.OnGiftSaved } } }
mit
2832c2e80fe5268532d111e8214b2516
44.690909
124
0.650816
4.818792
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/view/ActionActivity.kt
1
12949
/* * Copyright (C) 2017-2021 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.legacy.action.view import android.app.Activity import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.os.Parcelable import android.view.Menu import android.view.View import android.view.WindowInsets import android.view.WindowManager import androidx.recyclerview.widget.LinearLayoutManager import jp.hazuki.yuzubrowser.core.utility.log.Logger import jp.hazuki.yuzubrowser.legacy.Constants import jp.hazuki.yuzubrowser.legacy.R import jp.hazuki.yuzubrowser.legacy.action.* import jp.hazuki.yuzubrowser.legacy.databinding.ActionActivityBinding import jp.hazuki.yuzubrowser.ui.app.OnActivityResultListener import jp.hazuki.yuzubrowser.ui.app.StartActivityInfo import jp.hazuki.yuzubrowser.ui.app.ThemeActivity import jp.hazuki.yuzubrowser.ui.settings.AppPrefs import jp.hazuki.yuzubrowser.ui.widget.recycler.OnRecyclerListener class ActionActivity : ThemeActivity(), OnRecyclerListener { private var mActionManager: ActionManager? = null private var mOnActivityResultListener: OnActivityResultListener? = null lateinit var actionNameArray: ActionNameArray private set private var mActionId: Int = 0 private lateinit var mAction: Action private lateinit var adapter: ActionNameArrayAdapter private lateinit var binding: ActionActivityBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActionActivityBinding.inflate(layoutInflater) setContentView(binding.root) val intent = intent ?: throw NullPointerException("intent is null") if (ACTION_ALL_ACTION == intent.action) { val fullscreen = intent.getBooleanExtra(Constants.intent.EXTRA_MODE_FULLSCREEN, AppPrefs.fullscreen.get()) val orientation = intent.getIntExtra(Constants.intent.EXTRA_MODE_ORIENTATION, AppPrefs.oritentation.get()) if (fullscreen) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { window.insetsController?.hide(WindowInsets.Type.statusBars()) } else { @Suppress("DEPRECATION") window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) } } requestedOrientation = orientation } actionNameArray = intent.getParcelableExtra(ActionNameArray.INTENT_EXTRA) ?: ActionNameArray(this) adapter = ActionNameArrayAdapter(this, actionNameArray, this) binding.recyclerView.layoutManager = LinearLayoutManager(this) binding.recyclerView.adapter = adapter val mActionType = intent.getIntExtra(ActionManager.INTENT_EXTRA_ACTION_TYPE, 0) mActionId = intent.getIntExtra(ActionManager.INTENT_EXTRA_ACTION_ID, 0) if (mActionType != 0) { mActionManager = ActionManager.getActionManager(applicationContext, mActionType) mAction = when (mActionManager) { is SingleActionManager -> Action((mActionManager as SingleActionManager).getAction(mActionId))//copy is ListActionManager -> Action() else -> throw IllegalArgumentException() } } else { mActionManager = null mAction = intent.getParcelableExtra(EXTRA_ACTION) ?: Action() } title = intent.getStringExtra(Intent.EXTRA_TITLE) var initialPosition = -1 for (action in mAction) { val id = action.id val size = actionNameArray.actionValues.size for (i in 0 until size) { if (actionNameArray.actionValues[i] == id) { adapter.setChecked(i, true) if (initialPosition == -1) initialPosition = i } } } adapter.notifyDataSetChanged() if (initialPosition != -1) binding.recyclerView.scrollToPosition(initialPosition) binding.okButton.setOnClickListener { when (val actionManager = mActionManager) { null -> { val intent1 = Intent() intent1.putExtra(EXTRA_ACTION, mAction as Parcelable?) intent1.putExtra(EXTRA_RETURN, getIntent().getBundleExtra(EXTRA_RETURN)) setResult(Activity.RESULT_OK, intent1) } is SingleActionManager -> { val list = actionManager.getAction(mActionId) list.clear() list.addAll(mAction) mActionManager!!.save(applicationContext) setResult(Activity.RESULT_OK) } is ListActionManager -> { actionManager.addAction(mActionId, mAction) mActionManager!!.save(applicationContext) setResult(Activity.RESULT_OK) } } finish() } binding.okButton.setOnLongClickListener { startJsonStringActivity() false } binding.resetButton.setOnClickListener { mAction.clear() adapter.clearChoices() } binding.cancelButton.setOnClickListener { finish() } adapter.setListener(this::showSubPreference) } override fun onRecyclerItemClicked(v: View, position: Int) { itemClicked(position, false) } override fun onRecyclerItemLongClicked(v: View, position: Int): Boolean { if (!adapter.isChecked(position)) itemClicked(position, true) showSubPreference(position) return true } private fun itemClicked(position: Int, forceShowPref: Boolean) { val value = adapter.getItemValue(position) if (adapter.toggleCheck(position)) { val action = SingleAction.makeInstance(value) mAction.add(action) showPreference(if (forceShowPref) { action.showSubPreference(this) } else { action.showMainPreference(this) }) } else { for (i in mAction.indices) { if (mAction[i].id == value) { mAction.removeAt(i) break } } } } private fun showSubPreference(position: Int) { val value = adapter.getItemValue(position) val size = mAction.size for (i in 0 until size) { if (mAction[i].id == value) { showPreference(mAction[i].showSubPreference(this@ActionActivity)) break } } } private fun showPreference(screen: StartActivityInfo?): Boolean { if (screen == null) return false mOnActivityResultListener = screen.onActivityResultListener startActivityForResult(screen.intent, RESULT_REQUEST_PREFERENCE) return true } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { RESULT_REQUEST_PREFERENCE -> if (mOnActivityResultListener != null) { mOnActivityResultListener!!.invoke(this, resultCode, data) mOnActivityResultListener = null } RESULT_REQUEST_JSON -> if (resultCode == Activity.RESULT_OK && data != null) { val result = data.getParcelableExtra<Action>(ActionStringActivity.EXTRA_ACTION)!! mAction.clear() mAction.addAll(result) adapter.clearChoices() var initialPosition = -1 val actionNameArray = adapter.nameArray for (action in mAction) { val id = action.id val size = actionNameArray.actionValues.size for (i in 0 until size) { if (actionNameArray.actionValues[i] == id) { adapter.setChecked(i, true) if (initialPosition == -1) initialPosition = i } } } adapter.notifyDataSetChanged() if (initialPosition != -1) binding.recyclerView.scrollToPosition(initialPosition) } else -> super.onActivityResult(requestCode, resultCode, data) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menu.add(R.string.action_to_json).setOnMenuItemClickListener { startJsonStringActivity() false } return super.onCreateOptionsMenu(menu) } private fun startJsonStringActivity() { val intent = Intent(applicationContext, ActionStringActivity::class.java) intent.putExtra(ActionStringActivity.EXTRA_ACTION, mAction as Parcelable?) startActivityForResult(intent, RESULT_REQUEST_JSON) } class Builder(private val mContext: Context) { private val intent: Intent = Intent(mContext.applicationContext, ActionActivity::class.java) private var listener: OnActivityResultListener? = null fun setTitle(title: Int): Builder { intent.putExtra(Intent.EXTRA_TITLE, mContext.getString(title)) return this } fun setTitle(title: CharSequence): Builder { intent.putExtra(Intent.EXTRA_TITLE, title) return this } fun setActionNameArray(array: ActionNameArray?): Builder { intent.putExtra(ActionNameArray.INTENT_EXTRA, array as Parcelable?) return this } fun setActionManager(actionType: Int, actionId: Int): Builder { intent.putExtra(ActionManager.INTENT_EXTRA_ACTION_TYPE, actionType) intent.putExtra(ActionManager.INTENT_EXTRA_ACTION_ID, actionId) return this } fun setDefaultAction(action: Action?): Builder { intent.putExtra(EXTRA_ACTION, action as Parcelable?) return this } fun setReturnData(bundle: Bundle): Builder { intent.putExtra(EXTRA_RETURN, bundle) return this } fun setOnActionActivityResultListener(l: (action: Action) -> Unit): Builder { listener = listener@ { _, resultCode, intent -> val action = getActionFromIntent(resultCode, intent) if (action == null) { Logger.w("ActionActivityResult", "Action is null") return@listener } l.invoke(action) } return this } fun makeStartActivityInfo(): StartActivityInfo { return StartActivityInfo(intent, listener) } fun create(): Intent { return intent } fun show() { mContext.startActivity(intent) } fun show(requestCode: Int): OnActivityResultListener? { if (mContext is Activity) mContext.startActivityForResult(intent, requestCode) else throw IllegalArgumentException("Context is not instanceof Activity") return listener } } companion object { private const val TAG = "ActionActivity" const val ACTION_ALL_ACTION = "ActionActivity.action.allaction" const val EXTRA_ACTION = "ActionActivity.extra.action" const val EXTRA_RETURN = "ActionActivity.extra.return" const val RESULT_REQUEST_PREFERENCE = 1 private const val RESULT_REQUEST_JSON = 2 fun getActionFromIntent(resultCode: Int, intent: Intent?): Action? { if (resultCode != Activity.RESULT_OK || intent == null) { Logger.w(TAG, "resultCode != Activity.RESULT_OK || intent == null") return null } return intent.getParcelableExtra(EXTRA_ACTION) } @JvmStatic fun getActionFromIntent(intent: Intent): Action { return intent.getParcelableExtra(EXTRA_ACTION)!! } @JvmStatic fun getReturnData(intent: Intent): Bundle? { return intent.getBundleExtra(EXTRA_RETURN) } } }
apache-2.0
2dbf596a737e8c40ae3e6bb7f2ee59cd
35.891738
118
0.6097
5.240389
false
false
false
false
AlexandrDrinov/kotlin-koans-edu
test/ii_collections/ShopBuilders.kt
27
911
package ii_collections.shopBuilders import ii_collections.* class ShopBuilder(val name: String) { val customers = arrayListOf<Customer>() fun build(): Shop = Shop(name, customers) } fun shop(name: String, init: ShopBuilder.() -> Unit): Shop { val shopBuilder = ShopBuilder(name) shopBuilder.init() return shopBuilder.build() } fun ShopBuilder.customer(name: String, city: City, init: CustomerBuilder.() -> Unit) { val customer = CustomerBuilder(name, city) customer.init() customers.add(customer.build()) } class CustomerBuilder(val name: String, val city: City) { val orders = arrayListOf<Order>() fun build(): Customer = Customer(name, city, orders) } fun CustomerBuilder.order(isDelivered: Boolean, vararg products: Product) { orders.add(Order(products.toList(), isDelivered)) } fun CustomerBuilder.order(vararg products: Product) = order(true, *products)
mit
00dc7f44b13ecab056be88d430bd326e
27.46875
86
0.712404
3.764463
false
false
false
false
DR-YangLong/spring-boot-kotlin-demo
src/main/kotlin/site/yanglong/promotion/model/Perms.kt
1
1252
package site.yanglong.promotion.model import java.io.Serializable import com.baomidou.mybatisplus.enums.IdType import com.baomidou.mybatisplus.annotations.TableId import com.baomidou.mybatisplus.activerecord.Model import com.baomidou.mybatisplus.annotations.TableField import com.baomidou.mybatisplus.annotations.TableLogic /** * * * * * * @author Dr.YangLong * @since 2017-11-01 */ class Perms : Model<Perms>() { /** * 权限id */ @TableId(value = "id", type = IdType.AUTO) var id: Long? = null /** * 字符串标识 */ var identify: String? = null /** * 名称 */ var name: String? = null /** * 备注说明 */ var remark: String? = null /** * 是否启用 */ @TableField @TableLogic var enable: String? = null override fun pkVal(): Serializable? { return this.id } override fun toString(): String { return "Perms{" + ", id=" + id + ", identify=" + identify + ", name=" + name + ", remark=" + remark + ", enable=" + enable + "}" } companion object { private val serialVersionUID = 1L } }
apache-2.0
1445a72c34b9b2bb556e98b74d256b78
18.03125
54
0.542693
3.891374
false
false
false
false
porokoro/paperboy
paperboy/src/main/kotlin/com/github/porokoro/paperboy/ItemType.kt
1
936
/* * Copyright (C) 2015-2016 Dominik Hibbeln * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.porokoro.paperboy data class ItemType( var id: Int = 0, var name: String = "", var shorthand: String = "", var titleSingular: String = "", var titlePlural: String = "", var color: Int = 0, var icon: Int = 0, var sortOrder: Int = Int.MAX_VALUE)
apache-2.0
0d5f68eeb38391079b3ff41425d3b59d
35
75
0.67094
4
false
false
false
false
tmarsteel/kotlin-prolog
core/src/main/kotlin/com/github/prologdb/runtime/term/util.kt
1
3227
@file:JvmName("TermUtils") package com.github.prologdb.runtime.term import com.github.prologdb.runtime.RandomVariableScope import com.github.prologdb.runtime.unification.Unification import com.github.prologdb.runtime.unification.VariableBucket import java.util.concurrent.ConcurrentHashMap /** * Unifies the two arrays of terms as if the arguments to predicates with equal functors. * @return `Unification.FALSE` if the two arrays haf different lengths */ fun Array<out Term>.unify(rhs: Array<out Term>, randomVarsScope: RandomVariableScope): Unification? { if (size != rhs.size) { return Unification.FALSE } if (size == 0) { return Unification.TRUE } val vars = VariableBucket() for (argIndex in 0..lastIndex) { val lhsArg = this[argIndex].substituteVariables(vars.asSubstitutionMapper()) val rhsArg = rhs[argIndex].substituteVariables(vars.asSubstitutionMapper()) val argUnification = lhsArg.unify(rhsArg, randomVarsScope) if (argUnification == null) { // the arguments at place argIndex do not unify => the terms don't unify return Unification.FALSE } for ((variable, value) in argUnification.variableValues.values) { if (value != null) { // substitute all instantiated variables for simplicity val substitutedValue = value.substituteVariables(vars.asSubstitutionMapper()) if (vars.isInstantiated(variable)) { if (vars[variable] != substitutedValue && vars[variable] != value) { // instantiated to different value => no unification return Unification.FALSE } } else { vars.instantiate(variable, substitutedValue) } } } } return Unification(vars) } val Array<out Term>.variables: Iterable<Variable> get() = object : Iterable<Variable> { override fun iterator() = object : Iterator<Variable> { private var currentIndex = 0 private var currentSub: Iterator<Variable>? = null override fun hasNext(): Boolean { if (currentIndex >= [email protected]) { return false } if (currentSub == null) { currentSub = this@variables[currentIndex].variables.iterator() } if (!currentSub!!.hasNext()) { currentIndex++ currentSub = null return hasNext() } return true } override fun next(): Variable { if (!hasNext()) { throw NoSuchElementException() } return (currentSub ?: throw NoSuchElementException()).next() } } } private val prologTypeNameCache = ConcurrentHashMap<Class<out Term>, String>() val Class<out Term>.prologTypeName: String get() = prologTypeNameCache.computeIfAbsent(this) { clazz -> clazz.getAnnotation(PrologTypeName::class.java)?.value ?: clazz.simpleName }
mit
27a6bb7f9573215e84b1e4bf42093d6e
34.461538
101
0.588782
5.1632
false
false
false
false
jayrave/falkon
falkon-dao/src/test/kotlin/com/jayrave/falkon/dao/testLib/WhereHelpers.kt
1
2387
package com.jayrave.falkon.dao.testLib import com.jayrave.falkon.dao.where.Where import com.jayrave.falkon.sqlBuilders.lib.WhereSection import com.jayrave.falkon.sqlBuilders.lib.WhereSection.Connector.CompoundConnector import com.jayrave.falkon.sqlBuilders.lib.WhereSection.Connector.SimpleConnector import com.jayrave.falkon.sqlBuilders.lib.WhereSection.Predicate.* import org.assertj.core.api.Assertions /** * Stringifies the passed in list of [WhereSection]s. Mostly used for assertions as * [WhereSection] doesn't override #toString */ internal fun buildWhereClauseWithPlaceholders(whereSections: Iterable<WhereSection>?): String? { var firstSection = true val sb = whereSections?.foldIndexed(StringBuilder()) { index, sb, section -> when { firstSection -> firstSection = false else -> sb.append(", ") } when (section) { is NoArgPredicate -> sb.append("${section.type} ${section.columnName}") is OneArgPredicate -> sb.append("${section.type} ${section.columnName}") is MultiArgPredicate -> sb.append( "${section.type} ${section.columnName} ${section.numberOfArgs}" ) is MultiArgPredicateWithSubQuery -> sb.append( "${section.type} ${section.columnName} " + "${section.subQuery} ${section.numberOfArgs}" ) is BetweenPredicate -> sb.append("BETWEEN ${section.columnName}") is SimpleConnector -> sb.append("${section.type}") is CompoundConnector -> sb.append( "${section.type} ${buildWhereClauseWithPlaceholders(section.sections)}" ) else -> throw IllegalArgumentException("Don't know to handle: $section") } sb } return sb?.toString() } internal fun assertWhereEquality(actualWhere: Where, expectedWhere: Where) { Assertions.assertThat(actualWhere.buildString()).isEqualTo(expectedWhere.buildString()) } private fun Where.buildString(): String { val clauseWithPlaceholders = buildWhereClauseWithPlaceholders(whereSections) val argsString = arguments.joinToString { when (it) { is ByteArray -> kotlin.text.String(it) else -> it.toString() } } return "Where clause: $clauseWithPlaceholders; args: $argsString" }
apache-2.0
a10d5d75d0912b98e88a62aae86bf25e
35.738462
96
0.656473
4.643969
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/teams/list/TeamRecyclerViewAdapter.kt
1
4443
package ca.josephroque.bowlingcompanion.teams.list import android.support.design.chip.Chip import android.support.design.chip.ChipGroup import android.support.v4.content.ContextCompat import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.adapters.BaseRecyclerViewAdapter import ca.josephroque.bowlingcompanion.teams.Team /** * Copyright (C) 2018 Joseph Roque * * [RecyclerView.Adapter] that can display a [Team] and makes a call to the delegate. */ class TeamRecyclerViewAdapter( items: List<Team>, delegate: BaseRecyclerViewAdapter.AdapterDelegate<Team>? ) : BaseRecyclerViewAdapter<Team>(items, delegate) { companion object { @Suppress("unused") private const val TAG = "TeamRecyclerViewAdapter" private enum class ViewType { Active, Deleted; companion object { private val map = ViewType.values().associateBy(ViewType::ordinal) fun fromInt(type: Int) = map[type] } } } // MARK: BaseRecyclerViewAdapter override fun getItemViewType(position: Int): Int { return if (getItemAt(position).isDeleted) { ViewType.Deleted.ordinal } else { ViewType.Active.ordinal } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseRecyclerViewAdapter<Team>.ViewHolder { return when (ViewType.fromInt(viewType)) { ViewType.Active -> { ViewHolderActive(LayoutInflater .from(parent.context) .inflate(R.layout.list_item_team, parent, false)) } ViewType.Deleted -> { ViewHolderDeleted(LayoutInflater .from(parent.context) .inflate(R.layout.list_item_deleted, parent, false)) } else -> throw IllegalArgumentException("View Type `$viewType` is invalid") } } override fun onBindViewHolder(holder: BaseRecyclerViewAdapter<Team>.ViewHolder, position: Int) { holder.bind(getItemAt(position)) } // MARK: ViewHolderActive inner class ViewHolderActive(view: View) : BaseRecyclerViewAdapter<Team>.ViewHolder(view) { private val tvName: TextView? = view.findViewById(R.id.tv_name) private val chipGroupMembers: ChipGroup? = view.findViewById(R.id.cg_members) override fun bind(item: Team) { val context = itemView.context tvName?.text = item.name chipGroupMembers?.removeAllViews() item.members.forEach { val viewId = View.generateViewId() Chip(context).apply { id = viewId isFocusable = false isClickable = false text = it.bowlerName setChipBackgroundColorResource(R.color.colorPrimary) setTextColor(ContextCompat.getColor(context, R.color.primaryWhiteText)) chipGroupMembers?.addView(this) } } itemView.setOnClickListener(this@TeamRecyclerViewAdapter) itemView.setOnLongClickListener(this@TeamRecyclerViewAdapter) } } // MARK: ViewHolderDeleted inner class ViewHolderDeleted(view: View) : BaseRecyclerViewAdapter<Team>.ViewHolder(view) { private val tvDeleted: TextView? = view.findViewById(R.id.tv_deleted) private val tvUndo: TextView? = view.findViewById(R.id.tv_undo) override fun bind(item: Team) { val context = itemView.context tvDeleted?.text = String.format( context.resources.getString(R.string.query_delete_item), getItemAt(adapterPosition).name ) val deletedItemListener = View.OnClickListener { if (it.id == R.id.tv_undo) { delegate?.onItemSwipe(getItemAt(adapterPosition)) } else { delegate?.onItemDelete(getItemAt(adapterPosition)) } } itemView.setOnClickListener(deletedItemListener) itemView.setOnLongClickListener(null) tvUndo?.setOnClickListener(deletedItemListener) } } }
mit
2e9367504643a811f37014818c00b6e6
35.418033
113
0.63043
5.124567
false
false
false
false
AlmasB/FXGL
fxgl/src/test/kotlin/com/almasb/fxgl/dsl/components/OffscreenInvisibleComponentTest.kt
1
4203
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.dsl.components import com.almasb.fxgl.app.scene.Viewport import com.almasb.fxgl.entity.Entity import com.almasb.fxgl.entity.GameWorld import com.almasb.fxgl.physics.BoundingShape import com.almasb.fxgl.physics.HitBox import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.contains import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test /** * @author Johan Dykström */ class OffscreenInvisibleComponentTest { private lateinit var viewport: Viewport @BeforeEach fun setUp() { viewport = Viewport(800.0, 600.0) } @Test fun `Entity is hidden when entity moves offscreen`() { val e = Entity() e.addComponent(OffscreenInvisibleComponent(viewport)) val world = GameWorld() world.addEntity(e) assertThat(world.entities, contains(e)) assertTrue(e.isVisible) world.onUpdate(0.016) assertThat(world.entities, contains(e)) assertTrue(e.isVisible) e.x = -15.0 world.onUpdate(0.016) // World still contains entity, but it is invisible assertThat(world.entities, contains(e)) assertFalse(e.isVisible) } @Test fun `Entity is hidden when entity with bbox moves offscreen`() { val e = Entity() e.addComponent(OffscreenInvisibleComponent(viewport)) e.boundingBoxComponent.addHitBox(HitBox(BoundingShape.box(30.0, 30.0))) val world = GameWorld() world.addEntity(e) assertThat(world.entities, contains(e)) assertTrue(e.isVisible) world.onUpdate(0.016) assertThat(world.entities, contains(e)) assertTrue(e.isVisible) e.x = -25.0 world.onUpdate(0.016) assertThat(world.entities, contains(e)) assertTrue(e.isVisible) e.x = -30.0 world.onUpdate(0.016) assertThat(world.entities, contains(e)) assertTrue(e.isVisible) e.x = -31.0 world.onUpdate(0.016) // World still contains entity, but it is invisible assertThat(world.entities, contains(e)) assertFalse(e.isVisible) } @Test fun `Entity is hidden when viewport moves offscreen`() { val e = Entity() e.addComponent(OffscreenInvisibleComponent(viewport)) val world = GameWorld() world.addEntity(e) assertThat(world.entities, contains(e)) assertTrue(e.isVisible) world.onUpdate(0.016) assertThat(world.entities, contains(e)) assertTrue(e.isVisible) viewport.x = 5.0 world.onUpdate(0.016) // World still contains entity, but it is invisible assertThat(world.entities, contains(e)) assertFalse(e.isVisible) } @Test fun `Entity is displayed again when entity moves back onscreen`() { val e = Entity() e.addComponent(OffscreenInvisibleComponent(viewport)) val world = GameWorld() world.addEntity(e) assertThat(world.entities, contains(e)) assertTrue(e.isVisible) e.x = -15.0 world.onUpdate(0.016) // World still contains entity, but it is invisible assertThat(world.entities, contains(e)) assertFalse(e.isVisible) e.x = 10.0 world.onUpdate(0.016) // Entity is visible again assertThat(world.entities, contains(e)) assertTrue(e.isVisible) } @Test fun `Entity created offscreen becomes visible when it moves onscreen`() { val e = Entity() e.x = -100.0 e.addComponent(OffscreenInvisibleComponent(viewport)) val world = GameWorld() world.addEntity(e) assertThat(world.entities, contains(e)) assertFalse(e.isVisible) e.x = 10.0 world.onUpdate(0.016) // Entity is visible again assertThat(world.entities, contains(e)) assertTrue(e.isVisible) } }
mit
564e36f587a1084272dd786872292fe2
27.585034
79
0.641361
4.103516
false
false
false
false
Nandi/adventofcode
src/Day14/December14.kt
1
3771
package Day14 import java.nio.file.Files import java.nio.file.Paths import java.util.* import java.util.stream.Stream /** * todo: visualize * * This year is the Reindeer Olympics! Reindeer can fly at high speeds, but must rest occasionally to recover their * energy. Santa would like to know which of his reindeer is fastest, and so he has them race. * * Reindeer can only either be flying (always at their top speed) or resting (not moving at all), and always spend * whole seconds in either state. * * Part 1 * * Given the descriptions of each reindeer (in your puzzle input), after exactly 2503 seconds, what distance has the * winning reindeer traveled? * * Part 2 * * Seeing how reindeer move in bursts, Santa decides he's not pleased with the old scoring system. * * Instead, at the end of each second, he awards one point to the reindeer currently in the lead. (If there are * multiple reindeer tied for the lead, they each get one point.) He keeps the traditional 2503 second time limit, of * course, as doing otherwise would be entirely ridiculous. * * Again given the descriptions of each reindeer (in your puzzle input), after exactly 2503 seconds, how many points * does the winning reindeer have? * * Created by Simon on 14/12/2015. */ enum class STATE { RESTING, MOVING } data class Reindeer(val name: String, val speed: Int, val duration: Int, val rest: Int, var state: STATE = STATE.MOVING, var distance: Int = 0, var points: Int = 0) { var restTimer = rest var durationTimer = duration fun updateState() { when (state) { STATE.RESTING -> { restTimer-- if (restTimer == 0) { state = STATE.MOVING restTimer = rest } } STATE.MOVING -> { durationTimer-- if (durationTimer == 0) { state = STATE.RESTING durationTimer = duration } distance += speed } } } } class December14 { fun main() { var reindeerList = arrayListOf<Reindeer>() val lines = loadFile("src/Day14/14.dec_input.txt") for (line in lines) { var importantInfo = line.replace("can fly ", "") .replace("km/s for ", "") .replace("seconds, but then must rest for ", "") .replace(" seconds.", "") val (name, speed, duration, rest) = importantInfo.split(" ") if (name !is String || speed !is String || duration !is String || rest !is String) return reindeerList.add(Reindeer(name, speed.toInt(), duration.toInt(), rest.toInt())) } val byDistance = Comparator<Reindeer> { r1, r2 -> r2.distance.compareTo(r1.distance) } val byPoints = Comparator<Reindeer> { r1, r2 -> r2.points.compareTo(r1.points) } for (i in 1..2503) { reindeerList.forEach { r -> r.updateState() } reindeerList.sort(byDistance) reindeerList.filter({ r -> r.distance.equals(reindeerList[0].distance) }).forEach { r -> r.points++ } } println("==== Sorted by distance ====") reindeerList.sort(byDistance) reindeerList.forEach { r -> println("${r.name} - ${r.distance}") } println() println("==== Sorted by points ====") reindeerList.sort(byPoints) reindeerList.forEach { r -> println("${r.name} - ${r.points}") } } fun loadFile(path: String): Stream<String> { val input = Paths.get(path) val reader = Files.newBufferedReader(input) return reader.lines() } } fun main(args: Array<String>) { December14().main() }
mit
76e4a0b3d2da2ed7ec9301daf00f380d
32.678571
166
0.597985
3.844037
false
false
false
false
guyca/react-native-navigation
lib/android/app/src/main/java/com/reactnativenavigation/views/element/TransitionSet.kt
1
883
package com.reactnativenavigation.views.element import java.util.* class TransitionSet { var validSharedElementTransitions: MutableList<SharedElementTransition> = ArrayList() var validElementTransitions: MutableList<ElementTransition> = ArrayList() val isEmpty: Boolean get() = size() == 0 val transitions: List<Transition> get() = validElementTransitions + validSharedElementTransitions fun add(transition: SharedElementTransition) { validSharedElementTransitions.add(transition) } fun add(transition: ElementTransition) { validElementTransitions.add(transition) } fun forEach(action: ((Transition) -> Unit)) { validSharedElementTransitions.forEach(action) validElementTransitions.forEach(action) } fun size(): Int = validElementTransitions.size + validSharedElementTransitions.size }
mit
e45c0e463e9a42c865c52d50b9d6e573
31.740741
89
0.734994
5.224852
false
false
false
false
googlecodelabs/android-compose-codelabs
AnimationCodelab/finished/src/main/java/com/example/android/codelab/animation/ui/home/Home.kt
1
25888
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.example.android.codelab.animation.ui.home import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateColor import androidx.compose.animation.animateColorAsState import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.FastOutLinearInEasing import androidx.compose.animation.core.LinearOutSlowInEasing import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.Spring import androidx.compose.animation.core.animateDp import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.calculateTargetValue import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.keyframes import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.spring import androidx.compose.animation.core.tween import androidx.compose.animation.core.updateTransition import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.animation.splineBasedDecay import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.horizontalDrag import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.FloatingActionButton import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Surface import androidx.compose.material.TabPosition import androidx.compose.material.TabRow import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountBox import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.Refresh import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.positionChange import androidx.compose.ui.input.pointer.util.VelocityTracker import androidx.compose.ui.res.stringArrayResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.heading import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.android.codelab.animation.R import com.example.android.codelab.animation.ui.Amber600 import com.example.android.codelab.animation.ui.AnimationCodelabTheme import com.example.android.codelab.animation.ui.Green300 import com.example.android.codelab.animation.ui.Green800 import com.example.android.codelab.animation.ui.Purple100 import com.example.android.codelab.animation.ui.Purple700 import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlin.math.absoluteValue import kotlin.math.roundToInt private enum class TabPage { Home, Work } /** * Shows the entire screen. */ @Composable fun Home() { // String resources. val allTasks = stringArrayResource(R.array.tasks) val allTopics = stringArrayResource(R.array.topics).toList() // The currently selected tab. var tabPage by remember { mutableStateOf(TabPage.Home) } // True if the whether data is currently loading. var weatherLoading by remember { mutableStateOf(false) } // Holds all the tasks currently shown on the task list. val tasks = remember { mutableStateListOf(*allTasks) } // Holds the topic that is currently expanded to show its body. var expandedTopic by remember { mutableStateOf<String?>(null) } // True if the message about the edit feature is shown. var editMessageShown by remember { mutableStateOf(false) } // Simulates loading weather data. This takes 3 seconds. suspend fun loadWeather() { if (!weatherLoading) { weatherLoading = true delay(3000L) weatherLoading = false } } // Shows the message about edit feature. suspend fun showEditMessage() { if (!editMessageShown) { editMessageShown = true delay(3000L) editMessageShown = false } } // Load the weather at the initial composition. LaunchedEffect(Unit) { loadWeather() } val lazyListState = rememberLazyListState() // The background color. The value is changed by the current tab. val backgroundColor by animateColorAsState(if (tabPage == TabPage.Home) Purple100 else Green300) // The coroutine scope for event handlers calling suspend functions. val coroutineScope = rememberCoroutineScope() Scaffold( topBar = { HomeTabBar( backgroundColor = backgroundColor, tabPage = tabPage, onTabSelected = { tabPage = it } ) }, backgroundColor = backgroundColor, floatingActionButton = { HomeFloatingActionButton( extended = lazyListState.isScrollingUp(), onClick = { coroutineScope.launch { showEditMessage() } } ) } ) { padding -> LazyColumn( contentPadding = PaddingValues(horizontal = 16.dp, vertical = 32.dp), state = lazyListState, modifier = Modifier.padding(padding) ) { // Weather item { Header(title = stringResource(R.string.weather)) } item { Spacer(modifier = Modifier.height(16.dp)) } item { Surface( modifier = Modifier.fillMaxWidth(), elevation = 2.dp ) { if (weatherLoading) { LoadingRow() } else { WeatherRow(onRefresh = { coroutineScope.launch { loadWeather() } }) } } } item { Spacer(modifier = Modifier.height(32.dp)) } // Topics item { Header(title = stringResource(R.string.topics)) } item { Spacer(modifier = Modifier.height(16.dp)) } items(allTopics) { topic -> TopicRow( topic = topic, expanded = expandedTopic == topic, onClick = { expandedTopic = if (expandedTopic == topic) null else topic } ) } item { Spacer(modifier = Modifier.height(32.dp)) } // Tasks item { Header(title = stringResource(R.string.tasks)) } item { Spacer(modifier = Modifier.height(16.dp)) } if (tasks.isEmpty()) { item { TextButton(onClick = { tasks.clear(); tasks.addAll(allTasks) }) { Text(stringResource(R.string.add_tasks)) } } } items(count = tasks.size) { i -> val task = tasks.getOrNull(i) if (task != null) { key(task) { TaskRow( task = task, onRemove = { tasks.remove(task) } ) } } } } EditMessage(editMessageShown) } } /** * Shows the floating action button. * * @param extended Whether the tab should be shown in its expanded state. */ // AnimatedVisibility is currently an experimental API in Compose Animation. @Composable private fun HomeFloatingActionButton( extended: Boolean, onClick: () -> Unit ) { // Use `FloatingActionButton` rather than `ExtendedFloatingActionButton` for full control on // how it should animate. FloatingActionButton(onClick = onClick) { Row( modifier = Modifier.padding(horizontal = 16.dp) ) { Icon( imageVector = Icons.Default.Edit, contentDescription = null ) // Toggle the visibility of the content with animation. AnimatedVisibility(visible = extended) { Text( text = stringResource(R.string.edit), modifier = Modifier .padding(start = 8.dp, top = 3.dp) ) } } } } /** * Shows a message that the edit feature is not available. */ @Composable private fun EditMessage(shown: Boolean) { AnimatedVisibility( visible = shown, enter = slideInVertically( // Enters by sliding in from offset -fullHeight to 0. initialOffsetY = { fullHeight -> -fullHeight }, animationSpec = tween(durationMillis = 150, easing = LinearOutSlowInEasing) ), exit = slideOutVertically( // Exits by sliding out from offset 0 to -fullHeight. targetOffsetY = { fullHeight -> -fullHeight }, animationSpec = tween(durationMillis = 250, easing = FastOutLinearInEasing) ) ) { Surface( modifier = Modifier.fillMaxWidth(), color = MaterialTheme.colors.secondary, elevation = 4.dp ) { Text( text = stringResource(R.string.edit_message), modifier = Modifier.padding(16.dp) ) } } } /** * Returns whether the lazy list is currently scrolling up. */ @Composable private fun LazyListState.isScrollingUp(): Boolean { var previousIndex by remember(this) { mutableStateOf(firstVisibleItemIndex) } var previousScrollOffset by remember(this) { mutableStateOf(firstVisibleItemScrollOffset) } return remember(this) { derivedStateOf { if (previousIndex != firstVisibleItemIndex) { previousIndex > firstVisibleItemIndex } else { previousScrollOffset >= firstVisibleItemScrollOffset }.also { previousIndex = firstVisibleItemIndex previousScrollOffset = firstVisibleItemScrollOffset } } }.value } /** * Shows the header label. * * @param title The title to be shown. */ @Composable private fun Header( title: String ) { Text( text = title, modifier = Modifier.semantics { heading() }, style = MaterialTheme.typography.h5 ) } /** * Shows a row for one topic. * * @param topic The topic title. * @param expanded Whether the row should be shown expanded with the topic body. * @param onClick Called when the row is clicked. */ @OptIn(ExperimentalMaterialApi::class) @Composable private fun TopicRow(topic: String, expanded: Boolean, onClick: () -> Unit) { TopicRowSpacer(visible = expanded) Surface( modifier = Modifier .fillMaxWidth(), elevation = 2.dp, onClick = onClick ) { Column( modifier = Modifier .fillMaxWidth() .padding(16.dp) // This `Column` animates its size when its content changes. .animateContentSize() ) { Row { Icon( imageVector = Icons.Default.Info, contentDescription = null ) Spacer(modifier = Modifier.width(16.dp)) Text( text = topic, style = MaterialTheme.typography.body1 ) } if (expanded) { Spacer(modifier = Modifier.height(8.dp)) Text( text = stringResource(R.string.lorem_ipsum), textAlign = TextAlign.Justify ) } } } TopicRowSpacer(visible = expanded) } /** * Shows a separator for topics. */ @Composable fun TopicRowSpacer(visible: Boolean) { AnimatedVisibility(visible = visible) { Spacer(modifier = Modifier.height(8.dp)) } } /** * Shows the bar that holds 2 tabs. * * @param backgroundColor The background color for the bar. * @param tabPage The [TabPage] that is currently selected. * @param onTabSelected Called when the tab is switched. */ @Composable private fun HomeTabBar( backgroundColor: Color, tabPage: TabPage, onTabSelected: (tabPage: TabPage) -> Unit ) { TabRow( selectedTabIndex = tabPage.ordinal, backgroundColor = backgroundColor, indicator = { tabPositions -> HomeTabIndicator(tabPositions, tabPage) } ) { HomeTab( icon = Icons.Default.Home, title = stringResource(R.string.home), onClick = { onTabSelected(TabPage.Home) } ) HomeTab( icon = Icons.Default.AccountBox, title = stringResource(R.string.work), onClick = { onTabSelected(TabPage.Work) } ) } } /** * Shows an indicator for the tab. * * @param tabPositions The list of [TabPosition]s from a [TabRow]. * @param tabPage The [TabPage] that is currently selected. */ @Composable private fun HomeTabIndicator( tabPositions: List<TabPosition>, tabPage: TabPage ) { val transition = updateTransition( tabPage, label = "Tab indicator" ) val indicatorLeft by transition.animateDp( transitionSpec = { if (TabPage.Home isTransitioningTo TabPage.Work) { // Indicator moves to the right. // Low stiffness spring for the left edge so it moves slower than the right edge. spring(stiffness = Spring.StiffnessVeryLow) } else { // Indicator moves to the left. // Medium stiffness spring for the left edge so it moves faster than the right edge. spring(stiffness = Spring.StiffnessMedium) } }, label = "Indicator left" ) { page -> tabPositions[page.ordinal].left } val indicatorRight by transition.animateDp( transitionSpec = { if (TabPage.Home isTransitioningTo TabPage.Work) { // Indicator moves to the right // Medium stiffness spring for the right edge so it moves faster than the left edge. spring(stiffness = Spring.StiffnessMedium) } else { // Indicator moves to the left. // Low stiffness spring for the right edge so it moves slower than the left edge. spring(stiffness = Spring.StiffnessVeryLow) } }, label = "Indicator right" ) { page -> tabPositions[page.ordinal].right } val color by transition.animateColor( label = "Border color" ) { page -> if (page == TabPage.Home) Purple700 else Green800 } Box( Modifier .fillMaxSize() .wrapContentSize(align = Alignment.BottomStart) .offset(x = indicatorLeft) .width(indicatorRight - indicatorLeft) .padding(4.dp) .fillMaxSize() .border( BorderStroke(2.dp, color), RoundedCornerShape(4.dp) ) ) } /** * Shows a tab. * * @param icon The icon to be shown on this tab. * @param title The title to be shown on this tab. * @param onClick Called when this tab is clicked. * @param modifier The [Modifier]. */ @Composable private fun HomeTab( icon: ImageVector, title: String, onClick: () -> Unit, modifier: Modifier = Modifier ) { Row( modifier = modifier .clickable(onClick = onClick) .padding(16.dp), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Icon( imageVector = icon, contentDescription = null ) Spacer(modifier = Modifier.width(16.dp)) Text(text = title) } } /** * Shows the weather. * * @param onRefresh Called when the refresh icon button is clicked. */ @Composable private fun WeatherRow( onRefresh: () -> Unit ) { Row( modifier = Modifier .heightIn(min = 64.dp) .padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { Box( modifier = Modifier .size(48.dp) .clip(CircleShape) .background(Amber600) ) Spacer(modifier = Modifier.width(16.dp)) Text(text = stringResource(R.string.temperature), fontSize = 24.sp) Spacer(modifier = Modifier.weight(1f)) IconButton(onClick = onRefresh) { Icon( imageVector = Icons.Default.Refresh, contentDescription = stringResource(R.string.refresh) ) } } } /** * Shows the loading state of the weather. */ @Composable private fun LoadingRow() { // Creates an `InfiniteTransition` that runs infinite child animation values. val infiniteTransition = rememberInfiniteTransition() val alpha by infiniteTransition.animateFloat( initialValue = 0f, targetValue = 1f, // `infiniteRepeatable` repeats the specified duration-based `AnimationSpec` infinitely. animationSpec = infiniteRepeatable( // The `keyframes` animates the value by specifying multiple timestamps. animation = keyframes { // One iteration is 1000 milliseconds. durationMillis = 1000 // 0.7f at the middle of an iteration. 0.7f at 500 }, // When the value finishes animating from 0f to 1f, it repeats by reversing the // animation direction. repeatMode = RepeatMode.Reverse ) ) Row( modifier = Modifier .heightIn(min = 64.dp) .padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { Box( modifier = Modifier .size(48.dp) .clip(CircleShape) .background(Color.LightGray.copy(alpha = alpha)) ) Spacer(modifier = Modifier.width(16.dp)) Box( modifier = Modifier .fillMaxWidth() .height(32.dp) .background(Color.LightGray.copy(alpha = alpha)) ) } } /** * Shows a row for one task. * * @param task The task description. * @param onRemove Called when the task is swiped away and removed. */ @Composable private fun TaskRow(task: String, onRemove: () -> Unit) { Surface( modifier = Modifier .fillMaxWidth() .swipeToDismiss(onRemove), elevation = 2.dp ) { Row( modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { Icon( imageVector = Icons.Default.Check, contentDescription = null ) Spacer(modifier = Modifier.width(16.dp)) Text( text = task, style = MaterialTheme.typography.body1 ) } } } /** * The modified element can be horizontally swiped away. * * @param onDismissed Called when the element is swiped to the edge of the screen. */ private fun Modifier.swipeToDismiss( onDismissed: () -> Unit ): Modifier = composed { // This `Animatable` stores the horizontal offset for the element. val offsetX = remember { Animatable(0f) } pointerInput(Unit) { // Used to calculate a settling position of a fling animation. val decay = splineBasedDecay<Float>(this) // Wrap in a coroutine scope to use suspend functions for touch events and animation. coroutineScope { while (true) { // Wait for a touch down event. val pointerId = awaitPointerEventScope { awaitFirstDown().id } // Interrupt any ongoing animation. offsetX.stop() // Prepare for drag events and record velocity of a fling. val velocityTracker = VelocityTracker() // Wait for drag events. awaitPointerEventScope { horizontalDrag(pointerId) { change -> // Record the position after offset val horizontalDragOffset = offsetX.value + change.positionChange().x launch { // Overwrite the `Animatable` value while the element is dragged. offsetX.snapTo(horizontalDragOffset) } // Record the velocity of the drag. velocityTracker.addPosition(change.uptimeMillis, change.position) // Consume the gesture event, not passed to external if (change.positionChange() != Offset.Zero) change.consume() } } // Dragging finished. Calculate the velocity of the fling. val velocity = velocityTracker.calculateVelocity().x // Calculate where the element eventually settles after the fling animation. val targetOffsetX = decay.calculateTargetValue(offsetX.value, velocity) // The animation should end as soon as it reaches these bounds. offsetX.updateBounds( lowerBound = -size.width.toFloat(), upperBound = size.width.toFloat() ) launch { if (targetOffsetX.absoluteValue <= size.width) { // Not enough velocity; Slide back to the default position. offsetX.animateTo(targetValue = 0f, initialVelocity = velocity) } else { // Enough velocity to slide away the element to the edge. offsetX.animateDecay(velocity, decay) // The element was swiped away. onDismissed() } } } } } // Apply the horizontal offset to the element. .offset { IntOffset(offsetX.value.roundToInt(), 0) } } @Preview @Composable private fun PreviewHomeTabBar() { HomeTabBar( backgroundColor = Purple100, tabPage = TabPage.Home, onTabSelected = {} ) } @Preview @Composable private fun PreviewHome() { AnimationCodelabTheme { Home() } }
apache-2.0
990336cead3f23a5845f2946beb495ff
33.471372
100
0.619515
4.947067
false
false
false
false
videgro/Ships
app/src/main/java/net/videgro/ships/activities/AugmentedRealityLocationActivity.kt
1
24703
package net.videgro.ships.activities import android.app.Activity import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.* import android.util.Log import android.view.LayoutInflater import android.view.View import android.widget.LinearLayout import androidx.annotation.RequiresApi import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.google.ar.core.TrackingState import com.google.ar.core.exceptions.CameraNotAvailableException import com.google.ar.core.exceptions.UnavailableException import com.google.ar.sceneform.Node import com.google.ar.sceneform.rendering.ViewRenderable import kotlinx.android.synthetic.main.activity_augmented_reality_location.* import kotlinx.android.synthetic.main.augmented_reality_location.view.* import net.videgro.ships.Analytics import net.videgro.ships.R import net.videgro.ships.SettingsUtils import net.videgro.ships.Utils import net.videgro.ships.ar.utils.AugmentedRealityLocationUtils import net.videgro.ships.ar.utils.AugmentedRealityLocationUtils.INITIAL_MARKER_SCALE_MODIFIER import net.videgro.ships.ar.utils.AugmentedRealityLocationUtils.INVALID_MARKER_SCALE_MODIFIER import net.videgro.ships.ar.utils.PermissionUtils import net.videgro.ships.fragments.internal.FragmentUtils import net.videgro.ships.fragments.internal.OpenDeviceResult import net.videgro.ships.listeners.ImagePopupListener import net.videgro.ships.listeners.ShipReceivedListener import net.videgro.ships.nmea2ship.domain.Ship import net.videgro.ships.services.NmeaClientService import uk.co.appoly.arcorelocation.LocationMarker import uk.co.appoly.arcorelocation.LocationScene import java.text.DateFormat import java.text.DecimalFormat import java.util.* import java.util.concurrent.CompletableFuture @RequiresApi(Build.VERSION_CODES.N) class AugmentedRealityLocationActivity : AppCompatActivity(), ShipReceivedListener, ImagePopupListener { private val TAG = "ARLocationActivity" private val IMAGE_POPUP_ID_OPEN_RTLSDR_ERROR = 1102 private val IMAGE_POPUP_ID_IGNORE = 1109 private val IMAGE_POPUP_ID_AIS_RUNNING = 1110 private val IMAGE_POPUP_ID_START_AR_ERROR = 1111 private val IMAGE_POPUP_ID_REQUEST_PERMISSIONS = 1112 private val IMAGE_POPUP_ID_ACCURACY_MSG_SHOWN = 1113 private val REQ_CODE_START_RTLSDR = 1201 private val REQ_CODE_STOP_RTLSDR = 1202 // Our ARCore-Location scene private var locationScene: LocationScene? = null private var arHandler = Handler(Looper.getMainLooper()) lateinit var loadingDialog: AlertDialog private val resumeArElementsTask = Runnable { locationScene?.resume() arSceneView.resume() } private var shipsMap: HashMap<Int, Ship> = hashMapOf() private var markers: HashMap<Int, LocationMarker> = hashMapOf(); private var areAllMarkersLoaded = false private var triedToReceiveFromAntenna = false private var nmeaClientService: NmeaClientService? = null private var nmeaClientServiceConnection: ServiceConnection? = null /* Only render markers when ship is within this distance (meters) */ private var maxDistance=0 /* Remove ship from list of ships to render when last update is older than this value (in milliseconds) */ private var maxAge=0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val error=AugmentedRealityLocationUtils.checkAvailability(this); if (error.isEmpty()) { setContentView(R.layout.activity_augmented_reality_location) setupLoadingDialog() setupNmeaClientService() } else { // Not possible to start AR Log.e( TAG, error ) Analytics.logEvent( this, Analytics.CATEGORY_AR_ERRORS, TAG, error ) finish(); } } override fun onResume() { super.onResume() shipsMap.clear() maxDistance = SettingsUtils.getInstance().parseFromPreferencesArMaxDistance() maxAge = SettingsUtils.getInstance().parseFromPreferencesArMaxAge()*1000*60 checkAndRequestPermissions() } override fun onStart() { super.onStart() informationAccuracyMessage() } override fun onPause() { super.onPause() // Count number of rendered markers at THIS moment and log it var numMarkers=0 markers.values.forEach{marker -> if (marker.anchorNode!=null) numMarkers++ } val msg="Rendered markers on pause: "+numMarkers+" ("+shipsMap.size+")" Log.i( TAG, msg ) Analytics.logEvent( this, Analytics.CATEGORY_AR, TAG, msg ) arSceneView.session?.let { locationScene?.pause() arSceneView?.pause() } } override fun onDestroy() { destroyNmeaClientService() super.onDestroy() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) Log.i( TAG, "onActivityResult requestCode: $requestCode, resultCode: $resultCode" ) when (requestCode) { REQ_CODE_START_RTLSDR -> { val startRtlSdrResultAsString = FragmentUtils.parseOpenCloseDeviceActivityResultAsString(data) Analytics.logEvent( this, Analytics.CATEGORY_RTLSDR_DEVICE, OpenDeviceResult.TAG,startRtlSdrResultAsString + " - " + Utils.retrieveAbi() ) logStatus(startRtlSdrResultAsString) if (resultCode != Activity.RESULT_OK) { Utils.showPopup( IMAGE_POPUP_ID_OPEN_RTLSDR_ERROR, this, this, getString(R.string.popup_start_device_failed_title), getString(R.string.popup_start_device_failed_message) + " " + startRtlSdrResultAsString, R.drawable.thumbs_down_circle, null ) } else { FragmentUtils.rtlSdrRunning = true val msg = getString(R.string.popup_receiving_ais_message) logStatus(msg) Utils.showPopup( IMAGE_POPUP_ID_AIS_RUNNING, this, this, getString(R.string.popup_receiving_ais_title), msg, R.drawable.ic_information, null ) // On dismiss: Will continue onImagePopupDispose } } REQ_CODE_STOP_RTLSDR -> { logStatus(FragmentUtils.parseOpenCloseDeviceActivityResultAsString(data)) FragmentUtils.rtlSdrRunning = false } else -> Log.e( TAG, "Unexpected request code: $requestCode" ) } } private fun informationAccuracyMessage(){ Utils.showPopup( IMAGE_POPUP_ID_ACCURACY_MSG_SHOWN, this, this, getString(R.string.popup_ar_accuracy_title), getString(R.string.popup_ar_accuracy_message), R.drawable.ic_information, 30000 ) // On dismiss: Will continue onImagePopupDispose } private fun startReceivingAisFromAntenna() { val tag = "startReceivingAisFromAntenna - " if (!triedToReceiveFromAntenna && !FragmentUtils.rtlSdrRunning) { val ppm = SettingsUtils.getInstance().parseFromPreferencesRtlSdrPpm() if (SettingsUtils.isValidPpm(ppm)) { triedToReceiveFromAntenna = true val startResult = FragmentUtils.startReceivingAisFromAntenna(this, REQ_CODE_START_RTLSDR, ppm) logStatus((if (startResult) "Requested" else "Failed") + " to receive AIS from antenna (PPM: " + ppm + ").") // On positive result: Will continue at onActivityResult (REQ_CODE_START_RTLSDR) } else { Log.e(TAG, tag + "Invalid PPM: " + ppm) } } else { val msg = getString(R.string.popup_receiving_ais_message) logStatus(msg) Utils.showPopup( IMAGE_POPUP_ID_AIS_RUNNING, this, this, getString(R.string.popup_receiving_ais_title), msg, R.drawable.ic_information, null ) // On dismiss: Will continue onImagePopupDispose } } private fun logStatus(status: String) { //Utils.logStatus(getActivity(), logTextView, status) } private fun setupNmeaClientService() { val tag = "setupNmeaClientService - " nmeaClientServiceConnection = this.NmeaClientServiceConnection(this as ShipReceivedListener?) val serviceIntent = Intent(this, NmeaClientService::class.java) // On Android 8+ let service run in foreground if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForegroundService(serviceIntent) } else { startService(serviceIntent) } this.bindService( Intent(this, NmeaClientService::class.java), nmeaClientServiceConnection!!, Context.BIND_AUTO_CREATE ) } private fun destroyNmeaClientService() { if (nmeaClientService != null) { nmeaClientService!!.removeListener(this) } val nmeaClientServiceConnectionLocal = nmeaClientServiceConnection if (nmeaClientServiceConnectionLocal != null) { this.unbindService(nmeaClientServiceConnectionLocal) nmeaClientServiceConnection = null } } private fun setupLoadingDialog() { val alertDialogBuilder = AlertDialog.Builder(this) val dialogHintMainView = LayoutInflater.from(this).inflate(R.layout.loading_dialog, null) as LinearLayout alertDialogBuilder.setView(dialogHintMainView) loadingDialog = alertDialogBuilder.create() loadingDialog.setCanceledOnTouchOutside(false) } private fun setupSession():String{ var error:String=""; try { val session = AugmentedRealityLocationUtils.setupSession(this) if (session != null) { arSceneView.setupSession(session) } } catch (e: UnavailableException) { error = AugmentedRealityLocationUtils.handleSessionException(this, e) } return error } private fun setupLocationScene(){ locationScene = LocationScene(this, arSceneView) locationScene!!.setMinimalRefreshing(true) locationScene!!.setOffsetOverlapping(true) // locationScene!!.setRemoveOverlapping(true) locationScene!!.anchorRefreshInterval = 2000 } private fun createSession() { var error:String=""; if (arSceneView != null) { if (arSceneView.session == null) { error=setupSession() } if (error.isEmpty()) { if (locationScene == null) { setupLocationScene() } try { resumeArElementsTask.run() } catch (e: CameraNotAvailableException) { error=getString(R.string.popup_camera_open_error_message); } } } else { error=getString(R.string.popup_ar_error_arsceneview_not_set); } if (!error.isEmpty()){ Analytics.logEvent( this, Analytics.CATEGORY_AR_ERRORS, TAG, error ) Utils.showPopup( IMAGE_POPUP_ID_START_AR_ERROR, this, this, getString(R.string.popup_ar_error_title), error, R.drawable.thumbs_down_circle, null ) // On dismiss: Will continue onImagePopupDispose } } private fun render() { setupAndRenderMarkers() updateMarkers() } private fun setupAndRenderMarkers() { shipsMap.forEach { key, ship -> val completableFutureViewRenderable = ViewRenderable.builder() .setView(this, R.layout.augmented_reality_location) .build() CompletableFuture.anyOf(completableFutureViewRenderable) .handle<Any> { _, throwable -> //here we know the renderable was built or not if (throwable != null) { // handle renderable load fail return@handle null } try { val oldMarker = markers.get(ship.mmsi); val marker = LocationMarker( ship.lon, ship.lat, setNode(ship, completableFutureViewRenderable) ) marker.setOnlyRenderWhenWithin(maxDistance) markers.put(ship.mmsi, marker); arHandler.postDelayed({ // Remember old height, to prevent jumping markers marker.height=if (oldMarker != null) oldMarker.height else 0f; // First add marker, before eventually removing the old one to prevent blinking markers attachMarkerToScene( marker, completableFutureViewRenderable.get().view ) if (oldMarker != null) { removeMarkerFromScene(oldMarker,completableFutureViewRenderable.get().view) } if (shipsMap.values.indexOf(ship) == shipsMap.size - 1) { areAllMarkersLoaded = true } }, 200) } catch (e: Exception) { Log.e(TAG, e.toString()); } null } } } private fun updateMarkers() { arSceneView.scene.addOnUpdateListener() { if (!areAllMarkersLoaded) { return@addOnUpdateListener } locationScene?.mLocationMarkers?.forEach { locationMarker -> if (locationMarker.height==0f) { // There is no elevation information of vessels available, just generate a random height based on distance locationMarker.height = AugmentedRealityLocationUtils.generateRandomHeightBasedOnDistance( locationMarker?.anchorNode?.distance ?: 0 ) } } val frame = arSceneView!!.arFrame ?: return@addOnUpdateListener if (frame.camera.trackingState != TrackingState.TRACKING) { return@addOnUpdateListener } locationScene!!.processFrame(frame) } } private fun removeMarkerFromScene( locationMarker: LocationMarker, layoutRendarable: View ) { resumeArElementsTask.run { locationMarker.anchorNode?.isEnabled = false locationScene?.mLocationMarkers?.remove(locationMarker) arHandler.post { locationScene?.refreshAnchors() layoutRendarable.pinContainer.visibility = View.VISIBLE } } } private fun attachMarkerToScene( locationMarker: LocationMarker, layoutRendarable: View ) { resumeArElementsTask.run { locationMarker.scalingMode = LocationMarker.ScalingMode.FIXED_SIZE_ON_SCREEN locationMarker.scaleModifier = INITIAL_MARKER_SCALE_MODIFIER locationScene?.mLocationMarkers?.add(locationMarker) locationMarker.anchorNode?.isEnabled = true arHandler.post { locationScene?.refreshAnchors() layoutRendarable.pinContainer.visibility = View.VISIBLE } } locationMarker.setRenderEvent { locationNode -> layoutRendarable.distance.text = AugmentedRealityLocationUtils.showDistance(locationNode.distance) resumeArElementsTask.run { computeNewScaleModifierBasedOnDistance(locationMarker, locationNode.distance) } } } private fun computeNewScaleModifierBasedOnDistance( locationMarker: LocationMarker, distance: Int ) { val scaleModifier = AugmentedRealityLocationUtils.getScaleModifierBasedOnRealDistance(distance) return if (scaleModifier == INVALID_MARKER_SCALE_MODIFIER) { detachMarker(locationMarker) } else { locationMarker.scaleModifier = scaleModifier } } private fun detachMarker(locationMarker: LocationMarker) { locationMarker.anchorNode?.anchor?.detach() locationMarker.anchorNode?.isEnabled = false locationMarker.anchorNode = null } private fun setNode( ship: Ship, completableFuture: CompletableFuture<ViewRenderable> ): Node { val node = Node() node.renderable = completableFuture.get() val nodeLayout = completableFuture.get().view val name = nodeLayout.name val markerLayoutContainer = nodeLayout.pinContainer name.text = ship.name + " (" + ship.mmsi + ")" markerLayoutContainer.visibility = View.GONE nodeLayout.setOnTouchListener { _, _ -> val title = ship.name + " (" + ship.mmsi + ")"; var msg = getString(R.string.ships_table_country) + ship.countryName + "<br />" msg += getString(R.string.ships_table_callsign) + ship.callsign + "<br />" msg += getString(R.string.ships_table_type) + ship.shipType + "<br />" msg += getString(R.string.ships_table_destination) + ship.dest + "<br />" msg += getString(R.string.ships_table_navigation_status) + ship.navStatus + "<br />" msg += getString(R.string.ships_table_speed) + ship.sog + " knots<br />" msg += getString(R.string.ships_table_draught) + ship.draught + " meters/10<br />" msg += getString(R.string.ships_table_heading) + ship.heading + " degrees<br />" msg += getString(R.string.ships_table_course) + DecimalFormat("#.#").format(ship.cog / 10.toLong()) + " degrees<br />" msg += "<h3>" + getString(R.string.ships_table_head_position) + "</h3>" msg += " - " + getString(R.string.ships_table_latitude) + DecimalFormat("#.###").format(ship.lat) + "<br />" msg += " - " + getString(R.string.ships_table_longitude) + DecimalFormat("#.###").format(ship.lon) + "<br />" msg += "<h3>" + getString(R.string.ships_table_head_dimensions) + "</h3>" msg += " - " + getString(R.string.ships_table_dim_bow) + ship.dimBow + " meters<br />" msg += " - " + getString(R.string.ships_table_dim_port) + ship.dimPort + " meters<br />" msg += " - " + getString(R.string.ships_table_dim_starboard) + ship.dimStarboard + " meters<br />" msg += " - " + getString(R.string.ships_table_dim_stern) + ship.dimStern + " meters<br /><br />" msg += getString(R.string.ships_table_updated) + DateFormat.getDateTimeInstance().format(ship.timestamp) + " (age: " + (Calendar.getInstance().timeInMillis - ship.timestamp) + " ms)<br />" msg += getString(R.string.ships_table_source) + ship.source; Utils.showPopup( IMAGE_POPUP_ID_IGNORE, this, this, title, msg, R.drawable.ic_information, null ) // On dismiss: Will continue onImagePopupDispose false } Glide.with(this) .load("file:///android_asset/images/flags/" + ship.countryFlag + ".png") .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC) .into(nodeLayout.arMarkerCountry) return node } private fun checkAndRequestPermissions() { if (!PermissionUtils.hasLocationAndCameraPermissions(this)) { PermissionUtils.requestCameraAndLocationPermissions(this) } else { createSession() } } /** * Remove old ships from map */ private fun cleanUpShipsMap() { val now=Calendar.getInstance().timeInMillis; val cleanedShipsMap: HashMap<Int, Ship> = hashMapOf() shipsMap.forEach { key, ship -> if ((now - ship.timestamp) < maxAge) { cleanedShipsMap.put(ship.mmsi,ship) } } shipsMap=cleanedShipsMap; } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, results: IntArray ) { if (!PermissionUtils.hasLocationAndCameraPermissions(this)) { Utils.showPopup( IMAGE_POPUP_ID_REQUEST_PERMISSIONS, this, this, getString(R.string.popup_camera_and_location_permission_request_title), getString(R.string.popup_camera_and_location_permission_request_message), R.drawable.thumbs_down_circle, null ) // On dismiss: Will continue onImagePopupDispose } } /**** START ImagePopupListener */ override fun onImagePopupDispose(id: Int) { when (id) { IMAGE_POPUP_ID_ACCURACY_MSG_SHOWN -> { startReceivingAisFromAntenna() } IMAGE_POPUP_ID_OPEN_RTLSDR_ERROR -> { // Ignore this error. User can still receive Ships from peers } IMAGE_POPUP_ID_AIS_RUNNING -> { // AIS is running, invite to share data to cloud } IMAGE_POPUP_ID_START_AR_ERROR -> { // Not possible to start AR, exit activity finish(); } IMAGE_POPUP_ID_REQUEST_PERMISSIONS -> { if (!PermissionUtils.shouldShowRequestPermissionRationale(this)) { // Permission denied with checking "Do not ask again". PermissionUtils.launchPermissionSettings(this) } finish() } else -> Log.d(TAG, "onImagePopupDispose - id: $id") } } /**** END ImagePopupListener ****/ /**** START NmeaReceivedListener ****/ override fun onShipReceived(ship: Ship?) { if (ship != null) { shipsMap.put(ship.mmsi, ship) } cleanUpShipsMap() runOnUiThread(Runnable { arNumberOfShipsInView.setText(getString(R.string.ar_number_ships,shipsMap.size)) areAllMarkersLoaded = false // locationScene!!.clearMarkers() render() }) } /**** END NmeaListener ****/ inner class NmeaClientServiceConnection internal constructor(private val listener: ShipReceivedListener?) : ServiceConnection { private val tag = "NmeaCltServiceConn - " override fun onServiceConnected( className: ComponentName, service: IBinder ) { if (service is NmeaClientService.ServiceBinder) { Log.d(tag, "onServiceConnected") var localNmeaClientService = nmeaClientService; localNmeaClientService = service.service localNmeaClientService.addListener(listener) nmeaClientService = localNmeaClientService } } override fun onServiceDisconnected(className: ComponentName) { nmeaClientService = null } } }
gpl-2.0
abc113f28ed0687cf8cbe85d79b4b249
36.601218
200
0.585394
4.795768
false
false
false
false
MaibornWolff/codecharta
analysis/parser/RawTextParser/src/main/kotlin/de/maibornwolff/codecharta/parser/rawtextparser/ParserDialog.kt
1
2968
package de.maibornwolff.codecharta.parser.rawtextparser import com.github.kinquirer.KInquirer import com.github.kinquirer.components.promptConfirm import com.github.kinquirer.components.promptInput import com.github.kinquirer.components.promptInputNumber import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface import java.math.BigDecimal class ParserDialog { companion object : ParserDialogInterface { override fun collectParserArgs(): List<String> { val inputFileName = KInquirer.promptInput( message = "What is the file (.txt) or folder that has to be parsed?", ) val outputFileName: String = KInquirer.promptInput( message = "What is the name of the output file?", ) val isCompressed = (outputFileName.isEmpty()) || KInquirer.promptConfirm( message = "Do you want to compress the output file?", default = true ) val verbose: Boolean = KInquirer.promptConfirm(message = "Do you want to suppress command line output?", default = false) val metrics: String = KInquirer.promptInput( message = "What are the metrics to import (comma separated)?", hint = "metric1, metric2, metric3 (leave empty for all metrics)" ) val tabWidth: BigDecimal = KInquirer.promptInputNumber(message = "What is the tab width used (estimated if not provided)?") val maxIndentationLevel: BigDecimal = KInquirer.promptInputNumber(message = "What is the maximum Indentation Level?", default = "10", hint = "10") val exclude: String = KInquirer.promptInput(message = "Do you want to exclude file/folder according to regex pattern?", default = "", hint = "regex1, regex2.. (leave empty if you don't want to exclude anything)") val fileExtensions: String = KInquirer.promptInput(message = "Do you want to exclude file/folder according to regex pattern?", default = "", hint = "regex1, regex2.. (leave empty if you don't want to exclude anything)") val withoutDefaultExcludes: Boolean = KInquirer.promptConfirm(message = "Do you want to include build, target, dist, resources and out folders as well as files/folders starting with '.'?", default = false) return listOfNotNull( inputFileName, "--output-file=$outputFileName", if (isCompressed) null else "--not-compressed", "--verbose=$verbose", "--metrics=$metrics", "--tab-width=$tabWidth", "--max-indentation-level=$maxIndentationLevel", "--exclude=$exclude", "--file-extensions=$fileExtensions", "--without-default-excludes=$withoutDefaultExcludes", ) } } }
bsd-3-clause
ba3cd8ebee5b27f16d5c2b74d2dd14e3
46.111111
206
0.625674
5.271758
false
false
false
false
LorittaBot/Loritta
pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/services/ServerConfigsService.kt
1
4643
package net.perfectdreams.loritta.cinnamon.pudding.services import net.perfectdreams.loritta.common.utils.LorittaPermission import net.perfectdreams.loritta.cinnamon.pudding.Pudding import net.perfectdreams.loritta.cinnamon.pudding.data.* import net.perfectdreams.loritta.cinnamon.pudding.entities.PuddingServerConfigRoot import net.perfectdreams.loritta.cinnamon.pudding.tables.servers.ServerConfigs import net.perfectdreams.loritta.cinnamon.pudding.tables.servers.ServerRolePermissions import net.perfectdreams.loritta.cinnamon.pudding.tables.servers.moduleconfigs.* import net.perfectdreams.loritta.cinnamon.pudding.utils.exposed.selectFirstOrNull import net.perfectdreams.loritta.common.utils.PunishmentAction import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.select import java.util.* class ServerConfigsService(private val pudding: Pudding) : Service(pudding) { suspend fun getServerConfigRoot(guildId: ULong): PuddingServerConfigRoot? = pudding.transaction { ServerConfigs.selectFirstOrNull { ServerConfigs.id eq guildId.toLong() }?.let { PuddingServerConfigRoot.fromRow(it) } } suspend fun getModerationConfigByGuildId(guildId: ULong): ModerationConfig? = pudding.transaction { ModerationConfigs.innerJoin(ServerConfigs).selectFirstOrNull { ServerConfigs.id eq guildId.toLong() }?.let { ModerationConfig.fromRow(it) } } suspend fun getMessageForPunishmentTypeOnGuildId(guildId: ULong, punishmentAction: PunishmentAction): String? = pudding.transaction { val moderationConfig = getModerationConfigByGuildId(guildId) val moderationPunishmentMessageConfig = ModerationPunishmentMessagesConfig.selectFirstOrNull { ModerationPunishmentMessagesConfig.guild eq guildId.toLong() and (ModerationPunishmentMessagesConfig.punishmentAction eq punishmentAction) } moderationPunishmentMessageConfig?.get(ModerationPunishmentMessagesConfig.punishLogMessage) ?: moderationConfig?.punishLogMessage } suspend fun getPredefinedPunishmentMessagesByGuildId(guildId: ULong) = pudding.transaction { ModerationPredefinedPunishmentMessages.select { ModerationPredefinedPunishmentMessages.guild eq guildId.toLong() }.map { PredefinedPunishmentMessage(it[ModerationPredefinedPunishmentMessages.short], it[ModerationPredefinedPunishmentMessages.message]) } } suspend fun getStarboardConfigById(id: Long): StarboardConfig? = pudding.transaction { StarboardConfigs.selectFirstOrNull { StarboardConfigs.id eq id }?.let { StarboardConfig.fromRow(it) } } suspend fun getMiscellaneousConfigById(id: Long): MiscellaneousConfig? { return pudding.transaction { MiscellaneousConfigs.selectFirstOrNull { MiscellaneousConfigs.id eq id } }?.let { MiscellaneousConfig.fromRow(it) } } suspend fun getInviteBlockerConfigById(id: Long): InviteBlockerConfig? { return pudding.transaction { InviteBlockerConfigs.selectFirstOrNull { InviteBlockerConfigs.id eq id } }?.let { InviteBlockerConfig.fromRow(it) } } /** * Gets the [LorittaPermission] that the [roleIds] on [guildId] has. */ suspend fun getLorittaPermissionsOfRoles(guildId: ULong, roleIds: List<ULong>): Map<Long, EnumSet<LorittaPermission>> { if (roleIds.isEmpty()) return emptyMap() return pudding.transaction { // Pull the permissions from the database val permissions = ServerRolePermissions.select { ServerRolePermissions.guild eq guildId.toLong() and (ServerRolePermissions.roleId inList roleIds.map { it.toLong() }) } // Create a enum set val enumSet = permissions .asSequence() .map { it[ServerRolePermissions.roleId] to it[ServerRolePermissions.permission] } .groupBy { it.first } .map { it.key to it.value.map { it.second } } .associate { it.first to EnumSet.copyOf(it.second) } return@transaction enumSet } } /** * Checks if the [roleIds] on [guildId] has all the [permission]. */ suspend fun hasLorittaPermission(guildId: ULong, roleIds: List<ULong>, vararg permission: LorittaPermission): Boolean { val permissions = getLorittaPermissionsOfRoles(guildId, roleIds) return permissions.values.any { permission.all { perm -> it.contains(perm) } } } }
agpl-3.0
0e6122c7f1abe7db5fbc2dc26861b99e
44.529412
141
0.711824
4.629113
false
true
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/appointment/view/inclient_list.kt
1
2113
package at.cpickl.gadsu.appointment.view import at.cpickl.gadsu.appointment.Appointment import at.cpickl.gadsu.appointment.DeleteAppointmentEvent import at.cpickl.gadsu.appointment.OpenAppointmentEvent import at.cpickl.gadsu.service.formatDateTimeSemiLong import at.cpickl.gadsu.view.ViewNames import at.cpickl.gadsu.view.components.CellView import at.cpickl.gadsu.view.components.DefaultCellView import at.cpickl.gadsu.view.components.MyList import at.cpickl.gadsu.view.components.MyListCellRenderer import at.cpickl.gadsu.view.components.MyListModel import at.cpickl.gadsu.view.swing.transparent import com.github.christophpickl.kpotpourri.common.string.htmlize import com.google.common.eventbus.EventBus import java.awt.GridBagConstraints import javax.inject.Inject import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel class AppointmentList @Inject constructor( bus: EventBus ) : MyList<Appointment>( ViewNames.Appointment.ListInClientView, MyListModel<Appointment>(), bus, object : MyListCellRenderer<Appointment>() { override fun newCell(value: Appointment) = AppointmentCell(value) } ) { init { initSinglePopup("L\u00f6schen", ::DeleteAppointmentEvent) initDoubleClicked(::OpenAppointmentEvent) initEnterPressed(::OpenAppointmentEvent) } } class AppointmentCell(val appointment: Appointment) : DefaultCellView<Appointment>(appointment), CellView { private val lblDate = JLabel(appointment.start.formatDateTimeSemiLong()) private val hasNoteIndicator = JLabel(" [...]") override val applicableForegrounds: Array<JComponent> = arrayOf(lblDate, hasNoteIndicator) init { c.anchor = GridBagConstraints.NORTHWEST add(lblDate) if (appointment.note.isNotEmpty()) { toolTipText = appointment.note.htmlize() c.gridx++ add(hasNoteIndicator) } // fill UI hack ;) c.gridx++ c.weightx = 1.0 c.fill = GridBagConstraints.HORIZONTAL add(JPanel().transparent()) } }
apache-2.0
479cd53ebb7c1b3cc88f6cb965ae72d8
32.015625
107
0.734027
4.303462
false
false
false
false
YounesRahimi/java-utils
src/main/java/ir/iais/utilities/javautils/validators/annotations/Required.kt
2
1903
package ir.iais.utilities.javautils.validators.annotations import java.util.* import javax.validation.Constraint import javax.validation.ConstraintValidator import javax.validation.ConstraintValidatorContext import javax.validation.Payload import kotlin.reflect.KClass /** * Validation annotation to globalValidate that 2 fields have the same value. An array of fields and * their matching confirmation fields can be supplied. * * * Example, compare 1 pair of fields: @FieldMatch(first = "password", second = "confirmPassword", * message = "The password fields must match") * * * Example, compare more than 1 pair of fields: @FieldMatch.List({ @FieldMatch(first = * "password", second = "confirmPassword", message = "The password fields must * match"), @FieldMatch(first = "email", second = "confirmEmail", message = "The email fields must * match")}) */ @Target(AnnotationTarget.FIELD) //@Retention(RUNTIME) @kotlin.annotation.Retention //@Repeatable(List::class) @Repeatable @Constraint(validatedBy = [RequiredValidator::class]) @MustBeDocumented annotation class Required(val message: String = NonEmptyValidator.MESSAGE, val groups: Array<KClass<*>> = [], val payload: Array<KClass<Payload>> = [] ) open class RequiredValidator : ConstraintValidator<Required, Any?> { override fun initialize(constraintAnnotation: Required) { } override fun isValid(value: Any?, context: ConstraintValidatorContext): Boolean = hasValue(value) private fun hasValue(obj: Any?): Boolean = when (obj) { null -> false is String -> obj.isNotEmpty() is Collection<*> -> obj.isNotEmpty() is Optional<*> -> obj.isPresent is Enum<*> -> obj.name.toUpperCase() != "UNKNOWN" else -> true } companion object { const val MESSAGE = "error.required" } }
gpl-3.0
7b4592eac01d7b1ff0bf9329df929a1a
33
101
0.687336
4.477647
false
false
false
false
spark/photon-tinker-android
mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepCheckTargetDeviceHasThreadInterface.kt
1
1041
package io.particle.mesh.setup.flow.setupsteps import io.particle.firmwareprotos.ctrl.Network.InterfaceType import io.particle.mesh.common.Result.Absent import io.particle.mesh.common.Result.Error import io.particle.mesh.common.Result.Present import io.particle.mesh.setup.flow.MeshSetupStep import io.particle.mesh.setup.flow.Scopes import io.particle.mesh.setup.flow.context.SetupContexts import io.particle.mesh.setup.flow.throwOnErrorOrAbsent import mu.KotlinLogging class StepCheckTargetDeviceHasThreadInterface : MeshSetupStep() { private val log = KotlinLogging.logger {} override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) { if (ctxs.mesh.hasThreadInterface != null) { return } val response = ctxs.requireTargetXceiver().sendGetInterfaceList().throwOnErrorOrAbsent() val hasThreadInterface = null != response.interfacesList.firstOrNull { it.type == InterfaceType.THREAD } ctxs.mesh.hasThreadInterface = hasThreadInterface } }
apache-2.0
62f175a362ec4a6feb7c232996f8bca0
32.612903
96
0.757925
4.3375
false
false
false
false
idanarye/nisui
gui/src/main/kotlin/nisui/gui/TablePanel.kt
1
3803
package nisui.gui import kotlin.reflect.* import kotlin.reflect.jvm.* import javax.swing.* import javax.swing.event.* import javax.swing.table.* import javax.swing.border.Border import java.awt.BorderLayout import java.awt.Color import java.awt.Dimension import java.awt.event.KeyEvent import java.awt.event.ActionEvent abstract class TablePanel<T>: JScrollPane() { val table = JTable() val tableModel: AbstractTableModel val columns = mutableListOf<Column<T, *>>() open fun makeBorder(): Border? = null protected abstract fun getRowsSource(): List<T>; protected abstract fun addNewEntry(): T; protected abstract fun deleteEntry(index: Int); protected abstract fun populateColumns(); init { setViewportView(table) makeBorder()?.let(::setBorder) table.setFillsViewportHeight(true) populateColumns() setMinimumSize(Dimension(100 * columns.size, 100)) tableModel = object: AbstractTableModel() { override fun getColumnCount(): Int { return columns.size } override fun getColumnName(col: Int): String = columns[col].caption override fun getRowCount(): Int = getRowsSource().size + 1 override fun getValueAt(row: Int, col: Int): Any? { val item = getRowsSource().getOrNull(row) if (item == null) { return null } return columns[col].getter(item) } override fun isCellEditable(row: Int, col: Int) = columns[col].setter != null override fun setValueAt(value: Any, row: Int, col: Int) { val item = if (row == getRowsSource().size) { val newEntry = addNewEntry() fireTableChanged(TableModelEvent(this, row, row, TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT)); newEntry } else { getRowsSource()[row] } columns[col].invokeSetter(item, value) fireTableCellUpdated(row, col) } override fun getColumnClass(col: Int): Class<*> { return columns[col].returnType() as Class<*> } } table.setModel(tableModel) for ((column, tableColumn) in columns zip table.getColumnModel().getColumns().toList()) { column.configTableColumn(tableColumn) } table.getInputMap(WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete") table.getActionMap().put("delete", object: AbstractAction() { override fun actionPerformed(e: ActionEvent) { val row = table.getSelectedRow() if (row < getRowsSource().size) { deleteEntry(row) tableModel.fireTableChanged(TableModelEvent(tableModel, row, row, TableModelEvent.ALL_COLUMNS, TableModelEvent.DELETE)); } } }) } } class Column<T, V>(val caption: String, val getter: T.() -> V, val setter: (T.(V) -> Unit)? = null) { fun invokeSetter(item: T, value: Any?) { val setter = setter!! item.setter(value as V) } fun returnType(): Class<V> { val getter = getter as KCallable<V> return getter.returnType.javaType as Class<V> } val tableCellEditor: TableCellEditor? init { if (returnType().isEnum()) { tableCellEditor = DefaultCellEditor(JComboBox(returnType().getEnumConstants())) } else { tableCellEditor = null } } fun configTableColumn(tableColumn: TableColumn) { if (tableCellEditor != null) { tableColumn.setCellEditor(tableCellEditor) } } }
mit
66cb6c2458886ef32b627fbbdf2ed61a
33.572727
140
0.591901
4.67199
false
false
false
false
wireapp/wire-android
storage/src/main/kotlin/com/waz/zclient/storage/db/assets/UploadAssetsEntity.kt
1
2994
package com.waz.zclient.storage.db.assets import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import java.util.Objects @Entity(tableName = "UploadAssets") data class UploadAssetsEntity( @PrimaryKey @ColumnInfo(name = "_id") val id: String, @ColumnInfo(name = "source", defaultValue = "") val source: String, @ColumnInfo(name = "name", defaultValue = "") val name: String, @ColumnInfo(name = "sha", typeAffinity = ColumnInfo.BLOB) val sha: ByteArray?, @ColumnInfo(name = "md5", typeAffinity = ColumnInfo.BLOB) val md5: ByteArray?, @ColumnInfo(name = "mime", defaultValue = "") val mime: String, @ColumnInfo(name = "preview", defaultValue = "") val preview: String, @ColumnInfo(name = "uploaded", defaultValue = "0") val uploaded: Long, @ColumnInfo(name = "size", defaultValue = "0") val size: Long, @ColumnInfo(name = "retention", defaultValue = "0") val retention: Int, @ColumnInfo(name = "public", defaultValue = "0") val isPublic: Boolean, @ColumnInfo(name = "encryption", defaultValue = "") val encryption: String, @ColumnInfo(name = "encryption_salt") val encryptionSalt: String?, @ColumnInfo(name = "details", defaultValue = "") val details: String, @ColumnInfo(name = "status", defaultValue = "0") val uploadStatus: Int, @ColumnInfo(name = "asset_id") val assetId: String? ) { @Suppress("ComplexMethod") override fun equals(other: Any?): Boolean = (other === this) || (other is UploadAssetsEntity && other.id == this.id && other.source == this.source && other.name == this.name && blobEquals(this.sha, other.sha) && blobEquals(this.md5, other.md5) && other.mime == this.mime && other.preview == this.preview && other.uploaded == this.uploaded && other.size == this.size && other.retention == this.retention && other.isPublic == this.isPublic && other.encryption == this.encryption && other.encryptionSalt == this.encryptionSalt && other.details == this.details && other.uploadStatus == this.uploadStatus && other.assetId == this.assetId) override fun hashCode(): Int { var result = Objects.hash(id, source, name, mime, preview, uploaded, size, retention, isPublic, encryption, encryptionSalt, details, uploadStatus, assetId) result = 31 * result + (md5?.contentHashCode() ?: 0) result = 31 * result + (sha?.contentHashCode() ?: 0) return result } private fun blobEquals(blob1: ByteArray?, blob2: ByteArray?): Boolean { return if (blob2 == null && blob1 == null) true else blob2 != null && blob1 != null && blob2.contentEquals(blob1) } }
gpl-3.0
6f26ead8e8faac4e91d4331d4ea781c1
31.543478
93
0.594856
4.277143
false
false
false
false
Ph1b/MaterialAudiobookPlayer
data/src/main/kotlin/de/ph1b/audiobook/data/repo/BookContentRepo.kt
1
1069
package de.ph1b.audiobook.data.repo import de.ph1b.audiobook.data.Book2 import de.ph1b.audiobook.data.BookContent2 import de.ph1b.audiobook.data.repo.internals.dao.BookContent2Dao import kotlinx.coroutines.flow.MutableStateFlow import javax.inject.Inject import javax.inject.Singleton @Singleton class BookContentRepo @Inject constructor( private val dao: BookContent2Dao ) { private val cache = MutableStateFlow(mapOf<Book2.Id, BookContent2?>()) suspend fun get(id: Book2.Id): BookContent2? { val cached = cache.value return if (cached.containsKey(id)) { cached[id] } else { val content = dao.byId(id) cache.value = cached.toMutableMap().apply { put(id, content) } content } } suspend fun put(content2: BookContent2) { cache.value = cache.value.toMutableMap().apply { dao.insert(content2) this[content2.id] = content2 } } suspend inline fun getOrPut(id: Book2.Id, defaultValue: () -> BookContent2): BookContent2 { return get(id) ?: defaultValue().also { put(it) } } }
lgpl-3.0
a5e7e50a403b46208e550ece4ebd6d77
25.073171
93
0.698784
3.575251
false
false
false
false
square/leakcanary
leakcanary-android-core/src/main/java/leakcanary/internal/Notifications.kt
2
4747
/* * Copyright (C) 2015 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 leakcanary.internal import android.Manifest.permission.POST_NOTIFICATIONS import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.os.Build.VERSION.SDK_INT import android.os.Build.VERSION_CODES.JELLY_BEAN import android.os.Build.VERSION_CODES.O import com.squareup.leakcanary.core.R import leakcanary.LeakCanary import leakcanary.internal.InternalLeakCanary.FormFactor.MOBILE import shark.SharkLog internal object Notifications { private var notificationPermissionRequested = false // Instant apps cannot show background notifications // See https://github.com/square/leakcanary/issues/1197 // TV devices can't show notifications. // Watch devices: not sure, but probably not a good idea anyway? val canShowNotification: Boolean get() { if (InternalLeakCanary.formFactor != MOBILE) { return false } if (InternalLeakCanary.isInstantApp || !InternalLeakCanary.applicationVisible) { return false } if (!LeakCanary.config.showNotifications) { return false } if (SDK_INT >= 33) { val application = InternalLeakCanary.application if (application.applicationInfo.targetSdkVersion >= 33) { val notificationManager = application.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (!notificationManager.areNotificationsEnabled()) { if (notificationPermissionRequested) { SharkLog.d { "Not showing notification: already requested missing POST_NOTIFICATIONS permission." } } else { SharkLog.d { "Not showing notification: requesting missing POST_NOTIFICATIONS permission." } application.startActivity( RequestPermissionActivity.createIntent( application, POST_NOTIFICATIONS ) ) notificationPermissionRequested = true } return false } if (notificationManager.areNotificationsPaused()) { SharkLog.d { "Not showing notification, notifications are paused." } return false } } } return true } @Suppress("LongParameterList") fun showNotification( context: Context, contentTitle: CharSequence, contentText: CharSequence, pendingIntent: PendingIntent?, notificationId: Int, type: NotificationType ) { if (!canShowNotification) { return } val builder = if (SDK_INT >= O) { Notification.Builder(context, type.name) } else Notification.Builder(context) builder .setContentText(contentText) .setContentTitle(contentTitle) .setAutoCancel(true) .setContentIntent(pendingIntent) val notification = buildNotification(context, builder, type) val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(notificationId, notification) } fun buildNotification( context: Context, builder: Notification.Builder, type: NotificationType ): Notification { builder.setSmallIcon(R.drawable.leak_canary_leak) .setWhen(System.currentTimeMillis()) if (SDK_INT >= O) { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager var notificationChannel: NotificationChannel? = notificationManager.getNotificationChannel(type.name) if (notificationChannel == null) { val channelName = context.getString(type.nameResId) notificationChannel = NotificationChannel(type.name, channelName, type.importance) notificationManager.createNotificationChannel(notificationChannel) } builder.setChannelId(type.name) builder.setGroup(type.name) } return if (SDK_INT < JELLY_BEAN) { @Suppress("DEPRECATION") builder.notification } else { builder.build() } } }
apache-2.0
307dd37feae1187e99a5dc9d6658fea4
32.907143
113
0.693912
5.071581
false
false
false
false
actions-on-google/appactions-fitness-kotlin
app/src/main/java/com/devrel/android/fitactions/model/FitActivity.kt
1
1909
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.devrel.android.fitactions.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey import com.devrel.android.fitactions.R /** * Entity that describes an activity performed by the user. * * This entity is used for the Room DB in the fit_activities table. */ @Entity( tableName = "fit_activities", indices = [Index("id")] ) data class FitActivity( @PrimaryKey @ColumnInfo(name = "id") val id: String, @ColumnInfo(name = "date") val date: Long, @ColumnInfo(name = "type") val type: Type = Type.UNKNOWN, @ColumnInfo(name = "distanceMeters") val distanceMeters: Double, @ColumnInfo(name = "durationMs") val durationMs: Long ) { /** * Defines the type of activity */ enum class Type(val nameId: Int) { UNKNOWN(R.string.activity_unknown), RUNNING(R.string.activity_running), WALKING(R.string.activity_walking), CYCLING(R.string.activity_cycling); companion object { /** * @return a FitActivity.Type that matches the given name */ fun find(type: String): Type { return values().find { it.name.equals(other = type, ignoreCase = true) } ?: UNKNOWN } } } }
apache-2.0
e0bb387a016f79ab749250962f0f8115
29.806452
99
0.667889
4.053079
false
false
false
false
google/horologist
audio-ui/src/main/java/com/google/android/horologist/audio/ui/components/animated/AnimatedSetVolumeButton.kt
1
3273
/* * 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.audio.ui.components.animated import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.wear.compose.material.Button import androidx.wear.compose.material.ButtonDefaults import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.rememberLottieAnimatable import com.airbnb.lottie.compose.rememberLottieComposition import com.google.android.horologist.audio.VolumeState import com.google.android.horologist.audio.ui.components.actions.SetVolumeButton /** * Button to launch a screen to control the system volume. * * See [VolumeState] */ @Composable public fun AnimatedSetVolumeButton( onVolumeClick: () -> Unit, volumeState: VolumeState, modifier: Modifier = Modifier ) { if (LocalStaticPreview.current) { SetVolumeButton( onVolumeClick = onVolumeClick, volumeState = volumeState, modifier = modifier ) } else { val volumeUp by rememberLottieComposition( spec = LottieCompositionSpec.Asset("lottie/VolumeUp.json") ) val volumeDown by rememberLottieComposition( spec = LottieCompositionSpec.Asset("lottie/VolumeDown.json") ) val lottieAnimatable = rememberLottieAnimatable() var lastVolume by remember { mutableStateOf(volumeState.current) } LaunchedEffect(volumeState) { val lastVolumeBefore = lastVolume lastVolume = volumeState.current if (volumeState.current > lastVolumeBefore) { lottieAnimatable.animate( iterations = 1, composition = volumeUp ) } else { lottieAnimatable.animate( iterations = 1, composition = volumeDown ) } } Button( modifier = modifier.size(ButtonDefaults.SmallButtonSize), onClick = onVolumeClick, colors = ButtonDefaults.iconButtonColors() ) { LottieAnimation( composition = volumeDown, modifier = Modifier.size(24.dp), progress = { lottieAnimatable.progress } ) } } }
apache-2.0
4551bf80fcd32c20418d17aa79fff8ad
34.193548
80
0.681027
4.79912
false
false
false
false
toastkidjp/Yobidashi_kt
app/src/main/java/jp/toastkid/yobidashi/search/url_suggestion/UrlItemQueryUseCase.kt
1
2087
/* * Copyright (c) 2021 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.search.url_suggestion import jp.toastkid.yobidashi.browser.UrlItem import jp.toastkid.yobidashi.browser.bookmark.model.BookmarkRepository import jp.toastkid.yobidashi.browser.history.ViewHistoryRepository import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * @author toastkidjp */ class UrlItemQueryUseCase( private val submitItems: (List<UrlItem>) -> Unit, private val bookmarkRepository: BookmarkRepository, private val viewHistoryRepository: ViewHistoryRepository, private val switchVisibility: (Boolean) -> Unit, private val rtsSuggestionUseCase: RtsSuggestionUseCase = RtsSuggestionUseCase(), private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main, private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO ) { operator fun invoke(q: CharSequence) { CoroutineScope(mainDispatcher).launch { val newItems = mutableListOf<UrlItem>() rtsSuggestionUseCase.invoke(q.toString()) { newItems.add(0, it) } withContext(ioDispatcher) { if (q.isBlank()) { return@withContext } bookmarkRepository.search("%$q%", ITEM_LIMIT).forEach { newItems.add(it) } } withContext(ioDispatcher) { viewHistoryRepository.search("%$q%", ITEM_LIMIT).forEach { newItems.add(it) } } switchVisibility(newItems.isNotEmpty()) submitItems(newItems) } } companion object { /** * Item limit. */ private const val ITEM_LIMIT = 3 } }
epl-1.0
6d37b3e12088e61544820964913b5eed
32.142857
93
0.689986
4.933806
false
false
false
false
herbeth1u/VNDB-Android
app/src/main/java/com/booboot/vndbandroid/dao/TagDao.kt
1
1411
package com.booboot.vndbandroid.dao import com.booboot.vndbandroid.model.vndb.Tag import io.objectbox.BoxStore import io.objectbox.annotation.Entity import io.objectbox.annotation.Id import io.objectbox.kotlin.boxFor import io.objectbox.relation.ToMany @Entity class TagDao() { @Id(assignable = true) var id: Long = 0 var name: String = "" var description: String = "" var meta: Boolean = false var vns: Int = 0 var cat: String = "" lateinit var aliases: ToMany<TagAlias> lateinit var parents: ToMany<TagParent> constructor(tag: Tag, boxStore: BoxStore) : this() { id = tag.id name = tag.name description = tag.description meta = tag.meta vns = tag.vns cat = tag.cat boxStore.boxFor<TagDao>().attach(this) tag.aliases.forEach { aliases.add(TagAlias(it.hashCode().toLong(), it)) } tag.parents.forEach { parents.add(TagParent(it)) } boxStore.boxFor<TagAlias>().put(aliases) boxStore.boxFor<TagParent>().put(parents) } fun toBo() = Tag( id, name, description, meta, vns, cat, aliases.map { it.alias }, parents.map { it.id } ) } @Entity data class TagAlias( @Id(assignable = true) var id: Long = 0, var alias: String = "" ) @Entity data class TagParent( @Id(assignable = true) var id: Long = 0 )
gpl-3.0
e2e7561956c0f26f4ef65a419b3b2111
23.344828
81
0.620128
3.65544
false
false
false
false
jtransc/jtransc
jtransc-utils/src/com/jtransc/lang/extra.kt
1
2337
package com.jtransc.lang import com.jtransc.ds.getOrPut2 import java.util.* import kotlin.reflect.KProperty interface Extra { var extra: HashMap<String, Any?>? class Mixin(override var extra: HashMap<String, Any?>? = null) : Extra @Suppress("UNCHECKED_CAST", "NOTHING_TO_INLINE") class Property<T : Any?>(val name: String? = null, val defaultGen: () -> T) { inline operator fun getValue(thisRef: Extra, property: KProperty<*>): T { val res = (thisRef.extra?.get(name ?: property.name) as T?) if (res == null) { val r = defaultGen() setValue(thisRef, property, r) return r } return res } inline operator fun setValue(thisRef: Extra, property: KProperty<*>, value: T): Unit = run { //beforeSet(value) if (thisRef.extra == null) thisRef.extra = hashMapOf() thisRef.extra?.set(name ?: property.name, value as Any?) //afterSet(value) } } class PropertyThis<in T2 : Extra, T : Any?>(val name: String? = null, val defaultGen: T2.() -> T) { inline operator fun getValue(thisRef: T2, property: KProperty<*>): T { val res = (thisRef.extra?.get(name ?: property.name) as T?) if (res == null) { val r = defaultGen(thisRef) setValue(thisRef, property, r) return r } return res } inline operator fun setValue(thisRef: T2, property: KProperty<*>, value: T): Unit = run { //beforeSet(value) if (thisRef.extra == null) thisRef.extra = LinkedHashMap() thisRef.extra?.set(name ?: property.name, value as Any?) //afterSet(value) } } } @Suppress("UNCHECKED_CAST", "NOTHING_TO_INLINE") class extraProperty<T : Any?>(val default: () -> T) { inline operator fun getValue(thisRef: Extra, property: KProperty<*>): T = (thisRef.extra?.get(property.name) as T?) ?: default() inline operator fun setValue(thisRef: Extra, property: KProperty<*>, value: T): Unit = run { if (thisRef.extra == null) thisRef.extra = LinkedHashMap() thisRef.extra?.set(property.name, value as Any?) } } @Suppress("UNCHECKED_CAST", "NOTHING_TO_INLINE") class weakExtra<T : Any?>(val default: () -> T) { val map = WeakHashMap<Any?, T>() inline operator fun getValue(thisRef: Any, property: KProperty<*>): T { return map.getOrPut2(thisRef, default) } inline operator fun setValue(thisRef: Any, property: KProperty<*>, value: T): Unit = run { map.put(thisRef, value) } }
apache-2.0
ad003d25de04aaeb84ebf2c3bec1a36f
31.472222
129
0.666239
3.310198
false
false
false
false
minibugdev/Collaborate-Board
app/src/main/kotlin/com/trydroid/coboard/views/SimpleDrawView.kt
1
2749
package com.trydroid.coboard.views import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.MotionEvent import android.view.View typealias OnDrawListener = (List<Point>?) -> Unit /** * Customize form original source * - https://github.com/johncarl81/androiddraw/blob/master/src/main/java/org/example/androiddraw/SimpleDrawView.java * - https://github.com/ByoxCode/DrawView/blob/master/drawview/src/main/java/com/byox/drawview/views/DrawView.java * */ class SimpleDrawView(context: Context, attributeSet: AttributeSet) : View(context, attributeSet), View.OnTouchListener { private val mLineHistoryList: MutableList<MutableList<Point>> = mutableListOf() private val mPaint: Paint by lazy { Paint(Paint.ANTI_ALIAS_FLAG).apply { strokeWidth = STROKE_WIDTH style = Paint.Style.STROKE color = Color.RED } } var drawListener: OnDrawListener? = null init { isFocusable = true isFocusableInTouchMode = true this.setOnTouchListener(this) } override fun onDraw(canvas: Canvas) { mLineHistoryList.forEach { line -> if (line.size == 1) { onDrawPoint(canvas, line) } else { onDrawLine(canvas, line) } } } override fun onTouch(view: View, event: MotionEvent): Boolean { when (event.action) { MotionEvent.ACTION_DOWN -> { onTouchStart(event) } MotionEvent.ACTION_MOVE -> { onTouchMove(event) } MotionEvent.ACTION_UP -> { onTouchEnd() } } return true } fun clear() { mLineHistoryList.clear() invalidate() } fun drawLine(lineList: List<Point>) { mLineHistoryList.add(lineList.toMutableList()) invalidate() } private fun onDrawPoint(canvas: Canvas, line: MutableList<Point>) { line.firstOrNull() ?.let { point -> canvas.drawPoint(point.x.toFloat(), point.y.toFloat(), mPaint) } } private fun onDrawLine(canvas: Canvas, line: List<Point>) { val path = Path() line.forEachIndexed { index, point -> val x = point.x.toFloat() val y = point.y.toFloat() if (index == 0) { path.moveTo(x, y) } else { path.lineTo(x, y) } } canvas.drawPath(path, mPaint) } private fun onTouchStart(event: MotionEvent) { mLineHistoryList.add(mutableListOf()) addPointToCurrentLineHistory(event.x, event.y) invalidate() } private fun onTouchMove(event: MotionEvent) { addPointToCurrentLineHistory(event.x, event.y) invalidate() } private fun onTouchEnd() { drawListener?.invoke(mLineHistoryList.lastOrNull()) } private fun addPointToCurrentLineHistory(x: Float, y: Float) { Point().apply { this.x = x.toInt() this.y = y.toInt() }.let { point -> mLineHistoryList.last().add(point) } } companion object { private val STROKE_WIDTH = 4f } }
mit
e982638781b0ea7d0993a416b66e95d6
22.29661
120
0.698436
3.21897
false
false
false
false
KentVu/vietnamese-t9-ime
console/src/main/java/com/vutrankien/t9vietnamese/console/SortJava.kt
1
1442
/* * Vietnamese-t9-ime: T9 input method for Vietnamese. * Copyright (C) 2020 Vu Tran Kien. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.vutrankien.t9vietnamese.console import com.vutrankien.t9vietnamese.lib.VietnameseWordSeed.decomposeVietnamese import java.io.File import java.nio.file.Paths fun main(args: Array<String>) { val fromFile = File(args[0]) val wd = Paths.get("").toAbsolutePath() val toFile = File(fromFile.parent, "${fromFile.name}.sorted") println("Sorting file $fromFile wd=$toFile") val sorted = sortedSetOf<String>() fromFile.bufferedReader().useLines { lines -> lines.forEach { sorted.add(it.decomposeVietnamese()) } } toFile.bufferedWriter().use { writer -> sorted.forEach { writer.write(it + "\n") } } print("Written to $toFile") } class MyClass { }
gpl-3.0
d8617fb9eea2269cbf02362433047a8e
36
88
0.720527
3.794737
false
false
false
false
microg/android_packages_apps_GmsCore
play-services-location-core/src/main/java/org/microg/gms/location/UnifiedLocationProvider.kt
1
4224
package org.microg.gms.location import android.content.Context import android.location.Location import android.util.Log import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import org.microg.nlp.client.UnifiedLocationClient import java.util.* import java.util.concurrent.atomic.AtomicBoolean class UnifiedLocationProvider(context: Context?, changeListener: LocationChangeListener) { private val client: UnifiedLocationClient private var connectedMinTime: Long = 0 private var lastLocation: Location? = null private val connected = AtomicBoolean(false) private val changeListener: LocationChangeListener private val requests: MutableList<LocationRequestHelper> = ArrayList() private val listener: UnifiedLocationClient.LocationListener = object : UnifiedLocationClient.LocationListener { override fun onLocation(location: Location) { lastLocation = location changeListener.onLocationChanged() } } private var ready = false private val invokeOnceReady = hashSetOf<Runnable>() private fun updateLastLocation() { GlobalScope.launch(Dispatchers.Main) { Log.d(TAG, "unified network: requesting last location") val lastLocation = client.getLastLocation() Log.d(TAG, "unified network: got last location: $lastLocation") if (lastLocation != null) { [email protected] = lastLocation } synchronized(invokeOnceReady) { for (runnable in invokeOnceReady) { runnable.run() } ready = true } } } fun invokeOnceReady(runnable: Runnable) { synchronized(invokeOnceReady) { if (ready) runnable.run() else invokeOnceReady.add(runnable) } } fun addRequest(request: LocationRequestHelper) { Log.d(TAG, "unified network: addRequest $request") for (i in 0..requests.size) { if (i >= requests.size) break val req = requests[i] if (req.respondsTo(request.pendingIntent) || req.respondsTo(request.listener) || req.respondsTo(request.callback)) { requests.removeAt(i) } } requests.add(request) updateConnection() } fun removeRequest(request: LocationRequestHelper) { Log.d(TAG, "unified network: removeRequest $request") requests.remove(request) updateConnection() } fun getLastLocation(): Location? { if (lastLocation == null) { Log.d(TAG, "uh-ok: last location for unified network is null!") } return lastLocation } @Synchronized private fun updateConnection() { if (connected.get() && requests.isEmpty()) { Log.d(TAG, "unified network: no longer requesting location update") client.removeLocationUpdates(listener) connected.set(false) } else if (!requests.isEmpty()) { var minTime = Long.MAX_VALUE val sb = StringBuilder() var opPackageName: String? = null for (request in requests) { if (request.locationRequest.interval < minTime) { opPackageName = request.packageName minTime = request.locationRequest.interval } if (sb.isNotEmpty()) sb.append(", ") sb.append("${request.packageName}:${request.locationRequest.interval}ms") } client.opPackageName = opPackageName Log.d(TAG, "unified network: requesting location updates with interval ${minTime}ms ($sb)") if (!connected.get() || connectedMinTime != minTime) { client.requestLocationUpdates(listener, minTime) } connected.set(true) connectedMinTime = minTime } } companion object { const val TAG = "GmsLocProviderU" } init { client = UnifiedLocationClient[context!!] this.changeListener = changeListener updateLastLocation() } }
apache-2.0
eb1139d41a11901e85a4f5e80431e94b
35.413793
128
0.623106
5.004739
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/fire_hydrant/AddFireHydrantType.kt
1
1110
package de.westnordost.streetcomplete.quests.fire_hydrant import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement class AddFireHydrantType : OsmFilterQuestType<FireHydrantType>() { override val elementFilter = "nodes with emergency = fire_hydrant and !fire_hydrant:type" override val commitMessage = "Add fire hydrant type" override val wikiLink = "Tag:emergency=fire_hydrant" override val icon = R.drawable.ic_quest_fire_hydrant override val isDeleteElementEnabled = true override val questTypeAchievements = emptyList<QuestTypeAchievement>() override fun getTitle(tags: Map<String, String>) = R.string.quest_fireHydrant_type_title override fun createForm() = AddFireHydrantTypeForm() override fun applyAnswerTo(answer: FireHydrantType, changes: StringMapChangesBuilder) { changes.add("fire_hydrant:type", answer.osmValue) } }
gpl-3.0
e2df75725ef377ddb640a04baf482c5e
43.4
93
0.793694
4.352941
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/widget/PlayerStatView.kt
1
3183
package com.boardgamegeek.ui.widget import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.widget.LinearLayout import android.widget.TextView import androidx.core.view.isVisible import com.boardgamegeek.R import com.boardgamegeek.extensions.setSelectableBackground import java.text.DecimalFormat class PlayerStatView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr) { init { LayoutInflater.from(context).inflate(R.layout.widget_player_stat, this) orientation = VERTICAL val standardPadding = resources.getDimensionPixelSize(R.dimen.padding_standard) setPadding(0, standardPadding, 0, standardPadding) setSelectableBackground() } fun showScores(show: Boolean) { findViewById<LinearLayout>(R.id.scoresView).isVisible = show } fun setName(text: CharSequence) { findViewById<TextView>(R.id.nameView).text = text } fun setWinInfo(wins: Int, winnableGames: Int) { val winPercentage = when { wins >= winnableGames -> 100 winnableGames > 0 -> (wins.toDouble() / winnableGames * 100).toInt() else -> 0 } findViewById<TextView>(R.id.winCountView).text = context.getString(R.string.play_stat_win_percentage, wins, winnableGames, winPercentage) } fun setWinSkill(skill: Int) { findViewById<TextView>(R.id.playCountView).text = skill.toString() } fun setOverallLowScore(score: Double) { findViewById<ScoreGraphView>(R.id.graphView).lowScore = score } fun setOverallAverageScore(score: Double) { findViewById<ScoreGraphView>(R.id.graphView).averageScore = score } fun setOverallAverageWinScore(score: Double) { findViewById<ScoreGraphView>(R.id.graphView).averageWinScore = score } fun setOverallHighScore(score: Double) { findViewById<ScoreGraphView>(R.id.graphView).highScore = score } fun setLowScore(score: Double) { setScore(findViewById(R.id.lowScoreView), score, Integer.MAX_VALUE) findViewById<ScoreGraphView>(R.id.graphView).personalLowScore = score } fun setAverageScore(score: Double) { setScore(findViewById(R.id.averageScoreView), score, Integer.MIN_VALUE) findViewById<ScoreGraphView>(R.id.graphView).personalAverageScore = score } fun setAverageWinScore(score: Double) { setScore(findViewById(R.id.averageWinScoreView), score, Integer.MIN_VALUE) findViewById<ScoreGraphView>(R.id.graphView).personalAverageWinScore = score } fun setHighScore(score: Double) { setScore(findViewById(R.id.highScoreView), score, Integer.MIN_VALUE) findViewById<ScoreGraphView>(R.id.graphView).personalHighScore = score } private fun setScore(textView: TextView, score: Double, invalidScore: Int) { textView.text = if (score == invalidScore.toDouble()) "-" else DOUBLE_FORMAT.format(score) } companion object { private val DOUBLE_FORMAT = DecimalFormat("0.##") } }
gpl-3.0
98001dfb79eb2fb544bed8451174d157
33.978022
145
0.702796
4.149935
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/api/item/inventory/query/InventoryFilterBuilder.kt
1
4314
/* * 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.api.item.inventory.query import org.lanternpowered.api.data.Key import org.lanternpowered.api.item.inventory.Inventory import org.lanternpowered.api.registry.factoryOf import org.spongepowered.api.data.value.Value import java.util.function.Supplier typealias InventoryFilterBuilderFunction<I> = InventoryFilterBuilder<I>.() -> InventoryFilter<I> /** * Builds an [InventoryFilter] from the builder function. */ fun <I : Inventory> InventoryFilterBuilderFunction<I>.build(): InventoryFilter<I> = this.invoke(factoryOf<InventoryFilterBuilder.Factory>().of()) /** * A filter for inventories. */ typealias InventoryFilter<I> = (inventory: I) -> Boolean interface InventoryFilterBuilder<I : Inventory> { interface Factory { fun <I : Inventory> of(): InventoryFilterBuilder<I> } infix fun <V : Any> Key<out Value<V>>.eq(value: V?): InventoryFilter<I> infix fun <V : Any> Key<out Value<V>>.neq(value: V?): InventoryFilter<I> infix fun <V : Any> Key<out Value<V>>.greater(value: V?): InventoryFilter<I> infix fun <V : Any> Key<out Value<V>>.greaterEq(value: V?): InventoryFilter<I> infix fun <V : Any> Key<out Value<V>>.less(value: V?): InventoryFilter<I> infix fun <V : Any> Key<out Value<V>>.lessEq(value: V?): InventoryFilter<I> infix fun <V : Any> Supplier<out Key<out Value<V>>>.eq(value: V?): InventoryFilter<I> = this.get().eq(value) infix fun <V : Any> Supplier<out Key<out Value<V>>>.neq(value: V?): InventoryFilter<I> = this.get().neq(value) infix fun <V : Any> Supplier<out Key<out Value<V>>>.greater(value: V?): InventoryFilter<I> = this.get().greater(value) infix fun <V : Any> Supplier<out Key<out Value<V>>>.greaterEq(value: V?): InventoryFilter<I> = this.get().greaterEq(value) infix fun <V : Any> Supplier<out Key<out Value<V>>>.less(value: V?): InventoryFilter<I> = this.get().less(value) infix fun <V : Any> Supplier<out Key<out Value<V>>>.lessEq(value: V?): InventoryFilter<I> = this.get().lessEq(value) infix fun <V : Any> Supplier<out Key<out Value<V>>>.eq(value: Supplier<out V?>): InventoryFilter<I> = this.get().eq(value.get()) infix fun <V : Any> Supplier<out Key<out Value<V>>>.neq(value: Supplier<out V?>): InventoryFilter<I> = this.get().neq(value.get()) infix fun <V : Any> Supplier<out Key<out Value<V>>>.greater(value: Supplier<out V?>): InventoryFilter<I> = this.get().greater(value.get()) infix fun <V : Any> Supplier<out Key<out Value<V>>>.greaterEq(value: Supplier<out V?>): InventoryFilter<I> = this.get().greaterEq(value.get()) infix fun <V : Any> Supplier<out Key<out Value<V>>>.less(value: Supplier<out V?>): InventoryFilter<I> = this.get().less(value.get()) infix fun <V : Any> Supplier<out Key<out Value<V>>>.lessEq(value: Supplier<out V?>): InventoryFilter<I> = this.get().lessEq(value.get()) infix fun <V : Any> Key<out Value<V>>.eq(value: Supplier<out V?>): InventoryFilter<I> = this.eq(value.get()) infix fun <V : Any> Key<out Value<V>>.neq(value: Supplier<out V?>): InventoryFilter<I> = this.neq(value.get()) infix fun <V : Any> Key<out Value<V>>.greater(value: Supplier<out V?>): InventoryFilter<I> = this.greater(value.get()) infix fun <V : Any> Key<out Value<V>>.greaterEq(value: Supplier<out V?>): InventoryFilter<I> = this.greaterEq(value.get()) infix fun <V : Any> Key<out Value<V>>.less(value: Supplier<out V?>): InventoryFilter<I> = this.less(value.get()) infix fun <V : Any> Key<out Value<V>>.lessEq(value: Supplier<out V?>): InventoryFilter<I> = this.lessEq(value.get()) infix fun InventoryFilter<I>.and(filter: InventoryFilter<I>): InventoryFilter<I> infix fun InventoryFilter<I>.or(filter: InventoryFilter<I>): InventoryFilter<I> }
mit
79e905d44a779924fcfcaff0d94c106b
38.944444
112
0.651136
3.429253
false
false
false
false