content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
fun nonExhaustiveInt(x: Int) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'else' branch">when</error>(x) {
0 -> false
}
fun nonExhaustiveBoolean(b: Boolean) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'true' branch or 'else' branch instead">when</error>(b) {
false -> 0
}
fun nonExhaustiveNullableBoolean(b: Boolean?) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'null' branch or 'else' branch instead">when</error>(b) {
false -> 0
true -> 1
}
enum class Color {
RED,
GREEN,
BLUE
}
fun nonExhaustiveEnum(c: Color) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'RED', 'BLUE' branches or 'else' branch instead">when</error>(c) {
Color.GREEN -> 0xff00
}
fun nonExhaustiveNullable(c: Color?) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'GREEN', 'null' branches or 'else' branch instead">when</error>(c) {
Color.RED -> 0xff
Color.BLUE -> 0xff0000
}
fun whenOnEnum(c: Color) {
<warning descr="[NON_EXHAUSTIVE_WHEN] 'when' expression on enum is recommended to be exhaustive, add 'RED' branch or 'else' branch instead">when</warning>(c) {
Color.BLUE -> {}
Color.GREEN -> {}
}
}
enum class EnumInt {
A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15
}
fun whenOnLongEnum(i: EnumInt) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', ... branches or 'else' branch instead">when</error> (i) {
EnumInt.A7 -> 7
}
sealed class Variant {
object Singleton : Variant()
class Something : Variant()
object Another : Variant()
}
fun nonExhaustiveSealed(v: Variant) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'Another', 'is Something' branches or 'else' branch instead">when</error>(v) {
Variant.Singleton -> false
}
fun nonExhaustiveNullableSealed(v: Variant?) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'Another', 'null' branches or 'else' branch instead">when</error>(v) {
Variant.Singleton -> false
is Variant.Something -> true
}
sealed class Empty
fun nonExhaustiveEmpty(e: Empty) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'else' branch">when</error>(<warning>e</warning>) {}
fun nonExhaustiveNullableEmpty(e: Empty?) = <error descr="[NO_ELSE_IN_WHEN] 'when' expression must be exhaustive, add necessary 'else' branch">when</error>(<warning>e</warning>) {}
| plugins/kotlin/idea/tests/testData/checker/WhenNonExhaustive.kt | 4164934453 |
import java.lang.Runnable
import java.lang.Thread
class ThreadRunSuperTest : Thread() {
fun doTest() {
object : Thread("") {
override fun run() {
super.run()
}
}.start()
}
} | jvm/jvm-analysis-kotlin-tests/testData/codeInspection/threadrun/ThreadRunSuperTest.kt | 261931435 |
fun foo(): String.() -> Unit {
return (label@ {
f {
<caret>
}
})
}
fun f(p: Any.() -> Unit){}
// INVOCATION_COUNT: 1
// EXIST: { lookupString: "this", itemText: "this", tailText: null, typeText: "Any", attributes: "bold" }
// ABSENT: "this@f"
// EXIST: { lookupString: "this@label", itemText: "this", tailText: "@label", typeText: "String", attributes: "bold" }
| plugins/kotlin/completion/tests/testData/keywords/LabeledLambdaThis.kt | 4241781741 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.testFramework.binaryReproducibility
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.io.Decompressor
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFileAttributeView
import java.nio.file.attribute.PosixFilePermission
import java.security.DigestInputStream
import java.security.MessageDigest
import java.util.*
import kotlin.io.path.*
import kotlin.streams.toList
class FileTreeContentTest(private val diffDir: Path = Path.of(System.getProperty("user.dir")).resolve(".diff"),
private val tempDir: Path = Files.createTempDirectory(this::class.java.simpleName)) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
require(args.count() == 2)
val path1 = Path.of(args[0])
val path2 = Path.of(args[1])
require(path1.exists())
require(path2.exists())
val test = FileTreeContentTest()
val assertion = when {
path1.isDirectory() && path2.isDirectory() -> test.assertTheSameDirectoryContent(path1, path2)
path1.isRegularFile() && path2.isRegularFile() -> test.assertTheSameFile(path1, path2)
else -> throw IllegalArgumentException()
}
if (assertion != null) throw assertion
}
}
init {
FileUtil.delete(diffDir)
Files.createDirectories(diffDir)
}
private fun listingDiff(firstIteration: Set<Path>, nextIteration: Set<Path>) =
((firstIteration - nextIteration) + (nextIteration - firstIteration))
.filterNot { it.name == ".DS_Store" }
fun assertTheSameFile(relativeFilePath: Path, dir1: Path, dir2: Path): AssertionError? {
val path1 = dir1.resolve(relativeFilePath)
val path2 = dir2.resolve(relativeFilePath)
return assertTheSameFile(path1, path2, "$relativeFilePath")
}
private fun assertTheSameFile(path1: Path, path2: Path, relativeFilePath: String = path1.name): AssertionError? {
if (!Files.exists(path1) ||
!Files.exists(path2) ||
!path1.isRegularFile() ||
path1.checksum() == path2.checksum() &&
path1.permissions() == path2.permissions()) {
return null
}
println("Failed for $relativeFilePath")
require(path1.extension == path2.extension)
val contentError = when (path1.extension) {
"tar.gz", "gz", "tar" -> assertTheSameDirectoryContent(
path1.unpackingDir().also { Decompressor.Tar(path1).extract(it) },
path2.unpackingDir().also { Decompressor.Tar(path2).extract(it) }
) ?: AssertionError("No difference in $relativeFilePath content. Timestamp or ordering issue?")
"zip", "jar", "ijx" -> assertTheSameDirectoryContent(
path1.unpackingDir().also { Decompressor.Zip(path1).withZipExtensions().extract(it) },
path2.unpackingDir().also { Decompressor.Zip(path2).withZipExtensions().extract(it) }
) ?: AssertionError("No difference in $relativeFilePath content. Timestamp or ordering issue?")
else -> if (path1.checksum() != path2.checksum()) {
saveDiff(relativeFilePath, path1, path2)
AssertionError("Checksum mismatch for $relativeFilePath")
}
else null
}
if (path1.permissions() != path2.permissions()) {
val permError = AssertionError("Permissions mismatch for $relativeFilePath: ${path1.permissions()} vs ${path2.permissions()}")
contentError?.addSuppressed(permError) ?: return permError
}
requireNotNull(contentError)
return contentError
}
private fun saveDiff(relativePath: String, file1: Path, file2: Path) {
fun fileIn(subdir: String): Path {
val textFileName = relativePath.removeSuffix(".txt") + ".txt"
val target = diffDir.resolve(subdir)
.resolve(relativePath)
.resolveSibling(textFileName)
target.parent.createDirectories()
return target
}
val a = fileIn("a")
val b = fileIn("b")
file1.writeContent(a)
file2.writeContent(b)
fileIn("diff").writeText(diff(a, b))
}
private fun Path.checksum(): String = inputStream().buffered().use { input ->
val digest = MessageDigest.getInstance("SHA-256")
DigestInputStream(input, digest).use {
var bytesRead = 0
val buffer = ByteArray(1024 * 8)
while (bytesRead != -1) {
bytesRead = it.read(buffer)
}
}
Base64.getEncoder().encodeToString(digest.digest())
}
private fun Path.permissions(): Set<PosixFilePermission> =
Files.getFileAttributeView(this, PosixFileAttributeView::class.java)
?.readAttributes()?.permissions() ?: emptySet()
private fun Path.writeContent(target: Path) {
when (extension) {
"jar", "zip", "tar.gz", "gz", "tar", "ijx" -> error("$this is expected to be already unpacked")
"class" -> target.writeText(process("javap", "-verbose", "$this"))
else -> copyTo(target, overwrite = true)
}
}
private fun Path.unpackingDir(): Path {
val unpackingDir = tempDir
.resolve("unpacked")
.resolve("$fileName".replace(".", "_"))
.resolve(UUID.randomUUID().toString())
FileUtil.delete(unpackingDir)
return unpackingDir
}
private fun diff(path1: Path, path2: Path) = process("git", "diff", "--no-index", "--", "$path1", "$path2")
private fun process(vararg command: String): String {
val process = ProcessBuilder(*command).start()
val output = process.inputStream.bufferedReader().use { it.readText() }
process.waitFor()
return output
}
fun assertTheSameDirectoryContent(dir1: Path, dir2: Path): AssertionError? {
require(dir1.isDirectory())
require(dir2.isDirectory())
val listing1 = Files.walk(dir1).use { it.toList() }
val listing2 = Files.walk(dir2).use { it.toList() }
val relativeListing1 = listing1.map(dir1::relativize)
val listingDiff = listingDiff(relativeListing1.toSet(), listing2.map(dir2::relativize).toSet())
val contentComparisonFailures = relativeListing1.mapNotNull { assertTheSameFile(it, dir1, dir2) }
return when {
listingDiff.isNotEmpty() -> AssertionError(listingDiff.joinToString(prefix = "Listing diff for $dir1 and $dir2:\n", separator = "\n"))
contentComparisonFailures.isNotEmpty() -> AssertionError("$dir1 doesn't match $dir2")
else -> null
}?.apply {
contentComparisonFailures.forEach(::addSuppressed)
}
}
}
| platform/build-scripts/testFramework/src/org/jetbrains/intellij/build/testFramework/binaryReproducibility/FileTreeContentTest.kt | 4041749854 |
package com.habitrpg.android.habitica.ui.activities
import android.accounts.AccountManager
import android.animation.*
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.SharedPreferences
import android.os.Build
import android.os.Bundle
import android.text.InputType
import android.text.SpannableString
import android.text.style.UnderlineSpan
import android.view.MenuItem
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.*
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import androidx.preference.PreferenceManager
import com.facebook.*
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.google.android.gms.auth.GoogleAuthException
import com.google.android.gms.auth.GoogleAuthUtil
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException
import com.google.android.gms.auth.UserRecoverableAuthException
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.common.GooglePlayServicesUtil
import com.google.android.gms.common.Scopes
import com.habitrpg.android.habitica.BuildConfig
import com.habitrpg.android.habitica.HabiticaBaseApplication
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.api.HostConfig
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.ApiClient
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.extensions.addCancelButton
import com.habitrpg.android.habitica.extensions.addCloseButton
import com.habitrpg.android.habitica.extensions.addOkButton
import com.habitrpg.android.habitica.helpers.*
import com.habitrpg.android.habitica.models.auth.UserAuthResponse
import com.habitrpg.android.habitica.proxy.CrashlyticsProxy
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.helpers.dismissKeyboard
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import com.habitrpg.android.habitica.ui.views.login.LockableScrollView
import com.habitrpg.android.habitica.ui.views.login.LoginBackgroundView
import com.willowtreeapps.signinwithapplebutton.SignInWithAppleConfiguration
import io.reactivex.Flowable
import io.reactivex.exceptions.Exceptions
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import java.io.IOException
import javax.inject.Inject
class LoginActivity : BaseActivity(), Consumer<UserAuthResponse> {
@Inject
lateinit var apiClient: ApiClient
@Inject
lateinit var sharedPrefs: SharedPreferences
@Inject
lateinit var hostConfig: HostConfig
@Inject
internal lateinit var userRepository: UserRepository
@Inject
@JvmField
var keyHelper: KeyHelper? = null
@Inject
lateinit var crashlyticsProxy: CrashlyticsProxy
@Inject
lateinit var configManager: AppConfigManager
private var isRegistering: Boolean = false
private var isShowingForm: Boolean = false
private val backgroundContainer: LockableScrollView by bindView(R.id.background_container)
internal val backgroundView: LoginBackgroundView by bindView(R.id.background_view)
internal val newGameButton: Button by bindView(R.id.new_game_button)
internal val showLoginButton: Button by bindView(R.id.show_login_button)
internal val scrollView: ScrollView by bindView(R.id.login_scrollview)
private val formWrapper: LinearLayout by bindView(R.id.login_linear_layout)
private val backButton: Button by bindView(R.id.back_button)
private val logoView: ImageView by bindView(R.id.logo_view)
private val mLoginNormalBtn: Button by bindView(R.id.login_btn)
private val mProgressBar: ProgressBar by bindView(R.id.PB_AsyncTask)
private val mUsernameET: EditText by bindView(R.id.username)
private val mPasswordET: EditText by bindView(R.id.password)
private val mEmail: EditText by bindView(R.id.email)
private val mConfirmPassword: EditText by bindView(R.id.confirm_password)
private val forgotPasswordButton: Button by bindView(R.id.forgot_password)
private val facebookLoginButton: Button by bindView(R.id.fb_login_button)
private val googleLoginButton: Button by bindView(R.id.google_login_button)
private val appleLoginButton: Button by bindView(R.id.apple_login_button)
private var callbackManager = CallbackManager.Factory.create()
private var googleEmail: String? = null
private var loginManager = LoginManager.getInstance()
private val loginClick = View.OnClickListener {
mProgressBar.visibility = View.VISIBLE
if (isRegistering) {
val username: String = mUsernameET.text.toString().trim { it <= ' ' }
val email: String = mEmail.text.toString().trim { it <= ' ' }
val password: String = mPasswordET.text.toString()
val confirmPassword: String = mConfirmPassword.text.toString()
if (username.isEmpty() || password.isEmpty() || email.isEmpty() || confirmPassword.isEmpty()) {
showValidationError(R.string.login_validation_error_fieldsmissing)
return@OnClickListener
}
if (password.length < configManager.minimumPasswordLength()) {
showValidationError(getString(R.string.password_too_short, configManager.minimumPasswordLength()))
return@OnClickListener
}
apiClient.registerUser(username, email, password, confirmPassword)
.subscribe(this@LoginActivity,
Consumer {
hideProgress()
RxErrorHandler.reportError(it)
})
} else {
val username: String = mUsernameET.text.toString().trim { it <= ' ' }
val password: String = mPasswordET.text.toString()
if (username.isEmpty() || password.isEmpty()) {
showValidationError(R.string.login_validation_error_fieldsmissing)
return@OnClickListener
}
apiClient.connectUser(username, password).subscribe(this@LoginActivity,
Consumer {
hideProgress()
RxErrorHandler.reportError(it)
})
}
}
override fun getLayoutResId(): Int {
window.requestFeature(Window.FEATURE_ACTION_BAR)
return R.layout.activity_login
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar?.hide()
//Set default values to avoid null-responses when requesting unedited settings
PreferenceManager.setDefaultValues(this, R.xml.preferences_fragment, false)
setupFacebookLogin()
mLoginNormalBtn.setOnClickListener(loginClick)
val content = SpannableString(forgotPasswordButton.text)
content.setSpan(UnderlineSpan(), 0, content.length, 0)
forgotPasswordButton.text = content
this.isRegistering = true
val additionalData = HashMap<String, Any>()
additionalData["page"] = this.javaClass.simpleName
AmplitudeManager.sendEvent("navigate", AmplitudeManager.EVENT_CATEGORY_NAVIGATION, AmplitudeManager.EVENT_HITTYPE_PAGEVIEW, additionalData)
backgroundContainer.post { backgroundContainer.scrollTo(0, backgroundContainer.bottom) }
backgroundContainer.setScrollingEnabled(false)
val window = window
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.statusBarColor = ContextCompat.getColor(this, R.color.black_20_alpha)
}
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
newGameButton.setOnClickListener { newGameButtonClicked() }
showLoginButton.setOnClickListener { showLoginButtonClicked() }
backButton.setOnClickListener { backButtonClicked() }
forgotPasswordButton.setOnClickListener { onForgotPasswordClicked() }
facebookLoginButton.setOnClickListener { handleFacebookLogin() }
googleLoginButton.setOnClickListener { handleGoogleLogin() }
appleLoginButton.setOnClickListener {
val configuration = SignInWithAppleConfiguration(
clientId = BuildConfig.APPLE_AUTH_CLIENT_ID,
redirectUri = "${hostConfig.address}/api/v4/user/auth/apple",
scope = "name email"
)
val fragmentTag = "SignInWithAppleButton-SignInWebViewDialogFragment"
SignInWithAppleService(supportFragmentManager, fragmentTag, configuration) { result ->
when (result) {
is SignInWithAppleResult.Success -> {
val response = UserAuthResponse()
response.id = result.userID
response.apiToken = result.apiKey
response.newUser = result.newUser
}
}
}.show()
}
}
private fun setupFacebookLogin() {
callbackManager = CallbackManager.Factory.create()
loginManager.registerCallback(callbackManager,
object : FacebookCallback<LoginResult> {
override fun onSuccess(loginResult: LoginResult) {
val accessToken = AccessToken.getCurrentAccessToken()
compositeSubscription.add(apiClient.connectSocial("facebook", accessToken.userId, accessToken.token)
.subscribe(this@LoginActivity, RxErrorHandler.handleEmptyError()))
}
override fun onCancel() { /* no-on */ }
override fun onError(exception: FacebookException) {
exception.printStackTrace()
}
})
}
override fun onBackPressed() {
if (isShowingForm) {
hideForm()
} else {
super.onBackPressed()
}
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
private fun resetLayout() {
if (this.isRegistering) {
if (this.mEmail.visibility == View.GONE) {
show(this.mEmail)
}
if (this.mConfirmPassword.visibility == View.GONE) {
show(this.mConfirmPassword)
}
} else {
if (this.mEmail.visibility == View.VISIBLE) {
hide(this.mEmail)
}
if (this.mConfirmPassword.visibility == View.VISIBLE) {
hide(this.mConfirmPassword)
}
}
}
private fun startMainActivity() {
val intent = Intent(this@LoginActivity, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
private fun startSetupActivity() {
val intent = Intent(this@LoginActivity, SetupActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
private fun toggleRegistering() {
this.isRegistering = (!this.isRegistering)
this.setRegistering()
}
private fun setRegistering() {
if (this.isRegistering) {
this.mLoginNormalBtn.text = getString(R.string.register_btn)
mUsernameET.setHint(R.string.username)
mPasswordET.imeOptions = EditorInfo.IME_ACTION_NEXT
facebookLoginButton.setText(R.string.register_btn_fb)
googleLoginButton.setText(R.string.register_btn_google)
} else {
this.mLoginNormalBtn.text = getString(R.string.login_btn)
mUsernameET.setHint(R.string.email_username)
mPasswordET.imeOptions = EditorInfo.IME_ACTION_DONE
facebookLoginButton.setText(R.string.login_btn_fb)
googleLoginButton.setText(R.string.login_btn_google)
}
this.resetLayout()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
callbackManager.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
if (resultCode == Activity.RESULT_OK) {
googleEmail = data?.getStringExtra(AccountManager.KEY_ACCOUNT_NAME)
handleGoogleLoginResult()
}
}
if (requestCode == REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR) {
// RESULT_CANCELED occurs when user denies requested permissions. In this case we don't
// want to immediately ask them to accept permissions again. See Issue #1290 on github.
if (resultCode != Activity.RESULT_CANCELED) {
handleGoogleLoginResult()
}
}
if (requestCode == FacebookSdk.getCallbackRequestCodeOffset()) {
//This is necessary because the regular login callback is not called for some reason
val accessToken = AccessToken.getCurrentAccessToken()
if (accessToken != null && accessToken.token != null) {
compositeSubscription.add(apiClient.connectSocial("facebook", accessToken.userId, accessToken.token)
.subscribe(this@LoginActivity, Consumer { hideProgress() }))
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_toggleRegistering -> toggleRegistering()
}
return super.onOptionsItemSelected(item)
}
@Throws(Exception::class)
private fun saveTokens(api: String, user: String) {
this.apiClient.updateAuthenticationCredentials(user, api)
sharedPrefs.edit {
putString(getString(R.string.SP_userID), user)
val encryptedKey = if (keyHelper != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
keyHelper?.encrypt(api)
} catch (e: Exception) {
null
}
} else null
if (encryptedKey?.length ?: 0 > 5) {
putString(user, encryptedKey)
} else {
//Something might have gone wrong with encryption, so fall back to this.
putString(getString(R.string.SP_APIToken), api)
}
}
}
private fun hideProgress() {
runOnUiThread {
mProgressBar.visibility = View.GONE
}
}
private fun showValidationError(resourceMessageString: Int) {
showValidationError(getString(resourceMessageString))
}
private fun showValidationError(message: String) {
mProgressBar.visibility = View.GONE
val alert = HabiticaAlertDialog(this)
alert.setTitle(R.string.login_validation_error_title)
alert.setMessage(message)
alert.addOkButton()
alert.show()
}
override fun accept(userAuthResponse: UserAuthResponse) {
hideProgress()
try {
saveTokens(userAuthResponse.token, userAuthResponse.id)
} catch (e: Exception) {
crashlyticsProxy.logException(e)
}
HabiticaBaseApplication.reloadUserComponent()
compositeSubscription.add(userRepository.retrieveUser(true)
.subscribe(Consumer {
if (userAuthResponse.newUser) {
this.startSetupActivity()
} else {
AmplitudeManager.sendEvent("login", AmplitudeManager.EVENT_CATEGORY_BEHAVIOUR, AmplitudeManager.EVENT_HITTYPE_EVENT)
this.startMainActivity()
}
}, RxErrorHandler.handleEmptyError()))
}
private fun handleFacebookLogin() {
loginManager.logInWithReadPermissions(this, listOf("user_friends"))
}
private fun handleGoogleLogin() {
if (!checkPlayServices()) {
return
}
val accountTypes = arrayOf("com.google")
val intent = AccountManager.newChooseAccountIntent(null, null,
accountTypes, true, null, null, null, null)
try {
startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT)
} catch (e: ActivityNotFoundException) {
val alert = HabiticaAlertDialog(this)
alert.setTitle(R.string.authentication_error_title)
alert.setMessage(R.string.google_services_missing)
alert.addCloseButton()
alert.show()
}
}
private fun handleGoogleLoginResult() {
val scopesString = Scopes.PROFILE + " " + Scopes.EMAIL
val scopes = "oauth2:$scopesString"
Flowable.defer<String> {
try {
@Suppress("Deprecation")
return@defer Flowable.just(GoogleAuthUtil.getToken(this, googleEmail, scopes))
} catch (e: IOException) {
throw Exceptions.propagate(e)
} catch (e: GoogleAuthException) {
throw Exceptions.propagate(e)
}
}
.subscribeOn(Schedulers.io())
.flatMap { token -> apiClient.connectSocial("google", googleEmail ?: "", token) }
.subscribe(this@LoginActivity, Consumer { throwable ->
throwable.printStackTrace()
hideProgress()
throwable.cause?.let {
if (GoogleAuthException::class.java.isAssignableFrom(it.javaClass)) {
handleGoogleAuthException(throwable.cause as GoogleAuthException)
}
}
})
}
private fun handleGoogleAuthException(e: Exception) {
if (e is GooglePlayServicesAvailabilityException) {
// The Google Play services APK is old, disabled, or not present.
// Show a dialog created by Google Play services that allows
// the user to update the APK
val statusCode = e
.connectionStatusCode
GoogleApiAvailability.getInstance()
@Suppress("DEPRECATION")
GooglePlayServicesUtil.showErrorDialogFragment(statusCode,
this@LoginActivity,
REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR) {
}
} else if (e is UserRecoverableAuthException) {
// Unable to authenticate, such as when the user has not yet granted
// the app access to the account, but the user can fix this.
// Forward the user to an activity in Google Play services.
val intent = e.intent
startActivityForResult(intent, REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR)
}
}
private fun checkPlayServices(): Boolean {
val googleAPI = GoogleApiAvailability.getInstance()
val result = googleAPI.isGooglePlayServicesAvailable(this)
if (result != ConnectionResult.SUCCESS) {
if (googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result, PLAY_SERVICES_RESOLUTION_REQUEST).show()
}
return false
}
return true
}
private fun newGameButtonClicked() {
isRegistering = true
showForm()
setRegistering()
}
private fun showLoginButtonClicked() {
isRegistering = false
showForm()
setRegistering()
}
private fun backButtonClicked() {
if (isShowingForm) {
hideForm()
}
}
private fun showForm() {
isShowingForm = true
val panAnimation = ObjectAnimator.ofInt(backgroundContainer, "scrollY", 0).setDuration(1000)
val newGameAlphaAnimation = ObjectAnimator.ofFloat<View>(newGameButton, View.ALPHA, 0.toFloat())
val showLoginAlphaAnimation = ObjectAnimator.ofFloat<View>(showLoginButton, View.ALPHA, 0.toFloat())
val scaleLogoAnimation = ValueAnimator.ofInt(logoView.measuredHeight, (logoView.measuredHeight * 0.75).toInt())
scaleLogoAnimation.addUpdateListener { valueAnimator ->
val value = valueAnimator.animatedValue as? Int ?: 0
val layoutParams = logoView.layoutParams
layoutParams.height = value
logoView.layoutParams = layoutParams
}
if (isRegistering) {
newGameAlphaAnimation.startDelay = 600
newGameAlphaAnimation.duration = 400
showLoginAlphaAnimation.duration = 400
newGameAlphaAnimation.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
newGameButton.visibility = View.GONE
showLoginButton.visibility = View.GONE
scrollView.visibility = View.VISIBLE
scrollView.alpha = 1f
}
})
} else {
showLoginAlphaAnimation.startDelay = 600
showLoginAlphaAnimation.duration = 400
newGameAlphaAnimation.duration = 400
showLoginAlphaAnimation.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
newGameButton.visibility = View.GONE
showLoginButton.visibility = View.GONE
scrollView.visibility = View.VISIBLE
scrollView.alpha = 1f
}
})
}
val backAlphaAnimation = ObjectAnimator.ofFloat<View>(backButton, View.ALPHA, 1.toFloat()).setDuration(800)
val showAnimation = AnimatorSet()
showAnimation.playTogether(panAnimation, newGameAlphaAnimation, showLoginAlphaAnimation, scaleLogoAnimation)
showAnimation.play(backAlphaAnimation).after(panAnimation)
for (i in 0 until formWrapper.childCount) {
val view = formWrapper.getChildAt(i)
view.alpha = 0f
val animator = ObjectAnimator.ofFloat<View>(view, View.ALPHA, 1.toFloat()).setDuration(400)
animator.startDelay = (100 * i).toLong()
showAnimation.play(animator).after(panAnimation)
}
showAnimation.start()
}
private fun hideForm() {
isShowingForm = false
val panAnimation = ObjectAnimator.ofInt(backgroundContainer, "scrollY", backgroundContainer.bottom).setDuration(1000)
val newGameAlphaAnimation = ObjectAnimator.ofFloat<View>(newGameButton, View.ALPHA, 1.toFloat()).setDuration(700)
val showLoginAlphaAnimation = ObjectAnimator.ofFloat<View>(showLoginButton, View.ALPHA, 1.toFloat()).setDuration(700)
val scaleLogoAnimation = ValueAnimator.ofInt(logoView.measuredHeight, (logoView.measuredHeight * 1.333333).toInt())
scaleLogoAnimation.addUpdateListener { valueAnimator ->
val value = valueAnimator.animatedValue as? Int
val layoutParams = logoView.layoutParams
layoutParams.height = value ?: 0
logoView.layoutParams = layoutParams
}
showLoginAlphaAnimation.startDelay = 300
val scrollViewAlphaAnimation = ObjectAnimator.ofFloat<View>(scrollView, View.ALPHA, 0.toFloat()).setDuration(800)
scrollViewAlphaAnimation.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
newGameButton.visibility = View.VISIBLE
showLoginButton.visibility = View.VISIBLE
scrollView.visibility = View.INVISIBLE
}
})
val backAlphaAnimation = ObjectAnimator.ofFloat<View>(backButton, View.ALPHA, 0.toFloat()).setDuration(800)
val showAnimation = AnimatorSet()
showAnimation.playTogether(panAnimation, scrollViewAlphaAnimation, backAlphaAnimation, scaleLogoAnimation)
showAnimation.play(newGameAlphaAnimation).after(scrollViewAlphaAnimation)
showAnimation.play(showLoginAlphaAnimation).after(scrollViewAlphaAnimation)
showAnimation.start()
dismissKeyboard()
}
private fun onForgotPasswordClicked() {
val input = EditText(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
input.setAutofillHints(EditText.AUTOFILL_HINT_EMAIL_ADDRESS)
}
input.inputType = InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
val lp = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT)
input.layoutParams = lp
val alertDialog = HabiticaAlertDialog(this)
alertDialog.setTitle(R.string.forgot_password_title)
alertDialog.setMessage(R.string.forgot_password_description)
alertDialog.setAdditionalContentView(input)
alertDialog.addButton(R.string.send, true) { _, _ ->
userRepository.sendPasswordResetEmail(input.text.toString()).subscribe(Consumer { showPasswordEmailConfirmation() }, RxErrorHandler.handleEmptyError())
}
alertDialog.addCancelButton()
alertDialog.show()
}
private fun showPasswordEmailConfirmation() {
val alert = HabiticaAlertDialog(this)
alert.setMessage(R.string.forgot_password_confirmation)
alert.addOkButton()
alert.show()
}
companion object {
internal const val REQUEST_CODE_PICK_ACCOUNT = 1000
private const val REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR = 1001
private const val PLAY_SERVICES_RESOLUTION_REQUEST = 9000
fun show(v: View) {
v.visibility = View.VISIBLE
}
fun hide(v: View) {
v.visibility = View.GONE
}
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/LoginActivity.kt | 490600004 |
package com.kickstarter.models
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import org.joda.time.DateTime
/**
* Frequently Asked Questions Data Structure
*
* Note: This data model is written in kotlin and using kotlin
* parcelize because it's meant to be used only with GraphQL
* networking client.
*/
@Parcelize
class ProjectFaq private constructor(
val id: Long,
val answer: String,
val createdAt: DateTime? = null,
val question: String
) : Parcelable {
@Parcelize
data class Builder(
var id: Long = -1,
var answer: String = "",
var createdAt: DateTime? = null,
var question: String = ""
) : Parcelable {
fun id(id: Long) = apply { this.id = id }
fun answer(answer: String) = apply { this.answer = answer }
fun createdAt(createdAt: DateTime?) = apply { this.createdAt = createdAt }
fun question(question: String) = apply { this.question = question }
fun build() = ProjectFaq(id = id, answer = answer, createdAt = createdAt, question = question)
}
companion object {
fun builder() = Builder()
}
fun toBuilder() = Builder(this.id, this.answer, this.createdAt, this.question)
override fun equals(other: Any?): Boolean =
if (other is ProjectFaq) {
other.id == this.id && other.answer == this.answer &&
other.createdAt == this.createdAt && other.question == this.question
} else false
}
| app/src/main/java/com/kickstarter/models/ProjectFaq.kt | 4209071706 |
package org.webscene.client.html
import org.webscene.client.createHtmlElement
import org.webscene.client.createHtmlHeading
import org.webscene.client.createHtmlImage
import org.webscene.client.createParentHtmlElement
import org.webscene.client.html.element.HtmlElement
import org.webscene.client.html.element.ImageElement
import org.webscene.client.html.element.ParentHtmlElement
@Suppress("unused")
/**
* Manages creating HTML elements.
*/
object HtmlCreator {
/**
* Creates a new parent HTML element that can contain child HTML elements.
* @param tagName Name of the tag.
* @param block Initialisation block for setting up the HTML element.
* @return A new [parent HTML element][ParentHtmlElement].
*/
fun parentElement(tagName: String, block: ParentHtmlElement.() -> Unit) =
createParentHtmlElement(tagName, block)
/**
* Creates a new HTML element which doesn't have any child HTML elements.
* @param tagName Name of the tag.
* @param block Initialisation block for setting up the HTML element.
* @return A new [HTML element][HtmlElement].
*/
fun element(tagName: String, block: HtmlElement.() -> Unit) = createHtmlElement(tagName, block)
/**
* Creates a new HTML **span** element that can contain HTML elements, and is used to group element in a document.
* @param block Initialisation block for setting up the span element.
* @return A new span element.
*/
fun span(block: ParentHtmlElement.() -> Unit): ParentHtmlElement = parentElement("span", block)
/**
* Creates a new HTML **div** element that can contain HTML elements, and is used to layout elements in a document.
* @param block Initialisation block for setting up the div element.
* @return A new div element.
*/
fun div(block: ParentHtmlElement.() -> Unit): ParentHtmlElement = parentElement("div", block)
/**
* Creates a new HTML heading that can contain HTML elements, and is used to display a heading.
* @param level A number between 1-6 for the size of the heading. Using a bigger number results in a smaller
* heading being displayed.
* @param block Initialisation block for setting up the heading.
* @return A new heading.
*/
fun heading(level: Int = 1, block: ParentHtmlElement.() -> Unit): ParentHtmlElement = createHtmlHeading(
level, block)
fun header(block: ParentHtmlElement.() -> Unit): ParentHtmlElement = parentElement("header", block)
fun footer(block: ParentHtmlElement.() -> Unit): ParentHtmlElement = parentElement("footer", block)
fun image(src: String, alt: String = "", block: ImageElement.() -> Unit): ImageElement = createHtmlImage(
src = src, alt = alt, block = block)
fun bold(block: ParentHtmlElement.() -> Unit): ParentHtmlElement = parentElement("b", block)
fun italic(block: ParentHtmlElement.() -> Unit): ParentHtmlElement = parentElement("i", block)
}
| src/main/kotlin/org/webscene/client/html/HtmlCreator.kt | 2665887338 |
package info.nightscout.androidaps.danars.comm
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.modules.junit4.PowerMockRunner
import java.util.*
@RunWith(PowerMockRunner::class)
class DanaRS_Packet_Option_Set_Pump_TimeTest : DanaRSTestBase() {
private val packetInjector = HasAndroidInjector {
AndroidInjector {
if (it is DanaRS_Packet) {
it.aapsLogger = aapsLogger
it.dateUtil = dateUtil
}
if (it is DanaRS_Packet_Option_Set_Pump_Time) {
}
}
}
@Test fun runTest() {
val date = Date()
val packet = DanaRS_Packet_Option_Set_Pump_Time(packetInjector, date.time)
// test params
val params = packet.requestParams
Assert.assertEquals((date.year - 100 and 0xff).toByte(), params[0]) // 2019 -> 19
Assert.assertEquals((date.month + 1 and 0xff).toByte(), params[1])
Assert.assertEquals((date.date and 0xff).toByte(), params[2])
Assert.assertEquals((date.hours and 0xff).toByte(), params[3])
Assert.assertEquals((date.minutes and 0xff).toByte(), params[4])
Assert.assertEquals((date.seconds and 0xff).toByte(), params[5])
// test message decoding
packet.handleMessage(createArray(3, 0.toByte()))
Assert.assertEquals(false, packet.failed)
// everything ok :)
packet.handleMessage(createArray(17, 1.toByte()))
Assert.assertEquals(true, packet.failed)
Assert.assertEquals("OPTION__SET_PUMP_TIME", packet.friendlyName)
}
} | app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Set_Pump_TimeTest.kt | 1613004067 |
package ftl.run.status
import com.google.testing.model.TestDetails
import com.google.testing.model.TestExecution
import ftl.adapter.google.toApiModel
import ftl.api.TestMatrix
import ftl.args.IArgs
import ftl.util.MatrixState
import io.mockk.every
import io.mockk.mockk
import org.junit.Assert.assertArrayEquals
import org.junit.Test
class ExecutionStatusListPrinterTest {
@Test
fun test() {
// given
val time = "time"
val executions: List<List<TestMatrix.TestExecution>> = (0..1).map { size ->
(0..size).map { index ->
TestExecution().apply {
id = "${size}_$index"
state = MatrixState.PENDING
testDetails = TestDetails().apply {
errorMessage = "test error"
progressMessages = listOf("test progress")
}
}
}
}.map { it.toApiModel() }
val args = mockk<IArgs> {
every { outputStyle } returns OutputStyle.Single
every { flakyTestAttempts } returns 1
every { disableSharding } returns false
}
val result = mutableListOf<ExecutionStatus.Change>()
val printExecutionStatues = { changes: List<ExecutionStatus.Change> ->
result += changes
}
val printList = ExecutionStatusListPrinter(
args = args,
printExecutionStatues = printExecutionStatues
)
val previous = ExecutionStatus()
val current = ExecutionStatus(
state = "PENDING",
error = "test error",
progress = listOf("test progress")
)
val expected = listOf(
ExecutionStatus.Change("0 - 0", previous, current, time),
ExecutionStatus.Change("1 - 0", previous, current, time),
ExecutionStatus.Change("1 - 1", previous, current, time)
)
// when
executions.forEach { execution ->
printList(time, execution)
}
// then
assertArrayEquals(
expected.toTypedArray(),
result.toTypedArray()
)
}
}
| test_runner/src/test/kotlin/ftl/run/status/ExecutionStatusListPrinterTest.kt | 1399148253 |
// API_VERSION: 1.4
// WITH_STDLIB
val x: Int = listOf(1, 3, 2).<caret>sortedDescending().first() | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/sortedDescendingFirst2.kt | 3494176981 |
package com.radikal.pcnotifications.model.service.impl
import android.content.SharedPreferences
import com.radikal.pcnotifications.exceptions.ServerDetailsNotFoundException
import com.radikal.pcnotifications.model.domain.ServerDetails
import com.radikal.pcnotifications.model.service.ServerDetailsDao
import javax.inject.Inject
/**
* Created by tudor on 26.02.2017.
*/
class SharedPreferencesServerDetailsDao @Inject constructor(var sharedPreferences: SharedPreferences) : ServerDetailsDao{
val SERVER_HOSTNAME = "server_hostname"
val SERVER_IP = "server_ip"
val SERVER_PORT = "server_port"
override fun save(serverDetails: ServerDetails) {
val editor = sharedPreferences.edit()
editor.putString(SERVER_HOSTNAME, serverDetails.hostname)
editor.putString(SERVER_IP, serverDetails.ip)
editor.putInt(SERVER_PORT, serverDetails.port)
editor.apply()
}
override fun retrieve(): ServerDetails {
val hostname = sharedPreferences.getString(SERVER_HOSTNAME, "Default")
val ip = sharedPreferences.getString(SERVER_IP, null)
val port = sharedPreferences.getInt(SERVER_PORT, -1)
if (ip == null || port == -1) {
throw ServerDetailsNotFoundException("Server details not found")
}
return ServerDetails(hostname, ip, port)
}
override fun delete() {
val editor = sharedPreferences.edit()
editor.remove(SERVER_HOSTNAME)
editor.remove(SERVER_IP)
editor.remove(SERVER_PORT)
editor.apply()
}
} | mobile/app/src/main/kotlin/com/radikal/pcnotifications/model/service/impl/SharedPreferencesServerDetailsDao.kt | 3082303500 |
/*
* Copyright (c) 2011 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.moe.client.codebase.expressions
/**
* An [Expression] describing a repository checkout. This is the starting point for building
* Expressions, e.g.: `RepositoryExpression("myGitRepo").atRevision("12345").translateTo("public").`
*/
data class RepositoryExpression(val term: Term) : Expression() {
constructor(repositoryName: String) : this(Term(repositoryName))
val repositoryName: String
get() = term.identifier
/** Add an option name-value pair to the expression, e.g. "myRepo" -> "myRepo(revision=4)". */
fun withOption(optionName: String, optionValue: String): RepositoryExpression =
RepositoryExpression(term.withOption(optionName, optionValue))
/** Add multiple options to a repository. */
fun withOptions(options: Map<String, String>): RepositoryExpression =
RepositoryExpression(term.withOptions(options))
/** A helper method for adding a "revision" option with the given value. */
fun atRevision(revId: String): RepositoryExpression = withOption("revision", revId)
fun getOption(optionName: String): String? = term.options[optionName]
override fun toString(): String = term.toString()
}
| client/src/main/java/com/google/devtools/moe/client/codebase/expressions/RepositoryExpression.kt | 4211185509 |
// WITH_RUNTIME
// INTENTION_TEXT: "Replace with 'count{}'"
// IS_APPLICABLE_2: false
fun f(list: List<Any?>): Int{
var c = 0
<caret>for (d in list) {
if (d == "") continue
if (d != null) {
if (d is Int) continue
c++
}
}
return c
} | plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/count/countSomethingAndNotNull.kt | 3477736902 |
package eu.kanade.tachiyomi.ui.download
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.*
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.download.DownloadService
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.ui.base.fragment.BaseRxFragment
import eu.kanade.tachiyomi.ui.main.MainActivity
import eu.kanade.tachiyomi.util.plusAssign
import kotlinx.android.synthetic.main.fragment_download_queue.*
import nucleus.factory.RequiresPresenter
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.subscriptions.CompositeSubscription
import java.util.*
import java.util.concurrent.TimeUnit
/**
* Fragment that shows the currently active downloads.
* Uses R.layout.fragment_download_queue.
*/
@RequiresPresenter(DownloadPresenter::class)
class DownloadFragment : BaseRxFragment<DownloadPresenter>() {
/**
* Adapter containing the active downloads.
*/
private lateinit var adapter: DownloadAdapter
/**
* Menu item to start the queue.
*/
private var startButton: MenuItem? = null
/**
* Menu item to pause the queue.
*/
private var pauseButton: MenuItem? = null
/**
* Menu item to clear the queue.
*/
private var clearButton: MenuItem? = null
/**
* Subscription list to be cleared during [onDestroyView].
*/
private val subscriptions by lazy { CompositeSubscription() }
/**
* Map of subscriptions for active downloads.
*/
private val progressSubscriptions by lazy { HashMap<Download, Subscription>() }
/**
* Whether the download queue is running or not.
*/
private var isRunning: Boolean = false
companion object {
/**
* Creates a new instance of this fragment.
*
* @return a new instance of [DownloadFragment].
*/
fun newInstance(): DownloadFragment {
return DownloadFragment()
}
}
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedState: Bundle?): View {
return inflater.inflate(R.layout.fragment_download_queue, container, false)
}
override fun onViewCreated(view: View, savedState: Bundle?) {
setToolbarTitle(R.string.label_download_queue)
// Check if download queue is empty and update information accordingly.
setInformationView()
// Initialize adapter.
adapter = DownloadAdapter(activity)
recycler.adapter = adapter
// Set the layout manager for the recycler and fixed size.
recycler.layoutManager = LinearLayoutManager(activity)
recycler.setHasFixedSize(true)
// Suscribe to changes
subscriptions += presenter.downloadManager.runningSubject
.observeOn(AndroidSchedulers.mainThread())
.subscribe { onQueueStatusChange(it) }
subscriptions += presenter.getStatusObservable()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { onStatusChange(it) }
subscriptions += presenter.getProgressObservable()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { onUpdateDownloadedPages(it) }
}
override fun onDestroyView() {
for (subscription in progressSubscriptions.values) {
subscription.unsubscribe()
}
progressSubscriptions.clear()
subscriptions.clear()
super.onDestroyView()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.download_queue, menu)
// Set start button visibility.
startButton = menu.findItem(R.id.start_queue).apply {
isVisible = !isRunning && !presenter.downloadQueue.isEmpty()
}
// Set pause button visibility.
pauseButton = menu.findItem(R.id.pause_queue).apply {
isVisible = isRunning
}
// Set clear button visibility.
clearButton = menu.findItem(R.id.clear_queue).apply {
if (!presenter.downloadQueue.isEmpty()) {
isVisible = true
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.start_queue -> DownloadService.start(activity)
R.id.pause_queue -> DownloadService.stop(activity)
R.id.clear_queue -> {
DownloadService.stop(activity)
presenter.clearQueue()
}
else -> return super.onOptionsItemSelected(item)
}
return true
}
/**
* Called when the status of a download changes.
*
* @param download the download whose status has changed.
*/
private fun onStatusChange(download: Download) {
when (download.status) {
Download.DOWNLOADING -> {
observeProgress(download)
// Initial update of the downloaded pages
onUpdateDownloadedPages(download)
}
Download.DOWNLOADED -> {
unsubscribeProgress(download)
onUpdateProgress(download)
onUpdateDownloadedPages(download)
}
Download.ERROR -> unsubscribeProgress(download)
}
}
/**
* Observe the progress of a download and notify the view.
*
* @param download the download to observe its progress.
*/
private fun observeProgress(download: Download) {
val subscription = Observable.interval(50, TimeUnit.MILLISECONDS)
// Get the sum of percentages for all the pages.
.flatMap {
Observable.from(download.pages)
.map { it.progress }
.reduce { x, y -> x + y }
}
// Keep only the latest emission to avoid backpressure.
.onBackpressureLatest()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { progress ->
// Update the view only if the progress has changed.
if (download.totalProgress != progress) {
download.totalProgress = progress
onUpdateProgress(download)
}
}
// Avoid leaking subscriptions
progressSubscriptions.remove(download)?.unsubscribe()
progressSubscriptions.put(download, subscription)
}
/**
* Unsubscribes the given download from the progress subscriptions.
*
* @param download the download to unsubscribe.
*/
private fun unsubscribeProgress(download: Download) {
progressSubscriptions.remove(download)?.unsubscribe()
}
/**
* Called when the queue's status has changed. Updates the visibility of the buttons.
*
* @param running whether the queue is now running or not.
*/
private fun onQueueStatusChange(running: Boolean) {
isRunning = running
startButton?.isVisible = !running && !presenter.downloadQueue.isEmpty()
pauseButton?.isVisible = running
clearButton?.isVisible = !presenter.downloadQueue.isEmpty()
// Check if download queue is empty and update information accordingly.
setInformationView()
}
/**
* Called from the presenter to assign the downloads for the adapter.
*
* @param downloads the downloads from the queue.
*/
fun onNextDownloads(downloads: List<Download>) {
adapter.setItems(downloads)
}
fun onDownloadRemoved(position: Int) {
adapter.notifyItemRemoved(position)
}
/**
* Called when the progress of a download changes.
*
* @param download the download whose progress has changed.
*/
fun onUpdateProgress(download: Download) {
getHolder(download)?.notifyProgress()
}
/**
* Called when a page of a download is downloaded.
*
* @param download the download whose page has been downloaded.
*/
fun onUpdateDownloadedPages(download: Download) {
getHolder(download)?.notifyDownloadedPages()
}
/**
* Returns the holder for the given download.
*
* @param download the download to find.
* @return the holder of the download or null if it's not bound.
*/
private fun getHolder(download: Download): DownloadHolder? {
return recycler.findViewHolderForItemId(download.chapter.id!!) as? DownloadHolder
}
/**
* Set information view when queue is empty
*/
private fun setInformationView() {
(activity as MainActivity).updateEmptyView(presenter.downloadQueue.isEmpty(),
R.string.information_no_downloads, R.drawable.ic_file_download_black_128dp)
}
}
| app/src/main/java/eu/kanade/tachiyomi/ui/download/DownloadFragment.kt | 2601347616 |
class TestMutltipleCtorsWithJavadoc
/**
* Javadoc for 1st ctor
* @param x
*/(private val x: String?) {
private var y: String? = null
/**
* Javadoc for 2nd ctor
* @param x
* @param y
*/
constructor(x: String?, y: String?) : this(x) {
this.y = y
}
// ---
// Constructors
//
} | plugins/kotlin/j2k/new/tests/testData/newJ2k/issues/kt-19348.kt | 506878844 |
package foo
private fun dummy() {}
| plugins/kotlin/jps/jps-plugin/tests/testData/incremental/pureKotlin/moveFileWithChangingPackage/foo/dummy.kt | 3784136030 |
// "Create expected class in common module testModule_Common" "true"
// DISABLE-ERRORS
actual class <caret>My {
init {}
} | plugins/kotlin/idea/tests/testData/multiModuleQuickFix/createExpect/withInitializer/jvm/My.kt | 4146998159 |
package momentum.rt.resource
import java.io.InputStream
import java.io.Reader
import java.util.*
import kotlin.reflect.KClass
interface ResourceLoader {
/**
* Returns a character stream corresponding for resource in this path
* @throws ResourceNotFoundException if there is no resource in this path
*/
fun load(path: String): InputStream
}
class ResourceManager {
companion object {
fun makePath(path: String, sub: String): String {
// TODO: Ensure this is correct
if (sub.startsWith("/")) {
return sub
} else if (sub.isEmpty()) {
return path
} else if (path == "/") {
return sub
} else {
var pre = path
if (!pre.endsWith("/")) {
pre += "/"
}
return pre + sub
}
}
fun getFolder(path: String): String {
val idx = path.lastIndexOf('/')
return if (idx == -1) "/" else path.substring(0, idx)
}
}
enum class CacheOption {
Cache, NotCache
}
private data class AssetKey(val path: String, val type: KClass<*>)
private val loaders = ArrayList<ResourceLoader>()
private val cachedResources = HashMap<AssetKey, Any>()
fun registerLoader(loader: ResourceLoader) {
loaders.add(loader)
}
fun getStream(path: String): InputStream {
for (loader in loaders) {
try {
return loader.load(path)
} catch (e: ResourceNotFoundException) {
// not found for this loader, skip
}
}
throw ResourceNotFoundException(path)
}
inline fun<reified T: Any> load(path: String, cacheOption: CacheOption = CacheOption.Cache): T {
return load(T::class, path, cacheOption)
}
fun <T: Any> load(type: KClass<T>, path: String, cacheOption: CacheOption = CacheOption.Cache): T {
val key = AssetKey(path, type)
if (cachedResources.containsKey(key)) {
@Suppress("UNCHECKED_CAST")
return cachedResources[key] as T
} else {
val stream = getStream(path)
if (type == InputStream::class) {
@Suppress("UNCHECKED_CAST")
return stream as T
}
try {
val asset = AssetManager.load(this, type, path, stream)
if (cacheOption == CacheOption.Cache) {
cachedResources.put(key, asset as Any)
}
return asset
} finally {
stream.close()
}
}
}
}
class ResourceNotFoundException(path: String) : RuntimeException("Resource $path not found.") | Runtime/src/main/kotlin/momentum/rt/resource/ResourceManager.kt | 3274183372 |
package com.github.vhromada.catalog.web.utils
import com.github.vhromada.catalog.web.connector.entity.ChangeMusicRequest
import com.github.vhromada.catalog.web.connector.entity.Music
import com.github.vhromada.catalog.web.fo.MusicFO
import org.assertj.core.api.SoftAssertions.assertSoftly
/**
* A class represents utility class for music.
*
* @author Vladimir Hromada
*/
object MusicUtils {
/**
* Returns FO for music.
*
* @return FO for music
*/
fun getMusicFO(): MusicFO {
return MusicFO(
uuid = TestConstants.UUID,
name = TestConstants.NAME,
wikiEn = TestConstants.EN_WIKI,
wikiCz = TestConstants.CZ_WIKI,
mediaCount = TestConstants.MEDIA.toString(),
note = TestConstants.NOTE
)
}
/**
* Returns music.
*
* @return music
*/
fun getMusic(): Music {
return Music(
uuid = TestConstants.UUID,
name = TestConstants.NAME,
wikiEn = TestConstants.EN_WIKI,
wikiCz = TestConstants.CZ_WIKI,
mediaCount = TestConstants.MEDIA,
note = TestConstants.NOTE,
songsCount = 1,
length = TestConstants.LENGTH,
formattedLength = TestConstants.FORMATTED_LENGTH
)
}
/**
* Asserts music deep equals.
*
* @param expected expected music
* @param actual actual FO for music
*/
fun assertMusicDeepEquals(expected: Music, actual: MusicFO) {
assertSoftly {
it.assertThat(actual.uuid).isEqualTo(expected.uuid)
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.wikiEn).isEqualTo(expected.wikiEn)
it.assertThat(actual.wikiCz).isEqualTo(expected.wikiCz)
it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount.toString())
it.assertThat(actual.note).isEqualTo(expected.note)
}
}
/**
* Asserts FO for music and request deep equals.
*
* @param expected expected FO for music
* @param actual actual request for changing music
*/
fun assertRequestDeepEquals(expected: MusicFO, actual: ChangeMusicRequest) {
assertSoftly {
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.wikiEn).isEqualTo(expected.wikiEn)
it.assertThat(actual.wikiCz).isEqualTo(expected.wikiCz)
it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount!!.toInt())
it.assertThat(actual.note).isEqualTo(expected.note)
}
}
}
| web/src/test/kotlin/com/github/vhromada/catalog/web/utils/MusicUtils.kt | 419300159 |
package com.apollographql.apollo3.gradle.internal
import com.android.build.gradle.api.AndroidSourceSet
import org.gradle.api.file.SourceDirectorySet
import org.gradle.api.internal.HasConvention
// Copied from kotlin plugin
private fun Any.getConvention(name: String): Any? =
(this as HasConvention).convention.plugins[name]
// Copied from kotlin plugin
internal fun AndroidSourceSet.kotlinSourceSet(): SourceDirectorySet? {
val convention = (getConvention("kotlin") ?: getConvention("kotlin2js")) ?: return null
val kotlinSourceSet = convention.javaClass.interfaces.find { it.name == "org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet" }
val getKotlin = kotlinSourceSet?.methods?.find { it.name == "getKotlin" } ?: return null
return getKotlin(convention) as? SourceDirectorySet
}
| apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo3/gradle/internal/AndroidAndKotlinPluginFacade.kt | 239236217 |
// COMPILER_ARGUMENTS: -XXLanguage:+EnumEntries -opt-in=kotlin.ExperimentalStdlibApi
// WITH_STDLIB
enum class EnumClass
fun <T> functionWithGenericArg(a: T) {}
fun foo() {
functionWithGenericArg(EnumClass.values<caret>())
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/enumValuesSoftDeprecate/functionWithGenericArg.kt | 1835627669 |
/*
* 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.compose.ui.platform
/**
* Platform-specific mechanism for starting a monitor of global snapshot state writes
* in order to schedule the periodic dispatch of snapshot apply notifications.
* This process should remain platform-specific; it is tied to the threading and update model of
* a particular platform and framework target.
*
* Composition bootstrapping mechanisms for a particular platform/framework should call
* [ensureStarted] during setup to initialize periodic global snapshot notifications.
* For desktop, these notifications are always sent on [Dispatchers.Swing]. Other platforms
* may establish different policies for these notifications.
*/
internal expect object GlobalSnapshotManager {
fun ensureStarted()
}
| compose/ui/ui/src/skikoMain/kotlin/androidx/compose/ui/platform/GlobalSnapshotManager.skiko.kt | 1112133509 |
/*
* 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.bluetooth.core
import android.os.Build
import android.os.Bundle
import android.bluetooth.BluetoothGattCharacteristic as FwkBluetoothGattCharacteristic
import android.annotation.SuppressLint
import androidx.annotation.RequiresApi
import java.util.UUID
/**
* @hide
*/
class BluetoothGattCharacteristic internal constructor(
fwkCharacteristic: FwkBluetoothGattCharacteristic
) : Bundleable {
companion object {
/**
* Characteristic value format type float (32-bit float)
*/
const val FORMAT_FLOAT = FwkBluetoothGattCharacteristic.FORMAT_FLOAT
/**
* Characteristic value format type sfloat (16-bit float)
*/
const val FORMAT_SFLOAT = FwkBluetoothGattCharacteristic.FORMAT_SFLOAT
/**
* Characteristic value format type uint16
*/
const val FORMAT_SINT16 = FwkBluetoothGattCharacteristic.FORMAT_SINT16
/**
* Characteristic value format type sint32
*/
const val FORMAT_SINT32 = FwkBluetoothGattCharacteristic.FORMAT_SINT32
/**
* Characteristic value format type sint8
*/
const val FORMAT_SINT8 = FwkBluetoothGattCharacteristic.FORMAT_SINT8
/**
* Characteristic value format type uint16
*/
const val FORMAT_UINT16 = FwkBluetoothGattCharacteristic.FORMAT_UINT16
/**
* Characteristic value format type uint32
*/
const val FORMAT_UINT32 = FwkBluetoothGattCharacteristic.FORMAT_UINT32
/**
* Characteristic value format type uint8
*/
const val FORMAT_UINT8 = FwkBluetoothGattCharacteristic.FORMAT_UINT8
/**
* Characteristic property: Characteristic is broadcastable.
*/
const val PROPERTY_BROADCAST =
FwkBluetoothGattCharacteristic.PROPERTY_BROADCAST
/**
* Characteristic property: Characteristic is readable.
*/
const val PROPERTY_READ = FwkBluetoothGattCharacteristic.PROPERTY_READ
/**
* Characteristic property: Characteristic can be written without response.
*/
const val PROPERTY_WRITE_NO_RESPONSE =
FwkBluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE
/**
* Characteristic property: Characteristic can be written.
*/
const val PROPERTY_WRITE = FwkBluetoothGattCharacteristic.PROPERTY_WRITE
/**
* Characteristic property: Characteristic supports notification
*/
const val PROPERTY_NOTIFY = FwkBluetoothGattCharacteristic.PROPERTY_NOTIFY
/**
* Characteristic property: Characteristic supports indication
*/
const val PROPERTY_INDICATE =
FwkBluetoothGattCharacteristic.PROPERTY_BROADCAST
/**
* Characteristic property: Characteristic supports write with signature
*/
const val PROPERTY_SIGNED_WRITE =
FwkBluetoothGattCharacteristic.PROPERTY_SIGNED_WRITE
/**
* Characteristic property: Characteristic has extended properties
*/
const val PROPERTY_EXTENDED_PROPS =
FwkBluetoothGattCharacteristic.PROPERTY_EXTENDED_PROPS
/**
* Characteristic read permission
*/
const val PERMISSION_READ = FwkBluetoothGattCharacteristic.PERMISSION_READ
/**
* Characteristic permission: Allow encrypted read operations
*/
const val PERMISSION_READ_ENCRYPTED =
FwkBluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED
/**
* Characteristic permission: Allow reading with person-in-the-middle protection
*/
const val PERMISSION_READ_ENCRYPTED_MITM =
FwkBluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED_MITM
/**
* Characteristic write permission
*/
const val PERMISSION_WRITE = FwkBluetoothGattCharacteristic.PERMISSION_WRITE
/**
* Characteristic permission: Allow encrypted writes
*/
const val PERMISSION_WRITE_ENCRYPTED =
FwkBluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED
/**
* Characteristic permission: Allow encrypted writes with person-in-the-middle protection
*/
const val PERMISSION_WRITE_ENCRYPTED_MITM =
FwkBluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED_MITM
/**
* Characteristic permission: Allow signed write operations
*/
const val PERMISSION_WRITE_SIGNED =
FwkBluetoothGattCharacteristic.PERMISSION_WRITE_SIGNED
/**
* Characteristic permission: Allow signed write operations with
* person-in-the-middle protection
*/
const val PERMISSION_WRITE_SIGNED_MITM =
FwkBluetoothGattCharacteristic.PERMISSION_WRITE_SIGNED_MITM
/**
* Write characteristic, requesting acknowledgement by the remote device
*/
const val WRITE_TYPE_DEFAULT =
FwkBluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
/**
* Write characteristic without requiring a response by the remote device
*/
const val WRITE_TYPE_NO_RESPONSE =
FwkBluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
/**
* Write characteristic including authentication signature
*/
const val WRITE_TYPE_SIGNED =
FwkBluetoothGattCharacteristic.WRITE_TYPE_SIGNED
internal fun keyForField(field: Int): String {
return field.toString(Character.MAX_RADIX)
}
/**
* A companion object to create [BluetoothGattCharacteristic] from bundle
*/
val CREATOR: Bundleable.Creator<BluetoothGattCharacteristic> =
if (Build.VERSION.SDK_INT >= 24) {
GattCharacteristicImplApi24.CREATOR
} else {
GattCharacteristicImplApi21.CREATOR
}
}
/**
* Implementation based on version
*/
private val impl: GattCharacteristicImpl =
if (Build.VERSION.SDK_INT >= 24) {
GattCharacteristicImplApi24(fwkCharacteristic, this)
} else {
GattCharacteristicImplApi21(fwkCharacteristic, this)
}
/**
* Underlying framework's [android.bluetooth.BluetoothGattCharacteristic]
*/
internal val fwkCharacteristic
get() = impl.fwkCharacteristic
/**
* the UUID of this characteristic.
*/
val uuid
get() = impl.uuid
/**
* Characteristic properties
*/
val properties
get() = impl.properties
/**
* Write type for this characteristic.
*/
val permissions
get() = impl.permissions
/**
* Write type for this characteristic.
*/
val instanceId
get() = impl.instanceId
/**
* Write type for this characteristic.
*/
var writeType: Int
get() = impl.writeType
set(value) {
impl.writeType = value
}
/**
* Library's [BluetoothGattDescriptor] list that this characteristic owns
*/
val descriptors: List<BluetoothGattDescriptor>
get() = impl.descriptors
/**
* Library's [BluetoothGattService] that this belongs to
*/
var service: BluetoothGattService?
get() = impl.service
internal set(value) {
impl.service = value
}
/**
* Create a new BluetoothGattCharacteristic.
*
* @param uuid The UUID for this characteristic
* @param properties Properties of this characteristic
* @param permissions Permissions for this characteristic
*/
constructor (uuid: UUID, properties: Int, permissions: Int) : this(
FwkBluetoothGattCharacteristic(uuid, properties, permissions)
)
/**
* Adds a descriptor to this characteristic.
*
* @param descriptor Descriptor to be added to this characteristic.
* @return true, if the descriptor was added to the characteristic
*/
fun addDescriptor(descriptor: BluetoothGattDescriptor): Boolean {
return impl.addDescriptor(descriptor)
}
/**
* Get a descriptor by UUID
*/
fun getDescriptor(uuid: UUID): BluetoothGattDescriptor? {
return impl.getDescriptor(uuid)
}
/**
* Create a [Bundle] from this object
*/
override fun toBundle(): Bundle {
return impl.toBundle()
}
private interface GattCharacteristicImpl : Bundleable {
val fwkCharacteristic: FwkBluetoothGattCharacteristic
val uuid: UUID
val properties: Int
val permissions: Int
val instanceId: Int
var writeType: Int
val descriptors: List<BluetoothGattDescriptor>
var service: BluetoothGattService?
fun addDescriptor(descriptor: BluetoothGattDescriptor): Boolean
fun getDescriptor(uuid: UUID): BluetoothGattDescriptor?
override fun toBundle(): Bundle
}
private open class GattCharacteristicImplApi21(
final override val fwkCharacteristic: FwkBluetoothGattCharacteristic,
private val characteristic: BluetoothGattCharacteristic,
) : GattCharacteristicImpl {
companion object {
internal const val FIELD_FWK_CHARACTERISTIC_UUID = 1
internal const val FIELD_FWK_CHARACTERISTIC_INSTANCE_ID = 2
internal const val FIELD_FWK_CHARACTERISTIC_PROPERTIES = 3
internal const val FIELD_FWK_CHARACTERISTIC_PERMISSIONS = 4
internal const val FIELD_FWK_CHARACTERISTIC_WRITE_TYPE = 5
internal const val FIELD_FWK_CHARACTERISTIC_KEY_SIZE = 6
internal const val FIELD_FWK_CHARACTERISTIC_DESCRIPTORS = 7
val CREATOR: Bundleable.Creator<BluetoothGattCharacteristic> =
object : Bundleable.Creator<BluetoothGattCharacteristic> {
@SuppressLint("SoonBlockedPrivateApi")
override fun fromBundle(bundle: Bundle): BluetoothGattCharacteristic {
val uuid = bundle.getString(keyForField(FIELD_FWK_CHARACTERISTIC_UUID))
?: throw IllegalArgumentException("Bundle doesn't include uuid")
val instanceId =
bundle.getInt(keyForField(FIELD_FWK_CHARACTERISTIC_INSTANCE_ID), 0)
val properties =
bundle.getInt(keyForField(FIELD_FWK_CHARACTERISTIC_PROPERTIES), -1)
val permissions =
bundle.getInt(keyForField(FIELD_FWK_CHARACTERISTIC_PERMISSIONS), -1)
val writeType =
bundle.getInt(keyForField(FIELD_FWK_CHARACTERISTIC_WRITE_TYPE), -1)
val keySize =
bundle.getInt(keyForField(FIELD_FWK_CHARACTERISTIC_KEY_SIZE), -1)
if (permissions == -1) {
throw IllegalArgumentException("Bundle doesn't include permission")
}
if (properties == -1) {
throw IllegalArgumentException("Bundle doesn't include properties")
}
if (writeType == -1) {
throw IllegalArgumentException("Bundle doesn't include writeType")
}
if (keySize == -1) {
throw IllegalArgumentException("Bundle doesn't include keySize")
}
val fwkCharacteristicWithoutPrivateField = FwkBluetoothGattCharacteristic(
UUID.fromString(uuid),
properties,
permissions,
)
val fwkCharacteristic = fwkCharacteristicWithoutPrivateField.runCatching {
this.writeType = writeType
this.javaClass.getDeclaredField("mKeySize").let {
it.isAccessible = true
it.setInt(this, keySize)
}
this.javaClass.getDeclaredField("mInstanceId").let {
it.isAccessible = true
it.setInt(this, instanceId)
}
this
}.getOrDefault(fwkCharacteristicWithoutPrivateField)
val gattCharacteristic = BluetoothGattCharacteristic(fwkCharacteristic)
Utils.getParcelableArrayListFromBundle(
bundle,
keyForField(FIELD_FWK_CHARACTERISTIC_DESCRIPTORS),
Bundle::class.java
).forEach {
gattCharacteristic.addDescriptor(
BluetoothGattDescriptor.CREATOR.fromBundle(it)
)
}
return gattCharacteristic
}
}
}
override val uuid: UUID
get() = fwkCharacteristic.uuid
override val properties
get() = fwkCharacteristic.properties
override val permissions
get() = fwkCharacteristic.permissions
override val instanceId
get() = fwkCharacteristic.instanceId
override var writeType: Int
get() = fwkCharacteristic.writeType
set(value) {
fwkCharacteristic.writeType = value
}
private var _descriptors = mutableListOf<BluetoothGattDescriptor>()
override val descriptors
get() = _descriptors.toList()
override var service: BluetoothGattService? = null
init {
fwkCharacteristic.descriptors.forEach {
val descriptor = BluetoothGattDescriptor(it)
_descriptors.add(descriptor)
descriptor.characteristic = characteristic
}
}
override fun addDescriptor(
descriptor: BluetoothGattDescriptor,
): Boolean {
return if (fwkCharacteristic.addDescriptor(descriptor.fwkDescriptor)) {
_descriptors.add(descriptor)
descriptor.characteristic = characteristic
true
} else {
false
}
}
override fun getDescriptor(uuid: UUID): BluetoothGattDescriptor? {
return _descriptors.firstOrNull {
it.uuid == uuid
}
}
override fun toBundle(): Bundle {
assert(Build.VERSION.SDK_INT < 24)
val bundle = Bundle()
bundle.putString(keyForField(FIELD_FWK_CHARACTERISTIC_UUID), uuid.toString())
bundle.putInt(keyForField(FIELD_FWK_CHARACTERISTIC_INSTANCE_ID), instanceId)
bundle.putInt(keyForField(FIELD_FWK_CHARACTERISTIC_PROPERTIES), properties)
bundle.putInt(keyForField(FIELD_FWK_CHARACTERISTIC_PERMISSIONS), permissions)
bundle.putInt(keyForField(FIELD_FWK_CHARACTERISTIC_WRITE_TYPE), writeType)
// Asserted, this will always work
if (Build.VERSION.SDK_INT < 24) {
bundle.putInt(
keyForField(FIELD_FWK_CHARACTERISTIC_KEY_SIZE),
fwkCharacteristic.javaClass.getDeclaredField("mKeySize").runCatching {
this.isAccessible = true
this.getInt(fwkCharacteristic)
}.getOrDefault(16) // 16 is the default value in framework
)
}
val descriptorBundles = ArrayList(descriptors.map { it.toBundle() })
bundle.putParcelableArrayList(
keyForField(FIELD_FWK_CHARACTERISTIC_DESCRIPTORS),
descriptorBundles
)
return bundle
}
}
@RequiresApi(Build.VERSION_CODES.N)
private class GattCharacteristicImplApi24(
fwkCharacteristic: FwkBluetoothGattCharacteristic,
characteristic: BluetoothGattCharacteristic,
) : GattCharacteristicImplApi21(fwkCharacteristic, characteristic) {
companion object {
internal const val FIELD_FWK_CHARACTERISTIC = 0
val CREATOR: Bundleable.Creator<BluetoothGattCharacteristic> =
object : Bundleable.Creator<BluetoothGattCharacteristic> {
@Suppress("deprecation")
override fun fromBundle(bundle: Bundle): BluetoothGattCharacteristic {
val fwkCharacteristic =
Utils.getParcelableFromBundle(
bundle,
keyForField(FIELD_FWK_CHARACTERISTIC),
FwkBluetoothGattCharacteristic::class.java
) ?: throw IllegalArgumentException(
"Bundle doesn't include framework characteristic"
)
return BluetoothGattCharacteristic(fwkCharacteristic)
}
}
}
override fun toBundle(): Bundle {
val bundle = Bundle()
bundle.putParcelable(
keyForField(FIELD_FWK_CHARACTERISTIC),
fwkCharacteristic
)
return bundle
}
}
}
| bluetooth/bluetooth-core/src/main/java/androidx/bluetooth/core/BluetoothGattCharacteristic.kt | 2668103116 |
package com.kamer.orny.presentation.main
import com.kamer.orny.data.android.ActivityHolder
import com.kamer.orny.presentation.addexpense.AddExpenseActivity
import com.kamer.orny.presentation.settings.SettingsActivity
import javax.inject.Inject
class MainRouterImpl @Inject constructor(
val activityHolder: ActivityHolder
) : MainRouter {
override fun openAddExpenseScreen() {
activityHolder.getActivity()?.run { startActivity(AddExpenseActivity.getIntent(this)) }
}
override fun openSettingsScreen() {
activityHolder.getActivity()?.run { startActivity(SettingsActivity.getIntent(this)) }
}
} | app/src/main/kotlin/com/kamer/orny/presentation/main/MainRouterImpl.kt | 1968820562 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material.icons.generator.tasks
import androidx.compose.material.icons.generator.CoreIcons
import androidx.compose.material.icons.generator.IconWriter
import org.gradle.api.Project
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.bundling.Jar
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import java.io.File
/**
* Task responsible for converting core icons from xml to a programmatic representation.
*/
@CacheableTask
open class CoreIconGenerationTask : IconGenerationTask() {
override fun run() =
IconWriter(loadIcons()).generateTo(generatedSrcMainDirectory) { it in CoreIcons }
companion object {
/**
* Registers [CoreIconGenerationTask] in [project].
*/
@Suppress("DEPRECATION") // BaseVariant
fun register(project: Project, variant: com.android.build.gradle.api.BaseVariant? = null) {
val (task, buildDirectory) = project.registerGenerationTask(
"generateCoreIcons",
CoreIconGenerationTask::class.java,
variant
)
// Multiplatform
if (variant == null) {
registerIconGenerationTask(project, task, buildDirectory)
}
// AGP
else variant.registerIconGenerationTask(project, task, buildDirectory)
}
}
}
/**
* Task responsible for converting extended icons from xml to a programmatic representation.
*/
@CacheableTask
open class ExtendedIconGenerationTask : IconGenerationTask() {
override fun run() =
IconWriter(loadIcons()).generateTo(generatedSrcMainDirectory) { it !in CoreIcons }
companion object {
/**
* Registers [ExtendedIconGenerationTask] in [project]. (for use with mpp)
*/
@Suppress("DEPRECATION") // BaseVariant
fun register(project: Project, variant: com.android.build.gradle.api.BaseVariant? = null) {
val (task, buildDirectory) = project.registerGenerationTask(
"generateExtendedIcons",
ExtendedIconGenerationTask::class.java,
variant
)
// Multiplatform
if (variant == null) {
registerIconGenerationTask(project, task, buildDirectory)
}
// AGP
else variant.registerIconGenerationTask(project, task, buildDirectory)
}
/**
* Registers the icon generation task just for source jar generation, and not for
* compilation. This is temporarily needed since we manually parallelize compilation in
* material-icons-extended for the AGP build. When we remove that parallelization code,
* we can remove this too.
*/
@JvmStatic
@Suppress("DEPRECATION") // BaseVariant
fun registerSourceJarOnly(
project: Project,
variant: com.android.build.gradle.api.BaseVariant
) {
// Setup the source jar task if this is the release variant
if (variant.name == "release") {
val (task, buildDirectory) = project.registerGenerationTask(
"generateExtendedIcons",
ExtendedIconGenerationTask::class.java,
variant
)
val generatedSrcMainDirectory = buildDirectory.resolve(GeneratedSrcMain)
project.addToSourceJar(generatedSrcMainDirectory, task)
}
}
}
}
/**
* Helper to register [task] that outputs to [buildDirectory] as the Kotlin source generating
* task for [project].
*/
private fun registerIconGenerationTask(
project: Project,
task: TaskProvider<*>,
buildDirectory: File
) {
val sourceSet = project.getMultiplatformSourceSet(KotlinSourceSet.COMMON_MAIN_SOURCE_SET_NAME)
val generatedSrcMainDirectory = buildDirectory.resolve(IconGenerationTask.GeneratedSrcMain)
sourceSet.kotlin.srcDir(project.files(generatedSrcMainDirectory).builtBy(task))
// add it to the multiplatform sources as well.
project.tasks.named("multiplatformSourceJar", Jar::class.java).configure {
it.from(task.map { generatedSrcMainDirectory })
}
project.addToSourceJar(generatedSrcMainDirectory, task)
}
/**
* Helper to register [task] as the java source generating task that outputs to [buildDirectory].
*/
@Suppress("DEPRECATION") // BaseVariant
private fun com.android.build.gradle.api.BaseVariant.registerIconGenerationTask(
project: Project,
task: TaskProvider<*>,
buildDirectory: File
) {
val generatedSrcMainDirectory = buildDirectory.resolve(IconGenerationTask.GeneratedSrcMain)
registerJavaGeneratingTask(task, generatedSrcMainDirectory)
// Setup the source jar task if this is the release variant
if (name == "release") {
project.addToSourceJar(generatedSrcMainDirectory, task)
}
}
/**
* Adds the contents of [buildDirectory] to the source jar generated for this [Project] by [task]
*/
// TODO: b/191485164 remove when AGP lets us get generated sources from a TestedExtension or
// similar, then we can just add generated sources in SourceJarTaskHelper for all projects,
// instead of needing one-off support here.
private fun Project.addToSourceJar(buildDirectory: File, task: TaskProvider<*>) {
afterEvaluate {
val sourceJar = tasks.named("sourceJarRelease", Jar::class.java)
sourceJar.configure {
// Generating source jars requires the generation task to run first. This shouldn't
// be needed for the MPP build because we use builtBy to set up the dependency
// (https://github.com/gradle/gradle/issues/17250) but the path is different for AGP,
// so we will still need this for the AGP build.
it.dependsOn(task)
it.from(buildDirectory)
}
}
}
| compose/material/material/icons/generator/src/main/kotlin/androidx/compose/material/icons/generator/tasks/IconSourceTasks.kt | 922239607 |
package de.droidcon.berlin2018.schedule.backend.data2018.mapping
import com.google.auto.value.AutoValue
import de.droidcon.berlin2018.model.Session
import de.droidcon.berlin2018.model.Speaker
import org.threeten.bp.Instant
@AutoValue
abstract class SimpleSession : Session {
companion object {
fun create(
id: String,
title: String?,
description: String?,
tags: String?,
locationId: String?,
locationName: String?,
startTime: Instant?,
endTime: Instant?,
speakers: List<Speaker>?,
favorite: Boolean
): Session = AutoValue_SimpleSession(
id,
title,
description,
tags,
locationId,
locationName,
startTime,
endTime,
speakers,
favorite
)
}
}
| businesslogic/schedule/src/main/java/de/droidcon/berlin2018/schedule/backend/data2018/mapping/SimpleSession.kt | 1259779679 |
// 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.projectModel
import java.io.Serializable
interface ArgsInfo<T, R> : Serializable {
val currentCompilerArguments: T
val defaultCompilerArguments: T
val dependencyClasspath: Collection<R>
} | plugins/kotlin/base/project-model/src/org/jetbrains/kotlin/idea/projectModel/ArgsInfo.kt | 2896910032 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.SymbolicEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class FacetTestEntityImpl(val dataSource: FacetTestEntityData) : FacetTestEntity, WorkspaceEntityBase() {
companion object {
internal val MODULE_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleTestEntity::class.java, FacetTestEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
MODULE_CONNECTION_ID,
)
}
override val data: String
get() = dataSource.data
override val moreData: String
get() = dataSource.moreData
override val module: ModuleTestEntity
get() = snapshot.extractOneToManyParent(MODULE_CONNECTION_ID, this)!!
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: FacetTestEntityData?) : ModifiableWorkspaceEntityBase<FacetTestEntity, FacetTestEntityData>(
result), FacetTestEntity.Builder {
constructor() : this(FacetTestEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity FacetTestEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDataInitialized()) {
error("Field FacetTestEntity#data should be initialized")
}
if (!getEntityData().isMoreDataInitialized()) {
error("Field FacetTestEntity#moreData should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToManyParent<WorkspaceEntityBase>(MODULE_CONNECTION_ID, this) == null) {
error("Field FacetTestEntity#module should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] == null) {
error("Field FacetTestEntity#module should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as FacetTestEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.data != dataSource.data) this.data = dataSource.data
if (this.moreData != dataSource.moreData) this.moreData = dataSource.moreData
if (parents != null) {
val moduleNew = parents.filterIsInstance<ModuleTestEntity>().single()
if ((this.module as WorkspaceEntityBase).id != (moduleNew as WorkspaceEntityBase).id) {
this.module = moduleNew
}
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData(true).data = value
changedProperty.add("data")
}
override var moreData: String
get() = getEntityData().moreData
set(value) {
checkModificationAllowed()
getEntityData(true).moreData = value
changedProperty.add("moreData")
}
override var module: ModuleTestEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(MODULE_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
MODULE_CONNECTION_ID)]!! as ModuleTestEntity
}
else {
this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleTestEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*, *>) {
val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(MODULE_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*, *>) {
val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] = value
}
changedProperty.add("module")
}
override fun getEntityClass(): Class<FacetTestEntity> = FacetTestEntity::class.java
}
}
class FacetTestEntityData : WorkspaceEntityData.WithCalculableSymbolicId<FacetTestEntity>() {
lateinit var data: String
lateinit var moreData: String
fun isDataInitialized(): Boolean = ::data.isInitialized
fun isMoreDataInitialized(): Boolean = ::moreData.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<FacetTestEntity> {
val modifiable = FacetTestEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): FacetTestEntity {
return getCached(snapshot) {
val entity = FacetTestEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun symbolicId(): SymbolicEntityId<*> {
return FacetTestEntitySymbolicId(data)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return FacetTestEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return FacetTestEntity(data, moreData, entitySource) {
this.module = parents.filterIsInstance<ModuleTestEntity>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(ModuleTestEntity::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as FacetTestEntityData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
if (this.moreData != other.moreData) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as FacetTestEntityData
if (this.data != other.data) return false
if (this.moreData != other.moreData) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
result = 31 * result + moreData.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
result = 31 * result + moreData.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/FacetTestEntityImpl.kt | 4018219308 |
package com.intellij.codeInsight.codeVision.ui.model
import com.intellij.codeInsight.codeVision.CodeVisionAnchorKind
import com.intellij.codeInsight.codeVision.CodeVisionEntry
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.registry.Registry
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.reactive.map
import com.jetbrains.rd.util.throttleLast
import java.time.Duration
class CodeVisionListData(
val lifetime: Lifetime,
val projectModel: ProjectCodeVisionModel,
val rangeCodeVisionModel: RangeCodeVisionModel,
val inlay: Inlay<*>,
val anchoredLens: List<CodeVisionEntry>,
val anchor: CodeVisionAnchorKind
) {
companion object {
@JvmField
val KEY: Key<CodeVisionListData> = Key.create<CodeVisionListData>("CodeVisionListData")
}
var isPainted: Boolean = false
get() = field
set(value) {
if (field != value) {
field = value
if ((inlay.editor as? EditorImpl)?.isPurePaintingMode != true)
inlay.update()
}
}
val visibleLens: ArrayList<CodeVisionEntry> = ArrayList<CodeVisionEntry>()
private var throttle = false
init {
projectModel.hoveredInlay.map {
it == inlay
}.throttleLast(Duration.ofMillis(300), SwingScheduler).advise(lifetime) {
throttle = it
inlay.repaint()
}
updateVisible()
}
private fun updateVisible() {
val count = projectModel.maxVisibleLensCount[anchor]
visibleLens.clear()
if (count == null) {
visibleLens.addAll(anchoredLens)
return
}
val visibleCount = minOf(count, anchoredLens.size)
visibleLens.addAll(anchoredLens.subList(0, visibleCount))
}
fun state(): RangeCodeVisionModel.InlayState = rangeCodeVisionModel.state()
fun isMoreLensActive(): Boolean = throttle && Registry.`is`("editor.codeVision.more.inlay")
fun isHoveredEntry(entry: CodeVisionEntry): Boolean = projectModel.hoveredEntry.value == entry && projectModel.hoveredInlay.value == inlay
}
| platform/lang-impl/src/com/intellij/codeInsight/codeVision/ui/model/CodeVisionListData.kt | 539343521 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.ui.customization
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeBundle
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionStubBase
import com.intellij.openapi.util.IconLoader
import com.intellij.util.text.nullize
import org.jetbrains.annotations.Nls
import java.io.IOException
import javax.swing.Icon
internal val NONE = ActionIconInfo(null, IdeBundle.message("default.icons.none.text"), "", null)
internal val SEPARATOR = ActionIconInfo(null, "", "", null)
/**
* @param actionId id of the action that use this icon.
* @param iconPath path or URL of the icon.
* @param text template presentation text of the action or file name.
*/
internal class ActionIconInfo(val icon: Icon?,
@Nls val text: String,
val actionId: String?,
val iconPath: String?) {
val iconReference: String
get() = iconPath ?: actionId ?: error("Either actionId or iconPath should be set")
override fun toString(): String {
return text
}
}
internal fun getDefaultIcons(): List<ActionIconInfo> {
val icons = listOf(
getIconInfo(AllIcons.Toolbar.Unknown, IdeBundle.message("default.icons.unknown.text")),
getIconInfo(AllIcons.General.Add, IdeBundle.message("default.icons.add.text")),
getIconInfo(AllIcons.General.Remove, IdeBundle.message("default.icons.remove.text")),
getIconInfo(AllIcons.Actions.Edit, IdeBundle.message("default.icons.edit.text")),
getIconInfo(AllIcons.General.Filter, IdeBundle.message("default.icons.filter.text")),
getIconInfo(AllIcons.Actions.Find, IdeBundle.message("default.icons.find.text")),
getIconInfo(AllIcons.General.GearPlain, IdeBundle.message("default.icons.gear.plain.text")),
getIconInfo(AllIcons.Actions.ListFiles, IdeBundle.message("default.icons.list.files.text")),
getIconInfo(AllIcons.ToolbarDecorator.Export, IdeBundle.message("default.icons.export.text")),
getIconInfo(AllIcons.ToolbarDecorator.Import, IdeBundle.message("default.icons.import.text"))
)
return icons.filterNotNull()
}
private fun getIconInfo(icon: Icon, @Nls text: String): ActionIconInfo? {
val iconUrl = (icon as? IconLoader.CachedImageIcon)?.url
return iconUrl?.let { ActionIconInfo(icon, text, null, it.toString()) }
}
internal fun getAvailableIcons(): List<ActionIconInfo> {
val actionManager = ActionManager.getInstance()
return actionManager.getActionIdList("").mapNotNull { actionId ->
val action = actionManager.getActionOrStub(actionId) ?: return@mapNotNull null
val icon = if (action is ActionStubBase) {
val path = action.iconPath ?: return@mapNotNull null
IconLoader.findIcon(path, action.plugin.classLoader)
}
else {
val presentation = action.templatePresentation
presentation.getClientProperty(CustomActionsSchema.PROP_ORIGINAL_ICON) ?: presentation.icon
}
icon?.let { ActionIconInfo(it, action.templateText.nullize() ?: actionId, actionId, null) }
}
}
internal fun getCustomIcons(schema: CustomActionsSchema): List<ActionIconInfo> {
val actionManager = ActionManager.getInstance()
return schema.iconCustomizations.mapNotNull { (actionId, iconReference) ->
if (actionId == null || iconReference == null) return@mapNotNull null
val action = actionManager.getAction(iconReference)
if (action == null) {
val icon = try {
CustomActionsSchema.loadCustomIcon(iconReference)
}
catch (ex: IOException) {
null
}
if (icon != null) {
ActionIconInfo(icon, iconReference.substringAfterLast("/"), actionId, iconReference)
}
else null
}
else null
}
} | platform/platform-impl/src/com/intellij/ide/ui/customization/ActionIconInfo.kt | 1127847482 |
package entities.identifiers
import com.onyx.persistence.IManagedEntity
import com.onyx.persistence.annotations.Attribute
import com.onyx.persistence.annotations.Entity
import com.onyx.persistence.annotations.Identifier
import com.onyx.persistence.annotations.values.IdentifierGenerator
import entities.AbstractEntity
/**
* Created by timothy.osborn on 11/3/14.
*/
@Entity
class ImmutableSequenceIdentifierEntityForDelete : AbstractEntity(), IManagedEntity {
@Attribute
@Identifier(generator = IdentifierGenerator.SEQUENCE)
var identifier: Long = 0
@Attribute
var correlation: Int = 0
}
| onyx-database-tests/src/main/kotlin/entities/identifiers/ImmutableSequenceIdentifierEntityForDelete.kt | 1381766536 |
class A1<
x : String,
y : String,
>
class F<x : String, y : String>
class F2<
x : String,
y
: String,
>
class B1<
x : String,
y : String,
>
class C1<
x : String,
y : String,
>
class D1<
x : String,
y : String,
>
class A2<
x : String,
y : String,
z : String,
>
class B2<
x : String,
y : String,
z : String,
>
class C2<
x : String,
y : String,
z : String,
>
class D2<
x : String,
y : String,
z : String,
>
class A3<
x : String,
>
class B3<
x : String,
>
class C3<
x : String,
>
class D3<
x : String,
>
class A4<
x : String,
y : String,
z,
>
class B4<
x : String,
y,
z : String,
>
class C4<
x : String,
y : String,
z : String,
>
class D4<
x : String,
y,
z : String,
>
class E1<
x, y : String,
z : String,
>
class E2<
x : String, y : String, z : String,
>
class C<
z : String, v,
>
fun <
x : String,
y : String,
> a1() = Unit
fun <
x : String,
y : String,
> b1() = Unit
fun <
x : String,
y : String,
> c1() = Unit
fun <
x : String,
y : String,
> d1() = Unit
fun <
x : String,
y : String,
z : String,
> a2() = Unit
fun <
x : String,
y : String,
z : String,
> b2() = Unit
fun <
x : String,
y : String,
z : String,
> c2() = Unit
fun <
x : String,
y : String,
z : String,
> d2() = Unit
fun <
x : String,
> a3() = Unit
fun <
x : String,
> b3() = Unit
fun <
x : String,
> c3() = Unit
fun <
x : String,
> d3() = Unit
fun <
x : String,
y : String,
z : String,
> a4() = Unit
fun <
x : String,
y : String,
z : String,
> b4() = Unit
fun <
x : String,
y : String,
z : String,
> c4() = Unit
fun <
x : String,
y : String,
z : String,
> d4() = Unit
fun <
x,
> foo() {
}
fun <T> ag() {
}
fun <T> ag() {
}
fun <
T,
> ag() {
}
class C<
x : Int,
>
class G<
x : String, y : String,
/* */ z : String,
>
class G<
x : String, y : String,
/* */ /* */ z : String,
>()
class H<
x : String,
/*
*/
y : String,
z : String,
>
class J<
x : String, y : String, z : String,
/*
*/
>
class K<
x : String, y : String,
z : String,
>
class L<
x : String, y : String, z : String,
>
class C<
x : Int, // adad
>
class G<
x : String, y : String,
/* */ z : String, // adad
>
class G<
x : String, y : String,
/* */ /* */ z : String, /**/
>()
class H<
x : String,
/*
*/
y : String,
z : String,
/*
*/
>
class J<
x : String, y : String, z : String,
/*
*/
/**/
>
class K<
x : String, y : String,
z : String, // aw
>
class L<
x : String, y : String, z : String, //awd
>
// SET_TRUE: ALLOW_TRAILING_COMMA
| plugins/kotlin/idea/tests/testData/formatter/trailingComma/typeParameters/TypeParameterList.call.after.kt | 1426277275 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions
import com.intellij.featureStatistics.FeatureUsageTracker
import com.intellij.ide.IdeBundle.message
import com.intellij.ide.actions.Switcher.SwitcherPanel
import com.intellij.ide.lightEdit.LightEditCompatible
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CustomShortcutSet
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.DumbAwareToggleAction
import com.intellij.util.BitUtil.isSet
import com.intellij.util.ui.accessibility.ScreenReader
import java.awt.event.*
import java.util.function.Consumer
import javax.swing.AbstractAction
import javax.swing.JList
import javax.swing.KeyStroke
private fun forward(event: AnActionEvent) = true != event.inputEvent?.isShiftDown
internal class ShowSwitcherForwardAction : BaseSwitcherAction(true)
internal class ShowSwitcherBackwardAction : BaseSwitcherAction(false)
internal abstract class BaseSwitcherAction(val forward: Boolean?) : DumbAwareAction() {
private fun isControlTab(event: KeyEvent?) = event?.run { isControlDown && keyCode == KeyEvent.VK_TAB } ?: false
private fun isControlTabDisabled(event: AnActionEvent) = ScreenReader.isActive() && isControlTab(event.inputEvent as? KeyEvent)
override fun update(event: AnActionEvent) {
event.presentation.isEnabled = event.project != null && !isControlTabDisabled(event)
event.presentation.isVisible = forward == null
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun actionPerformed(event: AnActionEvent) {
val project = event.project ?: return
val switcher = Switcher.SWITCHER_KEY.get(project)
if (switcher != null && (!switcher.recent || forward != null)) {
switcher.go(forward ?: forward(event))
}
else {
FeatureUsageTracker.getInstance().triggerFeatureUsed("switcher")
SwitcherPanel(project, message("window.title.switcher"), event.inputEvent, null, forward ?: forward(event))
}
}
}
internal class ShowRecentFilesAction : LightEditCompatible, BaseRecentFilesAction(false)
internal class ShowRecentlyEditedFilesAction : BaseRecentFilesAction(true)
internal abstract class BaseRecentFilesAction(private val onlyEditedFiles: Boolean) : DumbAwareAction() {
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = event.project != null
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun actionPerformed(event: AnActionEvent) {
val project = event.project ?: return
Switcher.SWITCHER_KEY.get(project)?.cbShowOnlyEditedFiles?.apply { isSelected = !isSelected }
?: SwitcherPanel(project, message("title.popup.recent.files"), null, onlyEditedFiles, true)
}
}
internal class SwitcherIterateThroughItemsAction : DumbAwareAction() {
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = Switcher.SWITCHER_KEY.get(event.project) != null
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun actionPerformed(event: AnActionEvent) {
Switcher.SWITCHER_KEY.get(event.project)?.go(forward(event))
}
}
internal class SwitcherToggleOnlyEditedFilesAction : DumbAwareToggleAction() {
private fun getCheckBox(event: AnActionEvent) =
Switcher.SWITCHER_KEY.get(event.project)?.cbShowOnlyEditedFiles
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = getCheckBox(event) != null
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun isSelected(event: AnActionEvent) = getCheckBox(event)?.isSelected ?: false
override fun setSelected(event: AnActionEvent, selected: Boolean) {
getCheckBox(event)?.isSelected = selected
}
}
internal class SwitcherNextProblemAction : SwitcherProblemAction(true)
internal class SwitcherPreviousProblemAction : SwitcherProblemAction(false)
internal abstract class SwitcherProblemAction(val forward: Boolean) : DumbAwareAction() {
private fun getFileList(event: AnActionEvent) =
Switcher.SWITCHER_KEY.get(event.project)?.let { if (it.pinned) it.files else null }
private fun getErrorIndex(list: JList<SwitcherVirtualFile>): Int? {
val model = list.model ?: return null
val size = model.size
if (size <= 0) return null
val range = 0 until size
val start = when (forward) {
true -> list.leadSelectionIndex.let { if (range.first <= it && it < range.last) it + 1 else range.first }
else -> list.leadSelectionIndex.let { if (range.first < it && it <= range.last) it - 1 else range.last }
}
for (i in range) {
val index = when (forward) {
true -> (start + i).let { if (it > range.last) it - size else it }
else -> (start - i).let { if (it < range.first) it + size else it }
}
if (model.getElementAt(index)?.isProblemFile == true) return index
}
return null
}
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = getFileList(event) != null
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun actionPerformed(event: AnActionEvent) {
val list = getFileList(event) ?: return
val index = getErrorIndex(list) ?: return
list.selectedIndex = index
list.ensureIndexIsVisible(index)
}
}
internal class SwitcherListFocusAction(val fromList: JList<*>, val toList: JList<*>, vararg listActionIds: String)
: FocusListener, AbstractAction() {
override fun actionPerformed(event: ActionEvent) {
if (toList.isShowing) toList.requestFocusInWindow()
}
override fun focusLost(event: FocusEvent) = Unit
override fun focusGained(event: FocusEvent) {
val size = toList.model.size
if (size > 0) {
val fromIndex = fromList.selectedIndex
when {
fromIndex >= 0 -> toIndex = fromIndex.coerceAtMost(size - 1)
toIndex < 0 -> toIndex = 0
}
}
}
private var toIndex: Int
get() = toList.selectedIndex
set(index) {
fromList.clearSelection()
toList.selectedIndex = index
toList.ensureIndexIsVisible(index)
}
init {
listActionIds.forEach { fromList.actionMap.put(it, this) }
toList.addFocusListener(this)
toList.addListSelectionListener {
if (!fromList.isSelectionEmpty && !toList.isSelectionEmpty) {
fromList.selectionModel.clearSelection()
}
}
}
}
internal class SwitcherKeyReleaseListener(event: InputEvent?, val consumer: Consumer<InputEvent>) : KeyAdapter() {
private val wasAltDown = true == event?.isAltDown
private val wasAltGraphDown = true == event?.isAltGraphDown
private val wasControlDown = true == event?.isControlDown
private val wasMetaDown = true == event?.isMetaDown
val isEnabled = wasAltDown || wasAltGraphDown || wasControlDown || wasMetaDown
private val initialModifiers = if (!isEnabled) null
else StringBuilder().apply {
if (wasAltDown) append("alt ")
if (wasAltGraphDown) append("altGraph ")
if (wasControlDown) append("control ")
if (wasMetaDown) append("meta ")
}.toString()
val forbiddenMnemonic = (event as? KeyEvent)?.keyCode?.let { getMnemonic(it) }
fun getForbiddenMnemonic(keyStroke: KeyStroke) = when {
isSet(keyStroke.modifiers, InputEvent.ALT_DOWN_MASK) != wasAltDown -> null
isSet(keyStroke.modifiers, InputEvent.ALT_GRAPH_DOWN_MASK) != wasAltGraphDown -> null
isSet(keyStroke.modifiers, InputEvent.CTRL_DOWN_MASK) != wasControlDown -> null
isSet(keyStroke.modifiers, InputEvent.META_DOWN_MASK) != wasMetaDown -> null
else -> getMnemonic(keyStroke.keyCode)
}
private fun getMnemonic(keyCode: Int) = when (keyCode) {
in KeyEvent.VK_0..KeyEvent.VK_9 -> keyCode.toChar().toString()
in KeyEvent.VK_A..KeyEvent.VK_Z -> keyCode.toChar().toString()
else -> null
}
fun getShortcuts(vararg keys: String): CustomShortcutSet {
val modifiers = initialModifiers ?: return CustomShortcutSet.fromString(*keys)
val list = mutableListOf<String>()
keys.mapTo(list) { modifiers + it }
keys.mapTo(list) { modifiers + "shift " + it }
return CustomShortcutSet.fromStrings(list)
}
override fun keyReleased(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ALT -> if (wasAltDown) consumer.accept(keyEvent)
KeyEvent.VK_ALT_GRAPH -> if (wasAltGraphDown) consumer.accept(keyEvent)
KeyEvent.VK_CONTROL -> if (wasControlDown) consumer.accept(keyEvent)
KeyEvent.VK_META -> if (wasMetaDown) consumer.accept(keyEvent)
}
}
}
| platform/platform-impl/src/com/intellij/ide/actions/SwitcherActions.kt | 2194159640 |
// 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.gradleCodeInsightCommon
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.projectConfiguration.RepositoryDescription
abstract class SettingsScriptBuilder<T: PsiFile>(private val scriptFile: T) {
private val builder = StringBuilder(scriptFile.text)
private fun findBlockBody(blockName: String, startFrom: Int = 0): Int {
val blockOffset = builder.indexOf(blockName, startFrom)
if (blockOffset < 0) return -1
return builder.indexOf('{', blockOffset + 1) + 1
}
private fun getOrPrependTopLevelBlockBody(blockName: String): Int {
val blockBody = findBlockBody(blockName)
if (blockBody >= 0) return blockBody
builder.insert(0, "$blockName {}\n")
return findBlockBody(blockName)
}
private fun getOrAppendInnerBlockBody(blockName: String, offset: Int): Int {
val repositoriesBody = findBlockBody(blockName, offset)
if (repositoriesBody >= 0) return repositoriesBody
builder.insert(offset, "\n$blockName {}\n")
return findBlockBody(blockName, offset)
}
private fun appendExpressionToBlockIfAbsent(expression: String, offset: Int) {
var braceCount = 1
var blockEnd = offset
for (i in offset..builder.lastIndex) {
when (builder[i]) {
'{' -> braceCount++
'}' -> braceCount--
}
if (braceCount == 0) {
blockEnd = i
break
}
}
if (!builder.substring(offset, blockEnd).contains(expression.trim())) {
builder.insert(blockEnd, "\n$expression\n")
}
}
private fun getOrCreatePluginManagementBody() = getOrPrependTopLevelBlockBody("pluginManagement")
protected fun addPluginRepositoryExpression(expression: String) {
val repositoriesBody = getOrAppendInnerBlockBody("repositories", getOrCreatePluginManagementBody())
appendExpressionToBlockIfAbsent(expression, repositoriesBody)
}
fun addMavenCentralPluginRepository() {
addPluginRepositoryExpression("mavenCentral()")
}
abstract fun addPluginRepository(repository: RepositoryDescription)
fun addResolutionStrategy(pluginId: String) {
val resolutionStrategyBody = getOrAppendInnerBlockBody("resolutionStrategy", getOrCreatePluginManagementBody())
val eachPluginBody = getOrAppendInnerBlockBody("eachPlugin", resolutionStrategyBody)
appendExpressionToBlockIfAbsent(
"""
if (requested.id.id == "$pluginId") {
useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${'$'}{requested.version}")
}
""".trimIndent(),
eachPluginBody
)
}
fun addIncludedModules(modules: List<String>) {
builder.append(modules.joinToString(prefix = "include ", postfix = "\n") { "'$it'" })
}
fun build() = builder.toString()
abstract fun buildPsiFile(project: Project): T
}
| plugins/kotlin/gradle/code-insight-common/src/org/jetbrains/kotlin/idea/gradleCodeInsightCommon/SettingsScriptBuilder.kt | 2667352635 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.ui
import com.intellij.collaboration.auth.ui.AccountsPanelFactory.accountsPanel
import com.intellij.collaboration.util.ProgressIndicatorsProvider
import com.intellij.ide.DataManager
import com.intellij.openapi.components.service
import com.intellij.openapi.options.BoundConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.Disposer
import com.intellij.ui.layout.*
import org.jetbrains.plugins.github.GithubIcons
import org.jetbrains.plugins.github.authentication.accounts.GHAccountManager
import org.jetbrains.plugins.github.authentication.accounts.GithubProjectDefaultAccountHolder
import org.jetbrains.plugins.github.authentication.ui.GHAccountsDetailsProvider
import org.jetbrains.plugins.github.authentication.ui.GHAccountsHost
import org.jetbrains.plugins.github.authentication.ui.GHAccountsListModel
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.util.GithubSettings
import org.jetbrains.plugins.github.util.GithubUtil
internal class GithubSettingsConfigurable internal constructor(private val project: Project)
: BoundConfigurable(GithubUtil.SERVICE_DISPLAY_NAME, "settings.github") {
override fun createPanel(): DialogPanel {
val defaultAccountHolder = project.service<GithubProjectDefaultAccountHolder>()
val accountManager = service<GHAccountManager>()
val settings = GithubSettings.getInstance()
val indicatorsProvider = ProgressIndicatorsProvider().also {
Disposer.register(disposable!!, it)
}
val accountsModel = GHAccountsListModel(project)
val detailsProvider = GHAccountsDetailsProvider(indicatorsProvider, accountManager, accountsModel)
return panel {
row {
accountsPanel(accountManager, defaultAccountHolder, accountsModel, detailsProvider, disposable!!, GithubIcons.DefaultAvatar).also {
DataManager.registerDataProvider(it.component) { key ->
if (GHAccountsHost.KEY.`is`(key)) accountsModel
else null
}
}
}
row {
checkBox(GithubBundle.message("settings.clone.ssh"), settings::isCloneGitUsingSsh, settings::setCloneGitUsingSsh)
}
row {
cell {
label(GithubBundle.message("settings.timeout"))
intTextField({ settings.connectionTimeout / 1000 }, { settings.connectionTimeout = it * 1000 }, columns = 2, range = 0..60)
@Suppress("DialogTitleCapitalization")
label(GithubBundle.message("settings.timeout.seconds"))
}
}
}
}
} | plugins/github/src/org/jetbrains/plugins/github/ui/GithubSettingsConfigurable.kt | 314142968 |
/*
* 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.jsonrpc
import org.ethereum.core.Block
import org.ethereum.core.TransactionInfo
import org.ethereum.jsonrpc.TypeConverter.toJsonHex
class TransactionReceiptDTOExt(block: Block, txInfo: TransactionInfo) : TransactionReceiptDTO(block, txInfo) {
init {
val returnData = toJsonHex(txInfo.receipt.executionResult)
val error = txInfo.receipt.error
}
}
| free-ethereum-core/src/main/java/org/ethereum/jsonrpc/TransactionReceiptDTOExt.kt | 2690260869 |
// "Create class 'Foo'" "false"
// ACTION: Create extension function 'List<T>.Foo'
// ACTION: Do not show return expression hints
// ACTION: Rename reference
// ERROR: Unresolved reference: Foo
// WITH_STDLIB
class A<T>(val items: List<T>) {
fun test() = items.<caret>Foo<Int, String>(2, "2")
} | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/callExpression/typeArguments/extension.kt | 2329048106 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.commit.signature
import com.intellij.openapi.util.NlsSafe
import com.intellij.vcs.log.data.VcsCommitExternalStatus
internal sealed class GitCommitSignature : VcsCommitExternalStatus {
object NoSignature : GitCommitSignature()
class Verified(val user: @NlsSafe String, val fingerprint: @NlsSafe String) : GitCommitSignature()
class NotVerified(val reason: VerificationFailureReason) : GitCommitSignature()
object Bad : GitCommitSignature()
enum class VerificationFailureReason {
UNKNOWN,
EXPIRED,
EXPIRED_KEY,
REVOKED_KEY,
CANNOT_VERIFY
}
override fun toString(): String = ""
} | plugins/git4idea/src/git4idea/commit/signature/GitCommitSignature.kt | 3833010023 |
// "Remove @JvmField annotation" "true"
// WITH_STDLIB
interface I {
val x: Int
}
class C1 : I { <caret>@JvmField override val x: Int = 1 } | plugins/kotlin/idea/tests/testData/quickfix/removeAnnotation/jvmFieldOnOverridingProperty.kt | 4150539086 |
package com.haishinkit.codec
import android.media.MediaFormat
import java.nio.ByteBuffer
data class CodecOption(var key: String, var value: Any) {
internal fun apply(format: MediaFormat) {
when (true) {
value is Int -> format.setInteger(key, value as Int)
value is Long -> format.setLong(key, value as Long)
value is Float -> format.setFloat(key, value as Float)
value is String -> format.setString(key, value as String)
value is ByteBuffer -> format.setByteBuffer(key, value as ByteBuffer)
else -> throw IllegalArgumentException()
}
}
}
| haishinkit/src/main/java/com/haishinkit/codec/CodecOption.kt | 2461775822 |
// "Make 'bar' 'final'" "true"
interface Foo {
val bar: String
}
open class FooImpl : Foo {
override var bar: String = ""
<caret>private set
}
| plugins/kotlin/idea/tests/testData/quickfix/modifiers/overrideWithPrivateSetter1.kt | 2458833915 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.usages.impl.rules
import com.intellij.usages.ReadWriteAccessUsage
import com.intellij.usages.Usage
import com.intellij.usages.UsageTarget
import com.intellij.usages.rules.UsageFilteringRule
internal object ReadAccessFilteringRule : UsageFilteringRule {
override fun getActionId(): String = "UsageFiltering.ReadAccess"
override fun isVisible(usage: Usage, targets: Array<UsageTarget>): Boolean {
return usage !is ReadWriteAccessUsage || usage.isAccessedForWriting
}
}
| platform/usageView/src/com/intellij/usages/impl/rules/ReadAccessFilteringRule.kt | 3134060410 |
// "Replace with safe (?.) call" "true"
class Test(private val foo: Foo?) {
val baz = {
bar("")
bar("")
foo<caret>.s
}
}
class Foo {
val s = ""
}
fun bar(s: String) {} | plugins/kotlin/idea/tests/testData/quickfix/replaceWithSafeCall/lastStatementOfLambdaAsProperty.kt | 722678639 |
class C : (String) -> Boolean {
<caret>
} | plugins/kotlin/idea/tests/testData/codeInsight/overrideImplement/implementFunctionType.kt | 2691940807 |
package foo.bar
/**
* @see foo.B<caret>ar
*/
fun some() {
}
| plugins/kotlin/idea/tests/testData/kdoc/multiModuleResolve/samePackages/usage/foo/bar/usage.kt | 2529599349 |
fun foo() {
println("a")
if (1 > 2) {
println("foo")
}
}
class X {
fun foo() = 1
}
// SET_INT: KEEP_BLANK_LINES_BEFORE_RBRACE = 0
| plugins/kotlin/idea/tests/testData/formatter/BlankLinesBeforeRBrace.after.kt | 495873486 |
package c
import b.Test
fun bar() {
val t: Test = Test
}
| plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/moveObjectToPackage/after/c/specificImports.kt | 2536929632 |
/*
* Copyright 2021 Appmattus Limited
*
* 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.appmattus.layercache
import com.jakewharton.disklrucache.DiskLruCache
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
class DiskLruCacheWrapperShould {
private val lruCache = mock<DiskLruCache>()
private val snapshot = mock<DiskLruCache.Snapshot>()
private val wrappedCache: Cache<String, String> = Cache.fromDiskLruCache(lruCache)
// get
@Test
fun get_returns_value_from_cache() {
runBlocking {
// given value available in first cache only
whenever(snapshot.getString(0)).thenReturn("value")
whenever(lruCache.get("key")).thenReturn(snapshot)
// when we get the value
val result = wrappedCache.get("key")
// then we return the value
assertEquals("value", result)
}
}
@Test(expected = TestException::class)
fun get_throws() {
runBlocking {
// given value available in first cache only
whenever(lruCache.get("key")).then { throw TestException() }
// when we get the value
wrappedCache.get("key")
// then we throw an exception
}
}
// set
/*@Test
fun set_returns_value_from_cache() {
runBlocking {
// given
// when we set the value
wrappedCache.set("key", "value").await()
// then put is called
verify(lruCache).put("key", "value")
}
}
@Test(expected = TestException::class)
fun set_throws() {
runBlocking {
// given value available in first cache only
whenever(lruCache.put("key", "value")).then { throw TestException() }
// when we get the value
wrappedCache.set("key", "value").await()
// then we throw an exception
}
}
// evict
@Test
fun evict_returns_value_from_cache() {
runBlocking {
// given
// when we get the value
wrappedCache.evict("key").await()
// then we return the value
//assertEquals("value", result)
verify(lruCache).remove("key")
}
}
@Test(expected = TestException::class)
fun evict_throws() {
runBlocking {
// given value available in first cache only
whenever(lruCache.remove("key")).then { throw TestException() }
// when we get the value
wrappedCache.evict("key").await()
// then we throw an exception
}
}*/
}
| layercache-android/src/test/kotlin/com/appmattus/layercache/DiskLruCacheWrapperShould.kt | 3280748804 |
/*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.android.attrs
import java.io.File
public data class NameValue(
val name: String = "",
val value: String = "")
public data class Attr(
val name: String = "",
val format: List<String> = listOf(),
val flags: List<NameValue>? = null,
val enum: List<NameValue>? = null)
public val NoAttr: Attr = Attr()
public data class Styleable(
val name: String = "",
val attrs: List<Attr> = listOf())
public data class Attrs(
val free: List<Attr> = listOf(),
val styleables: Map<String, Styleable> = mapOf())
public fun readResource(filename: String): String {
return Attrs::class.java.classLoader.getResourceAsStream(filename)?.reader()?.readText()
?: File(filename).readText()
} | preview/attrs/src/org/jetbrains/kotlin/android/Attrs.kt | 1749218763 |
/*
* Copyright 2017-2022 Adobe.
*
* 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.adobe.testing.s3mock.its
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInfo
import software.amazon.awssdk.core.sync.RequestBody
import software.amazon.awssdk.services.s3.model.GetObjectTaggingRequest
import software.amazon.awssdk.services.s3.model.PutObjectRequest
import software.amazon.awssdk.services.s3.model.PutObjectTaggingRequest
import software.amazon.awssdk.services.s3.model.Tag
import software.amazon.awssdk.services.s3.model.Tagging
internal class ObjectTaggingV2IT : S3TestBase() {
@Test
fun testGetObjectTagging_noTags(testInfo: TestInfo) {
val bucketName = givenBucketV2(testInfo)
s3ClientV2.putObject(
{ b: PutObjectRequest.Builder -> b.bucket(bucketName).key("foo") },
RequestBody.fromString("foo")
)
assertThat(s3ClientV2.getObjectTagging { b: GetObjectTaggingRequest.Builder ->
b.bucket(
bucketName
).key("foo")
}
.tagSet())
.isEmpty()
}
@Test
fun testPutAndGetObjectTagging(testInfo: TestInfo) {
val bucketName = givenBucketV2(testInfo)
val key = "foo"
val tag1 = Tag.builder().key("tag1").value("foo").build()
val tag2 = Tag.builder().key("tag2").value("bar").build()
s3ClientV2.putObject(
{ b: PutObjectRequest.Builder -> b.bucket(bucketName).key(key) },
RequestBody.fromString("foo")
)
s3ClientV2.putObjectTagging(
PutObjectTaggingRequest.builder().bucket(bucketName).key(key)
.tagging(Tagging.builder().tagSet(tag1, tag2).build()).build()
)
assertThat(s3ClientV2.getObjectTagging { b: GetObjectTaggingRequest.Builder ->
b.bucket(
bucketName
).key(key)
}
.tagSet())
.contains(
tag1,
tag2
)
}
@Test
fun testPutObjectAndGetObjectTagging_withTagging(testInfo: TestInfo) {
val bucketName = givenBucketV2(testInfo)
s3ClientV2.putObject(
{ b: PutObjectRequest.Builder -> b.bucket(bucketName).key("foo").tagging("msv=foo") },
RequestBody.fromString("foo")
)
assertThat(s3ClientV2.getObjectTagging { b: GetObjectTaggingRequest.Builder ->
b.bucket(
bucketName
).key("foo")
}
.tagSet())
.contains(Tag.builder().key("msv").value("foo").build())
}
/**
* Verify that tagging with multiple tags can be obtained and returns expected content.
*/
@Test
fun testPutObjectAndGetObjectTagging_multipleTags(testInfo: TestInfo) {
val bucketName = givenBucketV2(testInfo)
val tag1 = Tag.builder().key("tag1").value("foo").build()
val tag2 = Tag.builder().key("tag2").value("bar").build()
s3ClientV2.putObject(
{ b: PutObjectRequest.Builder ->
b.bucket(bucketName).key("multipleFoo")
.tagging(Tagging.builder().tagSet(tag1, tag2).build())
}, RequestBody.fromString("multipleFoo")
)
assertThat(s3ClientV2.getObjectTagging { b: GetObjectTaggingRequest.Builder ->
b.bucket(
bucketName
).key("multipleFoo")
}
.tagSet())
.contains(
tag1,
tag2
)
}
}
| integration-tests/src/test/kotlin/com/adobe/testing/s3mock/its/ObjectTaggingV2IT.kt | 1594122386 |
package com.xmartlabs.bigbang.core.helper.ui
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog
import org.threeten.bp.Clock
import org.threeten.bp.LocalDate
object DatePickerDialogHelper {
/**
* Creates a [DatePickerDialog] instance.
*
* @param listener to be triggered when the user selects a date
* *
* @param clock to get the current date
* *
* @return the [DatePickerDialog] created instance
*/
fun createDialog(listener: ((LocalDate) -> Unit)?, clock: Clock) = createDialog(LocalDate.now(clock), listener)
/**
* Creates a [DatePickerDialog] instance with the `localDate` selected.
*
* @param localDate the selected start localDate
* *
* @param listener to be triggered when the user selects a localDate
* *
* @return the [DatePickerDialog] created instance
*/
fun createDialog(localDate: LocalDate, listener: ((LocalDate) -> Unit)?): DatePickerDialog {
val dialogCallBack = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
listener?.let { it(LocalDate.of(year, monthOfYear + 1, dayOfMonth)) }
}
val datePickerDialog = DatePickerDialog
.newInstance(dialogCallBack, localDate.year, localDate.monthValue - 1, localDate.dayOfMonth)
datePickerDialog.dismissOnPause(true)
return datePickerDialog
}
}
| core/src/main/java/com/xmartlabs/bigbang/core/helper/ui/DatePickerDialogHelper.kt | 2955246062 |
package sk.styk.martin.apkanalyzer.util.components
import android.view.View
import com.google.android.material.snackbar.Snackbar
import sk.styk.martin.apkanalyzer.util.TextInfo
data class SnackBarComponent(val message: TextInfo, val duration: Int = Snackbar.LENGTH_LONG,
val action: TextInfo? = null, val callback: View.OnClickListener? = null)
fun SnackBarComponent.toSnackbar(seekFromView: View) : Snackbar {
val snack = Snackbar.make(seekFromView, message.getText(seekFromView.context), duration)
if (action != null) {
snack.setAction(action.getText(seekFromView.context), callback)
}
return snack
}
| app/src/main/java/sk/styk/martin/apkanalyzer/util/components/SnackbarComponent.kt | 2219154338 |
package ch.rmy.android.framework.extensions
import android.os.Bundle
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
inline fun <T : Fragment> T.addArguments(block: Bundle.() -> Unit): T =
apply {
arguments = Bundle().apply(block)
}
fun Fragment.showSnackbar(@StringRes message: Int, long: Boolean = false) {
activity?.showSnackbar(message, long)
}
fun Fragment.showSnackbar(message: CharSequence, long: Boolean = false) {
activity?.showSnackbar(message, long)
}
| HTTPShortcuts/framework/src/main/kotlin/ch/rmy/android/framework/extensions/FragmentExtensions.kt | 996354981 |
// GENERATED
package com.fkorotkov.kubernetes.batch.v1beta1
import io.fabric8.kubernetes.api.model.batch.v1beta1.CronJobSpec as v1beta1_CronJobSpec
import io.fabric8.kubernetes.api.model.batch.v1beta1.JobTemplateSpec as v1beta1_JobTemplateSpec
fun v1beta1_CronJobSpec.`jobTemplate`(block: v1beta1_JobTemplateSpec.() -> Unit = {}) {
if(this.`jobTemplate` == null) {
this.`jobTemplate` = v1beta1_JobTemplateSpec()
}
this.`jobTemplate`.block()
}
| DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/batch/v1beta1/jobTemplate.kt | 538085622 |
package com.mapzen.erasermap.util
import android.app.Activity
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.SharedPreferences
import android.os.IBinder
import android.preference.PreferenceManager
import android.support.v4.app.NotificationCompat
import android.support.v4.app.TaskStackBuilder
import com.mapzen.erasermap.R
import com.mapzen.erasermap.service.NotificationService
import com.mapzen.erasermap.controller.MainActivity
class NotificationCreator(private val mainActivity: Activity) {
private var builder: NotificationCompat.Builder? = null
private var bigTextStyle: NotificationCompat.BigTextStyle? = null
private var stackBuilder: TaskStackBuilder? = null
private var notificationIntent: Intent? = null
private var exitNavigationIntent: Intent? = null
private var pendingNotificationIntent: PendingIntent? = null
private var pendingExitNavigationIntent: PendingIntent? = null
private val notificationManager: NotificationManager
private val serviceConnection: NotificationServiceConnection
private val preferences: SharedPreferences
private val serviceIntent: Intent
companion object {
const val EXIT_NAVIGATION = "exit_navigation"
const val NOTIFICATION_TAG_ROUTE = "route"
}
init {
notificationManager = mainActivity.getSystemService(
Context.NOTIFICATION_SERVICE) as NotificationManager
serviceConnection = NotificationServiceConnection(mainActivity)
preferences = PreferenceManager.getDefaultSharedPreferences(mainActivity)
serviceIntent = Intent(mainActivity, NotificationService::class.java)
}
/**
* All notifications created through this class should be killed using the
* {@link NotificationCreator#killNotification()}, do not call
* {@link NotificationManager#cancelAll()} directly
*
* Before we create a notification, we bind to a stub service so that when app is killed
* {@link MainActivity#onDestroy} is reliably called. This triggers a
* call to {@link NotificationCreator#killNotification} which removes notification from manager
*/
fun createNewNotification(title: String, content: String) {
initBuilder(title, content)
initBigTextStyle(title, content)
builder?.setStyle(bigTextStyle)
initNotificationIntent()
initExitNavigationIntent()
initStackBuilder(notificationIntent)
builder?.addAction(R.drawable.ic_dismiss, mainActivity.getString(R.string.exit_navigation),
pendingExitNavigationIntent)
builder?.setContentIntent(PendingIntent.getActivity(
mainActivity.applicationContext, 0, notificationIntent, 0))
mainActivity.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE)
notificationManager.notify(NOTIFICATION_TAG_ROUTE, 0, builder!!.build())
}
private fun initExitNavigationIntent() {
exitNavigationIntent = Intent(mainActivity, NotificationBroadcastReceiver::class.java)
exitNavigationIntent?.putExtra(EXIT_NAVIGATION, true)
pendingExitNavigationIntent = PendingIntent.getBroadcast(
mainActivity, 0, exitNavigationIntent, PendingIntent.FLAG_CANCEL_CURRENT)
}
private fun initNotificationIntent() {
notificationIntent = Intent(mainActivity, MainActivity::class.java)
notificationIntent?.setAction(Intent.ACTION_MAIN)
notificationIntent?.addCategory(Intent.CATEGORY_LAUNCHER)
notificationIntent?.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
pendingNotificationIntent = PendingIntent.getActivity(
mainActivity, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT)
}
private fun initStackBuilder(intent: Intent?) {
stackBuilder = TaskStackBuilder.create(mainActivity)
stackBuilder?.addParentStack(mainActivity.javaClass)
stackBuilder?.addNextIntent(intent)
}
private fun initBigTextStyle(title: String, content: String) {
bigTextStyle = NotificationCompat.BigTextStyle()
bigTextStyle?.setBigContentTitle(title)
bigTextStyle?.bigText(content)
}
private fun initBuilder(title: String, content: String) {
builder = NotificationCompat.Builder(mainActivity.baseContext)
builder?.setContentTitle(title)
builder?.setContentText(content)
builder?.setSmallIcon(R.drawable.ic_notif)
builder?.setPriority(NotificationCompat.PRIORITY_MAX)
builder?.setOngoing(true)
}
fun killNotification() {
notificationManager.cancelAll()
serviceConnection.service?.stopService(serviceIntent)
}
/**
* In charge of starting the stub service we bind to
*/
private class NotificationServiceConnection: ServiceConnection {
val activity: Activity
var service: NotificationService? = null
constructor(activity: Activity) {
this.activity = activity
}
override fun onServiceConnected(component: ComponentName?, inBinder: IBinder?) {
if (inBinder == null) {
return
}
val binder = inBinder as NotificationService.NotificationBinder
val intent: Intent = Intent(activity, NotificationService::class.java)
this.service = binder.service
binder.service.startService(intent)
}
override fun onServiceDisconnected(component: ComponentName?) {
}
}
}
| app/src/main/kotlin/com/mapzen/erasermap/util/NotificationCreator.kt | 715542399 |
package com.dreampany.framework.data.enums
/**
* Created by Hawladar Roman on 27/5/18.
* Dreampany Ltd
* [email protected]
*/
enum class EventType {
NEW
} | frame/src/main/kotlin/com/dreampany/framework/data/enums/EventType.kt | 484246320 |
package cz.united121.kotlin.Kotlin
import android.content.Context
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import cz.united121.kotlin.Java.MainActivity
import cz.united121.kotlin.Kotlin.UI.*
import cz.united121.kotlin.R
import kotlinx.android.synthetic.kotlin_layout.*
/**
* TODO add class description
* Created by Petr Lorenc[[email protected]] on {10/11/2015}
**/
public class KotlinClass : AppCompatActivity() {
override fun onCreate(savedInstanceState : Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.kotlin_layout)
var counter = 5
val counter2 : Int
counter2 = counter
hi_kotlin_button.setOnClickListener{
hi_kotlin.setText("Ahoj" + counter2 + " + " + counter++ )
var main = MainActivity()
main.functionInJava(applicationContext)
}
up.setOnClickListener{
foreground.animateUp()
}
down.setOnClickListener{
foreground.animateDown()
}
left.setOnClickListener{
foreground.animateLeft()
}
right.setOnClickListener{
foreground.animateRight()
}
scale.setOnClickListener {
foreground.scaleOut()
}
}
fun returnStringWithNoSpace(originalString: String, context : Context) {
Toast.makeText(context.getApplicationContext(), originalString.NoSpace() , Toast.LENGTH_SHORT).show()
}
}
fun returnStringWithNoSpace(originalString: String, context : Context) {
Toast.makeText(context.getApplicationContext(), originalString.NoSpace() , Toast.LENGTH_SHORT).show()
}
fun String.NoSpace() : String{
5.Add(5)
return this.replace(" ","")
}
fun Int.Add(a : Int) : Int{
return this + a;
} | app/src/main/java/cz/united121/kotlin/Kotlin/KotlinClass.kt | 4193368902 |
/**
* BreadWallet
*
* Created by Pablo Budelli <[email protected]> on 10/25/19.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.login
import android.content.Context
import com.breadwallet.tools.manager.BRSharedPrefs
import com.breadwallet.tools.security.BrdUserManager
import com.breadwallet.tools.security.isFingerPrintAvailableAndSetup
import com.breadwallet.tools.util.EventUtils
import com.breadwallet.ui.login.LoginScreen.E
import com.breadwallet.ui.login.LoginScreen.F
import drewcarlson.mobius.flow.subtypeEffectHandler
fun createLoginScreenHandler(
context: Context,
brdUser: BrdUserManager
) = subtypeEffectHandler<F, E> {
addAction<F.UnlockBrdUser> {
brdUser.unlock()
}
addFunction<F.CheckFingerprintEnable> {
E.OnFingerprintEnabled(
enabled = isFingerPrintAvailableAndSetup(context) && BRSharedPrefs.unlockWithFingerprint
)
}
addConsumer<F.TrackEvent> { effect ->
EventUtils.pushEvent(effect.eventName, effect.attributes)
}
} | app/src/main/java/com/breadwallet/ui/login/LoginScreenHandler.kt | 2893985376 |
package com.jaynewstrom.jsonDelight.sample.nested.folder
import com.jaynewstrom.jsonDelight.sample.JsonTestHelper
import org.fest.assertions.api.Assertions.assertThat
import org.junit.Test
class NestedFolderTest {
@Test fun testAllTheThings() {
val simple = JsonTestHelper().deserializeFile(Simple::class.java, "NestedFolderTest.json", this)
assertThat(simple.name).isEqualTo("Jay")
val json = JsonTestHelper().serialize(simple, Simple::class.java)
assertThat(json).isEqualTo("{\"name\":\"Jay\"}")
}
}
| tests/integration-tests/src/test/java/com/jaynewstrom/jsonDelight/sample/nested/folder/NestedFolderTest.kt | 801230728 |
/*
* 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.saga
import com.fasterxml.jackson.annotation.JsonTypeName
import com.netflix.spinnaker.clouddriver.event.AbstractSpinnakerEvent
import com.netflix.spinnaker.clouddriver.event.SpinnakerEvent
import com.netflix.spinnaker.clouddriver.saga.models.Saga
import com.netflix.spinnaker.kork.exceptions.SpinnakerException
/**
* Root event type for [Saga]s.
*/
interface SagaEvent : SpinnakerEvent
/**
* Warning: Do not use with Lombok @Value classes.
*/
abstract class AbstractSagaEvent : AbstractSpinnakerEvent(), SagaEvent
/**
* Emitted whenever a [Saga] is saved.
*
* This event does not attempt to find a difference in state, trading off persistence verbosity for a little bit
* of a simpler implementation.
*
* @param sequence The [Saga]'s latest sequence
*/
@JsonTypeName("sagaSaved")
class SagaSaved(
val sequence: Long
) : AbstractSagaEvent()
/**
* Emitted whenever an internal error has occurred while applying a [Saga].
*
* @param reason A human-readable cause for the error
* @param error The Exception (if any) that caused the error condition
* @param retryable Flags whether or not this error is recoverable
* @param data Additional data that can help with diagnostics of the error
*/
@JsonTypeName("sagaInternalErrorOccurred")
class SagaInternalErrorOccurred(
val reason: String,
val error: Exception? = null,
val retryable: Boolean = true,
val data: Map<String, String> = mapOf()
) : AbstractSagaEvent()
/**
* Emitted whenever an error has occurred within a [SagaAction] while applying a [Saga].
*
* @param actionName The Java simpleName of the handler
* @param error The Exception that caused the error condition
* @param retryable Flags whether or not this error is recoverable
*/
@JsonTypeName("sagaActionErrorOccurred")
class SagaActionErrorOccurred(
val actionName: String,
val error: Exception,
val retryable: Boolean
) : AbstractSagaEvent()
/**
* Informational log that can be added to a [Saga] for end-user feedback, as well as operational insight.
* This is a direct tie-in for the Kato Task Status concept with some additional bells and whistles.
*
* @param message A tuple message that allows passing end-user- and operator-focused messages
* @param diagnostics Additional metadata that can help provide context to the message
*/
@JsonTypeName("sagaLogAppended")
class SagaLogAppended(
val message: Message,
val diagnostics: Diagnostics? = null
) : AbstractSagaEvent() {
/**
* @param user An end-user friendly message
* @param system An operator friendly message
*/
data class Message(
val user: String? = null,
val system: String? = null
)
/**
* @param error An error, if one exists. This must be a [SpinnakerException] to provide retryable metadata
* @param data Additional metadata
*/
data class Diagnostics(
val error: SpinnakerException? = null,
val data: Map<String, String> = mapOf()
)
}
/**
* Emitted when all actions for a [Saga] have been applied.
*/
@JsonTypeName("sagaCompleted")
class SagaCompleted(
val success: Boolean
) : AbstractSagaEvent()
/**
* Emitted when a [Saga] enters a rollback state.
*/
@JsonTypeName("sagaRollbackStarted")
class SagaRollbackStarted : AbstractSagaEvent()
/**
* Emitted when all rollback actions for a [Saga] have been applied.
*/
@JsonTypeName("sagaRollbackCompleted")
class SagaRollbackCompleted : AbstractSagaEvent()
/**
* The root event type for all mutating [Saga] operations.
*/
interface SagaCommand : SagaEvent
/**
* The root event type for all [Saga] rollback operations.
*/
interface SagaRollbackCommand : SagaCommand
/**
* Marker event for recording that the work associated with a particular [SagaCommand] event has been completed.
*
* @param command The [SagaCommand] name
*/
@JsonTypeName("sagaCommandCompleted")
class SagaCommandCompleted(
val command: String
) : AbstractSagaEvent() {
fun matches(candidateCommand: Class<out SagaCommand>): Boolean =
candidateCommand.getAnnotation(JsonTypeName::class.java)?.value == command
}
/**
* A [SagaCommand] wrapper for [SagaAction]s that need to return more than one [SagaCommand].
*
* This event is unwrapped prior to being added to the event log; so all [SagaCommand]s defined within this
* wrapper will show up as their own distinct log entries.
*/
@JsonTypeName("sagaManyCommandsWrapper")
class ManyCommands(
command1: SagaCommand,
vararg extraCommands: SagaCommand
) : AbstractSagaEvent(), SagaCommand {
val commands = listOf(command1).plus(extraCommands)
}
| clouddriver-saga/src/main/kotlin/com/netflix/spinnaker/clouddriver/saga/events.kt | 830988587 |
/*
* Copyright 2019 Ross 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.locks.bukkit.event.lock
import com.rpkit.core.bukkit.event.RPKBukkitEvent
import org.bukkit.block.Block
import org.bukkit.event.Cancellable
import org.bukkit.event.HandlerList
class RPKBukkitBlockLockEvent(
override val block: Block
): RPKBukkitEvent(), RPKBlockLockEvent, Cancellable {
companion object {
@JvmStatic val handlerList = HandlerList()
}
private var cancel: Boolean = false
override fun isCancelled(): Boolean {
return cancel
}
override fun setCancelled(cancel: Boolean) {
this.cancel = cancel
}
override fun getHandlers(): HandlerList {
return handlerList
}
} | bukkit/rpk-lock-lib-bukkit/src/main/kotlin/com/rpkit/locks/bukkit/event/lock/RPKBukkitBlockLockEvent.kt | 1424691215 |
package com.github.developer__.extensions
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
/**
* Created by Jemo on 12/5/16.
*/
fun ImageView.loadImage(imgUrl: String?){
Glide.with(context).load(imgUrl).into(this)
}
fun ImageView.loadImage(imgDrawable: Drawable?){
this.setImageDrawable(imgDrawable)
}
fun View.stayVisibleOrGone(stay: Boolean){
this.visibility = if (stay) View.VISIBLE else View.GONE
} | beforeafterslider/src/main/java/com/github/developer__/extensions/Extensions.kt | 804945792 |
package org.evomaster.core.search.impact.impactinfocollection.sql
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.numeric.IntegerGene
import org.evomaster.core.search.gene.sql.SqlPrimaryKeyGene
import org.evomaster.core.search.impact.impactinfocollection.GeneImpact
import org.evomaster.core.search.impact.impactinfocollection.GeneImpactTest
import org.evomaster.core.search.impact.impactinfocollection.ImpactOptions
import org.evomaster.core.search.impact.impactinfocollection.MutatedGeneWithContext
import org.junit.jupiter.api.Test
/**
* created by manzh on 2019-10-09
*/
class SqlPrimaryGeneImpactTest : GeneImpactTest() {
override fun getGene(): Gene {
val gene = IntegerGene("gene", 0)
return SqlPrimaryKeyGene("primaryKey", tableName = "fake",gene = gene, uniqueId = 1L)
}
override fun checkImpactType(impact: GeneImpact) {
assert(impact is SqlPrimaryKeyGeneImpact)
}
override fun simulateMutation(original: Gene, geneToMutate: Gene, mutationTag: Int): MutatedGeneWithContext {
geneToMutate as SqlPrimaryKeyGene
val gene = geneToMutate.gene as IntegerGene
gene.value += if (gene.value + 1 > gene.getMaximum()) -1 else 1
return MutatedGeneWithContext(previous = original, current = geneToMutate)
}
@Test
fun testInsideGene(){
val gene = getGene()
val impact = initImpact(gene)
val pair = template(gene, impact, listOf(ImpactOptions.ONLY_IMPACT))
impact as SqlPrimaryKeyGeneImpact
assertImpact(impact.geneImpact, (pair.second as SqlPrimaryKeyGeneImpact).geneImpact, ImpactOptions.ONLY_IMPACT)
}
} | core/src/test/kotlin/org/evomaster/core/search/impact/impactinfocollection/sql/SqlPrimaryGeneImpactTest.kt | 2044452663 |
package net.ketc.numeri.presentation.view.activity.ui
import android.content.Context
import android.graphics.Color
import android.support.design.widget.AppBarLayout
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.NavigationView
import android.support.v4.widget.DrawerLayout
import android.support.v7.widget.Toolbar
import android.view.Gravity
import android.view.View
import android.view.ViewManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import net.ketc.numeri.R
import net.ketc.numeri.presentation.view.activity.MainActivity
import net.ketc.numeri.util.android.getResourceId
import net.ketc.numeri.util.android.startOf
import org.jetbrains.anko.*
import org.jetbrains.anko.appcompat.v7.toolbar
import org.jetbrains.anko.design.appBarLayout
import org.jetbrains.anko.design.coordinatorLayout
import org.jetbrains.anko.design.floatingActionButton
import org.jetbrains.anko.design.navigationView
import org.jetbrains.anko.support.v4.drawerLayout
class MainActivityUI : IMainActivityUI {
override lateinit var drawer: DrawerLayout
private set
override lateinit var navigation: NavigationView
private set
override lateinit var showAccountIndicator: ImageView
private set
override lateinit var navigationContent: RelativeLayout
private set
override lateinit var showAccountRelative: RelativeLayout
private set
override lateinit var addAccountButton: RelativeLayout
private set
override lateinit var accountsLinear: LinearLayout
private set
override lateinit var columnGroupWrapper: CoordinatorLayout
private set
override lateinit var toolbar: Toolbar
private set
override lateinit var tweetButton: FloatingActionButton
private set
override fun createView(ui: AnkoContext<MainActivity>) = with(ui) {
drawerLayout {
drawer = this
id = R.id.drawer
coordinatorLayout {
appBarLayout {
toolbar {
id = R.id.toolbar
toolbar = this
}.lparams(matchParent, wrapContent) {
scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or
AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL
}
}.lparams(matchParent, wrapContent)
coordinatorLayout {
columnGroupWrapper = this
id = R.id.column_group_wrapper_coordinator
}.lparams(matchParent, matchParent) {
behavior = AppBarLayout.ScrollingViewBehavior()
}
floatingActionButton {
tweetButton = this
image = ctx.getDrawable(R.drawable.ic_mode_edit_white_24dp)
size = FloatingActionButton.SIZE_AUTO
}.lparams {
margin = dimen(R.dimen.margin_medium)
anchorGravity = Gravity.BOTTOM or Gravity.END
anchorId = R.id.column_group_wrapper_coordinator
}
}
navigationView {
id = R.id.navigation
navigation = this
inflateMenu(R.menu.main_navigation)
addHeaderView(navigationHeader(ctx))
navigationContent()
}.lparams(wrapContent, matchParent) {
gravity = Gravity.START
}
}
}
private fun navigationHeader(ctx: Context) = ctx.relativeLayout {
lparams(matchParent, dip(160))
backgroundColor = Color.parseColor("#10505050")
imageView {
id = R.id.icon_image
image = ctx.getDrawable(R.mipmap.ic_launcher)
}.lparams(dimen(R.dimen.image_icon_large), dimen(R.dimen.image_icon_large)) {
topMargin = dimen(R.dimen.margin_medium)
marginStart = dimen(R.dimen.margin_medium)
}
relativeLayout {
showAccountRelative = this
id = R.id.show_account_relative
lparams(matchParent, dip(72)) {
alignParentBottom()
}
relativeLayout {
lparams {
alignParentBottom()
bottomMargin = dimen(R.dimen.margin_small)
}
backgroundResource = ctx.getResourceId(android.R.attr.selectableItemBackground)
textView {
id = R.id.user_name_text
text = "アカウント一覧"
lines = 1
}.lparams {
startOf(R.id.show_account_indicator)
alignParentStart()
centerVertically()
margin = dimen(R.dimen.margin_text_medium)
}
imageView {
showAccountIndicator = this
id = R.id.show_account_indicator
image = ctx.getDrawable(R.drawable.ic_expand_more_white_24dp)
backgroundColor = ctx.getColor(R.color.transparent)
scaleType = ImageView.ScaleType.CENTER_INSIDE
}.lparams(dip(16), dip(16)) {
alignParentEnd()
centerVertically()
marginEnd = dimen(R.dimen.margin_text_medium)
}
}
}
}
private fun ViewManager.navigationContent() = relativeLayout {
id = R.id.navigation_content
navigationContent = this
visibility = View.GONE
topPadding = dip(168)
lparams(matchParent, matchParent)
relativeLayout {
lparams(matchParent, matchParent)
linearLayout {
accountsLinear = this
id = R.id.accounts_linear
lparams(matchParent, wrapContent) {
backgroundColor = context.getColor(R.color.transparent)
}
orientation = LinearLayout.VERTICAL
}
relativeLayout {
addAccountButton = this
id = R.id.add_account_button
lparams(matchParent, dip(48)) {
below(R.id.accounts_linear)
}
backgroundResource = context.getResourceId(android.R.attr.selectableItemBackground)
isClickable = true
textView {
text = context.getString(R.string.add_account)
lines = 1
}.lparams(matchParent, wrapContent) {
centerVertically()
marginStart = dimen(R.dimen.margin_medium)
marginEnd = dimen(R.dimen.margin_medium)
}
}
}
}
}
interface IMainActivityUI : AnkoComponent<MainActivity> {
val toolbar: Toolbar
val drawer: DrawerLayout
val navigation: NavigationView
val showAccountIndicator: ImageView
val navigationContent: RelativeLayout
val showAccountRelative: RelativeLayout
val addAccountButton: RelativeLayout
val accountsLinear: LinearLayout
val columnGroupWrapper: CoordinatorLayout
val tweetButton: FloatingActionButton
} | app/src/main/kotlin/net/ketc/numeri/presentation/view/activity/ui/MainActivityUI.kt | 4237207912 |
package org.evomaster.core.search.structuralelement.individual
import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType
import org.evomaster.core.database.DbAction
import org.evomaster.core.database.schema.Column
import org.evomaster.core.database.schema.ColumnDataType
import org.evomaster.core.database.schema.ForeignKey
import org.evomaster.core.database.schema.Table
import org.evomaster.core.problem.rest.RestCallAction
import org.evomaster.core.problem.rest.RestIndividual
import org.evomaster.core.problem.rest.SampleType
import org.evomaster.core.problem.rest.param.BodyParam
import org.evomaster.core.search.gene.numeric.IntegerGene
import org.evomaster.core.search.gene.ObjectGene
import org.evomaster.core.search.gene.sql.SqlForeignKeyGene
import org.evomaster.core.search.gene.sql.SqlPrimaryKeyGene
import org.evomaster.core.search.structuralelement.StructuralElementBaseTest
import org.evomaster.core.search.structuralelement.resourcecall.ResourceNodeCluster
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
class RestIndividualStructureTest : StructuralElementBaseTest(){
override fun getStructuralElement(): RestIndividual {
val idColumn = Column("Id", ColumnDataType.INTEGER, 10,
primaryKey = true,
autoIncrement = false,
unique = false,
databaseType = DatabaseType.H2)
val foo = Table("Foo", setOf(idColumn), setOf())
val barIdColumn = Column("Id", ColumnDataType.INTEGER, 10,
primaryKey = true,
autoIncrement = false,
unique = false,
databaseType = DatabaseType.H2)
val fkColumn = Column("fooId", ColumnDataType.INTEGER, 10,
primaryKey = true,
autoIncrement = false,
unique = false,
databaseType = DatabaseType.H2)
val foreignKey = ForeignKey(sourceColumns = setOf(fkColumn), targetTable = foo.name)
val bar = Table("Bar", setOf(barIdColumn, fkColumn), setOf(foreignKey))
val insertId0 = 1001L
val pkGeneFoo = SqlPrimaryKeyGene("Id", "Foo", IntegerGene("Id", 1, 0, 10), insertId0)
val action0 = DbAction(foo, setOf(idColumn), insertId0, listOf(pkGeneFoo))
val insertId1 = 1002L
val pkGeneBar = SqlPrimaryKeyGene("Id", "Bar", IntegerGene("Id", 2, 0, 10), insertId0)
val fkGene = SqlForeignKeyGene("fooId", insertId1, "Foo", false, insertId0)
val action1 = DbAction(bar, setOf(barIdColumn, fkColumn), insertId1, listOf(pkGeneBar, fkGene))
val fooNode = ResourceNodeCluster.cluster.getResourceNode("/v3/api/rfoo/{rfooId}")
val barNode = ResourceNodeCluster.cluster.getResourceNode("/v3/api/rfoo/{rfooId}/rbar/{rbarId}")
val call1 = fooNode?.sampleRestResourceCalls("POST-GET", ResourceNodeCluster.randomness, 10) ?: throw IllegalStateException()
val call2 = barNode?.sampleRestResourceCalls("GET", ResourceNodeCluster.randomness, 10) ?: throw IllegalStateException()
return RestIndividual(mutableListOf(call1, call2), SampleType.RANDOM, dbInitialization = mutableListOf(action0, action1))
}
// 2 db + 2 resource call
override fun getExpectedChildrenSize(): Int = 2 + 2
@Test
fun testTraverseBackIndex(){
val root = getStructuralElementAndIdentifyAsRoot() as RestIndividual
assertEquals(root, root.getRoot())
val barId = root.seeInitializingActions()[1].seeTopGenes()[0]
val dbpath = listOf(1, 0)
assertEquals(barId, root.targetWithIndex(dbpath))
// root.seeMainExecutableActions()[0] is obtained with 2-> 0-> 0, i.e., 2nd children (resourceCall) -> 0th group -> 0th action
val action = root.seeMainExecutableActions()[0]
val param = action.parameters.find { it is BodyParam }
assertNotNull(param)
val index = action.parameters.indexOf(param)
val floatValue = (param!!.gene as ObjectGene).fields[3]
val path = listOf(2, 0, 0, index, 0, 3)
assertEquals(floatValue, root.targetWithIndex(path))
val actualPath = mutableListOf<Int>()
floatValue.traverseBackIndex(actualPath)
assertEquals(path, actualPath)
}
}
| core/src/test/kotlin/org/evomaster/core/search/structuralelement/individual/RestIndividualStructureTest.kt | 102194184 |
package com.example.ap.kotlinapgenjava
annotation class KotlinAnnotation
| test/com/facebook/buck/jvm/kotlin/testdata/kotlin_library_description/com/example/ap/kotlinapgenjava/KotlinAnnotation.kt | 4036474072 |
package com.gmail.blueboxware.libgdxplugin.settings
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.project.Project
import com.intellij.ui.EditorNotifications
import javax.swing.JComponent
/*
* 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.
*/
@State(name = "LibGDXPluginConfigurable")
class LibGDXPluginConfigurable(val project: Project) : Configurable {
private var form: LibGDXPluginSettingsPane? = null
override fun isModified() = getForm()?.isModified == true
override fun disposeUIResources() {
form = null
}
override fun getDisplayName() = "LibGDXPlugin"
override fun apply() {
getForm()?.apply()
EditorNotifications.getInstance(project).updateAllNotifications()
}
override fun createComponent(): JComponent? {
val settings = project.getService(LibGDXPluginSettings::class.java)
return getForm()?.createPanel(project, settings)
}
override fun reset() {
getForm()?.reset()
}
override fun getHelpTopic(): String? = null
private fun getForm(): LibGDXPluginSettingsPane? {
if (form == null) {
form = LibGDXPluginSettingsPane()
}
return form
}
}
@State(name = "LibGDXPluginSettings")
class LibGDXPluginSettings : PersistentStateComponent<LibGDXPluginSettings> {
var enableColorAnnotations: Boolean = true
var enableColorAnnotationsInJson: Boolean = true
var enableColorAnnotationsInSkin: Boolean = true
var neverAskAboutSkinFiles: Boolean = false
var neverAskAboutJsonFiles: Boolean = false
override fun loadState(state: LibGDXPluginSettings) {
enableColorAnnotations = state.enableColorAnnotations
enableColorAnnotationsInJson = state.enableColorAnnotationsInJson
enableColorAnnotationsInSkin = state.enableColorAnnotationsInSkin
neverAskAboutSkinFiles = state.neverAskAboutSkinFiles
neverAskAboutJsonFiles = state.neverAskAboutJsonFiles
}
override fun getState() = this
}
| src/main/kotlin/com/gmail/blueboxware/libgdxplugin/settings/LibGDXPluginConfigurable.kt | 1086650367 |
package me.proxer.library.enums
import com.serjltt.moshi.adapters.FallbackEnum
import com.squareup.moshi.Moshi
import org.amshove.kluent.shouldBe
import org.junit.jupiter.api.Test
/**
* @author Ruben Gees
*/
class NotificationTypeTest {
private val adapter = Moshi.Builder()
.add(FallbackEnum.ADAPTER_FACTORY)
.build()
.adapter(NotificationType::class.java)
@Test
fun testDefault() {
adapter.fromJson("\"ticket\"") shouldBe NotificationType.TICKET
}
@Test
fun testFallback() {
adapter.fromJson("\"xyz\"") shouldBe NotificationType.OTHER
}
}
| library/src/test/kotlin/me/proxer/library/enums/NotificationTypeTest.kt | 351402011 |
package a.erubit.platform.course
import a.erubit.platform.R
import android.content.Context
abstract class Progress {
var nextInteractionDate: Long = 0
var interactionDate: Long = 0
var trainDate: Long = 0
var familiarity = 0
var progress = 0
open fun getExplanation(context: Context): String {
val r = context.resources
return when (interactionDate) {
0L -> r.getString(R.string.unopened)
else -> r.getString(
R.string.progress_explanation,
progress, familiarity)
}
}
}
| erubit.platform/src/main/java/a/erubit/platform/course/Progress.kt | 3333100007 |
package i_introduction._6_Data_Classes
import util.TODO
import util.doc6
fun todoTask6(): Nothing = TODO(
"""
Convert 'JavaCode6.Person' class to Kotlin.
Then add a modifier `data` to the resulting class.
This annotation means the compiler will generate a bunch of useful methods in this class: `equals`/`hashCode`, `toString` and some others.
The `task6` function should return a list of persons.
""",
documentation = doc6(),
references = { JavaCode6.Person("Alice", 29) }
)
data class Person(val name: String, val age: Int)
fun task6(): List<Person> {
return listOf(Person("Alice", 29), Person("Bob", 31))
}
| src/i_introduction/_6_Data_Classes/DataClasses.kt | 366404484 |
/*
* Copyright 2018 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.execution
import org.gradle.api.Project
import org.gradle.api.internal.file.temp.TemporaryFileProvider
import org.gradle.api.plugins.ExtensionAware
import org.gradle.api.plugins.ExtensionContainer
import org.gradle.internal.classpath.ClassPath
import org.gradle.internal.hash.HashCode
import org.gradle.internal.hash.Hashing
import org.gradle.kotlin.dsl.execution.ResidualProgram.Dynamic
import org.gradle.kotlin.dsl.execution.ResidualProgram.Instruction
import org.gradle.kotlin.dsl.execution.ResidualProgram.Static
import org.gradle.kotlin.dsl.support.CompiledKotlinBuildScript
import org.gradle.kotlin.dsl.support.CompiledKotlinBuildscriptAndPluginsBlock
import org.gradle.kotlin.dsl.support.CompiledKotlinBuildscriptBlock
import org.gradle.kotlin.dsl.support.CompiledKotlinInitScript
import org.gradle.kotlin.dsl.support.CompiledKotlinInitscriptBlock
import org.gradle.kotlin.dsl.support.CompiledKotlinPluginsBlock
import org.gradle.kotlin.dsl.support.CompiledKotlinSettingsBuildscriptBlock
import org.gradle.kotlin.dsl.support.CompiledKotlinSettingsPluginManagementBlock
import org.gradle.kotlin.dsl.support.CompiledKotlinSettingsScript
import org.gradle.kotlin.dsl.support.ImplicitReceiver
import org.gradle.kotlin.dsl.support.KotlinScriptHost
import org.gradle.kotlin.dsl.support.bytecode.ALOAD
import org.gradle.kotlin.dsl.support.bytecode.ARETURN
import org.gradle.kotlin.dsl.support.bytecode.ASTORE
import org.gradle.kotlin.dsl.support.bytecode.CHECKCAST
import org.gradle.kotlin.dsl.support.bytecode.DUP
import org.gradle.kotlin.dsl.support.bytecode.GETSTATIC
import org.gradle.kotlin.dsl.support.bytecode.INVOKEINTERFACE
import org.gradle.kotlin.dsl.support.bytecode.INVOKESPECIAL
import org.gradle.kotlin.dsl.support.bytecode.INVOKESTATIC
import org.gradle.kotlin.dsl.support.bytecode.INVOKEVIRTUAL
import org.gradle.kotlin.dsl.support.bytecode.InternalName
import org.gradle.kotlin.dsl.support.bytecode.LDC
import org.gradle.kotlin.dsl.support.bytecode.NEW
import org.gradle.kotlin.dsl.support.bytecode.RETURN
import org.gradle.kotlin.dsl.support.bytecode.TRY_CATCH
import org.gradle.kotlin.dsl.support.bytecode.internalName
import org.gradle.kotlin.dsl.support.bytecode.loadByteArray
import org.gradle.kotlin.dsl.support.bytecode.publicClass
import org.gradle.kotlin.dsl.support.bytecode.publicDefaultConstructor
import org.gradle.kotlin.dsl.support.bytecode.publicMethod
import org.gradle.kotlin.dsl.support.compileKotlinScriptToDirectory
import org.gradle.kotlin.dsl.support.messageCollectorFor
import org.gradle.kotlin.dsl.support.scriptDefinitionFromTemplate
import org.gradle.plugin.management.internal.MultiPluginRequests
import org.gradle.plugin.use.internal.PluginRequestCollector
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.org.objectweb.asm.ClassVisitor
import org.jetbrains.org.objectweb.asm.ClassWriter
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Type
import org.slf4j.Logger
import java.io.File
import kotlin.reflect.KClass
import kotlin.script.experimental.api.KotlinType
internal
typealias CompileBuildOperationRunner = (String, String, () -> String) -> String
/**
* Compiles the given [residual program][ResidualProgram] to an [ExecutableProgram] subclass named `Program`
* stored in the given [outputDir].
*/
internal
class ResidualProgramCompiler(
private val outputDir: File,
private val classPath: ClassPath = ClassPath.EMPTY,
private val originalSourceHash: HashCode,
private val programKind: ProgramKind,
private val programTarget: ProgramTarget,
private val implicitImports: List<String> = emptyList(),
private val logger: Logger = interpreterLogger,
private val temporaryFileProvider: TemporaryFileProvider,
private val compileBuildOperationRunner: CompileBuildOperationRunner = { _, _, action -> action() },
private val pluginAccessorsClassPath: ClassPath = ClassPath.EMPTY,
private val packageName: String? = null,
private val injectedProperties: Map<String, KotlinType> = mapOf()
) {
fun compile(program: ResidualProgram) = when (program) {
is Static -> emitStaticProgram(program)
is Dynamic -> emitDynamicProgram(program)
}
private
fun emitStaticProgram(program: Static) {
program<ExecutableProgram> {
overrideExecute {
emit(program.instructions)
}
}
}
private
fun emitDynamicProgram(program: Dynamic) {
program<ExecutableProgram.StagedProgram> {
overrideExecute {
emit(program.prelude.instructions)
emitEvaluateSecondStageOf()
}
overrideGetSecondStageScriptText(program.source.text)
overrideLoadSecondStageFor()
}
}
private
fun ClassWriter.overrideGetSecondStageScriptText(secondStageScriptText: String) {
publicMethod(
"getSecondStageScriptText",
"()Ljava/lang/String;",
"()Ljava/lang/String;"
) {
if (mightBeLargerThan64KB(secondStageScriptText)) {
// Large scripts are stored as a resource to overcome
// the 64KB string constant limitation
val resourcePath = storeStringToResource(secondStageScriptText)
ALOAD(0)
LDC(resourcePath)
INVOKEVIRTUAL(
ExecutableProgram.StagedProgram::class.internalName,
ExecutableProgram.StagedProgram::loadScriptResource.name,
"(Ljava/lang/String;)Ljava/lang/String;"
)
} else {
LDC(secondStageScriptText)
}
ARETURN()
}
}
private
fun mightBeLargerThan64KB(secondStageScriptText: String) =
// We use a simple heuristic to avoid converting the string to bytes
// if all code points were in UTF32, 16K code points would require 64K bytes
secondStageScriptText.length >= 16 * 1024
private
fun storeStringToResource(secondStageScriptText: String): String {
val hash = Hashing.hashString(secondStageScriptText)
val resourcePath = "scripts/$hash.gradle.kts"
writeResourceFile(resourcePath, secondStageScriptText)
return resourcePath
}
private
fun writeResourceFile(resourcePath: String, resourceText: String) {
outputFile(resourcePath).apply {
parentFile.mkdir()
writeText(resourceText)
}
}
private
fun MethodVisitor.emit(instructions: List<Instruction>) {
instructions.forEach {
emit(it)
}
}
private
fun MethodVisitor.emit(instruction: Instruction) = when (instruction) {
is Instruction.SetupEmbeddedKotlin -> emitSetupEmbeddedKotlinFor()
is Instruction.CloseTargetScope -> emitCloseTargetScopeOf()
is Instruction.Eval -> emitEval(instruction.script)
is Instruction.ApplyBasePlugins -> emitApplyBasePluginsTo()
is Instruction.ApplyDefaultPluginRequests -> emitApplyEmptyPluginRequestsTo()
is Instruction.ApplyPluginRequestsOf -> {
val program = instruction.program
when (program) {
is Program.Plugins -> emitPrecompiledPluginsBlock(program)
is Program.PluginManagement -> emitStage1Sequence(program)
is Program.Stage1Sequence -> emitStage1Sequence(program.pluginManagement, program.buildscript, program.plugins)
else -> throw IllegalStateException("Expecting a residual program with plugins, got `$program'")
}
}
}
private
fun MethodVisitor.emitSetupEmbeddedKotlinFor() {
// programHost.setupEmbeddedKotlinFor(scriptHost)
ALOAD(Vars.ProgramHost)
ALOAD(Vars.ScriptHost)
invokeHost("setupEmbeddedKotlinFor", kotlinScriptHostToVoid)
}
private
fun MethodVisitor.emitEval(source: ProgramSource) {
val scriptDefinition = stage1ScriptDefinition
val precompiledScriptClass = compileStage1(source, scriptDefinition)
emitInstantiationOfPrecompiledScriptClass(precompiledScriptClass, scriptDefinition)
}
private
val Program.Stage1.fragment: ProgramSourceFragment
get() = when (this) {
is Program.Buildscript -> fragment
is Program.Plugins -> fragment
is Program.PluginManagement -> fragment
else -> TODO("Unsupported fragment: $fragment")
}
private
fun MethodVisitor.emitStage1Sequence(vararg stage1Seq: Program.Stage1?) {
emitStage1Sequence(listOfNotNull(*stage1Seq))
}
private
fun MethodVisitor.emitStage1Sequence(stage1Seq: List<Program.Stage1>) {
val scriptDefinition = buildscriptWithPluginsScriptDefinition
val plugins = stage1Seq.filterIsInstance<Program.Plugins>().singleOrNull()
val firstElement = stage1Seq.first()
val precompiledBuildscriptWithPluginsBlock =
compileStage1(
firstElement.fragment.source.map {
it.preserve(stage1Seq.map { stage1 -> stage1.fragment.range })
},
scriptDefinition,
pluginsBlockClassPath
)
val implicitReceiverType = implicitReceiverOf(scriptDefinition)!!
precompiledScriptClassInstantiation(precompiledBuildscriptWithPluginsBlock) {
emitPluginRequestCollectorInstantiation()
NEW(precompiledBuildscriptWithPluginsBlock)
ALOAD(Vars.ScriptHost)
// ${plugins}(temp.createSpec(lineNumber))
emitPluginRequestCollectorCreateSpecFor(plugins)
loadTargetOf(implicitReceiverType)
emitLoadExtensions()
INVOKESPECIAL(
precompiledBuildscriptWithPluginsBlock,
"<init>",
"(Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;Lorg/gradle/plugin/use/PluginDependenciesSpec;L${implicitReceiverType.internalName};$injectedPropertiesDescriptors)V"
)
emitApplyPluginsTo()
}
}
/**
* programHost.applyPluginsTo(scriptHost, collector.getPluginRequests())
*/
private
fun MethodVisitor.emitApplyPluginsTo() {
ALOAD(Vars.ProgramHost)
ALOAD(Vars.ScriptHost)
emitPluginRequestCollectorGetPluginRequests()
invokeApplyPluginsTo()
}
private
fun MethodVisitor.emitApplyBasePluginsTo() {
ALOAD(Vars.ProgramHost)
loadTargetOf(Project::class)
invokeHost(
"applyBasePluginsTo",
"(Lorg/gradle/api/Project;)V"
)
}
private
fun MethodVisitor.loadTargetOf(expectedType: KClass<*>) {
ALOAD(Vars.ScriptHost)
INVOKEVIRTUAL(
KotlinScriptHost::class.internalName,
"getTarget",
"()Ljava/lang/Object;"
)
CHECKCAST(expectedType.internalName)
}
private
fun MethodVisitor.emitApplyEmptyPluginRequestsTo() {
ALOAD(Vars.ProgramHost)
ALOAD(Vars.ScriptHost)
GETSTATIC(
MultiPluginRequests::class.internalName,
"EMPTY",
"Lorg/gradle/plugin/management/internal/PluginRequests;"
)
invokeApplyPluginsTo()
}
fun emitStage2ProgramFor(scriptFile: File, originalPath: String) {
val scriptDef = stage2ScriptDefinition
val precompiledScriptClass = compileScript(
scriptFile,
originalPath,
scriptDef,
StableDisplayNameFor.stage2
)
program<ExecutableProgram> {
overrideExecute {
emitInstantiationOfPrecompiledScriptClass(
precompiledScriptClass,
scriptDef
)
}
}
}
private
fun MethodVisitor.emitPrecompiledPluginsBlock(program: Program.Plugins) {
val precompiledPluginsBlock = compilePlugins(program)
precompiledScriptClassInstantiation(precompiledPluginsBlock) {
/*
* val collector = PluginRequestCollector(kotlinScriptHost.scriptSource)
*/
emitPluginRequestCollectorInstantiation()
// ${precompiledPluginsBlock}(collector.createSpec(lineNumber))
NEW(precompiledPluginsBlock)
emitPluginRequestCollectorCreateSpecFor(program)
emitLoadExtensions()
INVOKESPECIAL(
precompiledPluginsBlock,
"<init>",
"(Lorg/gradle/plugin/use/PluginDependenciesSpec;$injectedPropertiesDescriptors)V"
)
emitApplyPluginsTo()
}
}
private
val injectedPropertiesDescriptors
get() = injectedProperties.values
.map { Type.getType(it.fromClass?.java).descriptor }
.joinToString(separator = "")
/**
* extensions.getByName(name) as ExtensionType
*/
private
fun MethodVisitor.emitLoadExtension(name: String, type: KotlinType) {
ALOAD(Vars.ScriptHost)
INVOKEVIRTUAL(
KotlinScriptHost::class.internalName,
"getTarget",
"()Ljava/lang/Object;"
)
CHECKCAST(ExtensionAware::class)
INVOKEINTERFACE(
ExtensionAware::class.internalName,
"getExtensions",
"()Lorg/gradle/api/plugins/ExtensionContainer;"
)
LDC(name)
INVOKEINTERFACE(
ExtensionContainer::class.internalName,
"getByName",
"(Ljava/lang/String;)Ljava/lang/Object;"
)
CHECKCAST(type.fromClass!!)
}
/**
* val collector = PluginRequestCollector(kotlinScriptHost.scriptSource)
*/
private
fun MethodVisitor.emitPluginRequestCollectorInstantiation() {
NEW(pluginRequestCollectorType)
DUP()
ALOAD(Vars.ScriptHost)
INVOKEVIRTUAL(
KotlinScriptHost::class.internalName,
"getScriptSource",
"()Lorg/gradle/groovy/scripts/ScriptSource;"
)
INVOKESPECIAL(
pluginRequestCollectorType,
"<init>",
"(Lorg/gradle/groovy/scripts/ScriptSource;)V"
)
ASTORE(Vars.PluginRequestCollector)
}
private
fun MethodVisitor.emitPluginRequestCollectorGetPluginRequests() {
ALOAD(Vars.PluginRequestCollector)
INVOKEVIRTUAL(
pluginRequestCollectorType,
"getPluginRequests",
"()Lorg/gradle/plugin/management/internal/PluginRequests;"
)
}
private
fun MethodVisitor.emitPluginRequestCollectorCreateSpecFor(plugins: Program.Plugins?) {
ALOAD(Vars.PluginRequestCollector)
LDC(plugins?.fragment?.lineNumber ?: 0)
INVOKEVIRTUAL(
pluginRequestCollectorType,
"createSpec",
"(I)Lorg/gradle/plugin/use/PluginDependenciesSpec;"
)
}
private
val pluginRequestCollectorType = PluginRequestCollector::class.internalName
private
fun MethodVisitor.invokeApplyPluginsTo() {
invokeHost(
"applyPluginsTo",
"(Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;Lorg/gradle/plugin/management/internal/PluginRequests;)V"
)
}
private
fun ClassWriter.overrideLoadSecondStageFor() {
publicMethod(
name = "loadSecondStageFor",
desc = loadSecondStageForDescriptor
) {
ALOAD(Vars.ProgramHost)
ALOAD(0)
ALOAD(Vars.ScriptHost)
ALOAD(3)
ALOAD(4)
GETSTATIC(programKind)
GETSTATIC(programTarget)
ALOAD(5)
invokeHost(
ExecutableProgram.Host::compileSecondStageOf.name,
compileSecondStageOfDescriptor
)
ARETURN()
}
}
private
fun MethodVisitor.emitEvaluateSecondStageOf() {
// programHost.evaluateSecondStageOf(...)
ALOAD(Vars.ProgramHost)
ALOAD(Vars.Program)
ALOAD(Vars.ScriptHost)
LDC(programTarget.name + "/" + programKind.name + "/stage2")
// Move HashCode value to a static field so it's cached across invocations
loadHashCode(originalSourceHash)
if (requiresAccessors()) emitAccessorsClassPathForScriptHost() else GETSTATIC(ClassPath::EMPTY)
invokeHost(
ExecutableProgram.Host::evaluateSecondStageOf.name,
"(" +
stagedProgramType +
"Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;" +
"Ljava/lang/String;" +
"Lorg/gradle/internal/hash/HashCode;" +
"Lorg/gradle/internal/classpath/ClassPath;" +
")V"
)
}
private
val stagedProgram = Type.getType(ExecutableProgram.StagedProgram::class.java)
private
val stagedProgramType = stagedProgram.descriptor
private
val loadSecondStageForDescriptor = Type.getMethodDescriptor(
Type.getType(CompiledScript::class.java),
Type.getType(ExecutableProgram.Host::class.java),
Type.getType(KotlinScriptHost::class.java),
Type.getType(String::class.java),
Type.getType(HashCode::class.java),
Type.getType(ClassPath::class.java)
)
private
val compileSecondStageOfDescriptor = Type.getMethodDescriptor(
Type.getType(CompiledScript::class.java),
stagedProgram,
Type.getType(KotlinScriptHost::class.java),
Type.getType(String::class.java),
Type.getType(HashCode::class.java),
Type.getType(ProgramKind::class.java),
Type.getType(ProgramTarget::class.java),
Type.getType(ClassPath::class.java)
)
private
fun requiresAccessors() =
requiresAccessors(programTarget, programKind)
private
fun MethodVisitor.emitAccessorsClassPathForScriptHost() {
ALOAD(Vars.ProgramHost)
ALOAD(Vars.ScriptHost)
invokeHost(
"accessorsClassPathFor",
"(Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;)Lorg/gradle/internal/classpath/ClassPath;"
)
}
private
fun ClassVisitor.overrideExecute(methodBody: MethodVisitor.() -> Unit) {
publicMethod("execute", programHostToKotlinScriptHostToVoid, "(Lorg/gradle/kotlin/dsl/execution/ExecutableProgram\$Host;Lorg/gradle/kotlin/dsl/support/KotlinScriptHost<*>;)V") {
methodBody()
RETURN()
}
}
private
fun compilePlugins(program: Program.Plugins) =
compileStage1(
program.fragment.source.map { it.preserve(program.fragment.range) },
pluginsScriptDefinition,
pluginsBlockClassPath
)
private
val pluginsBlockClassPath
get() = classPath + pluginAccessorsClassPath
private
fun MethodVisitor.loadHashCode(hashCode: HashCode) {
loadByteArray(hashCode.toByteArray())
INVOKESTATIC(
HashCode::class.internalName,
"fromBytes",
"([B)Lorg/gradle/internal/hash/HashCode;"
)
}
private
fun MethodVisitor.emitInstantiationOfPrecompiledScriptClass(
precompiledScriptClass: InternalName,
scriptDefinition: ScriptDefinition
) {
val implicitReceiverType = implicitReceiverOf(scriptDefinition)
precompiledScriptClassInstantiation(precompiledScriptClass) {
// ${precompiledScriptClass}(scriptHost)
NEW(precompiledScriptClass)
val constructorSignature =
if (implicitReceiverType != null) {
ALOAD(Vars.ScriptHost)
loadTargetOf(implicitReceiverType)
emitLoadExtensions()
"(Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;L${implicitReceiverType.internalName};$injectedPropertiesDescriptors)V"
} else {
ALOAD(Vars.ScriptHost)
emitLoadExtensions()
"(Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;$injectedPropertiesDescriptors)V"
}
INVOKESPECIAL(precompiledScriptClass, "<init>", constructorSignature)
}
}
private
fun MethodVisitor.emitLoadExtensions() {
injectedProperties.forEach { name, type ->
emitLoadExtension(name, type)
}
}
private
fun MethodVisitor.precompiledScriptClassInstantiation(precompiledScriptClass: InternalName, instantiation: MethodVisitor.() -> Unit) {
TRY_CATCH<Throwable>(
tryBlock = {
instantiation()
},
catchBlock = {
emitOnScriptException(precompiledScriptClass)
}
)
}
private
fun MethodVisitor.emitOnScriptException(precompiledScriptClass: InternalName) {
// Exception is on the stack
ASTORE(4)
ALOAD(Vars.ProgramHost)
ALOAD(4)
LDC(Type.getType("L$precompiledScriptClass;"))
ALOAD(Vars.ScriptHost)
invokeHost(
"handleScriptException",
"(Ljava/lang/Throwable;Ljava/lang/Class;Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;)V"
)
}
private
fun MethodVisitor.emitCloseTargetScopeOf() {
// programHost.closeTargetScopeOf(scriptHost)
ALOAD(Vars.ProgramHost)
ALOAD(Vars.ScriptHost)
invokeHost("closeTargetScopeOf", kotlinScriptHostToVoid)
}
private
fun MethodVisitor.invokeHost(name: String, desc: String) {
INVOKEINTERFACE(ExecutableProgram.Host::class.internalName, name, desc)
}
private
object Vars {
const val Program = 0
const val ProgramHost = 1
const val ScriptHost = 2
// Only valid within the context of `overrideExecute`
const val PluginRequestCollector = 3
}
private
val programHostToKotlinScriptHostToVoid =
"(Lorg/gradle/kotlin/dsl/execution/ExecutableProgram\$Host;Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;)V"
private
val kotlinScriptHostToVoid =
"(Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;)V"
private
inline fun <reified T : ExecutableProgram> program(noinline classBody: ClassWriter.() -> Unit = {}) {
program(T::class.internalName, classBody)
}
private
fun program(superName: InternalName, classBody: ClassWriter.() -> Unit = {}) {
writeFile(
"Program.class",
publicClass(InternalName("Program"), superName, null) {
publicDefaultConstructor(superName)
classBody()
}
)
}
private
fun writeFile(relativePath: String, bytes: ByteArray) {
outputFile(relativePath).writeBytes(bytes)
}
private
fun outputFile(relativePath: String) =
outputDir.resolve(relativePath)
private
fun compileStage1(
source: ProgramSource,
scriptDefinition: ScriptDefinition,
compileClassPath: ClassPath = classPath
): InternalName =
temporaryFileProvider.withTemporaryScriptFileFor(source.path, source.text) { scriptFile ->
val originalScriptPath = source.path
compileScript(
scriptFile,
originalScriptPath,
scriptDefinition,
StableDisplayNameFor.stage1,
compileClassPath
)
}
private
fun compileScript(
scriptFile: File,
originalPath: String,
scriptDefinition: ScriptDefinition,
stage: String,
compileClassPath: ClassPath = classPath
) = InternalName.from(
compileBuildOperationRunner(originalPath, stage) {
compileKotlinScriptToDirectory(
outputDir,
scriptFile,
scriptDefinition,
compileClassPath.asFiles,
messageCollectorFor(logger) { path ->
if (path == scriptFile.path) originalPath
else path
}
)
}.let { compiledScriptClassName ->
packageName
?.let { "$it.$compiledScriptClassName" }
?: compiledScriptClassName
}
)
/**
* Stage descriptions for build operations.
*
* Changes to these constants must be coordinated with the GE team.
*/
private
object StableDisplayNameFor {
const val stage1 = "CLASSPATH"
const val stage2 = "BODY"
}
private
val stage1ScriptDefinition
get() = scriptDefinitionFromTemplate(
when (programTarget) {
ProgramTarget.Project -> CompiledKotlinBuildscriptBlock::class
ProgramTarget.Settings -> CompiledKotlinSettingsBuildscriptBlock::class
ProgramTarget.Gradle -> CompiledKotlinInitscriptBlock::class
}
)
private
val stage2ScriptDefinition
get() = scriptDefinitionFromTemplate(
when (programTarget) {
ProgramTarget.Project -> CompiledKotlinBuildScript::class
ProgramTarget.Settings -> CompiledKotlinSettingsScript::class
ProgramTarget.Gradle -> CompiledKotlinInitScript::class
}
)
private
val pluginsScriptDefinition
get() = scriptDefinitionFromTemplate(CompiledKotlinPluginsBlock::class)
private
fun implicitReceiverOf(scriptDefinition: ScriptDefinition): KClass<*>? =
implicitReceiverOf(scriptDefinition.baseClassType.fromClass!!)
private
val buildscriptWithPluginsScriptDefinition
get() = scriptDefinitionFromTemplate(
when (programTarget) {
ProgramTarget.Project -> CompiledKotlinBuildscriptAndPluginsBlock::class
ProgramTarget.Settings -> CompiledKotlinSettingsPluginManagementBlock::class
else -> TODO("Unsupported program target: `$programTarget`")
}
)
private
fun scriptDefinitionFromTemplate(template: KClass<out Any>) =
scriptDefinitionFromTemplate(
template,
implicitImports,
implicitReceiverOf(template),
injectedProperties,
classPath.asFiles
)
private
fun implicitReceiverOf(template: KClass<*>) =
template.annotations.filterIsInstance<ImplicitReceiver>().map { it.type }.firstOrNull()
}
internal
fun requiresAccessors(programTarget: ProgramTarget, programKind: ProgramKind) =
programTarget == ProgramTarget.Project && programKind == ProgramKind.TopLevel
| subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/execution/ResidualProgramCompiler.kt | 1972104020 |
package uk.co.alt236.underthehood.commandrunner.groups
import android.content.res.Resources
import uk.co.alt236.underthehood.commandrunner.CommandGroup
import uk.co.alt236.underthehood.commandrunner.R
import uk.co.alt236.underthehood.commandrunner.model.CommandOutputGroup
internal class PsCommands internal constructor(res: Resources) : CommandGroup(res) {
override fun execute(rooted: Boolean): List<CommandOutputGroup> {
val commands = getStringArray(R.array.commands_ps)
val list = execute(commands, rooted)
return listOf(
CommandOutputGroup(
name = "",
commandOutputs = list
)
)
}
} | command_runner/src/main/java/uk/co/alt236/underthehood/commandrunner/groups/PsCommands.kt | 1560432938 |
/*
* Copyright 2020 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache.serialization.codecs
import org.gradle.api.file.FileCollection
import org.gradle.api.file.FileTree
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ArtifactSetToFileCollectionFactory
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.LocalFileDependencyBackedArtifactSet
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ResolvedArtifactSet
import org.gradle.api.internal.artifacts.transform.TransformedExternalArtifactSet
import org.gradle.api.internal.artifacts.transform.TransformedProjectArtifactSet
import org.gradle.api.internal.file.FileCollectionFactory
import org.gradle.api.internal.file.FileCollectionInternal
import org.gradle.api.internal.file.FileCollectionStructureVisitor
import org.gradle.api.internal.file.FileTreeInternal
import org.gradle.api.internal.file.FilteredFileCollection
import org.gradle.api.internal.file.SubtractingFileCollection
import org.gradle.api.internal.file.collections.FailingFileCollection
import org.gradle.api.internal.file.collections.FileSystemMirroringFileTree
import org.gradle.api.internal.file.collections.MinimalFileSet
import org.gradle.api.internal.file.collections.ProviderBackedFileCollection
import org.gradle.api.internal.provider.ProviderInternal
import org.gradle.api.specs.Spec
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.util.PatternSet
import org.gradle.configurationcache.serialization.Codec
import org.gradle.configurationcache.serialization.ReadContext
import org.gradle.configurationcache.serialization.WriteContext
import org.gradle.configurationcache.serialization.decodePreservingIdentity
import org.gradle.configurationcache.serialization.encodePreservingIdentityOf
import java.io.File
internal
class FileCollectionCodec(
private val fileCollectionFactory: FileCollectionFactory,
private val artifactSetConverter: ArtifactSetToFileCollectionFactory
) : Codec<FileCollectionInternal> {
override suspend fun WriteContext.encode(value: FileCollectionInternal) {
encodePreservingIdentityOf(value) {
val visitor = CollectingVisitor()
value.visitStructure(visitor)
write(visitor.elements)
}
}
override suspend fun ReadContext.decode(): FileCollectionInternal {
return decodePreservingIdentity { id ->
val contents = read()
val collection = if (contents is Collection<*>) {
fileCollectionFactory.resolving(
contents.map { element ->
when (element) {
is File -> element
is SubtractingFileCollectionSpec -> element.left.minus(element.right)
is FilteredFileCollectionSpec -> element.collection.filter(element.filter)
is ProviderBackedFileCollectionSpec -> element.provider
is FileTree -> element
is ResolvedArtifactSet -> artifactSetConverter.asFileCollection(element)
is BeanSpec -> element.bean
else -> throw IllegalArgumentException("Unexpected item $element in file collection contents")
}
}
)
} else {
fileCollectionFactory.create(ErrorFileSet(contents as BrokenValue))
}
isolate.identities.putInstance(id, collection)
collection
}
}
}
private
class SubtractingFileCollectionSpec(val left: FileCollection, val right: FileCollection)
private
class FilteredFileCollectionSpec(val collection: FileCollection, val filter: Spec<in File>)
private
class ProviderBackedFileCollectionSpec(val provider: ProviderInternal<*>)
private
class CollectingVisitor : FileCollectionStructureVisitor {
val elements: MutableSet<Any> = mutableSetOf()
override fun startVisit(source: FileCollectionInternal.Source, fileCollection: FileCollectionInternal): Boolean =
when (fileCollection) {
is SubtractingFileCollection -> {
// TODO - when left and right are both static then we should serialize the current contents of the collection
elements.add(SubtractingFileCollectionSpec(fileCollection.left, fileCollection.right))
false
}
is FilteredFileCollection -> {
// TODO - when the collection is static then we should serialize the current contents of the collection
elements.add(FilteredFileCollectionSpec(fileCollection.collection, fileCollection.filterSpec))
false
}
is ProviderBackedFileCollection -> {
// Guard against file collection created from a task provider such as `layout.files(compileJava)`
// being referenced from a different task.
val provider = fileCollection.provider
if (provider !is TaskProvider<*>) {
elements.add(ProviderBackedFileCollectionSpec(provider))
false
} else {
true
}
}
is FileTreeInternal -> {
elements.add(fileCollection)
false
}
is FailingFileCollection -> {
elements.add(BeanSpec(fileCollection))
false
}
else -> {
true
}
}
override fun prepareForVisit(source: FileCollectionInternal.Source): FileCollectionStructureVisitor.VisitType =
if (source is TransformedProjectArtifactSet || source is LocalFileDependencyBackedArtifactSet || source is TransformedExternalArtifactSet) {
// Represents artifact transform outputs. Visit the source rather than the files
// Transforms may have inputs or parameters that are task outputs or other changing files
// When this is not the case, we should run the transform now and write the result.
// However, currently it is not easy to determine whether or not this is the case so assume that all transforms
// have changing inputs
FileCollectionStructureVisitor.VisitType.NoContents
} else {
FileCollectionStructureVisitor.VisitType.Visit
}
override fun visitCollection(source: FileCollectionInternal.Source, contents: Iterable<File>) {
when (source) {
is TransformedProjectArtifactSet -> {
elements.add(source)
}
is LocalFileDependencyBackedArtifactSet -> {
elements.add(source)
}
is TransformedExternalArtifactSet -> {
elements.add(source)
}
else -> {
elements.addAll(contents)
}
}
}
override fun visitFileTree(root: File, patterns: PatternSet, fileTree: FileTreeInternal) =
unsupportedFileTree(fileTree)
override fun visitFileTreeBackedByFile(file: File, fileTree: FileTreeInternal, sourceTree: FileSystemMirroringFileTree) =
unsupportedFileTree(fileTree)
private
fun unsupportedFileTree(fileTree: FileTreeInternal): Nothing =
throw UnsupportedOperationException(
"Unexpected file tree '$fileTree' of type '${fileTree.javaClass}' found while serializing a file collection."
)
}
private
class ErrorFileSet(private val error: BrokenValue) : MinimalFileSet {
override fun getDisplayName() =
"error-file-collection"
override fun getFiles() =
error.rethrow()
}
| subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/codecs/FileCollectionCodec.kt | 1470358669 |
package com.github.sybila.checker.operator
import com.github.sybila.checker.Operator
import com.github.sybila.checker.Partition
import com.github.sybila.checker.StateMap
import com.github.sybila.huctl.Formula
class FalseOperator<out Params : Any>(
partition: Partition<Params>
) : Operator<Params> {
private val value
= partition.run { emptyStateMap() }
override fun compute(): StateMap<Params> = value
}
class TrueOperator<out Params : Any>(
partition: Partition<Params>
) : Operator<Params> {
private val value: StateMap<Params>
= partition.run { (0 until stateCount).asStateMap(tt).restrictToPartition() }
override fun compute(): StateMap<Params> = value
}
class ReferenceOperator<out Params : Any>(
state: Int,
partition: Partition<Params>
) : Operator<Params> {
private val value = partition.run {
if (state in this) state.asStateMap(tt) else emptyStateMap()
}
override fun compute(): StateMap<Params> = value
}
class FloatOperator<out Params : Any>(
private val float: Formula.Atom.Float,
private val partition: Partition<Params>
) : Operator<Params> {
private val value: StateMap<Params> by lazy(LazyThreadSafetyMode.NONE) {
partition.run { float.eval().restrictToPartition() }
}
override fun compute(): StateMap<Params> = value
}
class TransitionOperator<out Params : Any>(
private val transition: Formula.Atom.Transition,
private val partition: Partition<Params>
) : Operator<Params> {
private val value: StateMap<Params> by lazy(LazyThreadSafetyMode.NONE) {
partition.run { transition.eval().restrictToPartition() }
}
override fun compute(): StateMap<Params> = value
} | src/main/kotlin/com/github/sybila/checker/operator/AtomOperator.kt | 3990318733 |
package com.github.premnirmal.ticker.repo.data
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class HoldingRow(
@PrimaryKey(autoGenerate = true) var id: Long? = null,
@ColumnInfo(name = "quote_symbol") val quoteSymbol: String,
@ColumnInfo(name = "shares") val shares: Float = 0.0f,
@ColumnInfo(name = "price") val price: Float = 0.0f
) | app/src/main/kotlin/com/github/premnirmal/ticker/repo/data/HoldingRow.kt | 522486223 |
/*
* Copyright 2017 Ali Salah Alddin
*
* 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 edu.uofk.eeese.eeese.data.database
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import edu.uofk.eeese.eeese.data.DataContract
import edu.uofk.eeese.eeese.di.scopes.ApplicationScope
import javax.inject.Inject
@ApplicationScope
class DatabaseHelper @Inject
constructor(context: Context) : SQLiteOpenHelper(context, DatabaseHelper.DATABASE_NAME, null, DatabaseHelper.DATABASE_VERSION) {
companion object {
private const val DATABASE_NAME = "eeese.db"
private const val DATABASE_VERSION = 1
}
override fun onCreate(db: SQLiteDatabase) {
val CREATE_PROJECTS_TABLE_QUERY =
"CREATE TABLE ${DataContract.ProjectEntry.TABLE_NAME} " +
"(" +
"${DataContract.ProjectEntry._ID} INTEGER PRIMARY KEY AUTOINCREMENT, " +
"${DataContract.ProjectEntry.COLUMN_PROJECT_ID} " +
"TEXT UNIQUE ON CONFLICT REPLACE, " +
"${DataContract.ProjectEntry.COLUMN_PROJECT_NAME} TEXT NOT NULL, " +
"${DataContract.ProjectEntry.COLUMN_PROJECT_HEAD} TEXT, " +
"${DataContract.ProjectEntry.COLUMN_PROJECT_DESC} TEXT, " +
"${DataContract.ProjectEntry.COLUMN_PROJECT_CATEGORY} INTEGER, " +
"${DataContract.ProjectEntry.COLUMN_PROJECT_PREREQS} TEXT" +
")"
val CREATE_EVENTS_TABLE_QUERY =
"CREATE TABLE ${DataContract.EventEntry.TABLE_NAME}" +
"( " +
"${DataContract.EventEntry._ID} INTEGER PRIMARY KEY AUTOINCREMENT, " +
"${DataContract.EventEntry.COLUMN_EVENT_ID} " +
"TEXT UNIQUE ON CONFLICT REPLACE, " +
"${DataContract.EventEntry.COLUMN_EVENT_NAME} TEXT NOT NULL, " +
"${DataContract.EventEntry.COLUMN_EVENT_DESC} TEXT, " +
"${DataContract.EventEntry.COLUMN_EVENT_IMAGE_URI} TEXT, " +
"${DataContract.EventEntry.COLUMN_EVENT_LOCATION} TEXT, " +
"${DataContract.EventEntry.COLUMN_EVENT_START_DATE} TEXT, " +
"${DataContract.EventEntry.COLUMN_EVENT_END_DATE} TEXT" +
")"
db.execSQL(CREATE_PROJECTS_TABLE_QUERY)
db.execSQL(CREATE_EVENTS_TABLE_QUERY)
}
override fun onUpgrade(db: SQLiteDatabase, i: Int, i1: Int) {
val DROP_PROJECTS_TABLE_QUERY =
"DROP TABLE IF EXISTS ${DataContract.ProjectEntry.TABLE_NAME}"
val DROP_EVENTS_TABLE_QUERY =
"DROP TABLE IF EXISTS ${DataContract.EventEntry.TABLE_NAME}"
db.execSQL(DROP_PROJECTS_TABLE_QUERY)
db.execSQL(DROP_EVENTS_TABLE_QUERY)
onCreate(db)
}
}
| app/src/main/java/edu/uofk/eeese/eeese/data/database/DatabaseHelper.kt | 1544136991 |
package org.openapitools.client.infrastructure
import okhttp3.Response
/**
* Provides an extension to evaluation whether the response is a 1xx code
*/
val Response.isInformational : Boolean get() = this.code in 100..199
/**
* Provides an extension to evaluation whether the response is a 3xx code
*/
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
val Response.isRedirect : Boolean get() = this.code in 300..399
/**
* Provides an extension to evaluation whether the response is a 4xx code
*/
val Response.isClientError : Boolean get() = this.code in 400..499
/**
* Provides an extension to evaluation whether the response is a 5xx (Standard) through 999 (non-standard) code
*/
val Response.isServerError : Boolean get() = this.code in 500..999
| ems-gateway-rest-sdk/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt | 2245260179 |
//package com.andretietz.retroauth
//
//import com.andretietz.retroauth.sqlite.CredentialTable
//import com.andretietz.retroauth.sqlite.DataTable
//import com.andretietz.retroauth.sqlite.DatabaseCredential
//import com.andretietz.retroauth.sqlite.DatabaseUser
//import com.andretietz.retroauth.sqlite.UserTable
//import com.andretietz.retroauth.sqlite.data.Account
//import org.jetbrains.exposed.sql.Database
//import org.jetbrains.exposed.sql.SchemaUtils
//import org.jetbrains.exposed.sql.StdOutSqlLogger
//import org.jetbrains.exposed.sql.addLogger
//import org.jetbrains.exposed.sql.selectAll
//import org.jetbrains.exposed.sql.transactions.transaction
//private const val OWNER_TYPE = "ownertype"
//
//fun main() {
// val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
//// Database.connect(
//// "jdbc:sqlite:accountdb.db",
//// user = "someuser",
//// password = "somepassword",
//// driver = "org.sqlite.JDBC"
//// )
//
// val credentialStore = SQLiteCredentialStore(database)
// val ownerStore: OwnerStorage<Account> = SQLiteOwnerStore(database)
//
// transaction(database) {
// addLogger(StdOutSqlLogger)
// SchemaUtils.create(UserTable, CredentialTable, DataTable)
//
// ownerStore.createOwner(CREDENTIAL_TYPE)?.let {
// credentialStore.storeCredentials(it, CREDENTIAL_TYPE, Credentials("myfancytoken"))
//
// val credential = credentialStore.getCredentials(it, CREDENTIAL_TYPE)
// println(credential)
// }
//
// SchemaUtils.drop(UserTable, CredentialTable, DataTable)
// }
//}
//
//
| sqlite/src/main/kotlin/com/andretietz/retroauth/Main.kt | 4202703020 |
package actor.proto.router
import actor.proto.PID
import actor.proto.send
internal class BroadcastRouterState : RouterState() {
private lateinit var routees: Set<PID>
override fun getRoutees(): Set<PID> = routees
override fun setRoutees(routees: Set<PID>) {
this.routees = routees
}
override fun routeMessage(message: Any) {
routees.forEach { send(it,message) }
}
}
| proto-router/src/main/kotlin/actor/proto/router/BroadcastRouterState.kt | 3933446006 |
package com.arcao.geocaching4locus.data.api.model.request.query.filter
class ProvinceFilter(val name: String) : Filter {
override fun isValid() = name.isNotEmpty()
override fun toString() = "prov:$name"
} | geocaching-api/src/main/java/com/arcao/geocaching4locus/data/api/model/request/query/filter/ProvinceFilter.kt | 4185518 |
@file:JvmName("Actors")
@file:JvmMultifileClass
package actor.proto
import actor.proto.mailbox.SystemMessage
@JvmSynthetic
fun fromProducer(producer: () -> Actor): Props = Props().withProducer(producer)
@JvmSynthetic
fun fromFunc(receive: suspend Context.(msg: Any) -> Unit): Props = fromProducer {
object : Actor {
override suspend fun Context.receive(msg: Any) = receive(this, msg)
}
}
fun spawn(props: Props): PID {
val name = ProcessRegistry.nextId()
return spawnNamed(props, name)
}
fun spawnPrefix(props: Props, prefix: String): PID {
val name = prefix + ProcessRegistry.nextId()
return spawnNamed(props, name)
}
fun spawnNamed(props: Props, name: String): PID = props.spawn(name, null)
fun stop(pid: PID) {
val process = pid.cachedProcess() ?: ProcessRegistry.get(pid)
process.stop(pid)
}
fun sendSystemMessage(pid: PID, sys: SystemMessage) {
val process: Process = pid.cachedProcess() ?: ProcessRegistry.get(pid)
process.sendSystemMessage(pid, sys)
}
| proto-actor/src/main/kotlin/actor/proto/API.kt | 2479374180 |
package org.droidplanner.android.activities
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.v7.widget.Toolbar
import android.view.View
import android.widget.Button
import android.widget.ImageButton
import com.o3dr.android.client.Drone
import com.o3dr.android.client.apis.CapabilityApi
import com.o3dr.android.client.apis.VehicleApi
import com.o3dr.android.client.apis.solo.SoloCameraApi
import com.o3dr.services.android.lib.coordinate.LatLong
import com.o3dr.services.android.lib.drone.attribute.AttributeEvent
import com.o3dr.services.android.lib.drone.attribute.AttributeType
import com.o3dr.services.android.lib.drone.companion.solo.SoloAttributes
import com.o3dr.services.android.lib.drone.companion.solo.SoloEvents
import com.o3dr.services.android.lib.drone.companion.solo.tlv.SoloGoproState
import org.droidplanner.android.R
import org.droidplanner.android.activities.helpers.SuperUI
import org.droidplanner.android.fragments.FlightDataFragment
import org.droidplanner.android.fragments.FlightMapFragment
import org.droidplanner.android.fragments.widget.TowerWidget
import org.droidplanner.android.fragments.widget.TowerWidgets
import org.droidplanner.android.fragments.widget.video.FullWidgetSoloLinkVideo
import org.droidplanner.android.utils.prefs.AutoPanMode
import kotlin.properties.Delegates
/**
* Created by Fredia Huya-Kouadio on 7/19/15.
*/
public class WidgetActivity : SuperUI() {
companion object {
val EXTRA_WIDGET_ID = "extra_widget_id"
}
override fun onCreate(savedInstanceState: Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_widget)
val fm = supportFragmentManager
var flightDataFragment = fm.findFragmentById(R.id.map_view) as FlightDataFragment?
if(flightDataFragment == null){
flightDataFragment = FlightDataFragment()
fm.beginTransaction().add(R.id.map_view, flightDataFragment).commit()
}
handleIntent(intent)
}
override fun onNewIntent(intent: Intent?){
super.onNewIntent(intent)
if(intent != null)
handleIntent(intent)
}
private fun handleIntent(intent: Intent){
val widgetId = intent.getIntExtra(EXTRA_WIDGET_ID, 0)
val fm = supportFragmentManager
val widget = TowerWidgets.getWidgetById(widgetId)
if(widget != null){
setToolbarTitle(widget.labelResId)
val currentWidget = fm.findFragmentById(R.id.widget_view) as TowerWidget?
val currentWidgetType = if(currentWidget == null) null else currentWidget.getWidgetType()
if(widget == currentWidgetType)
return
val widgetFragment = widget.getMaximizedFragment()
fm.beginTransaction().replace(R.id.widget_view, widgetFragment).commit()
}
}
override fun getToolbarId() = R.id.actionbar_container
} | Android/src/org/droidplanner/android/activities/WidgetActivity.kt | 638254157 |
package com.beust.kobalt.maven.aether
import com.beust.kobalt.Args
import com.beust.kobalt.HostConfig
import com.beust.kobalt.KobaltException
import com.beust.kobalt.api.Kobalt
import com.beust.kobalt.internal.KobaltSettings
import com.beust.kobalt.internal.getProxy
import com.beust.kobalt.maven.Kurl
import com.beust.kobalt.maven.LocalRepo
import com.beust.kobalt.maven.MavenId
import com.beust.kobalt.misc.LocalProperties
import com.google.common.eventbus.EventBus
import com.google.inject.Inject
import org.eclipse.aether.artifact.Artifact
import org.eclipse.aether.artifact.DefaultArtifact
import org.eclipse.aether.collection.CollectRequest
import org.eclipse.aether.collection.CollectResult
import org.eclipse.aether.graph.DefaultDependencyNode
import org.eclipse.aether.graph.Dependency
import org.eclipse.aether.graph.DependencyFilter
import org.eclipse.aether.repository.RemoteRepository
import org.eclipse.aether.resolution.DependencyRequest
import org.eclipse.aether.resolution.DependencyResult
import org.eclipse.aether.resolution.VersionRangeRequest
import org.eclipse.aether.resolution.VersionRangeResult
import org.eclipse.aether.util.repository.AuthenticationBuilder
import java.util.*
class KobaltMavenResolver @Inject constructor(val settings: KobaltSettings,
val args: Args,
localRepo: LocalRepo, eventBus: EventBus) {
companion object {
fun artifactToId(artifact: Artifact) = artifact.let {
MavenId.toId(it.groupId, it.artifactId, it.extension, it.classifier, it.version)
}
fun isRangeVersion(id: String) = id.contains(",")
fun initAuthentication(hostInfo: HostConfig) {
// See if the URL needs to be authenticated. Look in local.properties for keys
// of the format authUrl.<host>.user=xxx and authUrl.<host>.password=xxx
val properties = LocalProperties().localProperties
val host = java.net.URL(hostInfo.url).host
properties.entries.forEach {
val key = it.key.toString()
if (key == "${Kurl.KEY}.$host.${Kurl.VALUE_USER}") {
hostInfo.username = properties.getProperty(key)
} else if (key == "${Kurl.KEY}.$host.${Kurl.VALUE_PASSWORD}") {
hostInfo.password = properties.getProperty(key)
}
}
fun error(s1: String, s2: String) {
throw KobaltException("Found \"$s1\" but not \"$s2\" in local.properties for ${Kurl.KEY}.$host",
docUrl = "https://beust.com/kobalt/documentation/index.html#maven-repos-authenticated")
}
if (! hostInfo.username.isNullOrBlank() && hostInfo.password.isNullOrBlank()) {
error("username", "password")
} else if(hostInfo.username.isNullOrBlank() && ! hostInfo.password.isNullOrBlank()) {
error("password", "username")
}
}
}
fun resolveToArtifact(id: String, scope: Scope? = null,
filter: DependencyFilter = Filters.EXCLUDE_OPTIONAL_FILTER) : Artifact
= resolve(id, scope, filter).root.artifact
fun resolve(passedId: String, scope: Scope? = null,
filter: DependencyFilter = Filters.EXCLUDE_OPTIONAL_FILTER,
repos: List<String> = emptyList()): DependencyResult {
val mavenId = MavenId.toMavenId(passedId)
val id =
if (isRangeVersion(mavenId)) {
val artifact = DefaultArtifact(mavenId)
val request = VersionRangeRequest(artifact, createRepos(repos), null)
val rr = system.resolveVersionRange(session, request)
if (rr.highestVersion != null) {
val newArtifact = DefaultArtifact(artifact.groupId, artifact.artifactId, artifact.classifier,
artifact.extension, rr.highestVersion.toString())
artifactToId(newArtifact)
} else {
throw KobaltException("Couldn't resolve $passedId")
}
} else {
passedId
}
val collectRequest = createCollectRequest(id, scope, repos)
val dependencyRequest = DependencyRequest(collectRequest, filter)
val result = system.resolveDependencies(session, dependencyRequest)
// GraphUtil.displayGraph(listOf(result.root), { it -> it.children },
// { it: DependencyNode, indent: String -> println(indent + it.toString()) })
return result
}
fun resolve(artifact: Artifact, scope: Scope? = null,
filter: DependencyFilter = Filters.EXCLUDE_OPTIONAL_FILTER)
= resolve(artifactToId(artifact), scope, filter)
fun resolveToIds(id: String, scope: Scope? = null,
filter: DependencyFilter = Filters.EXCLUDE_OPTIONAL_FILTER,
seen: HashSet<String> = hashSetOf<String>()) : List<String> {
val rr = resolve(id, scope, filter)
val children =
rr.root.children.filter {
filter.accept(DefaultDependencyNode(it.dependency), emptyList())
}.filter {
it.dependency.scope != Scope.SYSTEM.scope
}
val result = listOf(artifactToId(rr.root.artifact)) + children.flatMap {
val thisId = artifactToId(it.artifact)
if (! seen.contains(thisId)) {
seen.add(thisId)
resolveToIds(thisId, scope, filter, seen)
} else {
emptyList()
}
}
return result
}
fun directDependencies(id: String, scope: Scope? = null): CollectResult?
= system.collectDependencies(session, createCollectRequest(id, scope))
fun directDependencies(artifact: Artifact, scope: Scope? = null): CollectResult?
= artifactToId(artifact).let { id ->
directDependencies(id, scope)
}
fun resolveRange(artifact: Artifact): VersionRangeResult? {
val request = VersionRangeRequest(artifact, kobaltRepositories, null)
val result = system.resolveVersionRange(session, request)
return result
}
/**
* Create an IClasspathDependency from a Kobalt id.
*/
fun create(id: String, optional: Boolean) = AetherDependency(DefaultArtifact(id), optional, args)
private val system = Booter.newRepositorySystem()
private val session = Booter.newRepositorySystemSession(system, localRepo.localRepo, settings, args, eventBus)
private fun createRepo(hostConfig: HostConfig) : RemoteRepository {
val builder = RemoteRepository.Builder(hostConfig.name, "default", hostConfig.url)
if (hostConfig.hasAuth()) {
val auth = AuthenticationBuilder()
.addUsername(hostConfig.username)
.addPassword(hostConfig.password)
.build()
builder.setAuthentication(auth)
}
return builder.build()
}
private val kobaltRepositories: List<RemoteRepository>
get() = Kobalt.repos.map {
createRepo(it).let { repository ->
val proxyConfigs = settings.proxyConfigs ?: return@map repository
RemoteRepository.Builder(repository).apply {
setProxy(proxyConfigs.getProxy(repository.protocol)?.toAetherProxy())
}.build()
}
}
private fun createRepos(repos: List<String>) : List<RemoteRepository>
= kobaltRepositories + repos.map { createRepo(HostConfig(it)) }
private fun createCollectRequest(id: String, scope: Scope? = null, repos: List<String> = emptyList())
= CollectRequest().apply {
val allIds = arrayListOf(MavenId.toMavenId(id))
dependencies = allIds.map { Dependency(DefaultArtifact(it), scope?.scope) }
root = Dependency(DefaultArtifact(MavenId.toMavenId(id)), scope?.scope)
repositories = createRepos(repos)
}
}
| modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/maven/aether/KobaltMavenResolver.kt | 3410181263 |
/*
Tickle
Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.tickle
import org.joml.Vector2d
import uk.co.nickthecoder.tickle.physics.offset
import uk.co.nickthecoder.tickle.physics.scale
/**
* The base class for NinePatchAppearance and TiledAppearance which can both be given an arbitrary size without scaling.
*/
abstract class ResizeAppearance(actor: Actor) : AbstractAppearance(actor) {
val size = Vector2d(1.0, 1.0)
/**
* The alignment, where x,y are both in the range 0..1
* (0,0) means the Actor's position is at the bottom left of the NinePatch.
* (1,1) means the Actor's position is at the top right of the NinePatch.
*/
val sizeAlignment = Vector2d(0.5, 0.5)
internal val oldSize = Vector2d(1.0, 1.0)
protected val oldAlignment = Vector2d(0.5, 0.5)
override fun height() = size.y
override fun width() = size.x
override fun offsetX() = size.x * sizeAlignment.x
override fun offsetY() = size.y * sizeAlignment.y
override fun touching(point: Vector2d) = pixelTouching(point)
override fun resize(width: Double, height: Double) {
size.x = width
size.y = height
}
override fun updateBody() {
if (oldSize != size) {
actor.body?.jBox2DBody?.scale((size.x / oldSize.x).toFloat(), (size.y / oldSize.y).toFloat())
oldSize.set(size)
}
if (oldAlignment != sizeAlignment) {
actor.body?.let { body ->
val world = body.tickleWorld
body.jBox2DBody.offset(
world.pixelsToWorld((oldAlignment.x - sizeAlignment.x) * width()),
world.pixelsToWorld((oldAlignment.y - sizeAlignment.y) * height()))
}
oldAlignment.set(sizeAlignment)
}
}
}
| tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/ResizeAppearance.kt | 2257853869 |
package coil.memory
import coil.memory.MemoryCache.Key
import coil.util.toImmutableMap
internal class RealMemoryCache(
private val strongMemoryCache: StrongMemoryCache,
private val weakMemoryCache: WeakMemoryCache
) : MemoryCache {
override val size get() = strongMemoryCache.size
override val maxSize get() = strongMemoryCache.maxSize
override val keys get() = strongMemoryCache.keys + weakMemoryCache.keys
override fun get(key: Key): MemoryCache.Value? {
return strongMemoryCache.get(key) ?: weakMemoryCache.get(key)
}
override fun set(key: Key, value: MemoryCache.Value) {
// Ensure that stored keys and values are immutable.
strongMemoryCache.set(
key = key.copy(extras = key.extras.toImmutableMap()),
bitmap = value.bitmap,
extras = value.extras.toImmutableMap()
)
// weakMemoryCache.set() is called by strongMemoryCache when
// a value is evicted from the strong reference cache.
}
override fun remove(key: Key): Boolean {
// Do not short circuit. There is a regression test for this.
val removedStrong = strongMemoryCache.remove(key)
val removedWeak = weakMemoryCache.remove(key)
return removedStrong || removedWeak
}
override fun clear() {
strongMemoryCache.clearMemory()
weakMemoryCache.clearMemory()
}
override fun trimMemory(level: Int) {
strongMemoryCache.trimMemory(level)
weakMemoryCache.trimMemory(level)
}
}
| coil-base/src/main/java/coil/memory/RealMemoryCache.kt | 1976886747 |
@file:JvmName("RxChip")
@file:JvmMultifileClass
package com.jakewharton.rxbinding4.material
import android.view.View
import android.view.View.OnClickListener
import androidx.annotation.CheckResult
import com.google.android.material.chip.Chip
import com.jakewharton.rxbinding4.internal.checkMainThread
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.android.MainThreadDisposable
/**
* Create an observable which emits on [Chip] close icon click events. The emitted value is
* unspecified and should only be used as notification.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [Chip.setOnCloseIconClickListener] to observe
* clicks. Only one observable can be used for a view at a time.
*/
@CheckResult
fun Chip.closeIconClicks(): Observable<Unit> {
return ChipCloseIconClicksObservable(this)
}
private class ChipCloseIconClicksObservable(
private val view: Chip
) : Observable<Unit>() {
override fun subscribeActual(observer: Observer<in Unit>) {
if (!checkMainThread(observer)) {
return
}
val listener = Listener(view, observer)
observer.onSubscribe(listener)
view.setOnCloseIconClickListener(listener)
}
private class Listener(
private val view: Chip,
private val observer: Observer<in Unit>
) : MainThreadDisposable(), OnClickListener {
override fun onClick(v: View) {
if (!isDisposed) {
observer.onNext(Unit)
}
}
override fun onDispose() {
view.setOnCloseIconClickListener(null)
}
}
}
| rxbinding-material/src/main/java/com/jakewharton/rxbinding4/material/ChipCloseIconClicksObservable.kt | 580043323 |
package org.loecasi.android.feature.main.gift
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.v4.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import butterknife.BindView
import butterknife.ButterKnife
import dagger.android.support.AndroidSupportInjection
import org.loecasi.android.R
import org.loecasi.android.feature.gift.create.GiftCreateActivity
import javax.inject.Inject
/**
* Created by dani on 10/30/17.
*/
class GiftFragment : Fragment(), GiftMvpView {
@Inject lateinit var presenter: GiftMvpPresenter<GiftMvpView>
@BindView(R.id.fab_add) lateinit var fabAdd: FloatingActionButton
companion object {
val LOG_TAG = GiftFragment::class.java.simpleName
}
override fun onAttach(context: Context?) {
AndroidSupportInjection.inject(this)
presenter.onAttach(this)
super.onAttach(context)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater?.inflate(R.layout.fragment_gift, container, false)
ButterKnife.bind(this, view!!)
return view
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fabAdd.setOnClickListener { presenter.onAddButtonClicked() }
}
override fun onDetach() {
presenter.onDetach()
super.onDetach()
}
override fun openCreateScreen() {
startActivity(Intent(activity, GiftCreateActivity::class.java))
}
override fun openDetailScreen() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
| app/src/main/java/org/loecasi/android/feature/main/gift/GiftFragment.kt | 2993388880 |
package org.rust.lang.core.psi.util
import org.rust.lang.core.psi.RustGenericDeclaration
import org.rust.lang.core.psi.RustTraitItemElement
import org.rust.lang.core.psi.RustTraitRefElement
import org.rust.lang.core.psi.RustTypeParamElement
/**
* `RustItemElement` related extensions
*/
val RustGenericDeclaration.typeParams: List<RustTypeParamElement>
get() = genericParams?.typeParamList.orEmpty()
val RustTraitRefElement.trait: RustTraitItemElement?
get() = path.reference.resolve() as? RustTraitItemElement
| src/main/kotlin/org/rust/lang/core/psi/util/RustItemExtensions.kt | 3737245539 |
package com.jeremiahzucker.pandroid.request.json.v5.model
/**
* Created by Jeremiah Zucker on 8/23/2017.
*/
data class StationSeedsModel(
val songs: List<SongSeedModel>,
val artists: List<ArtistSeedModel>,
val genres: List<GenreSeedModel>
)
| app/src/main/java/com/jeremiahzucker/pandroid/request/json/v5/model/StationSeedsModel.kt | 2126203761 |
package org.rust.ide.structure
import com.intellij.ide.structureView.StructureViewTreeElement
import com.intellij.ide.structureView.impl.common.PsiTreeElementBase
import org.rust.lang.core.psi.RustModDeclItemElement
class RustModDeclTreeElement(element: RustModDeclItemElement) : PsiTreeElementBase<RustModDeclItemElement>(element) {
override fun getPresentableText(): String? = element?.name
override fun getChildrenBase(): Collection<StructureViewTreeElement> = emptyList()
}
| src/main/kotlin/org/rust/ide/structure/RustModDeclTreeElement.kt | 4112063920 |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.builtInWebServer
import com.intellij.openapi.diagnostic.catchAndLog
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.io.endsWithName
import com.intellij.openapi.util.io.endsWithSlash
import com.intellij.openapi.util.io.getParentPath
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VFileProperty
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PathUtilRt
import com.intellij.util.io.*
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.FullHttpRequest
import io.netty.handler.codec.http.HttpRequest
import io.netty.handler.codec.http.HttpResponseStatus
import org.jetbrains.io.orInSafeMode
import org.jetbrains.io.send
import java.nio.file.Path
import java.nio.file.Paths
import java.util.regex.Pattern
val chromeVersionFromUserAgent: Pattern = Pattern.compile(" Chrome/([\\d.]+) ")
private class DefaultWebServerPathHandler : WebServerPathHandler() {
override fun process(path: String,
project: Project,
request: FullHttpRequest,
context: ChannelHandlerContext,
projectName: String,
decodedRawPath: String,
isCustomHost: Boolean): Boolean {
val channel = context.channel()
val isSignedRequest = request.isSignedRequest()
val extraHeaders = validateToken(request, channel, isSignedRequest) ?: return true
val pathToFileManager = WebServerPathToFileManager.getInstance(project)
var pathInfo = pathToFileManager.pathToInfoCache.getIfPresent(path)
if (pathInfo == null || !pathInfo.isValid) {
pathInfo = pathToFileManager.doFindByRelativePath(path, defaultPathQuery)
if (pathInfo == null) {
HttpResponseStatus.NOT_FOUND.send(channel, request, extraHeaders = extraHeaders)
return true
}
pathToFileManager.pathToInfoCache.put(path, pathInfo)
}
var indexUsed = false
if (pathInfo.isDirectory()) {
var indexVirtualFile: VirtualFile? = null
var indexFile: Path? = null
if (pathInfo.file == null) {
indexFile = findIndexFile(pathInfo.ioFile!!)
}
else {
indexVirtualFile = findIndexFile(pathInfo.file!!)
}
if (indexFile == null && indexVirtualFile == null) {
HttpResponseStatus.NOT_FOUND.send(channel, request, extraHeaders = extraHeaders)
return true
}
// we must redirect only after index file check to not expose directory status
if (!endsWithSlash(decodedRawPath)) {
redirectToDirectory(request, channel, if (isCustomHost) path else "$projectName/$path", extraHeaders)
return true
}
indexUsed = true
pathInfo = PathInfo(indexFile, indexVirtualFile, pathInfo.root, pathInfo.moduleName, pathInfo.isLibrary)
pathToFileManager.pathToInfoCache.put(path, pathInfo)
}
val userAgent = request.userAgent
if (!isSignedRequest && userAgent != null && request.isRegularBrowser() && request.origin == null && request.referrer == null) {
val matcher = chromeVersionFromUserAgent.matcher(userAgent)
if (matcher.find() && StringUtil.compareVersionNumbers(matcher.group(1), "51") < 0 && !canBeAccessedDirectly(pathInfo.name)) {
HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request)
return true
}
}
if (!indexUsed && !endsWithName(path, pathInfo.name)) {
if (endsWithSlash(decodedRawPath)) {
indexUsed = true
}
else {
// FallbackResource feature in action, /login requested, /index.php retrieved, we must not redirect /login to /login/
val parentPath = getParentPath(pathInfo.path)
if (parentPath != null && endsWithName(path, PathUtilRt.getFileName(parentPath))) {
redirectToDirectory(request, channel, if (isCustomHost) path else "$projectName/$path", extraHeaders)
return true
}
}
}
if (!checkAccess(pathInfo, channel, request)) {
return true
}
val canonicalPath = if (indexUsed) "$path/${pathInfo.name}" else path
for (fileHandler in WebServerFileHandler.EP_NAME.extensions) {
LOG.catchAndLog {
if (fileHandler.process(pathInfo!!, canonicalPath, project, request, channel, if (isCustomHost) null else projectName, extraHeaders)) {
return true
}
}
}
// we registered as a last handler, so, we should just return 404 and send extra headers
HttpResponseStatus.NOT_FOUND.send(channel, request, extraHeaders = extraHeaders)
return true
}
}
private fun checkAccess(pathInfo: PathInfo, channel: Channel, request: HttpRequest): Boolean {
if (pathInfo.ioFile != null || pathInfo.file!!.isInLocalFileSystem) {
val file = pathInfo.ioFile ?: Paths.get(pathInfo.file!!.path)
if (file.isDirectory()) {
HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request)
return false
}
else if (!hasAccess(file)) {
// we check only file, but all directories in the path because of https://youtrack.jetbrains.com/issue/WEB-21594
HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request)
return false
}
}
else if (pathInfo.file!!.`is`(VFileProperty.HIDDEN)) {
HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request)
return false
}
return true
}
private fun canBeAccessedDirectly(path: String): Boolean {
for (fileHandler in WebServerFileHandler.EP_NAME.extensions) {
for (ext in fileHandler.pageFileExtensions) {
if (FileUtilRt.extensionEquals(path, ext)) {
return true
}
}
}
return false
} | platform/built-in-server/src/org/jetbrains/builtInWebServer/DefaultWebServerPathHandler.kt | 632106976 |
package de.maibornwolff.codecharta.importer.gitlogparser
import de.maibornwolff.codecharta.filter.mergefilter.MergeFilter
import de.maibornwolff.codecharta.importer.gitlogparser.InputFormatNames.GIT_LOG_NUMSTAT_RAW_REVERSED
import de.maibornwolff.codecharta.importer.gitlogparser.converter.ProjectConverter
import de.maibornwolff.codecharta.importer.gitlogparser.input.metrics.MetricsFactory
import de.maibornwolff.codecharta.importer.gitlogparser.parser.LogParserStrategy
import de.maibornwolff.codecharta.importer.gitlogparser.parser.git.GitLogNumstatRawParserStrategy
import de.maibornwolff.codecharta.importer.gitlogparser.subcommands.LogScanCommand
import de.maibornwolff.codecharta.importer.gitlogparser.subcommands.RepoScanCommand
import de.maibornwolff.codecharta.model.Project
import de.maibornwolff.codecharta.serialization.ProjectDeserializer
import de.maibornwolff.codecharta.serialization.ProjectSerializer
import de.maibornwolff.codecharta.tools.interactiveparser.InteractiveParser
import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface
import org.mozilla.universalchardet.UniversalDetector
import picocli.CommandLine
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.PrintStream
import java.nio.charset.Charset
import java.nio.file.Files
import java.util.concurrent.Callable
import java.util.stream.Stream
@CommandLine.Command(
name = "gitlogparser",
description = ["git log parser - generates cc.json from git-log files"],
subcommands = [LogScanCommand::class, RepoScanCommand::class],
footer = ["Copyright(c) 2022, MaibornWolff GmbH"]
)
class GitLogParser(
private val input: InputStream = System.`in`,
private val output: PrintStream = System.out,
private val error: PrintStream = System.err
) : Callable<Void>, InteractiveParser {
private val inputFormatNames = GIT_LOG_NUMSTAT_RAW_REVERSED
@CommandLine.Option(names = ["-h", "--help"], usageHelp = true, description = ["displays this help and exits"])
private var help = false
private val logParserStrategy: LogParserStrategy
get() = getLogParserStrategyByInputFormat(inputFormatNames)
private val metricsFactory: MetricsFactory
get() {
val nonChurnMetrics = listOf(
"age_in_weeks",
"number_of_authors",
"number_of_commits",
"number_of_renames",
"range_of_weeks_with_commits",
"successive_weeks_of_commits",
"weeks_with_commits",
"highly_coupled_files",
"median_coupled_files"
)
return when (inputFormatNames) {
GIT_LOG_NUMSTAT_RAW_REVERSED -> MetricsFactory(nonChurnMetrics)
}
}
@Throws(IOException::class)
override fun call(): Void? {
print(" ")
return null
}
internal fun buildProject(
gitLogFile: File,
gitLsFile: File,
outputFilePath: String?,
addAuthor: Boolean,
silent: Boolean,
compress: Boolean
) {
var project = createProjectFromLog(
gitLogFile,
gitLsFile,
logParserStrategy,
metricsFactory,
addAuthor,
silent
)
val pipedProject = ProjectDeserializer.deserializeProject(input)
if (pipedProject != null) {
project = MergeFilter.mergePipedWithCurrentProject(pipedProject, project)
}
ProjectSerializer.serializeToFileOrStream(project, outputFilePath, output, compress)
}
private fun getLogParserStrategyByInputFormat(formatName: InputFormatNames): LogParserStrategy {
return when (formatName) {
GIT_LOG_NUMSTAT_RAW_REVERSED -> GitLogNumstatRawParserStrategy()
}
}
private fun readFileNameListFile(path: File): MutableList<String> {
val inputStream: InputStream = path.inputStream()
val lineList = mutableListOf<String>()
inputStream.bufferedReader().forEachLine { lineList.add(it) }
return lineList
}
private fun createProjectFromLog(
gitLogFile: File,
gitLsFile: File,
parserStrategy: LogParserStrategy,
metricsFactory: MetricsFactory,
containsAuthors: Boolean,
silent: Boolean = false
): Project {
val namesInProject = readFileNameListFile(gitLsFile)
val encoding = guessEncoding(gitLogFile) ?: "UTF-8"
if (!silent) error.println("Assumed encoding $encoding")
val lines: Stream<String> = Files.lines(gitLogFile.toPath(), Charset.forName(encoding))
val projectConverter = ProjectConverter(containsAuthors)
val logSizeInByte = gitLogFile.length()
return GitLogProjectCreator(parserStrategy, metricsFactory, projectConverter, logSizeInByte, silent).parse(
lines,
namesInProject
)
}
companion object {
private fun guessEncoding(pathToLog: File): String? {
val inputStream = pathToLog.inputStream()
val buffer = ByteArray(4096)
val detector = UniversalDetector(null)
var sizeRead = inputStream.read(buffer)
while (sizeRead > 0 && !detector.isDone) {
detector.handleData(buffer, 0, sizeRead)
sizeRead = inputStream.read(buffer)
}
detector.dataEnd()
return detector.detectedCharset
}
@JvmStatic
fun main(args: Array<String>) {
CommandLine(GitLogParser()).execute(*args)
}
}
override fun getDialog(): ParserDialogInterface = ParserDialog
}
| analysis/import/GitLogParser/src/main/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/GitLogParser.kt | 1979730098 |
package net.perfectdreams.loritta.morenitta.commands.vanilla.images
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.addJsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonArray
import net.dv8tion.jda.api.EmbedBuilder
import net.perfectdreams.loritta.common.commands.ArgumentType
import net.perfectdreams.loritta.common.commands.arguments
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordAbstractCommandBase
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.common.utils.Emotes
import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils
import java.awt.Color
class CortesFlowCommand(
m: LorittaBot,
) : DiscordAbstractCommandBase(
m,
listOf(
"cortesflow", "flowcortes"
),
net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES
) {
override fun command() = create {
localizedDescription("commands.command.cortesflow.description")
localizedExamples("commands.command.cortesflow.examples")
needsToUploadFiles = true
arguments {
argument(ArgumentType.TEXT) {}
argument(ArgumentType.TEXT) {}
}
executesDiscord {
OutdatedCommandUtils.sendOutdatedCommandMessage(this, locale, "brmemes cortesflow")
if (args.isEmpty()) {
val result = loritta.http.get("https://gabriela.loritta.website/api/v1/images/cortes-flow")
.bodyAsText()
val elements = Json.parseToJsonElement(result)
.jsonArray
val availableGroupedBy = elements.groupBy { it.jsonObject["participant"]!!.jsonPrimitive.content }
.entries
.sortedByDescending { it.value.size }
val embed = EmbedBuilder()
.setTitle("${Emotes.FLOW_PODCAST} ${locale["commands.command.cortesflow.embedTitle"]}")
.setDescription(
locale.getList(
"commands.command.cortesflow.embedDescription",
locale["commands.command.cortesflow.howToUseExample", serverConfig.commandPrefix],
locale["commands.command.cortesflow.commandExample", serverConfig.commandPrefix]
).joinToString("\n")
)
.setFooter(locale["commands.command.cortesflow.findOutThumbnailSource"], "https://yt3.ggpht.com/a/AATXAJwhhX5JXoYvdDwDI56fQfTDinfs21vzivC-DBW6=s88-c-k-c0x00ffffff-no-rj")
.setColor(Color.BLACK)
for ((_, value) in availableGroupedBy) {
embed.addField(
value.first().jsonObject["participantDisplayName"]!!.jsonPrimitive.content,
value.joinToString {
locale[
"commands.command.cortesflow.thumbnailSelection",
it.jsonObject["path"]!!.jsonPrimitive.content.removePrefix("/api/v1/images/cortes-flow/"),
it.jsonObject["source"]!!.jsonPrimitive.content
]
},
true
)
}
sendMessageEmbeds(
embed.build()
)
return@executesDiscord
}
if (args.size == 1)
fail(locale["commands.command.cortesflow.youNeedToAddText"])
val type = args.getOrNull(0)
val string = args
.drop(1)
.joinToString(" ")
val response = loritta.http.post("https://gabriela.loritta.website/api/v1/images/cortes-flow/$type") {
setBody(
buildJsonObject {
putJsonArray("strings") {
addJsonObject {
put("string", string)
}
}
}.toString()
)
}
if (response.status == HttpStatusCode.NotFound)
fail(locale["commands.command.cortesflow.unknownType", serverConfig.commandPrefix])
sendFile(response.readBytes(), "cortes_flow.jpg")
}
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/CortesFlowCommand.kt | 2597613985 |
package mainview
import javafx.scene.layout.BorderStrokeStyle
import javafx.scene.paint.Color
import javafx.scene.text.FontWeight
import tornadofx.*
/**
* Created on 29/08/2017.
*
* Stylesheet for the [MainView]
*/
class MainViewStyle : Stylesheet() {
init {
button {
fontFamily = "Helvetica"
fontWeight = FontWeight.EXTRA_BOLD
fontSize = 30.px
backgroundColor += c("#3B3B3B")
textFill = Color.WHITE
and(hover) {
backgroundColor += c("#005599")
borderColor += box(
all = c("#2c312e")
)
borderStyle += BorderStrokeStyle.DOTTED
}
and(pressed) {
backgroundColor += c("#2f2f2f")
}
}
label {
textFill = Color.WHITE
fontFamily = "Helvetica"
fontSize = 30.px
fontWeight = FontWeight.BOLD
}
root {
backgroundColor += c("2B2B2B")
padding = box(50.px, 10.px, 10.px, 10.px)
}
}
} | src/main/kotlin/mainview/MainViewStyle.kt | 981328151 |
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.packtracker
import dev.kord.core.entity.User
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.BarebonesSingleUserComponentData
import net.perfectdreams.loritta.cinnamon.discord.utils.ComponentExecutorIds
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.declarations.PackageCommand
import net.perfectdreams.loritta.cinnamon.discord.interactions.components.ButtonExecutorDeclaration
import net.perfectdreams.loritta.cinnamon.discord.interactions.components.CinnamonButtonExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.components.ComponentContext
import net.perfectdreams.loritta.cinnamon.discord.utils.correios.CorreiosClient
import net.perfectdreams.loritta.cinnamon.pudding.data.UserId
class GoBackToPackageListButtonClickExecutor(
loritta: LorittaBot,
val correios: CorreiosClient
) : CinnamonButtonExecutor(loritta) {
companion object : ButtonExecutorDeclaration(ComponentExecutorIds.GO_BACK_TO_PACKAGE_LIST_BUTTON_EXECUTOR)
override suspend fun onClick(user: User, context: ComponentContext) {
context.deferUpdateMessage()
context.decodeDataFromComponentAndRequireUserToMatch<BarebonesSingleUserComponentData>()
val packageIds = context.loritta.pudding.packagesTracking.getTrackedCorreiosPackagesByUser(UserId(context.user.id.value))
if (packageIds.isEmpty())
context.failEphemerally(
context.i18nContext.get(PackageCommand.I18N_PREFIX.List.YouAreNotFollowingAnyPackage(loritta.commandMentions.packageTrack)),
Emotes.LoriSob
)
val message = PackageListExecutor.createMessage(context.i18nContext, packageIds)
context.updateMessage {
message()
}
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/utils/packtracker/GoBackToPackageListButtonClickExecutor.kt | 3968141220 |
package net.perfectdreams.loritta.common.utils
actual fun String.format(vararg arguments: Any?): String {
var str = this
arguments.forEachIndexed { index, any ->
str = str.replace("{$index}", any.toString())
}
return str
} | common/src/jsMain/kotlin/net/perfectdreams/loritta/common/utils/TextUtils.kt | 646117115 |
package eu.kanade.tachiyomi.extension.all.mangadex
/**
* Mangadex languages
*/
class MangaDexPolish : Mangadex("pl", "pl", 3)
class MangaDexItalian : Mangadex("it", "it", 6)
class MangaDexRussian : Mangadex("ru", "ru", 7)
class MangaDexGerman : Mangadex("de", "de", 8)
class MangaDexFrench : Mangadex("fr", "fr", 10)
class MangaDexVietnamese : Mangadex("vi", "vn", 12)
class MangaDexSpanishSpain : Mangadex("es", "es", 15)
class MangaDexPortuguese : Mangadex("pt", "br", 16)
class MangaDexSwedish : Mangadex("sv", "se", 18)
class MangaDexTurkish : Mangadex("tr", "tr", 26)
class MangaDexIndonesian : Mangadex("id", "id", 27)
class MangaDexSpanishLTAM : Mangadex("es-419", "mx", 29)
class MangaDexCatalan : Mangadex("ca", "ct", 33)
class MangaDexHungarian : Mangadex("hu", "hu", 9)
class MangaDexBulgarian : Mangadex("bg", "bg", 14)
class MangaDexFilipino : Mangadex("fil", "ph", 34)
class MangaDexDutch : Mangadex("nl", "nl", 5)
class MangaDexArabic : Mangadex("ar", "sa", 19)
class MangaDexChineseSimp : Mangadex("zh-Hans", "cn", 21)
class MangaDexChineseTrad : Mangadex("zh-Hant", "hk", 35)
class MangaDexThai: Mangadex("th", "th", 32)
fun getAllMangaDexLanguages() = listOf(
MangaDexEnglish(),
MangaDexPolish(),
MangaDexItalian(),
MangaDexRussian(),
MangaDexGerman(),
MangaDexFrench(),
MangaDexVietnamese(),
MangaDexSpanishSpain(),
MangaDexPortuguese(),
MangaDexSwedish(),
MangaDexTurkish(),
MangaDexIndonesian(),
MangaDexSpanishLTAM(),
MangaDexCatalan(),
MangaDexHungarian(),
MangaDexBulgarian(),
MangaDexFilipino(),
MangaDexDutch(),
MangaDexArabic(),
MangaDexChineseSimp(),
MangaDexChineseTrad(),
MangaDexThai()
) | src/all/mangadex/src/eu/kanade/tachiyomi/extension/all/mangadex/MangadexLanguages.kt | 1042650416 |
/*
* Copyright 2018 Michael Rozumyanskiy
*
* 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 io.michaelrocks.lightsaber.processor.logging
import org.slf4j.LoggerFactory
fun <T : Any> T.getLogger() = getLogger(javaClass)
fun getLogger(name: String) = LoggerFactory.getLogger(name)
fun getLogger(type: Class<*>) = LoggerFactory.getLogger(type)
| processor/src/main/java/io/michaelrocks/lightsaber/processor/logging/LoggerExtensions.kt | 3151282238 |
/**
* Copyright 2016 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 org.openrewrite.java.tree
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.openrewrite.java.JavaParser
import org.openrewrite.java.asClass
open class NewClassTest : JavaParser() {
val a = """
package a;
public class A {
public static class B { }
}
"""
@Test
fun anonymousInnerClass() {
val c = """
import a.*;
public class C {
A.B anonB = new A.B() {};
}
"""
val b = parse(c, a).classes[0].fields[0].vars[0]
assertEquals("a.A.B", b.type.asClass()?.fullyQualifiedName)
}
@Test
fun concreteInnerClass() {
val c = """
import a.*;
public class C {
A.B anonB = new A.B();
}
"""
val cu = parse(c, a)
val b = cu.classes[0].fields[0].vars[0]
assertEquals("a.A.B", b.type.asClass()?.fullyQualifiedName)
assertEquals("A.B", (b.initializer as J.NewClass).clazz.printTrimmed())
}
@Test
fun concreteClassWithParams() {
val a = parse("""
import java.util.*;
public class A {
Object l = new ArrayList<String>(0);
}
""")
val newClass = a.classes[0].fields[0].vars[0].initializer as J.NewClass
assertEquals(1, newClass.args.args.size)
}
@Test
fun format() {
val a = parse("""
import java.util.*;
public class A {
Object l = new ArrayList< String > ( 0 ) { };
}
""")
val newClass = a.classes[0].fields[0].vars[0].initializer as J.NewClass
assertEquals("new ArrayList< String > ( 0 ) { }", newClass.printTrimmed())
}
@Test
fun formatRawType() {
val a = parse("""
import java.util.*;
public class A {
List<String> l = new ArrayList < > ();
}
""")
val newClass = a.classes[0].fields[0].vars[0].initializer as J.NewClass
assertEquals("new ArrayList < > ()", newClass.printTrimmed())
}
} | rewrite-java/src/test/kotlin/org/openrewrite/java/tree/NewClassTest.kt | 577703519 |
package com.sakebook.android.nexustimer.model
/**
* Created by sakemotoshinya on 16/06/08.
*/
enum class Week(val id: Long) {
Sun(10),
Mon(11),
Tue(12),
Wed(13),
Thu(14),
Fri(15),
Sat(16),
;
var enable = false
fun label(): String {
return when(enable) {
true -> "ON"
false -> "OFF"
}
}
} | app/src/main/java/com/sakebook/android/nexustimer/model/Week.kt | 2491030166 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.