content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package info.nightscout.androidaps.utils.androidNotification
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationCompat
import androidx.core.app.TaskStackBuilder
import info.nightscout.androidaps.MainActivity
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.NotificationHolderInterface
import info.nightscout.androidaps.utils.resources.IconsProvider
import info.nightscout.androidaps.utils.resources.ResourceHelper
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class NotificationHolder @Inject constructor(
private val resourceHelper: ResourceHelper,
private val context: Context,
private val iconsProvider: IconsProvider
) : NotificationHolderInterface {
override val channelID = "AndroidAPS-Ongoing"
override val notificationID = 4711
override lateinit var notification: Notification
init {
val stackBuilder = TaskStackBuilder.create(context)
.addParentStack(MainActivity::class.java)
.addNextIntent(Intent(context, MainApp::class.java))
val builder = NotificationCompat.Builder(context, channelID)
.setOngoing(true)
.setOnlyAlertOnce(true)
.setCategory(NotificationCompat.CATEGORY_STATUS)
.setSmallIcon(iconsProvider.getNotificationIcon())
.setLargeIcon(resourceHelper.decodeResource(iconsProvider.getIcon()))
.setContentTitle(resourceHelper.gs(R.string.loading))
.setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT))
notification = builder.build()
(context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).notify(notificationID, notification)
}
}
| app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt | 3096413887 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.editor.lists
import com.intellij.application.options.CodeStyle
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.guessProjectForFile
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiUtilCore
import com.intellij.psi.util.parentOfType
import com.intellij.util.text.CharArrayUtil
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownListImpl
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownListItemImpl
internal object ListUtils {
/** [offset] may be located inside the indent of the returned item, but not on a blank line */
fun MarkdownFile.getListItemAt(offset: Int, document: Document) =
getListItemAtLine(document.getLineNumber(offset), document)
/** [lineNumber] should belong to a list item and not represent a blank line, otherwise returns `null` */
fun MarkdownFile.getListItemAtLine(lineNumber: Int, document: Document): MarkdownListItemImpl? {
val lineStart = document.getLineStartOffset(lineNumber)
val lineEnd = document.getLineEndOffset(lineNumber)
val searchingOffset = CharArrayUtil.shiftBackward(document.charsSequence, lineStart, lineEnd - 1, " \t\n")
if (searchingOffset < lineStart) {
return null
}
val elementAtOffset = PsiUtilCore.getElementAtOffset(this, searchingOffset)
return elementAtOffset.parentOfType(true)
}
/** If 0 <= [lineNumber] < [Document.getLineCount], equivalent to [getListItemAtLine].
* Otherwise, returns null. */
fun MarkdownFile.getListItemAtLineSafely(lineNumber: Int, document: Document) =
if (lineNumber in 0 until document.lineCount)
getListItemAtLine(lineNumber, document)
else null
fun Document.getLineIndentRange(lineNumber: Int): TextRange {
val lineStart = getLineStartOffset(lineNumber)
val nonWsStart = CharArrayUtil.shiftForward(charsSequence, lineStart, " \t")
return TextRange.create(lineStart, nonWsStart)
}
/**
* Returns the indent at line [lineNumber], with all tabs replaced with spaces.
* Returns `null` if [file] is null and failed to guess it.
*/
fun Document.getLineIndentSpaces(lineNumber: Int, file: PsiFile? = null): String? {
val psiFile = file ?: run {
val virtualFile = FileDocumentManager.getInstance().getFile(this)
val project = guessProjectForFile(virtualFile) ?: return null
PsiDocumentManager.getInstance(project).getPsiFile(this) ?: return null
}
val tabSize = CodeStyle.getFacade(psiFile).tabSize
val indentStr = getText(getLineIndentRange(lineNumber))
return indentStr.replace("\t", " ".repeat(tabSize))
}
val MarkdownListImpl.items get() = children.filterIsInstance<MarkdownListItemImpl>()
val MarkdownListItemImpl.sublists get() = children.filterIsInstance<MarkdownListImpl>()
val MarkdownListItemImpl.list get() = parent as MarkdownListImpl
/**
* Returns a marker of the item with leading whitespaces trimmed, and with a single space in the end.
*/
val MarkdownListItemImpl.normalizedMarker: String
get() = this.markerElement!!.text.trim().let { "$it " }
}
| plugins/markdown/src/org/intellij/plugins/markdown/editor/lists/ListUtils.kt | 4242710026 |
package io.github.feelfreelinux.wykopmobilny.ui.modules.mywykop.observedtags
import io.github.feelfreelinux.wykopmobilny.api.tag.TagApi
import io.github.feelfreelinux.wykopmobilny.base.BasePresenter
import io.github.feelfreelinux.wykopmobilny.base.Schedulers
import io.github.feelfreelinux.wykopmobilny.utils.intoComposite
class MyWykopObservedTagsPresenter(
val schedulers: Schedulers,
private val tagsApi: TagApi
) : BasePresenter<MyWykopObservedTagsView>() {
fun loadTags() {
tagsApi.getObservedTags()
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe({ view?.showTags(it) }, { view?.showErrorDialog(it) })
.intoComposite(compositeObservable)
}
} | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/mywykop/observedtags/MyWykopObservedTagsPresenter.kt | 4018170391 |
class A(a: Int) {
constructor() : this(
<caret>
)
}
// SET_FALSE: ALIGN_MULTILINE_METHOD_BRACKETS | plugins/kotlin/idea/tests/testData/indentationOnNewline/emptyParameters/EmptyArgumentInThisAsConstructor.after.kt | 278441386 |
val somelong = 3 + 4 - (
<caret>
)
// SET_FALSE: ALIGN_MULTILINE_BINARY_OPERATION
// IGNORE_FORMATTER | plugins/kotlin/idea/tests/testData/indentationOnNewline/emptyParenthesisInBinaryExpression/InExpressionsParentheses2.after.kt | 3427794906 |
// WITH_RUNTIME
// IS_APPLICABLE: false
val f = { <caret>throw RuntimeException() }
| plugins/kotlin/idea/tests/testData/intentions/addThrowsAnnotation/inLambda.kt | 3985709844 |
// WITH_RUNTIME
fun foo(runnable: Runnable) {}
fun bar() {
foo(<caret>object : Runnable {
override fun run() {
}
})
} | plugins/kotlin/idea/tests/testData/intentions/objectLiteralToLambda/EmptyBody.kt | 2732279960 |
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.workflow
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.android.fhir.workflow.testing.PlanDefinition
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class PlanDefinitionProcessorAndroidTest {
@Test
fun testChildRoutineVisit() =
PlanDefinition.Assert.that(
"ChildRoutineVisit-PlanDefinition-1.0.0",
"Patient/ChildRoutine-Reportable",
null
)
.withData("/plan-definition/child-routine-visit/child_routine_visit_patient.json")
.withLibrary("/plan-definition/child-routine-visit/child_routine_visit_plan_definition.json")
.apply()
.isEqualsTo("/plan-definition/child-routine-visit/child_routine_visit_careplan.json")
@Test
fun testHelloWorld() =
PlanDefinition.Assert.that(
"hello-world-patient-view",
"helloworld-patient-1",
"helloworld-patient-1-encounter-1"
)
.withData("/plan-definition/hello-world/hello-world-patient-data.json")
.withLibrary("/plan-definition/hello-world/hello-world-patient-view-bundle.json")
.apply()
.isEqualsTo("/plan-definition/hello-world/hello-world-careplan.json")
@Test
fun testOpioidRec10PatientView() =
PlanDefinition.Assert.that(
"opioidcds-10-patient-view",
"example-rec-10-patient-view-POS-Cocaine-drugs",
"example-rec-10-patient-view-POS-Cocaine-drugs-prefetch"
)
.withData(
"/plan-definition/opioid-Rec10-patient-view/opioid-Rec10-patient-view-patient-data.json"
)
.withLibrary(
"/plan-definition/opioid-Rec10-patient-view/opioid-Rec10-patient-view-bundle.json"
)
.apply()
.isEqualsTo(
"/plan-definition/opioid-Rec10-patient-view/opioid-Rec10-patient-view-careplan.json"
)
@Test
fun testRuleFiltersNotReportable() =
PlanDefinition.Assert.that(
"plandefinition-RuleFilters-1.0.0",
"NotReportable",
null,
)
.withData("/plan-definition/rule-filters/tests-NotReportable-bundle.json")
.withLibrary("/plan-definition/rule-filters/RuleFilters-1.0.0-bundle.json")
.apply()
.isEqualsTo("/plan-definition/rule-filters/NotReportableCarePlan.json")
@Test
fun testRuleFiltersReportable() =
PlanDefinition.Assert.that(
"plandefinition-RuleFilters-1.0.0",
"Reportable",
null,
)
.withData("/plan-definition/rule-filters/tests-Reportable-bundle.json")
.withLibrary("/plan-definition/rule-filters/RuleFilters-1.0.0-bundle.json")
.apply()
.isEqualsTo("/plan-definition/rule-filters/ReportableCarePlan.json")
}
| workflow/src/androidTest/java/com/google/android/fhir/workflow/PlanDefinitionProcessorAndroidTest.kt | 1865832870 |
/*
* Copyright 2017 zhangqinglian
*
* 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.zqlite.android.diycode.device.view.custom
import com.zqlite.android.diycode.R
import com.zqlite.android.diycode.device.utils.NetworkUtils
import com.zqlite.android.diycode.device.view.BaseActivity
import kotlinx.android.synthetic.main.activity_iamge_viewer.*
/**
* Created by scott on 2017/8/17.
*/
class ImageViewerActivity : BaseActivity() {
override fun getLayoutId(): Int {
return R.layout.activity_iamge_viewer
}
override fun initView() {
}
override fun initData() {
val extra = intent.extras
if(extra != null){
val url = extra.getString("url")
NetworkUtils.getInstace(this@ImageViewerActivity)!!.loadImage(photo_view,url,R.drawable.error)
}
}
} | src/main/kotlin/com/zqlite/android/diycode/device/view/custom/ImageViewerActivity.kt | 1094762241 |
package vgrechka
import kotlin.properties.Delegates
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
annotation class Ser
annotation class AllOpen
var exhaustive: Any? = null
class BreakOnMeException(msg: String) : RuntimeException(msg)
fun <T: Any> notNull(): ReadWriteProperty<Any?, T> = Delegates.notNull()
class notNullOnce<T: Any> : ReadWriteProperty<Any?, T> {
var _value: T? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return _value ?: throw IllegalStateException("Property `${property.name}` should be initialized before get.")
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
check(this._value == null) {"Property `${property.name}` should be assigned only once"}
this._value = value
}
}
class maybeNullOnce<T: Any> : ReadWriteProperty<Any?, T?> {
// TODO:vgrechka Unify with notNullOnce
var assigned = false
var _value: T? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): T? {
if (!assigned) throw IllegalStateException("Property `${property.name}` should be initialized before get.")
return _value
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
check(!assigned) {"Property `${property.name}` should be assigned only once"}
this.assigned = true
this._value = value
}
}
fun <T> named(make: (ident: String) -> T) = object : ReadOnlyProperty<Any?, T> {
private var value: T? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
if (value == null)
value = make(property.name)
return bang(value)
}
}
fun myName() = named {it}
fun slashMyName() = named {"/" + it}
fun <T> bang(x: T?): T {
if (x == null) bitch("Banging on freaking null")
return x
}
fun StringBuilder.ln(x: Any? = "") {
append(x)
append("\n")
}
fun String.indexOfOrNull(needle: String, startIndex: Int = 0, ignoreCase: Boolean = false): Int? {
val index = indexOf(needle, startIndex, ignoreCase)
return if (index >= 0) index else null
}
inline fun <T> List<T>.indexOfFirstOrNull(predicate: (T) -> Boolean): Int? {
val index = this.indexOfFirst(predicate)
return when (index) {
-1 -> null
else -> index
}
}
fun <T> List<T>.indexOfOrNull(element: T): Int? {
val index = this.indexOf(element)
return when (index) {
-1 -> null
else -> index
}
}
// "Create parameter" refactoring aids
fun <R> call(f: () -> R): R = f()
fun <R, P0> call(f: (P0) -> R, p0: P0): R = f(p0)
fun <R, P0, P1> call(f: (P0, P1) -> R, p0: P0, p1: P1): R = f(p0, p1)
operator fun StringBuilder.plusAssign(x: Any?) {
this.append(x)
}
| shared-kjs/src/fuck.kt | 1160352646 |
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package kotlin
import kotlin.native.internal.ExportTypeInfo
/**
* The type with only one value: the `Unit` object.
*/
@ExportTypeInfo("theUnitTypeInfo")
public object Unit {
override fun toString() = "kotlin.Unit"
} | runtime/src/main/kotlin/kotlin/Unit.kt | 512043636 |
class A {
internal fun foo(collection: Collection<String>) {
for (i in collection.size downTo 0) {
println(i)
}
}
}
| plugins/kotlin/j2k/old/tests/testData/fileOrElement/for/falseIndicesReversed.kt | 875283205 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.core.util
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
@Deprecated("Use 'textRange' instead", ReplaceWith("textRange"))
val PsiElement.range: TextRange
get() = textRange!!
@Deprecated("Use 'startOffset' instead", ReplaceWith("startOffset"))
val TextRange.start: Int
get() = startOffset | plugins/kotlin/base/obsolete-compat/src/org/jetbrains/kotlin/idea/core/util/RangeUtils.kt | 2511244617 |
package org.thoughtcrime.securesms.safety
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import org.signal.core.util.DimensionUnit
import org.signal.core.util.or
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.AvatarImageView
import org.thoughtcrime.securesms.components.menu.ActionItem
import org.thoughtcrime.securesms.components.menu.SignalContextMenu
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.adapter.mapping.MappingModel
import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder
import org.thoughtcrime.securesms.util.visible
/**
* An untrusted recipient who can be verified or removed.
*/
object SafetyNumberRecipientRowItem {
fun register(mappingAdapter: MappingAdapter) {
mappingAdapter.registerFactory(Model::class.java, LayoutFactory(::ViewHolder, R.layout.safety_number_recipient_row_item))
}
class Model(
val recipient: Recipient,
val isVerified: Boolean,
val distributionListMembershipCount: Int,
val groupMembershipCount: Int,
val getContextMenuActions: (Model) -> List<ActionItem>
) : MappingModel<Model> {
override fun areItemsTheSame(newItem: Model): Boolean {
return recipient.id == newItem.recipient.id
}
override fun areContentsTheSame(newItem: Model): Boolean {
return recipient.hasSameContent(newItem.recipient) &&
isVerified == newItem.isVerified &&
distributionListMembershipCount == newItem.distributionListMembershipCount &&
groupMembershipCount == newItem.groupMembershipCount
}
}
class ViewHolder(itemView: View) : MappingViewHolder<Model>(itemView) {
private val avatar: AvatarImageView = itemView.findViewById(R.id.safety_number_recipient_avatar)
private val name: TextView = itemView.findViewById(R.id.safety_number_recipient_name)
private val identifier: TextView = itemView.findViewById(R.id.safety_number_recipient_identifier)
override fun bind(model: Model) {
avatar.setRecipient(model.recipient)
name.text = model.recipient.getDisplayName(context)
val identifierText = model.recipient.e164.or(model.recipient.username).orElse(null)
val subLineText = when {
model.isVerified && identifierText.isNullOrBlank() -> context.getString(R.string.SafetyNumberRecipientRowItem__verified)
model.isVerified -> context.getString(R.string.SafetyNumberRecipientRowItem__s_dot_verified, identifierText)
else -> identifierText
}
identifier.text = subLineText
identifier.visible = !subLineText.isNullOrBlank()
itemView.setOnClickListener {
itemView.isSelected = true
SignalContextMenu.Builder(itemView, itemView.rootView as ViewGroup)
.offsetY(DimensionUnit.DP.toPixels(12f).toInt())
.onDismiss { itemView.isSelected = false }
.show(model.getContextMenuActions(model))
}
}
}
}
| app/src/main/java/org/thoughtcrime/securesms/safety/SafetyNumberRecipientRowItem.kt | 3200315401 |
package org.thoughtcrime.securesms.testing
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.preference.PreferenceManager
import androidx.test.core.app.ActivityScenario
import androidx.test.platform.app.InstrumentationRegistry
import okhttp3.mockwebserver.MockResponse
import org.junit.rules.ExternalResource
import org.signal.libsignal.protocol.IdentityKey
import org.signal.libsignal.protocol.SignalProtocolAddress
import org.thoughtcrime.securesms.crypto.IdentityKeyUtil
import org.thoughtcrime.securesms.crypto.MasterSecretUtil
import org.thoughtcrime.securesms.crypto.ProfileKeyUtil
import org.thoughtcrime.securesms.database.IdentityDatabase
import org.thoughtcrime.securesms.database.SignalDatabase
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.dependencies.InstrumentationApplicationDependencyProvider
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.net.DeviceTransferBlockingInterceptor
import org.thoughtcrime.securesms.profiles.ProfileName
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.registration.RegistrationData
import org.thoughtcrime.securesms.registration.RegistrationRepository
import org.thoughtcrime.securesms.registration.RegistrationUtil
import org.thoughtcrime.securesms.util.Util
import org.whispersystems.signalservice.api.profiles.SignalServiceProfile
import org.whispersystems.signalservice.api.push.ACI
import org.whispersystems.signalservice.api.push.SignalServiceAddress
import org.whispersystems.signalservice.internal.ServiceResponse
import org.whispersystems.signalservice.internal.ServiceResponseProcessor
import org.whispersystems.signalservice.internal.push.VerifyAccountResponse
import java.lang.IllegalArgumentException
import java.util.UUID
/**
* Test rule to use that sets up the application in a mostly registered state. Enough so that most
* activities should be launchable directly.
*
* To use: `@get:Rule val harness = SignalActivityRule()`
*/
class SignalActivityRule(private val othersCount: Int = 4) : ExternalResource() {
val application: Application = ApplicationDependencies.getApplication()
lateinit var context: Context
private set
lateinit var self: Recipient
private set
lateinit var others: List<RecipientId>
private set
override fun before() {
context = InstrumentationRegistry.getInstrumentation().targetContext
self = setupSelf()
others = setupOthers()
InstrumentationApplicationDependencyProvider.clearHandlers()
}
private fun setupSelf(): Recipient {
DeviceTransferBlockingInterceptor.getInstance().blockNetwork()
PreferenceManager.getDefaultSharedPreferences(application).edit().putBoolean("pref_prompted_push_registration", true).commit()
val masterSecret = MasterSecretUtil.generateMasterSecret(application, MasterSecretUtil.UNENCRYPTED_PASSPHRASE)
MasterSecretUtil.generateAsymmetricMasterSecret(application, masterSecret)
val preferences: SharedPreferences = application.getSharedPreferences(MasterSecretUtil.PREFERENCES_NAME, 0)
preferences.edit().putBoolean("passphrase_initialized", true).commit()
val registrationRepository = RegistrationRepository(application)
InstrumentationApplicationDependencyProvider.addMockWebRequestHandlers(Put("/v2/keys") { MockResponse().success() })
val response: ServiceResponse<VerifyAccountResponse> = registrationRepository.registerAccountWithoutRegistrationLock(
RegistrationData(
code = "123123",
e164 = "+15555550101",
password = Util.getSecret(18),
registrationId = registrationRepository.registrationId,
profileKey = registrationRepository.getProfileKey("+15555550101"),
fcmToken = null,
pniRegistrationId = registrationRepository.pniRegistrationId
),
VerifyAccountResponse(UUID.randomUUID().toString(), UUID.randomUUID().toString(), false)
).blockingGet()
ServiceResponseProcessor.DefaultProcessor(response).resultOrThrow
SignalStore.kbsValues().optOut()
RegistrationUtil.maybeMarkRegistrationComplete(application)
SignalDatabase.recipients.setProfileName(Recipient.self().id, ProfileName.fromParts("Tester", "McTesterson"))
return Recipient.self()
}
private fun setupOthers(): List<RecipientId> {
val others = mutableListOf<RecipientId>()
if (othersCount !in 0 until 1000) {
throw IllegalArgumentException("$othersCount must be between 0 and 1000")
}
for (i in 0 until othersCount) {
val aci = ACI.from(UUID.randomUUID())
val recipientId = RecipientId.from(SignalServiceAddress(aci, "+15555551%03d".format(i)))
SignalDatabase.recipients.setProfileName(recipientId, ProfileName.fromParts("Buddy", "#$i"))
SignalDatabase.recipients.setProfileKeyIfAbsent(recipientId, ProfileKeyUtil.createNew())
SignalDatabase.recipients.setCapabilities(recipientId, SignalServiceProfile.Capabilities(true, true, true, true, true, true, true, true))
SignalDatabase.recipients.setProfileSharing(recipientId, true)
SignalDatabase.recipients.markRegistered(recipientId, aci)
ApplicationDependencies.getProtocolStore().aci().saveIdentity(SignalProtocolAddress(aci.toString(), 0), IdentityKeyUtil.generateIdentityKeyPair().publicKey)
others += recipientId
}
return others
}
inline fun <reified T : Activity> launchActivity(initIntent: Intent.() -> Unit = {}): ActivityScenario<T> {
return androidx.test.core.app.launchActivity(Intent(context, T::class.java).apply(initIntent))
}
fun changeIdentityKey(recipient: Recipient, identityKey: IdentityKey = IdentityKeyUtil.generateIdentityKeyPair().publicKey) {
ApplicationDependencies.getProtocolStore().aci().saveIdentity(SignalProtocolAddress(recipient.requireServiceId().toString(), 0), identityKey)
}
fun getIdentity(recipient: Recipient): IdentityKey {
return ApplicationDependencies.getProtocolStore().aci().identities().getIdentity(SignalProtocolAddress(recipient.requireServiceId().toString(), 0))
}
fun setVerified(recipient: Recipient, status: IdentityDatabase.VerifiedStatus) {
ApplicationDependencies.getProtocolStore().aci().identities().setVerified(recipient.id, getIdentity(recipient), IdentityDatabase.VerifiedStatus.VERIFIED)
}
}
| app/src/androidTest/java/org/thoughtcrime/securesms/testing/SignalActivityRule.kt | 3924267368 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.wearable.watchface
import android.annotation.SuppressLint
import android.os.Parcel
import android.os.Parcelable
import androidx.annotation.RestrictTo
/**
* Wraps a Parcelable.
*
* @hide
*/
@SuppressLint("BanParcelableUsage")
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class ParcelableWrapper(val parcelable: Parcelable) : Parcelable {
constructor(parcel: Parcel) : this(unparcel(parcel))
override fun writeToParcel(dest: Parcel, flags: Int) {
parcelable.writeToParcel(dest, flags)
}
override fun describeContents(): Int = parcelable.describeContents()
public companion object {
@JvmField
@Suppress("DEPRECATION")
public val CREATOR: Parcelable.Creator<ParcelableWrapper> =
object : Parcelable.Creator<ParcelableWrapper> {
override fun createFromParcel(parcel: Parcel) = ParcelableWrapper(parcel)
override fun newArray(size: Int) = arrayOfNulls<ParcelableWrapper?>(size)
}
internal var unparcel: (Parcel) -> Parcelable = {
throw RuntimeException("setUnparceler not called")
}
public fun setUnparceler(unparceler: (Parcel) -> Parcelable) {
unparcel = unparceler
}
}
} | wear/watchface/watchface-data/src/main/java/android/support/wearable/watchface/ParcelableWrapper.kt | 2717338282 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.testing
import android.os.Build
import androidx.camera.core.impl.utils.Exif.createFromInputStream
import androidx.camera.testing.ExifUtil.updateExif
import androidx.camera.testing.TestImageUtil.createJpegBytes
import com.google.common.truth.Truth.assertThat
import java.io.ByteArrayInputStream
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.internal.DoNotInstrument
/**
* Unit tests for [ExifUtil]
*/
@RunWith(RobolectricTestRunner::class)
@DoNotInstrument
@Config(minSdk = Build.VERSION_CODES.LOLLIPOP)
class ExifUtilTest {
companion object {
private const val DESCRIPTION = "description"
}
@Test
fun createJpegWithExif_verifyExif() {
// Arrange: create a JPEG file.
val jpeg = createJpegBytes(640, 480)
// Act: update the description tag.
val jpegWithExif = updateExif(jpeg) {
it.description = DESCRIPTION
}
// Assert: the description tag has been updated.
val exif = createFromInputStream(ByteArrayInputStream(jpegWithExif))
assertThat(exif.description).isEqualTo(DESCRIPTION)
}
} | camera/camera-testing/src/test/java/androidx/camera/testing/ExifUtilTest.kt | 3040925913 |
package com.sedsoftware.yaptalker.di.module.network
import android.content.Context
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.sedsoftware.yaptalker.BuildConfig
import com.sedsoftware.yaptalker.di.module.network.interceptors.HeaderAndParamManipulationInterceptor
import com.sedsoftware.yaptalker.di.module.network.interceptors.HtmlFixerInterceptor
import com.sedsoftware.yaptalker.di.module.network.interceptors.SaveReceivedCookiesInterceptor
import com.sedsoftware.yaptalker.di.module.network.interceptors.SendSavedCookiesInterceptor
import com.sedsoftware.yaptalker.domain.device.CookieStorage
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import okhttp3.logging.HttpLoggingInterceptor.Level
import javax.inject.Named
import javax.inject.Singleton
@Module
class HttpClientsModule {
private val loggingLevel: Level by lazy {
if (BuildConfig.DEBUG) Level.HEADERS
else Level.NONE
}
private val loggingInterceptor: HttpLoggingInterceptor by lazy {
HttpLoggingInterceptor().setLevel(loggingLevel)
}
@Provides
@Singleton
fun provideSetCookieCache(): SetCookieCache =
SetCookieCache()
@Provides
@Singleton
fun provideSharedPrefsCookiePersistor(context: Context): SharedPrefsCookiePersistor =
SharedPrefsCookiePersistor(context)
@Provides
@Singleton
fun providePersistentCookieJar(
cache: SetCookieCache,
persistor: SharedPrefsCookiePersistor
): PersistentCookieJar =
PersistentCookieJar(cache, persistor)
@Singleton
@Provides
@Named("siteClient")
fun provideSiteClient(cookieStorage: CookieStorage): OkHttpClient =
OkHttpClient.Builder()
.addInterceptor(HtmlFixerInterceptor())
.addInterceptor(HeaderAndParamManipulationInterceptor())
.addInterceptor(SaveReceivedCookiesInterceptor(cookieStorage))
.addInterceptor(SendSavedCookiesInterceptor(cookieStorage))
.addInterceptor(loggingInterceptor)
.build()
@Singleton
@Provides
@Named("apiClient")
fun provideApiClient(jar: PersistentCookieJar): OkHttpClient {
val builder = OkHttpClient.Builder()
builder.addInterceptor(HeaderAndParamManipulationInterceptor())
builder.addInterceptor(loggingInterceptor)
builder.cookieJar(jar)
builder.cache(null)
return builder.build()
}
@Singleton
@Provides
@Named("fileClient")
fun provideFileClient(): OkHttpClient = OkHttpClient.Builder().build()
@Singleton
@Provides
@Named("outerClient")
fun provideOuterClient(): OkHttpClient =
OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build()
}
| app/src/main/java/com/sedsoftware/yaptalker/di/module/network/HttpClientsModule.kt | 2092508938 |
/*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.material
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.SaveableStateHolder
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.TouchInjectionScope
import androidx.compose.ui.test.assertIsOff
import androidx.compose.ui.test.assertIsOn
import androidx.compose.ui.test.assertTextContains
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTouchInput
import androidx.compose.ui.test.swipe
import androidx.compose.ui.test.swipeLeft
import androidx.compose.ui.test.swipeRight
import java.lang.Math.sin
import org.junit.Assert.assertEquals
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
class SwipeToDismissBoxTest {
@get:Rule
val rule = createComposeRule()
@Test
fun supports_testtag() {
rule.setContentWithTheme {
val state = rememberSwipeToDismissBoxState()
SwipeToDismissBox(
state = state,
modifier = Modifier.testTag(TEST_TAG)
) {
Text("Testing")
}
}
rule.onNodeWithTag(TEST_TAG).assertExists()
}
@Test
fun dismisses_when_swiped_right() =
verifySwipe(gesture = { swipeRight() }, expectedToDismiss = true)
@Test
fun does_not_dismiss_when_swiped_left() =
// Swipe left is met with resistance and is not a swipe-to-dismiss.
verifySwipe(gesture = { swipeLeft() }, expectedToDismiss = false)
@Test
fun does_not_dismiss_when_swipe_right_incomplete() =
// Execute a partial swipe over a longer-than-default duration so that there
// is insufficient velocity to perform a 'fling'.
verifySwipe(
gesture = { swipeRight(startX = 0f, endX = width / 4f, durationMillis = LONG_SWIPE) },
expectedToDismiss = false
)
@Test
fun does_not_display_background_without_swipe() {
rule.setContentWithTheme {
val state = rememberSwipeToDismissBoxState()
SwipeToDismissBox(
state = state,
modifier = Modifier.testTag(TEST_TAG),
) { isBackground ->
if (isBackground) Text(BACKGROUND_MESSAGE) else messageContent()
}
}
rule.onNodeWithText(BACKGROUND_MESSAGE).assertDoesNotExist()
}
@Test
fun does_not_dismiss_if_has_background_is_false() {
var dismissed = false
rule.setContentWithTheme {
val state = rememberSwipeToDismissBoxState()
LaunchedEffect(state.currentValue) {
dismissed =
state.currentValue == SwipeToDismissValue.Dismissed
}
SwipeToDismissBox(
state = state,
modifier = Modifier.testTag(TEST_TAG),
hasBackground = false,
) {
Text(CONTENT_MESSAGE, color = MaterialTheme.colors.onPrimary)
}
}
rule.onNodeWithTag(TEST_TAG).performTouchInput({ swipeRight() })
rule.runOnIdle {
assertEquals(false, dismissed)
}
}
@Test
fun remembers_saved_state() {
val showCounterForContent = mutableStateOf(true)
rule.setContentWithTheme {
val state = rememberSwipeToDismissBoxState()
val holder = rememberSaveableStateHolder()
LaunchedEffect(state.currentValue) {
if (state.currentValue == SwipeToDismissValue.Dismissed) {
showCounterForContent.value = !showCounterForContent.value
state.snapTo(SwipeToDismissValue.Default)
}
}
SwipeToDismissBox(
state = state,
modifier = Modifier.testTag(TEST_TAG),
backgroundKey = if (showCounterForContent.value) TOGGLE_SCREEN else COUNTER_SCREEN,
contentKey = if (showCounterForContent.value) COUNTER_SCREEN else TOGGLE_SCREEN,
content = { isBackground ->
if (showCounterForContent.value xor isBackground)
counterScreen(holder)
else
toggleScreen(holder)
}
)
}
// Start with foreground showing Counter screen.
rule.onNodeWithTag(COUNTER_SCREEN).assertTextContains("0")
rule.onNodeWithTag(COUNTER_SCREEN).performClick()
rule.waitForIdle()
rule.onNodeWithTag(COUNTER_SCREEN).assertTextContains("1")
// Swipe to switch to Toggle screen
rule.onNodeWithTag(TEST_TAG).performTouchInput({ swipeRight() })
rule.waitForIdle()
rule.onNodeWithTag(TOGGLE_SCREEN).assertIsOff()
rule.onNodeWithTag(TOGGLE_SCREEN).performClick()
rule.waitForIdle()
rule.onNodeWithTag(TOGGLE_SCREEN).assertIsOn()
// Swipe back to Counter screen
rule.onNodeWithTag(TEST_TAG).performTouchInput({ swipeRight() })
rule.waitForIdle()
rule.onNodeWithTag(COUNTER_SCREEN).assertTextContains("1")
// Swipe back to Toggle screen
rule.onNodeWithTag(TEST_TAG).performTouchInput({ swipeRight() })
rule.waitForIdle()
rule.onNodeWithTag(TOGGLE_SCREEN).assertIsOn()
}
@Test
fun gives_top_swipe_box_gestures_when_nested() {
var outerDismissed = false
var innerDismissed = false
rule.setContentWithTheme {
val outerState = rememberSwipeToDismissBoxState()
LaunchedEffect(outerState.currentValue) {
outerDismissed =
outerState.currentValue == SwipeToDismissValue.Dismissed
}
SwipeToDismissBox(
state = outerState,
modifier = Modifier.testTag("OUTER"),
hasBackground = true,
) {
Text("Outer", color = MaterialTheme.colors.onPrimary)
val innerState = rememberSwipeToDismissBoxState()
LaunchedEffect(innerState.currentValue) {
innerDismissed =
innerState.currentValue == SwipeToDismissValue.Dismissed
}
SwipeToDismissBox(
state = innerState,
modifier = Modifier.testTag("INNER"),
hasBackground = true,
) {
Text(
text = "Inner",
color = MaterialTheme.colors.onPrimary,
modifier = Modifier.testTag(TEST_TAG)
)
}
}
}
rule.onNodeWithTag(TEST_TAG).performTouchInput({ swipeRight() })
rule.runOnIdle {
assertEquals(true, innerDismissed)
assertEquals(false, outerDismissed)
}
}
@Composable
fun toggleScreen(saveableStateHolder: SaveableStateHolder) {
saveableStateHolder.SaveableStateProvider(TOGGLE_SCREEN) {
var toggle by rememberSaveable { mutableStateOf(false) }
ToggleButton(
checked = toggle,
onCheckedChange = { toggle = !toggle },
content = { Text(text = if (toggle) TOGGLE_ON else TOGGLE_OFF) },
modifier = Modifier.testTag(TOGGLE_SCREEN)
)
}
}
@Composable
fun counterScreen(saveableStateHolder: SaveableStateHolder) {
saveableStateHolder.SaveableStateProvider(COUNTER_SCREEN) {
var counter by rememberSaveable { mutableStateOf(0) }
Button(
onClick = { ++counter },
modifier = Modifier.testTag(COUNTER_SCREEN)
) {
Text(text = "" + counter)
}
}
}
@Test
fun displays_background_during_swipe() =
verifyPartialSwipe(expectedMessage = BACKGROUND_MESSAGE)
@Test
fun displays_content_during_swipe() =
verifyPartialSwipe(expectedMessage = CONTENT_MESSAGE)
@Test
fun calls_ondismissed_after_swipe_when_supplied() {
var dismissed = false
rule.setContentWithTheme {
SwipeToDismissBox(
onDismissed = { dismissed = true },
modifier = Modifier.testTag(TEST_TAG),
) {
Text(CONTENT_MESSAGE, color = MaterialTheme.colors.onPrimary)
}
}
rule.onNodeWithTag(TEST_TAG).performTouchInput({ swipeRight() })
rule.runOnIdle {
assertEquals(true, dismissed)
}
}
@Test
fun edgeswipe_modifier_edge_swiped_right_dismissed() {
verifyEdgeSwipeWithNestedScroll(
gesture = { swipeRight() },
expectedToDismiss = true
)
}
@Test
fun edgeswipe_non_edge_swiped_right_with_offset_not_dismissed() {
verifyEdgeSwipeWithNestedScroll(
gesture = { swipeRight(200f, 400f) },
expectedToDismiss = false,
initialScrollState = 200
)
}
@Test
fun edgeswipe_non_edge_swiped_right_without_offset_not_dismissed() {
verifyEdgeSwipeWithNestedScroll(
gesture = { swipeRight(200f, 400f) },
expectedToDismiss = false,
initialScrollState = 0
)
}
@Test
fun edgeswipe_edge_swiped_left_not_dismissed() {
verifyEdgeSwipeWithNestedScroll(
gesture = { swipeLeft(20f, -40f) },
expectedToDismiss = false
)
}
@Test
fun edgeswipe_non_edge_swiped_left_not_dismissed() {
verifyEdgeSwipeWithNestedScroll(
gesture = { swipeLeft(200f, 0f) },
expectedToDismiss = false
)
}
@Test
fun edgeswipe_swipe_edge_content_was_not_swiped_right() {
val initialScrollState = 200
lateinit var horizontalScrollState: ScrollState
rule.setContentWithTheme {
val state = rememberSwipeToDismissBoxState()
horizontalScrollState = rememberScrollState(initialScrollState)
SwipeToDismissBox(
state = state,
modifier = Modifier.testTag(TEST_TAG),
) {
nestedScrollContent(state, horizontalScrollState)
}
}
rule.onNodeWithTag(TEST_TAG).performTouchInput { swipeRight(0f, 200f) }
rule.runOnIdle {
assertThat(horizontalScrollState.value == initialScrollState).isTrue()
}
}
@Test
fun edgeswipe_swipe_non_edge_content_was_swiped_right() {
val initialScrollState = 200
lateinit var horizontalScrollState: ScrollState
rule.setContentWithTheme {
val state = rememberSwipeToDismissBoxState()
horizontalScrollState = rememberScrollState(initialScrollState)
SwipeToDismissBox(
state = state,
modifier = Modifier.testTag(TEST_TAG),
) {
nestedScrollContent(state, horizontalScrollState)
}
}
rule.onNodeWithTag(TEST_TAG).performTouchInput { swipeRight(200f, 400f) }
rule.runOnIdle {
assertThat(horizontalScrollState.value < initialScrollState).isTrue()
}
}
@Test
fun edgeswipe_swipe_edge_content_right_then_left_no_scroll() {
testBothDirectionScroll(
initialTouch = 10,
duration = 2000,
amplitude = 100,
startLeft = false
) { scrollState ->
assertEquals(scrollState.value, 200)
}
}
@Test
fun edgeswipe_fling_edge_content_right_then_left_no_scroll() {
testBothDirectionScroll(
initialTouch = 10,
duration = 100,
amplitude = 100,
startLeft = false
) { scrollState ->
assertEquals(scrollState.value, 200)
}
}
@Test
fun edgeswipe_swipe_edge_content_left_then_right_with_scroll() {
testBothDirectionScroll(
initialTouch = 10,
duration = 2000,
amplitude = 100,
startLeft = true
) { scrollState ->
// After scrolling to the left, successful scroll to the right
// reduced scrollState
assertThat(scrollState.value < 200).isTrue()
}
}
@Test
fun edgeswipe_fling_edge_content_left_then_right_with_scroll() {
testBothDirectionScroll(
initialTouch = 10,
duration = 100,
amplitude = 100,
startLeft = true
) { scrollState ->
// Fling right to the start (0)
assertEquals(scrollState.value, 0)
}
}
private fun testBothDirectionScroll(
initialTouch: Long,
duration: Long,
amplitude: Long,
startLeft: Boolean,
testScrollState: (ScrollState) -> Unit
) {
val initialScrollState = 200
lateinit var horizontalScrollState: ScrollState
rule.setContentWithTheme {
val state = rememberSwipeToDismissBoxState()
horizontalScrollState = rememberScrollState(initialScrollState)
SwipeToDismissBox(
state = state,
modifier = Modifier.testTag(TEST_TAG),
) {
nestedScrollContent(state, horizontalScrollState)
}
}
rule.onNodeWithTag(TEST_TAG)
.performTouchInput {
swipeBothDirections(
startLeft = startLeft,
startX = initialTouch,
amplitude = amplitude,
duration = duration
)
}
rule.runOnIdle {
testScrollState(horizontalScrollState)
}
}
private fun verifySwipe(gesture: TouchInjectionScope.() -> Unit, expectedToDismiss: Boolean) {
var dismissed = false
rule.setContentWithTheme {
val state = rememberSwipeToDismissBoxState()
LaunchedEffect(state.currentValue) {
dismissed =
state.currentValue == SwipeToDismissValue.Dismissed
}
SwipeToDismissBox(
state = state,
modifier = Modifier.testTag(TEST_TAG),
) {
messageContent()
}
}
rule.onNodeWithTag(TEST_TAG).performTouchInput(gesture)
rule.runOnIdle {
assertEquals(expectedToDismiss, dismissed)
}
}
private fun verifyEdgeSwipeWithNestedScroll(
gesture: TouchInjectionScope.() -> Unit,
expectedToDismiss: Boolean,
initialScrollState: Int = 200
) {
var dismissed = false
rule.setContentWithTheme {
val state = rememberSwipeToDismissBoxState()
val horizontalScrollState = rememberScrollState(initialScrollState)
LaunchedEffect(state.currentValue) {
dismissed =
state.currentValue == SwipeToDismissValue.Dismissed
}
SwipeToDismissBox(
state = state,
modifier = Modifier.testTag(TEST_TAG),
) {
nestedScrollContent(state, horizontalScrollState)
}
}
rule.onNodeWithTag(TEST_TAG).performTouchInput(gesture)
rule.runOnIdle {
assertEquals(expectedToDismiss, dismissed)
}
}
private fun verifyPartialSwipe(expectedMessage: String) {
rule.setContentWithTheme {
val state = rememberSwipeToDismissBoxState()
SwipeToDismissBox(
state = state,
modifier = Modifier.testTag(TEST_TAG),
) { isBackground ->
if (isBackground) Text(BACKGROUND_MESSAGE) else messageContent()
}
}
// Click down and drag across 1/4 of the screen to start a swipe,
// but don't release the finger, so that the screen can be inspected
// (note that swipeRight would release the finger and does not pause time midway).
rule.onNodeWithTag(TEST_TAG).performTouchInput(
{
down(Offset(x = 0f, y = height / 2f))
moveTo(Offset(x = width / 4f, y = height / 2f))
}
)
rule.onNodeWithText(expectedMessage).assertExists()
}
@Composable
private fun messageContent() {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Text(CONTENT_MESSAGE, color = MaterialTheme.colors.onPrimary)
}
}
@Composable
private fun nestedScrollContent(
swipeToDismissState: SwipeToDismissBoxState,
horizontalScrollState: ScrollState
) {
Box(modifier = Modifier.fillMaxSize()) {
Text(
modifier = Modifier.align(Alignment.Center)
.edgeSwipeToDismiss(swipeToDismissState)
.horizontalScroll(horizontalScrollState),
text = "This text can be scrolled horizontally - to dismiss, swipe " +
"right from the left edge of the screen (called Edge Swiping)",
)
}
}
private fun TouchInjectionScope.swipeBothDirections(
startLeft: Boolean,
startX: Long,
amplitude: Long,
duration: Long = 200
) {
val sign = if (startLeft) -1 else 1
// By using sin function for range 0.. 3pi/2 , we can achieve 0 -> 1 and 1 -> -1 values
swipe(curve = { time ->
val x =
startX + sign * sin(time.toFloat() / duration.toFloat() * 3 * Math.PI / 2)
.toFloat() * amplitude
Offset(
x = x,
y = centerY
)
}, durationMillis = duration)
}
}
private const val BACKGROUND_MESSAGE = "The Background"
private const val CONTENT_MESSAGE = "The Content"
private const val LONG_SWIPE = 1000L
private const val TOGGLE_SCREEN = "Toggle"
private const val COUNTER_SCREEN = "Counter"
private const val TOGGLE_ON = "On"
private const val TOGGLE_OFF = "Off"
| wear/compose/compose-material/src/androidAndroidTest/kotlin/androidx/wear/compose/material/SwipeToDismissBoxTest.kt | 682645139 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.dfa
import com.intellij.codeInsight.PsiEquivalenceUtil
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.codeInspection.dataFlow.interpreter.RunnerResult
import com.intellij.codeInspection.dataFlow.interpreter.StandardDataFlowInterpreter
import com.intellij.codeInspection.dataFlow.jvm.JvmDfaMemoryStateImpl
import com.intellij.codeInspection.dataFlow.lang.DfaAnchor
import com.intellij.codeInspection.dataFlow.lang.DfaListener
import com.intellij.codeInspection.dataFlow.lang.UnsatisfiedConditionProblem
import com.intellij.codeInspection.dataFlow.lang.ir.DataFlowIRProvider
import com.intellij.codeInspection.dataFlow.lang.ir.DfaInstructionState
import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState
import com.intellij.codeInspection.dataFlow.types.DfType
import com.intellij.codeInspection.dataFlow.types.DfTypes
import com.intellij.codeInspection.dataFlow.value.DfaValue
import com.intellij.codeInspection.dataFlow.value.DfaValueFactory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.siblings
import com.intellij.util.ThreeState
import org.jetbrains.kotlin.caches.resolve.KotlinCacheService
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.inspections.dfa.KotlinAnchor.*
import org.jetbrains.kotlin.idea.inspections.dfa.KotlinProblem.*
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.isConstant
import org.jetbrains.kotlin.idea.intentions.negate
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.readWriteAccess
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.isNull
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.typeUtil.isNullableNothing
class KotlinConstantConditionsInspection : AbstractKotlinInspection() {
private enum class ConstantValue {
TRUE, FALSE, NULL, ZERO, UNKNOWN
}
private class KotlinDfaListener : DfaListener {
val constantConditions = hashMapOf<KotlinAnchor, ConstantValue>()
val problems = hashMapOf<KotlinProblem, ThreeState>()
override fun beforePush(args: Array<out DfaValue>, value: DfaValue, anchor: DfaAnchor, state: DfaMemoryState) {
if (anchor is KotlinAnchor) {
recordExpressionValue(anchor, state, value)
}
}
override fun onCondition(problem: UnsatisfiedConditionProblem, value: DfaValue, failed: ThreeState, state: DfaMemoryState) {
if (problem is KotlinProblem) {
problems.merge(problem, failed, ThreeState::merge)
}
}
private fun recordExpressionValue(anchor: KotlinAnchor, state: DfaMemoryState, value: DfaValue) {
val oldVal = constantConditions[anchor]
if (oldVal == ConstantValue.UNKNOWN) return
var newVal = when (val dfType = state.getDfType(value)) {
DfTypes.TRUE -> ConstantValue.TRUE
DfTypes.FALSE -> ConstantValue.FALSE
DfTypes.NULL -> ConstantValue.NULL
else -> {
val constVal: Number? = dfType.getConstantOfType(Number::class.java)
if (constVal != null && (constVal == 0 || constVal == 0L)) ConstantValue.ZERO
else ConstantValue.UNKNOWN
}
}
if (oldVal != null && oldVal != newVal) {
newVal = ConstantValue.UNKNOWN
}
constantConditions[anchor] = newVal
}
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
// Non-JVM is not supported now
if (holder.file.module?.platform?.isJvm() != true) return PsiElementVisitor.EMPTY_VISITOR
return object : KtVisitorVoid() {
override fun visitProperty(property: KtProperty) {
if (shouldAnalyzeProperty(property)) {
val initializer = property.delegateExpressionOrInitializer ?: return
analyze(initializer)
}
}
override fun visitPropertyAccessor(accessor: KtPropertyAccessor) {
if (shouldAnalyzeProperty(accessor.property)) {
val bodyExpression = accessor.bodyExpression ?: accessor.bodyBlockExpression ?: return
analyze(bodyExpression)
}
}
override fun visitParameter(parameter: KtParameter) {
analyze(parameter.defaultValue ?: return)
}
private fun shouldAnalyzeProperty(property: KtProperty) =
property.isTopLevel || property.parent is KtClassBody
override fun visitClassInitializer(initializer: KtClassInitializer) {
analyze(initializer.body ?: return)
}
override fun visitNamedFunction(function: KtNamedFunction) {
val body = function.bodyExpression ?: function.bodyBlockExpression ?: return
analyze(body)
}
private fun analyze(body: KtExpression) {
val factory = DfaValueFactory(holder.project)
processDataflowAnalysis(factory, body, holder, listOf(JvmDfaMemoryStateImpl(factory)))
}
}
}
private fun processDataflowAnalysis(
factory: DfaValueFactory,
body: KtExpression,
holder: ProblemsHolder,
states: Collection<DfaMemoryState>
) {
val flow = DataFlowIRProvider.forElement(body, factory) ?: return
val listener = KotlinDfaListener()
val interpreter = StandardDataFlowInterpreter(flow, listener)
if (interpreter.interpret(states.map { s -> DfaInstructionState(flow.getInstruction(0), s) }) != RunnerResult.OK) return
reportProblems(listener, holder)
for ((closure, closureStates) in interpreter.closures.entrySet()) {
if (closure is KtExpression) {
processDataflowAnalysis(factory, closure, holder, closureStates)
}
}
}
private fun reportProblems(
listener: KotlinDfaListener,
holder: ProblemsHolder
) {
listener.constantConditions.forEach { (anchor, cv) ->
if (cv != ConstantValue.UNKNOWN) {
when (anchor) {
is KotlinExpressionAnchor -> {
val expr = anchor.expression
if (!shouldSuppress(cv, expr)) {
val key = when (cv) {
ConstantValue.TRUE ->
if (shouldReportAsValue(expr))
"inspection.message.value.always.true"
else if (logicalChain(expr))
"inspection.message.condition.always.true.when.reached"
else
"inspection.message.condition.always.true"
ConstantValue.FALSE ->
if (shouldReportAsValue(expr))
"inspection.message.value.always.false"
else if (logicalChain(expr))
"inspection.message.condition.always.false.when.reached"
else
"inspection.message.condition.always.false"
ConstantValue.NULL -> "inspection.message.value.always.null"
ConstantValue.ZERO -> "inspection.message.value.always.zero"
else -> throw IllegalStateException("Unexpected constant: $cv")
}
val highlightType =
if (shouldReportAsValue(expr)) ProblemHighlightType.WEAK_WARNING
else ProblemHighlightType.GENERIC_ERROR_OR_WARNING
holder.registerProblem(expr, KotlinBundle.message(key, expr.text), highlightType)
}
}
is KotlinWhenConditionAnchor -> {
val condition = anchor.condition
if (!shouldSuppressWhenCondition(cv, condition)) {
val message = KotlinBundle.message("inspection.message.when.condition.always.false")
if (cv == ConstantValue.FALSE) {
holder.registerProblem(condition, message)
} else if (cv == ConstantValue.TRUE) {
condition.siblings(forward = true, withSelf = false)
.filterIsInstance<KtWhenCondition>()
.forEach { cond -> holder.registerProblem(cond, message) }
val nextEntry = condition.parent as? KtWhenEntry ?: return@forEach
nextEntry.siblings(forward = true, withSelf = false)
.filterIsInstance<KtWhenEntry>()
.filterNot { entry -> entry.isElse }
.flatMap { entry -> entry.conditions.asSequence() }
.forEach { cond -> holder.registerProblem(cond, message) }
}
}
}
is KotlinForVisitedAnchor -> {
val loopRange = anchor.forExpression.loopRange!!
if (cv == ConstantValue.FALSE && !shouldSuppressForCondition(loopRange)) {
val message = KotlinBundle.message("inspection.message.for.never.visited")
holder.registerProblem(loopRange, message)
}
}
}
}
}
listener.problems.forEach { (problem, state) ->
if (state == ThreeState.YES) {
when (problem) {
is KotlinArrayIndexProblem ->
holder.registerProblem(problem.index, KotlinBundle.message("inspection.message.index.out.of.bounds"))
is KotlinNullCheckProblem -> {
val expr = problem.expr
if (expr.baseExpression?.isNull() != true) {
holder.registerProblem(expr.operationReference, KotlinBundle.message("inspection.message.nonnull.cast.will.always.fail"))
}
}
is KotlinCastProblem -> {
val anchor = (problem.cast as? KtBinaryExpressionWithTypeRHS)?.operationReference ?: problem.cast
if (!isCompilationWarning(anchor)) {
holder.registerProblem(anchor, KotlinBundle.message("inspection.message.cast.will.always.fail"))
}
}
}
}
}
}
private fun shouldSuppressForCondition(loopRange: KtExpression): Boolean {
if (loopRange is KtBinaryExpression) {
val left = loopRange.left
val right = loopRange.right
// Reported separately by EmptyRangeInspection
return left != null && right != null && left.isConstant() && right.isConstant()
}
return false
}
private fun shouldReportAsValue(expr: KtExpression) =
expr is KtSimpleNameExpression || expr is KtQualifiedExpression && expr.selectorExpression is KtSimpleNameExpression
private fun logicalChain(expr: KtExpression): Boolean {
var context = expr
var parent = context.parent
while (parent is KtParenthesizedExpression) {
context = parent
parent = context.parent
}
if (parent is KtBinaryExpression && parent.right == context) {
val token = parent.operationToken
return token == KtTokens.ANDAND || token == KtTokens.OROR
}
return false
}
private fun shouldSuppressWhenCondition(
cv: ConstantValue,
condition: KtWhenCondition
): Boolean {
if (cv != ConstantValue.FALSE && cv != ConstantValue.TRUE) return true
if (cv == ConstantValue.TRUE && isLastCondition(condition)) return true
if (condition.textLength == 0) return true
return isCompilationWarning(condition)
}
private fun isLastCondition(condition: KtWhenCondition): Boolean {
val entry = condition.parent as? KtWhenEntry ?: return false
val whenExpr = entry.parent as? KtWhenExpression ?: return false
if (entry.conditions.last() == condition) {
val entries = whenExpr.entries
val lastEntry = entries.last()
if (lastEntry == entry) return true
val size = entries.size
// Also, do not report the always reachable entry right before 'else',
// usually it's necessary for the smart-cast, or for definite assignment, and the report is just noise
if (lastEntry.isElse && size > 1 && entries[size - 2] == entry) return true
}
return false
}
companion object {
private fun areEquivalent(e1: KtElement, e2: KtElement): Boolean {
return PsiEquivalenceUtil.areElementsEquivalent(e1, e2,
{ref1, ref2 -> ref1.element.text.compareTo(ref2.element.text)},
null, null, false)
}
private tailrec fun isOppositeCondition(candidate: KtExpression?, template: KtBinaryExpression, expression: KtExpression): Boolean {
if (candidate !is KtBinaryExpression || candidate.operationToken !== KtTokens.ANDAND) return false
val left = candidate.left
val right = candidate.right
if (left == null || right == null) return false
val templateLeft = template.left
val templateRight = template.right
if (templateLeft == null || templateRight == null) return false
if (templateRight === expression) {
return areEquivalent(left, templateLeft) && areEquivalent(right.negate(false), templateRight)
}
if (!areEquivalent(right, templateRight)) return false
if (templateLeft === expression) {
return areEquivalent(left.negate(false), templateLeft)
}
if (templateLeft !is KtBinaryExpression || templateLeft.operationToken !== KtTokens.ANDAND) return false
return isOppositeCondition(left, templateLeft, expression)
}
private fun hasOppositeCondition(whenExpression: KtWhenExpression, topCondition: KtExpression, expression: KtExpression): Boolean {
for (entry in whenExpression.entries) {
for (condition in entry.conditions) {
if (condition is KtWhenConditionWithExpression) {
val candidate = condition.expression
if (candidate === topCondition) return false
if (topCondition is KtBinaryExpression && isOppositeCondition(candidate, topCondition, expression)) return true
if (candidate != null && areEquivalent(expression.negate(false), candidate)) return true
}
}
}
return false
}
/**
* Returns true if expression is part of when condition expression that looks like
* ```
* when {
* a && b -> ...
* a && !b -> ...
* }
* ```
* In this case, !b could be reported as 'always true' but such warnings are annoying
*/
private fun isPairingConditionInWhen(expression: KtExpression): Boolean {
val parent = expression.parent
if (parent is KtBinaryExpression && parent.operationToken == KtTokens.ANDAND) {
var topAnd: KtBinaryExpression = parent
while (true) {
val nextParent = topAnd.parent
if (nextParent is KtBinaryExpression && nextParent.operationToken == KtTokens.ANDAND) {
topAnd = nextParent
} else break
}
val topAndParent = topAnd.parent
if (topAndParent is KtWhenConditionWithExpression) {
val whenExpression = (topAndParent.parent as? KtWhenEntry)?.parent as? KtWhenExpression
if (whenExpression != null && hasOppositeCondition(whenExpression, topAnd, expression)) {
return true
}
}
}
if (parent is KtWhenConditionWithExpression) {
val whenExpression = (parent.parent as? KtWhenEntry)?.parent as? KtWhenExpression
if (whenExpression != null && hasOppositeCondition(whenExpression, expression, expression)) {
return true
}
}
return false
}
private fun isCompilationWarning(anchor: KtElement): Boolean
{
val context = anchor.analyze(BodyResolveMode.FULL)
if (context.diagnostics.forElement(anchor).any
{ it.factory == Errors.CAST_NEVER_SUCCEEDS
|| it.factory == Errors.SENSELESS_COMPARISON
|| it.factory == Errors.SENSELESS_NULL_IN_WHEN
|| it.factory == Errors.USELESS_IS_CHECK
|| it.factory == Errors.DUPLICATE_LABEL_IN_WHEN }
) {
return true
}
val rootElement = anchor.containingFile
val suppressionCache = KotlinCacheService.getInstance(anchor.project).getSuppressionCache()
return suppressionCache.isSuppressed(anchor, rootElement, "CAST_NEVER_SUCCEEDS", Severity.WARNING) ||
suppressionCache.isSuppressed(anchor, rootElement, "SENSELESS_COMPARISON", Severity.WARNING) ||
suppressionCache.isSuppressed(anchor, rootElement, "SENSELESS_NULL_IN_WHEN", Severity.WARNING) ||
suppressionCache.isSuppressed(anchor, rootElement, "USELESS_IS_CHECK", Severity.WARNING) ||
suppressionCache.isSuppressed(anchor, rootElement, "DUPLICATE_LABEL_IN_WHEN", Severity.WARNING)
}
private fun isCallToMethod(call: KtCallExpression, packageName: String, methodName: String): Boolean {
val descriptor = call.resolveToCall()?.resultingDescriptor ?: return false
if (descriptor.name.asString() != methodName) return false
val packageFragment = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false
return packageFragment.fqName.asString() == packageName
}
// Do not report x.let { true } or x.let { false } as it's pretty evident
private fun isLetConstant(expr: KtExpression): Boolean {
val call = (expr as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression ?: return false
if (!isCallToMethod(call, "kotlin", "let")) return false
val lambda = call.lambdaArguments.singleOrNull()?.getLambdaExpression() ?: return false
return lambda.bodyExpression?.statements?.singleOrNull() is KtConstantExpression
}
// Do not report on also, as it always returns the qualifier. If necessary, qualifier itself will be reported
private fun isAlsoChain(expr: KtExpression): Boolean {
val call = (expr as? KtQualifiedExpression)?.selectorExpression as? KtCallExpression ?: return false
return isCallToMethod(call, "kotlin", "also")
}
private fun isAssertion(parent: PsiElement?, value: Boolean): Boolean {
return when (parent) {
is KtBinaryExpression ->
(parent.operationToken == KtTokens.ANDAND || parent.operationToken == KtTokens.OROR) && isAssertion(parent.parent, value)
is KtParenthesizedExpression ->
isAssertion(parent.parent, value)
is KtPrefixExpression ->
parent.operationToken == KtTokens.EXCL && isAssertion(parent.parent, !value)
is KtValueArgument -> {
if (!value) return false
val valueArgList = parent.parent as? KtValueArgumentList ?: return false
val call = valueArgList.parent as? KtCallExpression ?: return false
val descriptor = call.resolveToCall()?.resultingDescriptor ?: return false
val name = descriptor.name.asString()
if (name != "assert" && name != "require" && name != "check") return false
val pkg = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false
return pkg.fqName.asString() == "kotlin"
}
else -> false
}
}
private fun hasWritesTo(block: PsiElement?, variable: KtProperty): Boolean {
return !PsiTreeUtil.processElements(block, KtSimpleNameExpression::class.java) { ref ->
val write = ref.mainReference.isReferenceTo(variable) && ref.readWriteAccess(false).isWrite
!write
}
}
private fun isUpdateChain(expression: KtExpression): Boolean {
// x = x or ..., etc.
if (expression !is KtSimpleNameExpression) return false
val binOp = expression.parent as? KtBinaryExpression ?: return false
val op = binOp.operationReference.text
if (op != "or" && op != "and" && op != "xor" && op != "||" && op != "&&") return false
val assignment = binOp.parent as? KtBinaryExpression ?: return false
if (assignment.operationToken != KtTokens.EQ) return false
val left = assignment.left
if (left !is KtSimpleNameExpression || !left.textMatches(expression.text)) return false
val variable = expression.mainReference.resolve() as? KtProperty ?: return false
val varParent = variable.parent as? KtBlockExpression ?: return false
var context: PsiElement = assignment
var block = context.parent
while (block is KtContainerNode ||
block is KtBlockExpression && block.statements.first() == context ||
block is KtIfExpression && block.then?.parent == context && block.`else` == null && !hasWritesTo(block.condition, variable)
) {
context = block
block = context.parent
}
if (block !== varParent) return false
var curExpression = variable.nextSibling
while (curExpression != context) {
if (hasWritesTo(curExpression, variable)) return false
curExpression = curExpression.nextSibling
}
return true
}
fun shouldSuppress(value: DfType, expression: KtExpression): Boolean {
val constant = when(value) {
DfTypes.NULL -> ConstantValue.NULL
DfTypes.TRUE -> ConstantValue.TRUE
DfTypes.FALSE -> ConstantValue.FALSE
DfTypes.intValue(0), DfTypes.longValue(0) -> ConstantValue.ZERO
else -> ConstantValue.UNKNOWN
}
return shouldSuppress(constant, expression)
}
private fun shouldSuppress(value: ConstantValue, expression: KtExpression): Boolean {
// TODO: do something with always false branches in exhaustive when statements
// TODO: return x && y.let {return...}
var parent = expression.parent
if (parent is KtDotQualifiedExpression && parent.selectorExpression == expression) {
// Will be reported for parent qualified expression
return true
}
while (parent is KtParenthesizedExpression) {
parent = parent.parent
}
if (expression is KtConstantExpression ||
// If result of initialization is constant, then the initializer will be reported
expression is KtProperty ||
// If result of assignment is constant, then the right-hand part will be reported
expression is KtBinaryExpression && expression.operationToken == KtTokens.EQ ||
// Negation operand: negation itself will be reported
(parent as? KtPrefixExpression)?.operationToken == KtTokens.EXCL
) {
return true
}
if (expression is KtBinaryExpression && expression.operationToken == KtTokens.ELVIS) {
// Left part of Elvis is Nothing?, so the right part is always executed
// Could be caused by code like return x?.let { return ... } ?: true
// While inner "return" is redundant, the "always true" warning is confusing
// probably separate inspection could report extra "return"
if (expression.left?.getKotlinType()?.isNullableNothing() == true) {
return true
}
}
if (isAlsoChain(expression) || isLetConstant(expression) || isUpdateChain(expression)) return true
when (value) {
ConstantValue.TRUE -> {
if (isSmartCastNecessary(expression, true)) return true
if (isPairingConditionInWhen(expression)) return true
if (isAssertion(parent, true)) return true
}
ConstantValue.FALSE -> {
if (isSmartCastNecessary(expression, false)) return true
if (isAssertion(parent, false)) return true
}
ConstantValue.ZERO -> {
if (expression.readWriteAccess(false).isWrite) {
// like if (x == 0) x++, warning would be somewhat annoying
return true
}
if (expression is KtDotQualifiedExpression && expression.selectorExpression?.textMatches("ordinal") == true) {
var receiver: KtExpression? = expression.receiverExpression
if (receiver is KtQualifiedExpression) {
receiver = receiver.selectorExpression
}
if (receiver is KtSimpleNameExpression && receiver.mainReference.resolve() is KtEnumEntry) {
// ordinal() call on explicit enum constant
return true
}
}
val bindingContext = expression.analyze()
if (ConstantExpressionEvaluator.getConstant(expression, bindingContext) != null) return true
if (expression is KtSimpleNameExpression &&
(parent is KtValueArgument || parent is KtContainerNode && parent.parent is KtArrayAccessExpression)
) {
// zero value is passed as argument to another method or used for array access. Often, such a warning is annoying
return true
}
}
ConstantValue.NULL -> {
if (parent is KtProperty && parent.typeReference == null && expression is KtSimpleNameExpression) {
// initialize other variable with null to copy type, like
// var x1 : X = null
// var x2 = x1 -- let's suppress this
return true
}
if (expression is KtBinaryExpressionWithTypeRHS && expression.left.isNull()) {
// like (null as? X)
return true
}
if (parent is KtBinaryExpression) {
val token = parent.operationToken
if ((token === KtTokens.EQEQ || token === KtTokens.EXCLEQ || token === KtTokens.EQEQEQ || token === KtTokens.EXCLEQEQEQ) &&
(parent.left?.isNull() == true || parent.right?.isNull() == true)
) {
// like if (x == null) when 'x' is known to be null: report 'always true' instead
return true
}
}
val kotlinType = expression.getKotlinType()
if (kotlinType.toDfType() == DfTypes.NULL) {
// According to type system, nothing but null could be stored in such an expression (likely "Void?" type)
return true
}
}
else -> {}
}
if (expression is KtSimpleNameExpression) {
val target = expression.mainReference.resolve()
if (target is KtProperty && !target.isVar && target.initializer is KtConstantExpression) {
// suppress warnings uses of boolean constant like 'val b = true'
return true
}
}
if (isCompilationWarning(expression)) {
return true
}
return expression.isUsedAsStatement(expression.analyze(BodyResolveMode.FULL))
}
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KotlinConstantConditionsInspection.kt | 3160508416 |
/*
* Copyright (c) 2017 Lizhaotailang
*
* 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 io.github.tonnyl.mango.ui.main.shots
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.github.tonnyl.mango.R
import io.github.tonnyl.mango.data.Shot
import io.github.tonnyl.mango.glide.GlideLoader
import kotlinx.android.synthetic.main.item_shot.view.*
/**
* Created by lizhaotailang on 2017/6/29.
*/
class ShotsAdapter(context: Context, list: List<Shot>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var mContext = context
private var mList = list
private var mListener: OnRecyclerViewItemClickListener? = null
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
return ShotViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_shot, parent, false), mListener)
}
override fun onBindViewHolder(holderFollower: RecyclerView.ViewHolder?, position: Int) {
if (position <= mList.size) {
val shot = mList[position]
with(holderFollower as ShotViewHolder) {
GlideLoader.loadAvatar(itemView.avatar, shot.user?.avatarUrl)
GlideLoader.loadNormal(itemView.shot_image_view, shot.images.best())
itemView.tag_gif.visibility = if (shot.animated) View.VISIBLE else View.GONE
itemView.shot_title.text = mContext.getString(R.string.shot_title).format(shot.user?.name, shot.title)
}
}
}
override fun getItemCount() = mList.size
fun setItemClickListener(listener: OnRecyclerViewItemClickListener) {
mListener = listener
}
inner class ShotViewHolder(itemView: View, listener: OnRecyclerViewItemClickListener?) : RecyclerView.ViewHolder(itemView) {
private val mListener = listener
init {
itemView.avatar.setOnClickListener({ view ->
mListener?.onAvatarClick(view, layoutPosition)
})
itemView.setOnClickListener({ view ->
mListener?.onItemClick(view, layoutPosition)
})
}
}
} | app/src/main/java/io/github/tonnyl/mango/ui/main/shots/ShotsAdapter.kt | 1600060919 |
// 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.collaboration.ui.codereview.list.search
abstract class PersistingReviewListSearchHistoryModel<S : ReviewListSearchValue>(
private val historySizeLimit: Int = 10
) : ReviewListSearchHistoryModel<S> {
override fun getHistory(): List<S> = persistentHistory
protected abstract var persistentHistory: List<S>
override fun add(search: S) {
persistentHistory = persistentHistory.toMutableList().apply {
remove(search)
add(search)
}.takeLast(historySizeLimit)
}
} | platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/list/search/PersistingReviewListSearchHistoryModel.kt | 2948723525 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.tree.IElementType
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.copied
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.isTrueConstant
import org.jetbrains.kotlin.lexer.KtTokens.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.psi2ir.deparenthesize
import org.jetbrains.kotlin.resolve.CompileTimeConstantUtils
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode.PARTIAL
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.isFlexible
@Suppress("DEPRECATION")
class SimplifyBooleanWithConstantsInspection : IntentionBasedInspection<KtBinaryExpression>(SimplifyBooleanWithConstantsIntention::class) {
override fun inspectionProblemText(element: KtBinaryExpression): String {
return KotlinBundle.message("inspection.simplify.boolean.with.constants.display.name")
}
}
class SimplifyBooleanWithConstantsIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>(
KtBinaryExpression::class.java,
KotlinBundle.lazyMessage("simplify.boolean.expression")
) {
override fun isApplicableTo(element: KtBinaryExpression): Boolean = areThereExpressionsToBeSimplified(element.topBinary())
private fun KtBinaryExpression.topBinary(): KtBinaryExpression =
this.parentsWithSelf.takeWhile { it is KtBinaryExpression }.lastOrNull() as? KtBinaryExpression ?: this
private fun areThereExpressionsToBeSimplified(element: KtExpression?): Boolean {
if (element == null) return false
when (element) {
is KtParenthesizedExpression -> return areThereExpressionsToBeSimplified(element.expression)
is KtBinaryExpression -> {
val op = element.operationToken
if (op == ANDAND || op == OROR || op == EQEQ || op == EXCLEQ) {
if (areThereExpressionsToBeSimplified(element.left) && element.right.hasBooleanType()) return true
if (areThereExpressionsToBeSimplified(element.right) && element.left.hasBooleanType()) return true
}
if (isPositiveNegativeZeroComparison(element)) return false
}
}
return element.canBeReducedToBooleanConstant()
}
private fun isPositiveNegativeZeroComparison(element: KtBinaryExpression): Boolean {
val op = element.operationToken
if (op != EQEQ && op != EQEQEQ) {
return false
}
val left = element.left?.deparenthesize() as? KtExpression ?: return false
val right = element.right?.deparenthesize() as? KtExpression ?: return false
val context = element.safeAnalyzeNonSourceRootCode(PARTIAL)
fun KtExpression.getConstantValue() =
ConstantExpressionEvaluator.getConstant(this, context)?.toConstantValue(TypeUtils.NO_EXPECTED_TYPE)?.value
val leftValue = left.getConstantValue()
val rightValue = right.getConstantValue()
fun isPositiveZero(value: Any?) = value == +0.0 || value == +0.0f
fun isNegativeZero(value: Any?) = value == -0.0 || value == -0.0f
val hasPositiveZero = isPositiveZero(leftValue) || isPositiveZero(rightValue)
val hasNegativeZero = isNegativeZero(leftValue) || isNegativeZero(rightValue)
return hasPositiveZero && hasNegativeZero
}
override fun applyTo(element: KtBinaryExpression, editor: Editor?) {
val topBinary = element.topBinary()
val simplified = toSimplifiedExpression(topBinary)
val result = topBinary.replaced(KtPsiUtil.safeDeparenthesize(simplified, true))
removeRedundantAssertion(result)
}
internal fun removeRedundantAssertion(expression: KtExpression) {
val callExpression = expression.getNonStrictParentOfType<KtCallExpression>() ?: return
val fqName = callExpression.getCallableDescriptor()?.fqNameOrNull()
val valueArguments = callExpression.valueArguments
val isRedundant = fqName?.asString() == "kotlin.assert" &&
valueArguments.singleOrNull()?.getArgumentExpression().isTrueConstant()
if (isRedundant) callExpression.delete()
}
private fun toSimplifiedExpression(expression: KtExpression): KtExpression {
val psiFactory = KtPsiFactory(expression)
when {
expression.canBeReducedToTrue() -> {
return psiFactory.createExpression("true")
}
expression.canBeReducedToFalse() -> {
return psiFactory.createExpression("false")
}
expression is KtParenthesizedExpression -> {
val expr = expression.expression
if (expr != null) {
val simplified = toSimplifiedExpression(expr)
return if (simplified is KtBinaryExpression) {
// wrap in new parentheses to keep the user's original format
psiFactory.createExpressionByPattern("($0)", simplified)
} else {
// if we now have a simpleName, constant, or parenthesized we don't need parentheses
simplified
}
}
}
expression is KtBinaryExpression -> {
if (!areThereExpressionsToBeSimplified(expression)) return expression.copied()
val left = expression.left
val right = expression.right
val op = expression.operationToken
if (left != null && right != null && (op == ANDAND || op == OROR || op == EQEQ || op == EXCLEQ)) {
val simpleLeft = simplifyExpression(left)
val simpleRight = simplifyExpression(right)
return when {
simpleLeft.canBeReducedToTrue() -> toSimplifiedBooleanBinaryExpressionWithConstantOperand(true, simpleRight, op)
simpleLeft.canBeReducedToFalse() -> toSimplifiedBooleanBinaryExpressionWithConstantOperand(false, simpleRight, op)
simpleRight.canBeReducedToTrue() -> toSimplifiedBooleanBinaryExpressionWithConstantOperand(true, simpleLeft, op)
simpleRight.canBeReducedToFalse() -> toSimplifiedBooleanBinaryExpressionWithConstantOperand(false, simpleLeft, op)
else -> {
val opText = expression.operationReference.text
psiFactory.createExpressionByPattern("$0 $opText $1", simpleLeft, simpleRight)
}
}
}
}
}
return expression.copied()
}
private fun toSimplifiedBooleanBinaryExpressionWithConstantOperand(
constantOperand: Boolean,
otherOperand: KtExpression,
operation: IElementType
): KtExpression {
val factory = KtPsiFactory(otherOperand)
when (operation) {
OROR -> {
if (constantOperand) return factory.createExpression("true")
}
ANDAND -> {
if (!constantOperand) return factory.createExpression("false")
}
EQEQ, EXCLEQ -> toSimplifiedExpression(otherOperand).let {
return if (constantOperand == (operation == EQEQ)) it
else factory.createExpressionByPattern("!$0", it)
}
}
return toSimplifiedExpression(otherOperand)
}
private fun simplifyExpression(expression: KtExpression) = expression.replaced(toSimplifiedExpression(expression))
private fun KtExpression?.hasBooleanType(): Boolean {
val type = this?.getType(safeAnalyzeNonSourceRootCode(PARTIAL)) ?: return false
return KotlinBuiltIns.isBoolean(type) && !type.isFlexible()
}
private fun KtExpression.canBeReducedToBooleanConstant(constant: Boolean? = null): Boolean =
CompileTimeConstantUtils.canBeReducedToBooleanConstant(this, safeAnalyzeNonSourceRootCode(PARTIAL), constant)
private fun KtExpression.canBeReducedToTrue() = canBeReducedToBooleanConstant(true)
private fun KtExpression.canBeReducedToFalse() = canBeReducedToBooleanConstant(false)
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/SimplifyBooleanWithConstantsIntention.kt | 1033530441 |
package com.example.android.inventory.ui
import android.text.Editable
import android.text.TextWatcher
class ItemTextWatcher(private val onTextChanged: (String) -> Unit) : TextWatcher {
override fun afterTextChanged(p0: Editable?) {
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
onTextChanged(p0.toString())
}
} | app/src/main/java/com/example/android/inventory/ui/ItemTextWatcher.kt | 2524401983 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.editorconfig.language.schema.descriptors.impl
import com.intellij.psi.PsiElement
import org.editorconfig.language.psi.EditorConfigFlatOptionKey
import org.editorconfig.language.psi.EditorConfigOptionValueIdentifier
import org.editorconfig.language.psi.EditorConfigQualifiedKeyPart
import org.editorconfig.language.schema.descriptors.EditorConfigDescriptor
import org.editorconfig.language.schema.descriptors.EditorConfigDescriptorVisitor
import org.editorconfig.language.schema.descriptors.EditorConfigMutableDescriptor
data class EditorConfigDeclarationDescriptor(
val id: String,
val needsReferences: Boolean,
val isRequired: Boolean,
override val documentation: String?,
override val deprecation: String?
) : EditorConfigMutableDescriptor {
override var parent: EditorConfigDescriptor? = null
override fun accept(visitor: EditorConfigDescriptorVisitor) = visitor.visitDeclaration(this)
override fun matches(element: PsiElement) =
element is EditorConfigFlatOptionKey
|| element is EditorConfigQualifiedKeyPart
|| element is EditorConfigOptionValueIdentifier
}
| plugins/editorconfig/src/org/editorconfig/language/schema/descriptors/impl/EditorConfigDeclarationDescriptor.kt | 4256019817 |
// 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.util.indexing.diagnostic.dto
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
data class JsonProjectIndexingHistory(
val projectName: String = "",
val times: JsonProjectIndexingHistoryTimes = JsonProjectIndexingHistoryTimes(),
val fileCount: JsonProjectIndexingFileCount = JsonProjectIndexingFileCount(),
val totalStatsPerFileType: List<JsonStatsPerFileType> = emptyList(),
val totalStatsPerIndexer: List<JsonStatsPerIndexer> = emptyList(),
val scanningStatistics: List<JsonScanningStatistics> = emptyList(),
val fileProviderStatistics: List<JsonFileProviderIndexStatistics> = emptyList(),
val visibleTimeToAllThreadTimeRatio: Double = 0.0
) {
@JsonIgnoreProperties(ignoreUnknown = true)
data class JsonStatsPerFileType(
val fileType: String = "",
val partOfTotalProcessingTime: JsonPercentages = JsonPercentages(),
val partOfTotalContentLoadingTime: JsonPercentages = JsonPercentages(),
val totalNumberOfFiles: Int = 0,
val totalFilesSize: JsonFileSize = JsonFileSize(),
/**
* bytes to total (not visible) processing (not just indexing) time
*/
val totalProcessingSpeed: JsonProcessingSpeed = JsonProcessingSpeed(),
val biggestContributors: List<JsonBiggestFileTypeContributor> = emptyList()
) {
@JsonIgnoreProperties(ignoreUnknown = true)
data class JsonBiggestFileTypeContributor(
val providerName: String = "",
val numberOfFiles: Int = 0,
val totalFilesSize: JsonFileSize = JsonFileSize(),
val partOfTotalProcessingTimeOfThisFileType: JsonPercentages = JsonPercentages()
)
}
@JsonIgnoreProperties(ignoreUnknown = true)
data class JsonStatsPerIndexer(
val indexId: String = "",
val partOfTotalIndexingTime: JsonPercentages = JsonPercentages(),
val totalNumberOfFiles: Int = 0,
val totalNumberOfFilesIndexedByExtensions: Int = 0,
val totalFilesSize: JsonFileSize = JsonFileSize(),
val indexValueChangerEvaluationSpeed: JsonProcessingSpeed = JsonProcessingSpeed(),
val snapshotInputMappingStats: JsonSnapshotInputMappingStats = JsonSnapshotInputMappingStats()
) {
@JsonIgnoreProperties(ignoreUnknown = true)
data class JsonSnapshotInputMappingStats(
val totalRequests: Long = 0,
val totalMisses: Long = 0,
val totalHits: Long = 0
)
}
} | platform/lang-impl/src/com/intellij/util/indexing/diagnostic/dto/JsonProjectIndexingHistory.kt | 3208867952 |
// 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.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.core.setType
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtNullableType
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.typeUtil.makeNullable
class ConvertLateinitPropertyToNullableIntention : SelfTargetingIntention<KtProperty>(
KtProperty::class.java, KotlinBundle.lazyMessage("convert.to.nullable.var")
) {
override fun isApplicableTo(element: KtProperty, caretOffset: Int): Boolean = element.hasModifier(KtTokens.LATEINIT_KEYWORD)
&& element.isVar
&& element.typeReference?.typeElement !is KtNullableType
&& element.initializer == null
override fun applyTo(element: KtProperty, editor: Editor?) {
val typeReference: KtTypeReference = element.typeReference ?: return
val nullableType = element.analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, typeReference]?.makeNullable() ?: return
element.removeModifier(KtTokens.LATEINIT_KEYWORD)
element.setType(nullableType)
element.initializer = KtPsiFactory(element).createExpression(KtTokens.NULL_KEYWORD.value)
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertLateinitPropertyToNullableIntention.kt | 2867935680 |
// WITH_RUNTIME
// FIX: none
fun test(x: Int) {
val p = { _: String -> true }
x.run {<caret> p::invoke }
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/suspiciousCallableReferenceInLambda/invalidFunctionReference2.kt | 845556089 |
/*
* 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 kotlinx.cinterop
import kotlin.native.*
data class Pinned<out T : Any> internal constructor(private val stablePtr: COpaquePointer) {
/**
* Disposes the handle. It must not be [used][get] after that.
*/
fun unpin() {
disposeStablePointer(this.stablePtr)
}
/**
* Returns the underlying pinned object.
*/
fun get(): T = @Suppress("UNCHECKED_CAST") (derefStablePointer(stablePtr) as T)
}
fun <T : Any> T.pin() = Pinned<T>(createStablePointer(this))
inline fun <T : Any, R> T.usePinned(block: (Pinned<T>) -> R): R {
val pinned = this.pin()
return try {
block(pinned)
} finally {
pinned.unpin()
}
}
fun Pinned<ByteArray>.addressOf(index: Int): CPointer<ByteVar> = this.get().addressOfElement(index)
fun ByteArray.refTo(index: Int): CValuesRef<ByteVar> = this.usingPinned { addressOf(index) }
fun Pinned<String>.addressOf(index: Int): CPointer<COpaque> = this.get().addressOfElement(index)
fun String.refTo(index: Int): CValuesRef<COpaque> = this.usingPinned { addressOf(index) }
fun Pinned<CharArray>.addressOf(index: Int): CPointer<COpaque> = this.get().addressOfElement(index)
fun CharArray.refTo(index: Int): CValuesRef<COpaque> = this.usingPinned { addressOf(index) }
fun Pinned<ShortArray>.addressOf(index: Int): CPointer<ShortVar> = this.get().addressOfElement(index)
fun ShortArray.refTo(index: Int): CValuesRef<ShortVar> = this.usingPinned { addressOf(index) }
fun Pinned<IntArray>.addressOf(index: Int): CPointer<IntVar> = this.get().addressOfElement(index)
fun IntArray.refTo(index: Int): CValuesRef<IntVar> = this.usingPinned { addressOf(index) }
fun Pinned<LongArray>.addressOf(index: Int): CPointer<LongVar> = this.get().addressOfElement(index)
fun LongArray.refTo(index: Int): CValuesRef<LongVar> = this.usingPinned { addressOf(index) }
// TODO: pinning of unsigned arrays involves boxing as they are inline classes wrapping signed arrays.
fun Pinned<UByteArray>.addressOf(index: Int): CPointer<UByteVar> = this.get().addressOfElement(index)
fun UByteArray.refTo(index: Int): CValuesRef<UByteVar> = this.usingPinned { addressOf(index) }
fun Pinned<UShortArray>.addressOf(index: Int): CPointer<UShortVar> = this.get().addressOfElement(index)
fun UShortArray.refTo(index: Int): CValuesRef<UShortVar> = this.usingPinned { addressOf(index) }
fun Pinned<UIntArray>.addressOf(index: Int): CPointer<UIntVar> = this.get().addressOfElement(index)
fun UIntArray.refTo(index: Int): CValuesRef<UIntVar> = this.usingPinned { addressOf(index) }
fun Pinned<ULongArray>.addressOf(index: Int): CPointer<ULongVar> = this.get().addressOfElement(index)
fun ULongArray.refTo(index: Int): CValuesRef<ULongVar> = this.usingPinned { addressOf(index) }
fun Pinned<FloatArray>.addressOf(index: Int): CPointer<FloatVar> = this.get().addressOfElement(index)
fun FloatArray.refTo(index: Int): CValuesRef<FloatVar> = this.usingPinned { addressOf(index) }
fun Pinned<DoubleArray>.addressOf(index: Int): CPointer<DoubleVar> = this.get().addressOfElement(index)
fun DoubleArray.refTo(index: Int): CValuesRef<DoubleVar> = this.usingPinned { addressOf(index) }
private inline fun <T : Any, P : CPointed> T.usingPinned(
crossinline block: Pinned<T>.() -> CPointer<P>
) = object : CValuesRef<P>() {
override fun getPointer(scope: AutofreeScope): CPointer<P> {
val pinned = [email protected]()
scope.defer { pinned.unpin() }
return pinned.block()
}
}
@SymbolName("Kotlin_Arrays_getByteArrayAddressOfElement")
private external fun ByteArray.addressOfElement(index: Int): CPointer<ByteVar>
@SymbolName("Kotlin_Arrays_getStringAddressOfElement")
private external fun String.addressOfElement(index: Int): CPointer<COpaque>
@SymbolName("Kotlin_Arrays_getCharArrayAddressOfElement")
private external fun CharArray.addressOfElement(index: Int): CPointer<COpaque>
@SymbolName("Kotlin_Arrays_getShortArrayAddressOfElement")
private external fun ShortArray.addressOfElement(index: Int): CPointer<ShortVar>
@SymbolName("Kotlin_Arrays_getIntArrayAddressOfElement")
private external fun IntArray.addressOfElement(index: Int): CPointer<IntVar>
@SymbolName("Kotlin_Arrays_getLongArrayAddressOfElement")
private external fun LongArray.addressOfElement(index: Int): CPointer<LongVar>
@SymbolName("Kotlin_Arrays_getByteArrayAddressOfElement")
private external fun UByteArray.addressOfElement(index: Int): CPointer<UByteVar>
@SymbolName("Kotlin_Arrays_getShortArrayAddressOfElement")
private external fun UShortArray.addressOfElement(index: Int): CPointer<UShortVar>
@SymbolName("Kotlin_Arrays_getIntArrayAddressOfElement")
private external fun UIntArray.addressOfElement(index: Int): CPointer<UIntVar>
@SymbolName("Kotlin_Arrays_getLongArrayAddressOfElement")
private external fun ULongArray.addressOfElement(index: Int): CPointer<ULongVar>
@SymbolName("Kotlin_Arrays_getFloatArrayAddressOfElement")
private external fun FloatArray.addressOfElement(index: Int): CPointer<FloatVar>
@SymbolName("Kotlin_Arrays_getDoubleArrayAddressOfElement")
private external fun DoubleArray.addressOfElement(index: Int): CPointer<DoubleVar>
| Interop/Runtime/src/native/kotlin/kotlinx/cinterop/Pinning.kt | 1768547843 |
package com.github.kerubistan.kerub.model.expectations
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonTypeName
import com.github.kerubistan.kerub.model.ExpectationLevel
@JsonTypeName("cpu-clock-freq")
data class ClockFrequencyExpectation @JsonCreator constructor(
override val level: ExpectationLevel,
val minimalClockFrequency: Int
) : VirtualMachineExpectation | src/main/kotlin/com/github/kerubistan/kerub/model/expectations/ClockFrequencyExpectation.kt | 2358907468 |
/*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* 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 org.ethereum.net.dht
import org.ethereum.crypto.HashUtil
import org.spongycastle.util.BigIntegers
import org.spongycastle.util.encoders.Hex
import java.math.BigInteger
internal class Peer {
private var id: ByteArray? = null
private var host = "127.0.0.1"
private var port = 0
constructor(id: ByteArray, host: String, port: Int) {
this.id = id
this.host = host
this.port = port
}
constructor(ip: ByteArray) {
this.id = ip
}
constructor() {
HashUtil.randomPeerId()
}
fun nextBit(startPattern: String): Byte {
if (this.toBinaryString().startsWith(startPattern + "1"))
return 1
else
return 0
}
fun calcDistance(toPeer: Peer): ByteArray {
val aPeer = BigInteger(getId())
val bPeer = BigInteger(toPeer.getId())
val distance = aPeer.xor(bPeer)
return BigIntegers.asUnsignedByteArray(distance)
}
private fun getId(): ByteArray {
return id!!
}
fun setId(ip: ByteArray) {
this.id = id
}
override fun toString(): String {
return String.format("Peer {\n id=%s, \n host=%s, \n port=%d\n}", Hex.toHexString(id!!), host, port)
}
fun toBinaryString(): String {
val bi = BigInteger(1, id!!)
var out = String.format("%512s", bi.toString(2))
out = out.replace(' ', '0')
return out
}
}
| free-ethereum-core/src/main/java/org/ethereum/net/dht/Peer.kt | 750846673 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.fir.testGenerator
import org.jetbrains.kotlin.idea.k2.navigation.AbstractKotlinNavigationToLibrarySourceTest
import org.jetbrains.kotlin.testGenerator.model.MutableTWorkspace
import org.jetbrains.kotlin.testGenerator.model.model
import org.jetbrains.kotlin.testGenerator.model.testClass
import org.jetbrains.kotlin.testGenerator.model.testGroup
internal fun MutableTWorkspace.generateK2NavigationTests() {
testGroup("navigation/tests", testDataPath = "testData") {
testClass<AbstractKotlinNavigationToLibrarySourceTest> {
model("navigationToLibrarySourcePolicy")
}
}
} | plugins/kotlin/util/test-generator-fir/test/org/jetbrains/kotlin/fir/testGenerator/GenerateK2NavigationTests.kt | 1694018421 |
package io.github.sdsstudios.ScoreKeeper.Fragment
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v4.app.FragmentManager
import android.support.v7.app.AlertDialog
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.View
import io.github.sdsstudios.ScoreKeeper.R
import io.github.sdsstudios.ScoreKeeper.ViewModels.GameWithRoundsViewModel
/**
* Created by sethsch1 on 04/11/17.
*/
class ChangeScoreFragment : EditTextFragment() {
companion object {
private const val KEY_SCORE_INDEX = "score_index"
private const val KEY_PLAYER_ID = "player_id"
fun showDialog(fragmentManager: FragmentManager,
playerId: Long,
scoreIndex: Int) {
ChangeScoreFragment().apply {
arguments = Bundle().apply {
putLong(KEY_PLAYER_ID, playerId)
putInt(KEY_SCORE_INDEX, scoreIndex)
}
}.show(fragmentManager, TAG)
}
}
private val mPlayerId by lazy { arguments!!.getLong(KEY_PLAYER_ID) }
private val mScoreIndex by lazy { arguments!!.getInt(KEY_SCORE_INDEX) }
private val mPlayerScores by lazy {
mGameViewModel.game.rounds.single { it.playerId == mPlayerId }
}
private lateinit var mGameViewModel: GameWithRoundsViewModel
override val title by lazy { getString(R.string.title_change_score) }
override val inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_SIGNED
override fun onCreateDialog(savedInstanceState: Bundle?): AlertDialog {
mGameViewModel = ViewModelProviders.of(activity!!).get(GameWithRoundsViewModel::class.java)
return super.onCreateDialog(savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
editText.apply {
addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
if (s.isNullOrEmpty()) {
error = getString(R.string.error_can_not_be_empty)
return
} else {
try {
text.toString().toLong()
} catch (e: NumberFormatException) {
editText.error = getString(R.string.error_number_too_big)
return
}
}
if (error != null) error = null
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
})
setText(mPlayerScores.scores[mScoreIndex].toString())
}
}
override fun onPosClick() {
if (editText.error == null) {
mPlayerScores.score = editText.text.toString().toLong()
mGameViewModel.updateScoresInDb(mPlayerScores)
super.onPosClick()
}
}
} | app/src/main/java/io/github/sdsstudios/ScoreKeeper/Fragment/ChangeScoreFragment.kt | 4134147482 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.python.newProject.welcome
import com.intellij.execution.RunManager
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.RunConfigurationProducer
import com.intellij.ide.IdeBundle
import com.intellij.ide.impl.ProjectViewSelectInTarget
import com.intellij.ide.projectView.impl.ProjectViewPane
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileChooser.FileElement
import com.intellij.openapi.keymap.KeymapUtil.getShortcutText
import com.intellij.openapi.keymap.MacKeymapUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.DumbAwareRunnable
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectCoreUtil
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.ui.CheckBoxWithDescription
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.platform.DirectoryProjectConfigurator
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.ui.components.JBCheckBox
import com.intellij.xdebugger.XDebuggerUtil
import com.jetbrains.python.PythonPluginDisposable
import com.jetbrains.python.newProject.welcome.PyWelcomeCollector.Companion.ProjectType
import com.jetbrains.python.newProject.welcome.PyWelcomeCollector.Companion.ProjectViewPoint
import com.jetbrains.python.newProject.welcome.PyWelcomeCollector.Companion.ProjectViewResult
import com.jetbrains.python.newProject.welcome.PyWelcomeCollector.Companion.RunConfigurationResult
import com.jetbrains.python.newProject.welcome.PyWelcomeCollector.Companion.ScriptResult
import com.jetbrains.python.newProject.welcome.PyWelcomeCollector.Companion.logWelcomeRunConfiguration
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.run.PythonRunConfigurationProducer
import com.jetbrains.python.sdk.pythonSdk
import org.jetbrains.annotations.CalledInAny
import org.jetbrains.concurrency.CancellablePromise
import java.awt.event.ItemEvent
import java.util.concurrent.Callable
import javax.swing.JPanel
internal class PyWelcomeConfigurator : DirectoryProjectConfigurator {
override val isEdtRequired: Boolean
get() = false
override fun configureProject(project: Project, baseDir: VirtualFile, moduleRef: Ref<Module>, isProjectCreatedWithWizard: Boolean) {
if (isProjectCreatedWithWizard || isInsideTempDirectory(baseDir)) {
return
}
StartupManager.getInstance(project).runAfterOpened(
DumbAwareRunnable {
PyWelcomeCollector.logWelcomeProject(project, ProjectType.OPENED)
PyWelcome.welcomeUser(project, baseDir, moduleRef.get())
}
)
}
private fun isInsideTempDirectory(baseDir: VirtualFile): Boolean {
val tempDir = LocalFileSystem.getInstance().findFileByPath(FileUtil.getTempDirectory()) ?: return false
return VfsUtil.isAncestor(tempDir, baseDir, true)
}
}
internal object PyWelcomeGenerator {
fun createWelcomeSettingsPanel(): JPanel {
return CheckBoxWithDescription(
JBCheckBox(PyWelcomeBundle.message("py.welcome.new.project.text"),
PyWelcomeSettings.instance.createWelcomeScriptForEmptyProject).apply {
addItemListener { e -> PyWelcomeSettings.instance.createWelcomeScriptForEmptyProject = e.stateChange == ItemEvent.SELECTED }
},
PyWelcomeBundle.message("py.welcome.new.project.description")
)
}
fun welcomeUser(project: Project, baseDir: VirtualFile, module: Module) {
PyWelcomeCollector.logWelcomeProject(project, ProjectType.NEW)
PyWelcome.welcomeUser(project, baseDir, module)
}
}
private object PyWelcome {
private val LOG = Logger.getInstance(PyWelcome::class.java)
@CalledInAny
fun welcomeUser(project: Project, baseDir: VirtualFile, module: Module?) {
val enabled = PyWelcomeSettings.instance.createWelcomeScriptForEmptyProject
if (isEmptyProject(project, baseDir, module)) {
if (enabled) {
prepareFileAndOpen(project, baseDir).onSuccess {
if (it != null) {
// expand tree after the welcome script is created, otherwise expansion will have no effect on empty tree
expandProjectTree(project, baseDir, module, it.virtualFile)
createRunConfiguration(project, it)
}
}
}
else {
PyWelcomeCollector.logWelcomeScript(project, ScriptResult.DISABLED_BUT_COULD)
expandProjectTree(project, baseDir, module, null)
}
}
else {
PyWelcomeCollector.logWelcomeScript(project, if (enabled) ScriptResult.NOT_EMPTY else ScriptResult.DISABLED_AND_COULD_NOT)
expandProjectTree(project, baseDir, module, null)
}
}
private fun isEmptyProject(project: Project, baseDir: VirtualFile, module: Module?): Boolean {
return firstUserFile(project, baseDir, module) == null
}
private fun firstUserFile(project: Project, baseDir: VirtualFile, module: Module?): VirtualFile? {
if (module != null && module.isDisposed || module == null && project.isDisposed) return null
val sdkBinary = (module?.pythonSdk ?: project.pythonSdk)?.homeDirectory
val innerSdk = sdkBinary != null && VfsUtil.isAncestor(baseDir, sdkBinary, true)
return baseDir.children.filterNot {
ProjectCoreUtil.isProjectOrWorkspaceFile(it) ||
innerSdk && it.isDirectory && VfsUtil.isAncestor(it, sdkBinary!!, true) ||
FileElement.isFileHidden(it)
}.firstOrNull()
}
private fun prepareFileAndOpen(project: Project, baseDir: VirtualFile): CancellablePromise<PsiFile?> {
return AppUIExecutor
.onWriteThread()
.expireWith(PythonPluginDisposable.getInstance(project))
.submit(
Callable {
WriteAction.compute<PsiFile?, Exception> {
prepareFile(project, baseDir)?.also {
AppUIExecutor.onUiThread().expireWith(PythonPluginDisposable.getInstance(project)).execute { it.navigate(true) }
}
}
}
)
}
private fun createRunConfiguration(project: Project, file: PsiFile) {
RunConfigurationProducer
.getInstance(PythonRunConfigurationProducer::class.java)
.createConfigurationFromContext(ConfigurationContext(file))
.also {
logWelcomeRunConfiguration(project, if (it == null) RunConfigurationResult.NULL else RunConfigurationResult.CREATED)
}
?.let {
val settings = it.configurationSettings
val runManager = RunManager.getInstance(project)
runManager.addConfiguration(settings)
runManager.selectedConfiguration = settings
}
}
@CalledInAny
private fun expandProjectTree(project: Project, baseDir: VirtualFile, module: Module?, file: VirtualFile?) {
expandProjectTree(project, ToolWindowManager.getInstance(project), baseDir, module, file, ProjectViewPoint.IMMEDIATELY)
}
@CalledInAny
private fun expandProjectTree(project: Project,
toolWindowManager: ToolWindowManager,
baseDir: VirtualFile,
module: Module?,
file: VirtualFile?,
point: ProjectViewPoint) {
// the approach was taken from com.intellij.platform.PlatformProjectViewOpener
val toolWindow = toolWindowManager.getToolWindow(ToolWindowId.PROJECT_VIEW)
if (toolWindow == null) {
val listener = ProjectViewListener(project, baseDir, module, file)
Disposer.register(PythonPluginDisposable.getInstance(project), listener)
// collected listener will release the connection
project.messageBus.connect(listener).subscribe(ToolWindowManagerListener.TOPIC, listener)
}
else {
StartupManager.getInstance(project).runAfterOpened(
DumbAwareRunnable {
AppUIExecutor
.onUiThread(ModalityState.NON_MODAL)
.expireWith(PythonPluginDisposable.getInstance(project))
.submit {
val fileToChoose = (file ?: firstUserFile(project, baseDir, module)) ?: return@submit
ProjectViewSelectInTarget
.select(project, fileToChoose, ProjectViewPane.ID, null, fileToChoose, false)
.doWhenDone { PyWelcomeCollector.logWelcomeProjectView(project, point, ProjectViewResult.EXPANDED) }
.doWhenRejected(Runnable { PyWelcomeCollector.logWelcomeProjectView(project, point, ProjectViewResult.REJECTED) })
}
}
)
}
}
private fun prepareFile(project: Project, baseDir: VirtualFile): PsiFile? {
val file = kotlin.runCatching { baseDir.createChildData(this, "main.py") }
.onFailure { PyWelcomeCollector.logWelcomeScript(project, ScriptResult.NO_VFILE) }
.getOrThrow()
val psiFile = PsiManager.getInstance(project).findFile(file)
if (psiFile == null) {
LOG.warn("Unable to get psi for $file")
PyWelcomeCollector.logWelcomeScript(project, ScriptResult.NO_PSI)
return null
}
writeText(project, psiFile)?.also { line ->
PyWelcomeCollector.logWelcomeScript(project, ScriptResult.CREATED)
XDebuggerUtil.getInstance().toggleLineBreakpoint(project, file, line)
}
return psiFile
}
private fun writeText(project: Project, psiFile: PsiFile): Int? {
val document = PsiDocumentManager.getInstance(project).getDocument(psiFile)
if (document == null) {
LOG.warn("Unable to get document for ${psiFile.virtualFile}")
PyWelcomeCollector.logWelcomeScript(project, ScriptResult.NO_DOCUMENT)
return null
}
val languageLevel = LanguageLevel.forElement(psiFile)
val greeting = if (languageLevel.isAtLeast(LanguageLevel.PYTHON36)) "f'Hi, {name}'" else "\"Hi, {0}\".format(name)"
val breakpointLine = if (languageLevel.isPython2) 9 else 8
val toggleBreakpointTip = PyWelcomeBundle.message("py.welcome.script.toggle.breakpoint",
getShortcutText(IdeActions.ACTION_TOGGLE_LINE_BREAKPOINT))
// search everywhere is not initialized until its first usage happens
val searchEverywhereShortcut = IdeBundle.message("double.ctrl.or.shift.shortcut",
if (SystemInfo.isMac) MacKeymapUtil.SHIFT else "Shift")
document.setText(
(if (languageLevel.isPython2) "# coding=utf-8\n" else "") +
"""
# ${PyWelcomeBundle.message("py.welcome.script.header")}
# ${PyWelcomeBundle.message("py.welcome.script.run.or.type", getShortcutText(IdeActions.ACTION_DEFAULT_RUNNER))}
# ${PyWelcomeBundle.message("py.welcome.script.search.everywhere", searchEverywhereShortcut)}
def print_hi(name):
# ${PyWelcomeBundle.message("py.welcome.script.use.breakpoint")}
print($greeting) # $toggleBreakpointTip
# ${PyWelcomeBundle.message("py.welcome.script.run")}
if __name__ == '__main__':
print_hi('PyCharm')
# ${PyWelcomeBundle.message("py.welcome.script.help")}
""".trimIndent()
)
PsiDocumentManager.getInstance(project).commitDocument(document)
return breakpointLine
}
private class ProjectViewListener(private val project: Project,
private val baseDir: VirtualFile,
private val module: Module?,
private val file: VirtualFile?) : ToolWindowManagerListener, Disposable {
private var toolWindowRegistered = false
override fun toolWindowsRegistered(ids: List<String>, toolWindowManager: ToolWindowManager) {
if (ToolWindowId.PROJECT_VIEW in ids) {
toolWindowRegistered = true
Disposer.dispose(this) // to release message bus connection
expandProjectTree(project, toolWindowManager, baseDir, module, file, ProjectViewPoint.FROM_LISTENER)
}
}
override fun dispose() {
if (!toolWindowRegistered) {
PyWelcomeCollector.logWelcomeProjectView(project, ProjectViewPoint.FROM_LISTENER, ProjectViewResult.NO_TOOLWINDOW)
}
}
}
} | python/ide/impl/src/com/jetbrains/python/newProject/welcome/PyWelcome.kt | 1817040970 |
// IS_APPLICABLE: false
fun main(args: Array<String>){
val x = "<caret>\$d"
}
| plugins/kotlin/idea/tests/testData/intentions/convertToConcatenatedString/notAvailableForDollarSignLiteral.kt | 1803389144 |
package k
annotation class Anno1(val d: Int, val c: Int = 2)
annotation class Anno2(val c: IntArray, val g: String) | plugins/kotlin/idea/tests/testData/kotlinAndJavaChecker/javaAgainstKotlin/KotlinAnnotations.kt | 3294778020 |
// OPTION: 1
fun foo(n: Int): Int {
<caret>if (n > 0) {
println("> 0")
n + 10
} else {
println("<= 0")
n - 10
}
return n
}
| plugins/kotlin/idea/tests/testData/codeInsight/unwrapAndRemove/unwrapThen/thenCompoundInBlock.kt | 1074510370 |
// 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.openapi.project.ex.ProjectEx
import com.intellij.testFramework.EdtRule
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.RuleChain
import com.intellij.testFramework.RunsInEdt
import com.intellij.testFramework.rules.InMemoryFsRule
import org.junit.Rule
import org.junit.Test
import org.junit.rules.Verifier
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
@RunsInEdt
class PerProjectPluginsTest {
private val projectRule = ProjectRule()
private val project: ProjectEx
get() = projectRule.project
private val verifierRule = object : Verifier() {
override fun verify() {
val pluginTracker = DynamicPluginEnabler.findPluginTracker(project)
assertNotNull(pluginTracker)
assertTrue(pluginTracker.disabledPluginsIds.isEmpty())
assertTrue(pluginTracker.enabledPluginsIds.isEmpty())
}
}
private val inMemoryFsRule = InMemoryFsRule()
@Rule
@JvmField
val chain = RuleChain(
projectRule,
verifierRule,
inMemoryFsRule,
EdtRule(),
)
@Test
fun enabledAndDisablePerProject() {
val path = inMemoryFsRule.fs.getPath("/plugin")
PluginBuilder()
.randomId("enabledAndDisablePerProject")
.build(path)
val descriptor = loadDescriptorInTest(path)
assertNotNull(descriptor)
val pluginId = descriptor.pluginId
val pluginEnabler = PluginEnabler.getInstance() as? DynamicPluginEnabler
assertNotNull(pluginEnabler)
val loaded = pluginEnabler.updatePluginsState(
listOf(descriptor),
PluginEnableDisableAction.ENABLE_FOR_PROJECT,
project,
)
assertTrue(loaded)
assertRestartIsNotRequired()
assertFalse(PluginManagerCore.isDisabled(pluginId))
assertTrue(PluginManagerCore.getLoadedPlugins().contains(descriptor))
val unloaded = pluginEnabler.updatePluginsState(
listOf(descriptor),
PluginEnableDisableAction.DISABLE_FOR_PROJECT,
project,
)
assertTrue(unloaded)
assertRestartIsNotRequired()
assertFalse(PluginManagerCore.isDisabled(pluginId))
assertFalse(PluginManagerCore.getLoadedPlugins().contains(descriptor))
pluginEnabler.getPluginTracker(project)
.stopTracking(listOf(pluginId))
}
private fun assertRestartIsNotRequired() {
assertFalse(InstalledPluginsState.getInstance().isRestartRequired)
}
} | platform/platform-tests/testSrc/com/intellij/ide/plugins/PerProjectPluginsTest.kt | 1458735468 |
package zielu.gittoolbox.extension.blame
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import zielu.gittoolbox.util.AppUtil
import java.util.stream.Stream
internal class InlineBlameAllowedExtension(private val project: Project) {
fun isBlameAllowed(): Boolean {
return extensions().allMatch { ext -> ext.isAllowed(project) }
}
private fun extensions(): Stream<InlineBlameAllowed> {
return EXTENSION_POINT_NAME.extensionList
.stream()
.map { ext -> ext.instantiate() }
}
companion object {
fun isBlameAllowed(project: Project): Boolean {
return AppUtil.getServiceInstance(project, InlineBlameAllowedExtension::class.java).isBlameAllowed()
}
}
}
private val EXTENSION_POINT_NAME: ExtensionPointName<InlineBlameAllowedEP> = ExtensionPointName.create(
"zielu.gittoolbox.inlineBlameAllowed"
)
| src/main/kotlin/zielu/gittoolbox/extension/blame/InlineBlameAllowedExtension.kt | 2702966395 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.migration
import com.intellij.codeInspection.CleanupLocalInspectionTool
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.diagnostics.DiagnosticFactoryWithPsiElement
import org.jetbrains.kotlin.idea.configuration.MigrationInfo
import org.jetbrains.kotlin.idea.configuration.isLanguageVersionUpdate
import org.jetbrains.kotlin.idea.quickfix.migration.MigrationFix
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
class ProhibitJvmOverloadsOnConstructorsOfAnnotationClassesMigrationInspection :
AbstractDiagnosticBasedMigrationInspection<KtAnnotationEntry>(KtAnnotationEntry::class.java),
MigrationFix,
CleanupLocalInspectionTool {
override fun isApplicable(migrationInfo: MigrationInfo): Boolean {
return migrationInfo.isLanguageVersionUpdate(LanguageVersion.KOTLIN_1_3, LanguageVersion.KOTLIN_1_4)
}
override val diagnosticFactory: DiagnosticFactoryWithPsiElement<KtAnnotationEntry, *>
get() = ErrorsJvm.OVERLOADS_ANNOTATION_CLASS_CONSTRUCTOR
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/migration/ProhibitJvmOverloadsOnConstructorsOfAnnotationClassesMigrationInspection.kt | 3134561240 |
// WITH_DEFAULT_VALUE: false
fun foo(a: Int): Int {
fun Int.bar(n: Int) = this + n
return (<selection>a bar 1</selection>) * 2
}
fun test() {
foo(2)
} | plugins/kotlin/idea/tests/testData/refactoring/introduceParameter/substituteInfixCall.kt | 3138462890 |
package org.extendedmind.android.ui.data.content
import org.extendedmind.android.ui.data.Result
interface ContentRepository {
// Hub settings
fun setHubParams(url: String, publicKey: String): Unit
fun getHubUrl(): String?
fun getHubPublicKey(): String?
// Content methods
suspend fun getVersion(): Result<Int>;
// UI Preferences
fun isConnectShown(): Boolean
}
| ui/android/app/src/main/java/org/extendedmind/android/ui/data/content/ContentRepository.kt | 927614806 |
package com.intellij.aws.cloudformation.tests
import com.intellij.aws.cloudformation.CloudFormationParser
import com.intellij.testFramework.LightPlatformCodeInsightTestCase
import org.apache.commons.lang.SystemUtils
import java.io.File
class YamlParserTest : LightPlatformCodeInsightTestCase() {
fun testFunShortForm() = runTest("funShortForm")
fun testQuotedTextValue() = runTest("quotedTextValue")
fun testCompactSequences() = runTest("compactSequences")
fun testMappings() = runTest("mappings")
fun testParameters() = runTest("parameters")
fun testNestedFunctions() = runTest("nestedFunctions")
fun testNestedFunctions2() = runTest("nestedFunctions2")
fun runTest(name: String) {
configureByFile("$name.yaml")
val parsed = CloudFormationParser.parse(myFile)
TestUtil.checkContent(
File(testDataPath, "$name.expected"),
TestUtil.renderProblems(myFile, parsed.problems) + SystemUtils.LINE_SEPARATOR + TestUtil.nodeToString(parsed.root)
)
}
override fun getTestDataPath(): String {
return TestUtil.getTestDataPath("parser/yaml")
}
}
| src/test/kotlin/com/intellij/aws/cloudformation/tests/YamlParserTest.kt | 2206174067 |
package me.sargunvohra.lib.cakeparse.api
import me.sargunvohra.lib.cakeparse.exception.UnexpectedTokenException
import me.sargunvohra.lib.cakeparse.lexer.TokenInstance
import me.sargunvohra.lib.cakeparse.parser.Parser
import me.sargunvohra.lib.cakeparse.parser.Result
import me.sargunvohra.lib.common.cached
/**
* Apply the provided parser on the input sequence until the parser is satisfied. Remaining input is allowed.
*
* @param parser the target rule to satisfy.
*
* @return the result of the parse.
*/
fun <A> Sequence<TokenInstance>.parseToGoal(parser: Parser<A>) = parser.eat(this.cached())
/**
* Apply the provided parser on the input sequence and make sure all input is consumed. Remaining input is not allowed.
*
* @param parser the target rule to satisfy.
*
* @return the result of the parse.
*
* @throws UnexpectedTokenException when the parser does not consume the entire input.
*/
fun <A> Sequence<TokenInstance>.parseToEnd(parser: Parser<A>): Result<A> {
val result = this.parseToGoal(parser)
result.remainder.filter { !it.type.ignore }.firstOrNull()?.let {
throw UnexpectedTokenException(null, it)
}
return result
} | src/main/kotlin/me/sargunvohra/lib/cakeparse/api/Parsing.kt | 2753133974 |
package bj.vinylbrowser.singlelist
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import bj.vinylbrowser.R
import bj.vinylbrowser.artist.ArtistController
import bj.vinylbrowser.common.BaseController
import bj.vinylbrowser.label.LabelController
import bj.vinylbrowser.main.MainActivity
import bj.vinylbrowser.main.MainComponent
import bj.vinylbrowser.marketplace.MarketplaceController
import bj.vinylbrowser.master.MasterController
import bj.vinylbrowser.model.collection.CollectionRelease
import bj.vinylbrowser.model.common.RecyclerViewModel
import bj.vinylbrowser.model.listing.Listing
import bj.vinylbrowser.model.order.Order
import bj.vinylbrowser.model.wantlist.Want
import bj.vinylbrowser.order.OrderController
import bj.vinylbrowser.release.ReleaseController
import bj.vinylbrowser.utils.ImageViewAnimator
import bj.vinylbrowser.utils.analytics.AnalyticsTracker
import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.changehandler.FadeChangeHandler
import com.jakewharton.rxbinding2.widget.RxTextView
import io.reactivex.Observable
import kotlinx.android.synthetic.main.controller_single_list.view.*
import javax.inject.Inject
/**
* Created by Josh Laird on 30/05/2017.
*/
class SingleListController(val type: Int, val username: String)
: BaseController(), SingleListContract.View {
@Inject lateinit var presenter: SingleListPresenter
@Inject lateinit var imageViewAnimator: ImageViewAnimator
@Inject lateinit var tracker: AnalyticsTracker
@Inject lateinit var epxController: SingleListEpxController
lateinit var etFilter: EditText
constructor(args: Bundle) : this(args.getInt("type"), args.getString("username"))
override fun setupComponent(mainComponent: MainComponent) {
mainComponent
.singleListComponentBuilder()
.singleModule(SingleListModule(this))
.build()
.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View {
setupComponent((activity as MainActivity).mainComponent)
val view = inflater.inflate(R.layout.controller_single_list, container, false)
setupToolbar(view.toolbar, "")
setupRecyclerView(view.recyclerView, epxController)
etFilter = view.etFilter
presenter.setupFilterSubscription()
epxController.requestModelBuild()
presenter.getData(type, username)
return view
}
override fun onAttach(view: View) {
super.onAttach(view)
if (view.recyclerView.adapter == null)
setupRecyclerView(view.recyclerView, epxController)
}
override fun launchDetailedActivity(type: String, title: String, id: String) {
tracker.send(applicationContext!!.getString(R.string.single_list_activity), type, applicationContext!!.getString(R.string.clicked), "detailedActivity" + type, "1")
when (type) {
"release" -> router.pushController(RouterTransaction.with(ReleaseController(title, id))
.popChangeHandler(FadeChangeHandler())
.pushChangeHandler(FadeChangeHandler())
.tag("ReleaseController"))
"label" -> router.pushController(RouterTransaction.with(LabelController(title, id))
.popChangeHandler(FadeChangeHandler())
.pushChangeHandler(FadeChangeHandler())
.tag("LabelController"))
"artist" -> router.pushController(RouterTransaction.with(ArtistController(title, id))
.popChangeHandler(FadeChangeHandler())
.pushChangeHandler(FadeChangeHandler())
.tag("ArtistController"))
"master" -> router.pushController(RouterTransaction.with(MasterController(title, id))
.popChangeHandler(FadeChangeHandler())
.pushChangeHandler(FadeChangeHandler())
.tag("MasterController"))
"listing" -> router.pushController(RouterTransaction.with(MarketplaceController(title, id, "", ""))
.popChangeHandler(FadeChangeHandler())
.pushChangeHandler(FadeChangeHandler())
.tag("MarketplaceController"))
"order" -> router.pushController(RouterTransaction.with(OrderController(id))
.popChangeHandler(FadeChangeHandler())
.pushChangeHandler(FadeChangeHandler())
.tag("OrderController"))
}
}
/**
* Exposes an Observable that watches the EditText's changes.
*
* @return Observable.
*/
override fun filterIntent(): Observable<CharSequence> {
return RxTextView.textChanges(etFilter)
}
override fun onRestoreViewState(view: View, savedViewState: Bundle) {
epxController.setItems(savedViewState.get("items") as MutableList<out RecyclerViewModel>)
super.onRestoreViewState(view, savedViewState)
}
override fun onSaveViewState(view: View, outState: Bundle) {
when (type) {
R.string.selling ->
outState.putParcelableArrayList("items", (epxController.items as ArrayList<Listing>))
R.string.orders ->
outState.putParcelableArrayList("items", (epxController.items as ArrayList<Order>))
R.string.drawer_item_collection ->
outState.putParcelableArrayList("items", (epxController.items as ArrayList<CollectionRelease>))
R.string.drawer_item_wantlist ->
outState.putParcelableArrayList("items", (epxController.items as ArrayList<Want>))
}
super.onSaveViewState(view, outState)
}
} | app/src/main/java/bj/vinylbrowser/singlelist/SingleListController.kt | 3885744365 |
package ch.rmy.android.framework.extensions
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import ch.rmy.android.framework.viewmodel.BaseViewModel
import ch.rmy.android.framework.viewmodel.ViewModelEvent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
fun <ViewState : Any> LifecycleOwner.collectViewStateWhileActive(viewModel: BaseViewModel<*, ViewState>, onViewStateUpdate: (ViewState) -> Unit) {
whileLifecycleActive {
viewModel.viewState.collectLatest(onViewStateUpdate)
}
}
fun LifecycleOwner.collectEventsWhileActive(viewModel: BaseViewModel<*, *>, onEvent: (ViewModelEvent) -> Unit) {
whileLifecycleActive {
viewModel.events.collect(onEvent)
}
}
fun LifecycleOwner.whileLifecycleActive(block: suspend CoroutineScope.() -> Unit) {
lifecycleScope.launch {
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED, block)
}
}
fun Continuation<Unit>.resume() {
resume(Unit)
}
| HTTPShortcuts/framework/src/main/kotlin/ch/rmy/android/framework/extensions/CoroutineExtensions.kt | 1417693943 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package mobi.hsz.idea.gitignore.codeInspection
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement
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.impl.source.tree.TreeUtil
import mobi.hsz.idea.gitignore.IgnoreBundle
import mobi.hsz.idea.gitignore.psi.IgnoreEntry
import mobi.hsz.idea.gitignore.psi.IgnoreTypes
/**
* QuickFix action that removes specified entry handled by code inspections like [IgnoreCoverEntryInspection],
* [IgnoreDuplicateEntryInspection], [IgnoreUnusedEntryInspection].
*/
class IgnoreRemoveEntryFix(entry: IgnoreEntry) : LocalQuickFixAndIntentionActionOnPsiElement(entry) {
override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) {
if (startElement is IgnoreEntry) {
removeCrlf(startElement)
startElement.delete()
}
}
private fun removeCrlf(startElement: PsiElement) {
(
TreeUtil.findSibling(startElement.node, IgnoreTypes.CRLF) ?: TreeUtil.findSiblingBackward(
startElement.node,
IgnoreTypes.CRLF
)
)?.psi?.delete()
}
override fun getText(): String = IgnoreBundle.message("quick.fix.remove.entry")
override fun getFamilyName(): String = IgnoreBundle.message("codeInspection.group")
}
| src/main/kotlin/mobi/hsz/idea/gitignore/codeInspection/IgnoreRemoveEntryFix.kt | 3663571344 |
/*
* Copyright 2019 New Vector Ltd
*
* 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 im.vector.notifications
import android.app.Notification
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.PowerManager
import android.text.TextUtils
import android.view.WindowManager
import android.widget.ImageView
import androidx.core.app.NotificationCompat
import androidx.core.app.Person
import im.vector.BuildConfig
import im.vector.Matrix
import im.vector.R
import im.vector.VectorApp
import im.vector.util.SecretStoringUtils
import org.matrix.androidsdk.MXSession
import org.matrix.androidsdk.core.Log
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
/**
* The NotificationDrawerManager receives notification events as they arrived (from event stream or fcm) and
* organise them in order to display them in the notification drawer.
* Events can be grouped into the same notification, old (already read) events can be removed to do some cleaning.
*/
class NotificationDrawerManager(val context: Context) {
//The first time the notification drawer is refreshed, we force re-render of all notifications
private var firstTime = true
private var eventList = loadEventInfo()
private var myUserDisplayName: String = ""
private var myUserAvatarUrl: String = ""
private val avatarSize = context.resources.getDimensionPixelSize(R.dimen.profile_avatar_size)
private var currentRoomId: String? = null
private var iconLoader = IconLoader(context,
object : IconLoader.IconLoaderListener {
override fun onIconsLoaded() {
// Force refresh
refreshNotificationDrawer(null)
}
})
/**
* No multi session support for now
*/
private fun initWithSession(session: MXSession?) {
session?.let {
myUserDisplayName = it.myUser?.displayname ?: it.myUserId
// User Avatar
it.myUser?.avatarUrl?.let { avatarUrl ->
val userAvatarUrlPath = it.mediaCache?.thumbnailCacheFile(avatarUrl, avatarSize)
if (userAvatarUrlPath != null) {
myUserAvatarUrl = userAvatarUrlPath.path
} else {
// prepare for the next time
session.mediaCache?.loadAvatarThumbnail(session.homeServerConfig, ImageView(context), avatarUrl, avatarSize)
}
}
}
}
/**
Should be called as soon as a new event is ready to be displayed.
The notification corresponding to this event will not be displayed until
#refreshNotificationDrawer() is called.
Events might be grouped and there might not be one notification per event!
*/
fun onNotifiableEventReceived(notifiableEvent: NotifiableEvent) {
//If we support multi session, event list should be per userId
//Currently only manage single session
if (BuildConfig.LOW_PRIVACY_LOG_ENABLE) {
Log.d(LOG_TAG, "%%%%%%%% onNotifiableEventReceived $notifiableEvent")
}
synchronized(eventList) {
val existing = eventList.firstOrNull { it.eventId == notifiableEvent.eventId }
if (existing != null) {
if (existing.isPushGatewayEvent) {
//Use the event coming from the event stream as it may contains more info than
//the fcm one (like type/content/clear text)
// In this case the message has already been notified, and might have done some noise
// So we want the notification to be updated even if it has already been displayed
// But it should make no noise (e.g when an encrypted message from FCM should be
// update with clear text after a sync)
notifiableEvent.hasBeenDisplayed = false
notifiableEvent.noisy = false
eventList.remove(existing)
eventList.add(notifiableEvent)
} else {
//keep the existing one, do not replace
}
} else {
eventList.add(notifiableEvent)
}
}
}
/**
Clear all known events and refresh the notification drawer
*/
fun clearAllEvents() {
synchronized(eventList) {
eventList.clear()
}
refreshNotificationDrawer(null)
}
/** Clear all known message events for this room and refresh the notification drawer */
fun clearMessageEventOfRoom(roomId: String?) {
Log.d(LOG_TAG, "clearMessageEventOfRoom $roomId")
if (roomId != null) {
eventList.removeAll { e ->
if (e is NotifiableMessageEvent) {
return@removeAll e.roomId == roomId
}
return@removeAll false
}
NotificationUtils.cancelNotificationMessage(context, roomId, ROOM_MESSAGES_NOTIFICATION_ID)
}
refreshNotificationDrawer(null)
}
/**
Should be called when the application is currently opened and showing timeline for the given roomId.
Used to ignore events related to that room (no need to display notification) and clean any existing notification on this room.
*/
fun setCurrentRoom(roomId: String?) {
var hasChanged: Boolean
synchronized(eventList) {
hasChanged = roomId != currentRoomId
currentRoomId = roomId
}
if (hasChanged) {
clearMessageEventOfRoom(roomId)
}
}
fun homeActivityDidResume(matrixID: String?) {
synchronized(eventList) {
eventList.removeAll { e ->
return@removeAll e !is NotifiableMessageEvent //messages are cleared when entering room
}
}
}
fun clearMemberShipNotificationForRoom(roomId: String) {
synchronized(eventList) {
eventList.removeAll { e ->
if (e is InviteNotifiableEvent) {
return@removeAll e.roomId == roomId
}
return@removeAll false
}
}
}
fun refreshNotificationDrawer(outdatedDetector: OutdatedEventDetector?) {
try {
_refreshNotificationDrawer(outdatedDetector)
} catch (e: Exception) {
//defensive coding
Log.e(LOG_TAG, "## Failed to refresh drawer", e)
}
}
private fun _refreshNotificationDrawer(outdatedDetector: OutdatedEventDetector?) {
if (myUserDisplayName.isBlank()) {
initWithSession(Matrix.getInstance(context).defaultSession)
}
if (myUserDisplayName.isBlank()) {
// Should not happen, but myUserDisplayName cannot be blank if used to create a Person
return
}
synchronized(eventList) {
Log.d(LOG_TAG, "%%%%%%%% REFRESH NOTIFICATION DRAWER ")
//TMP code
var hasNewEvent = false
var summaryIsNoisy = false
val summaryInboxStyle = NotificationCompat.InboxStyle()
//group events by room to create a single MessagingStyle notif
val roomIdToEventMap: MutableMap<String, ArrayList<NotifiableMessageEvent>> = HashMap()
val simpleEvents: ArrayList<NotifiableEvent> = ArrayList()
val notifications: ArrayList<Notification> = ArrayList()
val eventIterator = eventList.listIterator()
while (eventIterator.hasNext()) {
val event = eventIterator.next()
if (event is NotifiableMessageEvent) {
val roomId = event.roomId
var roomEvents = roomIdToEventMap[roomId]
if (roomEvents == null) {
roomEvents = ArrayList()
roomIdToEventMap[roomId] = roomEvents
}
if (shouldIgnoreMessageEventInRoom(roomId) || outdatedDetector?.isMessageOutdated(event) == true) {
//forget this event
eventIterator.remove()
} else {
roomEvents.add(event)
}
} else {
simpleEvents.add(event)
}
}
Log.d(LOG_TAG, "%%%%%%%% REFRESH NOTIFICATION DRAWER ${roomIdToEventMap.size} room groups")
var globalLastMessageTimestamp = 0L
//events have been grouped
for ((roomId, events) in roomIdToEventMap) {
if (events.isEmpty()) {
//Just clear this notification
Log.d(LOG_TAG, "%%%%%%%% REFRESH NOTIFICATION DRAWER $roomId has no more events")
NotificationUtils.cancelNotificationMessage(context, roomId, ROOM_MESSAGES_NOTIFICATION_ID)
continue
}
val roomGroup = RoomEventGroupInfo(roomId)
roomGroup.hasNewEvent = false
roomGroup.shouldBing = false
roomGroup.isDirect = events[0].roomIsDirect
val roomName = events[0].roomName ?: events[0].senderName ?: ""
val style = NotificationCompat.MessagingStyle(Person.Builder()
.setName(myUserDisplayName)
.setIcon(iconLoader.getUserIcon(myUserAvatarUrl))
.setKey(events[0].matrixID)
.build())
roomGroup.roomDisplayName = roomName
style.isGroupConversation = !roomGroup.isDirect
if (!roomGroup.isDirect) {
style.conversationTitle = roomName
}
val largeBitmap = getRoomBitmap(events)
for (event in events) {
//if all events in this room have already been displayed there is no need to update it
if (!event.hasBeenDisplayed) {
roomGroup.shouldBing = roomGroup.shouldBing || event.noisy
roomGroup.customSound = event.soundName
}
roomGroup.hasNewEvent = roomGroup.hasNewEvent || !event.hasBeenDisplayed
val senderPerson = Person.Builder()
.setName(event.senderName)
.setIcon(iconLoader.getUserIcon(event.senderAvatarPath))
.setKey(event.senderId)
.build()
if (event.outGoingMessage && event.outGoingMessageFailed) {
style.addMessage(context.getString(R.string.notification_inline_reply_failed), event.timestamp, senderPerson)
roomGroup.hasSmartReplyError = true
} else {
style.addMessage(event.body, event.timestamp, senderPerson)
}
event.hasBeenDisplayed = true //we can consider it as displayed
//It is possible that this event was previously shown as an 'anonymous' simple notif.
//And now it will be merged in a single MessageStyle notif, so we can clean to be sure
NotificationUtils.cancelNotificationMessage(context, event.eventId, ROOM_EVENT_NOTIFICATION_ID)
}
try {
val summaryLine = context.resources.getQuantityString(
R.plurals.notification_compat_summary_line_for_room, events.size, roomName, events.size)
summaryInboxStyle.addLine(summaryLine)
} catch (e: Throwable) {
//String not found or bad format
Log.d(LOG_TAG, "%%%%%%%% REFRESH NOTIFICATION DRAWER failed to resolve string")
summaryInboxStyle.addLine(roomName)
}
if (firstTime || roomGroup.hasNewEvent) {
//Should update displayed notification
Log.d(LOG_TAG, "%%%%%%%% REFRESH NOTIFICATION DRAWER $roomId need refresh")
val lastMessageTimestamp = events.last().timestamp
if (globalLastMessageTimestamp < lastMessageTimestamp) {
globalLastMessageTimestamp = lastMessageTimestamp
}
NotificationUtils.buildMessagesListNotification(context, style, roomGroup, largeBitmap, lastMessageTimestamp, myUserDisplayName)
?.let {
//is there an id for this room?
notifications.add(it)
NotificationUtils.showNotificationMessage(context, roomId, ROOM_MESSAGES_NOTIFICATION_ID, it)
}
hasNewEvent = true
summaryIsNoisy = summaryIsNoisy || roomGroup.shouldBing
} else {
Log.d(LOG_TAG, "%%%%%%%% REFRESH NOTIFICATION DRAWER $roomId is up to date")
}
}
//Handle simple events
for (event in simpleEvents) {
//We build a simple event
if (firstTime || !event.hasBeenDisplayed) {
NotificationUtils.buildSimpleEventNotification(context, event, null, myUserDisplayName)?.let {
notifications.add(it)
NotificationUtils.showNotificationMessage(context, event.eventId, ROOM_EVENT_NOTIFICATION_ID, it)
event.hasBeenDisplayed = true //we can consider it as displayed
hasNewEvent = true
summaryIsNoisy = summaryIsNoisy || event.noisy
summaryInboxStyle.addLine(event.description)
}
}
}
//======== Build summary notification =========
//On Android 7.0 (API level 24) and higher, the system automatically builds a summary for
// your group using snippets of text from each notification. The user can expand this
// notification to see each separate notification.
// To support older versions, which cannot show a nested group of notifications,
// you must create an extra notification that acts as the summary.
// This appears as the only notification and the system hides all the others.
// So this summary should include a snippet from all the other notifications,
// which the user can tap to open your app.
// The behavior of the group summary may vary on some device types such as wearables.
// To ensure the best experience on all devices and versions, always include a group summary when you create a group
// https://developer.android.com/training/notify-user/group
if (eventList.isEmpty()) {
NotificationUtils.cancelNotificationMessage(context, null, SUMMARY_NOTIFICATION_ID)
} else {
val nbEvents = roomIdToEventMap.size + simpleEvents.size
val sumTitle = context.resources.getQuantityString(
R.plurals.notification_compat_summary_title, nbEvents, nbEvents)
summaryInboxStyle.setBigContentTitle(sumTitle)
NotificationUtils.buildSummaryListNotification(
context,
summaryInboxStyle,
sumTitle,
noisy = hasNewEvent && summaryIsNoisy,
lastMessageTimestamp = globalLastMessageTimestamp
)?.let {
NotificationUtils.showNotificationMessage(context, null, SUMMARY_NOTIFICATION_ID, it)
}
if (hasNewEvent && summaryIsNoisy) {
try {
// turn the screen on for 3 seconds
if (Matrix.getInstance(VectorApp.getInstance())!!.pushManager.isScreenTurnedOn) {
val pm = VectorApp.getInstance().getSystemService(Context.POWER_SERVICE) as PowerManager
val wl = pm.newWakeLock(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or PowerManager.ACQUIRE_CAUSES_WAKEUP,
NotificationDrawerManager::class.java.name)
wl.acquire(3000)
wl.release()
}
} catch (e: Throwable) {
Log.e(LOG_TAG, "## Failed to turn screen on", e)
}
}
}
//notice that we can get bit out of sync with actual display but not a big issue
firstTime = false
}
}
private fun getRoomBitmap(events: ArrayList<NotifiableMessageEvent>): Bitmap? {
if (events.isEmpty()) return null
//Use the last event (most recent?)
val roomAvatarPath = events[events.size - 1].roomAvatarPath
?: events[events.size - 1].senderAvatarPath
if (!TextUtils.isEmpty(roomAvatarPath)) {
val options = BitmapFactory.Options()
options.inPreferredConfig = Bitmap.Config.ARGB_8888
try {
return BitmapFactory.decodeFile(roomAvatarPath, options)
} catch (oom: OutOfMemoryError) {
Log.e(LOG_TAG, "## decodeFile failed with an oom", oom)
} catch (e: Exception) {
Log.e(LOG_TAG, "## decodeFile failed", e)
}
}
return null
}
private fun shouldIgnoreMessageEventInRoom(roomId: String?): Boolean {
return currentRoomId != null && roomId == currentRoomId
}
fun persistInfo() {
if (eventList.isEmpty()) {
deleteCachedRoomNotifications(context)
return
}
try {
val file = File(context.applicationContext.cacheDir, ROOMS_NOTIFICATIONS_FILE_NAME)
if (!file.exists()) file.createNewFile()
FileOutputStream(file).use {
SecretStoringUtils.securelyStoreObject(eventList, "notificationMgr", it, this.context)
}
} catch (e: Throwable) {
Log.e(LOG_TAG, "## Failed to save cached notification info", e)
}
}
private fun loadEventInfo(): ArrayList<NotifiableEvent> {
try {
val file = File(context.applicationContext.cacheDir, ROOMS_NOTIFICATIONS_FILE_NAME)
if (file.exists()) {
FileInputStream(file).use {
val events: ArrayList<NotifiableEvent>? = SecretStoringUtils.loadSecureSecret(it, "notificationMgr", this.context)
if (events != null) {
return ArrayList(events.mapNotNull { it as? NotifiableEvent })
}
}
}
} catch (e: Throwable) {
Log.e(LOG_TAG, "## Failed to load cached notification info", e)
}
return ArrayList()
}
private fun deleteCachedRoomNotifications(context: Context) {
val file = File(context.applicationContext.cacheDir, ROOMS_NOTIFICATIONS_FILE_NAME)
if (file.exists()) {
file.delete()
}
}
companion object {
private const val SUMMARY_NOTIFICATION_ID = 0
private const val ROOM_MESSAGES_NOTIFICATION_ID = 1
private const val ROOM_EVENT_NOTIFICATION_ID = 2
private const val ROOMS_NOTIFICATIONS_FILE_NAME = "im.vector.notifications.cache"
private val LOG_TAG = NotificationDrawerManager::class.java.simpleName
}
}
| vector/src/main/java/im/vector/notifications/NotificationDrawerManager.kt | 3594282325 |
package com.mapzen.erasermap.view
import android.os.Bundle
import android.preference.PreferenceManager
import android.widget.Toast
import com.mapzen.erasermap.EraserMapApplication
import com.mapzen.erasermap.model.AppSettings
import com.mapzen.pelias.SavedSearch
import javax.inject.Inject
class SettingsActivity : HomeAsUpActivity() {
@Inject lateinit var savedSearch: SavedSearch
@Inject lateinit var settings: AppSettings
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(application as EraserMapApplication).component()?.inject(this)
val fragment = SettingsFragment.newInstance(settings)
fragmentManager.beginTransaction()
.replace(android.R.id.content, fragment)
.commit()
}
fun clearHistory(title: String) {
savedSearch.clear()
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putString(SavedSearch.TAG, savedSearch.serialize())
.commit()
Toast.makeText(this@SettingsActivity, title, Toast.LENGTH_SHORT).show()
}
}
| app/src/main/kotlin/com/mapzen/erasermap/view/SettingsActivity.kt | 3279435104 |
package io.sentry.spring
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import io.sentry.SentryOptions
import java.security.Principal
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
class HttpServletRequestSentryUserProviderTest {
@Test
fun `attaches user's IP address to Sentry Event`() {
val request = MockHttpServletRequest()
request.addHeader("X-FORWARDED-FOR", "192.168.0.1,192.168.0.2")
RequestContextHolder.setRequestAttributes(ServletRequestAttributes(request))
val options = SentryOptions()
options.isSendDefaultPii = true
val userProvider = HttpServletRequestSentryUserProvider(options)
val result = userProvider.provideUser()
assertNotNull(result)
assertEquals("192.168.0.1", result.ipAddress)
}
@Test
fun `attaches username to Sentry Event`() {
val principal = mock<Principal>()
whenever(principal.name).thenReturn("janesmith")
val request = MockHttpServletRequest()
request.userPrincipal = principal
RequestContextHolder.setRequestAttributes(ServletRequestAttributes(request))
val options = SentryOptions()
options.isSendDefaultPii = true
val userProvider = HttpServletRequestSentryUserProvider(options)
val result = userProvider.provideUser()
assertNotNull(result)
assertEquals("janesmith", result.username)
}
@Test
fun `when sendDefaultPii is set to false, does not attach user data Sentry Event`() {
val principal = mock<Principal>()
whenever(principal.name).thenReturn("janesmith")
val request = MockHttpServletRequest()
request.userPrincipal = principal
RequestContextHolder.setRequestAttributes(ServletRequestAttributes(request))
val options = SentryOptions()
options.isSendDefaultPii = false
val userProvider = HttpServletRequestSentryUserProvider(options)
val result = userProvider.provideUser()
assertNull(result)
}
}
| sentry-spring/src/test/kotlin/io/sentry/spring/HttpServletRequestSentryUserProviderTest.kt | 1458155769 |
/*
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.docs.features.testing.springbootapplications.autoconfiguredrestclient
class RemoteVehicleDetailsService {
fun callRestService(): String {
return "hello"
}
} | spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/features/testing/springbootapplications/autoconfiguredrestclient/RemoteVehicleDetailsService.kt | 4020944836 |
package de.treichels.hott.tts.voicerss
import de.treichels.hott.tts.*
import java.net.URL
import java.net.URLEncoder
import java.util.*
import java.util.prefs.Preferences
import javax.sound.sampled.AudioInputStream
import javax.sound.sampled.AudioSystem
class VoiceRSSTTSProvider : Text2SpeechProvider() {
companion object {
private val PREFS = Preferences.userNodeForPackage(VoiceRSSTTSProvider::class.java)
private const val VOICE_RSS_DEFAULT_API_KEY = "46209359f9804adb8616c76d18de928a"
private const val API_KEY = "apiKey"
internal var apiKey: String?
get() = PREFS.get(API_KEY, null)
set(key) {
PREFS.put(API_KEY, key)
}
}
override val enabled = true
override val name = "VoiceRSS"
override val qualities: List<Quality> = SampleRate.values().flatMap {
listOf(Quality(it.rate.toInt(), 1), Quality(it.rate.toInt(), 2))
}
override val ssmlSupported: Boolean = false
override fun installedVoices() = VoiceRssLanguage.values().map { lang ->
Voice().apply {
enabled = true
age = Age.Adult // VoiceRSS has only adult voices
locale = Locale.forLanguageTag(lang.name.replace("_", "-"))
description = lang.toString()
gender = Gender.Female // VoiceRSS has only female voices
id = lang.key
name = locale.getDisplayLanguage(locale) // VoiceRSS does not provide a name for its voices - use the language instead
}
}
override fun speak(text: String, voice: Voice, speed: Int, volume: Int, quality: Quality, ssml: Boolean): AudioInputStream {
if (ssml) throw UnsupportedOperationException("SSML markup is not supported")
// test format - throws exception if not valid
val format = Format.valueOf("pcm_${quality.sampleRate / 1000}khz_${quality.sampleSize}bit_${if (quality.channels == 1) "mono" else "stereo"}")
val key = if (apiKey.isNullOrBlank()) VOICE_RSS_DEFAULT_API_KEY else apiKey!!
val url = URL("http://api.voicerss.org/?key=$key&hl=${voice.id}&r=$speed&c=WAV&f=${format.key}&ssml=false&b64=false&src=${URLEncoder.encode(text, "UTF-8")}")
return AudioSystem.getAudioInputStream(url)
}
}
| HoTT-TTS/src/main/kotlin/de/treichels/hott/tts/voicerss/VoiceRSSTTSProvider.kt | 1143294301 |
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.graphics
import android.graphics.Bitmap
import android.graphics.ColorSpace
import android.support.test.filters.SdkSuppress
import org.junit.Assert.assertEquals
import org.junit.Test
class BitmapTest {
@Test fun create() {
val bitmap = createBitmap(7, 9)
assertEquals(7, bitmap.width)
assertEquals(9, bitmap.height)
assertEquals(Bitmap.Config.ARGB_8888, bitmap.config)
}
@Test fun createWithConfig() {
val bitmap = createBitmap(7, 9, config = Bitmap.Config.RGB_565)
assertEquals(Bitmap.Config.RGB_565, bitmap.config)
}
@SdkSuppress(minSdkVersion = 26)
@Test fun createWithColorSpace() {
val colorSpace = ColorSpace.get(ColorSpace.Named.ADOBE_RGB)
val bitmap = createBitmap(7, 9, colorSpace = colorSpace)
assertEquals(colorSpace, bitmap.colorSpace)
}
@Test fun scale() {
val b = createBitmap(7, 9).scale(3, 5)
assertEquals(3, b.width)
assertEquals(5, b.height)
}
@Test fun applyCanvas() {
val p = createBitmap(2, 2).applyCanvas {
drawColor(0x40302010)
}.getPixel(1, 1)
assertEquals(0x40302010, p)
}
@Test fun getPixel() {
val b = createBitmap(2, 2).applyCanvas {
drawColor(0x40302010)
}
assertEquals(0x40302010, b[1, 1])
}
@Test fun setPixel() {
val b = createBitmap(2, 2)
b[1, 1] = 0x40302010
assertEquals(0x40302010, b[1, 1])
}
}
| core/ktx/src/androidTest/java/androidx/core/graphics/BitmapTest.kt | 3764236537 |
package com.ivanovsky.passnotes.extensions
import com.ivanovsky.passnotes.R
import com.ivanovsky.passnotes.data.entity.FSType
import com.ivanovsky.passnotes.data.entity.FileDescriptor
import com.ivanovsky.passnotes.data.entity.UsedFile
import com.ivanovsky.passnotes.domain.ResourceProvider
fun FileDescriptor.toUsedFile(
addedTime: Long,
lastAccessTime: Long? = null
): UsedFile =
UsedFile(
fsAuthority = fsAuthority,
filePath = path,
fileUid = uid,
fileName = name,
addedTime = addedTime,
lastAccessTime = lastAccessTime
)
fun FileDescriptor.formatReadablePath(resourceProvider: ResourceProvider): String {
return when (fsAuthority.type) {
FSType.REGULAR_FS -> {
path
}
FSType.DROPBOX -> {
resourceProvider.getString(R.string.dropbox) + ":/" + path
}
FSType.WEBDAV -> {
val url = fsAuthority.credentials?.serverUrl ?: ""
url + path
}
FSType.SAF -> {
path
}
}
} | app/src/main/kotlin/com/ivanovsky/passnotes/extensions/FileDescriptorExt.kt | 195633904 |
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.text
import android.graphics.Color.RED
import android.graphics.Color.YELLOW
import android.graphics.Typeface.BOLD
import android.graphics.Typeface.ITALIC
import android.text.SpannedString
import android.text.style.BackgroundColorSpan
import android.text.style.BulletSpan
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.text.style.StrikethroughSpan
import android.text.style.StyleSpan
import android.text.style.SubscriptSpan
import android.text.style.SuperscriptSpan
import android.text.style.UnderlineSpan
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Test
class SpannableStringBuilderTest {
@Test fun builder() {
val result: SpannedString = buildSpannedString {
append("Hello,")
append(" World")
}
assertEquals("Hello, World", result.toString())
}
@Test fun builderInSpan() {
val bold = StyleSpan(BOLD)
val result: SpannedString = buildSpannedString {
append("Hello, ")
inSpans(bold) {
append("World")
}
}
assertEquals("Hello, World", result.toString())
val spans = result.getSpans<Any>()
assertEquals(1, spans.size)
val boldSpan = spans.filterIsInstance<StyleSpan>().single()
assertSame(bold, boldSpan)
assertEquals(7, result.getSpanStart(bold))
assertEquals(12, result.getSpanEnd(bold))
}
@Test fun builderBold() {
val result: SpannedString = buildSpannedString {
append("Hello, ")
bold {
append("World")
}
}
assertEquals("Hello, World", result.toString())
val spans = result.getSpans<Any>()
assertEquals(1, spans.size)
val bold = spans.filterIsInstance<StyleSpan>().single()
assertEquals(BOLD, bold.style)
assertEquals(7, result.getSpanStart(bold))
assertEquals(12, result.getSpanEnd(bold))
}
@Test fun builderItalic() {
val result: SpannedString = buildSpannedString {
append("Hello, ")
italic {
append("World")
}
}
assertEquals("Hello, World", result.toString())
val spans = result.getSpans<Any>()
assertEquals(1, spans.size)
val italic = spans.filterIsInstance<StyleSpan>().single()
assertEquals(ITALIC, italic.style)
assertEquals(7, result.getSpanStart(italic))
assertEquals(12, result.getSpanEnd(italic))
}
@Test fun builderUnderline() {
val result: SpannedString = buildSpannedString {
append("Hello, ")
underline {
append("World")
}
}
assertEquals("Hello, World", result.toString())
val spans = result.getSpans<Any>()
assertEquals(1, spans.size)
val underline = spans.filterIsInstance<UnderlineSpan>().single()
assertEquals(7, result.getSpanStart(underline))
assertEquals(12, result.getSpanEnd(underline))
}
@Test fun builderColor() {
val result: SpannedString = buildSpannedString {
append("Hello, ")
color(RED) {
append("World")
}
}
assertEquals("Hello, World", result.toString())
val spans = result.getSpans<Any>()
assertEquals(1, spans.size)
val color = spans.filterIsInstance<ForegroundColorSpan>().single()
assertEquals(RED, color.foregroundColor)
assertEquals(7, result.getSpanStart(color))
assertEquals(12, result.getSpanEnd(color))
}
@Test fun builderBackgroundColor() {
val result: SpannedString = buildSpannedString {
append("Hello, ")
backgroundColor(RED) {
append("World")
}
}
assertEquals("Hello, World", result.toString())
val spans = result.getSpans<Any>()
assertEquals(1, spans.size)
val color = spans.filterIsInstance<BackgroundColorSpan>().single()
assertEquals(RED, color.backgroundColor)
assertEquals(7, result.getSpanStart(color))
assertEquals(12, result.getSpanEnd(color))
}
@Test fun builderStrikeThrough() {
val result: SpannedString = buildSpannedString {
append("Hello, ")
strikeThrough {
append("World")
}
}
assertEquals("Hello, World", result.toString())
val spans = result.getSpans<Any>()
assertEquals(1, spans.size)
val strikeThrough = spans.filterIsInstance<StrikethroughSpan>().single()
assertEquals(7, result.getSpanStart(strikeThrough))
assertEquals(12, result.getSpanEnd(strikeThrough))
}
@Test fun builderScale() {
val result: SpannedString = buildSpannedString {
append("Hello, ")
scale(2f) {
append("World")
}
}
assertEquals("Hello, World", result.toString())
val spans = result.getSpans<Any>()
assertEquals(1, spans.size)
val scale = spans.filterIsInstance<RelativeSizeSpan>().single()
assertEquals(2f, scale.sizeChange)
assertEquals(7, result.getSpanStart(scale))
assertEquals(12, result.getSpanEnd(scale))
}
@Test fun nested() {
val result: SpannedString = buildSpannedString {
color(RED) {
append('H')
inSpans(SubscriptSpan()) {
append('e')
}
append('l')
inSpans(SuperscriptSpan()) {
append('l')
}
append('o')
}
append(", ")
backgroundColor(YELLOW) {
append('W')
underline {
append('o')
bold {
append('r')
}
append('l')
}
append('d')
}
}
assertEquals("Hello, World", result.toString())
val spans = result.getSpans<Any>()
assertEquals(6, spans.size)
val color = spans.filterIsInstance<ForegroundColorSpan>().single()
assertEquals(RED, color.foregroundColor)
assertEquals(0, result.getSpanStart(color))
assertEquals(5, result.getSpanEnd(color))
val subscript = spans.filterIsInstance<SubscriptSpan>().single()
assertEquals(1, result.getSpanStart(subscript))
assertEquals(2, result.getSpanEnd(subscript))
val superscript = spans.filterIsInstance<SuperscriptSpan>().single()
assertEquals(3, result.getSpanStart(superscript))
assertEquals(4, result.getSpanEnd(superscript))
val backgroundColor = spans.filterIsInstance<BackgroundColorSpan>().single()
assertEquals(YELLOW, backgroundColor.backgroundColor)
assertEquals(7, result.getSpanStart(backgroundColor))
assertEquals(12, result.getSpanEnd(backgroundColor))
val underline = spans.filterIsInstance<UnderlineSpan>().single()
assertEquals(8, result.getSpanStart(underline))
assertEquals(11, result.getSpanEnd(underline))
val bold = spans.filterIsInstance<StyleSpan>().single()
assertEquals(BOLD, bold.style)
assertEquals(9, result.getSpanStart(bold))
assertEquals(10, result.getSpanEnd(bold))
}
@Test fun multipleSpans() {
val result: SpannedString = buildSpannedString {
append("Hello, ")
inSpans(BulletSpan(), UnderlineSpan()) {
append("World")
}
}
assertEquals("Hello, World", result.toString())
val spans = result.getSpans<Any>()
assertEquals(2, spans.size)
val bullet = spans.filterIsInstance<BulletSpan>().single()
assertEquals(7, result.getSpanStart(bullet))
assertEquals(12, result.getSpanEnd(bullet))
val underline = spans.filterIsInstance<UnderlineSpan>().single()
assertEquals(7, result.getSpanStart(underline))
assertEquals(12, result.getSpanEnd(underline))
}
}
| core/ktx/src/androidTest/java/androidx/core/text/SpannableStringBuilderTest.kt | 4290321239 |
package org.fossasia.openevent.general.attendees
import androidx.room.TypeConverter
class AttendeeIdConverter {
@TypeConverter
fun fromAttendeeId(attendeeId: AttendeeId): Long {
return attendeeId.id
}
@TypeConverter
fun toAttendeeId(id: Long): AttendeeId {
return AttendeeId(id)
}
}
| app/src/main/java/org/fossasia/openevent/general/attendees/AttendeeIdConverter.kt | 1703350117 |
package nl.kadaster.land_administration
import nl.kadaster.land_administration.core.commons.ObjectId
import nl.kadaster.land_administration.query.identifiers.IdentifierView
import nl.kadaster.land_administration.query.identifiers.api.LatestIdentifiers
import org.axonframework.messaging.responsetypes.ResponseTypes
import org.axonframework.queryhandling.QueryGateway
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.core.env.Environment
import org.springframework.ui.Model
import org.springframework.ui.set
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.servlet.ModelAndView
@RestController
class RootController(private val environment: Environment,
private val queryGateway: QueryGateway) {
private val logger: Logger = LoggerFactory.getLogger(RootController::class.java)
@GetMapping(value = ["/", "/index"])
fun index(model: Model): ModelAndView {
model["title"] = "It works!"
model["profile"] = environment.activeProfiles.joinToString(",")
model["objectId"] = getLatestObjectId()
logger.info("objectId in model: {}", model.getAttribute("objectId"))
return ModelAndView("index", model.asMap())
}
private fun getLatestObjectId(): String {
val query = queryGateway.query(
LatestIdentifiers(),
ResponseTypes.multipleInstancesOf(IdentifierView::class.java)).get()
logger.info("query result: {}", query)
@Suppress("UNCHECKED_CAST")
val latestIdentifiers = (query as List<Map<String, String>>)
.filter { v -> v["identifierType"] == ObjectId.namespace }
.getOrNull(0)
return latestIdentifiers?.get("value") ?: "000000000000001"
}
}
| boot/src/main/kotlin/nl/kadaster/land_administration/rootControllers.kt | 2168402035 |
package com.github.developer__.asycn
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.ClipDrawable
import android.os.AsyncTask
import android.os.Looper
import android.view.Gravity
import android.widget.ImageView
import android.widget.SeekBar
import com.bumptech.glide.Glide
import java.lang.ref.WeakReference
/**
* Created by Jemo on 12/5/16.
*/
class ClipDrawableProcessorTask<T>(imageView: ImageView, seekBar: SeekBar, private val context: Context, private val loadedFinishedListener: OnAfterImageLoaded? = null) : AsyncTask<T, Void, ClipDrawable>() {
private val imageRef: WeakReference<ImageView>
private val seekBarRef: WeakReference<SeekBar>
init {
this.imageRef = WeakReference(imageView)
this.seekBarRef = WeakReference(seekBar)
}
override fun doInBackground(vararg args: T): ClipDrawable? {
Looper.myLooper()?.let { Looper.prepare() }
try {
var theBitmap: Bitmap
if (args[0] is String) {
theBitmap = Glide.with(context)
.load(args[0])
.asBitmap()
.into(-1, -1)
.get()
} else {
theBitmap = (args[0] as BitmapDrawable).bitmap
}
val tmpBitmap = getScaledBitmap(theBitmap)
if (tmpBitmap != null)
theBitmap = tmpBitmap
val bitmapDrawable = BitmapDrawable(context.resources, theBitmap)
return ClipDrawable(bitmapDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL)
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
private fun getScaledBitmap(bitmap: Bitmap): Bitmap? {
try {
if (imageRef.get() == null)
return bitmap
val imageWidth = imageRef.get().width
val imageHeight = imageRef.get().height
if (imageWidth > 0 && imageHeight > 0)
return Bitmap.createScaledBitmap(bitmap, imageWidth, imageHeight, false)
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
override fun onPostExecute(clipDrawable: ClipDrawable?) {
if (imageRef.get() != null) {
if (clipDrawable != null) {
initSeekBar(clipDrawable)
imageRef.get().setImageDrawable(clipDrawable)
if (clipDrawable.level != 0) {
val progressNum = 5000
clipDrawable.level = progressNum
} else
clipDrawable.level = seekBarRef.get().progress
loadedFinishedListener?.onLoadedFinished(true)
} else {
loadedFinishedListener?.onLoadedFinished(false)
}
} else {
loadedFinishedListener?.onLoadedFinished(false)
}
}
private fun initSeekBar(clipDrawable: ClipDrawable) {
seekBarRef.get().setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
clipDrawable.level = i
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
}
})
}
interface OnAfterImageLoaded {
fun onLoadedFinished(loadedSuccess: Boolean)
}
} | beforeafterslider/src/main/java/com/github/developer__/asycn/ClipDrawableProcessorTask.kt | 4260363923 |
package com.almasb.zeph.character
/**
* Used to show where particular equipment goes on a character.
*
* @author Almas Baimagambetov (AlmasB) ([email protected])
*/
enum class EquipPlace(val emptyID: Int) {
/**
* Denotes a place for head item
*/
HELM(5000),
/**
* Denotes a place for body item
*/
BODY(5001),
/**
* Denotes a place for shoes item
*/
SHOES(5002),
/**
* Denotes a place for right hand item
*/
RIGHT_HAND(4000),
/**
* Denotes a place for left hand item
*/
LEFT_HAND(4000);
val isWeapon: Boolean
get() = ordinal >= RIGHT_HAND.ordinal
} | src/main/kotlin/com/almasb/zeph/character/EquipPlace.kt | 4223890991 |
/*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.kork.plugins.loaders
import com.netflix.spinnaker.kork.plugins.finders.SpinnakerPropertiesPluginDescriptorFinder
import com.netflix.spinnaker.kork.plugins.testplugin.api.TestExtension
import com.netflix.spinnaker.kork.plugins.testplugin.basicGeneratedPlugin
import dev.minutest.junit.JUnit5Minutests
import dev.minutest.rootContext
import io.mockk.mockk
import java.nio.file.Path
import java.nio.file.Paths
import org.pf4j.PluginClassLoader
import org.pf4j.PluginDescriptor
import org.pf4j.PluginLoader
import org.pf4j.PluginManager
import strikt.api.expectThat
import strikt.assertions.isA
import strikt.assertions.isEqualTo
import strikt.assertions.isTrue
abstract class SpinnakerPluginLoadersTCK : JUnit5Minutests {
protected abstract fun subjectSupplier(): (f: Fixture) -> PluginLoader
protected abstract fun buildFixture(): Fixture
fun tests() = rootContext<Fixture> {
fixture { buildFixture() }
test("unsafe plugin directory is applicable") {
expectThat(subject.isApplicable(unsafePluginPath)).isTrue()
}
test("loads the unsafe plugin class") {
val classpath = subject.loadPlugin(unsafePluginPath, unsafePluginDescriptor)
expectThat(classpath).isA<UnsafePluginClassLoader>()
expectThat(classpath.loadClass(unsafePluginDescriptor.pluginClass).name).isEqualTo(unsafePluginDescriptor.pluginClass)
}
test("standard plugin directory is applicable") {
expectThat(subject.isApplicable(standardPluginPath)).isTrue()
}
test("loads the standard plugin") {
val classpath = subject.loadPlugin(standardPluginPath, standardPluginDescriptor)
expectThat(classpath).isA<PluginClassLoader>()
val pluginClass = classpath.loadClass(standardPluginDescriptor.pluginClass)
expectThat(pluginClass.name).isEqualTo(standardPluginDescriptor.pluginClass)
val extensionClassName = "${pluginClass.`package`.name}.${standardPluginName}Extension"
val extensionClass = classpath.loadClass(extensionClassName)
val extensionConfigClassName = "${pluginClass.`package`.name}.${standardPluginName}PluginConfiguration"
val extensionConfigClass = classpath.loadClass(extensionConfigClassName)
val extensionConfig = extensionConfigClass.newInstance()
expectThat(TestExtension::class.java.isAssignableFrom(extensionClass)).isTrue()
val extension = extensionClass.constructors.first().newInstance(extensionConfig) as TestExtension
expectThat(extension.testValue).isEqualTo(extensionClass.simpleName)
}
}
interface Fixture {
val subject: PluginLoader
val unsafePluginPath: Path
val unsafePluginDescriptor: PluginDescriptor
val pluginManager: PluginManager
val standardPluginPath: Path
val standardPluginDescriptor: PluginDescriptor
val standardPluginName: String
}
protected open inner class FixtureImpl(supplier: (f: Fixture) -> PluginLoader) : Fixture {
val unsafeDescriptorDirectory: Path = Paths.get(javaClass.getResource("/unsafe-testplugin/plugin.properties").toURI()).parent
override val unsafePluginPath: Path = unsafeDescriptorDirectory
override val unsafePluginDescriptor: PluginDescriptor = SpinnakerPropertiesPluginDescriptorFinder().find(unsafeDescriptorDirectory)
override val pluginManager: PluginManager = mockk(relaxed = true)
override val standardPluginPath: Path = plugin.pluginPath
override val standardPluginDescriptor: PluginDescriptor = plugin.descriptor
override val standardPluginName: String = generatedPluginName
override val subject = supplier(this)
}
companion object {
const val generatedPluginName = "PluginLoaderTests"
val plugin = basicGeneratedPlugin(generatedPluginName).generate()
}
}
class SpinnakerDefaultPluginLoaderTest : SpinnakerPluginLoadersTCK() {
override fun subjectSupplier(): (f: Fixture) -> PluginLoader = { SpinnakerDefaultPluginLoader(it.pluginManager) }
override fun buildFixture(): Fixture = FixtureImpl(subjectSupplier())
}
| kork-plugins/src/test/kotlin/com/netflix/spinnaker/kork/plugins/loaders/SpinnakerPluginLoaderTests.kt | 2253683230 |
/*
* Copyright (C) 2017 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.settings.activity
import android.os.Bundle
import androidx.fragment.app.commit
import androidx.fragment.app.setFragmentResultListener
import androidx.preference.Preference
import jp.hazuki.yuzubrowser.core.utility.utils.ui
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.legacy.settings.preference.ThemePreference
import jp.hazuki.yuzubrowser.ui.RestartActivity
import kotlinx.coroutines.delay
class UiSettingFragment : YuzuPreferenceFragment() {
override fun onCreateYuzuPreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.pref_ui_settings)
findPreference<Preference>("theme_setting")!!.setOnPreferenceChangeListener { _, _ ->
ui {
delay(100L)
startActivity(RestartActivity.createIntent(requireContext()))
}
true
}
findPreference<Preference>("theme_management")!!.setOnPreferenceClickListener {
openFragment(ThemeManagementFragment())
true
}
findPreference<Preference>("restart")!!.setOnPreferenceClickListener {
startActivity(RestartActivity.createIntent(requireContext()))
true
}
findPreference<Preference>("reader_settings")!!.setOnPreferenceClickListener {
parentFragmentManager.commit {
replace(R.id.container, ReaderSettingsFragment())
addToBackStack("reader_settings")
}
true
}
setFragmentResultListener(ThemeManagementFragment.REQUEST_THEME_LIST_UPDATE) { _, bundle ->
if (bundle.getBoolean(ThemeManagementFragment.REQUEST_THEME_LIST_UPDATE)) {
findPreference<ThemePreference>("theme_setting")!!.load()
}
}
}
}
| legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/settings/activity/UiSettingFragment.kt | 1151838577 |
package com.foo.rest.examples.spring.openapi.v3.uuid
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.util.*
@RestController
@RequestMapping(path = ["/api/uuid"])
class UuidRest {
@GetMapping(path = ["/{a}"])
open fun check(@PathVariable("a") a: String) : ResponseEntity<String> {
val x = UUID.fromString(a)
return if (x != null){
ResponseEntity.ok("OK")
} else{
ResponseEntity.status(500).build()
}
}
} | e2e-tests/spring-rest-openapi-v3/src/main/kotlin/com/foo/rest/examples/spring/openapi/v3/uuid/UuidRest.kt | 1380569927 |
package org.evomaster.core.database.extract.postgres
import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType
import org.evomaster.client.java.controller.db.SqlScriptRunner
import org.evomaster.client.java.controller.internal.db.SchemaExtractor
import org.evomaster.core.database.DbActionTransformer
import org.evomaster.core.database.SqlInsertBuilder
import org.evomaster.core.search.gene.numeric.IntegerGene
import org.evomaster.core.search.gene.sql.SqlMultidimensionalArrayGene
import org.evomaster.core.search.gene.optional.NullableGene
import org.evomaster.core.search.gene.string.StringGene
import org.evomaster.core.search.service.Randomness
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
/**
* Created by jgaleotti on 07-May-19.
*/
class ArrayTypesTest : ExtractTestBasePostgres() {
override fun getSchemaLocation() = "/sql_schema/postgres_array_types.sql"
private val rand = Randomness()
@BeforeEach
fun initRand() {
rand.updateSeed(42)
}
@Test
fun testExtractionOfArrayTypes() {
val schema = SchemaExtractor.extract(connection)
assertNotNull(schema)
assertEquals("public", schema.name.lowercase())
assertEquals(DatabaseType.POSTGRES, schema.databaseType)
assertTrue(schema.tables.any { it.name.equals("ArrayTypes".lowercase()) })
val table = schema.tables.find { it.name.equals("ArrayTypes".lowercase()) }
assertTrue(table!!.columns.any { it.name.equals("nonArrayColumn".lowercase()) })
val nonArrayColumnDto = table.columns.find { it.name.equals("nonArrayColumn".lowercase()) }!!
assertEquals("int4", nonArrayColumnDto.type)
assertEquals(0, nonArrayColumnDto.numberOfDimensions)
assertTrue(table.columns.any { it.name.equals("arrayColumn".lowercase()) })
val arrayColumnDto = table.columns.find { it.name.equals("arrayColumn".lowercase()) }!!
assertEquals("_int4", arrayColumnDto.type)
assertEquals(1, arrayColumnDto.numberOfDimensions)
assertTrue(table.columns.any { it.name.equals("matrixColumn".lowercase()) })
val matrixColumnDto = table.columns.find { it.name.equals("matrixColumn".lowercase()) }!!
assertEquals("_int4", matrixColumnDto.type)
assertEquals(2, matrixColumnDto.numberOfDimensions)
assertTrue(table.columns.any { it.name.equals("spaceColumn".lowercase()) })
val spaceColumnDto = table.columns.find { it.name.equals("spaceColumn".lowercase()) }!!
assertEquals("_int4", spaceColumnDto.type)
assertEquals(3, spaceColumnDto.numberOfDimensions)
assertTrue(table.columns.any { it.name.equals("manyDimensionsColumn".lowercase()) })
val manyDimensionsColumnDto = table.columns.find { it.name.equals("manyDimensionsColumn".lowercase()) }!!
assertEquals("_int4", manyDimensionsColumnDto.type)
assertEquals(4, manyDimensionsColumnDto.numberOfDimensions)
assertTrue(table.columns.any { it.name.equals("exactSizeArrayColumn".lowercase()) })
val exactSizeArrayColumnDto = table.columns.find { it.name.equals("exactSizeArrayColumn".lowercase()) }!!
assertEquals("_int4", exactSizeArrayColumnDto.type)
assertEquals(1, exactSizeArrayColumnDto.numberOfDimensions)
assertTrue(table.columns.any { it.name.equals("exactSizeMatrixColumn".lowercase()) })
val exactSizeMatrixColumnDto = table.columns.find { it.name.equals("exactSizeMatrixColumn".lowercase()) }!!
assertEquals("_int4", exactSizeMatrixColumnDto.type)
assertEquals(2, exactSizeMatrixColumnDto.numberOfDimensions)
}
@Test
fun testBuildGenesOfArrayTypes() {
val schema = SchemaExtractor.extract(connection)
val builder = SqlInsertBuilder(schema)
val actions = builder.createSqlInsertionAction(
"ArrayTypes",
setOf(
"nonArrayColumn",
"arrayColumn",
"matrixColumn",
"spaceColumn",
"manyDimensionsColumn",
"exactSizeArrayColumn",
"exactSizeMatrixColumn"
)
)
val genes = actions[0].seeTopGenes()
assertEquals(7, genes.size)
assertTrue(genes[0] is IntegerGene)
assertTrue(genes[1] is SqlMultidimensionalArrayGene<*>)
assertTrue(genes[2] is SqlMultidimensionalArrayGene<*>)
assertTrue(genes[3] is SqlMultidimensionalArrayGene<*>)
assertTrue(genes[4] is SqlMultidimensionalArrayGene<*>)
assertTrue(genes[5] is SqlMultidimensionalArrayGene<*>)
assertTrue(genes[6] is SqlMultidimensionalArrayGene<*>)
val arrayColumn = genes[1] as SqlMultidimensionalArrayGene<IntegerGene>
assertEquals(1, arrayColumn.numberOfDimensions)
arrayColumn.doInitialize(rand)
do {
arrayColumn.randomize(rand, tryToForceNewValue = false)
} while (arrayColumn.getDimensionSize(0) != 0)
assertEquals("\"{}\"", arrayColumn.getValueAsPrintableString())
val matrixColumn = genes[2] as SqlMultidimensionalArrayGene<IntegerGene>
assertEquals(2, matrixColumn.numberOfDimensions)
val spaceColumn = genes[3] as SqlMultidimensionalArrayGene<IntegerGene>
assertEquals(3, spaceColumn.numberOfDimensions)
do {
arrayColumn.randomize(rand, tryToForceNewValue = false)
} while (arrayColumn.getDimensionSize(0) != 3)
assertEquals(3, arrayColumn.getDimensionSize(0))
arrayColumn.getElement(listOf(0)).value = 1
arrayColumn.getElement(listOf(1)).value = 2
arrayColumn.getElement(listOf(2)).value = 3
assertEquals("\"{1, 2, 3}\"", arrayColumn.getValueAsPrintableString())
}
@Test
fun testInsertValuesOfArrayGenes() {
val schema = SchemaExtractor.extract(connection)
val builder = SqlInsertBuilder(schema)
val actions = builder.createSqlInsertionAction(
"ArrayTypes",
setOf(
"nonArrayColumn",
"arrayColumn",
"matrixColumn",
"spaceColumn",
"manyDimensionsColumn",
"exactSizeArrayColumn",
"exactSizeMatrixColumn"
)
)
actions.forEach{ it.seeTopGenes().forEach { it.doInitialize(rand) }}
val dbCommandDto = DbActionTransformer.transform(actions)
SqlScriptRunner.execInsert(connection, dbCommandDto.insertions)
}
@Test
fun testInsertNullIntoNullableArray() {
val schema = SchemaExtractor.extract(connection)
val builder = SqlInsertBuilder(schema)
val actions = builder.createSqlInsertionAction(
"NullableArrayTable",
setOf(
"nullableArrayColumn"
)
)
val genes = actions[0].seeTopGenes()
assertEquals(1, genes.size)
val nullableArrayColumn = genes[0] as SqlMultidimensionalArrayGene<*>
assertEquals(1, nullableArrayColumn.numberOfDimensions)
assertTrue(nullableArrayColumn.template is NullableGene)
nullableArrayColumn.doInitialize(rand)
do {
nullableArrayColumn.randomize(rand, tryToForceNewValue = false)
} while (nullableArrayColumn.getDimensionSize(0) != 1)
val sqlNullableGene = nullableArrayColumn.getElement(listOf(0)) as NullableGene
sqlNullableGene.isPresent = false
assertEquals("\"{NULL}\"", nullableArrayColumn.getValueAsPrintableString())
val dbCommandDto = DbActionTransformer.transform(actions)
SqlScriptRunner.execInsert(connection, dbCommandDto.insertions)
}
@Test
fun testInsertStringIntoArray() {
val schema = SchemaExtractor.extract(connection)
val builder = SqlInsertBuilder(schema)
val actions = builder.createSqlInsertionAction(
"StringArrayTable",
setOf(
"stringArrayColumn"
)
)
val genes = actions[0].seeTopGenes()
assertEquals(1, genes.size)
val stringArrayColumn = genes[0] as SqlMultidimensionalArrayGene<*>
assertEquals(1, stringArrayColumn.numberOfDimensions)
assertTrue(stringArrayColumn.template is StringGene)
stringArrayColumn.doInitialize(rand)
do {
stringArrayColumn.randomize(rand, tryToForceNewValue = false)
} while (stringArrayColumn.getDimensionSize(0) != 1)
val stringGene = stringArrayColumn.getElement(listOf(0)) as StringGene
stringGene.value = "Hello World"
assertEquals("\"{\"Hello World\"}\"", stringArrayColumn.getValueAsPrintableString())
val dbCommandDto = DbActionTransformer.transform(actions)
SqlScriptRunner.execInsert(connection, dbCommandDto.insertions)
}
@Test
fun testInsertStringIntoArrayWithQuotes() {
val schema = SchemaExtractor.extract(connection)
val builder = SqlInsertBuilder(schema)
val actions = builder.createSqlInsertionAction(
"StringArrayTable",
setOf(
"stringArrayColumn"
)
)
val genes = actions[0].seeTopGenes()
assertEquals(1, genes.size)
val stringArrayColumn = genes[0] as SqlMultidimensionalArrayGene<*>
assertEquals(1, stringArrayColumn.numberOfDimensions)
assertTrue(stringArrayColumn.template is StringGene)
stringArrayColumn.doInitialize(rand)
do {
stringArrayColumn.randomize(rand, tryToForceNewValue = false)
} while (stringArrayColumn.getDimensionSize(0) != 1)
val stringGene = stringArrayColumn.getElement(listOf(0)) as StringGene
stringGene.value = "Hello\"World"
assertEquals("\"{\"Hello\\\"World\"}\"", stringArrayColumn.getValueAsPrintableString())
val dbCommandDto = DbActionTransformer.transform(actions)
SqlScriptRunner.execInsert(connection, dbCommandDto.insertions)
}
@Test
fun testInsertStringIntoArrayWithApostrophe() {
val schema = SchemaExtractor.extract(connection)
val builder = SqlInsertBuilder(schema)
val actions = builder.createSqlInsertionAction(
"StringArrayTable",
setOf(
"stringArrayColumn"
)
)
val genes = actions[0].seeTopGenes()
assertEquals(1, genes.size)
val stringArrayColumn = genes[0] as SqlMultidimensionalArrayGene<*>
assertEquals(1, stringArrayColumn.numberOfDimensions)
assertTrue(stringArrayColumn.template is StringGene)
stringArrayColumn.doInitialize(rand)
do {
stringArrayColumn.randomize(rand, tryToForceNewValue = false)
} while (stringArrayColumn.getDimensionSize(0) != 1)
val stringGene = stringArrayColumn.getElement(listOf(0)) as StringGene
stringGene.value = "Hello'World"
assertEquals("\"{\"Hello'World\"}\"", stringArrayColumn.getValueAsPrintableString())
val dbCommandDto = DbActionTransformer.transform(actions)
SqlScriptRunner.execInsert(connection, dbCommandDto.insertions)
}
} | core/src/test/kotlin/org/evomaster/core/database/extract/postgres/ArrayTypesTest.kt | 2003816808 |
package org.evomaster.core.database.extract.postgres
import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType
import org.evomaster.client.java.controller.internal.db.SchemaExtractor
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
/**
* Created by jgaleotti on 07-May-19.
*/
class CreateTableExtractCheckTest : ExtractTestBasePostgres() {
override fun getSchemaLocation() = "/sql_schema/create_table_check.sql"
@Test
fun testCreateAndExtract() {
val schema = SchemaExtractor.extract(connection)
assertNotNull(schema)
assertEquals("public", schema.name.toLowerCase())
assertEquals(DatabaseType.POSTGRES, schema.databaseType)
assertTrue(schema.tables.any { it.name == "people" })
assertEquals(2, schema.tables.first { it.name == "people" }.columns.size)
assertTrue(schema.tables.first { it.name == "people" }.columns.any { it.name == "age" });
assertEquals(1, schema.tables.first { it.name == "people" }.tableCheckExpressions.size)
assertEquals("(age <= 100)", schema.tables.first { it.name == "people" }.tableCheckExpressions[0].sqlCheckExpression)
}
} | core/src/test/kotlin/org/evomaster/core/database/extract/postgres/CreateTableExtractCheckTest.kt | 2306687258 |
package day16
import java.io.File
import java.util.*
fun main(args: Array<String>) {
val re = Regex("([sxp])(\\d+|\\w)/?(\\d+|\\w)?")
var programs = ('a'..'p').map { it.toString() }.toMutableList()
File("src/day16/input.txt").bufferedReader().readLine()!!.split(",").forEach { action ->
val (move, param1, param2) = re.matchEntire(action)!!.destructured
when (move) {
"s" -> {
val spins = param1.toInt() % programs.size
val left = programs.subList(programs.size - spins, programs.size)
val right = programs.subList(0, programs.size - spins)
programs = left
programs.addAll(right)
}
"x" -> Collections.swap(programs, param1.toInt(), param2.toInt())
"p" -> Collections.swap(programs, programs.indexOf(param1), programs.indexOf(param2))
else -> throw IllegalArgumentException("Unknown dance move: $move")
}
}
println(programs.joinToString(""))
} | 2017/src/day16/part01.kt | 465179725 |
package net.mieczkowski.yelpbusinessexample
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import com.bluelinelabs.conductor.Conductor
import com.bluelinelabs.conductor.Controller
import com.bluelinelabs.conductor.Router
import com.bluelinelabs.conductor.RouterTransaction
import kotlinx.android.synthetic.main.activity_main.*
import net.mieczkowski.yelpbusinessexample.controllers.LocationController
import net.mieczkowski.yelpbusinessexample.controllers.WelcomeController
import net.mieczkowski.yelpbusinessexample.interfaces.IToolbar
class MainActivity : AppCompatActivity(), IToolbar {
private lateinit var router: Router
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
val rootController: Controller = if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
LocationController()
} else {
WelcomeController()
}
router = Conductor.attachRouter(this, controllerContainer, savedInstanceState)
if (!router.hasRootController()) {
router.setRoot(RouterTransaction.with(rootController))
}
}
override fun onBackPressed() {
if (!router.handleBack()) {
super.onBackPressed()
}
}
override fun getToolBar(): Toolbar = toolbar
}
| app/src/main/java/net/mieczkowski/yelpbusinessexample/MainActivity.kt | 444946770 |
package com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.LibGDXSkinLanguage
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_BLOCK_COMMENT
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_BRACES
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_BRACKETS
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_CLASS_NAME
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_COLON
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_COMMA
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_INVALID_ESCAPE
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_KEYWORD
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_LINE_COMMENT
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_NUMBER
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_PARENT_PROPERTY
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_PROPERTY_NAME
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_RESOURCE_NAME
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_STRING
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.highlighting.SkinSyntaxHighlighterFactory.Companion.SKIN_VALID_ESCAPE
import com.intellij.application.options.colors.InspectionColorSettingsPage
import com.intellij.openapi.fileTypes.SyntaxHighlighter
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory
import com.intellij.openapi.options.colors.AttributesDescriptor
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import com.intellij.psi.codeStyle.DisplayPriority
import com.intellij.psi.codeStyle.DisplayPrioritySortable
import icons.Icons
import javax.swing.Icon
/*
* Copyright 2016 Blue Box Ware
*
* 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.
*/
class LibGDXSkinColorsPage : ColorSettingsPage, InspectionColorSettingsPage, DisplayPrioritySortable {
companion object {
private val additionalHighlighting = mapOf(
"resourceName" to SKIN_RESOURCE_NAME,
"propertyName" to SKIN_PROPERTY_NAME,
"className" to SKIN_CLASS_NAME,
"number" to SKIN_NUMBER,
"keyword" to SKIN_KEYWORD,
"parent" to SKIN_PARENT_PROPERTY
)
private val myAttributeDescriptors = arrayOf(
AttributesDescriptor("Property name", SKIN_PROPERTY_NAME),
AttributesDescriptor("Parent property", SKIN_PARENT_PROPERTY),
AttributesDescriptor("Braces", SKIN_BRACES),
AttributesDescriptor("Brackets", SKIN_BRACKETS),
AttributesDescriptor("Comma", SKIN_COMMA),
AttributesDescriptor("Colon", SKIN_COLON),
AttributesDescriptor("Number", SKIN_NUMBER),
AttributesDescriptor("Keyword", SKIN_KEYWORD),
AttributesDescriptor("Line comment", SKIN_LINE_COMMENT),
AttributesDescriptor("Block comment", SKIN_BLOCK_COMMENT),
AttributesDescriptor("Valid escape sequence", SKIN_VALID_ESCAPE),
AttributesDescriptor("Invalid escape sequence", SKIN_INVALID_ESCAPE),
AttributesDescriptor("String", SKIN_STRING),
AttributesDescriptor("Class name", SKIN_CLASS_NAME),
AttributesDescriptor("Resource name", SKIN_RESOURCE_NAME)
)
}
override fun getIcon(): Icon = Icons.SKIN_FILETYPE
override fun getHighlighter(): SyntaxHighlighter =
SyntaxHighlighterFactory.getSyntaxHighlighter(
LibGDXSkinLanguage.INSTANCE,
null,
null
)
override fun getDemoText() = """
{
// Line comment
/* Block comment */
<className>com.badlogic.gdx.graphics.Color</className>: {
<resourceName>red</resourceName>: { <propertyName>r</propertyName>: <number>1</number>, <propertyName>g</propertyName>: <number>0</number>, <propertyName>b</propertyName>: <number>0</number>, <propertyName>a</propertyName>: <number>1</number> },
<resourceName>yellow</resourceName>: { <propertyName>r</propertyName>: <number>0.5</number>, <propertyName>g</propertyName>: <number>0.5</number>, <propertyName>b</propertyName>: <number>0</number>, <propertyName>a</propertyName>: <number>1</number> }
},
<className>com.badlogic.gdx.graphics.g2d.BitmapFont</className>: {
<resourceName>medium</resourceName>: { <propertyName>file</propertyName>: medium.fnt, <propertyName>keyword</propertyName>: <keyword>true</keyword> }
},
<className>com.badlogic.gdx.scenes.scene2d.ui.TextButton${'$'}TextButtonStyle</className>: {
<resourceName>default</resourceName>: {
<propertyName>down</propertyName>: "round-down", <propertyName>up</propertyName>: round,
<propertyName>font</propertyName>: 'medium', <propertyName>fontColor</propertyName>: white
},
<resourceName>toggle</resourceName>: {
<parent>parent</parent>: default,
<propertyName>down</propertyName>: round-down, <propertyName>up</propertyName>: round, <propertyName>checked</propertyName>: round-down,
<propertyName>font</propertyName>: medium, <propertyName>fontColor</propertyName>: white, <propertyName>checkedFontColor</propertyName>: red
},
}
}
"""
override fun getAdditionalHighlightingTagToDescriptorMap() = additionalHighlighting
override fun getAttributeDescriptors(): Array<out AttributesDescriptor> = myAttributeDescriptors
override fun getColorDescriptors(): Array<out ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY
@Suppress("DialogTitleCapitalization")
override fun getDisplayName() = "libGDX skin"
override fun getPriority(): DisplayPriority = DisplayPriority.LANGUAGE_SETTINGS
}
| src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/highlighting/LibGDXSkinColorsPage.kt | 2169265820 |
package builders
import org.junit.Assert
import org.junit.Test
class BuildersHowItWorksTest {
@Test
fun testBuildersQuiz() {
if (answers.values.toSet() == setOf(null)) {
Assert.fail("Please specify your answers!")
}
val correctAnswers = mapOf(22 - 20 to Answer.b, 1 + 3 to Answer.c, 11 - 8 to Answer.b, 79 - 78 to Answer.c)
if (correctAnswers != answers) {
val incorrect = (1..4).filter { answers[it] != correctAnswers[it] }
Assert.fail("Your answers are incorrect! $incorrect")
}
}
} | src/test/kotlin/builders/BuildersHowItWorks.kt | 213798518 |
/*
* Transportr
*
* Copyright (c) 2013 - 2018 Torsten Grote
*
* This program is Free Software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.grobox.transportr.about
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import de.grobox.transportr.R
import de.grobox.transportr.TransportrFragment
import de.grobox.transportr.about.ContributorAdapter.ContributorViewHolder
import de.grobox.transportr.about.ContributorGroupAdapter.ContributorGroupViewHolder
class ContributorFragment : TransportrFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.fragment_contributors, container, false)
val list = v.findViewById<RecyclerView>(R.id.list)
list.layoutManager = LinearLayoutManager(context)
list.adapter = ContributorGroupAdapter(CONTRIBUTORS)
return v
}
}
class TranslatorsFragment : TransportrFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.fragment_translators, container, false)
val list = v.findViewById<RecyclerView>(R.id.list)
list.layoutManager = LinearLayoutManager(context)
list.adapter = ContributorGroupAdapter(LANGUAGES)
return v
}
}
private class ContributorGroupAdapter(val groups: List<ContributorGroup>) : RecyclerView.Adapter<ContributorGroupViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContributorGroupViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.list_item_contributor_group, parent, false)
return ContributorGroupViewHolder(v)
}
override fun onBindViewHolder(ui: ContributorGroupViewHolder, position: Int) {
ui.bind(groups[position])
}
override fun getItemCount(): Int = groups.size
private class ContributorGroupViewHolder(v: View) : RecyclerView.ViewHolder(v) {
val languageName: TextView = v.findViewById(R.id.languageName)
val list: RecyclerView = v.findViewById(R.id.list)
internal fun bind(contributorGroup: ContributorGroup) {
languageName.setText(contributorGroup.name)
list.layoutManager = LinearLayoutManager(list.context)
list.adapter = ContributorAdapter(contributorGroup.contributors)
}
}
}
private class ContributorAdapter(val contributors: List<Contributor>) : RecyclerView.Adapter<ContributorViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContributorViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.list_item_contributor, parent, false)
return ContributorViewHolder(v)
}
override fun onBindViewHolder(ui: ContributorViewHolder, position: Int) {
ui.bind(contributors[position])
}
override fun getItemCount(): Int = contributors.size
private class ContributorViewHolder(v: View) : RecyclerView.ViewHolder(v) {
val name: TextView = v.findViewById(R.id.name)
internal fun bind(contributor: Contributor) {
name.text = contributor.name
}
}
}
| app/src/main/java/de/grobox/transportr/about/ContributorFragment.kt | 2309302447 |
package com.s16.utils
import android.app.Activity
import android.app.Service
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.Surface
import android.view.WindowManager
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
/*
* Context
*/
val Context.screenOrientation: Int
get() {
val manager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
val rotation = manager.defaultDisplay.rotation
val orientation = resources.configuration.orientation
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
return if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_270) {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
} else {
ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT
}
}
return if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) {
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
} else {
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
}
} else ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
}
val Context.isTablet: Boolean
get() {
val xlarge =
resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK == 4
val large =
resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK == Configuration.SCREENLAYOUT_SIZE_LARGE
return xlarge || large
}
val Context.isPortrait: Boolean
get() {
return screenOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ||
screenOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT
}
inline fun <reified T: Any> Context.intentFor(vararg params: Pair<String, Any?>): Intent
= Intent(this, T::class.java).also {
if (params.isNotEmpty()) {
it.putExtras(bundleOf(*params))
}
}
inline fun <reified T: Any> Fragment.intentFor(vararg params: Pair<String, Any?>): Intent
= Intent(this.activity, T::class.java).also {
if (params.isNotEmpty()) {
it.putExtras(bundleOf(*params))
}
}
inline fun <reified T: Activity> Context.startActivity(extras: Bundle? = null) {
val intent = Intent(this, T::class.java)
if (extras != null) {
intent.putExtras(extras)
}
startActivity(intent)
}
inline fun <reified T: Activity> Context.startActivity(vararg params: Pair<String, Any?>) {
val intent = Intent(this, T::class.java)
if (params.isNotEmpty()) {
intent.putExtras(bundleOf(*params))
}
startActivity(intent)
}
inline fun <reified T: Service> Context.startService(vararg params: Pair<String, Any?>) {
val intent = Intent(this, T::class.java)
if (params.isNotEmpty()) {
intent.putExtras(bundleOf(*params))
}
startService(intent)
}
inline fun <reified T : Service> Context.stopService(vararg params: Pair<String, Any?>) {
val intent = Intent(this, T::class.java)
if (params.isNotEmpty()) {
intent.putExtras(bundleOf(*params))
}
stopService(intent)
}
fun Context.share(text: String, subject: String = "", title: String? = null): Boolean {
return try {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
intent.putExtra(Intent.EXTRA_TEXT, text)
startActivity(Intent.createChooser(intent, title))
true
} catch (e: ActivityNotFoundException) {
e.printStackTrace()
false
}
}
fun Context.browse(url: String, newTask: Boolean = false): Boolean {
return try {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(url)
if (newTask) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
startActivity(intent)
true
} catch (e: ActivityNotFoundException) {
e.printStackTrace()
false
}
}
fun Context.getColorCompat(@ColorRes resId: Int): Int {
return ContextCompat.getColor(this, resId)
}
fun Context.getDrawableCompat(@DrawableRes resId: Int): Drawable? {
return ContextCompat.getDrawable(this, resId)
}
fun Context.dpToPixel(dp: Int): Int {
val metrics = resources.displayMetrics
val px = dp * (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
return px.toInt()
}
fun Context.dpToPixel(dp: Float): Float {
val metrics = resources.displayMetrics
return dp * (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
}
fun Context.pixelToDp(px: Int): Float {
val metrics = resources.displayMetrics
return px / (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
} | app/src/main/java/com/s16/utils/Extension.context.kt | 1874294173 |
package com.ctzen.config.gradle
object Config {
/**
* Versions
*/
object Vers {
const val gradle = "5.1"
const val spring = "5.1.4.RELEASE"
}
/**
* Dependencies
*/
object Deps {
const val libGroovy = "org.codehaus.groovy:groovy-all:2.5.5"
const val libGuava = "com.google.guava:guava:27.0.1-jre"
// spring dependencies
const val libSpringContext = "org.springframework:spring-context:${Vers.spring}"
// logging dependencies
const val libSlf4j = "org.slf4j:slf4j-api:1.7.25"
// test dependencies
const val libAssertj = "org.assertj:assertj-core:3.11.1"
const val libTestNg = "org.testng:testng:6.14.3"
const val libReportNg = "org.uncommons:reportng:1.1.4"
const val libGuice = "com.google.inject:guice:4.2.2" // reportng dependencies
const val libLogback = "ch.qos.logback:logback-classic:1.2.3"
const val libSpringTest = "org.springframework:spring-test:${Vers.spring}"
}
/*
dependencies {
// logging
runtime 'org.slf4j:jcl-over-slf4j:1.7.12' // bridge commons-logging to slf4j
runtime 'org.slf4j:log4j-over-slf4j:1.7.12' // bridge log4j to slf4j
// testing
testCompile 'org.slf4j:jcl-over-slf4j:1.7.12' // need this to compile groovy tests
}
configurations {
all*.exclude group: 'commons-logging' // exclude to use slf4j
all*.exclude group: 'log4j' // exclude to use slf4j
}
*/
val javaCompilerArgs = arrayOf(
"-Xlint:unchecked",
"-Xlint:deprecation"
)
}
| buildSrc/src/main/kotlin/com/ctzen/config/gradle/Config.kt | 1027625124 |
/*
* Copyright (c) 2020 Giorgio Antonioli
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("StaggeredDividerDecoration")
package com.fondesa.recyclerviewdivider
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
/**
* Creates a new [StaggeredDividerBuilder] using the given [Context].
*
* @return a new [StaggeredDividerBuilder].
* @see StaggeredDividerBuilder
*/
@JvmName("builder")
public fun Context.staggeredDividerBuilder(): StaggeredDividerBuilder = StaggeredDividerBuilder(context = this)
/**
* Attaches a default divider created with [StaggeredDividerBuilder] to the given [RecyclerView].
*
* @see StaggeredDividerBuilder
*/
@JvmName("attachTo")
public fun RecyclerView.addStaggeredDivider() {
context.staggeredDividerBuilder().build().addTo(this)
}
| recycler-view-divider/src/main/kotlin/com/fondesa/recyclerviewdivider/CreateStaggeredDivider.kt | 3563101246 |
/*
* Copyright 2022 Ren Binden
*
* 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.rpkit.blocklog.bukkit.block
import com.rpkit.core.location.RPKBlockLocation
import com.rpkit.core.service.Service
import org.bukkit.Material
import org.bukkit.inventory.ItemStack
import java.time.LocalDateTime
import java.util.concurrent.CompletableFuture
interface RPKBlockHistoryService : Service {
fun getBlockHistory(id: RPKBlockHistoryId): CompletableFuture<out RPKBlockHistory?>
fun addBlockHistory(blockHistory: RPKBlockHistory): CompletableFuture<Void>
fun updateBlockHistory(blockHistory: RPKBlockHistory): CompletableFuture<Void>
fun removeBlockHistory(blockHistory: RPKBlockHistory): CompletableFuture<Void>
fun getBlockChange(id: RPKBlockChangeId): CompletableFuture<out RPKBlockChange?>
fun addBlockChange(blockChange: RPKBlockChange): CompletableFuture<Void>
fun updateBlockChange(blockChange: RPKBlockChange): CompletableFuture<Void>
fun removeBlockChange(blockChange: RPKBlockChange): CompletableFuture<Void>
fun getBlockInventoryChange(id: RPKBlockInventoryChangeId): CompletableFuture<out RPKBlockInventoryChange?>
fun addBlockInventoryChange(blockInventoryChange: RPKBlockInventoryChange): CompletableFuture<Void>
fun updateBlockInventoryChange(blockInventoryChange: RPKBlockInventoryChange): CompletableFuture<Void>
fun removeBlockInventoryChange(blockInventoryChange: RPKBlockInventoryChange): CompletableFuture<Void>
fun getBlockHistory(block: RPKBlockLocation): CompletableFuture<RPKBlockHistory>
fun getBlockTypeAtTime(block: RPKBlockLocation, time: LocalDateTime): CompletableFuture<Material>
fun getBlockInventoryAtTime(block: RPKBlockLocation, time: LocalDateTime): CompletableFuture<Array<ItemStack>>
} | bukkit/rpk-block-log-lib-bukkit/src/main/kotlin/com/rpkit/blocklog/bukkit/block/RPKBlockHistoryService.kt | 1447395536 |
package com.cesarferreira.pluralize
import com.cesarferreira.pluralize.utils.Plurality
import java.util.regex.Pattern
fun String.pluralize(plurality: Plurality = Plurality.Singular): String {
if (plurality == Plurality.Plural) return this
if (plurality == Plurality.Singular)
return this.pluralizer()
if (this.singularizer() != this && this.singularizer() + "s" != this &&
this.singularizer().pluralizer() == this && this.pluralizer() != this)
return this
return this.pluralizer()
}
fun String.singularize(plurality: Plurality = Plurality.Plural): String {
if (plurality == Plurality.Singular) return this
if (plurality == Plurality.Plural) return this.singularizer()
if (this.pluralizer() != this && this + "s" != this.pluralizer() &&
this.pluralizer().singularize() == this && this.singularizer() != this)
return this
return this.singularize()
}
fun String.pluralize(count: Int): String {
if (count > 1)
return this.pluralize(Plurality.Plural)
else
return this.pluralize(Plurality.Singular)
}
fun String.singularize(count: Int): String {
if (count > 1)
return this.singularize(Plurality.Plural)
else
return this.singularize(Plurality.Singular)
}
private fun String.pluralizer(): String {
if (unCountable().contains(this.toLowerCase())) return this
val rule = pluralizeRules().last { Pattern.compile(it.component1(), Pattern.CASE_INSENSITIVE).matcher(this).find() }
var found = Pattern.compile(rule.component1(), Pattern.CASE_INSENSITIVE).matcher(this).replaceAll(rule.component2())
val endsWith = exceptions().firstOrNull { this.endsWith(it.component1()) }
if (endsWith != null) found = this.replace(endsWith.component1(), endsWith.component2())
val exception = exceptions().firstOrNull() { this.equals(it.component1(), true) }
if (exception != null) found = exception.component2()
return found
}
private fun String.singularizer(): String {
if (unCountable().contains(this.toLowerCase())) {
return this
}
val exceptions = exceptions().firstOrNull() { this.equals(it.component2(), true) }
if (exceptions != null) {
return exceptions.component1()
}
val endsWith = exceptions().firstOrNull { this.endsWith(it.component2()) }
if (endsWith != null) return this.replace(endsWith.component2(), endsWith.component1())
try {
if (singularizeRules().count {
Pattern.compile(it.component1(), Pattern.CASE_INSENSITIVE).matcher(this).find()
} == 0) return this
val rule = singularizeRules().last {
Pattern.compile(it.component1(), Pattern.CASE_INSENSITIVE).matcher(this).find()
}
return Pattern.compile(rule.component1(), Pattern.CASE_INSENSITIVE).matcher(this).replaceAll(rule.component2())
} catch(ex: IllegalArgumentException) {
Exception("Can't singularize this word, could not find a rule to match.")
}
return this
}
fun unCountable(): List<String> {
return listOf("equipment", "information", "rice", "money",
"species", "series", "fish", "sheep", "aircraft", "bison",
"flounder", "pliers", "bream",
"gallows", "proceedings", "breeches", "graffiti", "rabies",
"britches", "headquarters", "salmon", "carp", "herpes",
"scissors", "chassis", "high-jinks", "sea-bass", "clippers",
"homework", "cod", "innings", "shears",
"contretemps", "jackanapes", "corps", "mackerel",
"swine", "debris", "measles", "trout", "diabetes", "mews",
"tuna", "djinn", "mumps", "whiting", "eland", "news",
"wildebeest", "elk", "pincers", "sugar")
}
fun exceptions(): List<Pair<String, String>> {
return listOf("person" to "people",
"man" to "men",
"goose" to "geese",
"child" to "children",
"sex" to "sexes",
"move" to "moves",
"stadium" to "stadiums",
"deer" to "deer",
"codex" to "codices",
"murex" to "murices",
"silex" to "silices",
"radix" to "radices",
"helix" to "helices",
"alumna" to "alumnae",
"alga" to "algae",
"vertebra" to "vertebrae",
"persona" to "personae",
"stamen" to "stamina",
"foramen" to "foramina",
"lumen" to "lumina",
"afreet" to "afreeti",
"afrit" to "afriti",
"efreet" to "efreeti",
"cherub" to "cherubim",
"goy" to "goyim",
"human" to "humans",
"lumen" to "lumina",
"seraph" to "seraphim",
"Alabaman" to "Alabamans",
"Bahaman" to "Bahamans",
"Burman" to "Burmans",
"German" to "Germans",
"Hiroshiman" to "Hiroshimans",
"Liman" to "Limans",
"Nakayaman" to "Nakayamans",
"Oklahoman" to "Oklahomans",
"Panaman" to "Panamans",
"Selman" to "Selmans",
"Sonaman" to "Sonamans",
"Tacoman" to "Tacomans",
"Yakiman" to "Yakimans",
"Yokohaman" to "Yokohamans",
"Yuman" to "Yumans", "criterion" to "criteria",
"perihelion" to "perihelia",
"aphelion" to "aphelia",
"phenomenon" to "phenomena",
"prolegomenon" to "prolegomena",
"noumenon" to "noumena",
"organon" to "organa",
"asyndeton" to "asyndeta",
"hyperbaton" to "hyperbata",
"foot" to "feet")
}
fun pluralizeRules(): List<Pair<String, String>> {
return listOf(
"$" to "s",
"s$" to "s",
"(ax|test)is$" to "$1es",
"us$" to "i",
"(octop|vir)us$" to "$1i",
"(octop|vir)i$" to "$1i",
"(alias|status)$" to "$1es",
"(bu)s$" to "$1ses",
"(buffal|tomat)o$" to "$1oes",
"([ti])um$" to "$1a",
"([ti])a$" to "$1a",
"sis$" to "ses",
"(,:([^f])fe|([lr])f)$" to "$1$2ves",
"(hive)$" to "$1s",
"([^aeiouy]|qu)y$" to "$1ies",
"(x|ch|ss|sh)$" to "$1es",
"(matr|vert|ind)ix|ex$" to "$1ices",
"([m|l])ouse$" to "$1ice",
"([m|l])ice$" to "$1ice",
"^(ox)$" to "$1en",
"(quiz)$" to "$1zes",
"f$" to "ves",
"fe$" to "ves",
"um$" to "a",
"on$" to "a",
"tion" to "tions",
"sion" to "sions")
}
fun singularizeRules(): List<Pair<String, String>> {
return listOf(
"s$" to "",
"(s|si|u)s$" to "$1s",
"(n)ews$" to "$1ews",
"([ti])a$" to "$1um",
"((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$" to "$1$2sis",
"(^analy)ses$" to "$1sis",
"(^analy)sis$" to "$1sis",
"([^f])ves$" to "$1fe",
"(hive)s$" to "$1",
"(tive)s$" to "$1",
"([lr])ves$" to "$1f",
"([^aeiouy]|qu)ies$" to "$1y",
"(s)eries$" to "$1eries",
"(m)ovies$" to "$1ovie",
"(x|ch|ss|sh)es$" to "$1",
"([m|l])ice$" to "$1ouse",
"(bus)es$" to "$1",
"(o)es$" to "$1",
"(shoe)s$" to "$1",
"(cris|ax|test)is$" to "$1is",
"(cris|ax|test)es$" to "$1is",
"(octop|vir)i$" to "$1us",
"(octop|vir)us$" to "$1us",
"(alias|status)es$" to "$1",
"(alias|status)$" to "$1",
"^(ox)en" to "$1",
"(vert|ind)ices$" to "$1ex",
"(matr)ices$" to "$1ix",
"(quiz)zes$" to "$1",
"a$" to "um",
"i$" to "us",
"ae$" to "a")
}
| library/src/main/kotlin/com/cesarferreira/pluralize/Pluralize.kt | 2381607084 |
package tw.shounenwind.kmnbottool
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
@Throws(Exception::class)
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("tw.shounenwind.kmnbottool", appContext.packageName)
}
}
| app/src/androidTest/java/tw/shounenwind/kmnbottool/ExampleInstrumentedTest.kt | 3643988774 |
package app.cash.inject.inflation.processor.internal
import com.squareup.javapoet.AnnotationSpec
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.CodeBlock
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeName
import javax.lang.model.element.AnnotationMirror
import javax.lang.model.element.TypeElement
import javax.lang.model.type.TypeMirror
import kotlin.reflect.KClass
fun TypeElement.toClassName(): ClassName = ClassName.get(this)
fun TypeMirror.toTypeName(): TypeName = TypeName.get(this)
fun KClass<*>.toClassName(): ClassName = ClassName.get(java)
fun AnnotationMirror.toAnnotationSpec(): AnnotationSpec = AnnotationSpec.get(this)
fun Iterable<CodeBlock>.joinToCode(separator: String = ", ") = CodeBlock.join(this, separator)
/**
* Like [ClassName.peerClass] except instead of honoring the enclosing class names they are
* concatenated with `$` similar to the reflection name. `foo.Bar.Baz` invoking this function with
* `Fuzz` will produce `foo.Baz$Fuzz`.
*/
fun ClassName.peerClassWithReflectionNesting(name: String): ClassName {
var prefix = ""
var peek = this
while (true) {
peek = peek.enclosingClassName() ?: break
prefix = peek.simpleName() + "$" + prefix
}
return ClassName.get(packageName(), prefix + name)
}
// TODO https://github.com/square/javapoet/issues/671
fun TypeName.rawClassName(): ClassName = when (this) {
is ClassName -> this
is ParameterizedTypeName -> rawType
else -> throw IllegalStateException("Cannot extract raw class name from $this")
}
| inflation-inject-processor/src/main/java/app/cash/inject/inflation/processor/internal/javaPoet.kt | 3063595339 |
package com.bastien7.transport.analyzer
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class TransportAnalyzerApplication
fun main(args: Array<String>) {
SpringApplication.run(TransportAnalyzerApplication::class.java, *args)
}
| src/main/com/bastien7/transport/analyzer/Application.kt | 3316766057 |
@file:JvmName("RxToolbar")
@file:JvmMultifileClass
package com.jakewharton.rxbinding4.widget
import androidx.annotation.RequiresApi
import android.view.MenuItem
import android.widget.Toolbar
import android.widget.Toolbar.OnMenuItemClickListener
import androidx.annotation.CheckResult
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.android.MainThreadDisposable
import com.jakewharton.rxbinding4.internal.checkMainThread
/**
* Create an observable which emits the clicked item in `view`'s menu.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
@CheckResult
@RequiresApi(21)
fun Toolbar.itemClicks(): Observable<MenuItem> {
return ToolbarItemClickObservable(this)
}
@RequiresApi(21)
private class ToolbarItemClickObservable(
private val view: Toolbar
) : Observable<MenuItem>() {
override fun subscribeActual(observer: Observer<in MenuItem>) {
if (!checkMainThread(observer)) {
return
}
val listener = Listener(view, observer)
observer.onSubscribe(listener)
view.setOnMenuItemClickListener(listener)
}
private class Listener(
private val view: Toolbar,
private val observer: Observer<in MenuItem>
) : MainThreadDisposable(), OnMenuItemClickListener {
override fun onMenuItemClick(item: MenuItem): Boolean {
if (!isDisposed) {
observer.onNext(item)
return true
}
return false
}
override fun onDispose() {
view.setOnMenuItemClickListener(null)
}
}
}
| rxbinding/src/main/java/com/jakewharton/rxbinding4/widget/ToolbarItemClickObservable.kt | 1726872350 |
/*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.clouddriver.event
import com.fasterxml.jackson.annotation.JsonIgnore
/**
* Marks a [SpinnakerEvent] as being constructed of multiple [SpinnakerEvent]s.
*
* This interface is necessary to correctly hydrate [EventMetadata] on [SpinnakerEvent] before persisting.
*/
interface CompositeSpinnakerEvent : SpinnakerEvent {
/**
* Returns a list of the composed [SpinnakerEvent]s.
*/
@JsonIgnore
fun getComposedEvents(): List<SpinnakerEvent>
}
| clouddriver-event/src/main/kotlin/com/netflix/spinnaker/clouddriver/event/CompositeSpinnakerEvent.kt | 199658481 |
package me.proxer.app.profile.history
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.RecyclerView
import com.jakewharton.rxbinding3.view.clicks
import com.jakewharton.rxbinding3.view.longClicks
import com.uber.autodispose.autoDisposable
import io.reactivex.subjects.PublishSubject
import kotterknife.bindView
import me.proxer.app.GlideRequests
import me.proxer.app.R
import me.proxer.app.base.AutoDisposeViewHolder
import me.proxer.app.base.BaseAdapter
import me.proxer.app.profile.history.HistoryAdapter.ViewHolder
import me.proxer.app.util.extension.defaultLoad
import me.proxer.app.util.extension.distanceInWordsToNow
import me.proxer.app.util.extension.mapBindingAdapterPosition
import me.proxer.app.util.extension.toAppString
import me.proxer.library.enums.Category
import me.proxer.library.util.ProxerUrls
/**
* @author Ruben Gees
*/
class HistoryAdapter : BaseAdapter<LocalUserHistoryEntry, ViewHolder>() {
var glide: GlideRequests? = null
val clickSubject: PublishSubject<Pair<ImageView, LocalUserHistoryEntry>> = PublishSubject.create()
val longClickSubject: PublishSubject<Pair<ImageView, LocalUserHistoryEntry>> = PublishSubject.create()
init {
setHasStableIds(false)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_history_entry, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(data[position])
override fun onViewRecycled(holder: ViewHolder) {
glide?.clear(holder.image)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
glide = null
}
inner class ViewHolder(itemView: View) : AutoDisposeViewHolder(itemView) {
internal val container: ViewGroup by bindView(R.id.container)
internal val title: TextView by bindView(R.id.title)
internal val medium: TextView by bindView(R.id.medium)
internal val image: ImageView by bindView(R.id.image)
internal val status: TextView by bindView(R.id.status)
fun bind(item: LocalUserHistoryEntry) {
container.clicks()
.mapBindingAdapterPosition({ bindingAdapterPosition }) { image to data[it] }
.autoDisposable(this)
.subscribe(clickSubject)
container.longClicks()
.mapBindingAdapterPosition({ bindingAdapterPosition }) { image to data[it] }
.autoDisposable(this)
.subscribe(longClickSubject)
ViewCompat.setTransitionName(image, "history_${item.id}")
title.text = item.name
medium.text = item.medium.toAppString(medium.context)
status.text = when (item is LocalUserHistoryEntry.Ucp) {
true -> status.context.getString(
when (item.category) {
Category.ANIME -> R.string.fragment_history_entry_ucp_status_anime
Category.MANGA, Category.NOVEL -> R.string.fragment_history_entry_ucp_status_manga
},
item.episode,
item.date.distanceInWordsToNow(status.context)
)
false -> status.context.getString(
when (item.category) {
Category.ANIME -> R.string.fragment_history_entry_status_anime
Category.MANGA, Category.NOVEL -> R.string.fragment_history_entry_status_manga
},
item.episode
)
}
glide?.defaultLoad(image, ProxerUrls.entryImage(item.entryId))
}
}
}
| src/main/kotlin/me/proxer/app/profile/history/HistoryAdapter.kt | 808117547 |
package me.proxer.app.settings
import android.content.SharedPreferences
import android.content.SharedPreferences.OnSharedPreferenceChangeListener
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Environment
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import me.proxer.app.BuildConfig
import me.proxer.app.MainActivity
import me.proxer.app.R
import me.proxer.app.base.BaseActivity
import me.proxer.app.chat.prv.sync.MessengerWorker
import me.proxer.app.notification.NotificationWorker
import me.proxer.app.profile.settings.ProfileSettingsActivity
import me.proxer.app.settings.theme.ThemeDialog
import me.proxer.app.util.KotterKnifePreference
import me.proxer.app.util.bindPreference
import me.proxer.app.util.data.PreferenceHelper
import me.proxer.app.util.data.PreferenceHelper.Companion.AGE_CONFIRMATION
import me.proxer.app.util.data.PreferenceHelper.Companion.EXTERNAL_CACHE
import me.proxer.app.util.data.PreferenceHelper.Companion.HTTP_LOG_LEVEL
import me.proxer.app.util.data.PreferenceHelper.Companion.HTTP_REDACT_TOKEN
import me.proxer.app.util.data.PreferenceHelper.Companion.HTTP_VERBOSE
import me.proxer.app.util.data.PreferenceHelper.Companion.NOTIFICATIONS_ACCOUNT
import me.proxer.app.util.data.PreferenceHelper.Companion.NOTIFICATIONS_CHAT
import me.proxer.app.util.data.PreferenceHelper.Companion.NOTIFICATIONS_INTERVAL
import me.proxer.app.util.data.PreferenceHelper.Companion.NOTIFICATIONS_NEWS
import me.proxer.app.util.data.PreferenceHelper.Companion.THEME
import me.proxer.app.util.data.StorageHelper
import me.proxer.app.util.extension.clearTop
import me.proxer.app.util.extension.clicks
import me.proxer.app.util.extension.safeInject
import me.proxer.app.util.extension.snackbar
import net.xpece.android.support.preference.ListPreference
import net.xpece.android.support.preference.Preference
import net.xpece.android.support.preference.PreferenceCategory
import net.xpece.android.support.preference.TwoStatePreference
import net.xpece.android.support.preference.XpPreferenceFragment
import kotlin.system.exitProcess
/**
* @author Ruben Gees
*/
class SettingsFragment : XpPreferenceFragment(), OnSharedPreferenceChangeListener {
companion object {
fun newInstance() = SettingsFragment().apply {
arguments = bundleOf()
}
}
private val hostingActivity: BaseActivity
get() = activity as MainActivity
private val packageManager by safeInject<PackageManager>()
private val preferenceHelper by safeInject<PreferenceHelper>()
private val storageHelper by safeInject<StorageHelper>()
private val profile by bindPreference<Preference>("profile")
private val ageConfirmation by bindPreference<TwoStatePreference>(AGE_CONFIRMATION)
private val theme by bindPreference<Preference>(THEME)
private val externalCache by bindPreference<TwoStatePreference>(EXTERNAL_CACHE)
private val notificationsInterval by bindPreference<ListPreference>(NOTIFICATIONS_INTERVAL)
private val developerOptions by bindPreference<PreferenceCategory>("developer_options")
override fun onCreatePreferences2(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.preferences)
if (
Environment.isExternalStorageEmulated() ||
Environment.getExternalStorageState() != Environment.MEDIA_MOUNTED
) {
externalCache.isVisible = false
}
if (!BuildConfig.DEBUG && !BuildConfig.LOG) {
developerOptions.isVisible = false
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
storageHelper.isLoggedInObservable
.autoDisposable(viewLifecycleOwner.scope())
.subscribe { profile.isEnabled = it }
profile.clicks()
.autoDisposable(viewLifecycleOwner.scope())
.subscribe { ProfileSettingsActivity.navigateTo(requireActivity()) }
ageConfirmation.clicks()
.autoDisposable(viewLifecycleOwner.scope())
.subscribe {
if (ageConfirmation.isChecked) {
ageConfirmation.isChecked = false
AgeConfirmationDialog.show(requireActivity() as AppCompatActivity)
}
}
theme.clicks()
.autoDisposable(viewLifecycleOwner.scope())
.subscribe {
ThemeDialog.show(requireActivity() as AppCompatActivity)
}
profile.isEnabled = storageHelper.isLoggedIn
theme.summary = preferenceHelper.themeContainer.let { (theme, variant) ->
"${getString(theme.themeName)} ${if (variant.variantName != null) getString(variant.variantName) else ""}"
}
updateIntervalNotificationPreference()
listView.isFocusable = false
}
override fun onResume() {
super.onResume()
preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
override fun onPause() {
preferenceManager.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
super.onPause()
}
override fun onDestroyView() {
KotterKnifePreference.reset(this)
super.onDestroyView()
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
when (key) {
AGE_CONFIRMATION -> if (preferenceHelper.isAgeRestrictedMediaAllowed) {
ageConfirmation.isChecked = true
}
NOTIFICATIONS_NEWS, NOTIFICATIONS_ACCOUNT -> {
updateIntervalNotificationPreference()
NotificationWorker.enqueueIfPossible()
}
NOTIFICATIONS_CHAT -> MessengerWorker.enqueueSynchronizationIfPossible()
NOTIFICATIONS_INTERVAL -> {
NotificationWorker.enqueueIfPossible()
MessengerWorker.enqueueSynchronizationIfPossible()
}
EXTERNAL_CACHE, HTTP_LOG_LEVEL, HTTP_VERBOSE, HTTP_REDACT_TOKEN -> showRestartMessage()
}
}
private fun updateIntervalNotificationPreference() {
notificationsInterval.isEnabled = preferenceHelper.areNewsNotificationsEnabled ||
preferenceHelper.areAccountNotificationsEnabled
}
private fun showRestartMessage() {
hostingActivity.snackbar(
R.string.fragment_settings_restart_message,
actionMessage = R.string.fragment_settings_restart_action,
actionCallback = View.OnClickListener {
val intent = packageManager.getLaunchIntentForPackage(BuildConfig.APPLICATION_ID)?.clearTop()
startActivity(intent)
exitProcess(0)
}
)
}
}
| src/main/kotlin/me/proxer/app/settings/SettingsFragment.kt | 472725946 |
package net.perfectdreams.loritta.cinnamon.discord.utils
object DiscordResourceLimits {
object Command {
object Description {
const val Length = 100
}
object Options {
object Description {
const val Length = 100
}
}
}
object Message {
const val Length = 2000
const val EmbedsPerMessage = 10
}
object Embed {
const val Title = 256
const val Description = 4096
const val FieldsPerEmbed = 25
const val TotalCharacters = 6000
object Field {
const val Name = 256
const val Value = 1024
}
object Footer {
const val Text = 2048
}
object Author {
const val Name = 256
}
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/utils/DiscordResourceLimits.kt | 211369484 |
/*
MyFlightbook for Android - provides native access to MyFlightbook
pilot's logbook
Copyright (C) 2017-2022 MyFlightbook, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.myflightbook.android
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import model.MFBConstants
import android.widget.VideoView
import android.net.Uri
import android.util.Log
import java.io.File
class ActLocalVideo : AppCompatActivity() {
private var szTempFile: String? = ""
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.localvideo)
val szURL = this.intent.getStringExtra(MFBConstants.intentViewURL)
szTempFile = this.intent.getStringExtra(MFBConstants.intentViewTempFile)
val video = findViewById<VideoView>(R.id.video)
// Load and start the movie
video.setVideoURI(Uri.parse(szURL))
video.start()
}
public override fun onPause() {
super.onPause()
if (szTempFile != null && szTempFile!!.isNotEmpty()) {
if (!File(szTempFile!!).delete()) Log.v(MFBConstants.LOG_TAG, "Local video delete failed")
}
}
} | app/src/main/java/com/myflightbook/android/ActLocalVideo.kt | 912347402 |
package org.portalmirror.twitterfeed.core.domain
import org.joda.time.DateTime
import org.portalmirror.twitterfeed.core.logic.TwitterRepository
import twitter4j.Status
class TwitterFeedEntry {
val screenName : String
val status : Status
var replies : List<TwitterFeedEntry>
private val repository: TwitterRepository
val depth : Int
val createdAt : DateTime
private val repliesMaxDepth: Int
/***
* Constructor to create root entries
*/
constructor(screenName : String, status : Status, repository: TwitterRepository, repliesMaxDepth: Int) {
this.screenName = screenName
this.status = status
this.repository = repository
this.depth = 0
this.repliesMaxDepth = repliesMaxDepth
if(this.repliesMaxDepth > 0 ) {
this.replies = getReplies(repository, status)
} else {
this.replies = emptyList()
}
this.createdAt = DateTime.now()
}
constructor(status : Status, repository: TwitterRepository, parent : TwitterFeedEntry) {
this.screenName = status.user.screenName
this.status = status
this.repository = repository
this.depth = parent.depth + 1
this.repliesMaxDepth = parent.repliesMaxDepth
if(this.repliesMaxDepth > this.depth) {
this.replies = getReplies(repository, status)
} else {
this.replies = emptyList()
}
this.createdAt = DateTime.now()
}
private fun getReplies(repository: TwitterRepository, status: Status) = repository.getAllRepliesToStatus(this.status).map { s -> TwitterFeedEntry(s, repository, this) }
fun isEagerLoaded() : Boolean {
return this.depth <= this.repliesMaxDepth
}
fun refreshReplies() : Unit {
this.replies = getReplies(this.repository, this.status)
}
fun isReplyTo() : Boolean {
return status.inReplyToStatusId > 0
}
fun isRetweeted() : Boolean {
return status.retweetedStatus != null
}
fun hasQuotedStatus() : Boolean {
return status.quotedStatus != null
}
fun hasVideo() : Boolean {
return hasMediaEntityOfType("video")
}
fun hasGif() : Boolean {
return hasMediaEntityOfType("animated_gif")
}
fun hasPhoto() : Boolean {
return hasMediaEntityOfType("photo")
}
private fun hasMediaEntityOfType(type : String) = status.mediaEntities.find { me -> me.type.equals(type) } != null
}
| portalmirror-twitterfeed-core/src/main/kotlin/org/portalmirror/twitterfeed/core/domain/TwitterFeedEntry.kt | 400912986 |
package com.rectanglel.patstatic.routes
import com.google.gson.annotations.Expose
/**
* TrueTime representation of bus routes
*
*
* Created by epicstar on 3/4/17.
* @author Jeremy Jao
*/
data class BusRoute (
@Expose
val routeNumber: String? = null,
@Expose
val routeName: String? = null,
@Expose
val routeColor: String? = null,
@Expose
val routeDd: String? = null
)
| pat-static/src/main/java/com/rectanglel/patstatic/routes/BusRoute.kt | 39917309 |
package ee.lang
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test
class ItemApiTest {
@Test
fun deriveTest_equals() {
val item = Item { name("ItemTest").namespace("ee.lang.test") }
val derived: Item = item.derive()
assertThat(derived.name(), equalTo("ItemTest"))
assertThat(derived.namespace(), equalTo("ee.lang.test"))
}
@Test
fun deriveTest_different() {
val item = Item { name("ItemTest").namespace("ee.lang.test") }
val derived: Item = item.derive { name("${item.name()}Derived").namespace("${item.namespace()}Derived") }
assertThat(derived.name(), equalTo("ItemTestDerived"))
assertThat(derived.namespace(), equalTo("ee.lang.testDerived"))
}
} | ee-lang_item/src/test/kotlin/ee/lang/ItemApiTest.kt | 2529278705 |
/*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić 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
*
* 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.vanniktech.emoji.traits
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import com.vanniktech.emoji.EmojiPopup
import com.vanniktech.emoji.internal.EmojiSearchPopup
import com.vanniktech.emoji.search.NoSearchEmoji
/**
* Popup similar to how Telegram and Slack does it to search for an Emoji
*/
class SearchInPlaceTrait(
private val emojiPopup: EmojiPopup,
) : EmojiTraitable {
override fun install(editText: EditText): EmojiTrait {
if (emojiPopup.searchEmoji is NoSearchEmoji) {
return EmptyEmojiTrait
}
val popup = EmojiSearchPopup(emojiPopup.rootView, editText, emojiPopup.theming)
val handler = Handler(Looper.getMainLooper())
val watcher = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
override fun afterTextChanged(s: Editable) {
handler.removeCallbacksAndMessages(null)
// Cheap debounce without RxJava.
handler.postDelayed({
val lastColon = s.indexOfLast { it == ':' }
if (lastColon >= 0) {
val query = s.drop(lastColon + 1).toString()
val isProperQuery = query.all { it.isLetterOrDigit() || it == '_' }
if (isProperQuery) {
popup.show(
emojis = emojiPopup.searchEmoji.search(query),
delegate = {
val new = "${it.unicode} "
editText.text.replace(lastColon, s.length, new, 0, new.length)
},
)
} else {
popup.dismiss()
}
} else {
popup.dismiss()
}
}, 300L,)
}
}
editText.addTextChangedListener(watcher)
return object : EmojiTrait {
override fun uninstall() {
popup.dismiss()
editText.removeTextChangedListener(watcher)
}
}
}
}
| emoji/src/androidMain/kotlin/com/vanniktech/emoji/traits/SearchInPlaceTrait.kt | 3349042635 |
package net.yested.ext.jquery
import globals.JQuery
import globals.JQueryStatic
import globals.jQuery
import org.w3c.dom.HTMLElement
import org.w3c.dom.Window
/**
* JQuery functions that are are available via Yested to applications.
* If you need additional functions, create similar code with a different Kotlin name.
* Your new code can extend YestedJQuery, which will enable chaining into these functions.
*/
@Deprecated("use globals.jQuery", replaceWith = ReplaceWith("jQuery", "globals.jQuery"))
val yestedJQuery: JQuery = jQuery.unsafeCast<JQuery>()
@Deprecated("use jQuery(element)", replaceWith = ReplaceWith("jQuery(element)", "globals.jQuery"))
fun yestedJQuery(element: HTMLElement): JQuery = jQuery(element)
@Deprecated("use jQuery(window)", replaceWith = ReplaceWith("jQuery(window)", "globals.jQuery"))
fun yestedJQuery(window: Window): JQuery = jQuery(window)
@Deprecated("use JQuery")
typealias YestedJQuery = JQuery
fun JQuery.datetimepicker(param: Any?) {
this.asDynamic().datetimepicker(param)
}
fun JQuery.modal(command: String) {
this.asDynamic().modal(command)
}
fun <T> JQueryStatic.get(url:String, loaded:(response: T) -> Unit) {
this.asDynamic().get(url, loaded)
}
fun <RESULT> JQueryStatic.ajax(request: AjaxRequest<RESULT>) {
this.asDynamic().ajax(request)
}
@Deprecated("use JQuery", replaceWith = ReplaceWith("JQuery", "globals.JQuery"))
typealias JQueryWindow = JQuery
| src/jsMain/kotlin/net/yested/ext/jquery/YestedJQuery.kt | 668487440 |
/**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.5.1-pre.0
* Contact: [email protected]
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.models
import org.openapitools.server.models.Link
/**
*
* @param repositories
* @param self
* @param propertyClass
*/
data class GithubOrganizationlinks(
val repositories: Link? = null,
val self: Link? = null,
val propertyClass: kotlin.String? = null
)
| clients/kotlin-server/generated/src/main/kotlin/org/openapitools/server/models/GithubOrganizationlinks.kt | 3229670381 |
/*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.etm.pages
import android.content.Intent
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 com.nextcloud.client.etm.EtmBaseFragment
import com.owncloud.android.R
import kotlinx.android.synthetic.main.fragment_etm_accounts.*
import kotlinx.android.synthetic.main.fragment_etm_preferences.*
class EtmAccountsFragment : EtmBaseFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_etm_accounts, container, false)
}
override fun onResume() {
super.onResume()
val builder = StringBuilder()
vm.accounts.forEach {
builder.append("Account: ${it.account.name}\n")
it.userData.forEach {
builder.append("\t${it.key}: ${it.value}\n")
}
}
etm_accounts_text.text = builder.toString()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.fragment_etm_accounts, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.etm_accounts_share -> {
onClickedShare(); true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun onClickedShare() {
val intent = Intent(Intent.ACTION_SEND)
intent.putExtra(Intent.EXTRA_SUBJECT, "Nextcloud accounts information")
intent.putExtra(Intent.EXTRA_TEXT, etm_accounts_text.text)
intent.type = "text/plain"
startActivity(intent)
}
}
| src/main/java/com/nextcloud/client/etm/pages/EtmAccountsFragment.kt | 3261113084 |
package com.sksamuel.kotest.property.arbitrary
import io.kotest.assertions.throwables.shouldNotThrow
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FunSpec
import io.kotest.data.forAll
import io.kotest.matchers.doubles.plusOrMinus
import io.kotest.matchers.shouldBe
import io.kotest.property.arbitrary.Arb
import io.kotest.property.arbitrary.choose
import io.kotest.data.row
import io.kotest.property.arbitrary.single
import io.kotest.property.random
class ChooseTest : FunSpec({
test("weighted should honour seed") {
val seedListA = Arb.choose(1 to 'A', 3 to 'B', 4 to 'C', 5 to 'D').samples(684658365846L.random()).take(500).toList().map { it.value }
val seedListB = Arb.choose(1 to 'A', 3 to 'B', 4 to 'C', 5 to 'D').samples(684658365846L.random()).take(500).toList().map { it.value }
seedListA shouldBe seedListB
}
test("weighted should generate expected values in correct ratios according to weights") {
forAll(
row(listOf(1 to 'A', 1 to 'B'), mapOf('A' to 0.5, 'B' to 0.5)),
row(listOf(1 to 'A', 3 to 'B', 1 to 'C'), mapOf('A' to 0.2, 'B' to 0.6, 'C' to 0.2)),
row(listOf(1 to 'A', 3 to 'C', 1 to 'C'), mapOf('A' to 0.2, 'C' to 0.8)),
row(listOf(1 to 'A', 3 to 'B', 1 to 'C', 4 to 'D'), mapOf('A' to 0.11, 'B' to 0.33, 'C' to 0.11, 'D' to 0.44))
) { weightPairs, expectedRatiosMap ->
val genCount = 100000
val chooseGen = Arb.choose(weightPairs[0], weightPairs[1], *weightPairs.drop(2).toTypedArray())
val actualCountsMap = (1..genCount).map { chooseGen.single() }.groupBy { it }.map { (k, v) -> k to v.count() }
val actualRatiosMap = actualCountsMap.map { (k, v) -> k to (v.toDouble() / genCount) }.toMap()
actualRatiosMap.keys shouldBe expectedRatiosMap.keys
actualRatiosMap.forEach { (k, actualRatio) ->
actualRatio shouldBe (expectedRatiosMap[k] as Double plusOrMinus 0.02)
}
}
}
test("weighted should not accept negative weights") {
shouldThrow<IllegalArgumentException> { Arb.choose(-1 to 'A', 1 to 'B') }
}
test("weighted should not accept all zero weights") {
shouldThrow<IllegalArgumentException> { Arb.choose(0 to 'A', 0 to 'B') }
}
test("weighted should accept weights if at least one is non-zero") {
shouldNotThrow<Exception> { Arb.choose(0 to 'A', 0 to 'B', 1 to 'C') }
}
})
| kotest-property/src/jvmTest/kotlin/com/sksamuel/kotest/property/arbitrary/ChooseTest.kt | 1721056489 |
package org.DUCodeWars.framework.server.net.packets.notifications.broadcast
import org.DUCodeWars.framework.server.net.PlayerConnection
import org.DUCodeWars.framework.server.net.server.Server
import org.DUCodeWars.framework.server.net.packets.notifications.NotificationRequest
import org.DUCodeWars.framework.server.net.packets.notifications.NotificationResponse
class BroadcastNotificationDrop<I : NotificationRequest>(
server: Server,
connections: Collection<PlayerConnection>,
requestCreator: (PlayerConnection) -> I)
: BroadcastDrop<I, NotificationResponse>(
server,
connections,
requestCreator,
{ _, _, _ ->}
) {
constructor(server: Server, connections: Collection<PlayerConnection>,
request: I) : this(server, connections, { request })
} | src/main/java/org/DUCodeWars/framework/server/net/packets/notifications/broadcast/BroadcastNotificationDrop.kt | 3532127113 |
package org.tameter.partialorder.dag.kpouchdb
import org.tameter.kpouchdb.PouchDoc
/**
* Copyright (c) 2016-2017 Hugh Greene ([email protected]).
*/
external interface AxisDoc: PouchDoc {
// var edges: Array<E>
}
fun AxisDoc(_id: String): AxisDoc {
return PouchDoc<AxisDoc>(_id, "A").apply {
}
}
| partial-order-app/src/main/kotlin/org/tameter/partialorder/dag/kpouchdb/AxisDoc.kt | 893374607 |
package com.cout970.magneticraft.systems.tilemodules
import com.cout970.magneticraft.api.heat.IHeatNode
import com.cout970.magneticraft.misc.add
import com.cout970.magneticraft.misc.crafting.IHeatCraftingProcess
import com.cout970.magneticraft.misc.crafting.TimedCraftingProcess
import com.cout970.magneticraft.misc.gui.ValueAverage
import com.cout970.magneticraft.misc.network.FloatSyncVariable
import com.cout970.magneticraft.misc.network.SyncVariable
import com.cout970.magneticraft.misc.newNbt
import com.cout970.magneticraft.misc.world.isClient
import com.cout970.magneticraft.systems.gui.DATA_ID_BURNING_TIME
import com.cout970.magneticraft.systems.gui.DATA_ID_MACHINE_CONSUMPTION
import com.cout970.magneticraft.systems.tileentities.IModule
import com.cout970.magneticraft.systems.tileentities.IModuleContainer
import net.minecraft.nbt.NBTTagCompound
/**
* Created by cout970 on 2017/07/01.
*/
class ModuleHeatProcessing(
val craftingProcess: IHeatCraftingProcess,
val node: IHeatNode,
val workingRate: Float,
val costPerTick: Float,
override val name: String = "module_electric_processing"
) : IModule {
override lateinit var container: IModuleContainer
val timedProcess = TimedCraftingProcess(craftingProcess, this::onWorkingTick)
val consumption = ValueAverage()
var working = false
override fun update() {
if (world.isClient) return
val rate = (workingRate * getSpeed()).toDouble()
//making sure that (speed * costPerTick) is an integer
val speed = Math.floor((rate * costPerTick)).toFloat() / costPerTick
if (speed > 0) {
timedProcess.tick(world, speed)
}
val isWorking = timedProcess.isWorking(world)
if (isWorking != working) {
working = isWorking
container.sendUpdateToNearPlayers()
}
consumption.tick()
}
fun getSpeed(): Float {
val headDiff = node.temperature - craftingProcess.minTemperature()
return headDiff.toFloat().coerceIn(0.0f, 1.0f)
}
fun onWorkingTick(speed: Float) {
consumption += speed * costPerTick
node.applyHeat(-speed * costPerTick.toDouble())
}
override fun deserializeNBT(nbt: NBTTagCompound) {
timedProcess.deserializeNBT(nbt.getCompoundTag("timedProcess"))
working = nbt.getBoolean("working")
}
override fun serializeNBT(): NBTTagCompound = newNbt {
add("timedProcess", timedProcess.serializeNBT())
add("working", working)
}
override fun getGuiSyncVariables(): List<SyncVariable> = listOf(
FloatSyncVariable(DATA_ID_BURNING_TIME, { timedProcess.timer }, { timedProcess.timer = it }),
consumption.toSyncVariable(DATA_ID_MACHINE_CONSUMPTION)
)
} | src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/ModuleHeatProcessing.kt | 4065038353 |
package com.cout970.magneticraft.features.items
import com.cout970.magneticraft.api.energy.IElectricNode
import com.cout970.magneticraft.api.energy.IManualConnectionHandler.Result.*
import com.cout970.magneticraft.api.heat.IHeatNode
import com.cout970.magneticraft.misc.*
import com.cout970.magneticraft.misc.gui.formatHeat
import com.cout970.magneticraft.misc.inventory.isNotEmpty
import com.cout970.magneticraft.misc.player.sendMessage
import com.cout970.magneticraft.misc.player.sendUnlocalizedMessage
import com.cout970.magneticraft.misc.world.isClient
import com.cout970.magneticraft.misc.world.isServer
import com.cout970.magneticraft.registry.*
import com.cout970.magneticraft.systems.blocks.IRotable
import com.cout970.magneticraft.systems.items.*
import net.minecraft.block.properties.IProperty
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.util.*
import net.minecraft.util.math.BlockPos
import net.minecraft.util.text.TextFormatting
import net.minecraft.world.World
/**
* Created by cout970 on 2017/06/12.
*/
object ToolItems : IItemMaker {
lateinit var stoneHammer: ItemBase private set
lateinit var ironHammer: ItemBase private set
lateinit var steelHammer: ItemBase private set
lateinit var copperCoil: ItemBase private set
lateinit var voltmeter: ItemBase private set
lateinit var thermometer: ItemBase private set
lateinit var wrench: ItemBase private set
override fun initItems(): List<Item> {
val builder = ItemBuilder().apply {
creativeTab = CreativeTabMg
isFull3d = true
maxStackSize = 1
}
stoneHammer = builder.withName("stone_hammer").copy {
onHitEntity = createHitEntity(2.0f)
maxDamage = 130
}.build()
ironHammer = builder.withName("iron_hammer").copy {
onHitEntity = createHitEntity(3.5f)
maxDamage = 250
}.build()
steelHammer = builder.withName("steel_hammer").copy {
onHitEntity = createHitEntity(5.0f)
maxDamage = 750
}.build()
copperCoil = builder.withName("copper_coil").copy {
constructor = ToolItems::CopperCoil
isFull3d = false
maxStackSize = 16
}.build()
voltmeter = builder.withName("voltmeter").copy {
onItemUse = ToolItems::onUseVoltmeter
}.build()
thermometer = builder.withName("thermometer").copy {
onItemUse = ToolItems::onUseThermometer
}.build()
wrench = builder.withName("wrench").copy {
onItemUse = ToolItems::onUseWrench
}.build()
return listOf(stoneHammer, ironHammer, steelHammer, copperCoil, voltmeter, thermometer, wrench)
}
fun onUseVoltmeter(args: OnItemUseArgs): EnumActionResult {
if (args.worldIn.isServer) {
val tile = args.worldIn.getTileEntity(args.pos) ?: return EnumActionResult.PASS
val handler = tile.getOrNull(ELECTRIC_NODE_HANDLER, args.facing) ?: return EnumActionResult.PASS
val msg = handler.nodes
.filterIsInstance<IElectricNode>()
.joinToString("\n") {
"%.2fV %.2fA %.2fW".format(it.voltage, it.amperage, it.voltage * it.amperage)
}
args.player.sendUnlocalizedMessage(msg)
}
return EnumActionResult.PASS
}
fun onUseThermometer(args: OnItemUseArgs): EnumActionResult {
if (args.worldIn.isServer) {
val tile = args.worldIn.getTileEntity(args.pos) ?: return EnumActionResult.PASS
val handler = tile.getOrNull(HEAT_NODE_HANDLER, args.facing) ?: return EnumActionResult.PASS
val msg = handler.nodes
.filterIsInstance<IHeatNode>()
.joinToString("\n") {
formatHeat(it.temperature)
}
args.player.sendUnlocalizedMessage(msg)
}
return EnumActionResult.PASS
}
fun onUseWrench(args: OnItemUseArgs): EnumActionResult {
if (args.worldIn.isClient) return EnumActionResult.PASS
val state = args.worldIn.getBlockState(args.pos)
val entry = state.properties.entries.find { it.value is IRotable } ?: return EnumActionResult.PASS
@Suppress("UNCHECKED_CAST") val prop = entry.key as IProperty<IRotable<Any>>
val facing = state.getValue(prop)
val newState = state.withProperty(prop, facing.next())
if (state != newState) {
args.worldIn.setBlockState(args.pos, newState)
}
return EnumActionResult.PASS
}
private fun createHitEntity(damage: Float): (HitEntityArgs) -> Boolean {
return {
it.stack.damageItem(2, it.attacker)
it.target.attackEntityFrom(DamageSource.GENERIC, damage)
}
}
class CopperCoil : ItemBase() {
companion object {
const val POSITION_KEY = "Position"
}
override fun getItemStackDisplayName(stack: ItemStack): String {
val name = super.getItemStackDisplayName(stack)
if (stack.hasKey(POSITION_KEY)) {
val basePos = stack.getBlockPos(POSITION_KEY)
return name + " [${TextFormatting.AQUA}${basePos.x}, ${basePos.y}, ${basePos.z}${TextFormatting.WHITE}]"
}
return name
}
override fun onItemRightClick(worldIn: World, playerIn: EntityPlayer,
handIn: EnumHand): ActionResult<ItemStack> {
if (playerIn.isSneaking && playerIn.getHeldItem(handIn).isNotEmpty) {
val item = playerIn.getHeldItem(handIn)
item.checkNBT()
item.tagCompound?.removeTag(POSITION_KEY)
return ActionResult(EnumActionResult.SUCCESS, item)
}
return super.onItemRightClick(worldIn, playerIn, handIn)
}
override fun onItemUse(player: EntityPlayer, worldIn: World, pos: BlockPos, hand: EnumHand,
facing: EnumFacing, hitX: Float, hitY: Float, hitZ: Float): EnumActionResult {
val stack = player.getHeldItem(hand)
if (stack.isEmpty) return EnumActionResult.PASS
val block = worldIn.getBlockState(pos)
val handler = MANUAL_CONNECTION_HANDLER!!.fromBlock(block.block)
if (handler != null) {
if (player.isSneaking) {
val basePos = handler.getBasePos(pos, worldIn, player, facing, stack)
if (basePos != null) {
stack.setBlockPos(POSITION_KEY, basePos)
player.sendMessage("text.magneticraft.wire_connect.updated_position",
"[${TextFormatting.AQUA}" +
"${basePos.x}, ${basePos.y}, ${basePos.z}${TextFormatting.WHITE}]")
return EnumActionResult.SUCCESS
}
} else {
if (stack.hasKey(POSITION_KEY)) {
val basePos = stack.getBlockPos(POSITION_KEY)
val result = handler.connectWire(basePos, pos, worldIn, player, facing, stack)
if (worldIn.isServer) {
when (result) {
SUCCESS -> player.sendMessage("text.magneticraft.wire_connect.success")
TOO_FAR -> player.sendMessage("text.magneticraft.wire_connect.too_far")
NOT_A_CONNECTOR -> player.sendMessage("text.magneticraft.wire_connect.not_a_connector")
INVALID_CONNECTOR -> player.sendMessage("text.magneticraft.wire_connect.invalid_connector")
SAME_CONNECTOR -> player.sendMessage("text.magneticraft.wire_connect.same_connector")
ALREADY_CONNECTED -> player.sendMessage("text.magneticraft.wire_connect.already_connected")
ERROR, null -> player.sendMessage("text.magneticraft.wire_connect.fail")
}
}
return EnumActionResult.SUCCESS
} else {
if (worldIn.isServer) {
player.sendMessage("text.magneticraft.wire_connect.no_other_connector")
}
}
}
}
return EnumActionResult.PASS
}
}
} | src/main/kotlin/com/cout970/magneticraft/features/items/ToolItems.kt | 1553391420 |
package com.github.shynixn.petblocks.core.logic.persistence.entity
import com.github.shynixn.petblocks.api.business.annotation.YamlSerialize
import com.github.shynixn.petblocks.api.persistence.entity.AIFollowOwner
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
class AIFollowOwnerEntity : AIBaseEntity(), AIFollowOwner {
/**
* Name of the type.
*/
override var type: String = "follow-owner"
/**
* Distance to the owner which the pet tries to stay away.
*/
@YamlSerialize(value = "min-distance", orderNumber = 1)
override var distanceToOwner: Double = 3.0
/**
* The max range a pet can be away from a player until it teleports back.
*/
@YamlSerialize(value = "max-distance", orderNumber = 2)
override var maxRange: Double = 50.0
/**
* Speed of the pathfinder.
*/
@YamlSerialize(value = "speed", orderNumber = 3)
override var speed: Double = 3.0
} | petblocks-core/src/main/kotlin/com/github/shynixn/petblocks/core/logic/persistence/entity/AIFollowOwnerEntity.kt | 2271878593 |
package com.almasb.fxglgames.geojumper
import com.almasb.fxgl.app.GameApplication
import com.almasb.fxgl.app.GameSettings
import com.almasb.fxgl.core.math.FXGLMath
import com.almasb.fxgl.dsl.*
import com.almasb.fxgl.entity.Entity
import com.almasb.fxgl.entity.EntityFactory
import com.almasb.fxgl.entity.SpawnData
import com.almasb.fxgl.entity.Spawns
import com.almasb.fxgl.entity.component.Component
import com.almasb.fxgl.entity.components.CollidableComponent
import com.almasb.fxgl.input.UserAction
import com.almasb.fxgl.physics.BoundingShape
import com.almasb.fxgl.physics.CollisionHandler
import com.almasb.fxgl.physics.HitBox
import com.almasb.fxgl.physics.PhysicsComponent
import com.almasb.fxgl.physics.box2d.dynamics.BodyType
import javafx.geometry.Point2D
import javafx.scene.input.KeyCode
import javafx.scene.input.MouseButton
import javafx.scene.paint.Color
import javafx.scene.shape.Rectangle
import java.util.*
/**
*
*
* @author Almas Baimagambetov ([email protected])
*/
class GeoJumperApp : GameApplication() {
private val LEVEL_HEIGHT = 2600.0
private lateinit var playerComponent: PlayerComponent
override fun initSettings(settings: GameSettings) {
with(settings) {
width = 600
height = 800
title = "Geo Jumper"
version = "0.1"
}
}
override fun initInput() {
onBtnDown(MouseButton.PRIMARY, "Jump") {
playerComponent.jump()
}
getInput().addAction(object : UserAction("Rewind") {
override fun onAction() {
playerComponent.rewind()
}
override fun onActionEnd() {
playerComponent.endRewind()
}
}, KeyCode.R)
}
override fun initGame() {
getGameWorld().addEntityFactory(Factory())
//gameWorld.addEntity(Entities.makeScreenBounds(40.0))
// ground
entityBuilder()
.at(0.0, LEVEL_HEIGHT)
.bbox(HitBox(BoundingShape.box(getAppWidth()*1.0, 40.0)))
.with(PhysicsComponent())
.buildAndAttach()
initPlayer()
initPlatforms()
}
override fun initPhysics() {
getPhysicsWorld().setGravity(0.0, 1200.0)
getPhysicsWorld().addCollisionHandler(object : CollisionHandler(EntityType.PLAYER, EntityType.PLATFORM) {
override fun onCollisionBegin(player: Entity, platform: Entity) {
// only if player actually lands on the platform
if (player.bottomY <= platform.y) {
platform.getComponent(PlatformComponent::class.java).stop()
playerComponent.startNewCapture()
}
}
override fun onCollisionEnd(player: Entity, platform: Entity) {
// only if player is jumping off that platform
if (player.bottomY <= platform.y) {
playerComponent.removedPlatformAt(platform.position)
platform.removeFromWorld()
}
}
})
}
private fun initPlayer() {
val physics = PhysicsComponent()
physics.setBodyType(BodyType.DYNAMIC)
physics.addGroundSensor(HitBox(Point2D(10.0, 60.0), BoundingShape.box(10.0, 5.0)))
playerComponent = PlayerComponent()
val player = entityBuilder()
.type(EntityType.PLAYER)
.at(getAppWidth() / 2.0, LEVEL_HEIGHT - 60.0)
.viewWithBBox(Rectangle(30.0, 60.0, Color.BLUE))
.with(physics, CollidableComponent(true))
.with(playerComponent)
.buildAndAttach()
getGameScene().viewport.setBounds(0, 0, getAppWidth(), LEVEL_HEIGHT.toInt())
getGameScene().viewport.bindToEntity(player, 0.0, getAppHeight() / 2.0)
}
private fun initPlatforms() {
for (y in 0..LEVEL_HEIGHT.toInt() step 200) {
entityBuilder()
.at(0.0, y * 1.0)
.view(getUIFactoryService().newText("$y", Color.BLACK, 16.0))
.buildAndAttach()
spawn("platform", 20.0, y * 1.0)
}
}
}
class PlayerComponent : Component() {
private lateinit var physics: PhysicsComponent
private val playerPoints = ArrayDeque<Point2D>()
private val platformPoints = arrayListOf<Point2D>()
private var isRewinding = false
private var t = 0.0
override fun onUpdate(tpf: Double) {
physics.velocityX = 0.0
t += tpf
if (t >= 0.05 && !isRewinding) {
playerPoints.addLast(entity.position)
t = 0.0
}
}
fun startNewCapture() {
//if (isOnPlatform()) {
playerPoints.clear()
platformPoints.clear()
//}
}
fun removedPlatformAt(point: Point2D) {
platformPoints.add(point)
}
fun rewind() {
if (playerPoints.isEmpty()) {
isRewinding = false
entity.getComponent(CollidableComponent::class.java).value = true
t = 0.0
return
}
isRewinding = true
entity.getComponent(CollidableComponent::class.java).value = false
val point = playerPoints.removeLast()
entity.getComponent(PhysicsComponent::class.java).overwritePosition(point)
if (platformPoints.isNotEmpty()) {
platformPoints.forEach {
spawn("platform", it).getComponent(PlatformComponent::class.java).stop()
}
platformPoints.clear()
}
}
fun endRewind() {
isRewinding = false
entity.getComponent(CollidableComponent::class.java).value = true
t = 0.0
}
fun isOnPlatform(): Boolean = physics.isOnGround || FXGLMath.abs(physics.velocityY) < 2
fun jump() {
if (isOnPlatform()) {
physics.velocityY = -800.0
}
}
}
class PlatformComponent : Component() {
private val speed = FXGLMath.random(100.0, 400.0)
private lateinit var physics: PhysicsComponent
override fun onAdded() {
physics.setOnPhysicsInitialized {
physics.velocityX = speed
}
}
override fun onUpdate(tpf: Double) {
if (entity.rightX >= FXGL.getAppWidth()) {
physics.velocityX = -speed
}
if (entity.x <= 0) {
physics.velocityX = speed
}
}
fun stop() {
pause()
physics.velocityX = 0.0
}
}
class Factory : EntityFactory {
@Spawns("platform")
fun newPlatform(data: SpawnData): Entity {
val physics = PhysicsComponent()
physics.setBodyType(BodyType.KINEMATIC)
return entityBuilder(data)
.type(EntityType.PLATFORM)
.viewWithBBox(Rectangle(100.0, 40.0))
.with(physics, CollidableComponent(true))
.with(PlatformComponent())
.build()
}
}
enum class EntityType {
PLAYER, PLATFORM
}
fun main(args: Array<String>) {
GameApplication.launch(GeoJumperApp::class.java, args)
} | GeoJumper/src/main/kotlin/com/almasb/fxglgames/geojumper/GeoJumperApp.kt | 583758892 |
/*
* Copyright (c) 2019 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.image.preview
import android.graphics.Bitmap
/**
* @author toastkidjp
*/
class ImageRotationUseCase(
private val viewModel: ImagePreviewFragmentViewModel,
private val currentBitmap: () -> Bitmap?,
private val rotatedBitmapFactory: RotatedBitmapFactory = RotatedBitmapFactory()
) {
fun rotateLeft() {
currentBitmap()?.let {
viewModel.nextBitmap(rotatedBitmapFactory.rotateLeft(it))
}
}
fun rotateRight() {
currentBitmap()?.let {
viewModel.nextBitmap(rotatedBitmapFactory.rotateRight(it))
}
}
fun reverse() {
currentBitmap()?.let {
viewModel.nextBitmap(rotatedBitmapFactory.reverse(it))
}
}
} | image/src/main/java/jp/toastkid/image/preview/ImageRotationUseCase.kt | 4066160430 |
/*
* 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.settings.background
import android.content.Context
import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import coil.Coil
import coil.ImageLoader
import coil.request.ImageRequest
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.mockk
import io.mockk.mockkConstructor
import io.mockk.mockkObject
import io.mockk.unmockkAll
import io.mockk.verify
import org.junit.After
import org.junit.Before
import org.junit.Test
class ImageLoadingUseCaseTest {
private lateinit var imageLoadingUseCase: ImageLoadingUseCase
@MockK
private lateinit var contentView: View
@MockK
private lateinit var arguments: Bundle
@MockK
private lateinit var imageView: ImageView
@MockK
private lateinit var imageRequestBuilder: ImageRequest.Builder
@MockK
private lateinit var imageLoader: ImageLoader
@MockK
private lateinit var context: Context
@Before
fun setUp() {
MockKAnnotations.init(this)
imageLoadingUseCase = ImageLoadingUseCase()
every { contentView.findViewById<ImageView>(any()) }.returns(imageView)
every { imageView.getContext() }.returns(context)
mockkConstructor(ImageRequest.Builder::class)
every { anyConstructed<ImageRequest.Builder>().data(any()) }.returns(imageRequestBuilder)
every { imageRequestBuilder.target(any<ImageView>()) }.returns(imageRequestBuilder)
every { imageRequestBuilder.build() }.returns(mockk())
mockkObject(Coil)
every { Coil.imageLoader(any()) }.returns(imageLoader)
every { imageLoader.enqueue(any()) }.returns(mockk())
}
@After
fun tearDown() {
unmockkAll()
}
@Test
fun test() {
every { arguments.containsKey(any()) }.returns(true)
every { arguments.getParcelable<Bitmap>(any()) }.returns(mockk())
imageLoadingUseCase.invoke(contentView, arguments)
verify(exactly = 1) { arguments.containsKey(any()) }
verify(exactly = 1) { arguments.getParcelable<Bitmap>(any()) }
verify(exactly = 1) { contentView.findViewById<ImageView>(any()) }
verify(atLeast = 1) { imageView.getContext() }
verify(exactly = 1) { anyConstructed<ImageRequest.Builder>().data(any()) }
verify(exactly = 1) { imageRequestBuilder.target(any<ImageView>()) }
verify(exactly = 1) { imageRequestBuilder.build() }
verify(exactly = 1) { imageLoader.enqueue(any()) }
}
@Test
fun testNotContainsKey() {
every { arguments.containsKey(any()) }.returns(false)
every { arguments.getParcelable<Bitmap>(any()) }.returns(mockk())
imageLoadingUseCase.invoke(contentView, arguments)
verify(atLeast = 1) { arguments.containsKey(any()) }
verify(exactly = 0) { arguments.getParcelable<Bitmap>(any()) }
verify(exactly = 1) { contentView.findViewById<ImageView>(any()) }
verify(exactly = 0) { imageView.getContext() }
verify(exactly = 0) { anyConstructed<ImageRequest.Builder>().data(any()) }
verify(exactly = 0) { imageRequestBuilder.target(any<ImageView>()) }
verify(exactly = 0) { imageRequestBuilder.build() }
verify(exactly = 0) { imageLoader.enqueue(any()) }
}
@Test
fun testUrlCase() {
every { arguments.containsKey("image") }.returns(false)
every { arguments.containsKey("imageUrl") }.returns(true)
every { arguments.getString(any()) }.returns("test")
imageLoadingUseCase.invoke(contentView, arguments)
verify(atLeast = 1) { arguments.containsKey(any()) }
verify(exactly = 1) { arguments.getString(any()) }
verify(exactly = 1) { contentView.findViewById<ImageView>(any()) }
verify(atLeast = 1) { imageView.getContext() }
verify(exactly = 1) { anyConstructed<ImageRequest.Builder>().data(any()) }
verify(exactly = 1) { imageRequestBuilder.target(any<ImageView>()) }
verify(exactly = 1) { imageRequestBuilder.build() }
verify(exactly = 1) { imageLoader.enqueue(any()) }
}
} | app/src/test/java/jp/toastkid/yobidashi/settings/background/ImageLoadingUseCaseTest.kt | 655278215 |
package sdk.chat.ui.recycler
import android.app.Activity
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton
import kotlinx.android.synthetic.main.recycler_view_holder_navigation.view.*
import kotlinx.android.synthetic.main.recycler_view_holder_radio.view.*
import kotlinx.android.synthetic.main.recycler_view_holder_section.view.*
import kotlinx.android.synthetic.main.recycler_view_holder_section.view.textView
import kotlinx.android.synthetic.main.recycler_view_holder_toggle.view.*
import sdk.chat.ui.R
import sdk.chat.ui.icons.Icons
import smartadapter.viewholder.SmartViewHolder
import java.util.*
open class SmartViewModel() {
}
open class SectionViewModel(val title: String, val paddingTop: Int? = null): SmartViewModel() {
var hideTopBorder = false
var hideBottomBorder = false
open fun hideBorders(top: Boolean? = false, bottom: Boolean? = false): SectionViewModel {
if (top != null) {
hideTopBorder = top
}
if (bottom != null) {
hideBottomBorder = bottom
}
return this
}
}
interface RadioRunnable {
fun run(value: String)
}
class RadioViewModel(val group: String, val title: String, val value: String, var starting: StartingValue, val onClick: RadioRunnable): SmartViewModel() {
var checked: Boolean = starting.get()
fun click() {
onClick.run(value)
}
}
class NavigationViewModel(val title: String, val onClick: Runnable): SmartViewModel() {
var clicked = false
fun click() {
if (!clicked) {
clicked = true
onClick.run()
}
}
}
class DividerViewModel(): SmartViewModel()
interface ButtonRunnable {
fun run(value: Activity)
}
class ButtonViewModel(val title: String, val color: Int, val onClick: ButtonRunnable): SmartViewModel() {
fun click(activity: Activity) {
onClick.run(activity)
}
}
interface ToggleRunnable {
fun run(value: Boolean)
}
interface StartingValue {
fun get(): Boolean
}
class ToggleViewModel(val title: String, var enabled: StartingValue, val onChange: ToggleRunnable): SmartViewModel() {
fun change(value: Boolean) {
onChange.run(value)
}
}
open class RadioViewHolder(parentView: ViewGroup) :
SmartViewHolder<RadioViewModel>(parentView, R.layout.recycler_view_holder_radio) {
override fun bind(item: RadioViewModel) {
with(itemView) {
textView.text = item.title
radioButton.isChecked = item.starting.get()
}
}
}
open class SectionViewHolder(parentView: ViewGroup) :
SmartViewHolder<SectionViewModel>(parentView, R.layout.recycler_view_holder_section) {
override fun bind(item: SectionViewModel) {
with(itemView) {
if (item.paddingTop != null) {
itemView.setPadding(itemView.paddingLeft, item.paddingTop, itemView.paddingRight, itemView.paddingBottom)
itemView.requestLayout();
}
textView.text = item.title.toUpperCase(Locale.ROOT)
if (item.hideTopBorder) {
topBorder.visibility = View.INVISIBLE
} else {
topBorder.visibility = View.VISIBLE
}
if (item.hideBottomBorder) {
bottomBorder.visibility = View.INVISIBLE
} else {
bottomBorder.visibility = View.VISIBLE
}
}
}
}
open class NavigationViewHolder(parentView: ViewGroup) :
SmartViewHolder<NavigationViewModel>(parentView, R.layout.recycler_view_holder_navigation) {
init {
with(itemView) {
imageView.setImageDrawable(Icons.get(Icons.choose().arrowRight, R.color.gray_very_light))
}
}
// init(par) {
// imageView
// }
override fun bind(item: NavigationViewModel) {
with(itemView) {
textView.text = item.title
}
}
}
open class ButtonViewHolder(parentView: ViewGroup) :
SmartViewHolder<ButtonViewModel>(parentView, R.layout.recycler_view_holder_button) {
override fun bind(item: ButtonViewModel) {
with(itemView) {
textView.text = item.title
textView.setTextColor(item.color)
}
}
}
open class DividerViewHolder(parentView: ViewGroup) :
SmartViewHolder<DividerViewModel>(parentView, R.layout.recycler_view_holder_divider) {
override fun bind(item: DividerViewModel) {}
}
open class ToggleViewHolder(parentView: ViewGroup) :
SmartViewHolder<ToggleViewModel>(parentView, R.layout.recycler_view_holder_toggle) {
protected var model: ToggleViewModel? = null
// protected var checked = false
init {
with(itemView) {
itemView.isEnabled = false
switchMaterial.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { _, isChecked ->
// Run after animation
model?.change(isChecked)
// if (isChecked != checked) {
// }
})
}
}
override fun bind(item: ToggleViewModel) {
with(itemView) {
model = item
textView.text = item.title
switchMaterial.isChecked = item.enabled.get()
}
}
} | chat-sdk-core-ui/src/main/java/sdk/chat/ui/recycler/ViewHolders.kt | 4287313621 |
Subsets and Splits